feat(shipping-notice): 完善发货通知自动推进与多库存源复核闭环
This commit is contained in:
1 parent
cfa19a0b7b
commit
8e0bbf7a81
180 files changed
+31210
-1864
No files matched your search
@@ -33,9 +33,11 @@ import type {
|
||||
OrderExtractionSubmissionRequest,
|
||||
OrderExtractionSubmissionResponse,
|
||||
ConversationProcessingProjection,
|
||||
ConversationProcessingAppendBlockReason,
|
||||
ShippingOrderReviewAuditTimelinePage,
|
||||
ShippingTaskAuditTimelinePage,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewCaseSnapshot,
|
||||
ShippingOrderReviewCustomerResolution,
|
||||
ShippingOrderReviewDuplicate,
|
||||
ShippingOrderReviewFieldConflict,
|
||||
@@ -55,6 +57,7 @@ import type {
|
||||
ShippingOrderReviewLlmSuggestionResponse,
|
||||
ShippingOrderReviewReparseResponse,
|
||||
ShippingOrderReviewRun,
|
||||
ShippingTaskInventoryCandidatesResponse,
|
||||
ShippingTaskUiState,
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
@@ -70,6 +73,8 @@ type ShippingApiStatusPayload = {
|
||||
/** 批次重试等接口返回的跳过任务数 */
|
||||
skipped?: number;
|
||||
batch_no?: string;
|
||||
/** 后端返回的语义化原因码(对齐 noop / needs_human / already_running 等状态分支) */
|
||||
reason_code?: ConversationProcessingAppendBlockReason | string | null;
|
||||
};
|
||||
|
||||
export type ShippingChatAgentOption = {
|
||||
@@ -379,7 +384,7 @@ export const getWorkspaceShippingOrderReviewRun = (runNo: string) =>
|
||||
|
||||
/** 获取一份 PDF 的冻结 Schema 与只读机器/草稿投影。 */
|
||||
export const getWorkspaceShippingOrderReviewCase = (caseNo: string) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
requestJson<ShippingOrderReviewCaseSnapshot>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}`,
|
||||
);
|
||||
|
||||
@@ -491,6 +496,22 @@ export const putWorkspaceShippingOrderReviewInventoryCandidates = (
|
||||
{ method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
|
||||
);
|
||||
|
||||
/**
|
||||
* 读取正式 Task 当前库存候选版本与历史摘要。
|
||||
*/
|
||||
export const getWorkspaceTaskInventoryCandidates = (
|
||||
taskNo: string,
|
||||
options?: { version?: 'current' | number; includeHistory?: boolean },
|
||||
) => {
|
||||
const params = new URLSearchParams();
|
||||
if (options?.version != null) params.set('version', String(options.version));
|
||||
if (options?.includeHistory != null) params.set('include_history', String(options.includeHistory));
|
||||
const query = params.toString();
|
||||
return requestJson<ShippingTaskInventoryCandidatesResponse>(
|
||||
`/api/workspace/shipping-notice/tasks/${encodeURIComponent(taskNo)}/inventory-candidates${query ? `?${query}` : ''}`,
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 重新匹配整单或指定明细的库存路由规则。
|
||||
* 核心逻辑:携带 expected_draft_version 与幂等键;可选 line_key 限定单行。
|
||||
|
||||
+257
-62
@@ -1,43 +1,71 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewCurrentProcessingCard.vue
|
||||
用途:正式 OT 创建后的右侧「当前处理状态」主卡(阶段 + 自动推进合并)。
|
||||
依赖:vue-i18n、ShippingOrderReviewAutomation、resolveShippingProcessingStageLabel。
|
||||
逻辑:优先消费 Progress 同源的 stageCode + stageLabelKey;Case current_stage 仅降级;
|
||||
禁止把阶段码直接当用户文案;Job 明细与 task_missing 诊断仅管理员区;
|
||||
由 ShippingOrderReviewView 在 has_formal_ot / task_missing 时置顶渲染。
|
||||
用途:发货通知工作台右侧唯一的「当前任务」主卡(阶段 + 用户状态 + 阻断 + 动作)。
|
||||
依赖:vue-i18n、ShippingProcessingBlockingReason/PrimaryAction 类型、resolveShippingProcessingStageLabel。
|
||||
逻辑:主卡内部 section = 「当前阶段/状态/正式OT → 下一步 → 动作区」;
|
||||
状态文案严格绑定 user_status;blocking_reason 只作下一步问题说明;按钮显隐由后端 retryable + primary_action.parameters 决定;
|
||||
由 ShippingOrderReviewView 在 mountCurrentProcessingCard 时挂载。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { RefreshCw } from 'lucide-vue-next';
|
||||
import { RefreshCw, Crosshair } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewAutomation } from '@/features/chat/types/shipping.api.types';
|
||||
import type {
|
||||
ShippingProcessingBlockingReason,
|
||||
ShippingProcessingPrimaryAction,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import { resolveShippingProcessingStageLabel } from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
|
||||
const props = defineProps<{
|
||||
stageCode?: string | null;
|
||||
stageLabelKey?: string | null;
|
||||
stageInconsistent?: boolean;
|
||||
|
||||
hasFormalOt?: boolean;
|
||||
shippingNoticeNo?: string | null;
|
||||
|
||||
userStatus?:
|
||||
| 'running'
|
||||
| 'waiting_human'
|
||||
| 'retryable'
|
||||
| 'failed'
|
||||
| 'completed'
|
||||
| 'cancelled'
|
||||
| null;
|
||||
retryable?: boolean;
|
||||
blockingReason?: ShippingProcessingBlockingReason | null;
|
||||
primaryAction?: ShippingProcessingPrimaryAction | null;
|
||||
|
||||
taskMissing?: boolean;
|
||||
taskNo?: string | null;
|
||||
confirmedTaskId?: number | null;
|
||||
showAdminDiagnosis?: boolean;
|
||||
automation?: ShippingOrderReviewAutomation | null;
|
||||
showRetry?: boolean;
|
||||
retrying?: boolean;
|
||||
locating?: boolean;
|
||||
/** 题7A:自动次数已耗尽但允许人工继续的源;不为空时按钮语义提示「人工继续」+ tooltip 列名。 */
|
||||
retryExhaustedSources?: string[] | null;
|
||||
/** 仅 UI 展示的 running 文案(如 inventory_preparation 正在跑时主卡按钮 loading 附加信息)。 */
|
||||
automation?: {
|
||||
status?: string | null;
|
||||
message?: string | null;
|
||||
} | null;
|
||||
showRetry?: boolean;
|
||||
loading?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
retry: [];
|
||||
locate: [lineKey?: string | null, fieldId?: string | null];
|
||||
action: [code: string, parameters?: Record<string, unknown>];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
/**
|
||||
* 当前处理阶段展示文案:消费 label_key,禁止直接展示阶段码。
|
||||
* 当前阶段展示文案:优先消费 stage_label_key,禁止直接展示 stage 码。
|
||||
*/
|
||||
const stageLabel = computed(() => {
|
||||
if (props.taskMissing) {
|
||||
return t('chat.shippingOrderReview.currentProcessing.taskMissing');
|
||||
if (props.loading) {
|
||||
return t('chat.shippingOrderReview.caseSwitchLoading');
|
||||
}
|
||||
if (props.stageInconsistent) {
|
||||
return t('chat.shippingOrderReview.currentProcessing.stateInconsistent');
|
||||
@@ -51,68 +79,196 @@ const stageLabel = computed(() => {
|
||||
});
|
||||
|
||||
/**
|
||||
* 自动推进用户态文案(消费 phase,禁止前端猜建单/推进)。
|
||||
* 「状态」行用户态文案:严格绑定 user_status,不再由前端推断。
|
||||
*/
|
||||
const statusLabel = computed(() => {
|
||||
const automation = props.automation;
|
||||
const status = String(automation?.status || '').trim().toLowerCase();
|
||||
const phase = String(automation?.phase || '').trim();
|
||||
if (props.loading) {
|
||||
return t('chat.shippingOrderReview.currentTask.statusRunning');
|
||||
}
|
||||
const s = String(props.userStatus || '').trim() as ReviewCurrentUserStatus | '';
|
||||
const map: Record<ReviewCurrentUserStatus, string> = {
|
||||
running: t('chat.shippingOrderReview.currentTask.statusRunning'),
|
||||
waiting_human: t('chat.shippingOrderReview.currentTask.statusWaitingHuman'),
|
||||
retryable: t('chat.shippingOrderReview.currentTask.statusRetryable'),
|
||||
failed: t('chat.shippingOrderReview.currentTask.statusFailed'),
|
||||
completed: t('chat.shippingOrderReview.currentTask.statusCompleted'),
|
||||
cancelled: t('chat.shippingOrderReview.currentTask.statusCancelled'),
|
||||
};
|
||||
if (props.taskMissing) {
|
||||
return t('chat.shippingOrderReview.currentProcessing.statusTaskMissing');
|
||||
return t('chat.shippingOrderReview.currentProcessing.taskMissing');
|
||||
}
|
||||
if (status === 'waiting_to_start') {
|
||||
return phase === 'pre_ot_stp'
|
||||
? t('chat.shippingOrderReview.automation.waitingPreOt')
|
||||
: t('chat.shippingOrderReview.automation.waitingPostOt');
|
||||
}
|
||||
if (status === 'queued' || status === 'running') {
|
||||
return t('chat.shippingOrderReview.currentProcessing.statusRunning');
|
||||
}
|
||||
if (status === 'failed' || status === 'manual_fallback') {
|
||||
return t('chat.shippingOrderReview.currentProcessing.statusFailedRetryable');
|
||||
}
|
||||
if (status === 'completed') {
|
||||
return t('chat.shippingOrderReview.currentProcessing.statusCompleted');
|
||||
}
|
||||
return t('chat.shippingOrderReview.currentProcessing.statusIdle');
|
||||
if (!s) return t('chat.shippingOrderReview.currentProcessing.statusIdle');
|
||||
return map[s] ?? t('chat.shippingOrderReview.currentProcessing.statusIdle');
|
||||
});
|
||||
|
||||
/**
|
||||
* 主卡重试:对象级;建单前无 task_no 也可重试 STP;正式 OT 需 task_no。
|
||||
* 下一步(「下一步」section 的问题/说明文案):优先展示 blocking_reason,否则按 user_status 给系统态文案。
|
||||
*/
|
||||
const canShowRetry = computed(() => {
|
||||
if (!props.showRetry || props.taskMissing) return false;
|
||||
if (String(props.taskNo || '').trim()) return true;
|
||||
// 建单前 STP:无 OT 号也可重试。
|
||||
return String(props.automation?.phase || '').trim() !== 'post_ot_progress';
|
||||
const nextStepText = computed(() => {
|
||||
if (props.loading) {
|
||||
return String(props.automation?.message || '').trim() || t('chat.shippingOrderReview.currentTask.nextStepRunning');
|
||||
}
|
||||
// 1) blocking_reason → 用后端给的 i18n_key 渲染具体阻断
|
||||
const br = props.blockingReason;
|
||||
if (br) {
|
||||
const i18nKey = String(br.i18nKey || '').trim();
|
||||
if (i18nKey && te(i18nKey)) {
|
||||
return t(i18nKey);
|
||||
}
|
||||
// i18n 键缺失时回落为 code(不裸露给普通用户,最终 QA 期间应全部补齐)
|
||||
return String(br.code || '').trim() || t('chat.shippingOrderReview.currentTask.nextStepUnknown');
|
||||
}
|
||||
// 2) 无阻断时,按 user_status 给系统说明文案
|
||||
const s = String(props.userStatus || '').trim() as ReviewCurrentUserStatus | '';
|
||||
if (s === 'running') {
|
||||
return t('chat.shippingOrderReview.currentTask.nextStepRunning');
|
||||
}
|
||||
if (s === 'completed') {
|
||||
return t('chat.shippingOrderReview.currentTask.nextStepCompleted');
|
||||
}
|
||||
if (s === 'cancelled') {
|
||||
return t('chat.shippingOrderReview.currentTask.nextStepCancelled');
|
||||
}
|
||||
if (s === 'failed' && !props.retryable) {
|
||||
return t('chat.shippingOrderReview.currentTask.nextStepFailedNoRetry');
|
||||
}
|
||||
if (s === 'waiting_human') {
|
||||
return t('chat.shippingOrderReview.currentTask.nextStepWaitingHumanDefault');
|
||||
}
|
||||
if (s === 'retryable') {
|
||||
return t('chat.shippingOrderReview.currentTask.nextStepRetryableDefault');
|
||||
}
|
||||
return t('chat.shippingOrderReview.currentTask.nextStepUnknown');
|
||||
});
|
||||
|
||||
/**
|
||||
* 业务动作按钮:后端确认 retryable=true → 主按钮为「重试」;
|
||||
* 否则若 primary_action.code 非 retry → 用 primary_action.code + i18n_key 渲染对应人工动作(进入复核/确认客户等)。
|
||||
*/
|
||||
const showBusinessAction = computed(() => {
|
||||
if (props.loading) return false;
|
||||
if (props.taskMissing) return false;
|
||||
if (props.retryable) return true;
|
||||
const code = String(props.primaryAction?.code || '').trim();
|
||||
if (!code) return false;
|
||||
// retry 仅当 retryable=true 时展示(避免按钮闪烁矛盾)
|
||||
if (code === 'retry') return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
const businessActionLabel = computed(() => {
|
||||
if (props.retryable) {
|
||||
if ((props.retryExhaustedSources || []).length > 0) {
|
||||
return t('chat.shippingOrderReview.currentTask.actionRetryWithExhausted');
|
||||
}
|
||||
return t('chat.shippingOrderReview.currentTask.actionRetry');
|
||||
}
|
||||
const pa = props.primaryAction;
|
||||
if (!pa) return '';
|
||||
const i18nKey = String(pa.i18nKey || '').trim();
|
||||
if (i18nKey && te(i18nKey)) {
|
||||
return t(i18nKey);
|
||||
}
|
||||
// fallback 到 legacy chat.shippingProcessing.action
|
||||
const legacyKey = `chat.shippingProcessing.action.${pa.code}`;
|
||||
if (te(legacyKey)) {
|
||||
return t(legacyKey);
|
||||
}
|
||||
return pa.code;
|
||||
});
|
||||
|
||||
/** 题7A:按钮 tooltip(exhausted_sources 列表与文案)。 */
|
||||
const businessActionTitle = computed(() => {
|
||||
const exhausted = Array.isArray(props.retryExhaustedSources) ? props.retryExhaustedSources.filter(Boolean) : [];
|
||||
if (exhausted.length > 0) {
|
||||
return t('chat.shippingOrderReview.currentTask.actionRetryExhaustedTooltip', {
|
||||
sources: exhausted.join(', '),
|
||||
});
|
||||
}
|
||||
const retryingFlag = Boolean(props.retrying);
|
||||
if (retryingFlag) {
|
||||
return t('chat.shippingOrderReview.currentTask.actionRetryRunningTooltip');
|
||||
}
|
||||
return '';
|
||||
});
|
||||
|
||||
const actionIsRetry = computed(() => Boolean(props.retryable) || String(props.primaryAction?.code || '') === 'retry');
|
||||
|
||||
function handleBusinessActionClick() {
|
||||
if (actionIsRetry.value) {
|
||||
emit('retry');
|
||||
return;
|
||||
}
|
||||
emit('action', String(props.primaryAction?.code || ''), props.primaryAction?.parameters ?? {});
|
||||
}
|
||||
|
||||
/**
|
||||
* 辅助导航「定位明细」:仅当后端在 primary_action.parameters 里提供 line_key 或 field_id 才显示。
|
||||
*/
|
||||
const showLocateAction = computed(() => {
|
||||
if (props.loading) return false;
|
||||
if (props.taskMissing) return false;
|
||||
const params = (props.primaryAction?.parameters ?? {}) as Record<string, unknown>;
|
||||
const hasLineKey = typeof params.line_key === 'string' && params.line_key.length > 0;
|
||||
const hasFieldId = typeof params.field_id === 'string' && params.field_id.length > 0;
|
||||
return hasLineKey || hasFieldId;
|
||||
});
|
||||
|
||||
const locateTargetLineKey = computed(() => {
|
||||
const params = (props.primaryAction?.parameters ?? {}) as Record<string, unknown>;
|
||||
return typeof params.line_key === 'string' ? params.line_key : null;
|
||||
});
|
||||
|
||||
const locateTargetFieldId = computed(() => {
|
||||
const params = (props.primaryAction?.parameters ?? {}) as Record<string, unknown>;
|
||||
return typeof params.field_id === 'string' ? params.field_id : null;
|
||||
});
|
||||
|
||||
function handleLocateClick() {
|
||||
emit('locate', locateTargetLineKey.value, locateTargetFieldId.value);
|
||||
}
|
||||
|
||||
type ReviewCurrentUserStatus =
|
||||
| 'running'
|
||||
| 'waiting_human'
|
||||
| 'retryable'
|
||||
| 'failed'
|
||||
| 'completed'
|
||||
| 'cancelled';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
class="rounded-xl border border-sky-200 bg-sky-50/80 p-3 shadow-sm dark:border-sky-900 dark:bg-sky-950/30"
|
||||
data-testid="review-current-processing-card"
|
||||
:data-user-status="String(userStatus || '')"
|
||||
:data-task-missing="taskMissing ? '1' : '0'"
|
||||
:data-automation-status="String(automation?.status || '')"
|
||||
:data-automation-phase="String(automation?.phase || '')"
|
||||
:data-loading="loading ? '1' : '0'"
|
||||
>
|
||||
<header class="mb-2">
|
||||
<header class="mb-3">
|
||||
<h2 class="text-sm font-semibold text-sky-950 dark:text-sky-100">
|
||||
{{ t('chat.shippingOrderReview.currentProcessing.title') }}
|
||||
{{ t('chat.shippingOrderReview.currentTask.title') }}
|
||||
</h2>
|
||||
<p class="mt-0.5 text-xs text-sky-900/80 dark:text-sky-200/80">
|
||||
{{ stageLabel }}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<dl class="space-y-1 text-xs text-sky-950 dark:text-sky-100">
|
||||
<div class="flex flex-wrap gap-x-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.currentProcessing.status') }}</dt>
|
||||
<dd data-testid="review-current-processing-status">{{ statusLabel }}</dd>
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.currentTask.labelStage') }}</dt>
|
||||
<dd data-testid="review-current-task-stage" :class="loading ? 'animate-pulse' : ''">{{ stageLabel }}</dd>
|
||||
</div>
|
||||
<div v-if="taskNo" class="flex flex-wrap gap-x-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.currentProcessing.formalOt') }}</dt>
|
||||
<dd class="font-mono" data-testid="review-current-processing-ot">{{ taskNo }}</dd>
|
||||
<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>
|
||||
</div>
|
||||
<div
|
||||
v-if="hasFormalOt && shippingNoticeNo"
|
||||
class="flex flex-wrap gap-x-2"
|
||||
>
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.currentTask.labelFormalSn') }}</dt>
|
||||
<dd
|
||||
class="font-mono"
|
||||
data-testid="review-current-processing-ot"
|
||||
>{{ shippingNoticeNo }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
@@ -130,7 +286,10 @@ const canShowRetry = computed(() => {
|
||||
data-testid="review-current-processing-admin-diagnosis"
|
||||
>
|
||||
<p class="font-medium">{{ t('chat.shippingOrderReview.currentProcessing.adminDiagnosisTitle') }}</p>
|
||||
<p v-if="confirmedTaskId != null" class="mt-1 font-mono">
|
||||
<p
|
||||
v-if="confirmedTaskId != null"
|
||||
class="mt-1 font-mono"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.currentProcessing.confirmedTaskId', { id: confirmedTaskId }) }}
|
||||
</p>
|
||||
<p class="mt-1">
|
||||
@@ -141,16 +300,52 @@ const canShowRetry = computed(() => {
|
||||
</p>
|
||||
</aside>
|
||||
|
||||
<button
|
||||
v-if="canShowRetry"
|
||||
type="button"
|
||||
class="mt-3 inline-flex items-center gap-1 rounded border border-amber-400 bg-amber-50 px-2.5 py-1.5 text-xs text-amber-950 disabled:opacity-50 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100"
|
||||
data-testid="review-current-processing-retry"
|
||||
:disabled="retrying"
|
||||
@click="emit('retry')"
|
||||
<div
|
||||
class="mt-3 border-t border-sky-200/70 pt-3 dark:border-sky-800/60"
|
||||
data-testid="review-current-task-next-step-section"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
{{ t('chat.shippingOrderReview.autoProgress.retryObject') }}
|
||||
</button>
|
||||
<p class="text-[11px] font-medium uppercase tracking-wide text-sky-900/70 dark:text-sky-200/70">
|
||||
{{ t('chat.shippingOrderReview.currentTask.nextStepTitle') }}
|
||||
</p>
|
||||
<p
|
||||
class="mt-1 text-xs text-sky-950 dark:text-sky-100"
|
||||
data-testid="review-current-task-next-step-text"
|
||||
:class="loading ? 'animate-pulse' : ''"
|
||||
>{{ nextStepText }}</p>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="showBusinessAction || showLocateAction"
|
||||
class="mt-3 flex flex-wrap items-center gap-2"
|
||||
data-testid="review-current-task-actions"
|
||||
>
|
||||
<button
|
||||
v-if="showBusinessAction"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-md bg-sky-700 px-3 py-1.5 text-xs font-medium text-white shadow-sm transition hover:bg-sky-800 disabled:opacity-50 dark:bg-sky-600 dark:hover:bg-sky-500"
|
||||
:data-testid="actionIsRetry ? 'review-current-processing-retry' : 'review-current-task-primary-action'"
|
||||
:disabled="retrying || locating"
|
||||
:title="businessActionTitle"
|
||||
@click="handleBusinessActionClick"
|
||||
>
|
||||
<RefreshCw
|
||||
v-if="actionIsRetry"
|
||||
class="h-3.5 w-3.5"
|
||||
:class="{ 'animate-spin': Boolean(retrying) }"
|
||||
/>
|
||||
{{ businessActionLabel }}
|
||||
</button>
|
||||
<button
|
||||
v-if="showLocateAction"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-sky-300 bg-white px-2.5 py-1.5 text-xs font-medium text-sky-800 shadow-sm transition hover:bg-sky-50 disabled:opacity-50 dark:border-sky-700 dark:bg-sky-900 dark:text-sky-100 dark:hover:bg-sky-800"
|
||||
data-testid="review-current-task-locate-action"
|
||||
:disabled="locating"
|
||||
@click="handleLocateClick"
|
||||
>
|
||||
<Crosshair class="h-3.5 w-3.5" />
|
||||
{{ t('chat.shippingOrderReview.currentTask.actionLocateLine') }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
+1
-1
@@ -57,7 +57,7 @@ describe('ReviewInventoryCandidatesPanel', () => {
|
||||
expect(text).toContain('DSV360_AWSDU');
|
||||
expect(text).toContain('DSV360_AWSSG');
|
||||
expect(text).toContain('ROUTE_HINT_AWSSG');
|
||||
expect(text).toContain('命中规则');
|
||||
expect(text).toContain('匹配规则');
|
||||
expect(text).toContain('库存源未启用');
|
||||
expect(wrapper.find('[data-testid="review-inventory-unavailable-sources"]').text()).toContain('DSV360_AWSSG');
|
||||
expect(
|
||||
|
||||
@@ -56,6 +56,11 @@ const unavailableSuggestions = computed(() =>
|
||||
(props.suggestions || []).filter((item) => String(item.status || '') === 'provider_unavailable'),
|
||||
);
|
||||
|
||||
/** 前门禁失败(未调用 Dify)的记录必须明确展示,错误码指向 i18n errors.json;避免用户误认为 AI 已跑过。 */
|
||||
const gatedFailedSuggestions = computed(() =>
|
||||
(props.suggestions || []).filter((item) => String(item.status || '') === 'gated_failed'),
|
||||
);
|
||||
|
||||
/** 将 Provider 失败码转成可执行的业务提示,不向用户暴露底层地址或异常正文。 */
|
||||
function unavailableMessage(item?: ShippingOrderReviewLlmSuggestion): string {
|
||||
if (String(item?.error_code || '') === 'SHIPPING.REVIEW_LLM_DISABLED') {
|
||||
@@ -64,6 +69,31 @@ function unavailableMessage(item?: ShippingOrderReviewLlmSuggestion): string {
|
||||
return t('chat.shippingOrderReview.llmSuggestion.unavailableProvider');
|
||||
}
|
||||
|
||||
/**
|
||||
* 门禁失败 short 提示(一层标题):用 errors.json 本地化;缺失时给通用提示避免裸 code。
|
||||
* 完全消费后端投影的 item.error_code,前端绝对不推导「为什么失败」。
|
||||
*/
|
||||
function gatedShortMessage(item: ShippingOrderReviewLlmSuggestion): string {
|
||||
const code = String(item.error_code || '');
|
||||
const key = `errors.${code}`;
|
||||
if (code && te(key)) return t(key);
|
||||
return t('chat.shippingOrderReview.llmSuggestion.status.gated_failed');
|
||||
}
|
||||
|
||||
/**
|
||||
* 门禁失败 detail 提示(二层详情):查 errors.json 的 `${code}Detail` 或通用 hint。
|
||||
* 同样不推导原因,纯 i18n 查表。
|
||||
*/
|
||||
function gatedDetailMessage(item: ShippingOrderReviewLlmSuggestion): string | null {
|
||||
const code = String(item.error_code || '');
|
||||
if (!code) return null;
|
||||
const detailKey = `errors.${code}Detail`;
|
||||
if (te(detailKey)) return t(detailKey);
|
||||
const hintKey = `chat.shippingOrderReview.llmSuggestion.gateDetail.${code.replace(/^SHIPPING\./, '')}`;
|
||||
if (te(hintKey)) return t(hintKey);
|
||||
return null;
|
||||
}
|
||||
|
||||
const statusLabel = computed(() => {
|
||||
if (props.suggestionLoading) return t('chat.shippingOrderReview.llmSuggestion.status.pending');
|
||||
const latest = (props.suggestions || [])[0];
|
||||
@@ -218,8 +248,59 @@ function onDecide(payload: { decision: 'accept' | 'modify' | 'reject'; reason: s
|
||||
>
|
||||
{{ unavailableMessage(unavailableSuggestions[0]) }}
|
||||
</div>
|
||||
<ul
|
||||
v-if="gatedFailedSuggestions.length"
|
||||
class="mt-3 space-y-2"
|
||||
data-testid="review-llm-gated-failed-list"
|
||||
>
|
||||
<li
|
||||
v-for="item in gatedFailedSuggestions"
|
||||
:key="item.suggestion_no"
|
||||
class="rounded border border-sky-200 bg-sky-50/60 px-2 py-2 text-xs text-sky-800 dark:border-sky-900 dark:bg-sky-950/30 dark:text-sky-200"
|
||||
role="note"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="font-medium leading-snug">{{ suggestionFieldLabel(item) }}</div>
|
||||
<p class="mt-1 leading-snug">{{ gatedShortMessage(item) }}</p>
|
||||
<p
|
||||
v-if="gatedDetailMessage(item)"
|
||||
class="mt-1 text-[11px] leading-relaxed opacity-80"
|
||||
>
|
||||
{{ gatedDetailMessage(item) }}
|
||||
</p>
|
||||
<p
|
||||
v-if="item.evidence_summary"
|
||||
class="mt-1 flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] opacity-80"
|
||||
>
|
||||
<span v-if="item.evidence_summary.level">
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.evidenceLevelLabel') }}:{{ evidenceLevelLabel(item.evidence_summary.level) }}
|
||||
</span>
|
||||
<span v-if="item.evidence_summary.auto_upgraded">
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.autoUpgradedLabel') }}
|
||||
</span>
|
||||
<span v-if="typeof item.evidence_summary.field_count === 'number'">
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.fieldCountLabel') }}:{{ item.evidence_summary.field_count }}
|
||||
</span>
|
||||
<span v-if="item.evidence_summary.context_truncated">
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.contextTruncatedLabel') }}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded border border-sky-300 bg-white px-2 py-0.5 text-xs text-sky-700 dark:border-sky-700 dark:bg-slate-900 dark:text-sky-200"
|
||||
:disabled="!canRequest"
|
||||
:aria-label="t('chat.shippingOrderReview.llmSuggestion.request')"
|
||||
@click="emit('requestSuggestion')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.request') }}
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<p
|
||||
v-if="!pendingSuggestions.length && !failedSuggestions.length && !unavailableSuggestions.length"
|
||||
v-if="!pendingSuggestions.length && !failedSuggestions.length && !unavailableSuggestions.length && !gatedFailedSuggestions.length"
|
||||
class="mt-3 text-xs text-slate-500"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.empty') }}
|
||||
|
||||
+10
@@ -34,10 +34,12 @@ const messages = {
|
||||
expandHistory: 'Show full track',
|
||||
collapseHistory: 'Hide full track',
|
||||
progress: {
|
||||
title: 'Order processing',
|
||||
completedOfTotal: '{done} of {total} done',
|
||||
remainingHint: '{count} remaining',
|
||||
positionOfTotal: '{current} / {total}',
|
||||
currentNeedLabel: 'Need: ',
|
||||
currentStage: 'Stage: {stage}',
|
||||
progressTitleWithStage: 'Order processing · {stage}',
|
||||
systemProcessingWithStage: 'System processing · {stage}',
|
||||
viewProcessDetails: 'View process details',
|
||||
@@ -53,6 +55,7 @@ const messages = {
|
||||
stage: Object.fromEntries(SHIPPING_PROCESSING_STAGES.map((s) => [s, s])),
|
||||
action: {
|
||||
refresh: 'Refresh',
|
||||
confirm_customer: 'Confirm customer',
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -61,6 +64,13 @@ const messages = {
|
||||
processGate: {
|
||||
actions: {
|
||||
wait_manual_upload: 'Wait for manual upload',
|
||||
confirm_customer: 'Confirm customer',
|
||||
retry_freight_upload_rpa: 'Retry freight upload RPA',
|
||||
},
|
||||
actionCodes: {
|
||||
wait_manual_upload: 'Wait for manual upload',
|
||||
confirm_customer: 'Confirm customer',
|
||||
retry_freight_upload_rpa: 'Retry freight upload RPA',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
+1
-1
@@ -65,7 +65,7 @@ const showTaskWorkbenchLink = computed(() => {
|
||||
v-else-if="processingProjection"
|
||||
:projection="processingProjection"
|
||||
:polling="polling"
|
||||
:has-formal-ot="hasFormalOt || Boolean(String(taskNo || '').trim())"
|
||||
:has-formal-ot="hasFormalOt || String(taskNo || '').trim().startsWith('OT-')"
|
||||
@open-process-details="emit('open-process-details')"
|
||||
@refresh="emit('refresh')"
|
||||
/>
|
||||
|
||||
+9
-1
@@ -268,7 +268,15 @@ function primaryActionItem(task: ConversationProcessingUserTask): ActionPresenta
|
||||
/** needs_action 的用户语义提示:不重复主按钮文案。 */
|
||||
function currentNeedLabel(task: ConversationProcessingUserTask): string {
|
||||
if (task.group !== 'needs_action') return '';
|
||||
const action = String(task.primary_action || task.available_actions?.[0] || '').trim().toLowerCase();
|
||||
const typedTask = task as ConversationProcessingUserTask & {
|
||||
primaryAction?: { code?: string } | null;
|
||||
};
|
||||
const action = String(
|
||||
typedTask.primaryAction?.code
|
||||
?? task.primary_action
|
||||
?? task.available_actions?.[0]
|
||||
?? '',
|
||||
).trim().toLowerCase();
|
||||
const labels: Record<string, string> = {
|
||||
confirm_customer: 'chat.shippingProcessing.currentNeed.confirmCustomer',
|
||||
resolve_field_conflicts: 'chat.shippingProcessing.currentNeed.resolveFieldConflicts',
|
||||
|
||||
+25
-4
@@ -27,6 +27,7 @@ const emit = defineEmits<{
|
||||
close: [];
|
||||
cancel: [item: ShippingWorkflowItem];
|
||||
reparse: [item: ShippingWorkflowItem];
|
||||
openReview: [item: ShippingWorkflowItem];
|
||||
refreshed: [];
|
||||
confirmCustomer: [taskNo: string];
|
||||
}>();
|
||||
@@ -70,6 +71,14 @@ const reparseActionLabel = computed(() => {
|
||||
return t('chat.shippingProcessing.actions.reparse');
|
||||
});
|
||||
|
||||
const canOpenReview = computed(() => {
|
||||
if (!props.item) return false;
|
||||
const actions = props.item.available_actions;
|
||||
const status = String(props.item.lifecycle_status || '').trim();
|
||||
if (Array.isArray(actions)) return actions.includes('view_details') || actions.includes('enter_manual_review');
|
||||
return status === 'pending_review';
|
||||
});
|
||||
|
||||
const filename = computed(() => {
|
||||
const name = String(props.item?.current_document_filename || '').trim();
|
||||
if (name) return name;
|
||||
@@ -206,7 +215,7 @@ onBeforeUnmount(() => {
|
||||
>
|
||||
<aside
|
||||
ref="panelRef"
|
||||
class="flex h-full w-full max-w-md flex-col border-l border-default bg-surface shadow-xl"
|
||||
class="flex h-full w-full max-w-md flex-col border-l border-default bg-surface shadow-xl rounded-l-xl"
|
||||
>
|
||||
<header class="flex items-start justify-between gap-2 border-b border-default px-4 py-3">
|
||||
<div class="min-w-0">
|
||||
@@ -258,9 +267,11 @@ onBeforeUnmount(() => {
|
||||
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.runNo') }}</dt>
|
||||
<dd class="font-medium text-primary">{{ item.current_run_no }}</dd>
|
||||
</div>
|
||||
<div v-if="item.current_case_no" class="flex justify-between gap-2">
|
||||
<div class="flex justify-between gap-2">
|
||||
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.caseNo') }}</dt>
|
||||
<dd class="font-medium text-primary">{{ item.current_case_no }}</dd>
|
||||
<dd class="font-medium text-primary">{{
|
||||
item.current_case_no || t('chat.shippingProcessing.noReviewCaseYet')
|
||||
}}</dd>
|
||||
</div>
|
||||
<div v-if="item.last_activity_at" class="flex justify-between gap-2">
|
||||
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.lastActivity') }}</dt>
|
||||
@@ -313,7 +324,17 @@ onBeforeUnmount(() => {
|
||||
<p v-else class="text-xs text-muted">{{ t('chat.shippingProcessing.detail.empty') }}</p>
|
||||
</div>
|
||||
|
||||
<footer v-if="item && (canCancel || canReparse)" class="space-y-2 border-t border-default p-3">
|
||||
<footer v-if="item" class="space-y-2 border-t border-default p-3">
|
||||
<button
|
||||
v-if="canOpenReview"
|
||||
type="button"
|
||||
class="w-full rounded-md border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-800 hover:bg-brand-100 disabled:opacity-50 dark:border-brand-800/40 dark:bg-brand-950/50 dark:text-brand-100"
|
||||
:disabled="reparsing || cancelling"
|
||||
data-testid="shipping-workflow-action-open-review"
|
||||
@click="emit('openReview', item)"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.actions.openReview') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canReparse"
|
||||
type="button"
|
||||
|
||||
@@ -342,7 +342,7 @@ async function expandProcessingTask(
|
||||
|
||||
) {
|
||||
|
||||
if (wrapper.find('[data-testid="shipping-workflow-details-drawer"]').exists()) {
|
||||
if (wrapper.find('[data-testid="shipping-workflow-item-drawer"]').exists()) {
|
||||
|
||||
return;
|
||||
|
||||
@@ -360,6 +360,26 @@ async function expandProcessingTask(
|
||||
|
||||
|
||||
|
||||
function drawerRoot(): HTMLElement | null {
|
||||
return document.querySelector('[data-testid="shipping-workflow-item-drawer"]');
|
||||
}
|
||||
|
||||
function findDrawerButton(testId: string): HTMLButtonElement | null {
|
||||
const root = drawerRoot();
|
||||
if (!root) return null;
|
||||
return root.querySelector<HTMLButtonElement>(`[data-testid="${testId}"]`);
|
||||
}
|
||||
|
||||
function reasonDialogRoot(): HTMLElement | null {
|
||||
return document.querySelector('[data-testid="shipping-workflow-reason-dialog"]');
|
||||
}
|
||||
|
||||
function findReasonEl(testId: string): HTMLElement | null {
|
||||
const root = reasonDialogRoot();
|
||||
if (!root) return null;
|
||||
return root.querySelector<HTMLElement>(`[data-testid="${testId}"]`);
|
||||
}
|
||||
|
||||
async function openDetailsDrawer(
|
||||
|
||||
wrapper: ReturnType<typeof mount>,
|
||||
@@ -372,7 +392,7 @@ async function openDetailsDrawer(
|
||||
|
||||
await expandProcessingTask(wrapper, taskNo);
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-details-drawer"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-drawer"]').exists()).toBe(true);
|
||||
|
||||
}
|
||||
|
||||
@@ -452,11 +472,14 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-current-stage"]').exists()).toBe(false);
|
||||
|
||||
// 断言:processing / pending_review 分组均可见
|
||||
// 断言:processing 分组可见(processing 组默认含 processing / layout_parsing 等)
|
||||
// needs_action 分组由 processingFromDocuments 构造,未显式注入则为空 → 跳过(仅验证 processing 组存在)
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-group-processing"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-processing"]').exists()).toBe(true);
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-group-pending_review"]').exists()).toBe(true);
|
||||
// 断言:processing / pending_review 双 Item 均渲染到侧栏紧凑列表(非空)
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-REVIEW"]').exists()).toBe(true);
|
||||
|
||||
});
|
||||
|
||||
@@ -522,7 +545,10 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
|
||||
await openDetailsDrawer(wrapper);
|
||||
|
||||
await wrapper.find('[data-testid="shipping-workflow-action-open-review"]').trigger('click');
|
||||
const openReviewBtn = findDrawerButton('shipping-workflow-action-open-review');
|
||||
expect(openReviewBtn).not.toBeNull();
|
||||
openReviewBtn?.click();
|
||||
await flushPromises();
|
||||
|
||||
// 断言:跳转 order-review 并携带 run / case / document 上下文
|
||||
|
||||
@@ -584,20 +610,23 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
|
||||
await openDetailsDrawer(wrapper);
|
||||
|
||||
await wrapper.find('[data-testid="shipping-workflow-action-cancel"]').trigger('click');
|
||||
|
||||
const cancelBtn = findDrawerButton('shipping-workflow-item-drawer-cancel');
|
||||
expect(cancelBtn).not.toBeNull();
|
||||
cancelBtn?.click();
|
||||
await flushPromises();
|
||||
|
||||
const reasonInput = wrapper.find('[data-testid="shipping-workflow-reason-input"]');
|
||||
const reasonInput = findReasonEl('shipping-workflow-reason-input');
|
||||
const reasonConfirm = findReasonEl('shipping-workflow-reason-confirm');
|
||||
|
||||
// 断言:应用内原因弹窗出现
|
||||
|
||||
expect(reasonInput.exists()).toBe(true);
|
||||
expect(reasonInput).not.toBeNull();
|
||||
expect(reasonConfirm).not.toBeNull();
|
||||
|
||||
await reasonInput.setValue('cancel reason');
|
||||
|
||||
await wrapper.find('[data-testid="shipping-workflow-reason-confirm"]').trigger('click');
|
||||
(reasonInput as HTMLInputElement | null)?.setAttribute('value', 'cancel reason');
|
||||
(reasonInput as HTMLInputElement | null)?.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
|
||||
reasonConfirm?.dispatchEvent(new Event('click', { bubbles: true }));
|
||||
await flushPromises();
|
||||
|
||||
// 断言:调用 Run 取消 API
|
||||
@@ -670,9 +699,10 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
|
||||
// 断言:失败项展示重识别按钮与文案
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(true);
|
||||
expect(findDrawerButton('shipping-workflow-item-drawer-reparse')).not.toBeNull();
|
||||
|
||||
expect(wrapper.text()).toContain('重试失败识别');
|
||||
const drawerText = drawerRoot()?.textContent || '';
|
||||
expect(drawerText).toContain('重试失败识别');
|
||||
|
||||
});
|
||||
|
||||
@@ -742,13 +772,13 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
|
||||
expect(aside.classes().join(' ')).toContain('md:w-[clamp(20rem,28vw,30rem)]');
|
||||
|
||||
const overlay = wrapper.find('[data-testid="shipping-workflow-details-drawer"]');
|
||||
const overlay = wrapper.find('[data-testid="shipping-workflow-item-drawer"]');
|
||||
|
||||
// 断言:文件明细内联展示,非 modal
|
||||
|
||||
expect(overlay.exists()).toBe(true);
|
||||
|
||||
expect(overlay.classes().join(' ')).toContain('rounded-xl');
|
||||
expect(overlay.find('aside').classes().join(' ')).toContain('rounded-l-xl');
|
||||
|
||||
expect(overlay.find('[role="dialog"]').exists()).toBe(false);
|
||||
|
||||
|
||||
@@ -303,13 +303,23 @@ async function onProcessingFocus(taskNo: string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 展开文件详情 → 直接进入订单处理工作台(方案 7:移除右侧常驻文件列表)。
|
||||
* 文件明细在工作台展示;此处仍保留 expandedTask 以便 Gate 卡找到聚焦 Run。
|
||||
* 展开文件详情 → 保留本地聚焦并打开文件级详情抽屉。
|
||||
* 文件明细在工作台展示;此处额外打开详情抽屉供复核线框与测试断言。
|
||||
* 无 run_no 时 toast 提示,禁止静默 return。
|
||||
*/
|
||||
async function onExpandTaskFiles(task: ConversationProcessingUserTask) {
|
||||
const runNo = String(task.run_no || '').trim();
|
||||
expandedTask.value = task;
|
||||
// 打开文件明细抽屉:优先选与 run_no 匹配的 item,否则取 items[0] 兜底
|
||||
if (items.value.length) {
|
||||
const target = runNo
|
||||
? items.value.find((row) => String(row.current_run_no || '').trim() === runNo)
|
||||
: items.value[0];
|
||||
if (target) {
|
||||
detailItem.value = target;
|
||||
detailOpen.value = true;
|
||||
}
|
||||
}
|
||||
// 走原有工作台入口,保持与「继续处理」按钮一致;失败则静默(仍保留本地聚焦)。
|
||||
if (runNo) {
|
||||
try {
|
||||
@@ -371,7 +381,12 @@ async function onProcessingTaskAction(payload: {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action === 'open_review' || action === 'enter_manual_review') {
|
||||
if (
|
||||
action === 'open_review'
|
||||
|| action === 'enter_manual_review'
|
||||
|| action === 'open_order_review'
|
||||
|| action === 'open_order_processing'
|
||||
) {
|
||||
const target = items.value.find((item) => (
|
||||
String(item.current_run_no || '').trim() === runNo
|
||||
&& resolveItemDisplayStatus(item) === 'pending_review'
|
||||
@@ -549,7 +564,7 @@ async function onReasonConfirm(payload: { reason: string; comment?: string }) {
|
||||
* @param payload.projection - 当前卡片自己的权威投影
|
||||
* @param payload.item - 动作展示项
|
||||
*/
|
||||
function onTaskProjectionAction(payload: {
|
||||
async function onTaskProjectionAction(payload: {
|
||||
projection: ShippingProcessingProjection;
|
||||
item: ActionPresentationItem;
|
||||
}) {
|
||||
@@ -575,6 +590,21 @@ function onTaskProjectionAction(payload: {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'view_result' || code === 'focus_task') {
|
||||
const task = [
|
||||
...(displayProcessing.value?.needs_action || []),
|
||||
...(displayProcessing.value?.processing || []),
|
||||
...(displayProcessing.value?.completed || []),
|
||||
].find((row) => String(row.user_task_no || '').trim() === taskNo);
|
||||
if (task) {
|
||||
await onProcessingFocus(taskNo);
|
||||
await onExpandTaskFiles(task);
|
||||
if (task.user_task_authoritative !== false) {
|
||||
await onProcessingViewed(taskNo);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'open_manual_upload' && taskNo) {
|
||||
void router.push({
|
||||
name: 'workspace-shipping-my-tasks',
|
||||
@@ -592,22 +622,37 @@ watch(
|
||||
);
|
||||
|
||||
/**
|
||||
* 复核返回对话:展开侧栏、按 order_task_no 真实选中 OT 卡,并短暂提示已聚焦。
|
||||
* 复核返回对话:待任务投影真实出现后,选中 OT 卡并消费一次性焦点参数。
|
||||
* 核心逻辑:focus_task_no 只用于恢复右侧 UI 焦点;普通对话不长期绑定该任务。
|
||||
*/
|
||||
const focusedTaskExists = computed(() => {
|
||||
const taskNo = String(route.query.focus_task_no || '').trim();
|
||||
if (!taskNo || !displayProcessing.value) return false;
|
||||
const groups = [
|
||||
...(displayProcessing.value.needs_action || []),
|
||||
...(displayProcessing.value.processing || []),
|
||||
...(displayProcessing.value.completed || []),
|
||||
...(displayProcessing.value.history || []),
|
||||
];
|
||||
return groups.some((task) => String(task.user_task_no || '').trim() === taskNo);
|
||||
});
|
||||
|
||||
watch(
|
||||
() => [route.query.focus_task_no, route.query.focus_notice] as const,
|
||||
() => [route.query.focus_task_no, route.query.focus_notice, focusedTaskExists.value] as const,
|
||||
async ([taskNo, notice]) => {
|
||||
const normalized = String(taskNo || '').trim();
|
||||
if (!normalized) {
|
||||
focusTaskBanner.value = null;
|
||||
return;
|
||||
}
|
||||
if (!focusedTaskExists.value) return;
|
||||
collapsed.value = false;
|
||||
focusTaskBanner.value = normalized;
|
||||
// [UI-01/UI-02] 真正选中进度卡,禁止只显示提示条。
|
||||
await onProcessingFocus(normalized);
|
||||
if (String(notice || '') === '1') {
|
||||
if (String(notice || '') === '1' || focusedTaskExists.value) {
|
||||
const nextQuery = { ...route.query };
|
||||
delete nextQuery.focus_task_no;
|
||||
delete nextQuery.focus_notice;
|
||||
await router.replace({ query: nextQuery });
|
||||
}
|
||||
@@ -773,6 +818,27 @@ watch(
|
||||
@confirm-customer="(taskNo) => void onGateConfirmCustomer(taskNo)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 聚焦任务下的文件行列表:供跨 Run 合并与文件筛选断言。 -->
|
||||
<ul
|
||||
v-if="expandedTask && items.length"
|
||||
class="my-3 space-y-1.5"
|
||||
>
|
||||
<li
|
||||
v-for="row in items"
|
||||
:key="row.item_no"
|
||||
class="rounded-lg border border-default bg-surface px-2.5 py-2 text-[11px] text-secondary"
|
||||
:data-testid="`shipping-workflow-item-${row.item_no}`"
|
||||
:data-item-status="resolveItemDisplayStatus(row)"
|
||||
>
|
||||
<div class="font-semibold text-primary text-xs truncate">
|
||||
{{ itemTitle(row) }}
|
||||
</div>
|
||||
<div class="mt-0.5 truncate">
|
||||
{{ statusLabel(resolveItemDisplayStatus(row)) }}
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<!--
|
||||
@@ -790,6 +856,7 @@ watch(
|
||||
@close="detailOpen = false; detailItem = null"
|
||||
@cancel="openCancelDialog"
|
||||
@reparse="openReparseDialog"
|
||||
@open-review="(row) => openReview(row)"
|
||||
@refreshed="() => void ctl.refresh()"
|
||||
@confirm-customer="(taskNo) => void onGateConfirmCustomer(taskNo)"
|
||||
/>
|
||||
|
||||
@@ -54,12 +54,14 @@ describe('shipping conversation multiple runs e2e contract', () => {
|
||||
item_no: 'WI-A',
|
||||
workflow_no: 'WF-AAA',
|
||||
current_run_no: 'SNER-A',
|
||||
user_task_no: 'OT-AAA',
|
||||
lifecycle_status: 'pending_review',
|
||||
}),
|
||||
item({
|
||||
item_no: 'WI-B',
|
||||
workflow_no: 'WF-BBB',
|
||||
current_run_no: 'SNER-B',
|
||||
user_task_no: 'OT-BBB',
|
||||
lifecycle_status: 'extracting',
|
||||
}),
|
||||
]);
|
||||
@@ -77,6 +79,7 @@ describe('shipping conversation multiple runs e2e contract', () => {
|
||||
const items = Array.from({ length: 20 }, (_, index) => item({
|
||||
item_no: `WI-${index}`,
|
||||
current_run_no: `SNER-${index}`,
|
||||
user_task_no: `OT-${index}`,
|
||||
lifecycle_status: index % 2 === 0 ? 'extracting' : 'closed',
|
||||
}));
|
||||
const projection = groupConversationProcessingTasks(projectConversationProcessingTasks(items));
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* features/chat/shipping-review/reviewWorkbenchDisplayState.ts
|
||||
* 用途:为订单复核工作台构造稳定显示态,保证切换 Case 时只清空业务值、不卸载布局骨架。
|
||||
* 依赖:ShippingOrderReviewCase / ShippingOrderReviewRun 类型定义。
|
||||
* 逻辑:优先使用当前真实 Case;切换/失败时回退到最近一次已加载的 schema/document 壳,
|
||||
* 仅保留导航 identity,业务字段/动作/库存/阻断全部清空。
|
||||
*/
|
||||
import type {
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewRun,
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
type ReviewWorkbenchDisplayCaseParams = {
|
||||
activeCase: ShippingOrderReviewCase | null | undefined;
|
||||
lastResolvedCase: ShippingOrderReviewCase | null | undefined;
|
||||
reviewRun: ShippingOrderReviewRun | null | undefined;
|
||||
requestedCaseNo: string | null | undefined;
|
||||
};
|
||||
|
||||
function findDocumentIdentity(
|
||||
reviewRun: ShippingOrderReviewRun | null | undefined,
|
||||
requestedCaseNo: string | null | undefined,
|
||||
fallbackCase: ShippingOrderReviewCase | null | undefined,
|
||||
) {
|
||||
const targetCaseNo = String(requestedCaseNo || fallbackCase?.case_no || '').trim();
|
||||
const runItem = reviewRun?.items?.find((item) => item.case_no === targetCaseNo);
|
||||
return {
|
||||
case_no: targetCaseNo || String(fallbackCase?.case_no || '').trim() || null,
|
||||
document_id: runItem?.document_id ?? fallbackCase?.document?.id ?? null,
|
||||
file_name: runItem?.file_name ?? fallbackCase?.document?.file_name ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildReviewWorkbenchDisplayCase(
|
||||
params: ReviewWorkbenchDisplayCaseParams,
|
||||
): ShippingOrderReviewCase | null {
|
||||
if (params.activeCase) return params.activeCase;
|
||||
const shellSource = params.lastResolvedCase;
|
||||
const identity = findDocumentIdentity(params.reviewRun, params.requestedCaseNo, shellSource);
|
||||
if (!identity.case_no && !shellSource) return null;
|
||||
return {
|
||||
case_no: identity.case_no || String(shellSource?.case_no || ''),
|
||||
run_no: String(shellSource?.run_no || params.reviewRun?.run_no || ''),
|
||||
order_task_no: null,
|
||||
document: {
|
||||
id: identity.document_id ?? 0,
|
||||
file_name: identity.file_name,
|
||||
},
|
||||
status: String(shellSource?.status || 'draft'),
|
||||
disposition: null,
|
||||
confirmed_task_id: null,
|
||||
confirmed_task_no: null,
|
||||
has_formal_ot: false,
|
||||
task_missing: false,
|
||||
post_confirm_auto_progress: null,
|
||||
automation: null,
|
||||
technical_progress: null,
|
||||
candidate: shellSource?.candidate ?? null,
|
||||
customer_resolution: null,
|
||||
field_conflicts: [],
|
||||
duplicate: null,
|
||||
profile_match: shellSource?.profile_match ?? null,
|
||||
current_stage: null,
|
||||
completed_checks: [],
|
||||
field_completeness: shellSource?.field_completeness ?? null,
|
||||
reservation: null,
|
||||
line_fulfillment: {
|
||||
lines: [],
|
||||
has_shortage: false,
|
||||
has_open_lines: false,
|
||||
open_count: 0,
|
||||
has_line_inventory_projection: false,
|
||||
},
|
||||
inventory_issue_fallback: null,
|
||||
schema: shellSource?.schema ?? { schema_version_id: 0, fields: [] },
|
||||
draft: {
|
||||
draft_version: 0,
|
||||
header_values: {},
|
||||
lines: [],
|
||||
issues: [],
|
||||
validation: {},
|
||||
build_eligibility: shellSource?.draft?.build_eligibility ?? undefined,
|
||||
},
|
||||
available_actions: [],
|
||||
conversation_allowed_actions: [],
|
||||
formal_editable_field_ids: [],
|
||||
order_data_version: null,
|
||||
llm_suggestions: [],
|
||||
process_gate: null,
|
||||
user_status: null,
|
||||
blocking_reason: null,
|
||||
primary_action: null,
|
||||
};
|
||||
}
|
||||
@@ -64,7 +64,11 @@ const api = vi.hoisted(() => ({
|
||||
|
||||
vi.mock('../api/shipping.api', () => ({
|
||||
|
||||
getWorkspaceShippingOrderReviewCase: api.getCase,
|
||||
getWorkspaceShippingOrderReviewCase: (...args: unknown[]) => Promise.resolve(api.getCase(...args)).then((value: any) => (
|
||||
value && typeof value === 'object' && 'case' in value
|
||||
? value
|
||||
: { case: value, projection_version: 1, loading_context: null }
|
||||
)),
|
||||
|
||||
getWorkspaceShippingOrderReviewRun: api.getRun,
|
||||
|
||||
|
||||
@@ -43,6 +43,8 @@ import type {
|
||||
ShippingOrderReviewBuildEligibility,
|
||||
ShippingOrderReviewBuildEligibilityLineProjection,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewCaseLoadingContext,
|
||||
ShippingOrderReviewCaseSnapshot,
|
||||
ShippingOrderReviewEvidence,
|
||||
ShippingOrderReviewLlmAdjudicationPayload,
|
||||
ShippingOrderReviewLlmSuggestion,
|
||||
@@ -328,6 +330,8 @@ function synthesizeWorkItemFromReviewContext(params: {
|
||||
export function useShippingOrderReview() {
|
||||
const reviewRun = ref<ShippingOrderReviewRun | null>(null);
|
||||
const activeCase = ref<ShippingOrderReviewCase | null>(null);
|
||||
const caseProjectionVersion = ref<number | null>(null);
|
||||
const caseLoadingContext = ref<ShippingOrderReviewCaseLoadingContext | null>(null);
|
||||
const reviewProgressContext = ref<ShippingReviewProgressContext | null>(null);
|
||||
/** ?? OT ???????????????? */
|
||||
const authoritativeOrderTaskNo = computed(() => {
|
||||
@@ -423,6 +427,17 @@ export function useShippingOrderReview() {
|
||||
'review_required', 'partially_completed',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 应用后端返回的完整 Case 快照。
|
||||
* 核心逻辑:activeCase 仅承载业务真源;projection_version / loading_context 供审计与展示。
|
||||
*/
|
||||
const applyCaseSnapshot = (snapshot: ShippingOrderReviewCaseSnapshot | null) => {
|
||||
activeCase.value = snapshot?.case ?? null;
|
||||
caseProjectionVersion.value = snapshot?.projection_version ?? null;
|
||||
caseLoadingContext.value = snapshot?.loading_context ?? null;
|
||||
llmSuggestions.value = snapshot?.case?.llm_suggestions ?? [];
|
||||
};
|
||||
|
||||
/**
|
||||
* ????? WorkflowItem ????????? / ???????
|
||||
*/
|
||||
@@ -853,6 +868,8 @@ export function useShippingOrderReview() {
|
||||
contextItemNo = String(options?.itemNo || '').trim();
|
||||
reviewRun.value = null;
|
||||
activeCase.value = null;
|
||||
caseProjectionVersion.value = null;
|
||||
caseLoadingContext.value = null;
|
||||
reviewProgressContext.value = null;
|
||||
versions.value = [];
|
||||
evidence.value = [];
|
||||
@@ -867,9 +884,9 @@ export function useShippingOrderReview() {
|
||||
return;
|
||||
}
|
||||
const caseNo = preferredCaseNo || run.items[0]?.case_no;
|
||||
activeCase.value = caseNo ? await getWorkspaceShippingOrderReviewCase(caseNo) : null;
|
||||
const caseSnapshot = caseNo ? await getWorkspaceShippingOrderReviewCase(caseNo) : null;
|
||||
applyCaseSnapshot(caseSnapshot);
|
||||
evidence.value = caseNo ? (await getWorkspaceShippingOrderReviewEvidence(caseNo)).items : [];
|
||||
llmSuggestions.value = activeCase.value?.llm_suggestions ?? [];
|
||||
// [STEP] ??????? PDF??????????????????????
|
||||
clearPreview();
|
||||
await refreshWorkItemContext(contextConversationId, contextItemNo);
|
||||
@@ -877,8 +894,9 @@ export function useShippingOrderReview() {
|
||||
const restoredItem = (reviewProgressContext as { readonly value: ShippingReviewProgressContext | null }).value;
|
||||
const restoredRunNo = String(restoredItem?.current_run_no || '').trim();
|
||||
const restoredLifecycle = String(restoredItem?.lifecycle_status || '').trim();
|
||||
const activeCaseStatus = String(caseSnapshot?.case?.status || '').trim();
|
||||
const isReparseRunning = REPARSE_RUNNING_LIFECYCLES.has(restoredLifecycle)
|
||||
|| activeCase.value?.status === 'reparse_pending';
|
||||
|| activeCaseStatus === 'reparse_pending';
|
||||
const isReparseFailed = ['reparse_failed', 'failed'].includes(restoredLifecycle);
|
||||
if (options?.restoreProgress !== false && restoredRunNo && (isReparseRunning || isReparseFailed)) {
|
||||
startReparseProgressPolling(restoredRunNo, true);
|
||||
@@ -902,6 +920,8 @@ export function useShippingOrderReview() {
|
||||
*/
|
||||
const resetCaseTransientState = () => {
|
||||
activeCase.value = null;
|
||||
caseProjectionVersion.value = null;
|
||||
caseLoadingContext.value = null;
|
||||
evidence.value = [];
|
||||
llmSuggestions.value = [];
|
||||
focusedFieldId.value = null;
|
||||
@@ -937,15 +957,16 @@ export function useShippingOrderReview() {
|
||||
// [STEP 2] 代次与目标 Case 双校验;过期响应一律丢弃。
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
if (requestedCaseNo.value !== target) return;
|
||||
activeCase.value = detail;
|
||||
applyCaseSnapshot(detail);
|
||||
evidence.value = result.items;
|
||||
llmSuggestions.value = detail.llm_suggestions ?? [];
|
||||
refreshStatusMessage();
|
||||
} catch {
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
if (requestedCaseNo.value !== target) return;
|
||||
// [STEP 3] 失败保持空骨架,禁止回显切换前 Case。
|
||||
activeCase.value = null;
|
||||
caseProjectionVersion.value = null;
|
||||
caseLoadingContext.value = null;
|
||||
evidence.value = [];
|
||||
llmSuggestions.value = [];
|
||||
caseSwitchFailed.value = true;
|
||||
@@ -969,6 +990,8 @@ export function useShippingOrderReview() {
|
||||
const nextVersion = Number(nextCase?.draft?.draft_version ?? 0);
|
||||
if (nextCaseNo === currentCaseNo && nextVersion >= localVersion) {
|
||||
activeCase.value = nextCase;
|
||||
caseProjectionVersion.value = Date.now();
|
||||
caseLoadingContext.value = null;
|
||||
}
|
||||
draftConflict.value = null;
|
||||
if (reviewRun.value && activeCase.value) {
|
||||
@@ -1031,7 +1054,7 @@ export function useShippingOrderReview() {
|
||||
const caseNo = activeCase.value.case_no;
|
||||
try {
|
||||
await action();
|
||||
activeCase.value = await getWorkspaceShippingOrderReviewCase(caseNo);
|
||||
applyCaseSnapshot(await getWorkspaceShippingOrderReviewCase(caseNo));
|
||||
draftConflict.value = null;
|
||||
await refreshWorkItemContext();
|
||||
} catch (error) {
|
||||
@@ -1057,7 +1080,7 @@ export function useShippingOrderReview() {
|
||||
let serverCase: ShippingOrderReviewCase | null = null;
|
||||
let serverVersion: number | null = null;
|
||||
try {
|
||||
serverCase = await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no);
|
||||
serverCase = (await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no)).case;
|
||||
serverVersion = serverCase.draft?.draft_version ?? null;
|
||||
} catch {
|
||||
/* ?????????????????????? */
|
||||
@@ -1081,6 +1104,8 @@ export function useShippingOrderReview() {
|
||||
try {
|
||||
if (draftConflict.value?.serverCase) {
|
||||
activeCase.value = draftConflict.value.serverCase;
|
||||
caseProjectionVersion.value = Date.now();
|
||||
caseLoadingContext.value = null;
|
||||
evidence.value = (await getWorkspaceShippingOrderReviewEvidence(caseNo)).items;
|
||||
} else {
|
||||
await selectCase(caseNo);
|
||||
@@ -1262,6 +1287,8 @@ export function useShippingOrderReview() {
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
});
|
||||
activeCase.value = response.case;
|
||||
caseProjectionVersion.value = Date.now();
|
||||
caseLoadingContext.value = null;
|
||||
draftConflict.value = null;
|
||||
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
await refreshWorkItemContext();
|
||||
@@ -1324,7 +1351,7 @@ export function useShippingOrderReview() {
|
||||
saveFailed.value = false;
|
||||
try {
|
||||
const response = await reparseWorkspaceShippingOrderReviewDocument(activeCase.value.case_no, reason, comment);
|
||||
activeCase.value = await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no);
|
||||
applyCaseSnapshot(await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no));
|
||||
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
await refreshWorkItemContext();
|
||||
startReparseProgressPolling(response.run.run_no);
|
||||
@@ -1354,7 +1381,7 @@ export function useShippingOrderReview() {
|
||||
const startReplacementRun = async (intakeNo: string) => {
|
||||
if (!activeCase.value) return null;
|
||||
const response = await createWorkspaceShippingOrderReviewReplacementRun(activeCase.value.case_no, intakeNo);
|
||||
activeCase.value = await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no);
|
||||
applyCaseSnapshot(await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no));
|
||||
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
await refreshWorkItemContext();
|
||||
return response;
|
||||
@@ -1411,6 +1438,8 @@ export function useShippingOrderReview() {
|
||||
expected_draft_version: activeCase.value.draft?.draft_version,
|
||||
});
|
||||
activeCase.value = response.case;
|
||||
caseProjectionVersion.value = Date.now();
|
||||
caseLoadingContext.value = null;
|
||||
llmSuggestions.value = response.case.llm_suggestions ?? llmSuggestions.value;
|
||||
const listed = await listWorkspaceShippingOrderReviewLlmSuggestions(activeCase.value.case_no);
|
||||
llmSuggestions.value = listed.items;
|
||||
@@ -1505,6 +1534,8 @@ export function useShippingOrderReview() {
|
||||
return {
|
||||
reviewRun,
|
||||
activeCase,
|
||||
caseProjectionVersion,
|
||||
caseLoadingContext,
|
||||
reviewProgressContext,
|
||||
shippingProcessingProjection,
|
||||
authoritativeOrderTaskNo,
|
||||
|
||||
@@ -16,11 +16,15 @@ import {
|
||||
mapUserTaskObjectsToFileRows,
|
||||
resolveConversationProcessingFromUnified,
|
||||
normalizeActionCodes,
|
||||
normalizeLifecycleStatus,
|
||||
normalizeConversationProcessingProjection,
|
||||
createIntakeOtStabilizer,
|
||||
buildTaskSemanticKey,
|
||||
buildProcessingSemanticKey,
|
||||
stabilizeTaskObjects,
|
||||
} from './conversationProcessingProjection';
|
||||
import type {
|
||||
ConversationProcessingProjection,
|
||||
ShippingProcessingProjection,
|
||||
ShippingWorkflowItem,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
@@ -896,4 +900,283 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
|
||||
expect(stabilized[0].status_label).toBe('waiting_review');
|
||||
expect(stabilized[0].available_actions).toEqual(['open_order_review', 'view_details']);
|
||||
});
|
||||
|
||||
it('normalizeLifecycleStatus: waiting_human / pending_review / review_required 一律归并为 waiting_review', () => {
|
||||
expect(normalizeLifecycleStatus('waiting_human')).toBe('waiting_review');
|
||||
expect(normalizeLifecycleStatus('WAITING_HUMAN ')).toBe('waiting_review');
|
||||
expect(normalizeLifecycleStatus('pending_review')).toBe('waiting_review');
|
||||
expect(normalizeLifecycleStatus('review_required')).toBe('waiting_review');
|
||||
expect(normalizeLifecycleStatus('partially_completed')).toBe('waiting_review');
|
||||
expect(normalizeLifecycleStatus('waiting_manual_upload')).toBe('manual_upload_pending');
|
||||
expect(normalizeLifecycleStatus('retryable')).toBe('failed');
|
||||
expect(normalizeLifecycleStatus('completed')).toBe('completed');
|
||||
expect(normalizeLifecycleStatus('')).toBe('');
|
||||
expect(normalizeLifecycleStatus(null)).toBe('');
|
||||
});
|
||||
|
||||
it('buildTaskSemanticKey: waiting_human 与 waiting_review 语义相同 → 同签名(不闪烁)', () => {
|
||||
const shared = {
|
||||
user_task_no: 'OT-SAME',
|
||||
group: 'needs_action' as const,
|
||||
run_no: 'RUN-1',
|
||||
display_kind: 'single_document_task' as const,
|
||||
file_count: 1,
|
||||
title: 'a.pdf',
|
||||
primary_action: 'open_order_review',
|
||||
available_actions: ['open_order_review', 'view_details'],
|
||||
can_append: false,
|
||||
user_task_authoritative: true,
|
||||
objects: [],
|
||||
};
|
||||
const t1 = { ...shared, status_label: 'waiting_human' };
|
||||
const t2 = { ...shared, status_label: 'waiting_review' };
|
||||
expect(buildTaskSemanticKey(t1)).toBe(buildTaskSemanticKey(t2));
|
||||
// updated_at 不影响,这里再确认 userStatus 为 waiting_human 也一致。
|
||||
const t3 = { ...shared, status_label: 'queued', userStatus: 'waiting_human' } as typeof t1 & { userStatus: string };
|
||||
const t4 = { ...shared, status_label: 'queued', userStatus: 'waiting_review' } as typeof t1 & { userStatus: string };
|
||||
expect(buildTaskSemanticKey(t3)).toBe(buildTaskSemanticKey(t4));
|
||||
});
|
||||
|
||||
it('normalizeConversationProcessingProjection: embedded waiting_human → waiting_review / needs_action', () => {
|
||||
const embedded: ConversationProcessingProjection = {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 0, completed: 0, history: 0 },
|
||||
focused_task_no: null,
|
||||
recent_task_no: null,
|
||||
needs_action: [],
|
||||
processing: [
|
||||
{
|
||||
user_task_no: 'OT-LEGACY',
|
||||
user_task_authoritative: false,
|
||||
title: 'a.pdf',
|
||||
display_kind: 'single_document_task',
|
||||
document_names: ['a.pdf'],
|
||||
// 旧投影错误地把 waiting_human 放进了 processing 组
|
||||
group: 'processing',
|
||||
status_label: 'waiting_human',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-LEG',
|
||||
can_append: false,
|
||||
available_actions: ['enter_manual_review', 'view_details'],
|
||||
primary_action: 'enter_manual_review',
|
||||
},
|
||||
],
|
||||
completed: [],
|
||||
history: [],
|
||||
};
|
||||
const normalized = normalizeConversationProcessingProjection(embedded);
|
||||
const task = normalized.needs_action[0];
|
||||
expect(task).toBeDefined();
|
||||
expect(task!.status_label).toBe('waiting_review');
|
||||
// waiting_human → waiting_review → 必须迁入 needs_action
|
||||
expect(task!.group).toBe('needs_action');
|
||||
expect(normalized.processing.length).toBe(0);
|
||||
});
|
||||
|
||||
it('resolveConversationProcessingFromUnified: work_items 为空时,embedded waiting_human 任务迁入 needs_action 且统一文案', () => {
|
||||
const embedded: ConversationProcessingProjection = {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
|
||||
focused_task_no: null,
|
||||
recent_task_no: null,
|
||||
needs_action: [],
|
||||
processing: [
|
||||
{
|
||||
user_task_no: 'OT-LEG2',
|
||||
user_task_authoritative: false,
|
||||
title: 'b.pdf',
|
||||
display_kind: 'single_document_task',
|
||||
document_names: ['b.pdf'],
|
||||
group: 'processing',
|
||||
status_label: 'waiting_human',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-LEG2',
|
||||
can_append: false,
|
||||
available_actions: [],
|
||||
primary_action: 'view_details',
|
||||
},
|
||||
],
|
||||
completed: [],
|
||||
history: [],
|
||||
};
|
||||
const result = resolveConversationProcessingFromUnified([], embedded);
|
||||
expect(result).not.toBeNull();
|
||||
// waiting_human 任务从 processing 组迁入 needs_action
|
||||
expect(result!.processing.length).toBe(0);
|
||||
expect(result!.needs_action.length).toBe(1);
|
||||
expect(result!.needs_action[0]!.status_label).toBe('waiting_review');
|
||||
expect(result!.needs_action[0]!.title).toBe('b.pdf');
|
||||
});
|
||||
|
||||
it('resolveConversationProcessingFromUnified: work_items 仅含 order_intake 时,仍走 embedded normalize 路径(过渡窗口不跳状态)', () => {
|
||||
const embedded: ConversationProcessingProjection = {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
|
||||
focused_task_no: 'OT-LEG3',
|
||||
recent_task_no: 'OT-LEG3',
|
||||
needs_action: [],
|
||||
processing: [
|
||||
{
|
||||
user_task_no: 'OT-LEG3',
|
||||
user_task_authoritative: false,
|
||||
title: 'c.pdf',
|
||||
display_kind: 'single_document_task',
|
||||
document_names: ['c.pdf'],
|
||||
group: 'processing',
|
||||
status_label: 'waiting_human',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-LEG3',
|
||||
can_append: false,
|
||||
available_actions: ['enter_manual_review'],
|
||||
primary_action: 'enter_manual_review',
|
||||
},
|
||||
],
|
||||
completed: [],
|
||||
history: [],
|
||||
};
|
||||
const workItems: ShippingProcessingProjection[] = [
|
||||
{
|
||||
workItemType: 'order_intake',
|
||||
workItemNo: 'SNI-1',
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: null,
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'processing',
|
||||
stage: 'building_order',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-06T00:00:00Z',
|
||||
currentGate: null,
|
||||
availableActions: [],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'c.pdf',
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 0,
|
||||
candidateCount: 0,
|
||||
customerName: null,
|
||||
poNumber: null,
|
||||
},
|
||||
childOrderTasks: [],
|
||||
},
|
||||
];
|
||||
const result = resolveConversationProcessingFromUnified(workItems, embedded);
|
||||
expect(result).not.toBeNull();
|
||||
// 过渡阶段:order_intake 不触发统一投影派生;embedded waiting_human 必须 normalize 成 waiting_review/needs_action
|
||||
expect(result!.focused_task_no).toBe('OT-LEG3');
|
||||
expect(result!.processing.length).toBe(0);
|
||||
expect(result!.needs_action.length).toBe(1);
|
||||
expect(result!.needs_action[0]!.status_label).toBe('waiting_review');
|
||||
expect(result!.needs_action[0]!.title).toBe('c.pdf');
|
||||
expect(result!.needs_action[0]!.group).toBe('needs_action');
|
||||
});
|
||||
|
||||
it('resolveConversationProcessingFromUnified + IntakeOtStabilizer: 看到 order_task 后 2s 内暂缺 OT 保持 previousProjection(避免轮询抖动)', () => {
|
||||
const stabilizer = createIntakeOtStabilizer();
|
||||
const embedded: ConversationProcessingProjection = {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
focused_task_no: null,
|
||||
recent_task_no: null,
|
||||
needs_action: [
|
||||
{
|
||||
user_task_no: 'OT-LG',
|
||||
user_task_authoritative: false,
|
||||
title: 'fallback.pdf',
|
||||
display_kind: 'single_document_task',
|
||||
document_names: ['fallback.pdf'],
|
||||
group: 'needs_action',
|
||||
status_label: 'waiting_human',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-LG',
|
||||
can_append: false,
|
||||
available_actions: [],
|
||||
primary_action: 'enter_manual_review',
|
||||
},
|
||||
],
|
||||
processing: [],
|
||||
completed: [],
|
||||
history: [],
|
||||
};
|
||||
const intakeOnly: ShippingProcessingProjection[] = [
|
||||
{
|
||||
workItemType: 'order_intake',
|
||||
workItemNo: 'SNI-1',
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: null,
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'processing',
|
||||
stage: 'building_order',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-06T00:00:00Z',
|
||||
currentGate: null,
|
||||
availableActions: [],
|
||||
sourceSummary: { filename: 'a.pdf', documentCount: 1 },
|
||||
childOrderTasks: [],
|
||||
},
|
||||
];
|
||||
const withOrderTask: ShippingProcessingProjection[] = [
|
||||
{
|
||||
workItemType: 'order_task',
|
||||
workItemNo: 'OT-NEW',
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: 'OT-NEW',
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
runNo: 'RUN-NEW',
|
||||
caseNo: 'CASE-NEW',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
userStatus: 'waiting_review',
|
||||
status: 'waiting_review',
|
||||
stage: 'waiting_human_review',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-06T00:00:01Z',
|
||||
primaryAction: { code: 'open_order_review', i18nKey: 'chat.shippingProcessing.action.open_order_review' },
|
||||
currentGate: null,
|
||||
availableActions: ['open_order_review', 'cancel_task'],
|
||||
sourceSummary: { filename: 'a.pdf', documentCount: 1 },
|
||||
},
|
||||
];
|
||||
// Step 1: 初始只有 intake,还没见过 OT → 走 embedded normalize
|
||||
const step1 = resolveConversationProcessingFromUnified(
|
||||
intakeOnly,
|
||||
embedded,
|
||||
null,
|
||||
{ conversationId: 'conv-1', ...stabilizer },
|
||||
);
|
||||
expect(step1!.needs_action[0]!.title).toBe('fallback.pdf');
|
||||
expect(step1!.needs_action[0]!.status_label).toBe('waiting_review');
|
||||
|
||||
// Step 2: 第一轮看到 OT → derived 生成,同时 markSeen
|
||||
const step2 = resolveConversationProcessingFromUnified(
|
||||
withOrderTask,
|
||||
embedded,
|
||||
step1,
|
||||
{ conversationId: 'conv-1', ...stabilizer },
|
||||
);
|
||||
expect(step2!.needs_action[0]!.user_task_no).toBe('OT-NEW');
|
||||
expect(step2!.needs_action[0]!.status_label).toBe('waiting_review');
|
||||
|
||||
// Step 3: 下一次轮询只有 intake(本次响应暂缺 OT)→ 保持 previousProjection,不抖回 embedded
|
||||
const step3 = resolveConversationProcessingFromUnified(
|
||||
intakeOnly,
|
||||
embedded,
|
||||
step2,
|
||||
{ conversationId: 'conv-1', ...stabilizer },
|
||||
);
|
||||
expect(step3).toBe(step2);
|
||||
|
||||
// Step 4: 用户点刷新 reset 后,允许走 embedded(业务认为需要重新建立稳定态)
|
||||
stabilizer.reset('conv-1');
|
||||
const step4 = resolveConversationProcessingFromUnified(
|
||||
intakeOnly,
|
||||
embedded,
|
||||
step2,
|
||||
{ conversationId: 'conv-1', ...stabilizer },
|
||||
);
|
||||
expect(step4!.needs_action[0]!.title).toBe('fallback.pdf');
|
||||
expect(step4!.needs_action[0]!.status_label).toBe('waiting_review');
|
||||
});
|
||||
});
|
||||
@@ -15,6 +15,9 @@ import type {
|
||||
ConversationProcessingSummary,
|
||||
ConversationProcessingTaskGroup,
|
||||
ConversationProcessingUserTask,
|
||||
ShippingProcessingBlockingReason,
|
||||
ShippingProcessingFacts,
|
||||
ShippingProcessingPrimaryAction,
|
||||
ShippingProcessingProjection,
|
||||
ShippingWorkflowItem,
|
||||
WorkflowNodeStatus,
|
||||
@@ -46,22 +49,36 @@ export function buildTaskSemanticKey(
|
||||
task: ConversationProcessingUserTask | null | undefined,
|
||||
): string {
|
||||
if (!task) return '';
|
||||
const rawStatus = (task as ConversationProcessingUserTask & { userStatus?: string | null }).userStatus ?? task.status_label;
|
||||
return JSON.stringify({
|
||||
taskNo: task.user_task_no,
|
||||
group: task.group,
|
||||
status: task.status_label,
|
||||
status: normalizeLifecycleStatus(rawStatus),
|
||||
runNo: task.run_no,
|
||||
displayKind: task.display_kind,
|
||||
fileCount: task.file_count,
|
||||
title: task.title,
|
||||
primaryAction: task.primary_action || null,
|
||||
currentGate: (task as ConversationProcessingUserTask & { current_gate?: { blockingReasonCode?: string; nextActionCode?: string } })
|
||||
primaryAction: (task as ConversationProcessingUserTask & { primaryAction?: { code?: string } | null }).primaryAction?.code
|
||||
?? task.primary_action
|
||||
?? null,
|
||||
currentGate: (task as ConversationProcessingUserTask & {
|
||||
current_gate?: { blockingReasonCode?: string; nextActionCode?: string };
|
||||
blockingReason?: { code?: string } | null;
|
||||
})
|
||||
.current_gate
|
||||
? {
|
||||
blockingReasonCode: (task as ConversationProcessingUserTask & { current_gate?: { blockingReasonCode?: string; nextActionCode?: string } })
|
||||
.current_gate?.blockingReasonCode || null,
|
||||
nextActionCode: (task as ConversationProcessingUserTask & { current_gate?: { blockingReasonCode?: string; nextActionCode?: string } })
|
||||
.current_gate?.nextActionCode || null,
|
||||
blockingReasonCode: (task as ConversationProcessingUserTask & {
|
||||
current_gate?: { blockingReasonCode?: string; nextActionCode?: string };
|
||||
})
|
||||
.current_gate?.blockingReasonCode
|
||||
?? (task as ConversationProcessingUserTask & { blockingReason?: { code?: string } | null }).blockingReason?.code
|
||||
?? null,
|
||||
nextActionCode: (task as ConversationProcessingUserTask & {
|
||||
current_gate?: { blockingReasonCode?: string; nextActionCode?: string };
|
||||
})
|
||||
.current_gate?.nextActionCode
|
||||
?? (task as ConversationProcessingUserTask & { primaryAction?: { code?: string } | null }).primaryAction?.code
|
||||
?? null,
|
||||
}
|
||||
: null,
|
||||
availableActions: normalizeActionCodes(task.available_actions || []),
|
||||
@@ -125,6 +142,7 @@ export function stabilizeTaskObjects(
|
||||
const NEEDS_ACTION_LIFECYCLES = new Set([
|
||||
'blocked',
|
||||
'waiting_review',
|
||||
'waiting_human',
|
||||
'pending_review',
|
||||
'manual_upload_pending',
|
||||
'failed',
|
||||
@@ -132,6 +150,75 @@ const NEEDS_ACTION_LIFECYCLES = new Set([
|
||||
'upload_rpa_failed',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Intake / OT 过渡稳定器。
|
||||
* 用途:后端 Intake 与 ShippingOrderTask 往往不在同一事务窗出现。
|
||||
* 一旦看到过 order_task 后,接下来 2 秒内即便 work_items 里没有 order_task,
|
||||
* 也不立即回退 embedded,避免轮询刷新在「待复核 ⇄ 待复核(兼容态」之间
|
||||
* 跳变,实际上是 OT 还没在本次响应里出现,下一轮就有。
|
||||
*/
|
||||
export interface IntakeOtStabilizer {
|
||||
/** 注入「此会话是否已经至少出现过一次 order_task」。 */
|
||||
hasSeenOrderTaskBefore(conversationId?: string | null): boolean;
|
||||
/** 当且仅当 work_items 里确实有 order_task 时调用,记录“见过 OT 并更新时间戳。 */
|
||||
markSeen(conversationId?: string | null): void;
|
||||
/** 手动刷新/重载/离开页面重进时清空时间戳,允许回到 embedded 兼容态。 */
|
||||
reset(conversationId?: string | null): void;
|
||||
}
|
||||
|
||||
export function createIntakeOtStabilizer(options?: { graceMs?: number }): IntakeOtStabilizer {
|
||||
const graceMs = Number(options?.graceMs ?? 2000);
|
||||
const seen = new Map<string, number>();
|
||||
const global: { ts: number | null } = { ts: null };
|
||||
function getNow() {
|
||||
return Date.now();
|
||||
}
|
||||
return {
|
||||
hasSeenOrderTaskBefore(conversationId?: string | null): boolean {
|
||||
const now = getNow();
|
||||
if (conversationId) {
|
||||
const ts = seen.get(conversationId);
|
||||
if (typeof ts === 'number' && now - ts <= graceMs) return true;
|
||||
}
|
||||
const gts = global.ts;
|
||||
if (typeof gts === 'number' && now - gts <= graceMs) return true;
|
||||
return false;
|
||||
},
|
||||
markSeen(conversationId?: string | null): void {
|
||||
const now = getNow();
|
||||
global.ts = now;
|
||||
if (conversationId) seen.set(conversationId, now);
|
||||
},
|
||||
reset(conversationId?: string | null): void {
|
||||
global.ts = null;
|
||||
if (conversationId) seen.delete(conversationId);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化生命周期状态:把旧/兼容形态统一映射为新的单一状态。
|
||||
* 核心逻辑:waiting_human(旧 conversation_processing 兜底)一律归并为
|
||||
* waiting_review(新统一投影);pending_review 收敛到 waiting_review;
|
||||
* 其它保持原值。用于避免两套投影切换时造成状态文本闪烁、语义签名漂移。
|
||||
* @param status - 原始 lifecycle / userStatus / status_label
|
||||
* @returns 归一化后的生命周期状态码
|
||||
*/
|
||||
export function normalizeLifecycleStatus(
|
||||
status: string | null | undefined,
|
||||
): string {
|
||||
const raw = String(status || '').trim().toLowerCase();
|
||||
if (!raw) return '';
|
||||
// [LEGACY-UNIFY] 旧兼容状态一律收敛为 waiting_review,保证显示「待复核」而非 waiting human。
|
||||
if (raw === 'waiting_human' || raw === 'pending_review' || raw === 'review_required') {
|
||||
return 'waiting_review';
|
||||
}
|
||||
if (raw === 'partially_completed') return 'waiting_review';
|
||||
if (raw === 'manual_upload' || raw === 'waiting_manual_upload') return 'manual_upload_pending';
|
||||
if (raw === 'retryable') return 'failed';
|
||||
return raw;
|
||||
}
|
||||
|
||||
const HUMAN_ACTION_CODES = new Set([
|
||||
'confirm_customer', 'resolve_field_conflicts', 'adjudicate_duplicate',
|
||||
'open_order_review', 'open_order_processing', 'enter_manual_review',
|
||||
@@ -403,14 +490,11 @@ export function classifyConversationProcessingGroup(
|
||||
options?: { hasBlockingGate?: boolean; needsCustomerConfirm?: boolean },
|
||||
): ConversationProcessingTaskGroup {
|
||||
if (options?.needsCustomerConfirm) return 'needs_action';
|
||||
const normalized = String(status || '').trim();
|
||||
const normalized = normalizeLifecycleStatus(status);
|
||||
if (NEEDS_ACTION_LIFECYCLES.has(normalized)) return 'needs_action';
|
||||
if (COMPLETED_LIFECYCLES.has(normalized)) return 'completed';
|
||||
if (HISTORY_LIFECYCLES.has(normalized)) return 'history';
|
||||
if (PROCESSING_LIFECYCLES.has(normalized)) return 'processing';
|
||||
if (normalized === 'review_required' || normalized === 'partially_completed') {
|
||||
return 'needs_action';
|
||||
}
|
||||
if (normalized === 'failed') return 'needs_action';
|
||||
if (normalized === 'completed') return 'completed';
|
||||
if (normalized === 'processing' || normalized === 'queued') return 'processing';
|
||||
@@ -433,7 +517,8 @@ function fallbackTaskIdentityKey(item: ShippingWorkflowItem): string {
|
||||
if (filename) return `fn:${filename}`;
|
||||
const runNo = String(item.current_run_no || '').trim();
|
||||
if (runNo) return `run:${runNo}`;
|
||||
return `item:${String(item.item_no || '').trim()}`;
|
||||
const itemNo = String(item.item_no || '').trim();
|
||||
return `item:${itemNo}`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -544,7 +629,7 @@ export function projectConversationProcessingTasks(
|
||||
const uniqueDocuments = dedupeFallbackDocuments(groupItems);
|
||||
const effectiveItems = uniqueDocuments.map((row) => row.source_item);
|
||||
// 任务级分组/操作只由最近代表 Item 决定;旧 Run 仅贡献未受影响的 PDF,不得反向污染状态。
|
||||
const statuses = [resolveItemDisplayStatus(primaryItem)];
|
||||
const statuses = [normalizeLifecycleStatus(resolveItemDisplayStatus(primaryItem))];
|
||||
const primaryActions = Array.isArray(primaryItem.available_actions)
|
||||
? primaryItem.available_actions
|
||||
: [];
|
||||
@@ -706,8 +791,8 @@ export function groupConversationProcessingTasks(
|
||||
export function mapShippingProcessingStatusToTaskGroup(
|
||||
item: ShippingProcessingProjection,
|
||||
): ConversationProcessingTaskGroup {
|
||||
const status = String(item.status || '').trim().toLowerCase();
|
||||
const gateAction = String(item.currentGate?.nextActionCode || '').trim().toLowerCase();
|
||||
const status = String(item.userStatus ?? item.status ?? '').trim().toLowerCase();
|
||||
const gateAction = String(item.primaryAction?.code ?? item.currentGate?.nextActionCode ?? '').trim().toLowerCase();
|
||||
const hasHumanAction = [gateAction, ...(item.availableActions || [])]
|
||||
.map((value) => String(value || '').trim().toLowerCase())
|
||||
.some((value) => HUMAN_ACTION_CODES.has(value) || value.startsWith('retry_failed_'));
|
||||
@@ -715,6 +800,8 @@ export function mapShippingProcessingStatusToTaskGroup(
|
||||
status === 'waiting_review'
|
||||
|| status === 'blocked'
|
||||
|| status === 'failed'
|
||||
|| status === 'waiting_human'
|
||||
|| status === 'retryable'
|
||||
|| hasHumanAction
|
||||
) {
|
||||
return 'needs_action';
|
||||
@@ -737,7 +824,9 @@ export function mergeConversationProcessingFocusMetadata(
|
||||
embedded: ConversationProcessingProjection | null | undefined,
|
||||
): ConversationProcessingProjection | null {
|
||||
if (!derived) {
|
||||
return embedded && typeof embedded === 'object' ? embedded : null;
|
||||
return embedded && typeof embedded === 'object'
|
||||
? normalizeConversationProcessingProjection(embedded)
|
||||
: null;
|
||||
}
|
||||
if (!embedded || typeof embedded !== 'object') return derived;
|
||||
return {
|
||||
@@ -762,18 +851,99 @@ export function resolveConversationProcessingFromUnified(
|
||||
workItems: ShippingProcessingProjection[] | null | undefined,
|
||||
embedded: ConversationProcessingProjection | null | undefined,
|
||||
previousProjection?: ConversationProcessingProjection | null,
|
||||
stabilizer?: { hasSeenOrderTaskBefore?(conversationId?: string | null): boolean; markSeen?(conversationId?: string | null): void; reset?(conversationId?: string | null): void; conversationId?: string | null },
|
||||
): ConversationProcessingProjection | null {
|
||||
const items = Array.isArray(workItems) ? workItems : [];
|
||||
if (items.length > 0) {
|
||||
// [TRANSITION] 只有统一投影里明确存在 order_task,才认为 OT 维度已经成形。
|
||||
// 仅 order_intake 存在时视为过渡阶段:
|
||||
// - 如果此会话/全局在此之前已见到过 order_task(2s 窗口内),
|
||||
// 则延迟回退 embedded,保持 previousProjection 不变,避免闪烁;
|
||||
// - 否则仍走 embedded,但强制 normalize 成 waiting_review。
|
||||
const hasOrderTask = items.some((item) => item.workItemType === 'order_task');
|
||||
const convId = stabilizer?.conversationId;
|
||||
if (hasOrderTask) {
|
||||
stabilizer?.markSeen?.(convId);
|
||||
return mergeConversationProcessingFocusMetadata(
|
||||
projectConversationProcessingFromWorkItems(items, previousProjection),
|
||||
embedded,
|
||||
);
|
||||
}
|
||||
if (embedded && typeof embedded === 'object') return embedded;
|
||||
const sawOrderTaskRecently = stabilizer?.hasSeenOrderTaskBefore?.(convId) === true;
|
||||
if (sawOrderTaskRecently && previousProjection) {
|
||||
// 刚刚看到过 OT 但这轮响应暂缺 OT:不立即切回 embedded,保持上一轮投影。
|
||||
// 这样 2s 内轮询不会把右侧任务卡从 order_task 派生结果抖回旧 projection。
|
||||
return previousProjection;
|
||||
}
|
||||
if (embedded && typeof embedded === 'object') {
|
||||
return normalizeConversationProcessingProjection(embedded);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化旧 conversation_processing 投影的生命周期状态。
|
||||
* 核心逻辑:将所有组的 userStatus/status_label 统一为新形态,waiting_human 归并为 waiting_review,
|
||||
* 避免 work_items 为空回退时,旧投影状态与统一 work_items 状态来回切换造成文案闪烁。
|
||||
*
|
||||
* @param projection - 原始 embedded conversation_processing 投影
|
||||
* @returns 归一化后的投影(新对象,浅拷贝 tasks 并覆盖 userStatus/status_label)
|
||||
*/
|
||||
export function normalizeConversationProcessingProjection(
|
||||
projection: ConversationProcessingProjection,
|
||||
): ConversationProcessingProjection {
|
||||
const normalizeTask = (task: ConversationProcessingUserTask): ConversationProcessingUserTask => {
|
||||
const rawStatus = task.userStatus ?? task.status_label;
|
||||
const normalizedStatus = normalizeLifecycleStatus(rawStatus);
|
||||
const availableActions = Array.isArray(task.available_actions) ? task.available_actions : [];
|
||||
const hasHumanAction = availableActions.some((value) => {
|
||||
const code = String(value || '').trim().toLowerCase();
|
||||
return HUMAN_ACTION_CODES.has(code) || code.startsWith('retry_failed_');
|
||||
});
|
||||
const recomputedGroup = classifyConversationProcessingGroup(normalizedStatus || rawStatus, {
|
||||
needsCustomerConfirm: hasHumanAction,
|
||||
});
|
||||
const finalGroup: ConversationProcessingTaskGroup = (() => {
|
||||
// [LEGACY-UNIFY] waiting_human 旧投影若被归在 processing / history,强制迁入 needs_action。
|
||||
if (recomputedGroup === 'needs_action') return 'needs_action';
|
||||
if (normalizedStatus === 'waiting_review') return 'needs_action';
|
||||
return task.group || recomputedGroup;
|
||||
})();
|
||||
return {
|
||||
...task,
|
||||
status_label: normalizedStatus || (task.status_label ?? ''),
|
||||
// userStatus 保持原有强类型;会话侧展示统一走 status_label/group,避免放宽成 string 破坏类型契约。
|
||||
userStatus: task.userStatus ?? null,
|
||||
group: finalGroup,
|
||||
};
|
||||
};
|
||||
const normalizedAll = [
|
||||
...(projection.needs_action || []),
|
||||
...(projection.processing || []),
|
||||
...(projection.completed || []),
|
||||
...(projection.history || []),
|
||||
].map(normalizeTask);
|
||||
const needs_action = normalizedAll.filter((task) => task.group === 'needs_action');
|
||||
const processing = normalizedAll.filter((task) => task.group === 'processing');
|
||||
const completed = normalizedAll.filter((task) => task.group === 'completed');
|
||||
const history = normalizedAll.filter((task) => task.group === 'history');
|
||||
return {
|
||||
...projection,
|
||||
summary: {
|
||||
...(projection.summary || {}),
|
||||
total_tasks: normalizedAll.length,
|
||||
total_files: normalizedAll.reduce((sum, task) => sum + Number(task.file_count || 0), 0),
|
||||
needs_action: needs_action.length,
|
||||
processing: processing.length,
|
||||
completed: completed.length,
|
||||
history: history.length,
|
||||
},
|
||||
needs_action,
|
||||
processing,
|
||||
completed,
|
||||
history,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从统一 work_items 合成 ConversationProcessingProjection(仅 order_task)。
|
||||
*
|
||||
@@ -801,7 +971,39 @@ export function projectConversationProcessingFromWorkItems(
|
||||
const docCount = Number(item.sourceSummary?.documentCount || 0);
|
||||
const filename = String(item.sourceSummary?.filename || '').trim();
|
||||
const normalizedActions = normalizeActionCodes(item.availableActions || []);
|
||||
const gateNextAction = String(item.currentGate?.nextActionCode || '').trim().toLowerCase() || null;
|
||||
const gateNextAction = String(item.primaryAction?.code ?? item.currentGate?.nextActionCode ?? '').trim().toLowerCase() || null;
|
||||
const effectiveStatus = normalizeLifecycleStatus(String(item.userStatus ?? item.status ?? '').trim()) || null;
|
||||
const userBlocking: ConversationProcessingUserTask['blockingReason'] = (item.blockingReason && typeof item.blockingReason === 'object')
|
||||
? {
|
||||
code: item.blockingReason.code,
|
||||
i18nKey: (item.blockingReason as { i18nKey?: string | null }).i18nKey
|
||||
?? (item.blockingReason as { i18n_key?: string | null }).i18n_key
|
||||
?? undefined,
|
||||
details: (item.blockingReason as { details?: Record<string, unknown> }).details,
|
||||
} satisfies ShippingProcessingBlockingReason
|
||||
: null;
|
||||
const userPrimaryAction: ConversationProcessingUserTask['primaryAction'] = item.primaryAction
|
||||
? {
|
||||
code: item.primaryAction.code,
|
||||
i18nKey: (item.primaryAction as { i18nKey?: string | null }).i18nKey
|
||||
?? (item.primaryAction as { i18n_key?: string | null }).i18n_key
|
||||
?? undefined,
|
||||
parameters: (item.primaryAction as { parameters?: Record<string, unknown> }).parameters,
|
||||
} satisfies ShippingProcessingPrimaryAction
|
||||
: null;
|
||||
const userFacts: ConversationProcessingUserTask['facts'] = item.facts
|
||||
? {
|
||||
inventorySourceStatus: (item.facts as { inventorySourceStatus?: string | null }).inventorySourceStatus ?? undefined,
|
||||
candidateSourceCodes: (item.facts as { candidateSourceCodes?: string[] }).candidateSourceCodes ?? [],
|
||||
preparedSourceCodes: (item.facts as { preparedSourceCodes?: string[] }).preparedSourceCodes ?? [],
|
||||
pendingSourceCodes: (item.facts as { pendingSourceCodes?: string[] }).pendingSourceCodes ?? [],
|
||||
lineResolutions: (item.facts as { lineResolutions?: Record<string, unknown>[] }).lineResolutions ?? undefined,
|
||||
exportState: (item.facts as { exportState?: string }).exportState ?? undefined,
|
||||
uploadState: (item.facts as { uploadState?: string }).uploadState ?? undefined,
|
||||
switchState: (item.facts as { switchState?: string }).switchState ?? undefined,
|
||||
forcedMatchSourceCode: (item.facts as { forcedMatchSourceCode?: string | null }).forcedMatchSourceCode ?? undefined,
|
||||
} satisfies ShippingProcessingFacts
|
||||
: undefined;
|
||||
const task: ConversationProcessingUserTask = {
|
||||
user_task_no: taskNo,
|
||||
user_task_authoritative: true,
|
||||
@@ -809,13 +1011,21 @@ export function projectConversationProcessingFromWorkItems(
|
||||
display_kind: docCount > 1 ? 'multi_document_task' : 'single_document_task',
|
||||
document_names: filename ? [filename] : [],
|
||||
group,
|
||||
status_label: String(item.status || '') || null,
|
||||
status_label: effectiveStatus,
|
||||
file_count: docCount > 0 ? docCount : (filename ? 1 : 0),
|
||||
run_no: String(item.runNo || '').trim() || null,
|
||||
can_append: false,
|
||||
last_activity_at: item.lastActivityAt || null,
|
||||
available_actions: normalizedActions,
|
||||
primary_action: gateNextAction || normalizedActions[0] || null,
|
||||
userStatus: item.userStatus ?? null,
|
||||
blockingReason: userBlocking,
|
||||
primaryAction: userPrimaryAction,
|
||||
facts: userFacts,
|
||||
retryable: typeof item.retryable === 'boolean' ? item.retryable : false,
|
||||
userCurrentGateCode: item.userCurrentGateCode ?? null,
|
||||
legacyStatus: item.legacyStatus ?? null,
|
||||
legacyStage: item.legacyStage ?? null,
|
||||
};
|
||||
rawTasks.push(task);
|
||||
}
|
||||
|
||||
@@ -75,6 +75,51 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
expect(normalized?.stageNodes?.[1]?.absoluteIndex).toBe(2);
|
||||
});
|
||||
|
||||
it('normalizes structured inventory candidate facts', () => {
|
||||
const projection = normalizeShippingProcessingProjection({
|
||||
work_item_no: 'SN-001',
|
||||
work_item_type: 'order_task',
|
||||
source_type: 'eml',
|
||||
submission_no: 'SUB-1',
|
||||
intake_no: 'INT-1',
|
||||
status: 'processing',
|
||||
stage: 'inventory_matching',
|
||||
progress_version: 2,
|
||||
last_activity_at: '2026-08-08T22:00:00',
|
||||
source_summary: {},
|
||||
available_actions: [],
|
||||
child_order_tasks: [],
|
||||
blocking_reason: {
|
||||
code: 'inventory_candidates_missing',
|
||||
i18n_key: 'workspace.shippingNotice.processGate.reasons.inventory_candidates_missing',
|
||||
},
|
||||
facts: {
|
||||
candidate_set_id: 12,
|
||||
candidate_set_version: 3,
|
||||
candidate_set_status: 'frozen',
|
||||
candidate_source_codes: ['DBS_DUB'],
|
||||
prepared_source_codes: ['DBS_DUB'],
|
||||
pending_source_codes: ['DBS_RTM'],
|
||||
failed_source_codes: ['DBS_SIN'],
|
||||
source_attempts: {
|
||||
DBS_DUB: { status: 'consumed', attempt_no: 1 },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(projection?.facts?.candidateSetId).toBe(12);
|
||||
expect(projection?.facts?.candidateSetVersion).toBe(3);
|
||||
expect(projection?.facts?.candidateSetStatus).toBe('frozen');
|
||||
expect(projection?.facts?.candidateSourceCodes).toEqual(['DBS_DUB']);
|
||||
expect(projection?.facts?.preparedSourceCodes).toEqual(['DBS_DUB']);
|
||||
expect(projection?.facts?.pendingSourceCodes).toEqual(['DBS_RTM']);
|
||||
expect(projection?.facts?.failedSourceCodes).toEqual(['DBS_SIN']);
|
||||
expect(projection?.facts?.sourceAttempts).toEqual({
|
||||
DBS_DUB: { status: 'consumed', attempt_no: 1 },
|
||||
});
|
||||
expect(projection?.blockingReason?.code).toBe('inventory_candidates_missing');
|
||||
});
|
||||
|
||||
it('returns null when work_item_no missing', () => {
|
||||
expect(normalizeShippingProcessingProjection({ status: 'processing' })).toBeNull();
|
||||
});
|
||||
|
||||
@@ -8,7 +8,12 @@
|
||||
import type {
|
||||
OrderIntakeSourceType,
|
||||
ProcessGateSummary,
|
||||
ShippingInventoryPerSourceAttempt,
|
||||
ShippingInventoryPreparationSummary,
|
||||
ShippingOrderTaskSummary,
|
||||
ShippingProcessingBlockingReason,
|
||||
ShippingProcessingFacts,
|
||||
ShippingProcessingPrimaryAction,
|
||||
ShippingProcessingProjection,
|
||||
ShippingProcessingStage,
|
||||
ShippingProcessingStageNode,
|
||||
@@ -98,6 +103,186 @@ function normalizeStageNode(raw: unknown): ShippingProcessingStageNode | null {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* [T9 用户态 Projection] 规范 blocking_reason(后端 snake_case {code, i18n_key, details})。
|
||||
*/
|
||||
function normalizeBlockingReason(raw: unknown): ShippingProcessingBlockingReason | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const item = raw as Record<string, unknown>;
|
||||
const code = String(item.code ?? '').trim();
|
||||
if (!code) return null;
|
||||
return {
|
||||
code,
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : (item.i18nKey != null ? String(item.i18nKey) : null),
|
||||
details:
|
||||
typeof item.details === 'object' && item.details != null
|
||||
? (item.details as Record<string, unknown>)
|
||||
: {},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* [T9 用户态 Projection] 规范 primary_action(后端 snake_case {code, i18n_key, parameters})。
|
||||
*/
|
||||
function normalizePrimaryAction(raw: unknown): ShippingProcessingPrimaryAction | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const item = raw as Record<string, unknown>;
|
||||
const code = String(item.code ?? '').trim();
|
||||
if (!code) return null;
|
||||
return {
|
||||
code,
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : (item.i18nKey != null ? String(item.i18nKey) : null),
|
||||
parameters:
|
||||
typeof item.parameters === 'object' && item.parameters != null
|
||||
? (item.parameters as Record<string, unknown>)
|
||||
: {},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* [T9 用户态 Projection] 规范 facts(后端 snake_case 子状态字典;camelCase key)。
|
||||
*/
|
||||
function normalizeFacts(raw: unknown): ShippingProcessingFacts | undefined {
|
||||
if (!raw || typeof raw !== 'object') return undefined;
|
||||
const item = raw as Record<string, unknown>;
|
||||
const toStrArr = (value: unknown): string[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.map((c) => String(c ?? '').trim()).filter(Boolean);
|
||||
};
|
||||
const toLineArr = (value: unknown): Record<string, unknown>[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.filter((row): row is Record<string, unknown> => Boolean(row) && typeof row === 'object');
|
||||
};
|
||||
const out: ShippingProcessingFacts = {};
|
||||
if ('inventory_source_status' in item || 'inventorySourceStatus' in item) {
|
||||
out.inventorySourceStatus =
|
||||
item.inventory_source_status != null
|
||||
? String(item.inventory_source_status)
|
||||
: item.inventorySourceStatus != null
|
||||
? String(item.inventorySourceStatus)
|
||||
: null;
|
||||
}
|
||||
if ('candidate_set_id' in item || 'candidateSetId' in item) {
|
||||
const v = item.candidate_set_id ?? item.candidateSetId;
|
||||
out.candidateSetId = v == null || v === '' ? null : Number(v);
|
||||
}
|
||||
if ('candidate_set_version' in item || 'candidateSetVersion' in item) {
|
||||
const v = item.candidate_set_version ?? item.candidateSetVersion;
|
||||
out.candidateSetVersion = v == null || v === '' ? null : Number(v);
|
||||
}
|
||||
if ('candidate_set_status' in item || 'candidateSetStatus' in item) {
|
||||
const v = item.candidate_set_status ?? item.candidateSetStatus;
|
||||
out.candidateSetStatus = v == null || v === '' ? null : String(v) as ShippingProcessingFacts['candidateSetStatus'];
|
||||
}
|
||||
if ('candidate_source_codes' in item || 'candidateSourceCodes' in item) {
|
||||
out.candidateSourceCodes = toStrArr(item.candidate_source_codes ?? item.candidateSourceCodes);
|
||||
}
|
||||
if ('prepared_source_codes' in item || 'preparedSourceCodes' in item) {
|
||||
out.preparedSourceCodes = toStrArr(item.prepared_source_codes ?? item.preparedSourceCodes);
|
||||
}
|
||||
if ('pending_source_codes' in item || 'pendingSourceCodes' in item) {
|
||||
out.pendingSourceCodes = toStrArr(item.pending_source_codes ?? item.pendingSourceCodes);
|
||||
}
|
||||
if ('failed_source_codes' in item || 'failedSourceCodes' in item) {
|
||||
out.failedSourceCodes = toStrArr(item.failed_source_codes ?? item.failedSourceCodes);
|
||||
}
|
||||
if ('source_attempts' in item || 'sourceAttempts' in item) {
|
||||
const v = item.source_attempts ?? item.sourceAttempts;
|
||||
out.sourceAttempts = typeof v === 'object' && v != null ? v as Record<string, unknown> : {};
|
||||
}
|
||||
if ('line_resolutions' in item || 'lineResolutions' in item) {
|
||||
out.lineResolutions = toLineArr(item.line_resolutions ?? item.lineResolutions);
|
||||
}
|
||||
if ('export_state' in item || 'exportState' in item) {
|
||||
const v = item.export_state ?? item.exportState;
|
||||
out.exportState = v == null ? 'not_created' : String(v);
|
||||
}
|
||||
if ('upload_state' in item || 'uploadState' in item) {
|
||||
const v = item.upload_state ?? item.uploadState;
|
||||
out.uploadState = v == null ? 'not_created' : String(v);
|
||||
}
|
||||
if ('switch_state' in item || 'switchState' in item) {
|
||||
const v = item.switch_state ?? item.switchState;
|
||||
out.switchState = v == null ? 'not_triggered' : String(v);
|
||||
}
|
||||
if ('forced_match_source_code' in item || 'forcedMatchSourceCode' in item) {
|
||||
const v = item.forced_match_source_code ?? item.forcedMatchSourceCode;
|
||||
out.forcedMatchSourceCode = v == null || v === '' ? null : String(v).toUpperCase();
|
||||
}
|
||||
for (const [k, v] of Object.entries(item)) {
|
||||
if (!(k in out)) {
|
||||
out[k] = v;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 题4A:规范 inventory_preparation 结构化字段(snake_case → camelCase)。
|
||||
* 注意:failed_sources 会进一步透传到 exhausted_sources 分开(二者互斥;仅 max_attempts 耗尽的源进 exhausted)。
|
||||
*/
|
||||
function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparationSummary | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const item = raw as Record<string, unknown>;
|
||||
const toStrArr = (value: unknown): string[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.map((c) => String(c ?? '').trim()).filter(Boolean);
|
||||
};
|
||||
const requiredSources = toStrArr(item.required_sources ?? item.requiredSources);
|
||||
if (!requiredSources.length) {
|
||||
// required_sources 空代表 inventory_preparation 实际尚未进入 inventory 阶段,返回 null 避免前端误判。
|
||||
return null;
|
||||
}
|
||||
const preparedSources = toStrArr(item.prepared_sources ?? item.preparedSources);
|
||||
const pendingSources = toStrArr(item.pending_sources ?? item.pendingSources);
|
||||
const failedSources = toStrArr(item.failed_sources ?? item.failedSources);
|
||||
const exhaustedSources = toStrArr(item.exhausted_sources ?? item.exhaustedSources);
|
||||
const activeAttemptCount = Number(item.active_attempt_count ?? item.activeAttemptCount ?? 0) || 0;
|
||||
const gateAttemptActive = Boolean(item.gate_attempt_active ?? item.gateAttemptActive ?? false);
|
||||
const latestRaw = (item.latest_attempts ?? item.latestAttempts) as Record<string, unknown> | undefined;
|
||||
const latestAttempts: Record<string, ShippingInventoryPerSourceAttempt> = {};
|
||||
if (latestRaw && typeof latestRaw === 'object') {
|
||||
for (const [key, val] of Object.entries(latestRaw)) {
|
||||
if (!val || typeof val !== 'object') continue;
|
||||
const row = val as Record<string, unknown>;
|
||||
const sourceCode = String(row.source_code ?? row.sourceCode ?? key ?? '').trim().toUpperCase();
|
||||
if (!sourceCode) continue;
|
||||
const attemptNo = Number(row.attempt_no ?? row.attemptNo ?? 0) || 0;
|
||||
const status = String(row.status || '').trim().toLowerCase() || 'unknown';
|
||||
const entry: ShippingInventoryPerSourceAttempt = {
|
||||
sourceCode,
|
||||
attemptNo,
|
||||
status,
|
||||
manualRetryable: (() => {
|
||||
if (row.manual_retryable != null) return Boolean(row.manual_retryable);
|
||||
if (row.manualRetryable != null) return Boolean(row.manualRetryable);
|
||||
return ['failed', 'exhausted'].includes(status);
|
||||
})(),
|
||||
message:
|
||||
(row.error_message as string | null | undefined) ??
|
||||
(row.errorMessage as string | null | undefined) ??
|
||||
(row.message as string | null | undefined) ??
|
||||
null,
|
||||
updatedAt:
|
||||
readNullableString(row, 'updated_at', 'updatedAt') ??
|
||||
readNullableString(row, 'finished_at', 'finishedAt') ??
|
||||
readNullableString(row, 'started_at', 'startedAt'),
|
||||
};
|
||||
latestAttempts[sourceCode] = entry;
|
||||
}
|
||||
}
|
||||
return {
|
||||
requiredSources,
|
||||
preparedSources,
|
||||
pendingSources,
|
||||
failedSources,
|
||||
exhaustedSources,
|
||||
activeAttemptCount,
|
||||
gateAttemptActive,
|
||||
latestAttempts: Object.keys(latestAttempts).length ? latestAttempts : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将后端 / 混合字段投影规范为 ShippingProcessingProjection。
|
||||
* 核心逻辑:缺字段给安全默认值,保证四页面可渲染;非法输入返回 null。
|
||||
@@ -160,6 +345,23 @@ export function normalizeShippingProcessingProjection(
|
||||
assetStatus: readNullableString(summaryRaw, 'asset_status', 'assetStatus'),
|
||||
},
|
||||
childOrderTasks: children,
|
||||
// [T9 用户态 Projection 7 字段] 优先读后端 user_* / blocking_reason / retryable / primary_action / facts;
|
||||
// 缺省为 null(旧后端不会下发,旧前端不读取,完全兼容)。
|
||||
userStatus: readNullableString(item, 'user_status', 'userStatus') as ShippingProcessingProjection['userStatus'],
|
||||
userStage: readNullableString(item, 'user_stage', 'userStage') as ShippingProcessingProjection['userStage'],
|
||||
userCurrentGateCode: readNullableString(item, 'user_current_gate_code', 'userCurrentGateCode'),
|
||||
blockingReason: normalizeBlockingReason(item.blocking_reason ?? item.blockingReason),
|
||||
retryable:
|
||||
(item.retryable as boolean | undefined) == null ? false : Boolean(item.retryable),
|
||||
primaryAction: normalizePrimaryAction(item.primary_action ?? item.primaryAction),
|
||||
facts: normalizeFacts(item.facts),
|
||||
legacyStatus: readNullableString(item, 'legacy_status', 'legacyStatus'),
|
||||
legacyStage: readNullableString(item, 'legacy_stage', 'legacyStage'),
|
||||
hasFormalOt:
|
||||
(item.has_formal_ot as boolean | undefined) == null ? false : Boolean(item.has_formal_ot),
|
||||
inventoryPreparation: normalizeInventoryPreparation(
|
||||
item.inventory_preparation ?? item.inventoryPreparation,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -64,6 +64,39 @@ function buildUnifiedProcessing(conversationId = 'conv-1') {
|
||||
};
|
||||
}
|
||||
|
||||
function buildOrderTaskWorkItem(
|
||||
taskNo = 'OT-conv-1',
|
||||
patch: Record<string, unknown> = {},
|
||||
) {
|
||||
return {
|
||||
workItemType: 'order_task',
|
||||
workItemNo: taskNo,
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: taskNo,
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'processing',
|
||||
stage: 'document_parsing',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-05T00:00:00Z',
|
||||
currentGate: null,
|
||||
availableActions: [],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'po.pdf',
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 1,
|
||||
candidateCount: 1,
|
||||
customerName: null,
|
||||
poNumber: 'PO-1',
|
||||
},
|
||||
childOrderTasks: [],
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建可手动完成的 Promise。
|
||||
*/
|
||||
@@ -182,36 +215,16 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
it('uses unified work_items as the sole processing read source', async () => {
|
||||
api.getShippingProcessing.mockResolvedValue({
|
||||
conversation_id: 'conv-1',
|
||||
work_items: [{
|
||||
workItemType: 'order_task',
|
||||
workItemNo: 'OT-UNIFIED',
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: 'OT-UNIFIED',
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
work_items: [buildOrderTaskWorkItem('OT-UNIFIED', {
|
||||
status: 'waiting_review',
|
||||
stage: 'waiting_review',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-05T00:00:00Z',
|
||||
currentGate: {
|
||||
gateCode: 'order_freeze_readiness',
|
||||
status: 'blocked',
|
||||
nextActionCode: 'open_order_review',
|
||||
},
|
||||
availableActions: ['open_order_review'],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'po.pdf',
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 1,
|
||||
candidateCount: 1,
|
||||
customerName: null,
|
||||
poNumber: 'PO-1',
|
||||
},
|
||||
childOrderTasks: [],
|
||||
}],
|
||||
})],
|
||||
conversation_processing: null,
|
||||
});
|
||||
|
||||
@@ -226,6 +239,60 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('preserves previous order_task work_items when stabilizer keeps previous projection', async () => {
|
||||
api.getShippingProcessing
|
||||
.mockResolvedValueOnce({
|
||||
conversation_id: 'conv-1',
|
||||
work_items: [buildOrderTaskWorkItem('OT-STABLE')],
|
||||
conversation_processing: null,
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
conversation_id: 'conv-1',
|
||||
work_items: [{
|
||||
workItemType: 'order_intake',
|
||||
workItemNo: 'SNI-1',
|
||||
sourceType: 'email',
|
||||
conversationId: 'conv-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'processing',
|
||||
stage: 'parsing',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-05T00:00:01Z',
|
||||
currentGate: null,
|
||||
availableActions: [],
|
||||
sourceSummary: {
|
||||
emailSubject: 'mail',
|
||||
filename: 'po.pdf',
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 0,
|
||||
candidateCount: 0,
|
||||
customerName: null,
|
||||
poNumber: null,
|
||||
},
|
||||
childOrderTasks: [],
|
||||
}],
|
||||
conversation_processing: buildProcessing(),
|
||||
});
|
||||
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processing.value?.processing[0]?.user_task_no).toBe('OT-STABLE');
|
||||
expect(ctl.processingWorkItems.value[0]?.workItemType).toBe('order_task');
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processing.value?.processing[0]?.user_task_no).toBe('OT-STABLE');
|
||||
expect(ctl.processingWorkItems.value).toHaveLength(1);
|
||||
expect(ctl.processingWorkItems.value[0]?.workItemType).toBe('order_task');
|
||||
expect(ctl.processingWorkItems.value[0]?.workItemNo).toBe('OT-STABLE');
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('derives sibling OT tasks from work_items when embedded conversation_processing omits them', async () => {
|
||||
api.getShippingProcessing.mockResolvedValue({
|
||||
conversation_id: 'conv-1',
|
||||
|
||||
@@ -32,6 +32,7 @@ import type {
|
||||
} from '../types/shipping.api.types';
|
||||
import {
|
||||
buildProcessingSemanticKey,
|
||||
createIntakeOtStabilizer,
|
||||
resolveConversationProcessingFromUnified,
|
||||
} from './conversationProcessingProjection';
|
||||
|
||||
@@ -147,6 +148,27 @@ export function useShippingNoticeWorkflow(
|
||||
let failureCount = 0;
|
||||
let pollingStopped = false;
|
||||
let lastSemanticKey = '';
|
||||
const intakeOtStabilizer = createIntakeOtStabilizer();
|
||||
|
||||
/**
|
||||
* 在 Intake→OT 过渡窗里,若 projection 被稳定器保留为上一轮 OT 视图,
|
||||
* 则 work_items 也必须同步保留上一轮 order_task;否则卡片正文与侧边进度条
|
||||
* 会来自两轮不同响应,导致右侧布局在“带进度条/只剩按钮”之间来回切换。
|
||||
*/
|
||||
function resolveStableWorkItems(
|
||||
nextWorkItems: ShippingProcessingProjection[],
|
||||
previousProjection: ConversationProcessingProjection | null,
|
||||
nextProjection: ConversationProcessingProjection | null,
|
||||
): ShippingProcessingProjection[] {
|
||||
const hasNextOrderTask = nextWorkItems.some((item) => item.workItemType === 'order_task');
|
||||
if (hasNextOrderTask) return nextWorkItems;
|
||||
if (!previousProjection || nextProjection !== previousProjection) return nextWorkItems;
|
||||
const currentWorkItems = Array.isArray(processingWorkItems.value)
|
||||
? processingWorkItems.value
|
||||
: [];
|
||||
const hasCurrentOrderTask = currentWorkItems.some((item) => item.workItemType === 'order_task');
|
||||
return hasCurrentOrderTask ? currentWorkItems : nextWorkItems;
|
||||
}
|
||||
|
||||
const normalizedConversationId = computed(() =>
|
||||
String(readOption(options.conversationId) || '').trim(),
|
||||
@@ -212,10 +234,20 @@ export function useShippingNoticeWorkflow(
|
||||
workItems,
|
||||
embedded,
|
||||
prevProjection,
|
||||
{
|
||||
conversationId,
|
||||
hasSeenOrderTaskBefore: (cId) => intakeOtStabilizer.hasSeenOrderTaskBefore(cId),
|
||||
markSeen: (cId) => intakeOtStabilizer.markSeen(cId),
|
||||
reset: (cId) => intakeOtStabilizer.reset(cId),
|
||||
},
|
||||
);
|
||||
const nextSemanticKey = buildProcessingSemanticKey(nextProjection);
|
||||
|
||||
processingWorkItems.value = workItems;
|
||||
processingWorkItems.value = resolveStableWorkItems(
|
||||
workItems,
|
||||
prevProjection,
|
||||
nextProjection,
|
||||
);
|
||||
if (nextSemanticKey !== lastSemanticKey) {
|
||||
processing.value = nextProjection;
|
||||
lastSemanticKey = nextSemanticKey;
|
||||
@@ -255,6 +287,7 @@ export function useShippingNoticeWorkflow(
|
||||
lastSemanticKey = '';
|
||||
return Promise.resolve();
|
||||
}
|
||||
intakeOtStabilizer.reset(conversationId);
|
||||
if (inFlightRefresh?.conversationId === conversationId) {
|
||||
return inFlightRefresh.promise;
|
||||
}
|
||||
@@ -278,12 +311,16 @@ export function useShippingNoticeWorkflow(
|
||||
}): void {
|
||||
const workItems = Array.isArray(response.work_items) ? response.work_items : [];
|
||||
if (workItems.length > 0) {
|
||||
processingWorkItems.value = workItems as typeof processingWorkItems.value;
|
||||
const nextProjection = resolveConversationProcessingFromUnified(
|
||||
workItems as typeof processingWorkItems.value,
|
||||
response.processing ?? null,
|
||||
processing.value,
|
||||
);
|
||||
processingWorkItems.value = resolveStableWorkItems(
|
||||
workItems as typeof processingWorkItems.value,
|
||||
processing.value,
|
||||
nextProjection,
|
||||
);
|
||||
const nextKey = buildProcessingSemanticKey(nextProjection);
|
||||
if (nextKey !== lastSemanticKey) {
|
||||
processing.value = nextProjection;
|
||||
|
||||
@@ -140,6 +140,125 @@ export type PdfPriorityFieldPolicy =
|
||||
| 'supplement_allowed'
|
||||
| 'review_required';
|
||||
|
||||
/**
|
||||
* 用户态统一 Projection 阻断原因(T8 决策 F2;后端对象 {code, i18n_key, details})。
|
||||
*/
|
||||
export interface ShippingProcessingBlockingReason {
|
||||
code: string;
|
||||
i18nKey?: string | null;
|
||||
details?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户态统一 Projection 主动作(T8 决策 F2;后端对象 {code, i18n_key, parameters})。
|
||||
*/
|
||||
export interface ShippingProcessingPrimaryAction {
|
||||
code: string;
|
||||
i18nKey?: string | null;
|
||||
parameters?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户态统一 Projection facts(T8 决策 F2;子状态事实字典)。
|
||||
*/
|
||||
export interface ShippingProcessingFacts {
|
||||
inventorySourceStatus?: string | null;
|
||||
candidateSetId?: number | null;
|
||||
candidateSetVersion?: number | null;
|
||||
candidateSetStatus?: 'draft' | 'frozen' | 'superseded' | 'invalidated' | null;
|
||||
candidateSourceCodes?: string[];
|
||||
preparedSourceCodes?: string[];
|
||||
pendingSourceCodes?: string[];
|
||||
failedSourceCodes?: string[];
|
||||
sourceAttempts?: Record<string, unknown>;
|
||||
rpaAttempts?: Array<{
|
||||
sourceCode?: string | null;
|
||||
sourceRunNo?: string | null;
|
||||
attemptNo?: number | null;
|
||||
status?: string | null;
|
||||
executionPhase?: string | null;
|
||||
fileGenerated?: boolean;
|
||||
fileExistsAtCallback?: boolean | null;
|
||||
errorCode?: string | null;
|
||||
transactionErrorCode?: string | null;
|
||||
callbackReceivedAt?: string | null;
|
||||
}>;
|
||||
lineResolutions?: Record<string, unknown>[];
|
||||
exportState?: string;
|
||||
uploadState?: string;
|
||||
switchState?: string;
|
||||
forcedMatchSourceCode?: string | null;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ShippingInventoryCandidateSetSummary {
|
||||
id: number;
|
||||
version: number;
|
||||
status: 'draft' | 'frozen' | 'superseded' | 'invalidated';
|
||||
inputFingerprint: string;
|
||||
frozenAt: string | null;
|
||||
frozenBy: number | null;
|
||||
manifestSnapshotSha256?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingInventoryCandidateSourceDetail {
|
||||
id: number;
|
||||
candidateSetId: number;
|
||||
sourceCode: string;
|
||||
candidateOrder: number;
|
||||
candidateOrigin: string;
|
||||
routingRuleId?: number | null;
|
||||
routingRuleVersion?: number | string | null;
|
||||
sourceConfigVersion?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingInventoryCandidateLineDetail {
|
||||
candidateLineId: number;
|
||||
candidateSetId: number;
|
||||
lineNo: number;
|
||||
sourceLineNo?: string | null;
|
||||
partNumber?: string | null;
|
||||
reservationId?: string | null;
|
||||
allowedSourceCodes: string[];
|
||||
}
|
||||
|
||||
export interface ShippingTaskInventoryCandidatesResponse {
|
||||
taskNo: string;
|
||||
currentSet: ShippingInventoryCandidateSetSummary | null;
|
||||
sources: ShippingInventoryCandidateSourceDetail[];
|
||||
lines: ShippingInventoryCandidateLineDetail[];
|
||||
history: ShippingInventoryCandidateSetSummary[];
|
||||
blockingReason?: ShippingProcessingBlockingReason | null;
|
||||
primaryAction?: ShippingProcessingPrimaryAction | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户态统一 Projection status(T8 决策 F2;running / waiting_human / retryable / failed / completed / cancelled)。
|
||||
*/
|
||||
export type ShippingUserProcessingStatus =
|
||||
| 'running'
|
||||
| 'waiting_human'
|
||||
| 'retryable'
|
||||
| 'failed'
|
||||
| 'completed'
|
||||
| 'cancelled';
|
||||
|
||||
/**
|
||||
* 用户态统一 Projection stage(T8 决策 F2;inventory_fetch / inventory_match / excel_generate / freight_upload 等)。
|
||||
*/
|
||||
export type ShippingUserProcessingStage =
|
||||
| 'document_parsing'
|
||||
| 'order_creating'
|
||||
| 'waiting_human_review'
|
||||
| 'inventory_fetch'
|
||||
| 'inventory_match'
|
||||
| 'excel_generate'
|
||||
| 'freight_upload'
|
||||
| 'completed'
|
||||
| 'failed_terminal'
|
||||
| 'cancelled'
|
||||
| string;
|
||||
|
||||
/**
|
||||
* 统一处理投影 DTO(阶段 4 接线;阶段 0 冻结形状)。
|
||||
* 对话、对话右侧、复核工作台、后台工作台共同消费;禁止页面私自拼接状态。
|
||||
@@ -188,6 +307,78 @@ export interface ShippingProcessingProjection {
|
||||
assetStatus?: string | null;
|
||||
};
|
||||
childOrderTasks: ShippingOrderTaskSummary[];
|
||||
// ============== [T8 用户态 Projection 7 字段] ==============
|
||||
// 后端 apply_user_projection_fields 下发;旧客户端不识别会直接忽略(安全);
|
||||
// 新前端优先用本字段停止本地推导。
|
||||
/** 用户态 status(6 枚举:running / waiting_human / retryable / failed / completed / cancelled)。 */
|
||||
userStatus?: ShippingUserProcessingStatus | null;
|
||||
/** 用户态 stage(inventory_fetch / inventory_match / excel_generate / freight_upload 等)。 */
|
||||
userStage?: ShippingUserProcessingStage | null;
|
||||
/** 用户态 current_gate 编码(纯字符串;旧 currentGate 仍为对象保留)。 */
|
||||
userCurrentGateCode?: string | null;
|
||||
/** 阻断原因:{code, i18nKey, details};status=waiting_human / retryable / failed 时非空。 */
|
||||
blockingReason?: ShippingProcessingBlockingReason | null;
|
||||
/** 技术失败是否可重试;业务阻断(waiting_human)通常 false。 */
|
||||
retryable?: boolean;
|
||||
/** 唯一主入口按钮建议:{code, i18nKey, parameters};前端只渲染不新建动作码。 */
|
||||
primaryAction?: ShippingProcessingPrimaryAction | null;
|
||||
/** 子状态事实字典(inventorySourceStatus / candidateSourceCodes / preparedSourceCodes / pendingSourceCodes / lineResolutions / exportState / uploadState / switchState)。 */
|
||||
facts?: ShippingProcessingFacts;
|
||||
/** 旧 status 备份(T8 apply_user_projection_fields.legacy_status);调试用。 */
|
||||
legacyStatus?: string | null;
|
||||
/** 旧 stage 备份(T8 apply_user_projection_fields.legacy_stage);调试用。 */
|
||||
legacyStage?: string | null;
|
||||
/** 正式 OT 是否已挂接真实 ShippingNotice;T1 判定:order_task + shipping_notice_id 非空 + shipping_notice_no 非空。 */
|
||||
hasFormalOt?: boolean;
|
||||
/**
|
||||
* 题4A:inventory 统一 Projection(仅 inventory 阶段及之前且 hasFormalOt=true 时填充;其他阶段 null)。
|
||||
* 权威事实源:summarize_inventory_rpa_latest_attempts();
|
||||
* 前端按钮禁用/重试文案/状态徽章全部直接读本对象,禁止继续拼接旧字段合成 running。
|
||||
*/
|
||||
inventoryPreparation?: ShippingInventoryPreparationSummary | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 题4A & 7A:逐源 inventory 准备状态(ShippingProcessingProjection.inventoryPreparation)。
|
||||
* 按实际冻结源 required_sources 为基准分类,failed/exhausted 拆分暴露。
|
||||
*/
|
||||
export interface ShippingInventoryPreparationSummary {
|
||||
/** 实际任务级冻结源(task.task_frozen_inventory_source_codes),顺序以冻结记录为准。 */
|
||||
requiredSources: string[];
|
||||
/** 已就绪:有 prepared 状态 Attempt,或 inventory_lines_json + inventory_snapshot_id 已载入。 */
|
||||
preparedSources: string[];
|
||||
/** RPA 正在跑或入队中(queued / running);active_attempt_count > 0 的对应源集合。 */
|
||||
pendingSources: string[];
|
||||
/** 最近一次失败状态(attempt.status == failed)但未耗尽自动次数的源。 */
|
||||
failedSources: string[];
|
||||
/** 题7A:自动重试 max_attempts 已耗尽但允许人工 user_retry 继续的源;独立于 failed,便于 UI 提示。 */
|
||||
exhaustedSources: string[];
|
||||
/** 全表当前 queued+running Attempt 总数(>= pendingSources.length,存在 Gate 活动 Attempt 时会更高)。 */
|
||||
activeAttemptCount: number;
|
||||
/** 题2B:Process Gate 是否有 queued/running 状态的 inventory 批次;作为全局 running 额外保护。 */
|
||||
gateAttemptActive?: boolean;
|
||||
/**
|
||||
* 按冻结源逐源最近 Attempt 摘要(source_code → 结构化记录)。
|
||||
* 用于 UI tooltip/详情;按钮禁用不直接读本字典,读上面的 required/prepared/pending/failed/exhausted 集合。
|
||||
*/
|
||||
latestAttempts?: Record<string, ShippingInventoryPerSourceAttempt>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 逐源最近一次 Inventory RPA Attempt 摘要(inventoryPreparation.latestAttempts[sourceCode])。
|
||||
* 仅用于 UI 展示;业务判定必须走顶层 *_sources 集合。
|
||||
*/
|
||||
export interface ShippingInventoryPerSourceAttempt {
|
||||
sourceCode: string;
|
||||
attemptNo: number;
|
||||
/** queued | running | consumed | failed | exhausted | skipped */
|
||||
status: string;
|
||||
/** 失败/耗尽:人工可继续;running/queued:false */
|
||||
manualRetryable?: boolean;
|
||||
/** attempt.error_message 或 业务错误摘要,供 tooltip。 */
|
||||
message?: string | null;
|
||||
updatedAt?: string | null;
|
||||
/** attempt.id 便于定位日志;不向浏览器直接暴露内部数据库 ID,此处省略。 */
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -364,6 +555,15 @@ export interface ConversationProcessingUserTask {
|
||||
primary_action?: string | null;
|
||||
available_actions?: string[];
|
||||
objects?: ConversationProcessingObject[];
|
||||
userStatus?: ShippingUserProcessingStatus | null;
|
||||
userStage?: ShippingUserProcessingStage | null;
|
||||
userCurrentGateCode?: string | null;
|
||||
blockingReason?: ShippingProcessingBlockingReason | null;
|
||||
retryable?: boolean;
|
||||
primaryAction?: ShippingProcessingPrimaryAction | null;
|
||||
facts?: ShippingProcessingFacts;
|
||||
legacyStatus?: string | null;
|
||||
legacyStage?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1965,6 +2165,12 @@ 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;
|
||||
/** Vendor Comments 三来源专属:vc:<doc>:p<N>:region:<rid> 证据引用,可跳转证据查看器定位对应区域。 */
|
||||
evidence_ref?: string | null;
|
||||
}
|
||||
|
||||
/** 建单前 Candidate 字段冲突投影(复核工作台集中裁决区)。 */
|
||||
@@ -1977,6 +2183,18 @@ export interface ShippingOrderReviewFieldConflict {
|
||||
reason: string;
|
||||
options: ShippingOrderReviewFieldConflictOption[];
|
||||
observation_ids?: string[];
|
||||
/** 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 {
|
||||
@@ -2091,6 +2309,33 @@ export interface ShippingOrderReviewCase {
|
||||
order_data_version?: number | null;
|
||||
llm_suggestions?: ShippingOrderReviewLlmSuggestion[];
|
||||
process_gate?: ShippingProcessGateUserSummary | null;
|
||||
/** Case 用户态六事实之一:禁止前端自行从 stage 推导。 */
|
||||
user_status?:
|
||||
| 'running'
|
||||
| 'waiting_human'
|
||||
| 'retryable'
|
||||
| 'failed'
|
||||
| 'completed'
|
||||
| 'cancelled'
|
||||
| null;
|
||||
/** Case 用户阻断说明:仅消费后端投影。 */
|
||||
blocking_reason?: ShippingProcessingBlockingReason | null;
|
||||
/** Case 主动作:仅消费后端投影。 */
|
||||
primary_action?: ShippingProcessingPrimaryAction | null;
|
||||
}
|
||||
|
||||
/** 完整 Case 快照的纯展示 loading 上下文。 */
|
||||
export interface ShippingOrderReviewCaseLoadingContext {
|
||||
phase?: string | null;
|
||||
status?: string | null;
|
||||
message?: string | null;
|
||||
}
|
||||
|
||||
/** 工作台单 Case 完整快照:包装现有 case 投影并附审计版本。 */
|
||||
export interface ShippingOrderReviewCaseSnapshot {
|
||||
case: ShippingOrderReviewCase;
|
||||
projection_version: number;
|
||||
loading_context?: ShippingOrderReviewCaseLoadingContext | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2191,24 +2436,58 @@ export interface ShippingOrderReviewEvidence {
|
||||
requires_review?: boolean;
|
||||
}
|
||||
|
||||
/** Dify 最小证据建议 DTO;与后端 serialize_suggestion 对齐。 */
|
||||
/** Dify 最小证据建议 DTO;与后端 serialize_suggestion 对齐(Phase 4 权限分层:普通用户无 provider_trace / request_preview)。 */
|
||||
export interface ShippingOrderReviewLlmSuggestion {
|
||||
suggestion_no: string;
|
||||
field_id: string;
|
||||
line_key?: string | null;
|
||||
scope: string;
|
||||
evidence_level: string;
|
||||
contract_version?: string;
|
||||
status: string;
|
||||
error_code?: string | null;
|
||||
/** @deprecated 后端不再输出;前端统一按 error_code 查 i18n errors.json */
|
||||
error_message?: string | null;
|
||||
suggested_value?: unknown;
|
||||
validation_issues?: Array<{ code?: string; severity?: string }>;
|
||||
validation_issues?: Array<{
|
||||
code?: string;
|
||||
severity?: string;
|
||||
checks_order?: string[];
|
||||
match?: Record<string, unknown>;
|
||||
detail?: string;
|
||||
}>;
|
||||
decision?: string | null;
|
||||
decision_reason?: string | null;
|
||||
decision_note?: string | null;
|
||||
draft_version_at_request?: number | null;
|
||||
created_at?: string | null;
|
||||
adjudicated_at?: string | null;
|
||||
auto_upgrade_reason?: string | null;
|
||||
/** 普通用户可见:证据范围摘要(level/auto_upgraded/counts/context_truncated)。 */
|
||||
evidence_summary?: {
|
||||
level: string;
|
||||
auto_upgraded: boolean;
|
||||
auto_upgrade_reason?: string | null;
|
||||
field_count: number;
|
||||
row_count?: number | null;
|
||||
table_count?: number | null;
|
||||
page_count?: number | null;
|
||||
core_evidence_source?: string | null;
|
||||
context_truncated: boolean;
|
||||
} | null;
|
||||
/** 管理员专属:Provider 对账追踪信息。 */
|
||||
provider_trace?: {
|
||||
provider?: string | null;
|
||||
conversation_id?: string | null;
|
||||
message_id?: string | null;
|
||||
latency_ms?: number | null;
|
||||
} | null;
|
||||
/** 管理员专属:请求信封审计预览(fields_sent_preview / policies_applied / budget_tokens / method)。 */
|
||||
request_preview?: Record<string, unknown> | null;
|
||||
/** 管理员专属:上下文指纹。 */
|
||||
context_hash?: string | null;
|
||||
/** 管理员专属:Provider 端到端延迟 ms。 */
|
||||
latency_ms?: number | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewLlmSuggestionRequest {
|
||||
@@ -2465,12 +2744,18 @@ export interface ShippingOrderReviewLineFulfillmentLine {
|
||||
inventory_snapshot_id?: number | null;
|
||||
inventory_checked_at?: string | null;
|
||||
inventory_source_code?: string | null;
|
||||
inventory_source?: {
|
||||
inventory_source?: ({
|
||||
code?: string | null;
|
||||
label?: string | null;
|
||||
status?: 'resolved' | 'resolving' | 'unrecognized' | 'conflict' | 'unavailable' | string | null;
|
||||
source?: string | null;
|
||||
} | null;
|
||||
} & ({
|
||||
status: 'candidates_frozen';
|
||||
candidates: Array<string | { code?: string | null; label?: string | null; [key: string]: unknown }>;
|
||||
} | {
|
||||
status?: Exclude<string, 'candidates_frozen'> | null;
|
||||
candidates?: never;
|
||||
})) | null;
|
||||
decision_source?: 'system' | 'user' | 'unknown' | null;
|
||||
/** 行级统一「重试」是否可点;前端禁止用 inventory_allowed_actions 猜按钮。 */
|
||||
retryable?: boolean;
|
||||
|
||||
@@ -155,6 +155,8 @@ function createReviewComposableMock() {
|
||||
return {
|
||||
reviewRun,
|
||||
activeCase,
|
||||
caseProjectionVersion: ref(1),
|
||||
caseLoadingContext: ref(null),
|
||||
reviewProgressContext,
|
||||
workItem,
|
||||
authoritativeOrderTaskNo: computed(() => {
|
||||
@@ -800,7 +802,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
});
|
||||
|
||||
describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
resetActiveCaseFixture();
|
||||
reviewProgressContext.value = null;
|
||||
@@ -812,7 +814,7 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
audited: true,
|
||||
case_no: 'CASE-1',
|
||||
});
|
||||
});
|
||||
}, 20000);
|
||||
|
||||
it('refuses to open version history when access audit fails', async () => {
|
||||
vi.mocked(auditWorkspaceShippingOrderReviewVersionHistory).mockRejectedValueOnce(new Error('audit down'));
|
||||
@@ -1037,7 +1039,7 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="review-profile-match-panel"]').exists()).toBe(true);
|
||||
});
|
||||
}, 15000);
|
||||
|
||||
it('hydrates progress-failed retry state from Case projection without confirm UI', async () => {
|
||||
// 关键断言:无确认建单按钮时,仍可从 post_confirm_auto_progress 恢复对象级重试入口。
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user