feat(shipping-notice): 实现对话级批量重试自动推进功能,优化库存与PDF匹配逻辑

- 新增对话级批量重试自动推进的完整链路:后端服务、API、数据投影逻辑
- 前端新增对话级重试按钮、多语言国际化支持与API类型定义
- 优化行级库存重试控制,新增retryable字段统一管控重试按钮展示,清理废弃的view_fulfillment_detail动作,标准化前端动作码排序逻辑
- 修复PDF坐标匹配的fail-close防护逻辑,避免生成伪精确匹配分数
- 调整订单确认后流程,提前进入库存获取阶段,移除冗余的确认建单按钮,优化用户流转体验
- 新增对应单元测试用例覆盖核心业务逻辑
This commit is contained in:
hugo committed 2026-08-07 16:30:45 +08:00
1 parent fd6a23f870
commit 1008911a7e
41 files changed
+3956 -1256

No files matched your search

+49 -1
View File
@@ -441,6 +441,40 @@ export const retryWorkspaceShippingOrderStpAutoCreate = (caseNo: string) =>
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}) },
);
/**
* 对话级「重试自动推进」:服务端扫描会话下可恢复 Case/正式 OT。
* 核心逻辑:前端不提交对象列表;返回 summary + 逐对象 items。
* @param conversationId - 会话 ID
* @param reason - 可选原因码
*/
export const retryWorkspaceConversationAutoProgress = (
conversationId: string,
reason = 'user_retry_auto_progress',
) =>
requestJson<{
conversation_id: string;
summary: {
total: number;
retried: number;
skipped: number;
failed: number;
};
items: Array<{
object_type: 'review_case' | 'formal_task' | string;
object_ref: string;
action?: string | null;
outcome: 'queued' | 'skipped' | 'failed' | string;
reason_code?: string | null;
}>;
}>(
`/api/workspace/shipping-conversations/${encodeURIComponent(conversationId)}/retry-auto-progress`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ reason }),
},
);
/**
* 为复核明细人工选定一个或多个已启用库存源候选。
* 核心逻辑:携带 expected_draft_version 乐观锁;服务端写入行级 inventory_routing 后重跑资格校验。
@@ -1034,7 +1068,21 @@ export async function replaceWorkspaceShippingTaskNotice(taskNo: string, file: F
export async function retryWorkspaceShippingTask(taskNo: string, comment?: string) {
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/retry`,
jsonPost(comment ? { comment } : {}),
jsonPost(comment ? { comment, reason: comment } : { reason: 'user_retry' }),
);
return assertShippingOk(body);
}
/**
* 行级统一「重试」:后端决策器选择 fetch/rematch/needs_human。
* 核心逻辑:前端不传内部动作码。
* @param taskNo - 正式任务号
* @param lineKey - 行键
*/
export async function retryWorkspaceShippingTaskLine(taskNo: string, lineKey: string) {
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/lines/${encodeURIComponent(lineKey)}/retry`,
jsonPost({ reason: 'user_retry_inventory' }),
);
return assertShippingOk(body);
}
@@ -78,13 +78,14 @@ const statusLabel = computed(() => {
});
/**
* 主卡重试:仅在有 task_no 且非 task_missing 时由父组件控制 showRetry。
* 主卡重试:对象级;建单前无 task_no 也可重试 STP;正式 OT 需 task_no。
*/
const canShowRetry = computed(() => (
Boolean(props.showRetry)
&& !props.taskMissing
&& Boolean(String(props.taskNo || '').trim())
));
const canShowRetry = computed(() => {
if (!props.showRetry || props.taskMissing) return false;
if (String(props.taskNo || '').trim()) return true;
// 建单前 STP:无 OT 号也可重试。
return String(props.automation?.phase || '').trim() !== 'post_ot_progress';
});
</script>
<template>
@@ -149,7 +150,7 @@ const canShowRetry = computed(() => (
@click="emit('retry')"
>
<RefreshCw class="h-3.5 w-3.5" />
{{ t('chat.shippingOrderReview.autoProgress.retryStp') }}
{{ t('chat.shippingOrderReview.autoProgress.retryObject') }}
</button>
</section>
</template>
@@ -1,6 +1,6 @@
/**
* features/chat/components/shipping-review/ReviewLineInventoryOps.spec.ts
* 用途:锁定库存浮层仅渲染 inventory_allowed_actions;关闭在更多操作;Teleport 菜单可见。
* 用途:锁定行级只渲染统一「重试」与关闭;消费 retryable,不展示内部动作码。
*/
import { afterEach, describe, expect, it } from 'vitest';
@@ -17,11 +17,8 @@ const i18n = createI18n({
chat: {
shippingOrderReview: {
lineOps: {
inventoryProcessing: '库存处理',
retryPreparation: '重试获取库存',
retryMatching: '重新匹配库存',
retry: '重试',
moreActions: '更多操作',
viewFulfillment: '查看履约详情',
},
fulfillmentDecision: {
closeLine: '关闭该明细',
@@ -32,11 +29,12 @@ const i18n = createI18n({
},
});
function mountOps(line: Partial<ShippingOrderReviewLineFulfillmentLine>) {
function mountOps(line: Partial<ShippingOrderReviewLineFulfillmentLine>, extra: Record<string, unknown> = {}) {
return mount(ReviewLineInventoryOps, {
props: {
line: line as ShippingOrderReviewLineFulfillmentLine,
editable: true,
...extra,
},
attachTo: document.body,
global: { plugins: [i18n] },
@@ -48,68 +46,44 @@ afterEach(() => {
});
describe('ReviewLineInventoryOps', () => {
it('shows only preparation when matching not allowed', async () => {
it('shows unified retry when retryable', async () => {
const wrapper = mountOps({
inventory_allowed_actions: ['retry_inventory_preparation'],
retryable: true,
line_allowed_actions: [],
});
await wrapper.get('[data-testid="review-line-view-inventory"]').trigger('click');
expect(document.querySelector('[data-testid="review-line-retry-preparation"]')).toBeTruthy();
expect(document.querySelector('[data-testid="review-line-retry-matching"]')).toBeFalsy();
expect(document.querySelector('[data-testid="review-line-decide-close"]')).toBeFalsy();
expect(wrapper.find('[data-testid="review-line-retry"]').exists()).toBe(true);
await wrapper.get('[data-testid="review-line-retry"]').trigger('click');
expect(wrapper.emitted('retry-line')?.length).toBe(1);
wrapper.unmount();
});
it('puts close under more actions, not inventory panel', async () => {
it('hides retry when not retryable even if internal actions present', () => {
const wrapper = mountOps({
inventory_allowed_actions: ['retry_inventory_preparation'],
retryable: false,
inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'],
line_allowed_actions: ['close_unfulfillable'],
});
await wrapper.get('[data-testid="review-line-view-inventory"]').trigger('click');
expect(document.querySelector('[data-testid="review-line-decide-close"]')).toBeFalsy();
await wrapper.get('[data-testid="review-line-more-actions"]').trigger('click');
expect(document.querySelector('[data-testid="review-line-decide-close"]')).toBeTruthy();
wrapper.unmount();
});
it('hides inventory icon when no inventory actions and no problem status', () => {
const wrapper = mountOps({
inventory_allowed_actions: [],
line_allowed_actions: ['close_unfulfillable'],
user_line_status: 'inventory_matched',
inventory_status: 'ready',
display_available: '50',
});
expect(wrapper.find('[data-testid="review-line-view-inventory"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-line-retry"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-line-more-actions"]').exists()).toBe(true);
wrapper.unmount();
});
it('shows inventory icon from problem status even when backend actions empty', async () => {
it('disables retry while task running', () => {
const wrapper = mountOps({
inventory_allowed_actions: [],
retryable: true,
line_allowed_actions: [],
user_line_status: 'inventory_pending',
inventory_status: 'preparing',
display_available: 'pending',
});
expect(wrapper.find('[data-testid="review-line-view-inventory"]').exists()).toBe(true);
await wrapper.get('[data-testid="review-line-view-inventory"]').trigger('click');
expect(document.querySelector('[data-testid="review-line-retry-preparation"]')).toBeTruthy();
}, { taskRunning: true });
expect(wrapper.find('[data-testid="review-line-retry"]').exists()).toBe(false);
wrapper.unmount();
});
it('emits retry-inventory for both floating actions', async () => {
it('puts close under more actions', async () => {
const wrapper = mountOps({
inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'],
line_allowed_actions: [],
retryable: false,
line_allowed_actions: ['close_unfulfillable'],
});
await wrapper.get('[data-testid="review-line-view-inventory"]').trigger('click');
expect(document.querySelector('[data-testid="review-line-retry-preparation"]')).toBeTruthy();
expect(document.querySelector('[data-testid="review-line-retry-matching"]')).toBeTruthy();
(document.querySelector('[data-testid="review-line-retry-matching"]') as HTMLButtonElement).click();
await wrapper.vm.$nextTick();
expect(wrapper.emitted('retry-inventory')?.[0]).toEqual(['retry_inventory_matching']);
await wrapper.get('[data-testid="review-line-more-actions"]').trigger('click');
expect(document.querySelector('[data-testid="review-line-decide-close"]')).toBeTruthy();
wrapper.unmount();
});
});
@@ -1,118 +1,55 @@
<!--
features/chat/components/shipping-review/ReviewLineInventoryOps.vue
用途:明细行库存处理浮层 + 行级更多操作(关闭);不进库存工作台、不在右侧挂动作。
依赖:vue-i18n、lucide、line.inventory_allowed_actions / line_allowed_actions。
逻辑:优先后端动作;库存问题态后端漏下发时前端兜底 preparation(+匹配失败时 matching);
菜单 Teleport 到 body,避免表格 overflow 裁切。
用途:明细行统一「重试」+ 更多操作(关闭);不进库存工作台。
依赖:vue-i18n、lucide、line.retryable / line_allowed_actions。
逻辑:只消费 retryable 布尔与 close 动作;不展示内部动作码;不发具体节点。
-->
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { MoreHorizontal, Warehouse } from 'lucide-vue-next';
import { MoreHorizontal, RefreshCw } from 'lucide-vue-next';
import type { ShippingOrderReviewLineFulfillmentLine } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
line: ShippingOrderReviewLineFulfillmentLine | null | undefined;
editable: boolean;
busy?: boolean;
/** 任务整体 queued/running 时禁用行级写 */
taskRunning?: boolean;
}>();
const emit = defineEmits<{
'retry-inventory': [actionCode: 'retry_inventory_preparation' | 'retry_inventory_matching'];
'retry-line': [];
'close-line': [];
'view-fulfillment': [];
}>();
const { t } = useI18n();
const inventoryMenuOpen = ref(false);
const moreMenuOpen = ref(false);
const inventoryBtnRef = ref<HTMLElement | null>(null);
const moreBtnRef = ref<HTMLElement | null>(null);
const inventoryMenuStyle = ref<Record<string, string>>({});
const moreMenuStyle = ref<Record<string, string>>({});
const PROBLEM_USER_STATUSES = new Set([
'inventory_file_missing',
'inventory_file_expired',
'inventory_match_failed',
'inventory_source_unrecognized',
'source_conflict',
'shortage',
'inventory_pending',
'acquiring_inventory',
'auto_fulfill_failed',
]);
const PROBLEM_INVENTORY_STATUSES = new Set([
'preparing',
'unavailable',
'mapping_failed',
'source_conflict',
'invalid_key',
]);
/**
* 库存动作集合:后端优先;问题态漏下发时兜底 preparation / matching。
* 是否展示统一「重试」:仅后端 retryable,且任务未整体运行。
*/
const inventoryActions = computed(() => {
const fromBe = [...(props.line?.inventory_allowed_actions || [])].filter(Boolean);
if (fromBe.length) return new Set(fromBe);
if (!props.line) return new Set<string>();
const userStatus = String(props.line.user_line_status || '').trim();
const invStatus = String(props.line.inventory_status || '').trim();
const matchResult = String(props.line.match_result || '').trim();
const isProblem = (
PROBLEM_USER_STATUSES.has(userStatus)
|| PROBLEM_INVENTORY_STATUSES.has(invStatus)
|| props.line.display_available === 'pending'
|| Boolean(props.line.is_shortage)
);
if (!isProblem) return new Set<string>();
const actions = new Set<string>(['retry_inventory_preparation']);
if (
userStatus === 'inventory_match_failed'
|| invStatus === 'mapping_failed'
|| matchResult === 'mapping_failed'
) {
actions.add('retry_inventory_matching');
}
return actions;
});
const lineActions = computed(() => {
const fromBe = [...(props.line?.line_allowed_actions || [])].filter(Boolean);
if (fromBe.length) return new Set(fromBe);
const userStatus = String(props.line?.user_line_status || '').trim();
if (!props.line) return new Set<string>();
if (['wave_created', 'fulfilled', 'closed'].includes(userStatus)) {
return userStatus === 'closed' ? new Set<string>() : new Set(['view_fulfillment_detail']);
}
if (PROBLEM_USER_STATUSES.has(userStatus) || Boolean(props.line.is_shortage)) {
return new Set(['close_unfulfillable']);
}
return new Set<string>();
});
const showInventoryOps = computed(() => (
inventoryActions.value.has('retry_inventory_preparation')
|| inventoryActions.value.has('retry_inventory_matching')
const showRetry = computed(() => (
Boolean(props.line?.retryable)
&& !props.taskRunning
));
const canRetryPreparation = computed(() => inventoryActions.value.has('retry_inventory_preparation'));
const canRetryMatching = computed(() => inventoryActions.value.has('retry_inventory_matching'));
const canClose = computed(() => lineActions.value.has('close_unfulfillable'));
const canViewFulfillment = computed(() => lineActions.value.has('view_fulfillment_detail'));
const showMore = computed(() => canClose.value || canViewFulfillment.value);
const canClose = computed(() => (
[...(props.line?.line_allowed_actions || [])].includes('close_unfulfillable')
));
const showMore = computed(() => canClose.value);
/**
* 按触发按钮定位浮动菜单(fixed,避免被表格 overflow 裁切)。
* 定位更多菜单。
*/
function placeMenu(anchor: HTMLElement | null, target: typeof inventoryMenuStyle) {
function placeMenu(anchor: HTMLElement | null) {
if (!anchor || typeof window === 'undefined') return;
const rect = anchor.getBoundingClientRect();
const width = 168;
const left = Math.max(8, Math.min(rect.right - width, window.innerWidth - width - 8));
target.value = {
moreMenuStyle.value = {
position: 'fixed',
top: `${Math.round(rect.bottom + 4)}px`,
left: `${Math.round(left)}px`,
@@ -121,68 +58,31 @@ function placeMenu(anchor: HTMLElement | null, target: typeof inventoryMenuStyle
};
}
/**
* 关闭所有浮层。
*/
function closeMenus() {
inventoryMenuOpen.value = false;
moreMenuOpen.value = false;
}
/**
* 文档点击/滚动时关闭浮层,避免残留遮挡。
*/
function onDocPointerDown(event: Event) {
const target = event.target as Node | null;
const target = event.target as HTMLElement | null;
if (!target) return;
const el = target as HTMLElement;
if (el.closest?.('[data-testid="review-line-inventory-panel"]')) return;
if (el.closest?.('[data-testid="review-line-more-menu"]')) return;
if (el.closest?.('[data-testid="review-line-view-inventory"]')) return;
if (el.closest?.('[data-testid="review-line-more-actions"]')) return;
if (target.closest?.('[data-testid="review-line-more-menu"]')) return;
if (target.closest?.('[data-testid="review-line-more-actions"]')) return;
closeMenus();
}
function onViewportChange() {
if (inventoryMenuOpen.value) placeMenu(inventoryBtnRef.value, inventoryMenuStyle);
if (moreMenuOpen.value) placeMenu(moreBtnRef.value, moreMenuStyle);
}
/**
* 切换库存处理浮层。
*/
async function toggleInventoryMenu() {
moreMenuOpen.value = false;
inventoryMenuOpen.value = !inventoryMenuOpen.value;
if (inventoryMenuOpen.value) {
await nextTick();
placeMenu(inventoryBtnRef.value, inventoryMenuStyle);
}
}
/**
* 切换更多操作浮层。
*/
async function toggleMoreMenu() {
inventoryMenuOpen.value = false;
moreMenuOpen.value = !moreMenuOpen.value;
if (moreMenuOpen.value) {
await nextTick();
placeMenu(moreBtnRef.value, moreMenuStyle);
placeMenu(moreBtnRef.value);
}
}
/**
* 触发库存动作并关闭浮层。
*/
function onRetry(actionCode: 'retry_inventory_preparation' | 'retry_inventory_matching') {
closeMenus();
emit('retry-inventory', actionCode);
function onRetry() {
if (props.busy || props.taskRunning || !showRetry.value) return;
emit('retry-line');
}
/**
* 关闭明细(由父级弹确认框)。
*/
function onCloseLine() {
closeMenus();
emit('close-line');
@@ -190,33 +90,27 @@ function onCloseLine() {
if (typeof document !== 'undefined') {
document.addEventListener('pointerdown', onDocPointerDown, true);
window.addEventListener('scroll', onViewportChange, true);
window.addEventListener('resize', onViewportChange);
}
onBeforeUnmount(() => {
if (typeof document === 'undefined') return;
document.removeEventListener('pointerdown', onDocPointerDown, true);
window.removeEventListener('scroll', onViewportChange, true);
window.removeEventListener('resize', onViewportChange);
});
</script>
<template>
<div class="relative inline-flex items-center gap-0.5">
<button
v-if="showInventoryOps"
ref="inventoryBtnRef"
v-if="showRetry"
type="button"
class="rounded p-1.5 hover:bg-slate-100 disabled:opacity-50 dark:hover:bg-slate-800"
data-testid="review-line-view-inventory"
:disabled="busy"
:aria-label="t('chat.shippingOrderReview.lineOps.inventoryProcessing')"
:title="t('chat.shippingOrderReview.lineOps.inventoryProcessing')"
:aria-expanded="inventoryMenuOpen"
@click="toggleInventoryMenu"
class="inline-flex items-center gap-0.5 rounded border border-amber-300 bg-amber-50 px-1.5 py-0.5 text-[11px] text-amber-950 hover:bg-amber-100 disabled:opacity-50 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100"
data-testid="review-line-retry"
:disabled="!editable || busy || taskRunning"
:aria-label="t('chat.shippingOrderReview.lineOps.retry')"
:title="t('chat.shippingOrderReview.lineOps.retry')"
@click="onRetry"
>
<Warehouse class="h-3.5 w-3.5" aria-hidden="true" />
<RefreshCw class="h-3 w-3" :class="busy ? 'animate-spin' : ''" aria-hidden="true" />
{{ t('chat.shippingOrderReview.lineOps.retry') }}
</button>
<button
@@ -225,7 +119,7 @@ onBeforeUnmount(() => {
type="button"
class="rounded p-1.5 hover:bg-slate-100 disabled:opacity-50 dark:hover:bg-slate-800"
data-testid="review-line-more-actions"
:disabled="!editable || busy"
:disabled="!editable || busy || taskRunning"
:aria-label="t('chat.shippingOrderReview.lineOps.moreActions')"
:title="t('chat.shippingOrderReview.lineOps.moreActions')"
:aria-expanded="moreMenuOpen"
@@ -235,35 +129,6 @@ onBeforeUnmount(() => {
</button>
<Teleport to="body">
<div
v-if="inventoryMenuOpen && showInventoryOps"
class="rounded-md border border-slate-200 bg-white py-1 shadow-lg dark:border-slate-700 dark:bg-slate-900"
role="menu"
data-testid="review-line-inventory-panel"
:style="inventoryMenuStyle"
>
<button
v-if="canRetryPreparation"
type="button"
class="block w-full px-3 py-2 text-left text-xs hover:bg-slate-50 dark:hover:bg-slate-800"
role="menuitem"
data-testid="review-line-retry-preparation"
@click="onRetry('retry_inventory_preparation')"
>
{{ t('chat.shippingOrderReview.lineOps.retryPreparation') }}
</button>
<button
v-if="canRetryMatching"
type="button"
class="block w-full px-3 py-2 text-left text-xs hover:bg-slate-50 dark:hover:bg-slate-800"
role="menuitem"
data-testid="review-line-retry-matching"
@click="onRetry('retry_inventory_matching')"
>
{{ t('chat.shippingOrderReview.lineOps.retryMatching') }}
</button>
</div>
<div
v-if="moreMenuOpen && showMore"
class="rounded-md border border-slate-200 bg-white py-1 shadow-lg dark:border-slate-700 dark:bg-slate-900"
@@ -271,16 +136,6 @@ onBeforeUnmount(() => {
data-testid="review-line-more-menu"
:style="moreMenuStyle"
>
<button
v-if="canViewFulfillment"
type="button"
class="block w-full px-3 py-2 text-left text-xs hover:bg-slate-50 dark:hover:bg-slate-800"
role="menuitem"
data-testid="review-line-fulfillment-detail"
@click="closeMenus(); emit('view-fulfillment')"
>
{{ t('chat.shippingOrderReview.lineOps.viewFulfillment') }}
</button>
<button
v-if="canClose"
type="button"
@@ -203,7 +203,7 @@ function flowLabel(item: ActionPresentationItem): string {
data-testid="review-retry-stp-auto-create"
@click="emit('retry-stp')"
>
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.autoProgress.retryStp') }}
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.autoProgress.retryObject') }}
</button>
<button
v-if="hasAction('validate')"
@@ -214,17 +214,6 @@ function flowLabel(item: ActionPresentationItem): string {
>
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveNow') }}
</button>
<button
v-if="hasAction('confirm') && !hideConfirmBecauseAutoGate"
type="button"
:disabled="controlsBusy || !canConfirmBuild"
class="rounded bg-emerald-600 px-3 py-2 text-sm font-medium text-white disabled:opacity-50"
data-testid="review-confirm-create"
:title="!canConfirmBuild ? t('chat.shippingOrderReview.buildEligibility.confirmBlocked') : undefined"
@click="emit('confirm')"
>
{{ t('chat.shippingOrderReview.confirmCreate') }}
</button>
</template>
</div>
</footer>
@@ -1,12 +1,13 @@
<!--
features/chat/components/shipping-review/ReviewWorkbenchHeader.vue
用途:订单复核工作台顶栏,展示标题上下文与保存状态。
用途:订单复核工作台顶栏——对话级动作、审计/版本入口与保存状态。
依赖:vue-i18n、lucide-vue-next。
逻辑:ShippingOrderReviewView 传入 run/reviewProgressContext 上下文;emit back 与 open-version-history;不含对话上下文切换。
逻辑:仅当后端 conversation_allowed_actions 含 retry_auto_progress 时渲染对话级按钮;
审计/版本为查看入口;「已保存」为状态文本;不含单个任务单写操作。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { ArrowLeft } from 'lucide-vue-next';
import { ArrowLeft, RefreshCw } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
const props = defineProps<{
@@ -19,12 +20,18 @@ const props = defineProps<{
isReadOnly: boolean;
showVersionHistory?: boolean;
showAuditTrail?: boolean;
/** 对话级「重试自动推进」;仅 eligible_count>0 时由父级置 true */
showConversationRetry?: boolean;
conversationRetryEligibleCount?: number;
conversationRetrying?: boolean;
conversationRetryDisabled?: boolean;
}>();
const emit = defineEmits<{
back: [];
'open-version-history': [];
'open-audit-trail': [];
'retry-conversation-auto-progress': [];
}>();
const { t } = useI18n();
@@ -41,6 +48,11 @@ const subtitle = computed(() => {
}
return t('chat.shippingOrderReview.run', { runNo: props.runNo });
});
const showRetry = computed(() => (
Boolean(props.showConversationRetry)
&& Number(props.conversationRetryEligibleCount || 0) > 0
));
</script>
<template>
@@ -57,6 +69,24 @@ 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="showRetry"
type="button"
class="inline-flex items-center gap-1 rounded border border-amber-400 bg-amber-50 px-2.5 py-1.5 text-xs font-medium text-amber-950 hover:bg-amber-100 disabled:opacity-50 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100"
data-testid="review-conversation-retry-auto-progress"
:disabled="conversationRetrying || conversationRetryDisabled || isReadOnly"
@click="emit('retry-conversation-auto-progress')"
>
<RefreshCw
class="h-3.5 w-3.5"
:class="conversationRetrying ? 'animate-spin' : ''"
/>
{{ t('chat.shippingOrderReview.autoProgress.retry') }}
<span
v-if="conversationRetryEligibleCount"
class="rounded bg-amber-200/80 px-1 text-[10px] dark:bg-amber-900/60"
>{{ conversationRetryEligibleCount }}</span>
</button>
<button
v-if="showAuditTrail"
type="button"
@@ -204,7 +204,7 @@ describe('ShippingConversationProcessingCard', () => {
const doneCard = wrapper.find('[data-testid="shipping-processing-task-OT-DONE"]');
expect(doneCard.find('[data-testid="sidebar-progress-inline"]').exists()).toBe(false);
expect(doneCard.find('[data-testid="shipping-processing-task-actions"]').exists()).toBe(false);
expect(doneCard.find('[data-testid="shipping-processing-action-view_details"]').exists()).toBe(true);
expect(doneCard.find('[data-testid="shipping-processing-action-view_result"]').exists()).toBe(true);
expect(doneCard.find('[data-testid="shipping-processing-action-cancel_task"]').exists()).toBe(false);
});
@@ -241,13 +241,10 @@ describe('ShippingConversationProcessingCard', () => {
expect(titleEl.text()).not.toContain('4518838152.pdf');
// UI-02:有文件对象时不双开「查看详情」与「展开文件详情」。
expect(wrapper.find('[data-testid="shipping-processing-expand-files"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-expand-files"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-processing-action-view_details"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-processing-action-cancel_task"]').exists()).toBe(false);
await wrapper.find('[data-testid="shipping-processing-expand-files"]').trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="shipping-processing-task-overflow-actions"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-action-cancel_task"]').text()).toContain('取消整个任务');
expect(wrapper.find('[data-testid="shipping-processing-task-overflow-actions"]').exists()).toBe(false);
});
it('shows view_details when task cannot expand file details, and keeps cancel as overflow', async () => {
@@ -274,10 +271,10 @@ describe('ShippingConversationProcessingCard', () => {
});
await flushPromises();
expect(wrapper.find('[data-testid="shipping-processing-expand-files"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-processing-action-view_details"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-action-view_details"]').exists()).toBe(false);
// 无文件对象时取消可直接挂在卡上(低频文字链,非主 CTA)。
expect(wrapper.find('[data-testid="shipping-processing-task-overflow-actions"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-action-cancel_task"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-task-overflow-actions"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-processing-action-cancel_task"]').exists()).toBe(false);
});
it('shows multi-document title from authoritative projection without workflow fallback', async () => {
@@ -384,11 +381,7 @@ describe('ShippingConversationProcessingCard', () => {
global: { plugins: [i18n] },
});
await flushPromises();
const expandBtn = wrapper.find('[data-testid="shipping-processing-expand-files"]');
await expandBtn.trigger('click');
expect(wrapper.emitted('expandFiles')?.[0]?.[0]).toMatchObject({ user_task_no: 'OT-NEED' });
await expandBtn.trigger('click');
expect(wrapper.emitted('collapseFiles')).toBeTruthy();
expect(wrapper.find('[data-testid="shipping-processing-expand-files"]').exists()).toBe(false);
});
it('renders twenty processing tasks in one top-level container', async () => {
@@ -490,12 +483,12 @@ describe('ShippingConversationProcessingCard', () => {
});
await flushPromises();
expect(wrapper.findAll('[data-testid="sidebar-progress-inline"]')).toHaveLength(2);
expect(wrapper.findAll('[data-testid="sidebar-progress-inline"]')).toHaveLength(1);
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]').text()).toContain('待复核');
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]').text()).toContain('库存匹配');
expect(wrapper.findAll('[data-testid="shipping-processing-task-actions"]')).toHaveLength(0);
// UI-02:有 workItem 时仍保留展开文件详情(OT-NEED 为多文件)。
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"] [data-testid="shipping-processing-expand-files"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"] [data-testid="shipping-processing-expand-files"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"] [data-testid="shipping-processing-action-view_details"]').exists()).toBe(false);
});
@@ -265,26 +265,28 @@ function primaryActionItem(task: ConversationProcessingUserTask): ActionPresenta
return taskActionPresentation(task).primary;
}
/** needs_action 的用户语义提示:不重复主按钮文案。 */
function currentNeedLabel(task: ConversationProcessingUserTask): string {
if (task.group !== 'needs_action') return '';
const action = String(task.primary_action || task.available_actions?.[0] || '').trim().toLowerCase();
const labels: Record<string, string> = {
confirm_customer: 'chat.shippingProcessing.currentNeed.confirmCustomer',
resolve_field_conflicts: 'chat.shippingProcessing.currentNeed.resolveFieldConflicts',
open_inventory_match_review: 'chat.shippingProcessing.currentNeed.inventoryMatch',
open_order_processing: 'chat.shippingProcessing.currentNeed.orderDraft',
retry: 'chat.shippingProcessing.currentNeed.retry',
retry_parse: 'chat.shippingProcessing.currentNeed.retry',
};
const key = labels[action];
return key && te(key) ? t(key) : t('chat.shippingProcessing.currentNeed.generic');
}
/**
* 次要文字链:有文件对象时可展开 → 不返回 view_details(改由展开文件入口承载);
* 无文件对象时优先 view_details,否则取非 cancel 的 presentation.secondary。
*/
function secondaryActionItem(task: ConversationProcessingUserTask): ActionPresentationItem | null {
if (canExpandFileDetails(task)) return null;
const presentation = taskActionPresentation(task);
const candidates = [
presentation.secondary,
...presentation.overflow,
].filter((item): item is ActionPresentationItem => Boolean(item));
const viewDetails = candidates.find(
(item) => String(item.actionCode || '').trim().toLowerCase() === 'view_details',
);
if (viewDetails) return viewDetails;
const secondary = presentation.secondary;
if (!secondary) return null;
const code = String(secondary.actionCode || '').trim().toLowerCase();
if (code === 'cancel_task' || code === 'cancel_run' || code === 'view_details') return null;
return secondary;
function secondaryActionItem(_task: ConversationProcessingUserTask): ActionPresentationItem | null {
return null;
}
/**
@@ -310,11 +312,8 @@ function overflowActionItems(task: ConversationProcessingUserTask): ActionPresen
* 是否展示低频溢出:有文件对象时仅展开后显示;无文件对象时直接挂在卡上(如取消)。
* 有 workItem 时不渲染任务级溢出(动作由进度条负责)。
*/
function shouldShowOverflowActions(task: ConversationProcessingUserTask): boolean {
if (projectionForTask(task)) return false;
if (!overflowActionItems(task).length) return false;
if (canExpandFileDetails(task)) return isDetailsExpanded(task);
return true;
function shouldShowOverflowActions(_task: ConversationProcessingUserTask): boolean {
return false;
}
/**
@@ -329,15 +328,19 @@ function shouldShowTaskLevelActions(task: ConversationProcessingUserTask): boole
* 处理记录只读卡:仅保留 view_details 文字链(无主 CTA / 取消 / 重解析)。
*/
function recordViewDetailsItem(task: ConversationProcessingUserTask): ActionPresentationItem | null {
if (String(task.status_label || '').trim().toLowerCase() === 'cancelled') return null;
const presentation = taskActionPresentation(task);
const candidates = [
presentation.primary,
presentation.secondary,
...presentation.overflow,
].filter((item): item is ActionPresentationItem => Boolean(item));
return candidates.find(
(item) => String(item.actionCode || '').trim().toLowerCase() === 'view_details',
) || null;
return candidates.find((item) => {
const code = String(item.actionCode || '').trim().toLowerCase();
return code === 'view_details' || code === 'view_result';
}) || (String(task.group || '') === 'completed'
? { intent: 'view_result', actionCode: 'view_result', labelKey: 'chat.shippingProcessing.action.view_result' }
: null);
}
/**
@@ -591,8 +594,15 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
{{ resolveShippingProcessingMessage('justCreated', te, t) }}
</div>
</button>
<div
v-if="task.group === 'needs_action' && currentNeedLabel(task)"
class="mt-1 text-[11px] text-secondary"
data-testid="shipping-processing-current-need"
>
{{ t('chat.shippingProcessing.progress.currentNeedLabel') }}{{ currentNeedLabel(task) }}
</div>
<SidebarProgressInline
v-if="progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
v-if="task.group === 'processing' && progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
class="mt-1.5 border-t border-current/10 pt-1.5"
:projection="projectionForTask(task)!"
:compact="progressModeForTask(task) === 'compact'"
@@ -612,57 +622,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
>
{{ presentationActionLabel(task, primaryActionItem(task)!) }}
</button>
<button
v-if="canExpandFileDetails(task)"
type="button"
class="inline-flex items-center gap-1 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
data-testid="shipping-processing-expand-files"
@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>
<button
v-else-if="secondaryActionItem(task)"
type="button"
class="text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
:data-testid="`shipping-processing-action-${secondaryActionItem(task)!.actionCode}`"
@click="onTaskAction(task, secondaryActionItem(task)!.actionCode)"
>
{{ presentationActionLabel(task, secondaryActionItem(task)!) }}
</button>
</div>
<button
v-else-if="canExpandFileDetails(task)"
type="button"
class="mt-1.5 inline-flex items-center gap-1 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
data-testid="shipping-processing-expand-files"
@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>
<div
v-if="shouldShowOverflowActions(task)"
class="mt-1.5 flex flex-wrap gap-x-3 gap-y-1"
data-testid="shipping-processing-task-overflow-actions"
>
<button
v-for="item in overflowActionItems(task)"
:key="`${task.user_task_no}-overflow-${item.actionCode}`"
type="button"
class="text-[11px] text-muted underline-offset-2 hover:text-secondary hover:underline"
:data-testid="`shipping-processing-action-${item.actionCode}`"
@click="onTaskAction(task, item.actionCode)"
>
{{ presentationActionLabel(task, item) }}
</button>
<span v-if="task.group === 'needs_action'" class="sr-only">{{ currentNeedLabel(task) }}</span>
</div>
</article>
</div>
@@ -54,7 +54,7 @@ const props = defineProps<{
controller?: UseShippingNoticeWorkflowReturn | null;
}>();
const { t, te, locale } = useI18n();
const { t, te } = useI18n();
const msg = useMessage();
const route = useRoute();
const router = useRouter();
@@ -93,8 +93,6 @@ const ctl = computed((): UseShippingNoticeWorkflowReturn => (
const collapsed = ref(false);
/** 复核返回对话时展示的聚焦提示(由 focus_notice 触发一次)。 */
const focusTaskBanner = ref<string | null>(null);
/** 侧栏默认展示本批次全部文件,用户需要同时看到已完成与待处理状态。 */
const pendingOnlyFilter = ref(false);
const actionBusyItemNo = ref<string | null>(null);
const detailOpen = ref(false);
const detailLoading = ref(false);
@@ -106,28 +104,26 @@ const reasonDialogItem = ref<ShippingWorkflowItem | null>(null);
/** 任务级取消:走 Run API,不绑单个 WorkflowItem。 */
const reasonDialogRunNo = ref<string | null>(null);
/** 当前展开文件明细的 OT 任务;收起后清空。 */
/** 移除右侧常驻批次与文件列表:文件明细改为进入订单处理工作台后展示。 */
const expandedTask = ref<ConversationProcessingUserTask | null>(null);
/** 文件明细:由展开任务的 document objects 合成。 */
/** 文件行仅用于 Gate 恢复卡、路由聚焦匹配 activeItem 与 open_review 动作兜底。 */
const items = computed((): ShippingWorkflowItem[] => (
mapUserTaskObjectsToFileRows(expandedTask.value)
));
const processing = computed(() => ctl.value.processing?.value ?? null);
const processingWorkItems = computed((): ShippingProcessingProjection[] => (
Array.isArray(ctl.value.processingWorkItems?.value)
? ctl.value.processingWorkItems.value
: []
));
const processing = computed(() => ctl.value.processing?.value ?? null);
/** 展示投影:统一 ShippingProcessing / conversation_processing。 */
const displayProcessing = computed(() => processing.value);
const loading = computed(() => ctl.value.loading.value);
/** 初始加载:首次打开投影仍为空时显示摘要占位。 */
const initialLoading = computed(() => Boolean(ctl.value.initialLoading?.value));
/** 用户主动刷新(刷新按钮 / 重试 / 重解析等):驱动顶部刷新图标旋转。 */
const manualRefreshing = computed(() => Boolean(ctl.value.manualRefreshing?.value));
const error = computed(() => ctl.value.error.value);
/** 用户从任务卡展开后,按任务内当前有效 PDF 身份过滤;旧数据才回退到 run_no。 */
const fileFilterRunNo = ref<string | null>(null);
const fileFilterDocumentKeys = ref<Set<string>>(new Set());
/** 任务卡明确展开文件详情时为 true(有任务卡时才约束显隐)。 */
const filesDetailVisible = ref(false);
/** 路由或复核返回的权威 OT 聚焦号。 */
const routeFocusedTaskNo = computed(() => String(
route.query.focus_task_no
|| focusTaskBanner.value
@@ -155,53 +151,6 @@ const activeItem = computed(() => {
}) || items.value.find((item) => resolveItemDisplayStatus(item) === 'pending_review') || items.value[0] || null;
});
const visibleItems = computed(() => {
const documentKeys = fileFilterDocumentKeys.value;
if (documentKeys.size) {
return items.value.filter((item) => workflowItemDocumentKeys(item).some(
(key) => documentKeys.has(key),
));
}
const runNo = String(fileFilterRunNo.value || '').trim();
if (!runNo) return items.value;
return items.value.filter((item) => String(item.current_run_no || '').trim() === runNo);
});
/**
* 解析 WorkflowItem 的 PDF 身份候选,顺序与后端聚合契约一致。
* @param item - 侧栏 WorkflowItem
* @returns 可用于匹配任务文档对象的稳定身份键列表
*/
function workflowItemDocumentKeys(item: ShippingWorkflowItem): string[] {
const keys: string[] = [];
const hash = String(item.content_hash || '').trim().toLowerCase();
const rootId = Number(item.root_document_id || 0);
const documentId = Number(item.current_document_id || 0);
if (hash) keys.push(`hash:${hash}`);
if (rootId > 0) keys.push(`root:${rootId}`);
if (documentId > 0) keys.push(`doc:${documentId}`);
return keys;
}
/**
* 解析任务投影内当前有效 PDF 身份,用于跨 Run 展开完整文件集合。
* @param task - 用户可见任务卡
* @returns 当前有效 PDF 的稳定身份键集合
*/
function taskDocumentKeys(task: ConversationProcessingUserTask): Set<string> {
const keys = new Set<string>();
for (const object of task.objects || []) {
if (object.kind !== 'document') continue;
const hash = String(object.content_hash || '').trim().toLowerCase();
const rootId = Number(object.root_document_id || 0);
const documentId = Number(object.document_id || 0);
if (hash) keys.add(`hash:${hash}`);
if (rootId > 0) keys.add(`root:${rootId}`);
if (documentId > 0) keys.add(`doc:${documentId}`);
}
return keys;
}
/** 任务聚合投影存在时隐藏独立「当前阶段」卡,避免三套状态重复(UI-F04)。 */
const showStandaloneCurrentStage = computed(() => {
const projection = displayProcessing.value;
@@ -248,12 +197,9 @@ watch(
);
/**
* 文件列表显隐:有用户任务卡时仅展开后显示;无任务卡时不展示空壳文件抽屉。
* 移除右侧常驻「批次与文件列表」长列表抽屉(UI-REFACTOR 方案 7)。
* 文件明细进入订单处理工作台后展示;此处仅保留 Gate 卡与独立 DetailDrawer,避免两套投影矛盾与高度抖动。
*/
const showFilesDrawer = computed(() => {
if (collapsed.value) return false;
return filesDetailVisible.value && Boolean(expandedTask.value);
});
function itemActivityLabel(item: ShippingWorkflowItem | null): string {
if (!item) return t('chat.shippingProcessing.emptyCompact');
@@ -357,25 +303,28 @@ async function onProcessingFocus(taskNo: string) {
}
/**
* 展开任务文件详情:优先按任务内当前有效 PDF 集合过滤;旧投影回退到代表 run_no。
* 展开文件详情 → 直接进入订单处理工作台(方案 7:移除右侧常驻文件列表)。
* 文件明细在工作台展示;此处仍保留 expandedTask 以便 Gate 卡找到聚焦 Run。
* 无 run_no 时 toast 提示,禁止静默 return。
*/
function onExpandTaskFiles(task: ConversationProcessingUserTask) {
async function onExpandTaskFiles(task: ConversationProcessingUserTask) {
const runNo = String(task.run_no || '').trim();
const documentKeys = taskDocumentKeys(task);
expandedTask.value = task;
fileFilterDocumentKeys.value = documentKeys;
fileFilterRunNo.value = documentKeys.size ? null : (runNo || null);
filesDetailVisible.value = true;
// 走原有工作台入口,保持与「继续处理」按钮一致;失败则静默(仍保留本地聚焦)。
if (runNo) {
try {
await openReviewFromTask(task);
} catch {
/* 路由失败不阻塞,交由上层统一错误处理。 */
}
}
}
/**
* 收起任务文件详情:清空过滤并隐藏下方文件列表。
* 收起文件详情:仅清空本地过滤聚焦态,右侧不再常驻文件长列表。
*/
function onCollapseTaskFiles() {
expandedTask.value = null;
fileFilterRunNo.value = null;
fileFilterDocumentKeys.value = new Set();
filesDetailVisible.value = false;
}
/**
@@ -461,104 +410,6 @@ async function onProcessingTaskAction(payload: {
}
}
type ItemGroupKey =
| 'processing'
| 'queued'
| 'completed'
| 'pending_review'
| 'failed'
| 'waiting_manual_upload';
const PROCESSING_STATUSES = new Set([
'layout_parsing',
'extracting',
'building_order',
'inventory_matching',
'generating_excel',
]);
const QUEUED_STATUSES = new Set(['queued']);
const FAILED_STATUSES = new Set(['failed', 'reparse_failed']);
/** 真正完成/取消;待人工登记不是完成。 */
const COMPLETED_STATUSES = new Set(['closed', 'cancelled']);
const WAITING_MANUAL_UPLOAD_STATUSES = new Set(['manual_upload_pending']);
const UPLOAD_RPA_RUNNING_STATUSES = new Set(['upload_rpa_pending', 'upload_rpa_running']);
const PENDING_REVIEW_STATUSES = new Set(['pending_review']);
const ACTIONABLE_FILTER_STATUSES = new Set([
'pending_review',
'failed',
'reparse_failed',
'queued',
'manual_upload_pending',
'upload_rpa_pending',
'upload_rpa_running',
'upload_rpa_failed',
]);
/**
* 将 Item 归入展示分组;优先 is_waiting_manual_upload / display(禁止单靠 lifecycle 推断人工待办)。
*/
function resolveGroup(item: ShippingWorkflowItem): ItemGroupKey {
const display = resolveItemDisplayStatus(item);
if (PENDING_REVIEW_STATUSES.has(display)) return 'pending_review';
if (FAILED_STATUSES.has(display) || display === 'upload_rpa_failed') return 'failed';
if (UPLOAD_RPA_RUNNING_STATUSES.has(display)) return 'processing';
if (item.is_waiting_manual_upload === true || item.upload_phase === 'manual_pending') {
return 'waiting_manual_upload';
}
if (WAITING_MANUAL_UPLOAD_STATUSES.has(display) && item.is_waiting_manual_upload !== false) {
return 'waiting_manual_upload';
}
const status = String(item.lifecycle_status || '').trim();
if (PENDING_REVIEW_STATUSES.has(status)) return 'pending_review';
if (FAILED_STATUSES.has(status)) return 'failed';
if (
item.is_waiting_manual_upload !== false
&& WAITING_MANUAL_UPLOAD_STATUSES.has(status)
&& !UPLOAD_RPA_RUNNING_STATUSES.has(display)
&& display !== 'upload_rpa_failed'
&& item.upload_phase !== 'rpa_pending'
&& item.upload_phase !== 'rpa_running'
&& item.upload_phase !== 'rpa_failed'
) {
return 'waiting_manual_upload';
}
if (COMPLETED_STATUSES.has(status)) return 'completed';
if (QUEUED_STATUSES.has(status)) return 'queued';
if (PROCESSING_STATUSES.has(status)) return 'processing';
return 'processing';
}
/**
* 是否允许取消:优先后端 available_actions;无 Run 时隐藏(co8 Workflow Item API 已下线)。
*/
function canCancel(item: ShippingWorkflowItem): boolean {
if (!String(item.current_run_no || '').trim()) return false;
const actions = item.available_actions;
if (Array.isArray(actions)) return actions.includes('cancel');
return !COMPLETED_STATUSES.has(String(item.lifecycle_status || '').trim());
}
/**
* 是否允许重试/重新识别:必须以后端 available_actions 为准,且绑定 current_run_no。
*/
function canReparse(item: ShippingWorkflowItem): boolean {
if (!String(item.current_run_no || '').trim()) return false;
const actions = item.available_actions;
if (Array.isArray(actions)) return actions.includes('reparse');
// 无契约时 fail-closed:禁止仅凭 pending_review 展示(会稳定触发 CASE_REQUIRED)。
return false;
}
/**
* 重识别按钮文案:区分 Case 新版本与失败 Run 重试。
*/
function reparseActionLabel(item: ShippingWorkflowItem): string {
if (item.reparse_kind === 'failed_run_retry') {
return t('chat.shippingProcessing.actions.retryFailedRun');
}
return t('chat.shippingProcessing.actions.reparse');
}
/**
* 列表主标题:优先文件名。
*/
@@ -570,42 +421,6 @@ function itemTitle(item: ShippingWorkflowItem): string {
});
}
const filteredItems = computed(() => {
const source = visibleItems.value;
if (!pendingOnlyFilter.value) return source;
return source.filter((item) => {
const display = resolveItemDisplayStatus(item);
return (
ACTIONABLE_FILTER_STATUSES.has(display)
|| ACTIONABLE_FILTER_STATUSES.has(String(item.lifecycle_status || '').trim())
);
});
});
const grouped = computed(() => {
const buckets: Record<ItemGroupKey, ShippingWorkflowItem[]> = {
processing: [],
queued: [],
pending_review: [],
waiting_manual_upload: [],
failed: [],
completed: [],
};
for (const item of filteredItems.value) {
buckets[resolveGroup(item)].push(item);
}
return buckets;
});
const groupOrder: ItemGroupKey[] = [
'processing',
'queued',
'pending_review',
'waiting_manual_upload',
'failed',
'completed',
];
/**
* 解析生命周期状态文案。
*/
@@ -614,20 +429,6 @@ function statusLabel(status: string): string {
return te(key) ? t(key) : t('chat.shippingProcessing.itemStatus.unknown');
}
/**
* 格式化更新时间。
*/
function formatUpdatedLabel(value?: string | null): string {
const date = new Date(String(value || ''));
if (Number.isNaN(date.getTime())) return '';
const time = new Intl.DateTimeFormat(String(locale.value || 'zh-CN'), {
hour: '2-digit',
minute: '2-digit',
hour12: false,
}).format(date);
return t('chat.shippingOrderExtractionDocumentTiming.updated', { time });
}
/**
* 手动刷新。
*/
@@ -635,17 +436,6 @@ async function onRefresh() {
await ctl.value.refresh();
}
/**
* 打开详情抽屉:仅用列表投影,不再请求已 DROP 的 WorkflowItem 详情 API。
*/
function openDetail(item: ShippingWorkflowItem) {
const itemNo = String(item.item_no || '').trim();
if (!itemNo) return;
detailOpen.value = true;
detailItem.value = item;
detailLoading.value = false;
}
/**
* 打开取消原因弹窗:优先绑定 current_run_no,走 Run 级取消 API。
*/
@@ -902,12 +692,15 @@ watch(
<button
type="button"
class="shrink-0 rounded-md p-1.5 text-muted hover:bg-surface-muted hover:text-primary disabled:opacity-50"
:disabled="loading"
:disabled="initialLoading || manualRefreshing"
:title="t('chat.shippingProcessing.actions.refresh')"
data-testid="shipping-workflow-refresh"
@click="onRefresh"
>
<RefreshCw class="h-3.5 w-3.5" :class="{ 'animate-spin': loading }" />
<RefreshCw
class="h-3.5 w-3.5"
:class="{ 'animate-spin': initialLoading || manualRefreshing }"
/>
</button>
</div>
@@ -982,174 +775,11 @@ watch(
</div>
</div>
<div
v-if="showFilesDrawer"
class="mt-3 min-h-0 flex-1 overflow-y-auto rounded-xl border border-default bg-surface-soft/40 p-2"
data-testid="shipping-workflow-details-drawer"
>
<section
class="flex min-h-0 w-full flex-col"
:aria-label="t('chat.shippingProcessing.detailsDrawerTitle')"
>
<div class="flex items-center justify-between gap-2 border-b border-default px-4 py-3">
<div class="min-w-0">
<div class="text-sm font-semibold text-primary">
{{ t('chat.shippingProcessing.detailsDrawerTitle') }}
</div>
<div class="mt-0.5 text-[11px] text-secondary">
{{ t('chat.shippingProcessing.compactSummary', {
active: items.length,
total: counts.total,
}) }}
</div>
</div>
<span class="text-[11px] text-secondary">{{ t('chat.shippingProcessing.activity.fileListTitle') }}</span>
</div>
<div class="p-4">
<div
class="mb-3 flex flex-wrap gap-1.5 text-[11px]"
data-testid="shipping-workflow-counts"
>
<span class="rounded-md bg-sky-50 px-2 py-0.5 text-sky-700 dark:bg-sky-950/40 dark:text-sky-200">
{{ t('chat.shippingProcessing.counts.processing', { count: counts.processing }) }}
</span>
<span
v-if="counts.pending_review > 0"
class="rounded-md bg-amber-50 px-2 py-0.5 text-amber-700 dark:bg-amber-950/40 dark:text-amber-200"
>
{{ t('chat.shippingProcessing.counts.pendingReview', { count: counts.pending_review }) }}
</span>
<span
v-if="(counts.waiting_manual_upload || 0) > 0"
class="rounded-md bg-amber-50 px-2 py-0.5 text-amber-800 dark:bg-amber-950/40 dark:text-amber-100"
>
{{ t('chat.shippingProcessing.counts.waitingManualUpload', {
count: counts.waiting_manual_upload || 0,
}) }}
</span>
<span class="rounded-md bg-emerald-50 px-2 py-0.5 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200">
{{ t('chat.shippingProcessing.counts.completed', { count: counts.completed }) }}
</span>
<span
v-if="counts.failed > 0"
class="rounded-md bg-rose-50 px-2 py-0.5 text-rose-700 dark:bg-rose-950/40 dark:text-rose-200"
>
{{ t('chat.shippingProcessing.counts.failed', { count: counts.failed }) }}
</span>
</div>
<template v-for="groupKey in groupOrder" :key="groupKey">
<section
v-if="grouped[groupKey].length"
class="mb-3"
:data-testid="`shipping-workflow-group-${groupKey}`"
>
<h3 class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-secondary">
{{ t(`chat.shippingProcessing.groups.${groupKey}`) }}
</h3>
<ul class="space-y-2">
<li
v-for="item in grouped[groupKey]"
:key="item.item_no"
class="rounded-lg border border-default bg-surface-soft/80 px-2.5 py-2"
:data-testid="`shipping-workflow-item-${item.item_no}`"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div
class="truncate text-xs font-semibold text-primary"
:title="itemTitle(item)"
data-testid="shipping-workflow-item-filename"
>
{{ itemTitle(item) }}
</div>
<div class="mt-0.5 text-[11px] text-muted">
{{ t('chat.shippingProcessing.versionLabel', { version: item.current_version_no }) }}
· {{ itemActivityLabel(item) }}
<span v-if="!item.current_case_no" class="ml-1 text-secondary">
· {{ t('chat.shippingProcessing.noReviewCaseYet') }}
</span>
</div>
</div>
<span
class="shrink-0 rounded-full px-1.5 py-0.5 text-[10px] font-medium"
:class="{
'bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-100':
groupKey === 'pending_review'
|| groupKey === 'failed'
|| groupKey === 'waiting_manual_upload',
'bg-sky-100 text-sky-800 dark:bg-sky-900/50 dark:text-sky-100':
groupKey === 'processing' || groupKey === 'queued',
'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-100':
groupKey === 'completed',
}"
>
{{ statusLabel(resolveItemDisplayStatus(item)) }}
</span>
</div>
<div v-if="item.last_activity_at || item.updated_at" class="mt-0.5 text-[11px] text-muted">
{{ formatUpdatedLabel(item.last_activity_at || item.updated_at) }}
</div>
<div v-if="groupKey === 'processing' || groupKey === 'queued'" class="mt-1 text-[11px] text-brand-700 dark:text-brand-300">
{{ t('chat.shippingProcessing.activity.currentAction', { action: itemActivityLabel(item) }) }}
</div>
<ProcessGateRecoveryCard
v-if="item.process_gate?.current_blocking_gate"
class="mt-2"
:summary="item.process_gate"
:can-handle="true"
:navigation-context="gateNavigationContext"
@refreshed="() => void ctl.refresh()"
@refresh-needed="() => void ctl.refresh()"
@confirm-customer="(taskNo) => void onGateConfirmCustomer(taskNo)"
/>
<div class="mt-2 flex min-w-0 items-center gap-2 overflow-x-auto whitespace-nowrap pb-0.5">
<button
v-if="groupKey === 'pending_review' && item.current_run_no"
type="button"
class="inline-flex shrink-0 items-center gap-1 rounded-md bg-brand-600 px-2.5 py-1 text-[11px] font-semibold text-white shadow-sm hover:bg-brand-700 disabled:opacity-50"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-workflow-action-open-review"
@click="openReview(item)"
>
{{ t('chat.shippingProcessing.actions.openReview') }}
</button>
<button
type="button"
class="inline-flex shrink-0 items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline"
data-testid="shipping-workflow-action-view"
@click="openDetail(item)"
>
{{ t('chat.shippingProcessing.actions.viewProgress') }}
</button>
<button
v-if="canReparse(item)"
type="button"
class="inline-flex shrink-0 items-center gap-1 text-[11px] font-medium text-amber-800 hover:underline disabled:opacity-50 dark:text-amber-200"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-workflow-action-reparse"
@click="openReparseDialog(item)"
>
{{ reparseActionLabel(item) }}
</button>
<button
v-if="canCancel(item)"
type="button"
class="inline-flex shrink-0 items-center gap-1 text-[11px] font-medium text-rose-700 hover:underline disabled:opacity-50"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-workflow-action-cancel"
@click="openCancelDialog(item)"
>
{{ t('chat.shippingProcessing.actions.cancelFile') }}
</button>
</div>
</li>
</ul>
</section>
</template>
</div>
</section>
</div>
<!--
方案 7:移除右侧常驻「批次与文件列表」聚合抽屉,避免与任务卡投影矛盾与高度抖动。
文件明细统一在订单处理工作台展示;任务卡仅显示任务名 / 文件数 / 状态 / 主按钮。
Gate 级阻断与进度详情仍通过 ProcessGateRecoveryCard 与 ShippingWorkflowItemDetailDrawer 呈现。
-->
<ShippingWorkflowItemDetailDrawer
:open="detailOpen"
@@ -15,6 +15,10 @@ import {
groupConversationProcessingTasks,
mapUserTaskObjectsToFileRows,
resolveConversationProcessingFromUnified,
normalizeActionCodes,
buildTaskSemanticKey,
buildProcessingSemanticKey,
stabilizeTaskObjects,
} from './conversationProcessingProjection';
import type {
ShippingProcessingProjection,
@@ -730,3 +734,166 @@ describe('conversationProcessingProjection', () => {
expect(merged?.recent_task_no).toBe('OT-RECENT');
});
});
/**
* 方案 1~4 的防御链单元测试:
* normalize → semanticKey → stabilize;任何一环击穿都会导致轮询按钮闪烁。
* 对应验收:动作顺序变化按钮不变 / updated_at 变化按钮不变 / 轮询相同数据按钮 DOM 不变。
*/
describe('conversationProcessingProjection — normalize & semantic & stabilize', () => {
it('normalizeActionCodes: 去空白、小写、去重、字典序排序', () => {
expect(normalizeActionCodes([' View_Details ', 'Confirm_Customer', 'view_details', ' confirm_customer ']))
.toEqual(['confirm_customer', 'view_details']);
expect(normalizeActionCodes([null, undefined, '', ' ', 'cancel', '0']))
.toEqual(['0', 'cancel']);
expect(normalizeActionCodes([])).toEqual([]);
expect(normalizeActionCodes([undefined, null])).toEqual([]);
});
it('buildTaskSemanticKey: available_actions 乱序 → 同一签名(不影响按钮顺序)', () => {
const base: Parameters<typeof projectConversationProcessingFromWorkItems>[0][number] = {
workItemType: 'order_task',
workItemNo: 'OT-1',
sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-1',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'waiting_review',
stage: 'waiting_review',
progressVersion: 1,
lastActivityAt: '2026-08-10T00:00:00Z',
currentGate: {
gateCode: 'order_freeze_readiness',
status: 'blocked',
nextActionCode: 'open_order_review',
blockingReasonCode: 'review_case_draft',
attemptNo: 0,
},
availableActions: ['open_order_review', 'view_details'],
sourceSummary: {
emailSubject: null,
filename: 'a.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 0,
customerName: null,
poNumber: 'PO-1',
},
childOrderTasks: [],
};
const p1 = projectConversationProcessingFromWorkItems([{ ...base }]);
const p2 = projectConversationProcessingFromWorkItems([
{ ...base, availableActions: ['view_details', 'open_order_review'], lastActivityAt: '2099-01-01T00:00:00Z' },
]);
const t1 = p1!.needs_action[0]!;
const t2 = p2!.needs_action[0]!;
// 相同语义字段 -> 同签名;即使 available_actions 顺序不同、lastActivityAt 不同。
expect(buildTaskSemanticKey(t1)).toBe(buildTaskSemanticKey(t2));
// available_actions 内永远是 normalized 排序后的数组,不是原始后端乱序。
expect(t1.available_actions).toEqual(['open_order_review', 'view_details']);
expect(t2.available_actions).toEqual(['open_order_review', 'view_details']);
});
it('stabilizeTaskObjects: 同一 user_task_no 且语义相同,优先复用旧对象引用(避免 DOM 重建)', () => {
const baseTask = (no: string, updatedAt: string) => ({
user_task_no: no,
group: 'processing' as const,
status_label: 'document_parsing',
run_no: 'RUN-1',
title: '订单识别任务',
primary_action: 'view_details',
display_kind: 'single_document_task',
file_count: 1,
can_append: false,
updated_at: updatedAt,
last_activity_at: updatedAt,
available_actions: ['view_details'],
current_gate: null,
user_task_authoritative: true,
documents: [],
});
const oldOne = baseTask('OT-1', '2026-08-10T00:00:00Z');
const nextOne = baseTask('OT-1', '2026-08-10T00:00:02Z');
const oldTasks = [oldOne];
const nextRawTasks = [nextOne];
const stabilized = stabilizeTaskObjects(oldTasks, nextRawTasks);
// updated_at/last_activity_at 不参与 semanticKey 比较 -> 复用旧引用。
expect(stabilized[0]).toBe(oldOne);
expect(stabilized[0].updated_at).toBe('2026-08-10T00:00:00Z');
});
it('buildProcessingSemanticKey: 只基于语义字段,忽略 updated_at/last_activity_at 扰动', () => {
function makeProjection() {
return projectConversationProcessingFromWorkItems([{
workItemType: 'order_task',
workItemNo: 'OT-A',
sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-A',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'processing',
stage: 'document_parsing',
progressVersion: 1,
lastActivityAt: '2026-08-10T00:00:00Z',
currentGate: null,
availableActions: ['view_details'],
sourceSummary: {
emailSubject: null, filename: 'a.pdf',
documentCount: 1, parsedDocumentCount: 1, candidateCount: 0,
customerName: null, poNumber: null,
},
childOrderTasks: [],
}])!;
}
const pA = makeProjection();
const pB = makeProjection();
// 模拟轮询差异:updated_at / last_activity_at / created_at 等辅助字段都变。
pA.processing[0]!.updated_at = '2026-08-10T00:00:00Z';
pA.processing[0]!.last_activity_at = '2026-08-10T00:00:00Z';
pB.processing[0]!.updated_at = '2026-08-10T00:00:02Z';
pB.processing[0]!.last_activity_at = '2026-08-10T00:00:02Z';
expect(buildProcessingSemanticKey(pA)).toBe(buildProcessingSemanticKey(pB));
});
it('stabilizeTaskObjects: 语义变化时(status 改变)必须返回新对象,不能错误冻结旧状态', () => {
const oldTask = {
user_task_no: 'OT-1',
group: 'processing' as const,
status_label: 'document_parsing',
run_no: 'RUN-1',
title: '订单识别任务',
primary_action: 'view_details',
display_kind: 'single_document_task',
file_count: 1,
can_append: false,
updated_at: '2026-08-10T00:00:00Z',
last_activity_at: '2026-08-10T00:00:00Z',
available_actions: ['view_details'],
current_gate: null,
user_task_authoritative: true,
documents: [],
};
const nextTask = {
...oldTask,
group: 'needs_action' as const,
status_label: 'waiting_review',
primary_action: 'open_order_review',
available_actions: ['open_order_review', 'view_details'],
updated_at: '2026-08-10T00:00:10Z',
last_activity_at: '2026-08-10T00:00:10Z',
current_gate: {
blockingReasonCode: 'review_case_draft',
nextActionCode: 'open_order_review',
},
};
const stabilized = stabilizeTaskObjects([oldTask], [nextTask]);
// 状态从 processing→needs_action 语义已变,必须替换成新引用。
expect(stabilized[0]).not.toBe(oldTask);
expect(stabilized[0].status_label).toBe('waiting_review');
expect(stabilized[0].available_actions).toEqual(['open_order_review', 'view_details']);
});
});
@@ -6,6 +6,7 @@
* 逻辑:Timeline 与 ShippingConversationProcessingCard 复用;文件明细由
* mapUserTaskObjectsToFileRows(task.objects) 合成;禁止 Workflow fallback reconcile;
* 可由统一 work_items(order_task)合成兼容分组。
* 语义签名与任务稳定化:轮询返回相同业务状态时复用旧对象,避免按钮闪烁。
*/
import type {
@@ -19,8 +20,111 @@ import type {
WorkflowNodeStatus,
} from '@/features/chat/types/shipping.api.types';
/**
* 标准化动作码列表:去空白、小写、去重、字典序排序。
* 核心逻辑:后端返回顺序或临时字段变化时,确保前端动作集合稳定。
*
* @param actions - 原始动作码数组
* @returns 标准化后的动作码数组(唯一、已排序)
*/
export function normalizeActionCodes(actions: unknown[]): string[] {
return [...new Set(
(actions || [])
.map((item) => String(item || '').trim().toLowerCase())
.filter(Boolean),
)].sort();
}
/**
* 构建单个用户任务的语义签名:只包含决定按钮与展示的核心字段。
* 排除 updated_at / last_activity_at 等仅用于辅助提示的字段。
*
* @param task - 用户可见任务
* @returns 语义签名字符串;任务为 null 时返回空串
*/
export function buildTaskSemanticKey(
task: ConversationProcessingUserTask | null | undefined,
): string {
if (!task) return '';
return JSON.stringify({
taskNo: task.user_task_no,
group: task.group,
status: task.status_label,
runNo: task.run_no,
displayKind: task.display_kind,
fileCount: task.file_count,
title: task.title,
primaryAction: task.primary_action || null,
currentGate: (task as ConversationProcessingUserTask & { current_gate?: { blockingReasonCode?: string; nextActionCode?: string } })
.current_gate
? {
blockingReasonCode: (task as ConversationProcessingUserTask & { current_gate?: { blockingReasonCode?: string; nextActionCode?: string } })
.current_gate?.blockingReasonCode || null,
nextActionCode: (task as ConversationProcessingUserTask & { current_gate?: { blockingReasonCode?: string; nextActionCode?: string } })
.current_gate?.nextActionCode || null,
}
: null,
availableActions: normalizeActionCodes(task.available_actions || []),
canAppend: task.can_append ?? null,
});
}
/**
* 构建整个会话处理投影的语义签名:summary + 各分组任务签名。
*
* @param projection - 会话处理投影
* @returns 语义签名字符串;投影为 null 时返回空串
*/
export function buildProcessingSemanticKey(
projection: ConversationProcessingProjection | null | undefined,
): string {
if (!projection) return '';
return JSON.stringify({
summary: {
total_tasks: projection.summary?.total_tasks || 0,
total_files: projection.summary?.total_files || 0,
processing: projection.summary?.processing || 0,
needs_action: projection.summary?.needs_action || 0,
completed: projection.summary?.completed || 0,
history: projection.summary?.history || 0,
},
focused_task_no: projection.focused_task_no || null,
recent_task_no: projection.recent_task_no || null,
needs_action: (projection.needs_action || []).map(buildTaskSemanticKey),
processing: (projection.processing || []).map(buildTaskSemanticKey),
completed: (projection.completed || []).map(buildTaskSemanticKey),
history: (projection.history || []).map(buildTaskSemanticKey),
});
}
/**
* 按任务号复用旧对象:语义签名相同时返回旧引用,保证 Vue v-for 复用 DOM。
*
* @param previousTasks - 上一次渲染的任务列表
* @param nextRawTasks - 本次轮询生成的新任务列表(原始未稳定化)
* @returns 稳定化后的任务列表;语义未变的任务沿用旧引用
*/
export function stabilizeTaskObjects(
previousTasks: ConversationProcessingUserTask[],
nextRawTasks: ConversationProcessingUserTask[],
): ConversationProcessingUserTask[] {
const previousByTaskNo = new Map(
(previousTasks || []).map((task) => [String(task.user_task_no || ''), task]),
);
return (nextRawTasks || []).map((nextTask) => {
const previous = previousByTaskNo.get(String(nextTask.user_task_no || ''));
if (!previous) return nextTask;
if (buildTaskSemanticKey(previous) === buildTaskSemanticKey(nextTask)) {
return previous;
}
return nextTask;
});
}
/** 需要人工处理的生命周期集合。 */
const NEEDS_ACTION_LIFECYCLES = new Set([
'blocked',
'waiting_review',
'pending_review',
'manual_upload_pending',
'failed',
@@ -28,6 +132,16 @@ const NEEDS_ACTION_LIFECYCLES = new Set([
'upload_rpa_failed',
]);
const HUMAN_ACTION_CODES = new Set([
'confirm_customer', 'resolve_field_conflicts', 'adjudicate_duplicate',
'open_order_review', 'open_order_processing', 'enter_manual_review',
'open_inventory_source_review', 'confirm_inventory_source',
'open_inventory_match_review', 'rematch', 'match_inventory',
'open_shortage_review', 'upload_inventory_file', 'open_manual_upload',
'wait_manual_upload', 'retry', 'retry_parse', 'retry_failed_documents',
'retry_failed_attachments', 'open_profile_review',
]);
/** 处理中生命周期集合。 */
const PROCESSING_LIFECYCLES = new Set([
'queued',
@@ -288,7 +402,7 @@ export function classifyConversationProcessingGroup(
status: string | null | undefined,
options?: { hasBlockingGate?: boolean; needsCustomerConfirm?: boolean },
): ConversationProcessingTaskGroup {
if (options?.hasBlockingGate || options?.needsCustomerConfirm) return 'needs_action';
if (options?.needsCustomerConfirm) return 'needs_action';
const normalized = String(status || '').trim();
if (NEEDS_ACTION_LIFECYCLES.has(normalized)) return 'needs_action';
if (COMPLETED_LIFECYCLES.has(normalized)) return 'completed';
@@ -297,7 +411,7 @@ export function classifyConversationProcessingGroup(
if (normalized === 'review_required' || normalized === 'partially_completed') {
return 'needs_action';
}
if (normalized === 'failed' || normalized === 'cancelled') return 'needs_action';
if (normalized === 'failed') return 'needs_action';
if (normalized === 'completed') return 'completed';
if (normalized === 'processing' || normalized === 'queued') return 'processing';
return 'processing';
@@ -431,10 +545,16 @@ export function projectConversationProcessingTasks(
const effectiveItems = uniqueDocuments.map((row) => row.source_item);
// 任务级分组/操作只由最近代表 Item 决定;旧 Run 仅贡献未受影响的 PDF,不得反向污染状态。
const statuses = [resolveItemDisplayStatus(primaryItem)];
const hasGate = Boolean(primaryItem.process_gate?.current_blocking_gate);
const primaryActions = Array.isArray(primaryItem.available_actions)
? primaryItem.available_actions
: [];
const hasHumanAction = primaryActions.some((value) => {
const code = String(value || '').trim().toLowerCase();
return HUMAN_ACTION_CODES.has(code) || code.startsWith('retry_failed_');
});
let group: ConversationProcessingTaskGroup = 'history';
for (const status of statuses) {
const g = classifyConversationProcessingGroup(status, { hasBlockingGate: hasGate });
const g = classifyConversationProcessingGroup(status, { needsCustomerConfirm: hasHumanAction });
if (g === 'needs_action') {
group = 'needs_action';
break;
@@ -523,12 +643,27 @@ export function groupConversationProcessingTasks(
options?: {
focusedTaskNo?: string | null;
recentTaskNo?: string | null;
/** 上一版投影(语义稳定化复用旧对象引用)。 */
previousProjection?: ConversationProcessingProjection | null;
},
): ConversationProcessingProjection {
const needs_action = tasks.filter((t) => t.group === 'needs_action');
const processing = tasks.filter((t) => t.group === 'processing');
const completed = tasks.filter((t) => t.group === 'completed');
const history = tasks.filter((t) => t.group === 'history');
const previousTasks: ConversationProcessingUserTask[] = options?.previousProjection
? [
...(options.previousProjection.needs_action || []),
...(options.previousProjection.processing || []),
...(options.previousProjection.completed || []),
...(options.previousProjection.history || []),
]
: [];
const stabilized = stabilizeTaskObjects(previousTasks, tasks);
const needs_action_raw = stabilized.filter((t) => t.group === 'needs_action');
const processing_raw = stabilized.filter((t) => t.group === 'processing');
const completed_raw = stabilized.filter((t) => t.group === 'completed');
const history_raw = stabilized.filter((t) => t.group === 'history');
const needs_action = stabilizeTaskObjects(options?.previousProjection?.needs_action || [], needs_action_raw);
const processing = stabilizeTaskObjects(options?.previousProjection?.processing || [], processing_raw);
const completed = stabilizeTaskObjects(options?.previousProjection?.completed || [], completed_raw);
const history = stabilizeTaskObjects(options?.previousProjection?.history || [], history_raw);
const all = [...needs_action, ...processing, ...completed, ...history];
const summary: ConversationProcessingSummary = {
total_tasks: all.length,
@@ -572,14 +707,15 @@ export function mapShippingProcessingStatusToTaskGroup(
item: ShippingProcessingProjection,
): ConversationProcessingTaskGroup {
const status = String(item.status || '').trim().toLowerCase();
const gateAction = String(item.currentGate?.nextActionCode || '').trim();
const gateAction = String(item.currentGate?.nextActionCode || '').trim().toLowerCase();
const hasHumanAction = [gateAction, ...(item.availableActions || [])]
.map((value) => String(value || '').trim().toLowerCase())
.some((value) => HUMAN_ACTION_CODES.has(value) || value.startsWith('retry_failed_'));
if (
status === 'waiting_review'
|| status === 'blocked'
|| status === 'failed'
|| gateAction === 'open_order_review'
|| gateAction === 'retry_parse'
|| gateAction === 'retry_failed_documents'
|| hasHumanAction
) {
return 'needs_action';
}
@@ -615,19 +751,22 @@ export function mergeConversationProcessingFocusMetadata(
* 从统一 shipping-processing 响应解析 ConversationProcessingProjection。
* 核心逻辑:work_items 非空时始终由 order_task 工作项合成任务列表;禁止优先 embedded
* (兄弟 OT 仅出现在 work_items,embedded 可能缺 sibling)。
* 语义稳定化:对比 previousProjection 的签名,复用未变的任务对象引用。
*
* @param workItems - unified.work_items
* @param embedded - unified.conversation_processing
* @param previousProjection - 上一版投影(用于任务对象稳定化)
* @returns 会话处理投影;无可用数据时 null
*/
export function resolveConversationProcessingFromUnified(
workItems: ShippingProcessingProjection[] | null | undefined,
embedded: ConversationProcessingProjection | null | undefined,
previousProjection?: ConversationProcessingProjection | null,
): ConversationProcessingProjection | null {
const items = Array.isArray(workItems) ? workItems : [];
if (items.length > 0) {
return mergeConversationProcessingFocusMetadata(
projectConversationProcessingFromWorkItems(items),
projectConversationProcessingFromWorkItems(items, previousProjection),
embedded,
);
}
@@ -638,22 +777,22 @@ export function resolveConversationProcessingFromUnified(
/**
* 从统一 work_items 合成 ConversationProcessingProjection(仅 order_task)。
*
* 核心逻辑:order_task 工作项填充 needs_action/processing/completed;intake 不入组。
* 核心逻辑:order_task 工作项填充 needs_action/processing/completed;intake 不入组;
* available_actions 使用标准化(去重、排序)动作码;按 previousProjection 复用旧对象引用。
*
* @param workItems - 统一投影 work_items
* @param previousProjection - 上一版投影(语义稳定化复用旧对象)
* @returns 兼容投影;无 order_task 时返回 null
*/
export function projectConversationProcessingFromWorkItems(
workItems: ShippingProcessingProjection[] | null | undefined,
previousProjection?: ConversationProcessingProjection | null,
): ConversationProcessingProjection | null {
const items = Array.isArray(workItems) ? workItems : [];
const orderTasks = items.filter((row) => row.workItemType === 'order_task');
if (!orderTasks.length) return null;
const needs_action: ConversationProcessingUserTask[] = [];
const processing: ConversationProcessingUserTask[] = [];
const completed: ConversationProcessingUserTask[] = [];
const history: ConversationProcessingUserTask[] = [];
const rawTasks: ConversationProcessingUserTask[] = [];
for (const item of orderTasks) {
const taskNo = String(item.workItemNo || item.rootOrderTaskNo || '').trim();
@@ -661,6 +800,8 @@ export function projectConversationProcessingFromWorkItems(
const group = mapShippingProcessingStatusToTaskGroup(item);
const docCount = Number(item.sourceSummary?.documentCount || 0);
const filename = String(item.sourceSummary?.filename || '').trim();
const normalizedActions = normalizeActionCodes(item.availableActions || []);
const gateNextAction = String(item.currentGate?.nextActionCode || '').trim().toLowerCase() || null;
const task: ConversationProcessingUserTask = {
user_task_no: taskNo,
user_task_authoritative: true,
@@ -670,22 +811,30 @@ export function projectConversationProcessingFromWorkItems(
group,
status_label: String(item.status || '') || null,
file_count: docCount > 0 ? docCount : (filename ? 1 : 0),
// [P0] 消费后端投影 run_no,禁止写死 null 导致「进入订单处理」静默失败。
run_no: String(item.runNo || '').trim() || null,
can_append: false,
last_activity_at: item.lastActivityAt || null,
available_actions: Array.isArray(item.availableActions) ? [...item.availableActions] : [],
primary_action: item.currentGate?.nextActionCode || item.availableActions?.[0] || null,
available_actions: normalizedActions,
primary_action: gateNextAction || normalizedActions[0] || null,
};
if (group === 'needs_action') needs_action.push(task);
else if (group === 'processing') processing.push(task);
else if (group === 'completed') completed.push(task);
else history.push(task);
rawTasks.push(task);
}
const active = [...needs_action, ...processing, ...completed];
if (!active.length && !history.length) return null;
// 后端未返回 embedded 汇总时,仍按 OT 主 PDF ID 去重,禁止兄弟 OT 重复累计。
if (!rawTasks.length) return null;
const needs_action_raw: ConversationProcessingUserTask[] = [];
const processing_raw: ConversationProcessingUserTask[] = [];
const completed_raw: ConversationProcessingUserTask[] = [];
const history_raw: ConversationProcessingUserTask[] = [];
for (const task of rawTasks) {
if (task.group === 'needs_action') needs_action_raw.push(task);
else if (task.group === 'processing') processing_raw.push(task);
else if (task.group === 'completed') completed_raw.push(task);
else history_raw.push(task);
}
const active = [...needs_action_raw, ...processing_raw, ...completed_raw];
if (!active.length && !history_raw.length) return null;
const documentIds = new Set(
orderTasks
.map((item) => Number(item.sourceSummary?.documentId || 0))
@@ -694,6 +843,35 @@ export function projectConversationProcessingFromWorkItems(
const totalFiles = documentIds.size > 0
? documentIds.size
: active.reduce((sum, task) => sum + Number(task.file_count || 0), 0);
const stabilizedAll = stabilizeTaskObjects(
previousProjection
? [
...(previousProjection.needs_action || []),
...(previousProjection.processing || []),
...(previousProjection.completed || []),
...(previousProjection.history || []),
]
: [],
rawTasks,
);
const needs_action = stabilizeTaskObjects(
previousProjection?.needs_action || [],
stabilizedAll.filter((t) => t.group === 'needs_action'),
);
const processing = stabilizeTaskObjects(
previousProjection?.processing || [],
stabilizedAll.filter((t) => t.group === 'processing'),
);
const completed = stabilizeTaskObjects(
previousProjection?.completed || [],
stabilizedAll.filter((t) => t.group === 'completed'),
);
const history = stabilizeTaskObjects(
previousProjection?.history || [],
stabilizedAll.filter((t) => t.group === 'history'),
);
return {
summary: {
total_tasks: active.length,
@@ -4,7 +4,10 @@
* 依赖:shipping.api getWorkspaceShippingProcessing / focus·viewed、Vue 响应式、BusinessError。
* 逻辑:由 ChatViewContent / ShippingWorkflowTimeline 消费;仅读 shipping-processing;
* focus/viewed 写路径优先应用响应中的 work_items;
* 前台 2s / 后台 8s;请求 10s AbortController 超时;失败指数退避至 8s;无活跃任务时停轮询。
* 前台 2s / 后台 8s;请求 10s AbortController 超时;失败指数退避至 8s;
* 分层轮询:系统处理中 2s 轮询,待复核 30s 轮询;
* 区分 initialLoading / manualRefreshing / polling 三种 loading 态;
* 语义签名比较:业务状态未变化时不替换投影对象,防止按钮闪烁与 DOM 重建。
*/
import {
computed,
@@ -27,7 +30,10 @@ import type {
ConversationProcessingProjection,
ShippingProcessingProjection,
} from '../types/shipping.api.types';
import { resolveConversationProcessingFromUnified } from './conversationProcessingProjection';
import {
buildProcessingSemanticKey,
resolveConversationProcessingFromUnified,
} from './conversationProcessingProjection';
const FOREGROUND_POLL_MS = 2000;
const BACKGROUND_POLL_MS = 8000;
@@ -46,7 +52,14 @@ export type UseShippingNoticeWorkflowReturn = {
processing: Ref<ConversationProcessingProjection | null>;
/** 统一 ShippingProcessing work_items。 */
processingWorkItems: Ref<ShippingProcessingProjection[]>;
/** 兼容旧消费者:任何加载状态均为 true。 */
loading: Ref<boolean>;
/** 首次打开会话加载中(投影仍为空)。 */
initialLoading: Ref<boolean>;
/** 用户主动点击刷新或执行重试/重解析/取消等写操作后加载。 */
manualRefreshing: Ref<boolean>;
/** 后台静默轮询中(不显示 loading,不禁用按钮)。 */
polling: Ref<boolean>;
error: Ref<string | null>;
refresh: () => Promise<void>;
focusConversationTask: (taskNo: string) => Promise<void>;
@@ -67,12 +80,19 @@ function readOption<T>(source: MaybeRefOrGetter<T>): T {
}
/**
* 按页面可见性选择轮询间隔。
* 按页面可见性 + 业务状态选择轮询间隔。
* 分层策略:系统处理中 2s;待人工复核 30s;后台标签页 8s(若仍需轮询)。
*/
function resolvePollMs(): number {
function resolvePollMs(
processing?: ConversationProcessingProjection | null,
): number {
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
return BACKGROUND_POLL_MS;
}
const processingCount = Number(
processing?.summary?.processing || processing?.processing?.length || 0,
);
if (processingCount > 0) return FOREGROUND_POLL_MS;
return FOREGROUND_POLL_MS;
}
@@ -87,14 +107,16 @@ export function resolveProcessingPollBackoffMs(failureCount: number): number {
/**
* 判断是否应继续轮询统一 ShippingProcessing。
* 核心逻辑:processing / needs_action 有活跃项则继续。
* 核心逻辑:仅系统处理中(processing>0)时持续 2s 轮询;
* 待人工复核不触发后台轮询;全部完成/取消/历史时停止轮询。
*/
export function shouldContinueProcessingPolling(
processing?: ConversationProcessingProjection | null,
): boolean {
const processingCount = Number(processing?.summary?.processing || processing?.processing?.length || 0);
const needsActionCount = Number(processing?.summary?.needs_action || processing?.needs_action?.length || 0);
return processingCount > 0 || needsActionCount > 0;
const processingCount = Number(
processing?.summary?.processing || processing?.processing?.length || 0,
);
return processingCount > 0;
}
/**
@@ -109,8 +131,13 @@ export function useShippingNoticeWorkflow(
): UseShippingNoticeWorkflowReturn {
const processing = ref<ConversationProcessingProjection | null>(null);
const processingWorkItems = ref<ShippingProcessingProjection[]>([]);
const loading = ref(false);
const initialLoading = ref(false);
const manualRefreshing = ref(false);
const polling = ref(false);
const error = ref<string | null>(null);
const loading = computed(() => (
initialLoading.value || manualRefreshing.value || polling.value
));
let pollTimer: ReturnType<typeof setTimeout> | null = null;
let pollGeneration = 0;
@@ -119,6 +146,7 @@ export function useShippingNoticeWorkflow(
let inFlightRefresh: { conversationId: string; promise: Promise<void> } | null = null;
let failureCount = 0;
let pollingStopped = false;
let lastSemanticKey = '';
const normalizedConversationId = computed(() =>
String(readOption(options.conversationId) || '').trim(),
@@ -152,12 +180,21 @@ export function useShippingNoticeWorkflow(
/**
* 仅拉取统一 shipping-processing 投影。
* 核心逻辑:work_items 非空时始终由 order_task 合成任务列表;embedded 仅补焦点元数据;
* 同会话在途请求合并;跨会话请求中止,且只有最新一代可回写页面数据。
* 同会话在途请求合并;跨会话请求中止,且只有最新一代可回写页面数据;
* 语义签名相同则不替换 projection 对象,避免 DOM 重建与按钮闪烁。
*
* @param conversationId - 会话 ID
* @param mode - 请求模式:initial=首次加载 / manual=用户主动触发 / poll=后台轮询
* @returns Promise<void>;可恢复网络失败写入 error,不向页面抛出。
*/
async function executeRefresh(conversationId: string): Promise<void> {
async function executeRefresh(
conversationId: string,
mode: 'initial' | 'manual' | 'poll',
): Promise<void> {
const generation = ++requestGeneration;
loading.value = true;
if (mode === 'initial') initialLoading.value = true;
else if (mode === 'manual') manualRefreshing.value = true;
else polling.value = true;
const controller = createRequestController();
try {
// [STEP 1] 统一投影为唯一读源。
@@ -170,8 +207,19 @@ export function useShippingNoticeWorkflow(
const workItems = Array.isArray(unified?.work_items) ? unified.work_items : [];
const embedded = unified?.conversation_processing as ConversationProcessingProjection | null | undefined;
const prevProjection = processing.value;
const nextProjection = resolveConversationProcessingFromUnified(
workItems,
embedded,
prevProjection,
);
const nextSemanticKey = buildProcessingSemanticKey(nextProjection);
processingWorkItems.value = workItems;
processing.value = resolveConversationProcessingFromUnified(workItems, embedded);
if (nextSemanticKey !== lastSemanticKey) {
processing.value = nextProjection;
lastSemanticKey = nextSemanticKey;
}
error.value = null;
failureCount = 0;
} catch (reason) {
@@ -186,12 +234,17 @@ export function useShippingNoticeWorkflow(
: 'network_recoverable';
} finally {
if (requestController === controller) requestController = null;
if (generation === requestGeneration) loading.value = false;
if (generation === requestGeneration) {
if (mode === 'initial') initialLoading.value = false;
else if (mode === 'manual') manualRefreshing.value = false;
else polling.value = false;
}
}
}
/**
* 拉取统一进度;同一会话已有请求时复用该 Promise,避免首屏触发源互相取消重发。
* 拉取统一进度(用户主动刷新模式:显示刷新图标旋转,不轮询)。
* 同一会话已有请求时复用该 Promise,避免首屏触发源互相取消重发。
*/
function refresh(): Promise<void> {
const conversationId = normalizedConversationId.value;
@@ -199,12 +252,15 @@ export function useShippingNoticeWorkflow(
processing.value = null;
processingWorkItems.value = [];
error.value = null;
lastSemanticKey = '';
return Promise.resolve();
}
if (inFlightRefresh?.conversationId === conversationId) {
return inFlightRefresh.promise;
}
const promise = executeRefresh(conversationId).finally(() => {
const isFirstLoad = processing.value === null && !initialLoading.value && !manualRefreshing.value && !polling.value;
const mode: 'initial' | 'manual' = isFirstLoad ? 'initial' : 'manual';
const promise = executeRefresh(conversationId, mode).finally(() => {
if (inFlightRefresh?.promise === promise) inFlightRefresh = null;
});
inFlightRefresh = { conversationId, promise };
@@ -213,7 +269,8 @@ export function useShippingNoticeWorkflow(
/**
* 将 focus/viewed/submit 写路径响应应用到本地 processing 与 work_items。
* 核心逻辑:有 work_items 时用统一合成;否则仅回写 processing 兼容块。
* 核心逻辑:有 work_items 时用统一合成;否则仅回写 processing 兼容块;
* 每次回写后更新语义签名,避免下一轮轮询误判为「无变化」。
*/
function applyMutationProcessingResponse(response: {
processing?: ConversationProcessingProjection | null;
@@ -222,13 +279,25 @@ export function useShippingNoticeWorkflow(
const workItems = Array.isArray(response.work_items) ? response.work_items : [];
if (workItems.length > 0) {
processingWorkItems.value = workItems as typeof processingWorkItems.value;
processing.value = resolveConversationProcessingFromUnified(
const nextProjection = resolveConversationProcessingFromUnified(
workItems as typeof processingWorkItems.value,
response.processing ?? null,
processing.value,
);
const nextKey = buildProcessingSemanticKey(nextProjection);
if (nextKey !== lastSemanticKey) {
processing.value = nextProjection;
lastSemanticKey = nextKey;
}
return;
}
if (response.processing) processing.value = response.processing;
if (response.processing) {
const nextKey = buildProcessingSemanticKey(response.processing);
if (nextKey !== lastSemanticKey) {
processing.value = response.processing;
lastSemanticKey = nextKey;
}
}
}
/**
@@ -257,6 +326,23 @@ export function useShippingNoticeWorkflow(
applyMutationProcessingResponse(response);
}
/**
* 执行后台静默轮询:不设置 manualRefreshing,使用 polling 态。
* 失败时复用 executeRefresh 的 failureCount 统计。
*/
async function runBackgroundPoll(conversationId: string): Promise<void> {
const existing = inFlightRefresh;
if (existing?.conversationId === conversationId) {
await existing.promise;
return;
}
const promise = executeRefresh(conversationId, 'poll').finally(() => {
if (inFlightRefresh?.promise === promise) inFlightRefresh = null;
});
inFlightRefresh = { conversationId, promise };
await promise;
}
/**
* 调度下一次轮询;失败时按退避间隔。
*/
@@ -264,7 +350,10 @@ export function useShippingNoticeWorkflow(
if (pollTimer) clearTimeout(pollTimer);
pollTimer = setTimeout(async () => {
if (generation !== pollGeneration || pollingStopped) return;
await refresh();
const conversationId = normalizedConversationId.value;
if (conversationId) {
await runBackgroundPoll(conversationId);
}
if (generation !== pollGeneration || pollingStopped) return;
if (!normalizedConversationId.value) return;
if (error.value) {
@@ -276,7 +365,7 @@ export function useShippingNoticeWorkflow(
}
const nextDelay = failureCount > 0
? resolveProcessingPollBackoffMs(failureCount)
: resolvePollMs();
: resolvePollMs(processing.value);
schedulePoll(generation, nextDelay);
}, delayMs);
}
@@ -300,7 +389,7 @@ export function useShippingNoticeWorkflow(
return;
}
if (!shouldContinueProcessingPolling(processing.value)) return;
schedulePoll(generation, resolvePollMs());
schedulePoll(generation, resolvePollMs(processing.value));
});
}
@@ -315,6 +404,7 @@ export function useShippingNoticeWorkflow(
processing.value = null;
processingWorkItems.value = [];
error.value = null;
lastSemanticKey = '';
}
restartPolling();
}, { immediate: true });
@@ -344,6 +434,9 @@ export function useShippingNoticeWorkflow(
processing,
processingWorkItems,
loading,
initialLoading,
manualRefreshing,
polling,
error,
refresh,
focusConversationTask,
@@ -2080,6 +2080,11 @@ export interface ShippingOrderReviewCase {
build_eligibility?: ShippingOrderReviewBuildEligibility;
} | null;
available_actions: string[];
/** 对话级可执行动作(与对话处理 GET 同源);仅 retryable 对象计入。 */
conversation_allowed_actions?: Array<{
code: string;
eligible_count: number;
}>;
/** 正式任务 Schema 放行可写字段 field_id;confirmed + edit_formal_task 时由后端投影。 */
formal_editable_field_ids?: string[];
/** 关联 Notice 的 order_data_version;formal patch 乐观锁。 */
@@ -2467,8 +2472,11 @@ export interface ShippingOrderReviewLineFulfillmentLine {
source?: string | null;
} | null;
decision_source?: 'system' | 'user' | 'unknown' | null;
/** @deprecated 使用 inventory_allowed_actions + line_allowed_actions */
/** 行级统一「重试」是否可点;前端禁止用 inventory_allowed_actions 猜按钮。 */
retryable?: boolean;
/** @deprecated 内部诊断保留;UI 不消费 */
allowed_actions?: string[];
/** 内部动作码(诊断/执行);UI 不渲染 */
inventory_allowed_actions?: string[];
line_allowed_actions?: string[];
auto_fulfill_error_message?: string | null;
@@ -1,9 +1,9 @@
/**
* features/chat/views/ShippingOrderReviewView.spec.ts
* 用途:锁定复核工作台布局重构阶段 1 的主结构与模式契约。
* 用途:锁定复核工作台布局与统一重试契约。
* 依赖:vitest、@vue/test-utils、vue-i18n、vue-router mocks。
* 逻辑:标准模式无对话上下文、无常驻 PDF 列;存在主编辑区/摘要侧栏/底栏确认按钮;
* 敏感面板审计失败不打开;确认后推进失败可由 Case 投影刷新恢复。
* 逻辑:标准模式无对话上下文、无常驻 PDF 列;底栏无「确认并创建任务」;
* 正式 OT / STP 对象级重试走 /retry 或 STP retry;敏感面板审计失败不打开。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { computed, ref } from 'vue';
@@ -15,8 +15,9 @@ import { CHAT_PAGE_KEY } from '@/features/chat/composables/chat.context';
import {
auditWorkspaceShippingOrderReviewEligibilityDetails,
auditWorkspaceShippingOrderReviewVersionHistory,
autoProgressWorkspaceShippingTask,
getWorkspaceShippingTask,
retryWorkspaceShippingOrderStpAutoCreate,
retryWorkspaceShippingTask,
} from '@/features/chat/api/shipping.api';
const focusSuggestionField = vi.fn();
@@ -119,12 +120,16 @@ vi.mock('@/features/chat/api/shipping.api', async (importOriginal) => {
...actual,
auditWorkspaceShippingOrderReviewVersionHistory: vi.fn().mockResolvedValue({ audited: true, case_no: 'CASE-1' }),
auditWorkspaceShippingOrderReviewEligibilityDetails: vi.fn().mockResolvedValue({ audited: true, case_no: 'CASE-1' }),
autoProgressWorkspaceShippingTask: vi.fn().mockResolvedValue({ status: 'ok' }),
retryWorkspaceShippingTask: vi.fn().mockResolvedValue({ status: 'ok' }),
retryWorkspaceShippingOrderStpAutoCreate: vi.fn().mockResolvedValue({
status: 'queued',
job_id: 901,
case: null,
}),
getWorkspaceShippingTask: vi.fn().mockResolvedValue({
task_no: 'SN-MOCK',
status: 'created',
}),
};
});
@@ -476,7 +481,6 @@ async function mountView() {
},
llmSuggestion: { request: '请求 AI' },
restoreMachine: '恢复机器值',
buildEligibility: { confirmBlocked: '不可建单' },
saving: '保存中',
saved: '已保存',
saveFailed: '失败',
@@ -502,16 +506,24 @@ async function mountView() {
},
},
autoProgress: {
status: { unknown: '', needs_retry: '待重试' },
status: { unknown: '', needs_retry: '待重试', needs_human: '需要人工处理' },
result: '{status}',
checkpoint: '{checkpoint}',
viewTask: '返回对话查看进度',
returnToChat: '返回对话查看进度',
retry: '重试自动推进',
retryObject: '重试',
retrySuccess: '已重新触发',
retryStp: '重试自动推进',
retryStpSuccess: '已重新入队自动建单',
},
conversationRetry: {
title: '对话重试结果',
retried: '已重试',
skipped: '已跳过',
failed: '失败',
closeAndRefresh: '关闭并刷新',
},
currentProcessing: {
title: '当前处理状态',
status: '状态',
@@ -536,6 +548,24 @@ async function mountView() {
waitingPreOt: '等待自动建单',
waitingPostOt: '等待系统启动自动推进',
},
buildEligibility: {
confirmBlocked: '不可建单',
autoGateWaitingHint: '资格已达标,等待系统自动建单',
autoGateRunningHint: '系统正在自动推进',
},
fulfillmentDecision: {
actions: '操作',
availableQty: '可用',
shortage: '缺口',
},
lineOps: {
retry: '重试',
moreActions: '更多操作',
inventorySource: '库存源',
},
workflowProgress: {
automatingFooterHint: '系统自动推进中',
},
confirmSuccess: '{taskNo}',
confirmAutoProgress: '{taskNo}',
confirmProgressFailed: '已创建任务 {taskNo},但自动推进失败,请重试推进',
@@ -679,10 +709,11 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.find('[data-testid="review-document-evidence-drawer"]').exists()).toBe(false);
});
it('keeps confirm footer visible when draft exists', async () => {
it('keeps footer actions without confirm-create when draft exists', async () => {
const wrapper = await mountView();
// 关键断言:底栏仍在,但正常路径不再暴露「确认并创建任务」。
expect(wrapper.find('[data-testid="review-footer-actions"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(false);
});
it('renders empty optional schema fields as editable line columns', async () => {
@@ -802,11 +833,21 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
expect(messageMocks.warning).toHaveBeenCalledWith('审计记录失败,敏感面板未打开,请重试');
});
it('restores amber retry banner from post_confirm_auto_progress after reload', async () => {
it('restores object-level retry from post_confirm_auto_progress after reload', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed',
has_formal_ot: true,
task_missing: false,
confirmed_task_id: 7,
confirmed_task_no: 'SN-RECOVER-1',
automation: {
status: 'failed',
retryable: true,
phase: 'post_ot_progress',
can_auto_create: false,
can_build: true,
},
post_confirm_auto_progress: {
task_no: 'SN-RECOVER-1',
needs_retry: true,
@@ -816,17 +857,16 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
};
const wrapper = await mountView();
await flushPromises();
const banner = wrapper.find('[data-testid="review-confirm-outcome"]');
// 关键断言:页面重载后仍能从 Case 投影恢复推进失败重试入口。
expect(banner.exists()).toBe(true);
expect(banner.attributes('data-progress-failed')).toBe('true');
expect(wrapper.find('[data-testid="retry-auto-progress-after-confirm"]').exists()).toBe(true);
expect(banner.text()).toContain('SN-RECOVER-1');
});
// 关键断言:琥珀色确认条已移除;刷新后对象级重试挂在当前处理卡。
expect(wrapper.find('[data-testid="review-confirm-outcome"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="retry-auto-progress-after-confirm"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-current-processing-ot"]').text()).toContain('SN-RECOVER-1');
}, 15000);
it('retries formal OT auto-progress from main card after refresh without confirmSuccess (UI-01)', async () => {
// 关键断言:刷新后无 confirmSuccess 时,主卡仍用 confirmed_task_no 调 auto-progress API。
vi.mocked(autoProgressWorkspaceShippingTask).mockClear();
it('retries formal OT via unified /retry from main card after refresh without confirmSuccess (UI-01)', async () => {
// 关键断言:刷新后无 confirmSuccess 时,主卡仍用 confirmed_task_no 调统一 /retry(禁止 auto-progress)。
vi.mocked(retryWorkspaceShippingTask).mockClear();
activeCase.value = {
...activeCase.value,
status: 'confirmed',
@@ -854,8 +894,8 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
expect(retryBtn.exists()).toBe(true);
await retryBtn.trigger('click');
await flushPromises();
expect(autoProgressWorkspaceShippingTask).toHaveBeenCalledWith('SN-OT-FAIL-1');
});
expect(retryWorkspaceShippingTask).toHaveBeenCalledWith('SN-OT-FAIL-1');
}, 15000);
it('keeps top / wide / narrow stage labels identical via Progress projection (waiting_system_start)', async () => {
// 关键断言:Case.current_stage 故意降级为误导码;三处必须消费 Progress label_key 文案。
@@ -928,7 +968,7 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
...activeCase.value,
status: 'ready',
confirmed_task_no: null,
available_actions: ['validate', 'confirm', 'retry_stp_auto_create'],
available_actions: ['validate', 'retry_stp_auto_create'],
automation: {
status: 'failed',
retryable: true,
@@ -939,20 +979,21 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
};
const wrapper = await mountView();
await flushPromises();
const btn = wrapper.find('[data-testid="review-retry-stp-auto-create"]');
// 关键断言:failed 态必须露出 STP 重试入口(非确认后 auto_progress 重试)。
expect(btn.exists()).toBe(true);
await btn.trigger('click');
// 关键断言:failed 态主卡/底栏露出 STP 重试(非确认后 auto_progress)。
const railBtn = wrapper.find('[data-testid="review-current-processing-retry"]');
const footerBtn = wrapper.find('[data-testid="review-retry-stp-auto-create"]');
expect(railBtn.exists() || footerBtn.exists()).toBe(true);
await (railBtn.exists() ? railBtn : footerBtn).trigger('click');
await flushPromises();
expect(retryWorkspaceShippingOrderStpAutoCreate).toHaveBeenCalledWith('CASE-1');
});
}, 15000);
it('shows STP retry for manual_fallback while keeping confirm fallback (UI-02)', async () => {
it('shows STP retry for manual_fallback without confirm-create (UI-02)', async () => {
activeCase.value = {
...activeCase.value,
status: 'ready',
confirmed_task_no: null,
available_actions: ['validate', 'confirm', 'retry_stp_auto_create'],
available_actions: ['validate', 'retry_stp_auto_create'],
automation: {
status: 'manual_fallback',
retryable: true,
@@ -963,9 +1004,13 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
};
const wrapper = await mountView();
await flushPromises();
expect(wrapper.find('[data-testid="review-retry-stp-auto-create"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(true);
});
expect(
wrapper.find('[data-testid="review-current-processing-retry"]').exists()
|| wrapper.find('[data-testid="review-retry-stp-auto-create"]').exists(),
).toBe(true);
// 关键断言:正常路径不再保留「确认并创建任务」兜底。
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(false);
}, 15000);
it('hides profile match panel when profile_match.available is false', async () => {
activeCase.value = {
@@ -994,31 +1039,35 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
expect(wrapper.find('[data-testid="review-profile-match-panel"]').exists()).toBe(true);
});
it('treats HTTP/confirm_ok success with confirm_outcome failed as progress failure', async () => {
confirmMock.mockResolvedValueOnce({
task_no: 'SN-CONFIRM-PROGRESS-FAIL',
confirm_ok: true,
confirm_outcome: 'confirmed_auto_progress_failed',
auto_progress_started: false,
auto_progress: {
status: 'enqueue_failed',
message: '入队失败',
checkpoint: 'created',
it('hydrates progress-failed retry state from Case projection without confirm UI', async () => {
// 关键断言:无确认建单按钮时,仍可从 post_confirm_auto_progress 恢复对象级重试入口。
activeCase.value = {
...activeCase.value,
status: 'confirmed',
has_formal_ot: true,
task_missing: false,
confirmed_task_id: 55,
confirmed_task_no: 'SN-CONFIRM-PROGRESS-FAIL',
automation: {
status: 'failed',
retryable: true,
phase: 'post_ot_progress',
can_auto_create: false,
can_build: true,
},
case: activeCase.value,
});
post_confirm_auto_progress: {
task_no: 'SN-CONFIRM-PROGRESS-FAIL',
needs_retry: true,
status: 'needs_retry',
message: '入队失败',
},
};
const wrapper = await mountView();
await wrapper.find('[data-testid="review-confirm-create"]').trigger('click');
await flushPromises();
await wrapper.find('[data-testid="review-action-confirm-submit"]').trigger('click');
await flushPromises();
const banner = wrapper.find('[data-testid="review-confirm-outcome"]');
// 关键断言:不得仅凭 success/confirm_ok 判定推进成功;须读 confirm_outcome。
expect(confirmMock).toHaveBeenCalled();
expect(banner.exists()).toBe(true);
expect(banner.attributes('data-progress-failed')).toBe('true');
expect(messageMocks.warning).toHaveBeenCalled();
});
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-current-processing-ot"]').text()).toContain('SN-CONFIRM-PROGRESS-FAIL');
}, 15000);
});
describe('ShippingOrderReviewView viewport layout remediation', () => {
@@ -9,9 +9,11 @@
ReviewCurrentProcessingCard、ReviewCompletedChecksPanel、ReviewFieldCompletenessPanel、
ReviewAutomationStatusPanel、ReviewBuildEligibilitySummary、ReviewInventory*、
ReviewLineInventoryOps(履约操作并入明细右侧列)、ReviewLineFulfillmentDetail(行内履约摘要)、
ProcessGateRecoveryCard;formal_task 仅显式动作挂载 TaskTodoPanel(主写在 Footer)。
ProcessGateRecoveryCard;formal_task 仅显式动作挂载 TaskTodoPanel(主写在 Footer);
shipping.api.retryWorkspaceConversationAutoProgress(对话级重试)。
逻辑:建单前订单检查为主卡;正式 OT 后保持 standard,不自动切 formal_task 空壳;
不挂当前处理/履约摘要重复卡;库存动作仅明细行浮层;写操作仅底栏。
对话级「重试自动推进」在顶栏;当前 Case 对象级重试优先右栏 CurrentProcessingCard,
仅当未挂载该卡时回落到底栏;库存动作仅明细行浮层;写操作仅底栏。
-->
<script setup lang="ts">
import { computed, defineAsyncComponent, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
@@ -28,16 +30,16 @@ import {
import {
auditWorkspaceShippingOrderReviewEligibilityDetails,
auditWorkspaceShippingOrderReviewVersionHistory,
autoProgressWorkspaceShippingTask,
attemptWorkspaceShippingOrderReviewFieldLocate,
decideWorkspaceShippingOrderReviewLineFulfillment,
getWorkspaceShippingOrderReviewEvidenceItem,
getWorkspaceShippingTask,
retryWorkspaceConversationAutoProgress,
retryWorkspaceShippingOrderStpAutoCreate,
retryWorkspaceShippingTask,
retryWorkspaceShippingTaskLine,
viewWorkspaceShippingOrderReviewHighlightDiagnostic,
} from '../api/shipping.api';
import type {
ShippingOrderReviewLineFulfillmentDecisionCode,
ShippingOrderReviewLineFulfillmentLine,
} from '../types/shipping.api.types';
import ReviewActionConfirmDialog, {
@@ -71,7 +73,6 @@ import ReviewWorkbenchHeader from '../components/shipping-review/ReviewWorkbench
import ReviewWorkbenchModeToggle from '../components/shipping-review/ReviewWorkbenchModeToggle.vue';
import ReviewUnsavedSwitchDialog from '../components/shipping-review/ReviewUnsavedSwitchDialog.vue';
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
import { postWorkspaceProcessGateAction } from '@/features/shipping-process-gates/api/process-gates.api';
import TaskTodoPanel from '@/features/workspace/shipping-task-center/TaskTodoPanel.vue';
import { downloadWorkspaceShippingExcelFile } from '@/features/workspace/api/shipping-tasks.api';
import ReviewLineNoOverrideDialog, {
@@ -312,6 +313,42 @@ const evidenceFocusConsumed = ref(false);
return Boolean(automation?.retryable) || (activeCase.value?.available_actions || []).includes('retry_stp_auto_create');
});
/**
* 对话级重试动作:后端 conversation_allowed_actions 中 retry_auto_progress 且 eligible_count>0。
*/
const conversationRetryAction = computed(() => {
const actions = activeCase.value?.conversation_allowed_actions || [];
return actions.find((item) => (
item.code === 'retry_auto_progress' && Number(item.eligible_count || 0) > 0
)) || null;
});
/** 顶栏是否展示对话级「重试自动推进」。 */
const showConversationRetry = computed(() => (
Boolean(conversationRetryAction.value) && Boolean(String(conversationId.value || '').trim())
));
/** 对话级可重试对象数量(徽标)。 */
const conversationRetryEligibleCount = computed(() => (
Number(conversationRetryAction.value?.eligible_count || 0)
));
/**
* 是否挂载右侧/窄屏「当前处理」卡:task_missing、正式 OT、或自动化进行中/失败态。
* 核心逻辑:对象级重试优先挂在此卡上,未挂载时才回落底栏。
*/
const mountCurrentProcessingCard = computed(() => {
if (!activeCase.value) return false;
if (Boolean(activeCase.value.task_missing)) return true;
if (hasFormalOt.value) return true;
const status = String(activeCase.value.automation?.status || '').trim().toLowerCase();
return ['waiting_to_start', 'queued', 'running', 'failed', 'manual_fallback'].includes(status);
});
/** 对象级重试:有当前处理卡时放右栏/窄屏主卡;否则回落底栏。 */
const showObjectRetryOnRail = computed(() => showStpRetry.value && mountCurrentProcessingCard.value);
const showObjectRetryOnFooter = computed(() => showStpRetry.value && !mountCurrentProcessingCard.value);
/**
* 正式 OT 后履约/库存卡片是否展开:仅 human + 可执行 blocking 时展开对应卡;
* 系统等待/排队/运行默认折叠。
@@ -435,10 +472,23 @@ const confirmSuccess = ref<{
restoredFromProjection?: boolean;
} | null>(null);
const progressRetrying = ref(false);
const conversationRetrying = ref(false);
const conversationRetryResultOpen = ref(false);
const conversationRetryResult = ref<{
summary: { total: number; retried: number; skipped: number; failed: number };
items: Array<{
object_type: string;
object_ref: string;
action?: string | null;
outcome: string;
reason_code?: string | null;
}>;
} | null>(null);
/**
* 从 Case 投影恢复「已建单但仍待推进」琥珀色重试条(覆盖页面刷新场景)。
* 核心逻辑:仅当 post_confirm_auto_progress.needs_retry 时写入;不覆盖同会话即时 confirm 结果。
* 注:确认成功琥珀色 UI 已移除(避免与对话级/对象级重试重复);本 hydrate 仍供内部状态与流程动作使用。
*/
function hydrateConfirmProgressFromCase() {
const caseRow = activeCase.value;
@@ -924,16 +974,6 @@ const openAuditTrail = () => {
auditTrailOpen.value = true;
};
/**
* 切换行内履约摘要:只展开当前行,不进入库存工作台。
* @param lineKey - 明细行键
*/
function toggleFulfillmentDetail(lineKey: string) {
const key = String(lineKey || '').trim();
if (!key) return;
fulfillmentDetailLineKey.value = fulfillmentDetailLineKey.value === key ? null : key;
}
/**
* 收起行内履约摘要。
*/
@@ -1001,73 +1041,6 @@ function displayShortageQty(line: ShippingOrderReviewLineFulfillmentLine | null)
return String(line.shortage_qty);
}
/**
* 归一化用户态状态码(与文案/badge 共用)。
*/
function resolveUserLineStatusCode(line: ShippingOrderReviewLineFulfillmentLine | null): string {
if (!line) return '';
const inventoryPending = (
line.display_available === 'pending'
|| ['preparing', 'mapping_failed', 'source_conflict', 'unavailable', 'invalid_key'].includes(
String(line.inventory_status || ''),
)
);
let code = String(line.user_line_status || '').trim();
if (inventoryPending && (!code || code === 'pending_decision')) {
code = 'inventory_pending';
} else if (!code) {
code = String(line.line_status || '').trim();
}
return code;
}
/**
* 用户态履约/库存状态文案(优先 user_line_status;库存未就绪时不展示「待决定」)。
* 核心逻辑:display_available=pending 或 preparing/conflict 等 → inventory_pending;
* 仅在库存数字已就绪后才信任 pending_decision / line_status。
*/
function userLineStatusLabel(line: ShippingOrderReviewLineFulfillmentLine | null): string {
const code = resolveUserLineStatusCode(line);
if (!code) return '—';
const key = `chat.shippingOrderReview.fulfillmentDecision.userLineStatus.${code}`;
if (te(key)) return t(key);
const legacy = `chat.shippingOrderReview.fulfillmentDecision.lineStatus.${code}`;
return te(legacy) ? t(legacy) : code;
}
/**
* 状态列 badge 视觉层级(UI-4):短缺/失败强调,进度次之,终态弱化。
*/
function userLineStatusBadgeClass(line: ShippingOrderReviewLineFulfillmentLine | null): string {
const code = resolveUserLineStatusCode(line);
const base = 'inline-flex max-w-full items-center rounded-md px-1.5 py-0.5 text-[11px] font-medium leading-tight';
switch (code) {
case 'shortage':
case 'auto_fulfill_failed':
case 'inventory_file_expired':
return `${base} bg-rose-100 text-rose-800 dark:bg-rose-950/60 dark:text-rose-200`;
case 'source_conflict':
case 'invalid':
case 'inventory_source_unrecognized':
case 'inventory_file_missing':
case 'inventory_match_failed':
return `${base} bg-amber-100 text-amber-900 dark:bg-amber-950/50 dark:text-amber-100`;
case 'inventory_pending':
case 'acquiring_inventory':
case 'auto_fulfilling':
return `${base} bg-sky-100 text-sky-900 dark:bg-sky-950/50 dark:text-sky-100`;
case 'wave_created':
case 'ready_to_fulfill':
case 'inventory_matched':
return `${base} bg-emerald-100 text-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-100`;
case 'fulfilled':
case 'closed':
return `${base} bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300`;
default:
return `${base} bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-200`;
}
}
/**
* 只读库存源展示(后端 inventory_source;禁止前端推断)。
*/
@@ -1084,6 +1057,15 @@ function displayInventorySource(line: ShippingOrderReviewLineFulfillmentLine | n
if (label && code) return `${label}(${code})`;
if (label) return label;
if (code) return code;
// 建单后最终行级库存源尚未匹配时,展示建单前已冻结的候选集合,
// 避免把“已识别候选”误显示为空;最终 source 仍只由后端履约投影提供。
const candidate = (buildEligibility.value?.line_projections || []).find(
(item) => String(item.line_key || '') === String(line.line_key || ''),
);
const candidates = (candidate?.candidate_inventory_source_codes || [])
.map((item) => String(item || '').trim())
.filter(Boolean);
if (candidates.length) return candidates.join(', ');
return '—';
}
@@ -1100,27 +1082,44 @@ function displayAvailableQty(line: ShippingOrderReviewLineFulfillmentLine | null
const lineOpsBusyKey = ref<string | null>(null);
/** 库存文件缺失/过期或库存匹配失败时,复用当前 Process Gate 的 RPA 重试动作。 */
async function retryLineInventoryRpa(lineKey: string, actionCode: string) {
const gate = activeCase.value?.process_gate;
const executionNo = String(gate?.execution_no || '').trim();
const blockingGate = gate?.current_blocking_gate;
const gateCode = String(blockingGate?.gate_code || '').trim();
const expectedVersion = Number(blockingGate?.evaluation_version || 0);
if (!executionNo || !gateCode || !actionCode || !Number.isFinite(expectedVersion) || expectedVersion < 1) {
/** 任务整体 queued/running:行级写操作隐藏/禁用。 */
const taskAutomationRunning = computed(() => {
const status = String(activeCase.value?.automation?.status || '').trim().toLowerCase();
return ['queued', 'running', 'processing', 'automating'].includes(status);
});
/**
* 明细行统一「重试」:POST .../lines/{line_key}/retry;不传内部动作码。
*/
async function retryLineUnified(lineKey: string) {
const key = String(lineKey || '').trim();
if (!key || taskAutomationRunning.value || caseSwitchLoading.value) {
msg.warning(t('chat.shippingOrderReview.lineOps.retryRpaUnavailable'));
return;
}
lineOpsBusyKey.value = lineKey;
const taskNo = String(
confirmedNoticeTaskNo.value
|| activeCase.value?.confirmed_task_no
|| formalOtRetryTaskNo.value
|| '',
).trim();
if (!taskNo) {
msg.warning(t('chat.shippingOrderReview.lineOps.retryRpaUnavailable'));
return;
}
lineOpsBusyKey.value = key;
try {
await postWorkspaceProcessGateAction(executionNo, gateCode, {
action_code: actionCode,
expected_gate_version: expectedVersion,
idempotency_key: crypto.randomUUID(),
payload: { line_key: lineKey },
});
msg.success(t('chat.shippingOrderReview.lineOps.retryRpaSubmitted'));
const result = await retryWorkspaceShippingTaskLine(taskNo, key);
const status = String(result?.status || '').trim().toLowerCase();
if (status === 'needs_human') {
msg.warning(String(result?.message || t('chat.shippingOrderReview.autoProgress.status.needs_human')));
} else if (status === 'failed') {
msg.warning(String(result?.message || t('chat.shippingOrderReview.lineOps.retryRpaFailed')));
} else {
msg.success(t('chat.shippingOrderReview.lineOps.retryRpaSubmitted'));
}
await reloadLatestDraft();
void refreshShippingProcessing();
} catch (error) {
msg.error(
error instanceof BusinessError
@@ -1133,40 +1132,10 @@ async function retryLineInventoryRpa(lineKey: string, actionCode: string) {
}
/**
* 行内履约决定(等待/关闭);换源只导航。
* Case 级库存兜底卡「重试」:走任务级统一决策器(无行键时)。
*/
async function onLineFulfillmentDecide(
lineKey: string,
code: ShippingOrderReviewLineFulfillmentDecisionCode,
) {
if (code === 'close_unfulfillable') {
openCloseFulfillmentDialog([lineKey]);
return;
}
// 更换库存源已取消:客户指定源不可覆盖,不再导航库存工作台。
if (code === 'change_inventory_source') {
return;
}
const caseNo = String(activeCase.value?.case_no || '').trim();
if (!caseNo || lineOpsBusyKey.value) return;
lineOpsBusyKey.value = lineKey;
try {
await decideWorkspaceShippingOrderReviewLineFulfillment(caseNo, {
line_key: lineKey,
decision_code: code,
expected_draft_version: activeCase.value?.draft?.draft_version ?? undefined,
});
msg.success(t('chat.shippingOrderReview.fulfillmentDecision.decideSuccess'));
await reloadLatestDraft();
} catch (error) {
msg.error(
error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: t('chat.shippingOrderReview.fulfillmentDecision.decideFailed'),
);
} finally {
lineOpsBusyKey.value = null;
}
async function retryCaseInventoryFallback() {
await retryFormalOtAutoProgress();
}
/**
@@ -1324,8 +1293,8 @@ const canEnterInventory = computed(() => {
});
const availableActions = computed(() => activeCase.value?.available_actions || []);
/** 订单处理工作台写权限(只读查看为 false)。 */
const workbenchActionsExecutable = computed(() => !isReadOnly.value);
/** 订单处理工作台写权限(只读查看 / Case 切换中为 false)。 */
const workbenchActionsExecutable = computed(() => !isReadOnly.value && !caseSwitchLoading.value);
/** 当前 Case 面板可用性,供注册表 requiresPanel 守卫。 */
const workbenchPanelAvailability = computed((): WorkbenchPanelAvailability => {
@@ -1566,7 +1535,7 @@ const linesTableMinWidthClass = computed(() => {
const linesTableColumnCount = computed(() => {
let count = 1 + visibleLineSchemaFields.value.length + 1; // # + schema + ops
if (!showLineInventoryColumns.value) return count;
count += 2; // inventory source + status
count += 1; // inventory source only(available/shortage 已由 qty 字段计入)
if (hasVisibleQtyField.value) {
count += visibleLineSchemaFields.value.filter((field) => isQtySchemaField(field)).length * 2;
} else {
@@ -1798,46 +1767,13 @@ const actionDialogOpen = ref(false);
const lineNoOverrideOpen = ref(false);
const pendingLineNoEdit = ref<{ lineKey: string; fieldId: string; value: string } | null>(null);
/** 将自动推进结果映射为本地化状态;服务端 message 继续作为具体停留原因。 */
const autoProgressStatusLabel = (status: string) => {
const normalized = String(status || '').trim();
const key = `chat.shippingOrderReview.autoProgress.status.${normalized}`;
return normalized && te(key) ? t(key) : t('chat.shippingOrderReview.autoProgress.status.unknown');
};
/**
* 确认后主路径留在复核页:统一动作栏驱动重试/刷新/任务台;返回对话仅作次要链接。
*/
const openTaskProgress = (orderTaskNo: string, noticeNo?: string) => {
const focusNo = String(orderTaskNo || '').trim();
const notice = String(noticeNo || '').trim();
// [UI-01] 无 OT 时禁止用 Notice 编号冒充 focus_task_no。
if (!focusNo) return;
const activeConversationId = String(route.query.conversation_id || conversationId.value || '').trim();
const bannerNo = focusNo || notice;
// [STEP] toast + focus_task_no=OT;禁止用 SN Notice 编号选中进度卡。
msg.success(t('chat.shippingOrderReview.autoProgress.returnedFocusHint', { taskNo: bannerNo }));
void router.replace({
name: 'Chat',
params: { agentId: agentId.value },
query: {
conversation_id: activeConversationId || undefined,
focus_task_no: focusNo || undefined,
focus_notice_no: notice || undefined,
focus_run_no: String(runNo.value || '').trim() || undefined,
focus_notice: '1',
},
});
};
/**
* 正式 OT auto-progress 共用重试:POST /shipping-tasks/<taskNo>/auto-progress。
* 核心逻辑:taskNo 来自参数 / confirmed_task_no / post_confirm;不依赖即时 confirmSuccess;
* task_missing 或无 task_no 时不请求。
* @param preferredTaskNo - 即时确认条可传入 outcome.taskNo
* 正式 OT 用户侧重试:POST /shipping-tasks/<taskNo>/retry(统一决策器)。
* 核心逻辑:禁止再调 auto-progress;task_missing 或无 task_no 时不请求。
* @param preferredTaskNo - 可选任务号覆盖
*/
const retryFormalOtAutoProgress = async (preferredTaskNo?: string | null) => {
if (Boolean(activeCase.value?.task_missing) || progressRetrying.value) return;
if (Boolean(activeCase.value?.task_missing) || progressRetrying.value || caseSwitchLoading.value) return;
const taskNo = String(
preferredTaskNo
|| formalOtRetryTaskNo.value
@@ -1847,7 +1783,7 @@ const retryFormalOtAutoProgress = async (preferredTaskNo?: string | null) => {
if (!taskNo) return;
progressRetrying.value = true;
try {
const result = await autoProgressWorkspaceShippingTask(taskNo);
const result = await retryWorkspaceShippingTask(taskNo);
const status = String(result?.status || 'ok');
const progressFailed = ['failed', 'enqueue_failed', 'sync_execution_failed'].includes(status);
if (confirmSuccess.value?.taskNo === taskNo || confirmSuccess.value) {
@@ -1866,6 +1802,8 @@ const retryFormalOtAutoProgress = async (preferredTaskNo?: string | null) => {
}
if (progressFailed) {
msg.warning(t('chat.shippingOrderReview.confirmProgressFailed', { taskNo }));
} else if (status === 'needs_human') {
msg.warning(String(result?.message || t('chat.shippingOrderReview.autoProgress.status.needs_human')));
} else {
msg.success(t('chat.shippingOrderReview.autoProgress.retrySuccess'));
}
@@ -1879,16 +1817,7 @@ const retryFormalOtAutoProgress = async (preferredTaskNo?: string | null) => {
};
/**
* 即时确认条重试:保留原入口,内部委托共用封装。
*/
const retryAutoProgressAfterConfirm = async () => {
const outcome = confirmSuccess.value;
if (!outcome?.taskNo || progressRetrying.value) return;
await retryFormalOtAutoProgress(outcome.taskNo);
};
/**
* 底栏「重试自动推进」:正式 OT 走 auto-progress;建单前走 STP retry。
* 底栏对象级「重试」兜底:正式 OT 走统一 /retry;建单前走 STP。
*/
const onFooterRetryAutomation = async () => {
if (hasFormalOt.value) {
@@ -1904,7 +1833,7 @@ const onFooterRetryAutomation = async () => {
*/
const retryStpAutoCreate = async () => {
const caseNo = String(activeCase.value?.case_no || '').trim();
if (!caseNo || progressRetrying.value) return;
if (!caseNo || progressRetrying.value || caseSwitchLoading.value) return;
progressRetrying.value = true;
try {
const result = await retryWorkspaceShippingOrderStpAutoCreate(caseNo);
@@ -1921,6 +1850,52 @@ const retryStpAutoCreate = async () => {
}
};
/**
* 对话级「重试自动推进」:扫描会话下可恢复 Case/正式 OT。
* 核心逻辑:调用 retryWorkspaceConversationAutoProgress;打开结果弹窗;刷新草稿与处理投影。
*/
const retryConversationAutoProgress = async () => {
const id = String(conversationId.value || '').trim();
if (!id || conversationRetrying.value || !showConversationRetry.value) return;
if (caseSwitchLoading.value || progressRetrying.value) return;
conversationRetrying.value = true;
try {
const result = await retryWorkspaceConversationAutoProgress(id);
conversationRetryResult.value = {
summary: result.summary,
items: result.items || [],
};
conversationRetryResultOpen.value = true;
await reloadLatestDraft();
await refreshShippingProcessing();
} catch (error) {
msg.error(resolveReviewErrorMessage(error));
} finally {
conversationRetrying.value = false;
}
};
/**
* 「关闭并刷新」:关闭对话级重试结果弹窗并重新拉取工作台投影。
*/
const closeConversationRetryResult = async () => {
conversationRetryResultOpen.value = false;
conversationRetryResult.value = null;
await reloadLatestDraft();
await refreshShippingProcessing();
};
/**
* 对话级重试跳过原因文案:优先 i18n reason.*,否则回退原始 reason_code。
* @param reasonCode - 后端 reason_code
*/
const conversationRetrySkipReasonLabel = (reasonCode?: string | null) => {
const code = String(reasonCode || '').trim();
if (!code) return '';
const key = `chat.shippingOrderReview.conversationRetry.reason.${code}`;
return te(key) ? t(key) : code;
};
/**
* 滚动到工作台锚点(data-testid)。
*/
@@ -2109,7 +2084,7 @@ const onUnifiedProcessingAction = async (item: ActionPresentationItem) => {
}
if (behavior === 'retry') {
await retryAutoProgressAfterConfirm();
await retryFormalOtAutoProgress();
await refreshShippingProcessing();
return;
}
@@ -2626,9 +2601,14 @@ watch(
:is-read-only="isReadOnly"
:show-version-history="Boolean(activeCase)"
:show-audit-trail="Boolean(activeCase)"
:show-conversation-retry="showConversationRetry"
:conversation-retry-eligible-count="conversationRetryEligibleCount"
:conversation-retrying="conversationRetrying"
:conversation-retry-disabled="caseSwitchLoading || progressRetrying"
@back="back"
@open-version-history="openVersionHistory"
@open-audit-trail="openAuditTrail"
@retry-conversation-auto-progress="() => void retryConversationAutoProgress()"
/>
<div
@@ -2707,63 +2687,6 @@ watch(
</p>
</div>
<div
v-if="confirmSuccess"
class="mx-4 mt-3 rounded-xl px-3 py-2 text-sm"
:class="confirmSuccess.progressFailed
? 'border border-amber-300 bg-amber-50 text-amber-950 dark:border-amber-800 dark:bg-amber-950/50 dark:text-amber-100'
: 'border border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-100'"
data-testid="review-confirm-outcome"
:data-progress-failed="confirmSuccess.progressFailed ? 'true' : 'false'"
>
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<p>
{{ confirmSuccess.progressFailed
? t('chat.shippingOrderReview.confirmProgressFailed', { taskNo: confirmSuccess.taskNo })
: confirmSuccess.autoProgress
? t('chat.shippingOrderReview.confirmAutoProgress', { taskNo: confirmSuccess.taskNo })
: t('chat.shippingOrderReview.confirmSuccess', { taskNo: confirmSuccess.taskNo }) }}
</p>
<p v-if="confirmSuccess.progressStatus" class="mt-1 text-xs">
{{ t('chat.shippingOrderReview.autoProgress.result', { status: autoProgressStatusLabel(confirmSuccess.progressStatus) }) }}
</p>
<p v-if="confirmSuccess.progressMessage" class="mt-1 text-xs">{{ confirmSuccess.progressMessage }}</p>
<p v-if="confirmSuccess.checkpoint" class="mt-1 text-xs text-amber-800 dark:text-amber-200">
{{ t('chat.shippingOrderReview.autoProgress.checkpoint', { checkpoint: confirmSuccess.checkpoint }) }}
</p>
<p
v-if="shippingProcessingSummaryLabel"
class="mt-1 text-xs"
data-testid="review-shipping-processing-summary"
>
{{ shippingProcessingSummaryLabel }}
</p>
</div>
<div class="flex shrink-0 flex-wrap items-center gap-2">
<button
v-if="confirmSuccess.progressFailed"
type="button"
class="inline-flex items-center gap-1 rounded border border-amber-500 bg-amber-100/80 px-2.5 py-1.5 text-xs font-medium hover:bg-amber-100 disabled:opacity-50 dark:bg-amber-900/40 dark:hover:bg-amber-900"
:disabled="progressRetrying"
data-testid="retry-auto-progress-after-confirm"
@click="retryAutoProgressAfterConfirm"
>
<RefreshCw class="h-3.5 w-3.5" />{{ t('chat.shippingOrderReview.autoProgress.retry') }}
</button>
<button
v-if="confirmSuccess.orderTaskNo"
type="button"
class="text-xs font-medium text-emerald-800 underline hover:text-emerald-950 dark:text-emerald-200 dark:hover:text-emerald-50"
data-testid="open-confirmed-task-progress-link"
@click="openTaskProgress(confirmSuccess.orderTaskNo, confirmSuccess.taskNo)"
>
{{ t('chat.shippingOrderReview.autoProgress.returnToChat') }}
</button>
</div>
</div>
</div>
<!-- 确认后统一进度主路径留在本页;返回对话仅作次要聚焦链接。 -->
<div v-if="loading" class="p-8 text-sm text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.loading') }}</div>
@@ -3037,13 +2960,13 @@ watch(
@set-mode="onWorkbenchModeChange"
/>
<!-- 窄屏:仅展示真正阻断卡;正式 OT 后不挂当前处理/履约摘要重复卡 -->
<!-- 窄屏:阻断卡 + 当前处理卡(对象级重试优先于此) -->
<div
class="space-y-2 xl:hidden"
data-testid="review-primary-blockers-narrow"
>
<ReviewCurrentProcessingCard
v-if="!hasFormalOt && activeCase?.task_missing"
v-if="mountCurrentProcessingCard"
:stage-code="currentProcessingStageDisplay.code"
:stage-label-key="currentProcessingStageDisplay.labelKey"
:stage-inconsistent="currentProcessingStageDisplay.inconsistent"
@@ -3052,15 +2975,15 @@ watch(
:confirmed-task-id="activeCase?.confirmed_task_id"
:show-admin-diagnosis="showAdminTaskMissingDiagnosis"
:automation="activeCase?.automation"
:show-retry="false"
:retrying="progressRetrying"
@retry="() => void retryFormalOtAutoProgress()"
:show-retry="showObjectRetryOnRail"
:retrying="progressRetrying || caseSwitchLoading"
@retry="() => void (hasFormalOt ? retryFormalOtAutoProgress() : retryStpAutoCreate())"
/>
<ReviewInventoryIssueFallbackCard
v-if="hasFormalOt && activeCase?.inventory_issue_fallback && !activeCase?.line_fulfillment?.has_line_inventory_projection"
:fallback="activeCase.inventory_issue_fallback"
:busy="Boolean(lineOpsBusyKey)"
@retry-preparation="() => void retryLineInventoryRpa('case', 'retry_inventory_preparation')"
@retry-preparation="() => void retryCaseInventoryFallback()"
/>
<ProcessGateRecoveryCard
v-if="!reparseProgressActive && showHumanBlockingGate && activeCase?.process_gate"
@@ -3337,12 +3260,6 @@ watch(
{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}
</th>
</template>
<th
v-if="showLineInventoryColumns"
class="min-w-24 border-b border-slate-200 px-2 py-1.5 font-medium dark:border-slate-800"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.status') }}
</th>
<th class="sticky right-0 z-10 min-w-28 border-b border-slate-200 bg-slate-50 px-2 py-1.5 dark:border-slate-800 dark:bg-slate-950">
<span class="sr-only">{{ t('chat.shippingOrderReview.fulfillmentDecision.actions') }}</span>
</th>
@@ -3484,14 +3401,6 @@ watch(
{{ displayShortageQty(lineFulfillmentFor(String(line.line_key || ''))) }}
</td>
</template>
<td v-if="showLineInventoryColumns" class="px-2 py-1.5 align-middle">
<span
:class="userLineStatusBadgeClass(lineFulfillmentFor(String(line.line_key || '')))"
data-testid="review-line-status-badge"
>
{{ userLineStatusLabel(lineFulfillmentFor(String(line.line_key || ''))) }}
</span>
</td>
<td class="sticky right-0 z-10 min-w-28 whitespace-nowrap bg-white px-2 py-1.5 dark:bg-slate-900">
<div class="flex items-center justify-end gap-0.5">
<button
@@ -3520,9 +3429,9 @@ watch(
:line="lineFulfillmentFor(String(line.line_key || ''))"
:editable="editable"
:busy="lineOpsBusyKey === String(line.line_key || '') || saving"
@retry-inventory="(actionCode) => void retryLineInventoryRpa(String(line.line_key || ''), actionCode)"
:task-running="taskAutomationRunning"
@retry-line="() => void retryLineUnified(String(line.line_key || ''))"
@close-line="openCloseFulfillmentDialog([String(line.line_key || '')])"
@view-fulfillment="toggleFulfillmentDetail(String(line.line_key || ''))"
/>
</div>
</td>
@@ -3569,10 +3478,10 @@ watch(
data-testid="review-build-gate-rail"
:aria-label="t('chat.shippingOrderReview.workbench.summaryRail')"
>
<!-- 宽屏侧栏:建单前订单检查;正式 OT 后不挂当前处理/履约摘要重复卡 -->
<!-- 宽屏侧栏:建单前订单检查 + 当前处理卡(对象级重试优先于此) -->
<div class="hidden space-y-2 xl:block" data-testid="review-primary-blockers-wide">
<ReviewCurrentProcessingCard
v-if="!hasFormalOt && activeCase?.task_missing"
v-if="mountCurrentProcessingCard"
:stage-code="currentProcessingStageDisplay.code"
:stage-label-key="currentProcessingStageDisplay.labelKey"
:stage-inconsistent="currentProcessingStageDisplay.inconsistent"
@@ -3581,15 +3490,15 @@ watch(
:confirmed-task-id="activeCase?.confirmed_task_id"
:show-admin-diagnosis="showAdminTaskMissingDiagnosis"
:automation="activeCase?.automation"
:show-retry="false"
:retrying="progressRetrying"
@retry="() => void retryFormalOtAutoProgress()"
:show-retry="showObjectRetryOnRail"
:retrying="progressRetrying || caseSwitchLoading"
@retry="() => void (hasFormalOt ? retryFormalOtAutoProgress() : retryStpAutoCreate())"
/>
<ReviewInventoryIssueFallbackCard
v-if="hasFormalOt && activeCase?.inventory_issue_fallback && !activeCase?.line_fulfillment?.has_line_inventory_projection"
:fallback="activeCase.inventory_issue_fallback"
:busy="Boolean(lineOpsBusyKey)"
@retry-preparation="() => void retryLineInventoryRpa('case', 'retry_inventory_preparation')"
@retry-preparation="() => void retryCaseInventoryFallback()"
/>
<ReviewCustomerResolutionPanel
v-if="activeCase && !activeCase.customer_resolution?.resolved && showEligibilityAsPrimary"
@@ -3845,7 +3754,7 @@ watch(
:can-confirm-build="canConfirmBuild"
:hide-confirm-because-auto-gate="hideConfirmBecauseAutoGate"
:show-auto-gate-hint="showAutoGateHint"
:show-stp-retry="showStpRetry"
:show-stp-retry="showObjectRetryOnFooter"
:auto-gate-hint="t(autoGateHintKey)"
:saving="saving"
:is-read-only="isReadOnly"
@@ -3884,6 +3793,56 @@ watch(
@save-and-switch="() => { void saveAndSwitchCase(); }"
/>
<div
v-if="conversationRetryResultOpen && conversationRetryResult"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-4"
data-testid="review-conversation-retry-result"
role="dialog"
aria-modal="true"
>
<div class="w-full max-w-md rounded-xl border border-slate-200 bg-white p-4 shadow-xl dark:border-slate-700 dark:bg-slate-900">
<h2 class="text-sm font-semibold text-slate-900 dark:text-slate-100">
{{ t('chat.shippingOrderReview.conversationRetry.title') }}
</h2>
<dl class="mt-3 space-y-1 text-xs text-slate-700 dark:text-slate-200">
<div class="flex justify-between gap-3">
<dt>{{ t('chat.shippingOrderReview.conversationRetry.retried') }}</dt>
<dd data-testid="review-conversation-retry-retried">{{ conversationRetryResult.summary.retried }}</dd>
</div>
<div class="flex justify-between gap-3">
<dt>{{ t('chat.shippingOrderReview.conversationRetry.skipped') }}</dt>
<dd data-testid="review-conversation-retry-skipped">{{ conversationRetryResult.summary.skipped }}</dd>
</div>
<div class="flex justify-between gap-3">
<dt>{{ t('chat.shippingOrderReview.conversationRetry.failed') }}</dt>
<dd data-testid="review-conversation-retry-failed">{{ conversationRetryResult.summary.failed }}</dd>
</div>
</dl>
<ul
v-if="conversationRetryResult.items.some((item) => item.outcome === 'skipped')"
class="mt-3 max-h-40 space-y-1 overflow-y-auto text-xs text-slate-600 dark:text-slate-300"
data-testid="review-conversation-retry-skip-list"
>
<li
v-for="item in conversationRetryResult.items.filter((row) => row.outcome === 'skipped')"
:key="`${item.object_type}:${item.object_ref}`"
>
{{ item.object_ref }}:{{ conversationRetrySkipReasonLabel(item.reason_code) || t('chat.shippingOrderReview.conversationRetry.skipped') }}
</li>
</ul>
<div class="mt-4 flex justify-end">
<button
type="button"
class="rounded bg-sky-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-sky-500"
data-testid="review-conversation-retry-close-refresh"
@click="() => void closeConversationRetryResult()"
>
{{ t('chat.shippingOrderReview.conversationRetry.closeAndRefresh') }}
</button>
</div>
</div>
</div>
<ReviewActionConfirmDialog
v-if="actionDialogOpen && pendingAction"
v-model="actionDialogOpen"
@@ -84,6 +84,22 @@ describe('resolveProcessingActionPresentation', () => {
expect([result.primary, result.secondary, ...result.overflow].some((i) => i?.intent === 'refresh')).toBe(false);
});
it('available_actions 乱序 / 大小写空格 / 重复不影响输出按钮顺序', () => {
const order1 = resolveProcessingActionPresentation(projection({
availableActions: [' Refresh ', 'view_details', 'retry_parse', 'view_details'],
}), { surface: 'chat', actionsExecutable: true });
const order2 = resolveProcessingActionPresentation(projection({
availableActions: ['retry_parse', 'VIEW_DETAILS', 'refresh'],
}), { surface: 'chat', actionsExecutable: true });
// presentation 主/次/溢出的 intent 序列必须相同,不受后端原始顺序影响。
const intentChain = (r: typeof order1) => [
r.primary?.intent ?? null,
r.secondary?.intent ?? null,
...r.overflow.map((o) => o.intent),
].join('|');
expect(intentChain(order1)).toBe(intentChain(order2));
});
it('maps open_order_review label to processing entry on chat surface', () => {
const result = resolveProcessingActionPresentation(projection({
availableActions: ['open_order_review'],
@@ -12,6 +12,7 @@ import type {
ShippingProcessingActionIntent,
ShippingProcessingProjection,
} from '@/features/chat/types/shipping.api.types';
import { normalizeActionCodes } from '@/features/chat/shipping/conversationProcessingProjection';
import type { ActionPresentation, ActionPresentationItem, ActionPresentationSurface } from './types';
import type { WorkbenchPanelAvailability } from './workbenchActionRegistry';
import {
@@ -65,6 +66,10 @@ const ACTION_CODE_TO_INTENT: Record<string, ShippingProcessingActionIntent> = {
};
const AUTOMATING_STATUSES = new Set(['processing', 'automating', 'queued']);
const NEEDS_ACTION_STATUSES = new Set([
'blocked', 'waiting_review', 'pending_review', 'failed', 'reparse_failed',
'manual_upload_pending', 'upload_rpa_failed',
]);
/** 永不升为主 CTA 的动作码(仍可作次要/溢出)。 */
const NEVER_PRIMARY_CODES = new Set(['cancel_task', 'cancel_run', 'view_details']);
@@ -213,7 +218,9 @@ export function resolveProcessingActionPresentation(
};
pushCode(projection.currentGate?.nextActionCode);
for (const action of projection.availableActions || []) {
// [ORDER-STABLE] 对 availableActions 标准化(去重 + 字典序排序),确保后端返回顺序不影响前端按钮顺序。
const normalizedAvailableActions = normalizeActionCodes(projection.availableActions || []);
for (const action of normalizedAvailableActions) {
pushCode(action);
}
@@ -243,6 +250,12 @@ export function resolveConversationTaskActionPresentation(
if (!task) return empty;
const surface = options?.surface || 'right';
const status = String(task.status_label || '').trim().toLowerCase();
const isNeedsAction = task.group === 'needs_action' || NEEDS_ACTION_STATUSES.has(status);
const isProcessing = task.group === 'processing' || AUTOMATING_STATUSES.has(status);
if (task.group === 'history' || status === 'cancelled') {
return empty;
}
const items: ActionPresentationItem[] = [];
const seen = new Set<string>();
@@ -258,16 +271,27 @@ export function resolveConversationTaskActionPresentation(
};
pushCode(task.primary_action);
for (const action of task.available_actions || []) {
// [ORDER-STABLE] 对 available_actions 标准化排序,确保后端顺序变化不影响按钮渲染顺序。
const normalizedTaskActions = normalizeActionCodes(task.available_actions || []);
for (const action of normalizedTaskActions) {
pushCode(action);
}
// 无正式业务入口时,默认提供查看进度(focus_task)。
// 人工待办禁止伪造查看进度;无明确动作时进入订单处理作为安全兜底。
if (isNeedsAction && !items.some((item) => !NEVER_PRIMARY_CODES.has(String(item.actionCode || '').trim().toLowerCase()))) {
pushCode('open_order_processing');
}
// 只有系统处理中才允许显示查看进度,且只能作为次要文字链。
if (isProcessing && !items.length) pushCode('focus_task');
const hasPrimaryCandidate = items.some(
(item) => !NEVER_PRIMARY_CODES.has(String(item.actionCode || '').trim().toLowerCase()),
);
if (!hasPrimaryCandidate) {
pushCode('focus_task');
if (!hasPrimaryCandidate && !isProcessing) {
return empty;
}
if (isProcessing) {
const progress = items.find((item) => String(item.actionCode).toLowerCase() === 'focus_task');
return { primary: null, secondary: progress || null, overflow: [] };
}
return partitionActionItems(items);
@@ -1,9 +1,10 @@
<!--
features/shipping-progress/components/ReviewProgressStrip.vue
用途:订单处理工作台只读进度——xl 等宽 15 阶;md 横向滚动;窄屏仅 N/15。
依赖:vue-i18n、ShippingProcessingProjection、progressWindow、stageNodesAuthority、gateReasonLabel。
逻辑:由 ReviewWorkflowProgressPanel 挂载;禁止点击节点;「当前需要」并入标题行文案;
「查看流程详情」在标题行右侧;正式 OT 后抑制「请确认建单」;写操作只在 Footer。
依赖:vue-i18n、ShippingProcessingProjection、progressWindow、stageNodesAuthority。
逻辑:由 ReviewWorkflowProgressPanel 挂载;禁止点击节点;标题只显示「订单处理进度」,
不混入等待系统启动/人工处理/失败等自动化文案(归右侧状态卡);
「查看流程详情」与标题同行;写操作只在 Footer / 右侧对象级。
-->
<script setup lang="ts">
import { computed, watch } from 'vue';
@@ -12,19 +13,18 @@ import type {
ShippingProcessingProjection,
ShippingProcessingStageNodeStatus,
} from '@/features/chat/types/shipping.api.types';
import { shippingProcessingStageKey, resolveShippingProcessingStageLabel } from '@/features/chat/shipping/shippingProcessingLabels';
import { shippingProcessingStageKey } from '@/features/chat/shipping/shippingProcessingLabels';
import { buildProgressRangeHint } from '../progressWindow';
import {
readAuthoritativeStageNodes,
warnStageNodesUnavailable,
} from '../stageNodesAuthority';
import { resolveCurrentNeedLabel } from '../gateReasonLabel';
const props = defineProps<{
projection: ShippingProcessingProjection;
/** 宿主轮询中提示(显示在标题行)。 */
polling?: boolean;
/** 正式 OT 已创建时禁止再投影「请确认建单」类当前需要。 */
/** 正式 OT 已创建时保留 prop 兼容(进度条不再展示当前需要文案)。 */
hasFormalOt?: boolean;
}>();
@@ -36,12 +36,6 @@ const emit = defineEmits<{
const { t, te } = useI18n();
const AUTOMATING_STATUSES = new Set(['processing', 'automating', 'queued']);
const CONFIRM_BUILD_ACTION_CODES = new Set([
'confirm_create',
'confirm_build',
'open_order_review',
'confirm_order',
]);
const SYSTEM_TECH_ACTION_PREFIXES = ['retry_', 'poll_'];
/** 权威 15 阶;非法时 null(fail-closed)。 */
@@ -50,7 +44,7 @@ const stageNodes = computed(() => readAuthoritativeStageNodes(props.projection))
const rangeHint = computed(() => buildProgressRangeHint(props.projection, 'workbench'));
/**
* 是否处于系统自动推进(含技术重试/轮询动作,避免被 nextAction 误判为人工待办)。
* 是否处于系统自动推进(用于刷新按钮,不进标题文案)。
*/
const isAutomating = computed(() => {
const status = String(props.projection.status || '').trim().toLowerCase();
@@ -61,50 +55,19 @@ const isAutomating = computed(() => {
return false;
});
const stageLabel = computed(() => resolveShippingProcessingStageLabel(
props.projection.stage,
te,
t,
props.projection.stageLabelKey,
));
/**
* 标题仅「订单处理进度」,阶段名由节点/窄屏摘要表达。
*/
const titleLine = computed(() => t('chat.shippingProcessing.progress.title'));
/**
* 单行标题:自动推进用「系统处理中 · 阶段」;否则「订单处理进度 · 阶段」。
* 窄屏当前阶段名:只用 stage code → 阶段 i18n,不用 waiting_system_start 等自动化 label_key。
*/
const titleLine = computed(() => {
const stage = stageLabel.value || '—';
if (isAutomating.value) {
return t('chat.shippingProcessing.progress.systemProcessingWithStage', { stage });
}
return t('chat.shippingProcessing.progress.progressTitleWithStage', { stage });
});
/**
* 有阻断 Gate 且非自动推进时展示「当前需要」。
* 正式 OT 已创建后禁止再显示确认建单类文案。
*/
const showCurrentNeed = computed(() => {
if (isAutomating.value) return false;
const gate = props.projection.currentGate;
if (!gate) return false;
const next = String(gate.nextActionCode || '').trim().toLowerCase();
if (props.hasFormalOt && CONFIRM_BUILD_ACTION_CODES.has(next)) return false;
if (props.hasFormalOt) {
const reason = String(gate.blockingReasonCode || '').trim().toLowerCase();
if (reason === 'waiting_review' || reason.includes('confirm')) return false;
}
return Boolean(
String(gate.blockingReasonCode || '').trim()
|| String(gate.nextActionCode || '').trim(),
);
});
/**
* 「当前需要」:blockingReasonCode 优先,缺失时回退 nextActionCode(与 Footer 语义对齐)。
*/
const currentNeed = computed(() => {
if (!showCurrentNeed.value) return '';
return resolveCurrentNeedLabel(props.projection.currentGate, { t, te });
const currentStageName = computed(() => {
const stage = String(props.projection.stage || '').trim();
if (!stage) return '—';
const key = shippingProcessingStageKey(stage);
return te(key) ? t(key) : stage;
});
watch(
@@ -153,11 +116,10 @@ function nodeShortLabel(stage: string): string {
>
{{ titleLine }}
<span
v-if="showCurrentNeed && currentNeed"
class="ml-2 font-semibold text-amber-800 dark:text-amber-200"
data-testid="review-progress-current-need"
class="ml-2 font-normal text-secondary md:hidden"
data-testid="review-progress-current-stage-narrow"
>
· {{ t('chat.shippingProcessing.progress.currentNeedLabel') }}{{ currentNeed }}
{{ t('chat.shippingProcessing.progress.currentStage', { stage: currentStageName }) }}
</span>
<span
v-if="polling"
@@ -189,7 +151,6 @@ function nodeShortLabel(stage: string): string {
</div>
</div>
<!-- xl:15 阶等宽铺满 -->
<div
v-if="stageNodes"
class="hidden xl:block"
@@ -218,7 +179,6 @@ function nodeShortLabel(stage: string): string {
</div>
</div>
<!-- md–xl:横向滚动、节点等宽 -->
<div
v-if="stageNodes"
class="hidden overflow-x-auto pb-1 md:block xl:hidden"
@@ -254,7 +214,6 @@ function nodeShortLabel(stage: string): string {
{{ t('chat.shippingProcessing.progress.stageNodesUnavailable') }}
</p>
<!-- &lt;md:仅已完成 N/15 + 标题中的当前阶段 -->
<p
v-if="rangeHint"
class="text-[11px] text-secondary md:hidden"
@@ -265,6 +224,5 @@ function nodeShortLabel(stage: string): string {
total: rangeHint.total,
}) }}
</p>
</div>
</template>