feat(shipping-notice): 实现滚动履约功能,优化发货通知流程与代码清理

清理废弃的ShippingCase相关代码与依赖,统一使用ShippingNotice直接关联客户数据。调整库存网关依赖规则,支持仅对库存满足或已人工放行的订单行生成发货Excel,实现滚动履约逻辑。
This commit is contained in:
hugo committed 2026-08-26 02:47:07 +08:00
1 parent 7cfd5d167e
commit 1e5aedb9ed
235 files changed
+11394 -9613

No files matched your search

+36 -8
View File
@@ -23,6 +23,7 @@ import type {
ShippingNoticeIntakeResponse,
ShippingTaskCreateResponse,
ShippingTaskDetail,
ShippingFreightNoticeGroupsResponse,
ShippingTaskBatchDispositionResponse,
ShippingTaskPage,
ShippingCustomerOption,
@@ -121,6 +122,12 @@ export const listShippingChatAgents = () => requestJson<ShippingChatAgentOption[
export const getWorkspaceShippingTask = (taskNo: string) =>
requestJson<ShippingTaskDetail>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}`);
/** 读取当前 PO 下按 business_no 聚合的货代上传 Notice。 */
export const getWorkspaceShippingFreightNoticeGroups = (taskNo: string) =>
requestJson<ShippingFreightNoticeGroupsResponse>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/freight-notice-groups`,
);
/**
* 分页拉取任务工作台统一审计时间线(ShippingAuditEvent 单源)。
*/
@@ -141,10 +148,14 @@ export const listWorkspaceShippingTaskAuditTimeline = (
export const getWorkspaceShippingTaskUiState = (taskNo: string) =>
requestJson<ShippingTaskUiState>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/ui-state`);
/** 生成任务导出文件的前端下载 URL。 */
/** 旧任务号 Excel 下载 URL;仅供未迁移页面兼容,新货代操作必须使用 business_no。 */
export const workspaceShippingExportUrl = (taskNo: string) =>
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/export`;
/** 按发货通知单号下载唯一正式 Excel。 */
export const workspaceShippingNoticeExportUrl = (businessNo: string) =>
`/api/workspace/shipping-notices/${encodeURIComponent(businessNo)}/export`;
/** 当前任务已关联库存快照的受控下载 URL;后端会再次校验任务归属与活动 link。 */
export const workspaceShippingInventoryFileUrl = (taskNo: string) =>
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/inventory-file`;
@@ -871,7 +882,7 @@ export const decideWorkspaceShippingOrderReviewLineFulfillment = (
);
/**
* 为选中完整明细行创建履约波次 Task。
* 为选中完整明细行创建独立发货通知和 Excel。
*/
export const waveWorkspaceShippingOrderReviewLineFulfillment = (
caseNo: string,
@@ -887,6 +898,7 @@ export const waveWorkspaceShippingOrderReviewLineFulfillment = (
resume_outcome?: ShippingOrderReviewResumeOutcome;
task_no?: string | null;
wave_no?: number | null;
notice_no?: string | null;
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/line-fulfillment/wave`,
{
@@ -1282,22 +1294,38 @@ export async function autoProgressWorkspaceShippingTask(taskNo: string, lang?: s
}
/**
* 标记货代系统已人工上传完成。
* @param taskNo - 发货任务编号
* @param payload - 当前 Artifact、人工回执 FileAsset 编号及可选货代参考号;回执编号必填。
* 按发货通知单号确认货代系统已人工上传完成。
* @param businessNo - 对外发货通知单号
* @param payload - 当前通知唯一 Excel 的可选 Artifact 编号。
* @returns 上传确认结果
*/
export async function markWorkspaceShippingManualUploaded(
taskNo: string,
payload: { evidence_asset_no: string; artifact_id?: number; freight_ref_no?: string },
businessNo: string,
payload: { artifact_id?: number } = {},
) {
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/mark-manual-uploaded`,
`/api/workspace/shipping-notices/${encodeURIComponent(businessNo)}/confirm-uploaded`,
jsonPost(payload),
);
return assertShippingOk(body);
}
/** 按多个发货通知单号批量确认人工上传;后端逐单裁决并返回逐单结果。 */
export async function batchConfirmWorkspaceShippingNoticesUploaded(businessNos: string[]) {
return requestJson<{ results: Array<Record<string, unknown>> }>(
'/api/workspace/shipping-notices/batch/confirm-uploaded',
jsonPost({ business_nos: businessNos }),
);
}
/** 按多个发货通知单号批量受理货代 RPA 上传;RPA 成功仍以回调为准。 */
export async function batchStartWorkspaceShippingNoticeRpaUpload(businessNos: string[]) {
return requestJson<{ results: Array<Record<string, unknown>> }>(
'/api/workspace/shipping-notices/batch/rpa-upload',
jsonPost({ business_nos: businessNos }),
);
}
/** 发货通知 Agent 应用类型标识(运行时识别)。 */
export const SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice';
@@ -19,9 +19,11 @@ const i18n = createI18n({
shippingNotice: {
processGate: {
actionCodes: {
reload_inventory_result: '重新读取库存结果',
retry_inventory_preparation: '重新获取库存',
},
inventoryActions: {
reloadInventoryResult: '重新读取库存结果',
retryInventoryMatching: '重新库存匹配',
retryInventoryPreparation: '重新获取库存',
},
@@ -80,6 +82,18 @@ describe('ReviewCurrentProcessingCard', () => {
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true);
});
it('renders reload inventory result as the timeout primary action', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'inventory_preparation', userStatus: 'retryable', retryable: true,
primaryAction: { code: 'reload_inventory_result' },
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').text()).toBe('重新读取库存结果');
});
it('hides the order-review entry when the user is already in the lifecycle workbench', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
@@ -352,7 +352,18 @@ type ReviewCurrentUserStatus =
</div>
<div class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.currentProcessing.status') }}</dt>
<dd data-testid="review-current-task-status" :class="loading ? 'animate-pulse' : ''">{{ statusLabel }}</dd>
<dd
class="inline-flex items-center gap-1"
data-testid="review-current-task-status"
:class="loading ? 'animate-pulse' : ''"
>
<RefreshCw
v-if="userStatus === 'running' && !loading"
class="h-3 w-3 animate-spin"
aria-hidden="true"
/>
{{ statusLabel }}
</dd>
</div>
<div
v-if="hasFormalOt && shippingNoticeNo"
@@ -1,275 +1,30 @@
<!--
features/chat/components/shipping-review/ReviewFulfillmentDecisionPanel.vue
用途:复核工作台行级履约决定(等待补货 / 完整行先行 / 关闭)。
依赖:vue-i18n、decide/wave line-fulfillment API、showReviewResumeOutcome。
逻辑:分列展示料号/需求数量/可用数量/预约单号/状态;禁止 part_number 回退预约单号;
逐行决定;选中 fulfill 行可确认波次;关闭 emit open-close-dialog。
-->
<!-- 履约摘要侧栏;完整明细与批量出单统一由主库存表承载。 -->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
decideWorkspaceShippingOrderReviewLineFulfillment,
waveWorkspaceShippingOrderReviewLineFulfillment,
} from '@/features/chat/api/shipping.api';
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
import type {
ShippingOrderReviewLineFulfillment,
ShippingOrderReviewLineFulfillmentDecisionCode,
ShippingOrderReviewLineFulfillmentLine,
} from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
caseNo: string;
draftVersion: number | null | undefined;
lineFulfillment: ShippingOrderReviewLineFulfillment | null | undefined;
editable: boolean;
}>();
const emit = defineEmits<{
refreshed: [];
'open-close-dialog': [lineKeys: string[]];
}>();
const { t, te } = useI18n();
const msg = useMessage();
const busyKey = ref<string | null>(null);
const selectedFulfillKeys = ref<string[]>([]);
const waveBusy = ref(false);
import type { ShippingOrderReviewLineFulfillment } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{ caseNo: string; draftVersion: number | null | undefined; lineFulfillment: ShippingOrderReviewLineFulfillment | null | undefined; editable: boolean }>();
const emit = defineEmits<{ refreshed: []; 'open-close-dialog': [lineKeys: string[]] }>();
const { t } = useI18n();
const TERMINAL_STATUSES = new Set(['task_created', 'fulfilled', 'closed_unfulfillable']);
const visible = computed(() => Boolean(
props.lineFulfillment?.has_open_lines
|| props.lineFulfillment?.has_shortage,
));
const openLines = computed(() => (props.lineFulfillment?.lines || []).filter(
(line) => !TERMINAL_STATUSES.has(String(line.line_status || '')),
));
/**
* 行状态本地化。
*/
function lineStatusLabel(status: string | null | undefined): string {
const normalized = String(status || 'pending_decision').trim();
const key = `chat.shippingOrderReview.fulfillmentDecision.lineStatus.${normalized}`;
return te(key) ? t(key) : normalized;
}
/**
* 切换 fulfill 波次选中行。
*/
function toggleFulfillSelection(lineKey: string, checked: boolean) {
const set = new Set(selectedFulfillKeys.value);
if (checked) set.add(lineKey);
else set.delete(lineKey);
selectedFulfillKeys.value = [...set];
}
/**
* 行是否可选入 fulfill 波次。
*/
function canSelectForWave(line: ShippingOrderReviewLineFulfillmentLine): boolean {
if (TERMINAL_STATUSES.has(String(line.line_status || ''))) return false;
return Boolean(line.can_fulfill_complete_line);
}
/**
* 写入单行履约决定。
*/
async function onDecide(
line: ShippingOrderReviewLineFulfillmentLine,
decisionCode: ShippingOrderReviewLineFulfillmentDecisionCode,
) {
if (!props.caseNo || !props.editable || busyKey.value) return;
if (decisionCode === 'close_unfulfillable') {
emit('open-close-dialog', [line.line_key]);
return;
}
busyKey.value = line.line_key;
try {
const result = await decideWorkspaceShippingOrderReviewLineFulfillment(props.caseNo, {
line_key: line.line_key,
decision_code: decisionCode,
expected_draft_version: props.draftVersion ?? undefined,
});
showReviewResumeOutcome(
result.resume_outcome,
msg,
t,
t('chat.shippingOrderReview.fulfillmentDecision.decideSuccess'),
);
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fulfillmentDecision.decideFailed'));
msg.warning(message);
} finally {
busyKey.value = null;
}
}
/**
* 为选中完整行创建履约波次 Task。
*/
async function onConfirmWave() {
if (!props.caseNo || props.draftVersion == null || waveBusy.value || !selectedFulfillKeys.value.length) return;
waveBusy.value = true;
try {
const idempotencyKey = `review-wave-${props.caseNo}-${Date.now()}-${selectedFulfillKeys.value.sort().join(',')}`;
const result = await waveWorkspaceShippingOrderReviewLineFulfillment(props.caseNo, {
line_keys: [...selectedFulfillKeys.value],
expected_draft_version: props.draftVersion,
idempotency_key: idempotencyKey,
});
showReviewResumeOutcome(
result.resume_outcome,
msg,
t,
t('chat.shippingOrderReview.fulfillmentDecision.waveSuccess', {
taskNo: result.task_no || '',
}),
);
selectedFulfillKeys.value = [];
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fulfillmentDecision.waveFailed'));
msg.warning(message);
} finally {
waveBusy.value = false;
}
}
/**
* 打开关闭剩余行对话框(全部开放行)。
*/
function onCloseRemaining() {
const keys = openLines.value.map((line) => line.line_key);
emit('open-close-dialog', keys);
}
const openLines = computed(() => (props.lineFulfillment?.lines || []).filter((line) => !TERMINAL_STATUSES.has(String(line.line_status || ''))));
const visible = computed(() => Boolean(props.lineFulfillment?.has_open_lines || props.lineFulfillment?.has_shortage));
function onCloseRemaining() { emit('open-close-dialog', openLines.value.map((line) => line.line_key)); }
</script>
<template>
<section
v-if="visible"
class="rounded-xl border border-sky-200 bg-sky-50/70 p-3 shadow-sm dark:border-sky-900 dark:bg-sky-950/40"
data-testid="review-fulfillment-decision-panel"
>
<section v-if="visible" class="rounded-xl border border-sky-200 bg-sky-50/70 p-3 shadow-sm dark:border-sky-900 dark:bg-sky-950/40" data-testid="review-fulfillment-decision-panel">
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold text-sky-950 dark:text-sky-50">
{{ t('chat.shippingOrderReview.fulfillmentDecision.title') }}
</h2>
<p class="mt-0.5 text-xs text-sky-900 dark:text-sky-200">
{{ t('chat.shippingOrderReview.fulfillmentDecision.subtitle') }}
</p>
</div>
<span class="rounded-full bg-sky-100 px-2.5 py-1 text-xs font-medium text-sky-900 dark:bg-sky-950 dark:text-sky-100">
{{ t('chat.shippingOrderReview.fulfillmentDecision.openCount', { count: lineFulfillment?.open_count ?? openLines.length }) }}
</span>
<div><h2 class="text-sm font-semibold text-sky-950 dark:text-sky-50">{{ t('chat.shippingOrderReview.fulfillmentDecision.title') }}</h2><p class="mt-0.5 text-xs text-sky-900 dark:text-sky-200">{{ t('chat.shippingOrderReview.fulfillmentDecision.railHint') }}</p></div>
<span class="rounded-full bg-sky-100 px-2.5 py-1 text-xs font-medium text-sky-900 dark:bg-sky-950 dark:text-sky-100">{{ t('chat.shippingOrderReview.fulfillmentDecision.openCount', { count: lineFulfillment?.open_count ?? openLines.length }) }}</span>
</header>
<div class="mt-2 overflow-x-auto">
<table class="min-w-full text-left text-xs">
<thead class="text-muted">
<tr>
<th v-if="editable" class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.waveSelect') }}</th>
<th class="px-1 py-1 font-medium">#</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.partNumber') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.requiredQty') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.reservationId') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.status') }}</th>
<th v-if="editable" class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.actions') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="line in lineFulfillment?.lines || []"
:key="line.line_key"
class="border-t border-sky-100 dark:border-sky-900"
>
<td v-if="editable" class="px-1 py-1">
<input
v-if="canSelectForWave(line)"
type="checkbox"
class="rounded border-default"
:checked="selectedFulfillKeys.includes(line.line_key)"
:data-testid="`review-fulfill-select-${line.line_key}`"
@change="toggleFulfillSelection(line.line_key, ($event.target as HTMLInputElement).checked)"
>
</td>
<td class="px-1 py-1">{{ (line.line_index ?? 0) + 1 }}</td>
<td class="px-1 py-1 font-mono" data-testid="review-fulfill-part-number">
{{ line.part_number || t('chat.shippingOrderReview.fulfillmentDecision.partUnrecognized') }}
</td>
<td class="px-1 py-1">{{ line.required_qty ?? '—' }}</td>
<td class="px-1 py-1">{{ line.available_qty ?? '—' }}</td>
<td class="px-1 py-1 font-mono">{{ line.reservation_id || '—' }}</td>
<td class="px-1 py-1">{{ lineStatusLabel(line.line_status) }}</td>
<td v-if="editable && !TERMINAL_STATUSES.has(String(line.line_status || ''))" class="px-1 py-1">
<div class="flex flex-wrap gap-1">
<button
type="button"
class="rounded border border-sky-300 px-2 py-1 text-xs hover:bg-sky-100 disabled:opacity-50 dark:border-sky-800 dark:hover:bg-sky-950"
:disabled="busyKey != null"
@click="onDecide(line, 'wait_inventory')"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.waitInventory') }}
</button>
<button
v-if="line.can_fulfill_complete_line"
type="button"
class="rounded border border-emerald-300 px-2 py-1 text-xs hover:bg-emerald-50 disabled:opacity-50 dark:border-emerald-800 dark:hover:bg-emerald-950"
:disabled="busyKey != null"
@click="onDecide(line, 'fulfill_complete_line_now')"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.fulfillNow') }}
</button>
<button
type="button"
class="rounded border border-rose-300 px-2 py-1 text-xs text-rose-800 hover:bg-rose-50 disabled:opacity-50 dark:border-rose-800 dark:text-rose-200 dark:hover:bg-rose-950"
:disabled="busyKey != null"
@click="onDecide(line, 'close_unfulfillable')"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.closeLine') }}
</button>
</div>
</td>
<td v-else-if="editable" class="px-1 py-1 text-muted">—</td>
</tr>
</tbody>
</table>
</div>
<div v-if="editable" class="mt-3 flex flex-wrap gap-2">
<button
type="button"
class="rounded-xl bg-emerald-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-60"
data-testid="review-fulfillment-confirm-wave"
:disabled="waveBusy || !selectedFulfillKeys.length || draftVersion == null"
@click="onConfirmWave"
>
{{ waveBusy
? t('chat.shippingOrderReview.fulfillmentDecision.waving')
: t('chat.shippingOrderReview.fulfillmentDecision.confirmWave', { count: selectedFulfillKeys.length }) }}
</button>
<button
v-if="openLines.length"
type="button"
class="rounded-xl border border-rose-300 bg-white px-3 py-1.5 text-sm text-rose-800 hover:bg-rose-50 disabled:opacity-60 dark:border-rose-800 dark:bg-slate-900 dark:text-rose-200"
data-testid="review-fulfillment-close-remaining"
:disabled="waveBusy || busyKey != null"
@click="onCloseRemaining"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.closeRemaining') }}
</button>
<div class="mt-2 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4">
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.readyCount', { count: lineFulfillment?.ready_count ?? 0 }) }}</div>
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortageCount', { count: lineFulfillment?.manual_pending_count ?? 0 }) }}</div>
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.autoProgressCount', { count: lineFulfillment?.auto_progress_count ?? 0 }) }}</div>
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.summaryHint') }}</div>
</div>
<div v-if="editable && openLines.length" class="mt-3"><button type="button" class="rounded-xl border border-rose-300 bg-white px-3 py-1.5 text-sm text-rose-800 hover:bg-rose-50 dark:border-rose-800 dark:bg-slate-900 dark:text-rose-200" data-testid="review-fulfillment-close-remaining" @click="onCloseRemaining">{{ t('chat.shippingOrderReview.fulfillmentDecision.closeRemaining') }}</button></div>
</section>
</template>
@@ -22,6 +22,7 @@ const i18n = createI18n({
lifecycle: {
navigation: '订单生命周期阶段',
current: '当前可处理',
processing: '处理中',
completed: '已完成,可查看',
blocked: '前置未完成',
},
@@ -41,7 +42,7 @@ const stages: ReviewLifecycleStageItem[] = [
/** 挂载导航,复用真实 i18n 以覆盖状态文案渲染。 */
function mountNavigation() {
return mount(ReviewLifecycleStageNavigation, {
props: { stages, activeCode: 'fulfillment_prep' },
props: { stages, activeCode: 'fulfillment_prep', processingCode: 'fulfillment_prep' },
global: { plugins: [i18n] },
});
}
@@ -102,6 +103,14 @@ describe('ReviewLifecycleStageNavigation', () => {
expect(wrapper.emitted('select')).toEqual([['order_review']]);
});
it('shows a spinner and processing label on the active stage while automation runs', () => {
const wrapper = mountNavigation();
const stage = wrapper.get('[data-testid="review-lifecycle-stage-fulfillment_prep"]');
expect(stage.attributes('data-processing')).toBe('1');
expect(stage.text()).toContain('处理中');
expect(stage.find('[data-testid="review-lifecycle-stage-spinner"]').exists()).toBe(true);
});
it('disables a future stage and does not emit a selection', async () => {
const wrapper = mountNavigation();
const future = wrapper.get('[data-testid="review-lifecycle-stage-upload_complete"]');
@@ -5,7 +5,7 @@
逻辑:用户可打开当前或已完成阶段查看;后续阶段由父级传入 blocked 并禁用,本组件不写业务状态。
-->
<script setup lang="ts">
import { Check, LockKeyhole } from 'lucide-vue-next';
import { Check, LockKeyhole, RefreshCw } from 'lucide-vue-next';
export type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
export type ReviewLifecycleStageState = 'current' | 'completed' | 'blocked';
@@ -23,6 +23,8 @@ const props = defineProps<{
activeCode: ReviewLifecycleStageCode | null;
/** 仅消费当前对象后端下发的恢复动作,禁止按阶段或状态由前端猜测。 */
availableActions?: string[];
/** 当前阶段正在执行自动推进时的技术阶段码;只影响展示,不授权动作。 */
processingCode?: ReviewLifecycleStageCode | null;
/** retry_parse 请求中的互斥状态,避免用户重复提交。 */
retrying?: boolean;
}>();
@@ -67,8 +69,15 @@ function selectStage(stage: ReviewLifecycleStageItem) {
stage.state === 'blocked' ? 'opacity-60' : '',
]"
:data-testid="`review-lifecycle-stage-${stage.code}`"
:data-processing="stage.code === props.processingCode ? '1' : '0'"
>
<span class="flex items-center gap-2 text-sm font-semibold">
<RefreshCw
v-if="stage.code === props.processingCode"
class="h-4 w-4 shrink-0 animate-spin text-brand-600"
data-testid="review-lifecycle-stage-spinner"
aria-hidden="true"
/>
<Check v-if="stage.state === 'completed'" class="h-4 w-4 shrink-0 text-emerald-600" />
<LockKeyhole v-else-if="stage.state === 'blocked'" class="h-4 w-4 shrink-0 text-muted" />
<span v-else class="h-2 w-2 shrink-0 rounded-full bg-brand-600" aria-hidden="true" />
@@ -88,7 +97,9 @@ function selectStage(stage: ReviewLifecycleStageItem) {
@click="selectStage(stage)"
>
{{ stage.state === 'current'
? $t('chat.shippingOrderReview.lifecycle.current')
? (stage.code === props.processingCode
? $t('chat.shippingOrderReview.lifecycle.processing')
: $t('chat.shippingOrderReview.lifecycle.current'))
: stage.state === 'completed'
? $t('chat.shippingOrderReview.lifecycle.completed')
: (stage.reason || $t('chat.shippingOrderReview.lifecycle.blocked')) }}
@@ -18,6 +18,7 @@ const i18n = createI18n({
title: '文档模板匹配', subtitle: '摘要', selected: '命中模板', noSelected: '未选定模板',
expandCandidates: '查看候选模板({count})', collapseCandidates: '收起候选模板',
routeType: '路由类型', executionMode: '执行模式',
extractionBlocked: '模板已命中,但字段提取仍被安全门禁阻断', extractionBlockedReason: '阻断原因:{reasons}',
coordinateModel: {
anchorFrame: '锚点坐标框架', status: '变换状态', translateX: '横向平移',
translateY: '纵向平移', reasonCodes: '原因码',
@@ -102,6 +103,27 @@ describe('ReviewProfileMatchPanel', () => {
expect(wrapper.get('[data-testid="review-profile-match-candidates"]').text()).not.toContain('ODP-A');
});
it('唯一命中时仍展示下游字段提取门禁的阻断原因', () => {
const wrapper = mount(ReviewProfileMatchPanel, {
props: {
profileMatch: {
available: true,
visibility: 'admin',
status: 'unique_match',
needs_review: true,
selected_profile: { profile_code: 'ODP-A', display_name: '客户订单模板', version: 1 },
candidates: [{ profile_code: 'ODP-A', display_name: '客户订单模板', score: 0.99 }],
fallback_reason_codes: ['PARSE_STRATEGY_ROW_MODE_AMBIGUOUS'],
},
},
global: { plugins: [i18n] },
});
// 关键断言:唯一模板命中不等于字段已提取,必须明确暴露下游阻断原因。
expect(wrapper.get('[data-testid="review-profile-match-extraction-blocked"]').text())
.toContain('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS');
});
it('管理员技术详情展示锚点框架平移和稳定原因码,不展示原始正文或完整坐标', async () => {
const wrapper = mountAnchorFramePanel();
@@ -43,6 +43,10 @@ const selectedCoordinateTransform = computed(() => {
const coordinateTransformReasonCodes = computed(() => (
selectedCoordinateTransform.value?.reason_codes || []
));
/** 唯一命中仅证明版式身份;下游字段/明细恢复若受门禁阻断,必须在同卡明确说明。 */
const extractionBlockReasons = computed(() => (
(props.profileMatch?.fallback_reason_codes || []).filter((code) => String(code).trim())
));
watch(
() => `${props.profileMatch?.status || ''}:${props.profileMatch?.selected_profile?.profile_code || ''}:${candidateCount.value}`,
@@ -108,6 +112,17 @@ const selectedLabel = computed(() => {
</div>
</dl>
<div
v-if="extractionBlockReasons.length"
class="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-profile-match-extraction-blocked"
>
<p class="font-medium">{{ t('chat.shippingOrderReview.profileMatch.extractionBlocked') }}</p>
<p class="mt-1 text-amber-800 dark:text-amber-200">
{{ t('chat.shippingOrderReview.profileMatch.extractionBlockedReason', { reasons: extractionBlockReasons.join(', ') }) }}
</p>
</div>
<template v-if="isAdminView && candidateCount">
<button
type="button"
@@ -0,0 +1,59 @@
/**
* features/chat/components/shipping-review/ReviewReservationPanel.spec.ts
* 用途:验证 Reservation 校验面板只展示问题与重新校验入口,不重复提供明细编辑入口。
* 依赖:Vue Test Utils、vue-i18n、Reservation 重校验 API。
* 逻辑:挂载存在异常的 Reservation 面板,确认问题文案与重新校验按钮保留,编辑按钮不再出现。
*/
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { describe, expect, it, vi } from 'vitest';
import chatZhCn from '@/locales/zh-CN/chat.json';
import ReviewReservationPanel from './ReviewReservationPanel.vue';
vi.mock('@/features/chat/api/shipping.api', () => ({
revalidateWorkspaceShippingOrderReviewReservation: vi.fn(),
}));
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => ({ success: vi.fn(), warning: vi.fn(), error: vi.fn(), info: vi.fn() }),
}));
vi.mock('@/features/chat/shipping-review/showReviewResumeOutcome', () => ({
showReviewResumeOutcome: vi.fn(),
}));
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: { 'zh-CN': { chat: chatZhCn } },
});
describe('ReviewReservationPanel', () => {
it('只保留校验提示和重新校验入口,不重复提供明细编辑按钮', () => {
const wrapper = mount(ReviewReservationPanel, {
props: {
caseNo: 'CASE-1',
draftVersion: 3,
editable: true,
reservation: {
needs_attention: true,
status: 'needs_attention',
issues: [{ code: 'reservation_missing', severity: 'blocking', line_index: 0 }],
lines: [{
line_key: 'line-1',
line_index: 0,
effective_reservation_id: null,
needs_attention: true,
block_reason: 'reservation_missing',
}],
},
},
global: { plugins: [i18n] },
});
expect(wrapper.text()).toContain('缺少预约单号');
expect(wrapper.get('[data-testid="review-reservation-revalidate"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-reservation-focus-line"]').exists()).toBe(false);
expect(wrapper.text()).not.toContain('编辑此行');
});
});
@@ -2,7 +2,7 @@
features/chat/components/shipping-review/ReviewReservationPanel.vue
用途:复核工作台 Reservation 校验摘要;展示行级有效预约号与阻断 issue。
依赖:vue-i18n、revalidateWorkspaceShippingOrderReviewReservation、showReviewResumeOutcome。
逻辑:needs_attention 时展示;编辑聚焦明细行;重校验后 emit refreshed 并展示 resume 提示。
逻辑:needs_attention 时展示问题;左侧订单明细是唯一编辑位置;重校验后 emit refreshed 并展示 resume 提示。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
@@ -20,10 +20,7 @@ const props = defineProps<{
editable: boolean;
}>();
const emit = defineEmits<{
refreshed: [];
'focus-line': [lineIndex: number];
}>();
const emit = defineEmits<{ refreshed: [] }>();
const { t, te } = useI18n();
const msg = useMessage();
@@ -55,14 +52,6 @@ function issueLabel(code: string | null | undefined): string {
return te(key) ? t(key) : normalized;
}
/**
* 聚焦明细行以便编辑 reservation_id。
*/
function onFocusLine(lineIndex: number | null | undefined) {
if (lineIndex == null || !Number.isFinite(Number(lineIndex))) return;
emit('focus-line', Number(lineIndex));
}
/**
* 显式重校验 Reservation 并刷新 Case / 建单资格。
*/
@@ -128,13 +117,16 @@ async function onRevalidate() {
</li>
</ul>
<p v-if="editable" class="mt-2 text-xs text-violet-900 dark:text-violet-200">
{{ t('chat.shippingOrderReview.reservation.editHint') }}
</p>
<div v-if="lines.length" class="mt-2 overflow-x-auto">
<table class="min-w-full text-left text-xs">
<thead class="text-muted">
<tr>
<th class="px-1 py-1 font-medium">#</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.reservation.reservationId') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.reservation.action') }}</th>
</tr>
</thead>
<tbody>
@@ -151,17 +143,6 @@ async function onRevalidate() {
{{ issueLabel(line.block_reason) }}
</span>
</td>
<td class="px-1 py-1">
<button
v-if="editable && line.line_index != null"
type="button"
class="text-[11px] text-primary underline-offset-2 hover:underline"
data-testid="review-reservation-focus-line"
@click="onFocusLine(line.line_index)"
>
{{ t('chat.shippingOrderReview.reservation.editLine') }}
</button>
</td>
</tr>
</tbody>
</table>
@@ -171,6 +171,16 @@ const canWriteCaseActions = computed(() => props.actionsExecutable && !props.isR
{{ autoGateHint || t('chat.shippingOrderReview.buildEligibility.autoGateWaitingHint') }}
</p>
<template v-if="!automating && canWriteCaseActions">
<button
v-if="showStpRetry && hasAction('retry_stp_auto_create')"
type="button"
:disabled="controlsBusy"
class="inline-flex items-center gap-1 rounded border border-sky-300 px-3 py-2 text-sm text-sky-700 hover:bg-sky-50 disabled:opacity-50 dark:border-sky-700 dark:text-sky-300 dark:hover:bg-sky-950/40"
data-testid="review-retry-stp-auto-create"
@click="emit('retry-stp')"
>
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.automation.retryStp') }}
</button>
<button
v-if="showValidate && hasAction('validate')"
type="button"
@@ -23,9 +23,9 @@ const messages = {
subtitle: 'Advances through freight upload',
polling: 'Refreshing…',
progressUnavailable: 'Progress unavailable — refresh the page.',
openTaskWorkbench: 'Open Task Center to register',
openTaskWorkbench: 'Open Task Center to confirm upload',
nextStepsManualUpload:
'Next: download Excel → upload on freight platform → submit evidence and receipt',
'Next: download Excel → upload on freight platform → confirm uploaded',
nextStepsGeneric: 'Manual action required — follow the system prompt.',
},
},
@@ -194,7 +194,7 @@ describe('ReviewWorkflowProgressPanel', () => {
});
expect(wrapper.get('[data-testid="review-manual-upload-next-steps"]').text()).toContain('download Excel');
const link = wrapper.get('[data-testid="review-open-task-workbench"]');
expect(link.text()).toContain('Open Task Center to register');
expect(link.text()).toContain('Open Task Center to confirm upload');
expect(link.attributes('href')).toContain('workspace-shipping-my-tasks');
expect(link.attributes('href')).toContain('SN-1');
});
@@ -73,7 +73,8 @@ describe('shipping order review workbench viewport layout contract', () => {
expect(lifecycleNavigation).toContain('class="grid gap-2 sm:grid-cols-5"');
// sidebar/sidebar_search 是唯一允许预留 16rem 的模式;tabs/hidden/narrow 均落入 contents。
expect(reviewWorkbench).toMatch(/reviewDocumentNavigationMode\.value === 'sidebar'\s*\|\|\s*reviewDocumentNavigationMode\.value === 'sidebar_search'/);
expect(reviewWorkbench).toMatch(/:class="reviewDocumentNavigationUsesSidebar\s*\? 'grid gap-2 lg:grid-cols-\[16rem_minmax\(0,1fr\)\] lg:items-start lg:gap-3'\s*:\s*'contents'"/);
expect(reviewWorkbench).toContain('reviewDocumentNavigationCollapsed');
expect(reviewWorkbench).toContain('lg:grid-cols-[16rem_minmax(0,1fr)]');
expect(reviewWorkbench).not.toMatch(/reviewDocumentNavigationMode\.value === '(?:tabs|hidden|narrow)'\s*\?\s*'[^']*16rem/);
});
});
@@ -38,6 +38,7 @@ function createContext(overrides: Partial<ChatPageSendContext> = {}): ChatPageSe
refreshHistoryAfterSend: vi.fn(async () => undefined),
refreshConversationAfterSend: vi.fn(async () => undefined),
tryHandleShippingAttachmentAutoFlow: vi.fn(async () => false),
tryHandleProcurementContractSend: vi.fn(async () => false),
tryHandleLeaveSend: vi.fn(() => false),
tryHandleShippingSend: vi.fn(async () => false),
refreshToolRunProgressAfterSend: vi.fn(async () => undefined),
@@ -741,6 +741,110 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.activeCase.value?.case_no).toBe('CASE-NEW');
});
it('marks only the first successful Run read as initial loading', async () => {
// 关键断言:后续 Run 切换仍可有 Run 读取态,但不能再被页面当作首次整页加载。
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
expect(review.initialLoading.value).toBe(false);
let resolveRun: ((value: Record<string, unknown>) => void) | null = null;
api.getRun.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => {
resolveRun = resolve;
}));
const pending = review.load('RUN-2', 'CASE-2');
expect(review.runLoading.value).toBe(true);
expect(review.initialLoading.value).toBe(false);
resolveRun?.({
run_no: 'RUN-2', summary: {},
items: [{ case_no: 'CASE-2', document_id: 2, status: 'draft', issue_count: 0 }],
});
await pending;
});
it('shows the cross-Run target Case when its snapshot arrives before slow navigation summaries', async () => {
// 关键断言:目标 Case/Evidence 是当前 PDF 的事实源;慢 Run/Queue 仅延后导航校准,
// 绝不能继续阻塞用户看到已完成读取的目标文件。
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
const previousQueue = review.reviewQueue.value;
let resolveRun: ((value: Record<string, unknown>) => void) | null = null;
let resolveQueue: ((value: Record<string, unknown>) => void) | null = null;
let resolveCase: ((value: ShippingOrderReviewCase) => void) | null = null;
let resolveEvidence: ((value: { items: unknown[] }) => void) | null = null;
api.getRun.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => { resolveRun = resolve; }));
api.getQueue.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => { resolveQueue = resolve; }));
api.getCase.mockImplementationOnce(() => new Promise<ShippingOrderReviewCase>((resolve) => { resolveCase = resolve; }));
api.getEvidence.mockImplementationOnce(() => new Promise<{ items: unknown[] }>((resolve) => { resolveEvidence = resolve; }));
const pending = review.load('RUN-2', 'CASE-2');
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
expect(review.reviewQueue.value).toBe(previousQueue);
expect(review.activeCase.value?.case_no).toBe('CASE-1');
await vi.waitFor(() => expect(resolveRun).toBeTypeOf('function'));
await vi.waitFor(() => expect(resolveQueue).toBeTypeOf('function'));
await vi.waitFor(() => expect(resolveCase).toBeTypeOf('function'));
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
expect(review.activeCase.value?.case_no).toBe('CASE-1');
resolveCase?.(buildCase({ case_no: 'CASE-2', run_no: 'RUN-2', document: { id: 2, file_name: 'second.pdf' } }));
await vi.waitFor(() => expect(resolveEvidence).toBeTypeOf('function'));
resolveEvidence?.({ items: [] });
await vi.waitFor(() => expect(review.activeCase.value?.case_no).toBe('CASE-2'));
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
expect(review.reviewQueue.value).toBe(previousQueue);
resolveRun?.({ run_no: 'RUN-2', summary: {}, items: [{ case_no: 'CASE-2', document_id: 2, status: 'draft', issue_count: 0 }] });
resolveQueue?.({ summary: { total: 1, needs_action: 1, processing: 0, completed: 0 }, items: [{ case_no: 'CASE-2', document_id: 2, source_run_no: 'RUN-2', status: 'draft', issue_count: 0, available_actions: [] }] });
await pending;
expect(review.reviewRun.value?.run_no).toBe('RUN-2');
expect(review.reviewQueue.value?.items[0]?.case_no).toBe('CASE-2');
expect(review.activeCase.value?.case_no).toBe('CASE-2');
});
it('starts the preferred Case and Evidence reads without waiting for a slow cross-Run summary', async () => {
// 关键断言:导航已提供目标 Case 时,Run/Queue 摘要不能把详情读取串行化。
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
let resolveRun: ((value: Record<string, unknown>) => void) | null = null;
let resolveQueue: ((value: Record<string, unknown>) => void) | null = null;
api.getCase.mockClear();
api.getEvidence.mockClear();
api.getRun.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => { resolveRun = resolve; }));
api.getQueue.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => { resolveQueue = resolve; }));
const pending = review.load('RUN-2', 'CASE-2');
await vi.waitFor(() => expect(api.getCase).toHaveBeenCalledWith('CASE-2'));
await vi.waitFor(() => expect(api.getEvidence).toHaveBeenCalledWith('CASE-2'));
await vi.waitFor(() => expect(review.runLoading.value).toBe(true));
expect(review.activeCase.value?.case_no).toBe('CASE-1');
resolveRun?.({ run_no: 'RUN-2', summary: {}, items: [{ case_no: 'CASE-2', document_id: 2, status: 'draft', issue_count: 0 }] });
resolveQueue?.({ summary: { total: 1, needs_action: 1, processing: 0, completed: 0 }, items: [{ case_no: 'CASE-2', document_id: 2, source_run_no: 'RUN-2', status: 'draft', issue_count: 0, available_actions: [] }] });
await pending;
});
it('keeps the stable workbench on a cross-Run load failure', async () => {
// 关键断言:目标 Run 读取失败时,用户可继续查看上一份稳定工作面,不能退回整页空白。
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
api.getCase.mockResolvedValueOnce(buildCase({ case_no: 'CASE-2', run_no: 'RUN-2' }));
api.getEvidence.mockResolvedValueOnce({ items: [] });
api.getRun.mockImplementationOnce(() => Promise.reject(new Error('target unavailable')));
api.getQueue.mockImplementationOnce(() => Promise.reject(new Error('target unavailable')));
await review.load('RUN-2', 'CASE-2');
expect(review.loadFailed.value).toBe(false);
expect(review.runSwitchFailed.value).toBe(true);
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
expect(review.reviewQueue.value?.items[0]?.case_no).toBe('CASE-1');
expect(review.activeCase.value?.case_no).toBe('CASE-1');
});
it('blocks confirm when build eligibility cannot build', async () => {
const review = useShippingOrderReview();
@@ -828,6 +932,57 @@ describe('useShippingOrderReview build eligibility writes', () => {
vi.useRealTimers();
});
it('refreshes the active Case and queue while post-confirm automation is still active', async () => {
vi.useFakeTimers();
const readyCase = buildCase({
status: 'ready',
draft: {
...buildCase().draft!,
build_eligibility: { can_build: true, status: 'ready', line_projections: [] },
},
});
const runningCase = {
...readyCase,
status: 'confirmed',
confirmed_task_no: 'OT-1',
automation: { status: 'running', phase: 'post_ot_progress' },
};
api.getCase
.mockResolvedValueOnce(readyCase)
.mockResolvedValue(runningCase);
api.getRun.mockResolvedValue({
run_no: 'RUN-1', summary: {},
items: [{ case_no: 'CASE-1', document_id: 1, status: 'confirmed', lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [] }],
});
api.getQueue.mockResolvedValue({
summary: { total: 1, needs_action: 0, processing: 1, completed: 0 },
items: [{ case_no: 'CASE-1', document_id: 1, source_run_no: 'RUN-1', status: 'confirmed', lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [] }],
});
api.getEvidence.mockResolvedValue({ items: [] });
api.getProcessingWorkItem.mockResolvedValue({
work_item_no: 'OT-1', status: 'processing', stage: 'inventory_preparation',
currentGate: { gateCode: 'inventory_preparation', status: 'running' },
});
api.confirmCase.mockResolvedValue({
task_no: 'SN-1', order_task_no: 'OT-1', shipping_notice_no: 'SN-1', idempotent_replay: false,
case: runningCase, auto_progress_started: true,
});
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'WFI-1' });
await review.confirm();
await vi.advanceTimersByTimeAsync(2600);
// 关键断言:活动窗口内同步刷新 Case 与队列,让顶部五阶段读取到后端已推进的通知准备。
expect(api.getCase.mock.calls.length).toBeGreaterThanOrEqual(2);
expect(api.getQueue.mock.calls.length).toBeGreaterThanOrEqual(2);
expect(review.activeCase.value?.confirmed_task_no).toBe('OT-1');
expect(review.reviewQueue.value?.items[0]?.lifecycle_stage).toBe('fulfillment_prep');
review.stopWorkflowProgressPolling();
vi.useRealTimers();
});
it('keeps polling after a recoverable RPA failure so a later callback can refresh the workflow', async () => {
vi.useFakeTimers();
const onWorkflowRefresh = vi.fn();
@@ -3,7 +3,7 @@
* 用途:订单复核工作台 composable,编排 Run/Case/PDF、草稿写入与建单确认。
* 依赖:shipping API review/extraction-run、useShippingProcessingWorkItem、Vue ref/computed、BusinessError。
* 逻辑:按 runNo 加载 Review Run/Case;合成 ShippingReviewProgressContext;
* OT 绑定 Case.order_task_no / Candidate;切换 Case 时清空 activeCase(纯 skeleton,禁止旧值 DOM);
* OT 绑定 Case.order_task_no / Candidate;切换时保留稳定显示壳,目标快照到齐后原子替换;
* 409 REVIEW_DRAFT_VERSION_MISMATCH 冲突处理;build_eligibility 驱动 confirm/reroute;
* 重识别后刷新正式 Run/Case/Gate 投影;PDF Blob 由 ensurePreviewLoaded 按需加载。
*/
@@ -47,6 +47,7 @@ import type {
ShippingOrderReviewLlmAdjudicationPayload,
ShippingOrderReviewLlmSuggestion,
ShippingOrderExtractionRun,
ShippingOrderExtractionLifecycleProgress,
ShippingOrderReviewRun,
ShippingOrderReviewQueue,
ShippingOrderReviewEmailEvidencePreview,
@@ -60,7 +61,6 @@ import { useShippingProcessingWorkItem } from '../shipping/useShippingProcessing
export type ReviewStatusMessage =
| 'superseded'
| 'work_item_closed'
| 'reparse_in_progress'
| 'restored'
| 'draft_version_conflict'
| null;
@@ -304,6 +304,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
const caseProjectionVersion = ref<number | null>(null);
const caseLoadingContext = ref<ShippingOrderReviewCaseLoadingContext | null>(null);
const reviewProgressContext = ref<ShippingReviewProgressContext | null>(null);
/** 当前 Run 的用户态五阶段进度;页面 loading 或尚无 Case 时仍可展示。 */
const extractionLifecycleProgress = ref<ShippingOrderExtractionLifecycleProgress | null>(null);
/** ?? OT ???????????????? */
const authoritativeOrderTaskNo = computed(() => {
const item = reviewProgressContext.value;
@@ -324,11 +326,19 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
enabled: computed(() => Boolean(authoritativeOrderTaskNo.value)),
// 订单处理工作台:旧 progress_version 不得覆盖较新本地投影。
monotonicProgressVersion: true,
// 复核页仅由下方 2.5 秒协调轮询驱动,避免此处额外开启 3 秒定时读取。
continuousPolling: false,
},
);
const versions = ref<ShippingReviewProgressVersion[]>([]);
const statusMessage = ref<ReviewStatusMessage>(null);
const loading = ref(false);
/** 首次进入工作台的页面级加载态;后续 Run 切换不得重新触发整页 loading。 */
const initialLoading = ref(false);
/** Run 数据读取态;供跨 Run 切换保持既有工作台壳时使用。 */
const runLoading = ref(false);
/** 跨 Run 读取失败;有稳定工作台时只显示局部错误,不触发页面失败态。 */
const runSwitchFailed = ref(false);
let initialLoadCompleted = false;
const loadFailed = ref(false);
const saving = ref(false);
const saveFailed = ref(false);
@@ -427,6 +437,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
const tick = async () => {
try {
const run = await getWorkspaceShippingOrderExtractionRun(targetRunNo);
extractionLifecycleProgress.value = run.lifecycle_progress || null;
const normalizedStatus = String(run.status || '').trim();
const synthesized = synthesizeWorkItemFromReviewContext({
reviewRun: reviewRun.value,
@@ -469,6 +480,26 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
}
};
/**
* 自动推进期间同步当前 Case 与生命周期队列。
*
* 核心逻辑:仅复用既有只读 API,且只在当前 Case 未切换时写回;不读证据/PDF,
* 不触发任何 RPA 或 Gate 写操作。正式 OT 的细粒度状态仍由 processing projection 负责。
*/
const refreshActiveAutomationLifecycle = async () => {
const caseNo = String(activeCase.value?.case_no || '').trim();
const runNo = String(reviewRun.value?.run_no || activeCase.value?.run_no || '').trim();
if (!caseNo || !runNo) return;
const [caseSnapshot, queue] = await Promise.all([
getWorkspaceShippingOrderReviewCase(caseNo),
getWorkspaceShippingOrderReviewQueue(runNo),
]);
// Case 切换或重新加载后,旧轮询响应不得覆盖当前工作台。
if (String(activeCase.value?.case_no || '').trim() !== caseNo) return;
applyCaseSnapshot(caseSnapshot);
reviewQueue.value = queue;
};
/**
* ?????????????????
* ???????? OT ?????? ShippingProcessing????? Extraction Run
@@ -486,6 +517,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
// RPA 超时、可重试失败和人工复核都可能被后续回调推进,页面留存期间持续读取 Projection。
const UNIFIED_TERMINAL = new Set(['completed', 'cancelled']);
let lastUnifiedStatus = '';
let lastLifecycleFingerprint = '';
const RUN_TERMINAL = new Set(['completed', 'partially_completed', 'failed', 'cancelled']);
const tick = async () => {
try {
@@ -502,11 +534,25 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
}
if (UNIFIED_TERMINAL.has(unifiedStatus)) {
stopWorkflowProgressPolling();
return;
}
// 顶部五阶段取 Case/Queue 的 lifecycle_entries。仅当 OT 投影的阶段/门禁发生变化
// 时刷新一次,避免每 2.5 秒重复读取队列;不等待该读取,保证终态轮询及时停止。
const lifecycleFingerprint = [
unifiedStatus,
String(shippingProcessingProjection.value?.stage || ''),
String(shippingProcessingProjection.value?.currentGate?.gateCode || ''),
String(shippingProcessingProjection.value?.currentGate?.status || ''),
].join('|');
if (lifecycleFingerprint !== lastLifecycleFingerprint) {
lastLifecycleFingerprint = lifecycleFingerprint;
void refreshActiveAutomationLifecycle();
}
return;
}
if (targetRunNo) {
const run = await getWorkspaceShippingOrderExtractionRun(targetRunNo);
extractionLifecycleProgress.value = run.lifecycle_progress || null;
const synthesized = synthesizeWorkItemFromReviewContext({
reviewRun: reviewRun.value,
activeCase: activeCase.value,
@@ -594,14 +640,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
}
// ?????? Case ?????? superseded????????????
// ?????????????????????????????
if (
activeCase.value?.status === 'reparse_pending'
|| reviewProgressContext.value?.lifecycle_status === 'extracting'
|| reviewProgressContext.value?.lifecycle_status === 'layout_parsing'
) {
statusMessage.value = 'reparse_in_progress';
return;
}
if (isViewingHistoricalVersion.value || activeCase.value?.status === 'superseded') {
statusMessage.value = 'superseded';
return;
@@ -869,59 +907,134 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
const generation = ++caseLoadGeneration;
++intakeParseRequestGeneration;
requestedCaseNo.value = String(preferredCaseNo || '').trim() || null;
loading.value = true;
const isInitialLoad = !initialLoadCompleted && !reviewRun.value;
if (isInitialLoad) initialLoading.value = true;
runLoading.value = true;
runSwitchFailed.value = false;
loadFailed.value = false;
draftConflict.value = null;
saveFailed.value = false;
// [STEP 1] ?????????????????????? WorkflowItem ????? Run ???
contextConversationId = String(options?.conversationId || '').trim();
contextItemNo = String(options?.itemNo || '').trim();
reviewRun.value = null;
activeCase.value = null;
caseProjectionVersion.value = null;
caseLoadingContext.value = null;
reviewProgressContext.value = null;
versions.value = [];
evidence.value = [];
llmSuggestions.value = [];
intakeParseContext.value = null;
intakeParseLoading.value = false;
intakeParseLoadFailed.value = false;
clearPreview();
const hasStableWorkbench = Boolean(reviewRun.value && activeCase.value);
const stableSnapshot = hasStableWorkbench
? {
reviewRun: reviewRun.value,
reviewQueue: reviewQueue.value,
activeCase: activeCase.value,
caseProjectionVersion: caseProjectionVersion.value,
caseLoadingContext: caseLoadingContext.value,
evidence: evidence.value,
llmSuggestions: llmSuggestions.value,
extractionLifecycleProgress: extractionLifecycleProgress.value,
}
: null;
if (!hasStableWorkbench) {
reviewRun.value = null;
activeCase.value = null;
caseProjectionVersion.value = null;
caseLoadingContext.value = null;
reviewProgressContext.value = null;
extractionLifecycleProgress.value = null;
versions.value = [];
evidence.value = [];
llmSuggestions.value = [];
intakeParseContext.value = null;
intakeParseLoading.value = false;
intakeParseLoadFailed.value = false;
clearPreview();
}
try {
const [run, queue] = await Promise.all([
getWorkspaceShippingOrderReviewRun(runNo),
getWorkspaceShippingOrderReviewQueue(runNo),
const runRequest = getWorkspaceShippingOrderReviewRun(runNo);
const queueRequest = getWorkspaceShippingOrderReviewQueue(runNo);
// 路由已明确目标 Case 时,详情读取不应等待较慢的 Run/Queue 摘要;
// 四份数据仍在全部成功后原子提交,避免混合工作面。
const preferredCaseRequest = preferredCaseNo
? Promise.all([
getWorkspaceShippingOrderReviewCase(preferredCaseNo),
getWorkspaceShippingOrderReviewEvidence(preferredCaseNo),
])
: null;
// 已有稳定工作台且路由明确目标 PDF 时,目标详情是用户切换的关键路径;
// Run/Queue 只负责后续更新导航和阶段摘要,不能用其慢投影阻塞当前文件显示。
if (hasStableWorkbench && preferredCaseRequest) {
const [caseSnapshot, caseEvidence] = await preferredCaseRequest;
if (generation !== caseLoadGeneration) return;
applyCaseSnapshot(caseSnapshot);
evidence.value = caseEvidence?.items || [];
clearPreview();
const [run, queue] = await Promise.all([runRequest, queueRequest]);
if (generation !== caseLoadGeneration) return;
reviewRun.value = run;
reviewQueue.value = queue;
extractionLifecycleProgress.value = run.lifecycle_progress || null;
await refreshWorkItemContext(contextConversationId, contextItemNo, {
expectedLoadGeneration: generation,
});
initialLoadCompleted = true;
return;
}
const [run, queue, preferredSnapshot] = await Promise.all([
runRequest,
queueRequest,
preferredCaseRequest,
]);
if (generation !== caseLoadGeneration) return;
// [STREAM] Run 替代不等于其内全部 PDF 替代;当前文件只由队列 Stream 裁决。
const caseNo = preferredCaseNo || queue.items[0]?.case_no || run.items[0]?.case_no;
const [caseSnapshot, caseEvidence] = preferredSnapshot
? preferredSnapshot
: caseNo
? await Promise.all([
getWorkspaceShippingOrderReviewCase(caseNo),
getWorkspaceShippingOrderReviewEvidence(caseNo),
])
: [null, null];
if (generation !== caseLoadGeneration) return;
reviewRun.value = run;
reviewQueue.value = queue;
// [STREAM] Run 替代不等于其内全部 PDF 替代;当前文件只由队列 Stream 裁决。
const caseNo = preferredCaseNo || queue.items[0]?.case_no || run.items[0]?.case_no;
const caseSnapshot = caseNo ? await getWorkspaceShippingOrderReviewCase(caseNo) : null;
if (generation !== caseLoadGeneration) return;
extractionLifecycleProgress.value = run.lifecycle_progress || null;
applyCaseSnapshot(caseSnapshot);
const caseEvidence = caseNo ? await getWorkspaceShippingOrderReviewEvidence(caseNo) : null;
if (generation !== caseLoadGeneration) return;
evidence.value = caseEvidence?.items || [];
// [STEP] ??????? PDF??????????????????????
clearPreview();
await refreshWorkItemContext(contextConversationId, contextItemNo, {
expectedLoadGeneration: generation,
});
initialLoadCompleted = true;
// refreshWorkItemContext ????? ref???????? ref????? load ???????????
} catch {
if (generation !== caseLoadGeneration) return;
loadFailed.value = true;
reviewRun.value = null;
activeCase.value = null;
reviewProgressContext.value = null;
reviewQueue.value = null;
versions.value = [];
statusMessage.value = null;
loadFailed.value = !hasStableWorkbench;
runSwitchFailed.value = hasStableWorkbench;
// 目标 Case 已先行显示时,若其所属 Run/Queue 校准失败,必须整体回退到同一份
// 稳定快照,不能留下“新文件 + 旧导航”的混合业务工作面。
if (stableSnapshot) {
reviewRun.value = stableSnapshot.reviewRun;
reviewQueue.value = stableSnapshot.reviewQueue;
activeCase.value = stableSnapshot.activeCase;
caseProjectionVersion.value = stableSnapshot.caseProjectionVersion;
caseLoadingContext.value = stableSnapshot.caseLoadingContext;
evidence.value = stableSnapshot.evidence;
llmSuggestions.value = stableSnapshot.llmSuggestions;
extractionLifecycleProgress.value = stableSnapshot.extractionLifecycleProgress;
}
if (!hasStableWorkbench) {
reviewRun.value = null;
activeCase.value = null;
reviewProgressContext.value = null;
extractionLifecycleProgress.value = null;
reviewQueue.value = null;
versions.value = [];
statusMessage.value = null;
}
} finally {
if (generation !== caseLoadGeneration) return;
loading.value = false;
if (isInitialLoad) initialLoading.value = false;
runLoading.value = false;
}
};
@@ -1269,7 +1382,10 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
caseProjectionVersion.value = Date.now();
caseLoadingContext.value = null;
draftConflict.value = null;
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
if (reviewRun.value) {
reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
extractionLifecycleProgress.value = reviewRun.value.lifecycle_progress || null;
}
await refreshWorkItemContext();
// [UI-02] ?????? OT???? Notice task_no / ??? workflow_item_id ??????
const orderTaskNo = String(
@@ -1331,7 +1447,10 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
try {
const response = await reparseWorkspaceShippingOrderReviewDocument(activeCase.value.case_no, reason, comment);
applyCaseSnapshot(await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no));
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
if (reviewRun.value) {
reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
extractionLifecycleProgress.value = reviewRun.value.lifecycle_progress || null;
}
await refreshWorkItemContext();
startReparseCaseRefreshPolling(response.run.run_no);
return response;
@@ -1458,6 +1577,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
caseProjectionVersion,
caseLoadingContext,
reviewProgressContext,
extractionLifecycleProgress,
shippingProcessingProjection,
authoritativeOrderTaskNo,
shippingProcessingLoading,
@@ -1497,7 +1617,9 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
clearPreview,
showWorkflowProgress,
workflowProgressPolling,
loading,
initialLoading,
runLoading,
runSwitchFailed,
loadFailed,
caseSwitchLoading,
caseSwitchFailed,
@@ -6,6 +6,7 @@
*/
import {
downloadWorkspaceShippingExportArchive as requestShippingExportArchive,
workspaceShippingNoticeExportUrl,
workspaceShippingExportUrl,
workspaceShippingInventoryFileUrl,
workspaceShippingLineInventoryFileUrl,
@@ -16,6 +17,14 @@ export async function downloadWorkspaceShippingExcelFile(taskId: string): Promis
await downloadWorkspaceShippingFile(workspaceShippingExportUrl(taskId), `${taskId}.xlsx`);
}
/**
* 按发货通知单号下载其唯一正式 Excel。
* 新货代操作只能传 business_no;task_no 下载函数仅保留给尚未迁移的非货代工作流。
*/
export async function downloadWorkspaceShippingNoticeExcelFile(businessNo: string): Promise<void> {
await downloadWorkspaceShippingFile(workspaceShippingNoticeExportUrl(businessNo), `${businessNo}.xlsx`);
}
/**
* 下载当前任务活动关联的库存快照。
* 核心逻辑:浏览器只发起受控 URL;后端复核任务归属、active link 与物理文件,不按库存源猜测文件。
@@ -64,3 +73,25 @@ async function downloadWorkspaceShippingFile(url: string, fallbackName: string):
export const downloadWorkspaceShippingExportArchive = (payload: {
task_nos?: string[];
}) => requestShippingExportArchive(payload);
/** 按多个 business_no 下载各自唯一 Excel 的 ZIP。 */
export async function downloadWorkspaceShippingNoticeExportArchive(businessNos: string[]): Promise<void> {
const response = await fetch('/api/workspace/shipping-notices/batch/export', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ business_nos: businessNos }),
});
if (!response.ok) {
const body = await response.json().catch(() => ({}));
throw new Error((body as { error?: string; message?: string }).error || response.statusText);
}
const blob = await response.blob();
const objectUrl = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = objectUrl;
anchor.download = 'shipping_notices.zip';
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
URL.revokeObjectURL(objectUrl);
}
@@ -33,7 +33,7 @@ export type ShippingProcessingWorkItemTypeArg = 'order_intake' | 'order_task';
*
* @param workItemType - order_intake | order_task
* @param workItemNo - Intake 编号或 OT 编号(MaybeRef)
* @param options.enabled - 是否启用;options.pollMs - 轮询间隔;
* @param options.enabled - 是否启用;options.pollMs - 轮询间隔;options.continuousPolling - 是否由本 composable 持续轮询;
* options.monotonicProgressVersion - 仅工作台:旧 progress_version 不覆盖本地
* @returns projection / loading / error / refresh / stop
*/
@@ -43,6 +43,8 @@ export function useShippingProcessingWorkItem(
options: {
enabled?: MaybeRefOrGetter<boolean>;
pollMs?: number;
/** false 时仅由调用方显式 refresh;用于已有页面级协调轮询的工作台。 */
continuousPolling?: boolean;
/** 仅订单处理工作台开启;任务中心保持默认 false。 */
monotonicProgressVersion?: boolean;
} = {},
@@ -61,6 +63,7 @@ export function useShippingProcessingWorkItem(
let stopped = false;
let refreshInFlight: { no: string; promise: Promise<void> } | null = null;
const pollMs = options.pollMs ?? DEFAULT_POLL_MS;
const continuousPolling = options.continuousPolling !== false;
const monotonic = Boolean(options.monotonicProgressVersion);
/**
@@ -112,7 +115,7 @@ export function useShippingProcessingWorkItem(
error.value = null;
clearTimer();
const next = projection.value;
if (next && !TERMINAL_STATUSES.has(next.status) && !stopped) {
if (continuousPolling && next && !TERMINAL_STATUSES.has(next.status) && !stopped) {
timer = window.setTimeout(() => {
void refresh();
}, pollMs);
@@ -128,7 +131,7 @@ export function useShippingProcessingWorkItem(
}
error.value = err instanceof BusinessError ? err.message : 'network_recoverable';
clearTimer();
if (!stopped) {
if (continuousPolling && !stopped) {
timer = window.setTimeout(() => {
void refresh();
}, pollMs);
@@ -90,6 +90,7 @@ export type ShippingProcessingActionIntent =
| 'open_inventory_match_review'
| 'open_shortage_review'
| 'upload_inventory_file'
| 'reload_inventory_result'
| 'retry_inventory_preparation'
| 'retry_inventory_matching'
| 'retry_parse'
@@ -824,9 +825,22 @@ export interface ShippingInventorySnapshot {
export interface ShippingTaskSummary {
id: number;
task_no: string;
shipping_case_id?: number | null;
case_no?: string | null;
business_no?: string | null;
/** 通知单列表只读行摘要;库存数据由后端当前匹配事实投影,前端不得自行计算。 */
notice_line_summary?: Array<{
line_no?: string | number | null;
part_number?: string | null;
customer_part_number?: string | null;
reservation_id?: string | null;
shipment_qty?: string | null;
available_qty?: string | null;
shortage_qty?: string | null;
inventory_status?: string | null;
}>;
artifact_summary?: {
export_file_name?: string | null;
export_file_path?: string | null;
} | null;
source_type: string;
source_file_name?: string | null;
source_file_type?: string | null;
@@ -1053,6 +1067,7 @@ export type ShippingProcessGateActionCode =
| 'retry_with_latest_rules'
| 'recheck_freeze_readiness'
| 'retry_task_creation'
| 'reload_inventory_result'
| 'retry_inventory_preparation'
| 'poll_inventory_preparation'
| 'upload_inventory_file'
@@ -1599,6 +1614,27 @@ export interface ShippingUiStateEventPayload {
source?: string;
}
/** 订单工作台货代上传区的 Notice 聚合行;一行对应一个 business_no 与唯一 Excel。 */
export interface ShippingFreightNoticeGroup {
business_no: string;
po_number: string | null;
upload_status?: string | null;
export_file_name?: string | null;
available_actions?: string[];
lines: Array<{
line_no?: string | number | null;
part_number?: string | null;
reservation_id?: string | null;
shipment_qty?: string | number | null;
}>;
}
export interface ShippingFreightNoticeGroupsResponse {
po_number: string | null;
items: ShippingFreightNoticeGroup[];
reason?: 'po_missing' | 'no_business_notice' | string | null;
}
export interface ShippingInventoryUploadResponse {
status: string;
message?: string;
@@ -1811,6 +1847,19 @@ export interface ShippingOrderExtractionRunSummary {
opened_existing_documents?: number;
}
/** 复核工作台直接消费的 Run 级五阶段进度;字段由后端 Projection 裁决。 */
export interface ShippingOrderExtractionLifecycleProgress {
lifecycle_stage: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete' | string;
lifecycle_status: 'running' | 'waiting' | 'failed' | 'cancelled' | 'completed' | string;
current_step_code?: string | null;
current_step_i18n_key?: string | null;
completed_step_codes: string[];
last_activity_at?: string | null;
health_status: 'normal' | 'attention' | 'failed' | string;
blocking_reason_i18n_key?: string | null;
primary_action?: string | null;
}
/**
* 会话恢复和任务中心列表的固定成本摘要;完整文档、Case、Gate 投影必须按 Run 编号单独读取。
*/
@@ -1864,6 +1913,7 @@ export interface ShippingOrderExtractionDocumentResult {
queue_position?: number | null;
elapsed_seconds?: number | null;
health_tips?: ShippingOrderExtractionHealthTip[];
lifecycle_progress?: ShippingOrderExtractionLifecycleProgress | null;
cancellation?: ShippingOrderExtractionCancellation | null;
activity_version?: number | null;
selection_batch?: number | null;
@@ -1975,6 +2025,8 @@ export interface ShippingOrderExtractionRun {
primary_notice?: string | null;
user_visible_stage?: ShippingOrderExtractionUserVisibleStage | null;
health_tips?: ShippingOrderExtractionHealthTip[];
/** Run 解析中或尚无 Case 时的后端用户态进度。 */
lifecycle_progress?: ShippingOrderExtractionLifecycleProgress | null;
cancellation?: ShippingOrderExtractionCancellation | null;
progress_version?: number | null;
last_activity_at?: string | null;
@@ -2245,6 +2297,8 @@ export interface ShippingOrderReviewRun {
superseded_by_run_no?: string | null;
summary: Record<string, number>;
items: ShippingOrderReviewCaseSummary[];
/** Run 解析中或尚无 Case 时的后端用户态进度。 */
lifecycle_progress?: ShippingOrderExtractionLifecycleProgress | null;
}
export interface ShippingOrderReviewQueue {
@@ -2480,10 +2534,6 @@ export interface ShippingOrderReviewFieldConflictOption {
evidence_role?: 'primary_pdf' | 'auxiliary' | 'context' | string | null;
/** PDF_PRIORITY_EVIDENCE_RANKS 档位名。 */
evidence_rank?: string | null;
/** Vendor Comments 三来源专属:字段来源种类(header_region / table_column / vendor_comments)。 */
vc_source_kind?: string | null;
/** Vendor Comments 三来源专属:来源种类的本地化展示标签。 */
vc_source_kind_label?: string | null;
/** 结构化文档证据或兼容字符串,可跳转证据查看器定位对应区域。 */
evidence_ref?: Record<string, unknown> | string | null;
}
@@ -2502,18 +2552,6 @@ export interface ShippingOrderReviewFieldConflict {
observation_ids?: string[];
/** 后端给出的下一步恢复动作;例如 reparse_current_pdf。 */
recovery_action?: string | null;
/** Vendor Comments 三来源专属:true 表示该冲突来自 VC 三来源合并,conflict_key 以 vc: 开头。 */
vc_kind?: boolean | null;
/** Vendor Comments 三来源专属:细因码(vc_source_conflict_unresolved / vc_source_format_invalid / vc_source_region_unbound)。 */
vc_reason?: string | null;
/** Vendor Comments 三来源专属:冲突组稳定键(scope:field_code:line_no),裁决时写回 merged_candidates 使用。 */
vc_conflict_group_key?: string | null;
/** Vendor Comments 三来源专属:只读诊断,展示 resolution / decision_status / format_valid。 */
vc_detail?: {
resolution?: string | null;
decision_status?: string | null;
format_valid?: boolean | null;
} | null;
}
export interface ShippingOrderReviewCase {
@@ -3039,6 +3077,7 @@ export interface ShippingOrderReviewLineFulfillmentDecision {
part_number?: string | null;
task_id?: number | null;
wave_no?: number | null;
notice_no?: string | null;
created_at?: string | null;
}
@@ -5,7 +5,7 @@
* 逻辑:标准模式无对话上下文、无常驻 PDF 列;底栏无「确认并创建任务」;
* 正式 OT / STP 对象级重试走 /retry 或 STP retry;敏感面板审计失败不打开。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
import { computed, nextTick, ref } from 'vue';
import { flushPromises, mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
@@ -16,21 +16,34 @@ import { CHAT_PAGE_KEY } from '@/features/chat/composables/chat.context';
import {
auditWorkspaceShippingOrderReviewEligibilityDetails,
auditWorkspaceShippingOrderReviewVersionHistory,
getWorkspaceShippingFreightNoticeGroups,
getWorkspaceShippingTask,
decideWorkspaceShippingOrderReviewLineFulfillment,
waveWorkspaceShippingOrderReviewLineFulfillment,
retryWorkspaceShippingOrderStpAutoCreate,
retryShippingNoticeIntake,
} from '@/features/chat/api/shipping.api';
const { batchConfirmFreightMock, batchRpaFreightMock, downloadFreightArchiveMock } = vi.hoisted(() => ({
batchConfirmFreightMock: vi.fn().mockResolvedValue({ results: [] }),
batchRpaFreightMock: vi.fn().mockResolvedValue({ results: [] }),
downloadFreightArchiveMock: vi.fn().mockResolvedValue(undefined),
}));
const { downloadWorkspaceShippingLineInventoryFileMock } = vi.hoisted(() => ({
downloadWorkspaceShippingLineInventoryFileMock: vi.fn().mockResolvedValue(undefined),
}));
const { downloadWorkspaceShippingExcelFileMock } = vi.hoisted(() => ({
downloadWorkspaceShippingExcelFileMock: vi.fn().mockResolvedValue(undefined),
}));
const { downloadWorkspaceShippingNoticeExcelFileMock } = vi.hoisted(() => ({
downloadWorkspaceShippingNoticeExcelFileMock: vi.fn().mockResolvedValue(undefined),
}));
vi.mock('@/features/chat/shipping/shippingDownload', () => ({
downloadWorkspaceShippingLineInventoryFile: downloadWorkspaceShippingLineInventoryFileMock,
downloadWorkspaceShippingNoticeExcelFile: downloadWorkspaceShippingNoticeExcelFileMock,
downloadWorkspaceShippingNoticeExportArchive: downloadFreightArchiveMock,
}));
vi.mock('@/features/workspace/api/shipping-tasks.api', () => ({
downloadWorkspaceShippingExcelFile: downloadWorkspaceShippingExcelFileMock,
@@ -44,10 +57,16 @@ const ensureIntakeParseContextLoaded = vi.fn().mockResolvedValue(true);
const confirmMock = vi.fn();
const reloadLatestDraftMock = vi.fn().mockResolvedValue(undefined);
const refreshShippingProcessingMock = vi.fn().mockResolvedValue(undefined);
const startWorkflowProgressPollingMock = vi.fn();
const patchLineMock = vi.fn().mockResolvedValue(undefined);
const { submitProcessGatePrimaryActionMock } = vi.hoisted(() => ({
submitProcessGatePrimaryActionMock: vi.fn().mockResolvedValue({ outcome: 'submitted' }),
}));
/**
* 本文件每个用例均挂载完整工作台;统一卸载,避免跨用例残留 watch/router 响应式副作用。
*/
const mountedWrappers: Array<{ unmount: () => void }> = [];
const { postFormalGateActionMock } = vi.hoisted(() => ({
postFormalGateActionMock: vi.fn().mockResolvedValue({}),
}));
@@ -105,12 +124,20 @@ const reviewQueue = ref({
});
const workItem = ref<Record<string, any> | null>(null);
const reviewProgressContext = ref<Record<string, any> | null>(null);
/** Run 解析中的用户态进度;与真实 composable 返回契约保持一致。 */
const extractionLifecycleProgress = ref<Record<string, any> | null>(null);
/** 旧重解析横幅状态;回归用例确认它不再驱动独立黄色进度提示。 */
const statusMessage = ref<string | null>(null);
const runLoading = ref(false);
const runSwitchFailed = ref(false);
/** 与 activeCase 同源共享,供断言 Progress 优先阶段源。 */
const shippingProcessingProjection = ref<Record<string, any> | null>(null);
/** 正式任务投影的请求中状态;用于覆盖 Case 先到、Projection 后到的过渡窗口。 */
const shippingProcessingLoading = ref(false);
const intakeParseContext = ref<Record<string, any> | null>(null);
const requestedCaseNo = ref<string | null>(null);
const reviewEditable = ref(true);
const reviewFormalEditable = ref(false);
/** 每个用例必须从独立的 Case 图快照开始,避免嵌套 schema/draft 被浅拷贝污染。 */
function createActiveCaseFixture() {
@@ -170,6 +197,7 @@ vi.mock('@/features/chat/api/shipping.api', async (importOriginal) => {
auditWorkspaceShippingOrderReviewVersionHistory: vi.fn().mockResolvedValue({ audited: true, case_no: 'CASE-1' }),
auditWorkspaceShippingOrderReviewEligibilityDetails: vi.fn().mockResolvedValue({ audited: true, case_no: 'CASE-1' }),
decideWorkspaceShippingOrderReviewLineFulfillment: vi.fn().mockResolvedValue({ status: 'ok' }),
waveWorkspaceShippingOrderReviewLineFulfillment: vi.fn().mockResolvedValue({ status: 'ok' }),
retryWorkspaceShippingOrderStpAutoCreate: vi.fn().mockResolvedValue({
status: 'queued',
job_id: 901,
@@ -180,6 +208,9 @@ vi.mock('@/features/chat/api/shipping.api', async (importOriginal) => {
task_no: 'SN-MOCK',
status: 'created',
}),
getWorkspaceShippingFreightNoticeGroups: vi.fn().mockResolvedValue({ items: [] }),
batchConfirmWorkspaceShippingNoticesUploaded: (...args: unknown[]) => batchConfirmFreightMock(...args),
batchStartWorkspaceShippingNoticeRpaUpload: (...args: unknown[]) => batchRpaFreightMock(...args),
};
});
@@ -209,6 +240,7 @@ function createReviewComposableMock() {
caseProjectionVersion: ref(1),
caseLoadingContext: ref(null),
reviewProgressContext,
extractionLifecycleProgress,
workItem,
authoritativeOrderTaskNo: computed(() => {
const no = String(reviewProgressContext.value?.user_task_no || '').trim();
@@ -216,7 +248,7 @@ function createReviewComposableMock() {
return no;
}),
versions: ref([]),
statusMessage: ref(null),
statusMessage,
draftConflict: ref(null),
draftConflictDiffLines: ref([]),
buildEligibility: ref({ can_build: true, issues: [], lines: [] }),
@@ -224,7 +256,9 @@ function createReviewComposableMock() {
routingRecoveryLines: ref([]),
isViewingHistoricalVersion: computed(() => false),
isReadOnly: computed(() => false),
loading: ref(false),
initialLoading: ref(false),
runLoading,
runSwitchFailed,
loadFailed: ref(false),
caseSwitchLoading: ref(false),
caseSwitchFailed: ref(false),
@@ -281,13 +315,14 @@ function createReviewComposableMock() {
clearEvidenceDrawerFocus: vi.fn(),
requestSuggestion: vi.fn(),
decideSuggestion: vi.fn(),
editable: computed(() => true),
formalEditable: computed(() => false),
editable: computed(() => reviewEditable.value),
formalEditable: computed(() => reviewFormalEditable.value),
canEditFormalFields: computed(() => false),
isFieldEditable: () => true,
isWorkItemClosed: computed(() => false),
showWorkflowProgress: computed(() => false),
workflowProgressPolling: computed(() => false),
startWorkflowProgressPolling: startWorkflowProgressPollingMock,
shippingProcessingProjection,
shippingProcessingLoading,
shippingProcessingError: ref(null),
@@ -604,6 +639,7 @@ async function mountView(query: Record<string, string> = {}) {
lifecycle: {
navigation: '订单生命周期阶段',
current: '当前可处理',
processing: '处理中',
prerequisite: '请先完成当前阶段',
stages: {
intake_parse: '接收解析',
@@ -642,6 +678,10 @@ async function mountView(query: Record<string, string> = {}) {
stageLabel: {
waiting_system_start: '等待系统启动',
},
progress: {
step: { profile_matching: '正在匹配订单模板' },
lifecycleReason: { processing_slow: '当前步骤耗时较长,系统仍在继续。' },
},
},
shippingSessionWorkItem: {
versionLabel: 'V{version}',
@@ -676,6 +716,7 @@ async function mountView(query: Record<string, string> = {}) {
[CHAT_PAGE_KEY as symbol]: {
conversationId: 'conv-1',
messages: [],
bumpWorkflowRefresh: vi.fn(),
},
},
stubs: {
@@ -693,6 +734,7 @@ async function mountView(query: Record<string, string> = {}) {
},
},
});
mountedWrappers.push(wrapper);
await flushPromises();
return wrapper;
}
@@ -700,21 +742,79 @@ async function mountView(query: Record<string, string> = {}) {
/** 将共享 Case fixture 恢复为可编辑草稿,避免跨用例污染确认恢复态。 */
function resetActiveCaseFixture() {
activeCase.value = createActiveCaseFixture();
reviewRun.value = {
run_no: 'RUN-1',
items: [{
case_no: 'CASE-1', document_id: 1, file_name: 'po.pdf', status: 'draft',
issue_count: 0, available_actions: ['validate', 'confirm'],
}],
};
requestedCaseNo.value = null;
shippingProcessingProjection.value = null;
shippingProcessingLoading.value = false;
intakeParseContext.value = null;
extractionLifecycleProgress.value = null;
statusMessage.value = null;
runLoading.value = false;
runSwitchFailed.value = false;
}
describe('ShippingOrderReviewView layout phase 1', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useRealTimers();
ensureIntakeParseContextLoaded.mockResolvedValue(true);
resetActiveCaseFixture();
reviewEditable.value = true;
reviewFormalEditable.value = false;
workItem.value = null;
reviewProgressContext.value = null;
});
afterEach(() => {
while (mountedWrappers.length) {
mountedWrappers.pop()?.unmount();
}
vi.useRealTimers();
});
it('puts customer PO line first and excludes internal line number and inventory source from the main table', async () => {
activeCase.value = {
...activeCase.value,
schema: {
...activeCase.value.schema,
fields: [
...activeCase.value.schema.fields,
{ field_id: 'fld-line-no', field_code: 'line_no', display_name: '内部项次', scope: 'line', value_type: 'string', required: true, options: [] },
{ field_id: 'fld-customer-po-line', field_code: 'customer_po_line_no', display_name: '客户 PO 项次', scope: 'line', value_type: 'string', required: true, options: [] },
{ field_id: 'fld-part-number', field_code: 'part_number', display_name: '料号', scope: 'line', value_type: 'string', required: true, options: [] },
],
},
draft: {
...activeCase.value.draft,
lines: [{
line_key: 'LINE-1',
values: {
'fld-line-no': { value: '10' },
'fld-customer-po-line': { value: '00010' },
'fld-part-number': { value: 'PN-ONE' },
'fld-inventory-source-hint': { value: 'DBS' },
},
machine_fields: [],
}],
},
};
const wrapper = await mountView();
const headers = wrapper.find('[data-testid="review-lines-scroll"]').findAll('th').map((item) => item.text());
// 关键断言:业务主键首列,内部项次和库存源线索不挤占默认主表宽度。
expect(headers.slice(0, 3)).toEqual(['#', '客户 PO 项次 *', '料号 *']);
expect(headers).not.toContain('内部项次 *');
expect(headers).not.toContain('库存源');
expect(wrapper.find('[data-testid="review-line-inventory-source"]').exists()).toBe(false);
});
it('keeps the requested replacement Case when the loaded Run updates the URL', async () => {
// 关键断言:新版 Run 先到而旧 URL Case 仍在时,不能拼出 RUN-NEW + CASE-OLD。
const wrapper = await mountView({ case_no: 'CASE-OLD' });
@@ -729,6 +829,50 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect((wrapper.vm as any).$route.query.case_no).toBe('CASE-NEW');
});
it('shows the five-stage Run progress and current parsing step before a Case is available', async () => {
activeCase.value = null as any;
reviewRun.value = { run_no: 'RUN-PARSING', items: [] };
extractionLifecycleProgress.value = {
lifecycle_stage: 'intake_parse', lifecycle_status: 'running',
current_step_i18n_key: 'chat.shippingProcessing.progress.step.profile_matching',
completed_step_codes: ['layout_parsing_completed'], health_status: 'normal',
};
const wrapper = await mountView();
expect(wrapper.get('[data-testid="review-run-lifecycle-progress"]').exists()).toBe(true);
expect(wrapper.get('[data-testid="review-run-lifecycle-current-step"]').text()).toContain('正在匹配订单模板');
expect(wrapper.find('[data-testid="review-lifecycle-stage-intake_parse"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-lifecycle-stage-upload_complete"]').exists()).toBe(true);
});
it('keeps the compact Run progress visible with a stable stalled reason', async () => {
activeCase.value = null as any;
reviewRun.value = { run_no: 'RUN-STALLED', items: [] };
extractionLifecycleProgress.value = {
lifecycle_stage: 'intake_parse', lifecycle_status: 'running',
current_step_i18n_key: 'chat.shippingProcessing.progress.step.profile_matching',
blocking_reason_i18n_key: 'chat.shippingProcessing.progress.lifecycleReason.processing_slow',
completed_step_codes: [], health_status: 'attention',
};
const wrapper = await mountView();
expect(wrapper.get('[data-testid="review-run-lifecycle-current-step"]').text()).toContain('当前步骤耗时较长');
});
it('uses the lifecycle progress below navigation instead of a legacy yellow reparse banner', async () => {
extractionLifecycleProgress.value = {
lifecycle_stage: 'intake_parse', lifecycle_status: 'running',
current_step_i18n_key: 'chat.shippingProcessing.progress.step.profile_matching',
completed_step_codes: ['layout_parsing_completed'], health_status: 'normal',
};
statusMessage.value = 'reparse_in_progress';
const wrapper = await mountView();
// 关键断言:重解析不再拥有第二条黄色横幅;唯一进度紧跟五阶段导航。
expect(wrapper.find('[data-testid="review-status-banner"]').exists()).toBe(false);
expect(wrapper.findAll('[data-testid="review-run-lifecycle-progress"]')).toHaveLength(1);
expect(wrapper.get('[data-testid="review-run-lifecycle-progress"]').text()).toContain('正在匹配订单模板');
});
it('loads a cross-Run file once through the route watcher', async () => {
const originalQueue = reviewQueue.value;
try {
@@ -759,6 +903,47 @@ describe('ShippingOrderReviewView layout phase 1', () => {
}
});
it('keeps old workbench content in place and shows only a non-layout-shifting loading indicator while a cross-Run target is loading', async () => {
// 关键断言:跨 Run 不能插入大块 skeleton 把旧内容推离视口;仅允许无布局占位的轻提示。
runLoading.value = true;
const wrapper = await mountView();
const shell = wrapper.get('[data-testid="review-case-workbench-shell"]');
expect(wrapper.find('[data-testid="review-workbench-scroll"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-case-switch-loading"]').exists()).toBe(false);
expect(wrapper.get('[data-testid="review-case-switch-indicator"]').exists()).toBe(true);
expect(shell.attributes('aria-busy')).toBe('true');
expect(shell.classes()).toContain('pointer-events-none');
expect((wrapper.vm as any).workbenchActionsExecutable).toBe(false);
});
it('does not read freight Notice groups while the selected file is outside freight upload', async () => {
// 关键断言:货代 Notice 聚合只服务货代上传面,不能加入普通文件切换关键路径。
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_no: 'SN-NOTICE-PREP', confirmed_task_id: 91, has_formal_ot: true,
};
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-NOTICE-PREP', status: 'processing', lines: [], events: [],
ui_state: { lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [], actions: { primary: null, secondary: [] } },
} as any);
await mountView({ lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
expect(taskApi.getWorkspaceShippingFreightNoticeGroups).not.toHaveBeenCalled();
});
it('keeps the workbench shell visible with a local retry state when cross-Run loading fails', async () => {
// 关键断言:跨 Run 失败不能进入页面级 unavailable 分支,旧文件仍可见且可重试。
runSwitchFailed.value = true;
const wrapper = await mountView();
expect(wrapper.find('[data-testid="review-workbench-scroll"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-order-review-load-failed"]').exists()).toBe(false);
expect(wrapper.get('[data-testid="review-run-switch-failed"]').exists()).toBe(true);
});
it('uses the current-task card as the only Gate action entry for every formal-OT Gate', async () => {
activeCase.value = {
...activeCase.value,
@@ -806,7 +991,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.find('[data-testid="mock-process-gate"]').exists()).toBe(false);
});
it('submits a server-authorized Gate action from the current-task card without an action-code alias', async () => {
it('does not expose Excel regeneration from the current-task card', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed', has_formal_ot: true, task_missing: false,
@@ -858,19 +1043,10 @@ describe('ShippingOrderReviewView layout phase 1', () => {
const wrapper = await mountView();
await flushPromises();
await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click');
await flushPromises();
// 关键断言:旧 Projection 的 regenerate_excel 不可执行;正式任务的原始动作码
// 只委托统一 Gate 执行器,由其按后端版本与授权再次校验。
expect(submitProcessGatePrimaryActionMock).toHaveBeenCalledWith(
expect.objectContaining({
execution_no: 'EXEC-EXCEL-1',
current_blocking_gate: expect.objectContaining({ gate_code: 'artifact_generation' }),
}),
{ actionCode: 'regenerate_excel_artifact' },
);
// 关键断言:Excel Artifact 属于发货通知单对象,右侧任务摘要不得提供写入口。
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
expect(postFormalGateActionMock).not.toHaveBeenCalled();
expect(submitProcessGatePrimaryActionMock).not.toHaveBeenCalled();
});
it('does not submit an action merely because its code has a Gate-like prefix', async () => {
@@ -1461,6 +1637,86 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(orderFooter.text()).toContain('提交订单');
});
it('switches the workbench to the backend current stage and marks it processing', async () => {
const originalQueue = reviewQueue.value;
try {
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0],
lifecycle_stage: 'order_review',
lifecycle_entries: [
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
}],
};
const wrapper = await mountView({ lifecycle_stage: 'order_review' });
shippingProcessingProjection.value = {
stage: 'inventory_preparation', status: 'processing',
uiState: {
status: 'running', lifecycleStage: 'fulfillment_prep', lifecycleEntries: [],
primary_action: null, secondary_actions: [],
},
};
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0],
lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
}],
};
await flushPromises();
// 关键断言:后端已推进时,仍停在旧当前阶段的页面必须自动进入新工作面并标注处理中。
expect((wrapper.vm as any).$router.currentRoute.value.query.lifecycle_stage).toBe('fulfillment_prep');
expect(wrapper.get('[data-testid="review-lifecycle-stage-fulfillment_prep"]').attributes('data-processing')).toBe('1');
} finally {
reviewQueue.value = originalQueue;
shippingProcessingProjection.value = null;
}
});
it('keeps a manually selected completed stage after the backend has already advanced', async () => {
const originalQueue = reviewQueue.value;
try {
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0],
lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
}],
};
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
await wrapper.get('[data-testid="review-lifecycle-stage-order_review"]').findAll('button')[1].trigger('click');
await flushPromises();
// 后端并未再次推进时,主动回看订单复核必须保持该工作面,不能被 watcher 改回通知准备。
expect((wrapper.vm as { $route: { query: Record<string, string> } }).$route.query.lifecycle_stage)
.toBe('order_review');
} finally {
reviewQueue.value = originalQueue;
}
});
it('does not request intake context when its lifecycle entry is missing or unavailable', async () => {
shippingProcessingProjection.value = {
uiState: {
@@ -1643,7 +1899,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(messageMocks.warning).not.toHaveBeenCalledWith('处理结果尚未生成');
});
it('uses case line fulfillment as a read-only fallback when formal preparation rows are temporarily empty', async () => {
it('normalizes Decimal quantity display in the case fallback while formal preparation rows are temporarily empty', async () => {
const taskApi = await import('@/features/chat/api/shipping.api');
// 正式任务详情延迟/失败不能阻塞已由 Case 投影下发的只读库存匹配事实。
vi.mocked(taskApi.getWorkspaceShippingTask).mockRejectedValue(new Error('detail unavailable'));
@@ -1656,7 +1912,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
line_fulfillment: {
lines: [{
line_key: 'line-1', reservation_id: 'RSV-FALLBACK', part_number: 'PN-FALLBACK',
required_qty: '8', available_qty: '5', shortage_qty: '3', inventory_source_code: 'DBS_DUB',
required_qty: '8.0', available_qty: '5.0', shortage_qty: '3.0', inventory_source_code: 'DBS_DUB',
}],
},
};
@@ -1674,7 +1930,9 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text()).toContain('RSV-FALLBACK');
expect(wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text()).toContain('PN-FALLBACK');
expect(wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text()).toContain('3');
const preparationText = wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text();
expect(preparationText).toContain('3');
expect(preparationText).not.toContain('3.0');
expect(wrapper.find('[data-testid="review-fulfillment-prep-workspace"]').exists()).toBe(true);
expect(messageMocks.warning).not.toHaveBeenCalledWith('处理结果尚未生成');
// 通知准备工作区必须属于五阶段导航的下方主区,不能仍停留在导航之前的状态摘要区。
@@ -1712,6 +1970,14 @@ describe('ShippingOrderReviewView layout phase 1', () => {
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-FROZEN', status: 'processing', lines: [], events: [],
ui_state: {
process_gate: {
execution_no: 'EXEC-FROZEN-LINE',
current_blocking_gate: { gate_code: 'inventory_preparation', status: 'blocked_retryable' },
},
actions: {
primary: { code: 'retry_inventory_preparation', enabled: true, dispatch: 'mutation' },
secondary: [],
},
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
stage_context: {
preparation: {
@@ -1735,6 +2001,12 @@ describe('ShippingOrderReviewView layout phase 1', () => {
// 关键断言:订单基线列和库存事实合为唯一行级工作表,库存源不得退化为任务级 CRANE。
const workspace = wrapper.get('[data-testid="review-fulfillment-prep-workspace"]');
// 关键交互断言:明细在窄视口保持横向可读,行级操作列固定在右侧。
expect(workspace.classes()).toContain('review-fulfillment-prep-workspace');
expect(workspace.classes()).toContain('overflow-x-auto');
expect(workspace.get('table').classes()).toContain('review-fulfillment-prep-table');
expect(workspace.get('thead th:last-child').classes()).toContain('review-fulfillment-sticky-action-head');
expect(workspace.get('tbody tr:first-child td:last-child').classes()).toContain('review-fulfillment-sticky-action-cell');
expect(workspace.text()).toContain('RSV-FROZEN');
expect(workspace.text()).toContain('PN-FROZEN');
expect(workspace.text()).toContain('DBS');
@@ -1756,6 +2028,8 @@ describe('ShippingOrderReviewView layout phase 1', () => {
payload: { line_key: 'line-frozen' },
}),
);
// Gate 恢复受理后立即启动五阶段轮询,不依赖浏览器手动刷新。
expect(startWorkflowProgressPollingMock).toHaveBeenCalledTimes(1);
await wrapper.get('[data-testid="review-fulfillment-line-release-line-frozen"]').trigger('click');
expect(wrapper.get('[data-testid="review-release-inventory-dialog"]').text()).toContain('ODM ID');
expect(wrapper.get('[data-testid="review-release-inventory-dialog"]').text()).toContain('ODM-001');
@@ -1768,6 +2042,62 @@ describe('ShippingOrderReviewView layout phase 1', () => {
reason: '客户确认分批发货',
release_field_values: { '102': 'A-01' },
}));
// 放行写成功后立即释放弹窗;后续读取不得阻塞用户确认按钮。
expect(wrapper.find('[data-testid="review-release-inventory-dialog"]').exists()).toBe(false);
expect(startWorkflowProgressPollingMock).toHaveBeenCalledTimes(2);
});
it('keeps the manual notice-generation entry in the main workspace for an editable formal task', async () => {
const taskApi = await import('@/features/chat/api/shipping.api');
reviewEditable.value = false;
reviewFormalEditable.value = true;
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_id: 904, confirmed_task_no: 'SN-READY', has_formal_ot: true,
line_fulfillment: {
lines: [{
line_key: 'line-ready', line_status: 'pending_decision', can_fulfill_complete_line: true,
inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' },
}],
},
};
shippingProcessingProjection.value = {
uiState: {
lifecycleStage: 'fulfillment_prep',
lifecycleEntries: [{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
primary_action: null,
secondary_actions: [],
},
};
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-READY', status: 'processing', lines: [], events: [],
ui_state: {
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
stage_context: {
preparation: {
status: 'ready', has_match_result: true,
lines: [{
line_key: 'line-ready', reservation_id: 'RSV-READY', part_number: 'PN-READY',
required_qty: '20', available_qty: '65', shortage_qty: '0', source_code: 'DBS', status: 'matched',
}],
},
},
},
} as any);
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
const workspace = wrapper.get('[data-testid="review-fulfillment-prep-workspace"]');
expect(workspace.get('[data-testid="review-fulfillment-prep-confirm-wave"]').exists()).toBe(true);
expect(wrapper.findComponent({ name: 'ReviewFulfillmentDecisionPanel' }).exists()).toBe(false);
await workspace.get('[data-testid="review-fulfillment-line-select-line-ready"]').setValue(true);
await workspace.get('[data-testid="review-fulfillment-prep-confirm-wave"]').trigger('click');
expect(vi.mocked(waveWorkspaceShippingOrderReviewLineFulfillment)).toHaveBeenCalledWith('CASE-1', expect.objectContaining({
line_keys: ['line-ready'],
expected_draft_version: 1,
}));
});
it('keeps intake parse on the standard workbench and removes the inventory return row', async () => {
@@ -1953,9 +2283,9 @@ describe('ShippingOrderReviewView layout phase 1', () => {
} finally {
reviewQueue.value = originalQueue;
}
});
}, 15000);
it('opens the page-level evidence dialog from freight upload when the current-task action is manual upload', async () => {
it('keeps manual-upload confirmation out of the current-task card', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_no: 'SN-UPLOAD-DIALOG', confirmed_task_id: 19, has_formal_ot: true,
@@ -1967,7 +2297,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
actions: {
primary: {
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
dispatch: 'dialog', ui_handler: 'manual_upload_evidence',
dispatch: 'dialog', ui_handler: 'manual_upload_confirmation',
target_surface: 'freight_upload', target_anchor: 'manual_upload',
requires_confirmation: false,
},
@@ -1975,17 +2305,24 @@ describe('ShippingOrderReviewView layout phase 1', () => {
},
summary: {}, steps: [],
},
} as any);
vi.mocked(taskApi.getWorkspaceShippingFreightNoticeGroups).mockResolvedValue({
po_number: 'PO-DOWNLOAD',
items: [{ business_no: 'WYC26082401', po_number: 'PO-DOWNLOAD', lines: [
{ line_no: '10', part_number: 'PN-ONE', reservation_id: 'RSV-1', shipment_qty: '4' },
{ line_no: '20', part_number: 'PN-TWO', reservation_id: 'RSV-2', shipment_qty: '7' },
] }],
} as any);
const wrapper = await mountView({ lifecycle_stage: 'freight_upload' });
await flushPromises();
await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="manual-upload-evidence-dialog"]').exists()).toBe(true);
// 人工确认由主区选中发货通知单后的批量入口处理,右侧不再打开单任务弹窗。
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="manual-upload-evidence-dialog"]').exists()).toBe(false);
});
it('renders the authorized Excel download in every freight-upload order line instead of the task rail', async () => {
it('renders one Notice card and one business_no Excel download for freight upload', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_no: 'SN-DOWNLOAD-DISPATCH', confirmed_task_id: 20, has_formal_ot: true,
@@ -2019,7 +2356,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
actions: {
primary: {
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
dispatch: 'dialog', ui_handler: 'manual_upload_evidence',
dispatch: 'dialog', ui_handler: 'manual_upload_confirmation',
requires_confirmation: false,
},
secondary: [{
@@ -2034,6 +2371,13 @@ describe('ShippingOrderReviewView layout phase 1', () => {
process_gate: { execution_no: 'EXEC-DOWNLOAD-DISPATCH' }, summary: {}, steps: [],
},
} as any);
vi.mocked(taskApi.getWorkspaceShippingFreightNoticeGroups).mockResolvedValue({
po_number: 'PO-DOWNLOAD',
items: [{ business_no: 'WYC26082401', po_number: 'PO-DOWNLOAD', lines: [
{ line_no: '10', part_number: 'PN-ONE', reservation_id: 'RSV-1', shipment_qty: '4' },
{ line_no: '20', part_number: 'PN-TWO', reservation_id: 'RSV-2', shipment_qty: '7' },
] }],
} as any);
const wrapper = await mountView({ lifecycle_stage: 'freight_upload' });
await flushPromises();
@@ -2042,13 +2386,13 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(rows).toHaveLength(2);
expect(rows[0].text()).toContain('PN-ONE');
expect(rows[1].text()).toContain('PN-TWO');
expect(wrapper.find('[data-testid="review-current-task-recovery-download_excel"]').exists()).toBe(false);
expect(wrapper.findAll('[data-testid="review-freight-upload-download"]').length).toBeGreaterThanOrEqual(1);
await wrapper.get('[data-testid="review-freight-upload-download-LINE-1"]').trigger('click');
await wrapper.get('[data-testid="review-freight-upload-download"]').trigger('click');
await flushPromises();
// 下载是 Artifact 只读操作;订单行不按 PO 聚合,且不得伪装成 Gate mutation。
expect(downloadWorkspaceShippingExcelFileMock).toHaveBeenCalledWith('SN-DOWNLOAD-DISPATCH');
expect(downloadWorkspaceShippingNoticeExcelFileMock).toHaveBeenCalledWith('WYC26082401');
expect(messageMocks.success).not.toHaveBeenCalled();
expect(submitProcessGatePrimaryActionMock).not.toHaveBeenCalled();
});
@@ -2275,14 +2619,14 @@ describe('ShippingOrderReviewView layout phase 1', () => {
actions: {
primary: {
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
dispatch: 'dialog', ui_handler: 'manual_upload_evidence',
dispatch: 'dialog', ui_handler: 'manual_upload_confirmation',
},
secondary: [],
},
stage_context: {
upload: {
latest_attempt: { status: 'failed', mode: 'rpa', freight_ref_no: 'LATEST-FAILED' },
succeeded_attempt: { status: 'succeeded', mode: 'manual', freight_ref_no: 'VERIFIED-REF' },
succeeded_attempt: { status: 'succeeded', mode: 'manual', freight_ref_no: 'LEGACY-REF-MUST-NOT-BE-SHOWN' },
},
},
summary: {}, steps: [],
@@ -2293,21 +2637,93 @@ describe('ShippingOrderReviewView layout phase 1', () => {
await flushPromises();
const evidence = wrapper.get('[data-testid="review-lifecycle-upload-complete"]');
expect(evidence.text()).toContain('VERIFIED-REF');
expect(evidence.text()).toContain('succeeded');
expect(evidence.text()).not.toContain('LATEST-FAILED');
// 人工确认不再展示或依赖货代回执号,即使历史投影仍带有 freight_ref_no。
expect(evidence.text()).not.toContain('LEGACY-REF-MUST-NOT-BE-SHOWN');
expect(evidence.text()).not.toContain('failed');
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(false);
});
it('renders empty optional schema fields as editable line columns', async () => {
it('aggregates freight upload by business_no and keeps one Excel action per notice', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_no: 'SN-PO-WAVE-1', confirmed_task_id: 22, has_formal_ot: true,
};
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-PO-WAVE-1', business_no: 'WYC26082401', status: 'processing', upload_status: 'pending',
lines: [], events: [],
ui_state: { lifecycle_stage: 'freight_upload', lifecycle_entries: [], actions: { primary: null, secondary: [] }, stage_context: { upload: {} } },
} as any);
vi.mocked(taskApi.getWorkspaceShippingFreightNoticeGroups).mockResolvedValue({
po_number: 'PO-100',
items: [
{ business_no: 'WYC26082401', po_number: 'PO-100', upload_status: 'pending', export_file_name: 'WYC26082401.xlsx', lines: [
{ line_no: '00010', part_number: 'PART-A', reservation_id: 'RSV-A', qty: '2' },
{ line_no: '00020', part_number: 'PART-B', reservation_id: 'RSV-B', qty: '1' },
] },
{ business_no: 'WYC26082402', po_number: 'PO-100', upload_status: 'pending', export_file_name: 'WYC26082402.xlsx', lines: [
{ line_no: '00030', part_number: 'PART-C', reservation_id: 'RSV-C', qty: '4' },
] },
],
} as any);
const wrapper = await mountView({ lifecycle_stage: 'freight_upload' });
await flushPromises();
const groups = wrapper.findAll('[data-testid="review-freight-upload-notice"]');
expect(groups).toHaveLength(2);
expect(wrapper.text()).toContain('WYC26082401');
expect(wrapper.text()).toContain('WYC26082402');
expect(wrapper.text()).toContain('PART-A');
expect(wrapper.text()).toContain('PART-C');
expect(wrapper.findAll('[data-testid="review-freight-upload-download"]')).toHaveLength(2);
expect(wrapper.findAll('[data-testid="review-freight-upload-line"]')).toHaveLength(3);
expect(wrapper.findAll('[data-testid="review-freight-upload-download-SN-PO-WAVE-1"]')).toHaveLength(0);
});
it('sends selected business_nos for freight batch actions', async () => {
activeCase.value = { ...activeCase.value, status: 'confirmed', confirmed_task_no: 'SN-PO-BATCH', confirmed_task_id: 23, has_formal_ot: true };
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-PO-BATCH', status: 'processing', lines: [], events: [],
ui_state: { lifecycle_stage: 'freight_upload', lifecycle_entries: [], actions: { primary: null, secondary: [] }, stage_context: { upload: {} } },
} as any);
vi.mocked(taskApi.getWorkspaceShippingFreightNoticeGroups).mockResolvedValue({
po_number: 'PO-BATCH', items: [
{ business_no: 'WYC26082411', po_number: 'PO-BATCH', lines: [] },
{ business_no: 'WYC26082412', po_number: 'PO-BATCH', lines: [] },
],
} as any);
const wrapper = await mountView({ lifecycle_stage: 'freight_upload' });
await flushPromises();
await wrapper.get('[aria-label="WYC26082411"]').setValue(true);
await wrapper.get('[aria-label="WYC26082412"]').setValue(true);
const buttons = wrapper.get('[data-testid="review-freight-upload-batch-toolbar"]').findAll('button');
await buttons[0].trigger('click');
await flushPromises();
expect(downloadFreightArchiveMock).toHaveBeenCalledWith(['WYC26082411', 'WYC26082412']);
await wrapper.get('[aria-label="WYC26082411"]').setValue(true);
await wrapper.get('[aria-label="WYC26082412"]').setValue(true);
await buttons[1].trigger('click');
await flushPromises();
expect(batchRpaFreightMock).toHaveBeenCalledWith(['WYC26082411', 'WYC26082412']);
await wrapper.get('[aria-label="WYC26082411"]').setValue(true);
await wrapper.get('[aria-label="WYC26082412"]').setValue(true);
await buttons[2].trigger('click');
await flushPromises();
expect(batchConfirmFreightMock).toHaveBeenCalledWith(['WYC26082411', 'WYC26082412']);
});
it('does not place internal inventory hint fields in the primary line table', async () => {
const wrapper = await mountView();
const inputs = wrapper.findAll('[data-testid="review-line-field-input"]');
// 关键断言:库存源线索即使非必填且尚无机器值,也必须作为 Schema 列显示并可编辑。
expect(wrapper.text()).toContain('库存源线索');
expect(inputs).toHaveLength(1);
expect(inputs[0].attributes('disabled')).toBeUndefined();
// 关键断言:主表只保留业务核对字段,库存源线索由行级履约详情承载。
expect(wrapper.text()).not.toContain('库存源线索');
expect(inputs).toHaveLength(0);
});
it('ignores a stale line change after the current draft has accepted the value', async () => {
@@ -2559,10 +2975,11 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
},
} as any);
const wrapper = await mountView();
// 正式 OT 动作只有进入履约工作面后才读取 ShippingTask.ui_state;测试必须提供真实阶段上下文。
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
expect(wrapper.get('[data-testid="review-current-task-primary-action"]').attributes('disabled')).toBeDefined();
expect(wrapper.get('[data-testid="review-current-processing-retry"]').attributes('disabled')).toBeDefined();
}, 15000);
it('keeps top / wide / narrow stage labels identical via Progress projection (waiting_system_start)', async () => {
@@ -2641,6 +3058,8 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
const wrapper = await mountView();
await flushPromises();
// 关键断言:failed 态主卡/底栏露出 STP 重试(非确认后 auto_progress)。
expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toContain('创建正式订单');
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toContain('自动处理失败');
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);
@@ -2649,6 +3068,28 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
expect(retryWorkspaceShippingOrderStpAutoCreate).toHaveBeenCalledWith('CASE-1');
}, 15000);
it('hides the duplicate submit-order guidance while STP auto-create is running', async () => {
activeCase.value = {
...activeCase.value,
status: 'ready',
available_actions: ['validate'],
automation: {
status: 'running',
retryable: false,
can_auto_create: true,
can_build: true,
phase: 'pre_ot_stp',
},
};
const wrapper = await mountView();
await flushPromises();
// 关键断言:系统接管建单后,底栏只能保留运行态,不得同时出现提交按钮及其旧说明。
expect(wrapper.find('[data-testid="review-footer-automating-hint"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-submit-order-hint"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-footer-actions"]').text()).not.toContain('提交订单');
}, 15000);
it('shows STP retry for manual_fallback without confirm-create (UI-02)', async () => {
activeCase.value = {
...activeCase.value,
File diff suppressed because it is too large. Load diff