feat(shipping-notice): 增强订单抽取功能,添加进度事件和诊断运行管理,优化数据模型和访问控制
This commit is contained in:
1 parent
ce26d6d0c4
commit
c4095b08da
175 files changed
+13064
-1814
No files matched your search
@@ -24,6 +24,7 @@ import type {
|
||||
ShippingTaskSummary,
|
||||
ShippingCustomerOption,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRunCreateResponse,
|
||||
ShippingTaskUiState,
|
||||
} from '../types/shipping.api.types';
|
||||
@@ -175,6 +176,26 @@ export const getWorkspaceShippingOrderExtractionRun = (runNo: string, signal?: A
|
||||
{ signal },
|
||||
);
|
||||
|
||||
/** 复用原附件与冻结快照,重新入队一次失败的订单抽取 Run。 */
|
||||
export const retryWorkspaceShippingOrderExtractionRun = (runNo: string) =>
|
||||
requestJson<ShippingOrderExtractionRunCreateResponse>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/retry`,
|
||||
jsonPost(),
|
||||
);
|
||||
|
||||
/** 用户展开状态卡时获取脱敏进度时间线;不返回节点或Workflow诊断数据。 */
|
||||
export const listWorkspaceShippingOrderExtractionProgressEvents = (runNo: string) =>
|
||||
requestJson<{ items: ShippingOrderExtractionProgressEvent[] }>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/progress-events`,
|
||||
);
|
||||
|
||||
/** 在终态状态卡已投影到当前会话后确认已查看,避免只因预加载会话列表而消除提醒。 */
|
||||
export const markWorkspaceShippingOrderExtractionRunSeen = (runNo: string) =>
|
||||
requestJson<{ seen: boolean }>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/seen`,
|
||||
jsonPost(),
|
||||
);
|
||||
|
||||
/** 按会话恢复订单抽取 Run,刷新页面后不依赖聊天 SSE 历史。 */
|
||||
export const listWorkspaceShippingOrderExtractionRuns = (
|
||||
conversationId: string,
|
||||
|
||||
@@ -103,6 +103,15 @@ const userInitial = (fallback: string) => {
|
||||
const name = String(props.currentUser?.username ?? '').trim();
|
||||
return (name || fallback).charAt(0).toUpperCase();
|
||||
};
|
||||
|
||||
/** 会话待查看采用点状提醒,颜色只表达业务处理优先级,不泄露订单或错误细节。 */
|
||||
const orderExtractionAttentionClass = (item: DisplayHistoryItem) => {
|
||||
switch (item.unseen_order_extraction_severity) {
|
||||
case 'error': return 'bg-rose-500';
|
||||
case 'warning': return 'bg-amber-500';
|
||||
default: return 'bg-sky-500';
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -220,6 +229,13 @@ const userInitial = (fallback: string) => {
|
||||
>
|
||||
{{ item.title || $t('chat.newChat') }}
|
||||
</button>
|
||||
<span
|
||||
v-if="item.unseen_order_extraction_count"
|
||||
class="absolute right-8 h-2 w-2 rounded-full"
|
||||
:class="orderExtractionAttentionClass(item)"
|
||||
:title="$t('chat.shippingOrderExtractionUnread', { count: item.unseen_order_extraction_count })"
|
||||
:aria-label="$t('chat.shippingOrderExtractionUnread', { count: item.unseen_order_extraction_count })"
|
||||
/>
|
||||
<button
|
||||
v-if="!item.__runId"
|
||||
type="button"
|
||||
|
||||
@@ -629,6 +629,9 @@ const handleSwitchBatch = (batchNo: string) => {
|
||||
:task-no="activeTaskDetail.task_no"
|
||||
:po-number="activeTaskDetail.po_number"
|
||||
:lines="activeTaskDetail.lines"
|
||||
:order-header="activeTaskDetail.order_header"
|
||||
:order-header-fields="activeTaskDetail.order_header_fields"
|
||||
:order-line-fields="activeTaskDetail.order_line_fields"
|
||||
:parse-validation="activeTaskDetail.parse_validation || activeTaskDetail.step_payload?.parse_validation || null"
|
||||
:process-field-gate="activeTaskDetail.process_field_gate || null"
|
||||
:source-candidate="activeTaskDetail.source_candidate || null"
|
||||
|
||||
@@ -12,6 +12,7 @@ import ShippingTaskFieldConflictPanel from '@/features/chat/components/ShippingT
|
||||
import type {
|
||||
ShippingFieldConflict,
|
||||
ShippingNoticeLine,
|
||||
ShippingOrderDisplayField,
|
||||
ShippingParseIssue,
|
||||
ShippingParseValidation,
|
||||
ShippingProcessFieldGate,
|
||||
@@ -22,6 +23,9 @@ const props = defineProps<{
|
||||
taskNo?: string | null;
|
||||
poNumber?: string | null;
|
||||
lines?: ShippingNoticeLine[] | null;
|
||||
orderHeader?: Record<string, unknown> | null;
|
||||
orderHeaderFields?: ShippingOrderDisplayField[] | null;
|
||||
orderLineFields?: ShippingOrderDisplayField[] | null;
|
||||
parseValidation?: ShippingParseValidation | null;
|
||||
processFieldGate?: ShippingProcessFieldGate | null;
|
||||
sourceCandidate?: ShippingSourceCandidateProjection | null;
|
||||
@@ -48,6 +52,8 @@ watch(
|
||||
);
|
||||
|
||||
const orderLines = computed(() => (props.lines || []).filter((line) => line && typeof line === 'object'));
|
||||
const orderedHeaderFields = computed(() => [...(props.orderHeaderFields || [])].sort((a, b) => a.sequence - b.sequence));
|
||||
const orderedLineFields = computed(() => [...(props.orderLineFields || [])].sort((a, b) => a.sequence - b.sequence));
|
||||
|
||||
const gateIssues = computed(() => {
|
||||
const fromGate = Array.isArray(props.processFieldGate?.issues) ? props.processFieldGate?.issues : [];
|
||||
@@ -142,6 +148,16 @@ function issueReasonLabel(reason?: string | null): string {
|
||||
@refreshed="emit('refreshed')"
|
||||
/>
|
||||
|
||||
<div v-if="orderedHeaderFields.length" class="rounded-xl border border-default bg-white/90 p-2.5">
|
||||
<div class="mb-2 font-semibold text-slate-700">{{ t('chat.shippingParsedResult.orderInformation') }}</div>
|
||||
<dl class="grid gap-2 sm:grid-cols-2">
|
||||
<div v-for="field in orderedHeaderFields" :key="field.field_code" class="rounded-lg bg-slate-50 px-2.5 py-2">
|
||||
<dt class="text-[10px] text-muted">{{ field.display_name }}</dt>
|
||||
<dd class="mt-0.5 break-words text-xs text-slate-800">{{ displayValue(orderHeader?.[field.field_code]) }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
<div v-if="missingFields.length" class="space-y-1">
|
||||
<div class="font-semibold text-amber-800">{{ t('chat.shippingParsedResult.missingFields') }}</div>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
@@ -182,12 +198,7 @@ function issueReasonLabel(reason?: string | null): string {
|
||||
<thead class="bg-surface text-left text-[11px] text-muted">
|
||||
<tr>
|
||||
<th class="px-2.5 py-2">#</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.partNumber') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.customerPartNumber') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.awsPartNumber') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.qty') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.reservationId') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.inventorySourceHint') }}</th>
|
||||
<th v-for="field in orderedLineFields" :key="field.field_code" class="px-2.5 py-2">{{ field.display_name }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -197,12 +208,7 @@ function issueReasonLabel(reason?: string | null): string {
|
||||
class="border-t border-default/60 text-xs"
|
||||
>
|
||||
<td class="px-2.5 py-2 text-muted">{{ index + 1 }}</td>
|
||||
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.part_number) }}</td>
|
||||
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.customer_part_number) }}</td>
|
||||
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.aws_part_number) }}</td>
|
||||
<td class="px-2.5 py-2">{{ displayValue(line.qty) }}</td>
|
||||
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.reservation_id) }}</td>
|
||||
<td class="px-2.5 py-2">{{ displayValue(line.inventory_source_hint) }}</td>
|
||||
<td v-for="field in orderedLineFields" :key="field.field_code" class="px-2.5 py-2" :class="{ 'font-mono': field.value_type === 'string' }">{{ displayValue((line as unknown as Record<string, unknown>)[field.field_code]) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;用户附件与文字共用同一气泡,助手正文与特殊交互委托页面 handlers。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import {
|
||||
Check,
|
||||
CircleCheck,
|
||||
@@ -36,6 +36,8 @@ import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../../type
|
||||
import type { ShippingMatchResultPayload } from '../../types/shipping.types';
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
|
||||
import { listWorkspaceShippingOrderExtractionProgressEvents } from '../../api/shipping.api';
|
||||
import type { ShippingOrderExtractionProgressEvent } from '../../types/shipping.api.types';
|
||||
|
||||
export interface ChatMessageBubbleHandlers {
|
||||
renderMarkdown: (text: string) => string;
|
||||
@@ -136,6 +138,30 @@ const showShippingActionsPanel = computed(() =>
|
||||
&& message.type !== 'shipping-match-result',
|
||||
);
|
||||
const shippingOrderExtractionState = computed(() => message.shipping_order_extraction_state);
|
||||
const retryingOrderExtraction = ref(false);
|
||||
const showOrderExtractionDetails = ref(false);
|
||||
const orderExtractionEvents = ref<ShippingOrderExtractionProgressEvent[]>([]);
|
||||
const loadingOrderExtractionEvents = ref(false);
|
||||
const orderExtractionEventsError = ref(false);
|
||||
const orderExtractionClock = ref(Date.now());
|
||||
let orderExtractionClockTimer: ReturnType<typeof setInterval> | null = null;
|
||||
const shippingOrderExtractionRunNo = computed(() => {
|
||||
const payload = message.payload && typeof message.payload === 'object'
|
||||
? message.payload as Record<string, unknown>
|
||||
: {};
|
||||
return String(payload.order_extraction_run_no || '').trim();
|
||||
});
|
||||
|
||||
/** 失败卡片复用原 Run 重试;按钮本地防重,成功后状态卡由 Run 轮询原位更新。 */
|
||||
const retryShippingOrderExtraction = async () => {
|
||||
if (!shippingOrderExtractionRunNo.value || retryingOrderExtraction.value) return;
|
||||
retryingOrderExtraction.value = true;
|
||||
try {
|
||||
await shippingHandlers.retryOrderExtractionRun(shippingOrderExtractionRunNo.value);
|
||||
} finally {
|
||||
retryingOrderExtraction.value = false;
|
||||
}
|
||||
};
|
||||
const shippingOrderExtractionTitleKey = computed(() => {
|
||||
switch (shippingOrderExtractionState.value?.status) {
|
||||
case 'completed': return 'chat.shippingOrderExtractionCompleted';
|
||||
@@ -144,6 +170,75 @@ const shippingOrderExtractionTitleKey = computed(() => {
|
||||
default: return 'chat.shippingOrderExtractionProcessing';
|
||||
}
|
||||
});
|
||||
const shippingOrderExtractionFailureHintKey = computed(() => (
|
||||
shippingOrderExtractionState.value?.status === 'failed'
|
||||
? 'chat.shippingOrderExtractionFailureHint'
|
||||
: ''
|
||||
));
|
||||
const shippingOrderExtractionStageKey = computed(() => {
|
||||
const code = String(shippingOrderExtractionState.value?.current_stage_code || '').trim();
|
||||
const known = new Set(['queued', 'workflow_accepted', 'document_processing', 'order_recognition', 'result_processing', 'provider_result_ready', 'hxops_persistence', 'auto_recovering', 'generic_processing']);
|
||||
return known.has(code) ? `chat.shippingOrderExtractionStage.${code}` : 'chat.shippingOrderExtractionProcessing';
|
||||
});
|
||||
const orderExtractionElapsedSeconds = computed(() => {
|
||||
const raw = shippingOrderExtractionState.value?.started_at;
|
||||
const started = raw ? Date.parse(raw) : NaN;
|
||||
if (!Number.isFinite(started)) return null;
|
||||
return Math.max(0, Math.floor((orderExtractionClock.value - started) / 1000));
|
||||
});
|
||||
|
||||
/**
|
||||
* 识别运行时刷新纯展示时钟,避免网络轮询间隔或无状态变化时运行时长停滞。
|
||||
* 仅在当前消息处于识别中时启动;后台 Run 的真实健康状态仍完全由服务端计算。
|
||||
*/
|
||||
watch(
|
||||
() => shippingOrderExtractionState.value?.status,
|
||||
(status) => {
|
||||
if (orderExtractionClockTimer) {
|
||||
clearInterval(orderExtractionClockTimer);
|
||||
orderExtractionClockTimer = null;
|
||||
}
|
||||
if (status === 'extracting') {
|
||||
orderExtractionClock.value = Date.now();
|
||||
orderExtractionClockTimer = setInterval(() => {
|
||||
orderExtractionClock.value = Date.now();
|
||||
}, 1000);
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (orderExtractionClockTimer) clearInterval(orderExtractionClockTimer);
|
||||
});
|
||||
const toggleOrderExtractionDetails = async () => {
|
||||
if (!shippingOrderExtractionRunNo.value) return;
|
||||
showOrderExtractionDetails.value = !showOrderExtractionDetails.value;
|
||||
if (!showOrderExtractionDetails.value || orderExtractionEvents.value.length || loadingOrderExtractionEvents.value) return;
|
||||
loadingOrderExtractionEvents.value = true;
|
||||
orderExtractionEventsError.value = false;
|
||||
try {
|
||||
const { items } = await listWorkspaceShippingOrderExtractionProgressEvents(shippingOrderExtractionRunNo.value);
|
||||
orderExtractionEvents.value = items;
|
||||
} catch {
|
||||
// 详情加载失败不影响 Run 短轮询或后台订单识别,只给出可理解的局部提示。
|
||||
orderExtractionEventsError.value = true;
|
||||
} finally {
|
||||
loadingOrderExtractionEvents.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 将服务端脱敏事件时间格式化为用户本地时间;无效值不伪造时间。 */
|
||||
const formatOrderExtractionEventTime = (value: string): string => {
|
||||
const timestamp = Date.parse(value);
|
||||
return Number.isFinite(timestamp) ? new Date(timestamp).toLocaleTimeString() : '';
|
||||
};
|
||||
|
||||
/** 把固定的阶段生命周期状态映射为本地化文案键,未知值使用中性兜底。 */
|
||||
const shippingOrderExtractionEventStatusKey = (status: string): string => {
|
||||
const known = new Set(['started', 'running', 'completed', 'failed', 'recovered']);
|
||||
return known.has(status) ? `chat.shippingOrderExtractionEventStatus.${status}` : 'chat.shippingOrderExtractionEventStatus.updated';
|
||||
};
|
||||
const showShippingOrderExtractionMessage = computed(() => {
|
||||
const stateMessage = String(shippingOrderExtractionState.value?.message || '').trim();
|
||||
const assistantContent = String(message.content || '').trim();
|
||||
@@ -696,6 +791,20 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
<CircleX v-else class="mt-0.5 h-5 w-5 shrink-0" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="text-sm font-semibold">{{ $t(shippingOrderExtractionTitleKey) }}</div>
|
||||
<template v-if="shippingOrderExtractionState.status === 'extracting'">
|
||||
<div class="mt-1 text-xs opacity-80">{{ $t(shippingOrderExtractionStageKey) }}</div>
|
||||
<div class="mt-1 flex flex-wrap gap-x-2 text-xs opacity-70">
|
||||
<span v-if="orderExtractionElapsedSeconds !== null">
|
||||
{{ $t('chat.shippingOrderExtractionElapsed', { seconds: orderExtractionElapsedSeconds }) }}
|
||||
</span>
|
||||
<span v-if="shippingOrderExtractionState.health === 'slow'">
|
||||
{{ $t('chat.shippingOrderExtractionSlow') }}
|
||||
</span>
|
||||
<span v-else-if="shippingOrderExtractionState.health === 'idle'">
|
||||
{{ $t('chat.shippingOrderExtractionIdle') }}
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
<div
|
||||
data-testid="shipping-order-extraction-progress"
|
||||
class="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-black/10 dark:bg-white/15"
|
||||
@@ -740,9 +849,42 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
{{ $t('chat.shippingOrderExtractionMissingFieldsCount', { count: shippingOrderExtractionState.created_with_missing_fields_count }) }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="showShippingOrderExtractionMessage" class="mt-1 break-words text-xs opacity-80">
|
||||
<div v-if="shippingOrderExtractionFailureHintKey" class="mt-1 break-words text-xs opacity-80">
|
||||
{{ $t(shippingOrderExtractionFailureHintKey) }}
|
||||
</div>
|
||||
<div v-else-if="showShippingOrderExtractionMessage" class="mt-1 break-words text-xs opacity-80">
|
||||
{{ shippingOrderExtractionState.message }}
|
||||
</div>
|
||||
<button
|
||||
v-if="shippingOrderExtractionRunNo"
|
||||
type="button"
|
||||
class="mt-2 text-xs font-medium underline underline-offset-2 opacity-80 hover:opacity-100"
|
||||
@click="toggleOrderExtractionDetails"
|
||||
>
|
||||
{{ $t(showOrderExtractionDetails ? 'chat.shippingOrderExtractionHideDetails' : 'chat.shippingOrderExtractionShowDetails') }}
|
||||
</button>
|
||||
<div v-if="showOrderExtractionDetails" class="mt-2 space-y-1 border-t border-current/15 pt-2 text-xs opacity-85">
|
||||
<div v-if="loadingOrderExtractionEvents">{{ $t('chat.shippingOrderExtractionLoadingDetails') }}</div>
|
||||
<div v-else-if="orderExtractionEventsError">{{ $t('chat.shippingOrderExtractionDetailsUnavailable') }}</div>
|
||||
<div v-else-if="orderExtractionEvents.length === 0">{{ $t('chat.shippingOrderExtractionNoDetails') }}</div>
|
||||
<div v-for="event in orderExtractionEvents" :key="`${event.stage_code}:${event.occurred_at}`">
|
||||
<span>{{ $t(`chat.shippingOrderExtractionStage.${event.stage_code}`) }}</span>
|
||||
<span class="ml-1 opacity-75">{{ $t(shippingOrderExtractionEventStatusKey(event.status)) }}</span>
|
||||
<time v-if="formatOrderExtractionEventTime(event.occurred_at)" class="ml-1 opacity-65">
|
||||
{{ formatOrderExtractionEventTime(event.occurred_at) }}
|
||||
</time>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
v-if="shippingOrderExtractionState.status === 'failed' && shippingOrderExtractionRunNo"
|
||||
type="button"
|
||||
class="mt-3 inline-flex items-center gap-1.5 rounded-md border border-rose-300 bg-white/75 px-3 py-1.5 text-xs font-medium text-rose-700 transition hover:bg-white disabled:cursor-not-allowed disabled:opacity-60 dark:border-rose-700 dark:bg-rose-950/40 dark:text-rose-200"
|
||||
:disabled="retryingOrderExtraction"
|
||||
@click="retryShippingOrderExtraction"
|
||||
>
|
||||
<RotateCw class="h-3.5 w-3.5" :class="{ 'animate-spin': retryingOrderExtraction }" />
|
||||
{{ $t(retryingOrderExtraction ? 'chat.shippingOrderExtractionRetrying' : 'chat.shippingOrderExtractionRetry') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<LeaveMessageBlock
|
||||
|
||||
@@ -15,4 +15,5 @@ export interface ShippingMessageHandlers {
|
||||
updateLine: (msg: ChatMessage, lineIndex: number, patch: Partial<ShippingNoticeLine>) => Promise<boolean>;
|
||||
addLine: (msg: ChatMessage, line: Partial<ShippingNoticeLine>) => Promise<boolean>;
|
||||
removeLine: (msg: ChatMessage, lineIndex: number) => Promise<boolean>;
|
||||
retryOrderExtractionRun: (runNo: string) => Promise<boolean>;
|
||||
}
|
||||
@@ -881,6 +881,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
query: { ...route.query, conversation_id: resolvedConversationId },
|
||||
});
|
||||
},
|
||||
onRetryError: (message) => msg.error(message),
|
||||
t,
|
||||
});
|
||||
|
||||
@@ -1470,6 +1471,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
handleShippingLocalFilesSelected,
|
||||
removeShippingNoticeAttachment: shippingIntakes.removeNoticeAttachment,
|
||||
retryShippingNoticeAttachment: shippingIntakes.retryNoticeAttachment,
|
||||
retryOrderExtractionRun: shippingOrderExtractionRuns.retryRun,
|
||||
shippingNoticeAllReadyForConfirmation: shippingIntakes.allReadyForConfirmation,
|
||||
setShippingCandidateSelected,
|
||||
updateShippingCandidateSummary,
|
||||
|
||||
@@ -35,6 +35,7 @@ type ShippingHandlerSource = Pick<
|
||||
| 'updateShippingParseReviewLine'
|
||||
| 'addShippingParseReviewLine'
|
||||
| 'removeShippingParseReviewLine'
|
||||
| 'retryOrderExtractionRun'
|
||||
>;
|
||||
|
||||
type TrainingHandlerSource = ReturnType<typeof useTrainingWorkspace>;
|
||||
@@ -68,6 +69,7 @@ export function createShippingMessageHandlers(shipping: ShippingHandlerSource):
|
||||
updateLine: shipping.updateShippingParseReviewLine,
|
||||
addLine: shipping.addShippingParseReviewLine,
|
||||
removeLine: shipping.removeShippingParseReviewLine,
|
||||
retryOrderExtractionRun: shipping.retryOrderExtractionRun,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -580,6 +580,9 @@ export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
|
||||
|
||||
if (msg?.role !== 'assistant') return false;
|
||||
|
||||
// 订单抽取 Run 有专用状态卡,不能再叠加通用工具进度卡。
|
||||
if (msg.shipping_order_extraction_state) return false;
|
||||
|
||||
if (!toolRunProgressConfig.value) return false;
|
||||
|
||||
if (assistantMessageHasError(msg)) return false;
|
||||
|
||||
@@ -14,12 +14,16 @@ const api = vi.hoisted(() => ({
|
||||
createRun: vi.fn(),
|
||||
getRun: vi.fn(),
|
||||
listRuns: vi.fn(),
|
||||
markSeen: vi.fn(),
|
||||
retryRun: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../api/shipping.api', () => ({
|
||||
createWorkspaceShippingOrderExtractionRun: api.createRun,
|
||||
getWorkspaceShippingOrderExtractionRun: api.getRun,
|
||||
listWorkspaceShippingOrderExtractionRuns: api.listRuns,
|
||||
markWorkspaceShippingOrderExtractionRunSeen: api.markSeen,
|
||||
retryWorkspaceShippingOrderExtractionRun: api.retryRun,
|
||||
}));
|
||||
|
||||
const run = (patch: Partial<ShippingOrderExtractionRun>): ShippingOrderExtractionRun => ({
|
||||
@@ -50,6 +54,7 @@ const createHarness = () => {
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
loadHistory: vi.fn(async () => undefined),
|
||||
onConversationResolved: vi.fn(async () => undefined),
|
||||
onRetryError: vi.fn(),
|
||||
t: (key: string) => key,
|
||||
};
|
||||
return { messages, conversationId, options, runs: useShippingOrderExtractionRuns(options) };
|
||||
@@ -127,16 +132,110 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
expect(harness.messages.value[1]?.shipping_order_extraction_state?.status).toBe('extracting');
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('retries a failed Run in place and resumes polling without creating a new user message', async () => {
|
||||
const failed = run({ run_no: 'SNER-RETRY', status: 'failed', phase: 'failed', error: { message: 'bad workflow' } });
|
||||
const queued = run({ run_no: 'SNER-RETRY', status: 'queued', phase: 'manual_retry_queued', error: null });
|
||||
api.listRuns.mockResolvedValue({ items: [failed] });
|
||||
api.retryRun.mockResolvedValue({ run: queued, reused: false });
|
||||
api.getRun.mockResolvedValue(queued);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
|
||||
await expect(harness.runs.retryRun('SNER-RETRY')).resolves.toBe(true);
|
||||
|
||||
expect(api.retryRun).toHaveBeenCalledWith('SNER-RETRY');
|
||||
expect(harness.options.refreshNoticeIntakeStatuses).toHaveBeenCalledTimes(1);
|
||||
expect(harness.messages.value).toHaveLength(1);
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('extracting');
|
||||
expect(harness.runs.getActiveRunNo()).toBe('SNER-RETRY');
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('reports a retry API error and leaves the failed state available for another retry', async () => {
|
||||
api.retryRun.mockRejectedValue(new Error('retry unavailable'));
|
||||
const harness = createHarness();
|
||||
|
||||
await expect(harness.runs.retryRun('SNER-FAILED')).resolves.toBe(false);
|
||||
|
||||
expect(harness.options.onRetryError).toHaveBeenCalledWith('retry unavailable');
|
||||
expect(harness.runs.getActiveRunNo()).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('mapOrderExtractionRunToMessageState', () => {
|
||||
it('maps queued/running to indeterminate extracting state', () => {
|
||||
expect(mapOrderExtractionRunToMessageState(run({ status: 'running', phase: 'calling_provider' }))).toMatchObject({
|
||||
expect(mapOrderExtractionRunToMessageState(run({
|
||||
status: 'running',
|
||||
phase: 'calling_provider',
|
||||
progress: {
|
||||
version: 3,
|
||||
current_stage_code: 'document_processing',
|
||||
health: 'normal',
|
||||
last_activity_at: '2026-07-21T03:24:51Z',
|
||||
},
|
||||
}))).toMatchObject({
|
||||
status: 'extracting', terminal: false, phase: 'llm_extraction',
|
||||
current_stage_code: 'document_processing', health: 'normal',
|
||||
last_activity_at: '2026-07-21T03:24:51Z',
|
||||
});
|
||||
});
|
||||
|
||||
it('persists a changed progress projection even when Run status and result are unchanged', async () => {
|
||||
vi.useFakeTimers();
|
||||
const first = run({
|
||||
run_no: 'SNER-PROGRESS',
|
||||
status: 'running',
|
||||
progress: { version: 1, current_stage_code: 'workflow_accepted' },
|
||||
});
|
||||
const second = run({
|
||||
run_no: 'SNER-PROGRESS',
|
||||
status: 'running',
|
||||
progress: { version: 2, current_stage_code: 'order_recognition' },
|
||||
});
|
||||
api.listRuns.mockResolvedValue({ items: [first] });
|
||||
api.getRun.mockResolvedValueOnce(second);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(1);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
|
||||
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.current_stage_code).toBe('order_recognition');
|
||||
harness.runs.stopPolling();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('merges duplicate local cards for one Run when a terminal update arrives', async () => {
|
||||
vi.useFakeTimers();
|
||||
const active = run({ run_no: 'SNER-DUPLICATE', status: 'running' });
|
||||
const failed = run({
|
||||
run_no: 'SNER-DUPLICATE', status: 'failed', phase: 'failed', error: { message: 'provider unavailable' },
|
||||
});
|
||||
api.listRuns.mockResolvedValue({ items: [active] });
|
||||
api.getRun.mockResolvedValue(failed);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
harness.messages.value.push({
|
||||
role: 'assistant', type: 'text', content: '', local_id: 'legacy-duplicate', local_only: true,
|
||||
shipping_order_extraction_state: mapOrderExtractionRunToMessageState(active),
|
||||
payload: { formId: 'legacy-state-card', order_extraction_run_no: 'SNER-DUPLICATE' },
|
||||
});
|
||||
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
|
||||
const cards = harness.messages.value.filter((item) => item.shipping_order_extraction_state);
|
||||
expect(cards).toHaveLength(1);
|
||||
expect(cards[0]?.shipping_order_extraction_state?.status).toBe('failed');
|
||||
harness.runs.stopPolling();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('maps completed result counters without guessing from text', () => {
|
||||
expect(mapOrderExtractionRunToMessageState(run({
|
||||
status: 'completed',
|
||||
@@ -152,6 +251,19 @@ describe('mapOrderExtractionRunToMessageState', () => {
|
||||
}))).toMatchObject({ status: 'partially_completed', pending_count: 3, terminal: true });
|
||||
expect(mapOrderExtractionRunToMessageState(run({
|
||||
status: 'failed', error: { code: 'X', message: 'provider failed' },
|
||||
}))).toMatchObject({ status: 'failed', message: 'provider failed', terminal: true });
|
||||
}))).toMatchObject({ status: 'failed', message: '', terminal: true });
|
||||
});
|
||||
|
||||
it('acknowledges a terminal Run only after it is restored into the active conversation', async () => {
|
||||
const terminal = run({ run_no: 'SNER-SEEN', status: 'completed' });
|
||||
api.listRuns.mockResolvedValue({ items: [terminal] });
|
||||
api.markSeen.mockResolvedValue({ seen: true });
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
|
||||
expect(api.markSeen).toHaveBeenCalledWith('SNER-SEEN');
|
||||
expect(harness.options.loadHistory).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
createWorkspaceShippingOrderExtractionRun,
|
||||
getWorkspaceShippingOrderExtractionRun,
|
||||
listWorkspaceShippingOrderExtractionRuns,
|
||||
markWorkspaceShippingOrderExtractionRunSeen,
|
||||
retryWorkspaceShippingOrderExtractionRun,
|
||||
} from '../api/shipping.api';
|
||||
import type { ChatMessage, ChatMessageAttachment, ShippingOrderExtractionState } from '../types/chat.types';
|
||||
import type { ShippingOrderExtractionRun } from '../types/shipping.api.types';
|
||||
@@ -25,6 +27,7 @@ interface UseShippingOrderExtractionRunsOptions {
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
loadHistory: () => Promise<void>;
|
||||
onConversationResolved: (conversationId: string) => Promise<void> | void;
|
||||
onRetryError: (message: string) => void;
|
||||
t: (key: string, params?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
@@ -39,7 +42,8 @@ export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtraction
|
||||
return {
|
||||
status: failed ? 'failed' : partial ? 'partially_completed' : completed ? 'completed' : 'extracting',
|
||||
phase: failed ? 'failed' : run.status === 'result_persisted' ? 'result_persisted' : 'llm_extraction',
|
||||
message: failed ? String(run.error?.message || '') : '',
|
||||
// Provider/网络错误正文仅供管理员诊断,用户卡片统一展示可操作的业务提示。
|
||||
message: '',
|
||||
created_count: Number(result.created_count || 0),
|
||||
opened_existing_count: Number(result.opened_existing_count || 0),
|
||||
pending_count: Number(result.pending_count || 0),
|
||||
@@ -47,6 +51,10 @@ export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtraction
|
||||
created_with_missing_fields_count: Number(result.created_with_missing_fields_count || 0),
|
||||
batch_no: result.batch_no || null,
|
||||
terminal: failed || partial || completed,
|
||||
current_stage_code: run.progress?.current_stage_code || null,
|
||||
health: run.progress?.health || 'normal',
|
||||
last_activity_at: run.progress?.last_activity_at || null,
|
||||
started_at: run.started_at || run.created_at || null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -77,10 +85,19 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
const upsertRunMessage = async (run: ShippingOrderExtractionRun): Promise<ChatMessage> => {
|
||||
const formId = `shipping-order-extraction-run:${run.run_no}`;
|
||||
const state = mapOrderExtractionRunToMessageState(run);
|
||||
let message = options.messages.value.find((item) => {
|
||||
const stateCards = options.messages.value.filter((item) => {
|
||||
if (item.role !== 'assistant') return false;
|
||||
const payload = item.payload && typeof item.payload === 'object' ? item.payload as Record<string, unknown> : {};
|
||||
return payload.formId === formId || payload.order_extraction_run_no === run.run_no;
|
||||
});
|
||||
let message = stateCards.find((item) => {
|
||||
const payload = item.payload && typeof item.payload === 'object' ? item.payload as Record<string, unknown> : {};
|
||||
return payload.formId === formId;
|
||||
});
|
||||
}) || stateCards[0];
|
||||
if (stateCards.length > 1) {
|
||||
// 网络恢复或历史合并可能重复注入同一 Run 的旧卡;Run 编号是唯一业务锚点,只保留一张原位更新。
|
||||
options.messages.value = options.messages.value.filter((item) => item === message || !stateCards.includes(item));
|
||||
}
|
||||
if (!message) {
|
||||
message = {
|
||||
role: 'assistant',
|
||||
@@ -97,7 +114,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
order_extraction_run_no: run.run_no,
|
||||
shipping_order_extraction_state: state,
|
||||
};
|
||||
const signature = JSON.stringify({ status: run.status, phase: run.phase, result: run.result, error: run.error });
|
||||
const signature = JSON.stringify({ status: run.status, phase: run.phase, result: run.result, error: run.error, progress: run.progress });
|
||||
if (persistedSignatures.get(run.run_no) !== signature) {
|
||||
const persisted = await options.saveLocalMessageToBackend(message);
|
||||
if (persisted) persistedSignatures.set(run.run_no, signature);
|
||||
@@ -105,6 +122,25 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
return message;
|
||||
};
|
||||
|
||||
/**
|
||||
* 终态卡已投影到当前会话后才确认已查看,避免侧栏或历史预加载错误清除提醒。
|
||||
* 确认失败不影响状态卡、轮询或业务 Run,下一次进入会话会继续尝试。
|
||||
*/
|
||||
const acknowledgeTerminalRunWhenVisible = async (run: ShippingOrderExtractionRun): Promise<void> => {
|
||||
if (ACTIVE_RUN_STATUSES.has(run.status) || run.conversation_id !== options.conversationId.value) return;
|
||||
const stateCardVisible = options.messages.value.some((item) => {
|
||||
const payload = item.payload && typeof item.payload === 'object' ? item.payload as Record<string, unknown> : {};
|
||||
return payload.order_extraction_run_no === run.run_no && item.shipping_order_extraction_state?.terminal;
|
||||
});
|
||||
if (!stateCardVisible) return;
|
||||
try {
|
||||
await markWorkspaceShippingOrderExtractionRunSeen(run.run_no);
|
||||
await options.loadHistory();
|
||||
} catch {
|
||||
// 待查看状态仍由服务端保留,后续成功加载同一终态卡时再次确认。
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Run 终态后容错刷新领域事实;单个视图失败不得阻断其他事实和聊天历史恢复。
|
||||
* @returns 所有可独立执行的刷新均已尝试完成。
|
||||
@@ -152,6 +188,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
if (generation !== pollGeneration || activeRunNo !== runNo) return;
|
||||
pollFailureCount = 0;
|
||||
await upsertRunMessage(run);
|
||||
await acknowledgeTerminalRunWhenVisible(run);
|
||||
if (generation !== pollGeneration || activeRunNo !== runNo) return;
|
||||
if (!ACTIVE_RUN_STATUSES.has(run.status)) {
|
||||
stopPolling();
|
||||
@@ -211,6 +248,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
options.messages.value.push(userMessage);
|
||||
await options.saveLocalMessageToBackend(userMessage, query);
|
||||
await upsertRunMessage(run);
|
||||
await acknowledgeTerminalRunWhenVisible(run);
|
||||
await options.onConversationResolved(run.conversation_id);
|
||||
if (ACTIVE_RUN_STATUSES.has(run.status)) {
|
||||
beginPolling(run.run_no, 1000);
|
||||
@@ -220,6 +258,26 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
return true;
|
||||
};
|
||||
|
||||
/** 复用原 Run 的冻结附件重新识别,并恢复同一状态卡的轮询。 */
|
||||
const retryRun = async (runNo: string): Promise<boolean> => {
|
||||
const normalizedRunNo = String(runNo || '').trim();
|
||||
if (!normalizedRunNo) return false;
|
||||
try {
|
||||
stopPolling();
|
||||
const response = await retryWorkspaceShippingOrderExtractionRun(normalizedRunNo);
|
||||
await upsertRunMessage(response.run);
|
||||
await acknowledgeTerminalRunWhenVisible(response.run);
|
||||
await Promise.allSettled([options.refreshNoticeIntakeStatuses()]);
|
||||
if (ACTIVE_RUN_STATUSES.has(response.run.status)) {
|
||||
beginPolling(response.run.run_no, 1000);
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
options.onRetryError(error instanceof Error ? error.message : options.t('chat.shippingOrderExtractionRetryFailed'));
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 刷新或进入既有会话时恢复最新 Run;活动 Run 继续轮询,终态只恢复状态卡。 */
|
||||
const restoreForConversation = async (conversationId: string): Promise<void> => {
|
||||
stopPolling();
|
||||
@@ -231,6 +289,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
const latest = items[0];
|
||||
if (!latest) return;
|
||||
await upsertRunMessage(latest);
|
||||
await acknowledgeTerminalRunWhenVisible(latest);
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
if (ACTIVE_RUN_STATUSES.has(latest.status)) {
|
||||
beginPolling(latest.run_no, 1000);
|
||||
@@ -241,5 +300,5 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
};
|
||||
|
||||
onBeforeUnmount(stopPolling);
|
||||
return { startRun, restoreForConversation, stopPolling, getActiveRunNo: () => activeRunNo };
|
||||
return { startRun, retryRun, restoreForConversation, stopPolling, getActiveRunNo: () => activeRunNo };
|
||||
}
|
||||
@@ -31,6 +31,10 @@ export interface ShippingOrderExtractionState {
|
||||
created_with_missing_fields_count: number;
|
||||
batch_no?: string | null;
|
||||
terminal: boolean;
|
||||
current_stage_code?: string | null;
|
||||
health?: string;
|
||||
last_activity_at?: string | null;
|
||||
started_at?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -123,6 +127,8 @@ export interface ChatSessionItem {
|
||||
conversation_id: string;
|
||||
title: string;
|
||||
created_at: string;
|
||||
unseen_order_extraction_count?: number;
|
||||
unseen_order_extraction_severity?: 'info' | 'warning' | 'error' | null;
|
||||
}
|
||||
|
||||
export type DisplayHistoryItem = ChatSessionItem & { __runId?: number; __status?: string };
|
||||
|
||||
@@ -249,6 +249,14 @@ export interface ShippingFieldAdjudication {
|
||||
conflicts?: Array<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
export interface ShippingOrderDisplayField {
|
||||
field_code: string;
|
||||
display_name: string;
|
||||
scope: 'header' | 'line' | string;
|
||||
value_type: string;
|
||||
sequence: number;
|
||||
}
|
||||
|
||||
/** 工作台任务列表的数据库分页响应;items 仅包含当前页。 */
|
||||
export interface ShippingTaskPage {
|
||||
items: ShippingTaskSummary[];
|
||||
@@ -338,6 +346,9 @@ export interface ShippingTaskDetail extends ShippingTaskSummary {
|
||||
export_version?: number | null;
|
||||
idempotency_key?: string | null;
|
||||
lines: ShippingNoticeLine[];
|
||||
order_header?: Record<string, unknown>;
|
||||
order_header_fields?: ShippingOrderDisplayField[];
|
||||
order_line_fields?: ShippingOrderDisplayField[];
|
||||
shortage?: ShippingShortageSummary | null;
|
||||
line_results?: ShippingMatchLineResult[];
|
||||
parse_confidence?: number | null;
|
||||
@@ -560,6 +571,15 @@ export interface ShippingOrderExtractionRun {
|
||||
schema_version?: number | null;
|
||||
schema_checksum?: string | null;
|
||||
attempt_count: number;
|
||||
progress?: {
|
||||
version: number;
|
||||
current_stage_code?: string | null;
|
||||
active_stage_codes?: string[];
|
||||
completed_stage_codes?: string[];
|
||||
message_code?: string | null;
|
||||
health?: string;
|
||||
last_activity_at?: string | null;
|
||||
} | null;
|
||||
result?: {
|
||||
batch_no?: string | null;
|
||||
created_count?: number;
|
||||
@@ -575,6 +595,12 @@ export interface ShippingOrderExtractionRun {
|
||||
finished_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionProgressEvent {
|
||||
stage_code: string;
|
||||
status: string;
|
||||
occurred_at: string;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionRunCreateResponse {
|
||||
run: ShippingOrderExtractionRun;
|
||||
reused: boolean;
|
||||
|
||||
Reference in new issue
Block a user