refactor(agent, shipping): 简化代理模型并完善订单抽取业务
- 移除 Agent 的 exposure_mode 与 internal_executor 相关逻辑,清理关联的过滤、序列化代码 - 删除废弃的 AgentRuntimeBinding 模型及其依赖 - 新增订单抽取上传批次、请求快照等数据库迁移与业务逻辑 - 修复附件完整性检测、订单抽取状态映射问题 - 更新多语言错误文案与前端单元测试配置 - 清理平台配置中不再使用的暴露模式配置
This commit is contained in:
1 parent
1f3ecb87b7
commit
61ac6403c4
159 files changed
+12883
-5099
No files matched your search
@@ -68,17 +68,30 @@ export type ShippingInventoryValidationBatch = {
|
||||
runs: ShippingInventoryConfigurationTest[];
|
||||
};
|
||||
|
||||
export type ShippingOrderExtractionDiagnosticAutoFreezePolicy = {
|
||||
mode: string;
|
||||
enabled: boolean;
|
||||
selected_profile_code?: string | null;
|
||||
qualification_status?: string | null;
|
||||
customer_scope_status?: string | null;
|
||||
business_scenario_status?: string | null;
|
||||
customer_confirmation_required: boolean;
|
||||
evaluated_from_run: boolean;
|
||||
blocking_reason_codes: string[];
|
||||
};
|
||||
|
||||
export type ShippingOrderExtractionDiagnosticRun = {
|
||||
run_no: string; status: string; phase: string; conversation_id: string; workflow_run_id?: string | null;
|
||||
attempt_count: number; current_stage_code?: string | null; created_at?: string | null; started_at?: string | null;
|
||||
finished_at?: string | null; error_code?: string | null; durations_ms: Record<string, number | null>;
|
||||
run_no: string; status: string; phase: string; conversation_id: string;
|
||||
attempt_count: number; current_event_code?: string | null; created_at?: string | null; started_at?: string | null;
|
||||
candidate_materialized_at?: string | null; finished_at?: string | null; error_code?: string | null; durations_ms: Record<string, number | null>;
|
||||
result_counts: Record<string, number>;
|
||||
auto_freeze_policy: ShippingOrderExtractionDiagnosticAutoFreezePolicy;
|
||||
};
|
||||
export type ShippingOrderExtractionDiagnosticDetail = {
|
||||
run: ShippingOrderExtractionDiagnosticRun;
|
||||
job_attempts: Array<{ job_id: number; status: string; attempts: number; max_attempts: number; created_at?: string | null; started_at?: string | null; finished_at?: string | null; duration_ms?: number | null }>;
|
||||
units: Array<{ unit_id: number; position: number; unit_type: string; document_type: string; status: string; attempt_count: number; duration_ms?: number | null; error_code?: string | null; route_decisions: Array<{ attempt_no: number; execution_mode: 'deterministic' | 'dify' | 'blocked'; match_status: string; selected_profile_code?: string | null; selected_profile_version?: number | null; auto_create_approved?: boolean | null; candidate_count: number; table_count: number; approved_table_count: number; candidates: Array<{ profile_code: string; version: number; score: number; hard_match: boolean; reason_codes: string[]; missing_required_anchor_ids?: string[] }>; fallback_reason_codes: string[] }> }>;
|
||||
progress_events: Array<{ event_type: string; node_type?: string | null; stage_code?: string | null; status?: string | null; workflow_run_id?: string | null; node_execution_id?: string | null; occurred_at?: string | null }>;
|
||||
units: Array<{ unit_id: number; position: number; unit_type: string; document_type: string; status: string; attempt_count: number; duration_ms?: number | null; error_code?: string | null; route_decisions: Array<{ attempt_no: number; execution_mode: 'deterministic' | 'review_required' | 'skipped'; match_status: string; selected_profile_code?: string | null; selected_profile_version?: number | null; auto_create_approved?: boolean | null; candidate_count: number; table_count: number; approved_table_count: number; candidates: Array<{ profile_code: string; version: number; score: number; hard_match: boolean; reason_codes: string[]; missing_required_anchor_ids?: string[] }>; fallback_reason_codes: string[] }> }>;
|
||||
progress_events: Array<{ sequence_no: number; visibility: 'workspace' | 'admin'; event_code: string; status?: string | null; unit_id?: number | null; document_id?: number | null; reason_code?: string | null; summary?: Record<string, unknown> | null; occurred_at?: string | null }>;
|
||||
};
|
||||
export const listShippingOrderExtractionDiagnosticRuns = (page = 1, pageSize = 25, status = '') => {
|
||||
const params = new URLSearchParams({ page: String(page), page_size: String(pageSize) });
|
||||
@@ -429,7 +442,6 @@ export interface AdminAgentRegistrySchema {
|
||||
runtime_providers: string[];
|
||||
conversation_modes: string[];
|
||||
dify_app_types: string[];
|
||||
exposure_modes: string[];
|
||||
suggested_questions_styles: string[];
|
||||
default_capabilities: Record<string, boolean>;
|
||||
tool_run_progress_defaults: {
|
||||
@@ -451,14 +463,6 @@ export interface AdminAgentRegistrySchema {
|
||||
default_intent_routes?: string[];
|
||||
progress_contract?: Record<string, unknown> | null;
|
||||
handler_config_schema?: Record<string, unknown>;
|
||||
required_runtime_capabilities?: Record<string, {
|
||||
label?: string;
|
||||
required?: boolean;
|
||||
allowed_runtime_providers?: string[];
|
||||
allowed_dify_app_types?: string[];
|
||||
allowed_exposure_modes?: string[];
|
||||
allowed_effective_roles?: string[];
|
||||
}>;
|
||||
}>;
|
||||
handler_config_schemas: Record<string, unknown>;
|
||||
content_profile_keys: string[];
|
||||
@@ -501,30 +505,11 @@ export interface AdminContentProfileOption {
|
||||
export const listAdminContentProfiles = () =>
|
||||
requestJson<AdminContentProfileOption[]>('/api/admin/agents/content-profiles', auth());
|
||||
|
||||
export const listAdminAgents = (scope?: 'applications' | 'executors') => requestJson<any[]>(
|
||||
`/api/admin/agents${scope ? `?scope=${scope}` : ''}`,
|
||||
auth(),
|
||||
);
|
||||
export const listAdminAgents = () => requestJson<any[]>('/api/admin/agents', auth());
|
||||
export const createAdminAgent = (payload: Record<string, unknown>) =>
|
||||
requestJson('/api/admin/agents', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||
export const updateAdminAgent = (id: number, payload: Record<string, unknown>) =>
|
||||
requestJson(`/api/admin/agents/${id}`, { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||
export const listAdminAgentRuntimeBindings = (agentId: number) =>
|
||||
requestJson<import('@/features/admin/types/agent.types').AgentRuntimeBindingRow[]>(
|
||||
`/api/admin/agents/${agentId}/runtime-bindings`, auth(),
|
||||
);
|
||||
export const listApprovedOrderExtractionQualityBatches = (ownerAgentId: number) =>
|
||||
requestJson<import('@/features/admin/types/agent.types').OrderExtractionQualityBatchOption[]>(
|
||||
`/api/admin/shipping-notice/order-extraction-quality-batches?owner_agent_id=${ownerAgentId}`, auth(),
|
||||
);
|
||||
export const saveAdminAgentRuntimeBinding = (
|
||||
agentId: number,
|
||||
capabilityCode: string,
|
||||
payload: { provider_agent_id: number; enabled: boolean; config: Record<string, unknown> },
|
||||
) => requestJson<import('@/features/admin/types/agent.types').AgentRuntimeBindingRow>(
|
||||
`/api/admin/agents/${agentId}/runtime-bindings/${capabilityCode}`,
|
||||
{ method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) },
|
||||
);
|
||||
export const deleteAdminAgent = (id: number) =>
|
||||
requestJson(`/api/admin/agents/${id}`, { method: 'DELETE', ...auth() });
|
||||
|
||||
|
||||
@@ -73,25 +73,14 @@ const {
|
||||
resetColumnWidths,
|
||||
} = useAgentsTableColumnResize();
|
||||
|
||||
const tableHeaderColumns = computed(() => (
|
||||
activeManagementTab.value === 'executors'
|
||||
? [
|
||||
{ key: 'name', label: t('admin.agent.headers.name'), align: 'left' as const },
|
||||
{ key: 'executorType', label: t('admin.agent.headers.executorType'), align: 'left' as const },
|
||||
{ key: 'protocol', label: t('admin.agent.headers.runtimeProtocol'), align: 'left' as const },
|
||||
{ key: 'config', label: t('admin.agent.headers.config'), align: 'left' as const },
|
||||
{ key: 'status', label: t('admin.agent.headers.status'), align: 'left' as const },
|
||||
{ key: 'actions', label: t('admin.agent.headers.actions'), align: 'right' as const },
|
||||
]
|
||||
: [
|
||||
{ key: 'name', label: t('admin.agent.headers.name'), align: 'left' as const },
|
||||
{ key: 'type', label: t('admin.agent.headers.type'), align: 'left' as const },
|
||||
{ key: 'aggregation', label: t('admin.agent.headers.aggregation'), align: 'left' as const },
|
||||
{ key: 'config', label: t('admin.agent.headers.config'), align: 'left' as const },
|
||||
{ key: 'status', label: t('admin.agent.headers.status'), align: 'left' as const },
|
||||
{ key: 'actions', label: t('admin.agent.headers.actions'), align: 'right' as const },
|
||||
]
|
||||
));
|
||||
const tableHeaderColumns = computed(() => [
|
||||
{ key: 'name', label: t('admin.agent.headers.name'), align: 'left' as const },
|
||||
{ key: 'type', label: t('admin.agent.headers.type'), align: 'left' as const },
|
||||
{ key: 'aggregation', label: t('admin.agent.headers.aggregation'), align: 'left' as const },
|
||||
{ key: 'config', label: t('admin.agent.headers.config'), align: 'left' as const },
|
||||
{ key: 'status', label: t('admin.agent.headers.status'), align: 'left' as const },
|
||||
{ key: 'actions', label: t('admin.agent.headers.actions'), align: 'right' as const },
|
||||
]);
|
||||
|
||||
const formatAgentCode = (agent: AgentRow) => agent.agent_code || 'generic';
|
||||
|
||||
@@ -144,17 +133,6 @@ const formatRuntimeProviderLabel = (agent: AgentRow) => {
|
||||
};
|
||||
|
||||
const showFormDialog = ref(false);
|
||||
const activeManagementTab = ref<'applications' | 'executors'>('applications');
|
||||
const visibleAgents = computed(() => agents.value.filter((agent) => (
|
||||
activeManagementTab.value === 'executors'
|
||||
? agent.exposure_mode === 'internal'
|
||||
: agent.exposure_mode !== 'internal'
|
||||
)));
|
||||
const emptyStateText = computed(() => (
|
||||
activeManagementTab.value === 'executors'
|
||||
? t('admin.agent.executor.empty')
|
||||
: t('admin.agent.noAgents')
|
||||
));
|
||||
|
||||
/**
|
||||
* 打开新建应用弹窗并重置表单状态。
|
||||
@@ -165,16 +143,6 @@ const openCreateDialog = (): void => {
|
||||
showFormDialog.value = true;
|
||||
};
|
||||
|
||||
const formatExecutorProtocol = (agent: AgentRow) => (
|
||||
`${formatRuntimeProviderLabel(agent)} · ${agent.dify_app_type === 'workflow' ? 'Workflow' : 'Chatflow'}`
|
||||
);
|
||||
|
||||
/** 打开内部执行器专用注册入口,预置 Dify Workflow 与 internal 可见性。 */
|
||||
const openCreateInternalExecutorDialog = (): void => {
|
||||
resetForm('internal_executor');
|
||||
showFormDialog.value = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开编辑应用弹窗并载入当前行数据。
|
||||
* 核心逻辑:复用 selectAgent 的表单映射逻辑,确保列表行、权限弹窗和保存接口使用同一份状态。
|
||||
@@ -210,41 +178,16 @@ onMounted(() => {
|
||||
<h2 class="section-title">{{ t('admin.agent.title') }}</h2>
|
||||
<p class="section-desc mt-1">{{ t('admin.agent.subtitle') }}</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<button v-if="activeManagementTab === 'executors'" type="button" class="btn-primary" @click="openCreateInternalExecutorDialog">
|
||||
<Plus class="w-5 h-5" />
|
||||
<span class="font-medium">{{ t('admin.agent.newInternalExecutor') }}</span>
|
||||
</button>
|
||||
<button v-else type="button" class="btn-primary" @click="openCreateDialog">
|
||||
<Plus class="w-5 h-5" />
|
||||
<span class="font-medium">{{ t('admin.agent.new') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-6 flex gap-1 border-b border-default">
|
||||
<button
|
||||
type="button"
|
||||
class="-mb-px border-b-2 px-4 py-2.5 text-sm font-medium transition-colors"
|
||||
:class="activeManagementTab === 'applications' ? 'border-brand-600 text-brand-600' : 'border-transparent text-muted hover:text-secondary'"
|
||||
@click="activeManagementTab = 'applications'"
|
||||
>
|
||||
{{ t('admin.agent.tabs.applications') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="-mb-px border-b-2 px-4 py-2.5 text-sm font-medium transition-colors"
|
||||
:class="activeManagementTab === 'executors' ? 'border-brand-600 text-brand-600' : 'border-transparent text-muted hover:text-secondary'"
|
||||
@click="activeManagementTab = 'executors'"
|
||||
>
|
||||
{{ t('admin.agent.tabs.executors') }}
|
||||
<button type="button" class="btn-primary" @click="openCreateDialog">
|
||||
<Plus class="w-5 h-5" />
|
||||
<span class="font-medium">{{ t('admin.agent.new') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="admin-table-wrap">
|
||||
<div v-if="visibleAgents.length === 0" class="admin-table-empty">
|
||||
<div v-if="agents.length === 0" class="admin-table-empty">
|
||||
<Bot class="w-12 h-12 mx-auto text-muted mb-3" />
|
||||
<p class="text-lg text-secondary">{{ emptyStateText }}</p>
|
||||
<p class="text-lg text-secondary">{{ t('admin.agent.noAgents') }}</p>
|
||||
</div>
|
||||
<table
|
||||
v-else
|
||||
@@ -280,7 +223,7 @@ onMounted(() => {
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="agent in visibleAgents"
|
||||
v-for="agent in agents"
|
||||
:key="agent.id"
|
||||
class="group cursor-pointer"
|
||||
:class="{ 'bg-blue-50/50': selectedAgentId === agent.id }"
|
||||
@@ -300,22 +243,16 @@ onMounted(() => {
|
||||
</td>
|
||||
<td class="px-4 py-4 align-middle">
|
||||
<div class="agent-list-cell">
|
||||
<p class="truncate text-sm text-primary" :title="activeManagementTab === 'executors' ? agent.name : formatAgentTypeLabel(agent)">
|
||||
{{ activeManagementTab === 'executors' ? t('admin.agent.executor.workflowExecutor') : formatAgentTypeLabel(agent) }}
|
||||
<p class="truncate text-sm text-primary" :title="formatAgentTypeLabel(agent)">
|
||||
{{ formatAgentTypeLabel(agent) }}
|
||||
</p>
|
||||
<p class="truncate text-xs text-muted" :title="formatRuntimeProviderLabel(agent)">
|
||||
{{ activeManagementTab === 'executors' ? t('admin.agent.executor.internalOnly') : formatRuntimeProviderLabel(agent) }}
|
||||
{{ formatRuntimeProviderLabel(agent) }}
|
||||
</p>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-4 py-4 align-middle">
|
||||
<div v-if="activeManagementTab === 'executors'" class="agent-list-cell">
|
||||
<p class="truncate text-sm font-medium text-primary" :title="formatExecutorProtocol(agent)">
|
||||
{{ formatExecutorProtocol(agent) }}
|
||||
</p>
|
||||
<p class="truncate text-xs text-muted">{{ t('admin.agent.executor.internalOnly') }}</p>
|
||||
</div>
|
||||
<div v-else class="agent-list-cell">
|
||||
<div class="agent-list-cell">
|
||||
<p
|
||||
class="truncate text-sm font-medium"
|
||||
:class="agent.is_aggregate ? 'text-brand-700' : 'text-secondary'"
|
||||
@@ -364,7 +301,6 @@ onMounted(() => {
|
||||
{{ t('admin.edit') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="agent.exposure_mode !== 'internal'"
|
||||
type="button"
|
||||
class="inline-flex shrink-0 items-center justify-center p-2 text-blue-600 bg-blue-50 hover:bg-blue-100 rounded-lg transition-all"
|
||||
:title="t('admin.agent.manageAccess')"
|
||||
|
||||
@@ -66,16 +66,6 @@ const directoryMemberSearch = ref('');
|
||||
|
||||
const showDifyFields = computed(() => props.form.runtime_provider === 'dify' || props.form.runtime_provider === 'hybrid');
|
||||
const showIframeFields = computed(() => props.form.runtime_provider === 'iframe');
|
||||
const isInternalExecutor = computed(() => props.form.exposure_mode === 'internal');
|
||||
const dialogTitle = computed(() => {
|
||||
if (isInternalExecutor.value) {
|
||||
return props.isEditing ? t('admin.agent.editInternalExecutor') : t('admin.agent.createInternalExecutor');
|
||||
}
|
||||
return props.isEditing ? t('admin.agent.edit') : t('admin.agent.create');
|
||||
});
|
||||
const dialogSubtitle = computed(() => (
|
||||
isInternalExecutor.value ? t('admin.agent.executor.formSubtitle') : t('admin.agent.subtitle')
|
||||
));
|
||||
const showToolRunProgress = computed(() => (
|
||||
showDifyFields.value
|
||||
&& props.form.dify_app_type !== 'workflow'
|
||||
@@ -218,18 +208,6 @@ watch(
|
||||
},
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.form.exposure_mode,
|
||||
(exposure) => {
|
||||
if (exposure === 'internal') {
|
||||
props.form.runtime_provider = 'dify';
|
||||
props.form.dify_app_type = 'workflow';
|
||||
props.form.conversation_mode = 'task_chat';
|
||||
props.form.welcome_message = '';
|
||||
props.form.suggested_questions = [];
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.form.is_aggregate,
|
||||
@@ -282,8 +260,8 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
<div class="flex max-h-[92vh] w-full max-w-5xl flex-col overflow-hidden rounded-2xl border border-default bg-surface shadow-2xl">
|
||||
<div class="flex items-start justify-between gap-4 border-b border-default px-6 py-5">
|
||||
<div>
|
||||
<h3 class="section-title">{{ dialogTitle }}</h3>
|
||||
<p class="section-desc mt-1">{{ dialogSubtitle }}</p>
|
||||
<h3 class="section-title">{{ isEditing ? t('admin.agent.edit') : t('admin.agent.create') }}</h3>
|
||||
<p class="section-desc mt-1">{{ t('admin.agent.subtitle') }}</p>
|
||||
</div>
|
||||
<button type="button" class="btn-icon-ds shrink-0" @click="emit('close')">
|
||||
<X class="h-5 w-5" />
|
||||
@@ -301,7 +279,7 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
:placeholder="t('admin.agent.fields.namePlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="!isInternalExecutor" class="space-y-2">
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.agentCode') }}</label>
|
||||
<select v-model="form.agent_code" class="w-full input-field text-sm" @change="handleAgentCodeChange">
|
||||
<option v-for="entry in typeCatalog" :key="entry.agent_code" :value="entry.agent_code">
|
||||
@@ -309,7 +287,7 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div v-if="!isInternalExecutor" class="space-y-2">
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.runtimeProvider') }}</label>
|
||||
<select v-model="form.runtime_provider" class="w-full input-field text-sm">
|
||||
<option v-for="provider in runtimeProviders" :key="provider" :value="provider">
|
||||
@@ -317,7 +295,7 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div v-if="!isInternalExecutor" class="space-y-2">
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.conversationMode') }}</label>
|
||||
<select v-model="form.conversation_mode" class="w-full input-field text-sm">
|
||||
<option v-for="mode in conversationModes" :key="mode" :value="mode">
|
||||
@@ -326,9 +304,9 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
</select>
|
||||
</div>
|
||||
<template v-if="showDifyFields">
|
||||
<div v-if="!isInternalExecutor" class="space-y-2">
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">Dify应用类型</label>
|
||||
<select v-model="form.dify_app_type" class="w-full input-field text-sm" :disabled="isInternalExecutor">
|
||||
<select v-model="form.dify_app_type" class="w-full input-field text-sm">
|
||||
<option value="chatflow">Chatflow</option>
|
||||
<option value="workflow">Workflow</option>
|
||||
</select>
|
||||
@@ -356,15 +334,6 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div v-if="isInternalExecutor" class="col-span-1 md:col-span-2 rounded-xl border border-default bg-surface-soft p-4">
|
||||
<div class="mb-4"><h4 class="text-sm font-semibold text-primary">{{ t('admin.agent.runtimeBinding.executorGovernance') }}</h4></div>
|
||||
<div class="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
<div class="space-y-2"><label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.runtimeBinding.providerMaxConcurrency') }}</label><input v-model.number="form.executor_provider_max_concurrency" type="number" min="1" max="20" class="w-full input-field text-sm" /></div>
|
||||
<div class="space-y-2"><label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.runtimeBinding.circuitFailureThreshold') }}</label><input v-model.number="form.executor_circuit_failure_threshold" type="number" min="2" max="20" class="w-full input-field text-sm" /></div>
|
||||
<div class="space-y-2"><label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.runtimeBinding.circuitCooldown') }}</label><input v-model.number="form.executor_circuit_cooldown_seconds" type="number" min="10" max="600" class="w-full input-field text-sm" /></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-if="showIframeFields">
|
||||
<div class="col-span-1 md:col-span-2 space-y-2">
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.iframeUrl') }}</label>
|
||||
@@ -372,7 +341,7 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div v-if="!isInternalExecutor" class="col-span-1 md:col-span-2 space-y-2">
|
||||
<div class="col-span-1 md:col-span-2 space-y-2">
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.description') }}</label>
|
||||
<input
|
||||
v-model="form.description"
|
||||
@@ -382,7 +351,7 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="!isInternalExecutor" class="col-span-1 md:col-span-2 space-y-2">
|
||||
<div class="col-span-1 md:col-span-2 space-y-2">
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.welcomeMessage') }}</label>
|
||||
<textarea
|
||||
v-model="form.welcome_message"
|
||||
@@ -392,7 +361,7 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="!isInternalExecutor" class="col-span-1 md:col-span-2 rounded-2xl border border-default bg-surface-soft/40 p-4">
|
||||
<div class="col-span-1 md:col-span-2 rounded-2xl border border-default bg-surface-soft/40 p-4">
|
||||
<div class="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
|
||||
<div>
|
||||
<div class="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-muted">
|
||||
@@ -476,7 +445,7 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="showIntentFastPathSection && !isInternalExecutor"
|
||||
v-if="showIntentFastPathSection"
|
||||
class="col-span-1 md:col-span-2 rounded-2xl border border-default bg-surface-soft/40 p-4"
|
||||
>
|
||||
<div class="mb-4">
|
||||
@@ -590,12 +559,11 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
</div>
|
||||
|
||||
<AgentCapabilitiesConfig
|
||||
v-if="!isInternalExecutor"
|
||||
:form="form"
|
||||
:catalog-entry="currentCatalogEntry"
|
||||
/>
|
||||
|
||||
<div v-if="!isInternalExecutor" class="col-span-1 md:col-span-2 space-y-3">
|
||||
<div class="col-span-1 md:col-span-2 space-y-3">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">常见问题</label>
|
||||
<button
|
||||
@@ -655,7 +623,7 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!isInternalExecutor" class="col-span-1 md:col-span-2 rounded-2xl border border-default bg-surface-soft/40 p-4">
|
||||
<div class="col-span-1 md:col-span-2 rounded-2xl border border-default bg-surface-soft/40 p-4">
|
||||
<div class="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
|
||||
<div>
|
||||
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ t('admin.agent.training.title') }}</div>
|
||||
|
||||
@@ -310,13 +310,7 @@ export function useAgentsAdmin() {
|
||||
|
||||
const loadAgents = async (): Promise<void> => {
|
||||
try {
|
||||
const [applications, executors] = await Promise.all([
|
||||
listAdminAgents('applications'),
|
||||
listAdminAgents('executors'),
|
||||
]);
|
||||
const byId = new Map<number, AgentRow>();
|
||||
[...applications, ...executors].forEach((agent) => byId.set(Number(agent.id), agent));
|
||||
agents.value = [...byId.values()].sort((a, b) => Number(a.id) - Number(b.id));
|
||||
agents.value = await listAdminAgents();
|
||||
} catch (e) {
|
||||
console.error('Error loading agents:', e);
|
||||
agents.value = [];
|
||||
@@ -370,18 +364,10 @@ export function useAgentsAdmin() {
|
||||
isLoading.value = false;
|
||||
};
|
||||
|
||||
const resetForm = (mode: 'user_agent' | 'internal_executor' = 'user_agent'): void => {
|
||||
const resetForm = (): void => {
|
||||
selectedAgentId.value = null;
|
||||
form.value = createEmptyAgentForm(defaultCapabilities());
|
||||
applyCatalogDefaultsToForm(form.value, typeCatalog.value[0]);
|
||||
if (mode === 'internal_executor') {
|
||||
form.value.exposure_mode = 'internal';
|
||||
form.value.runtime_provider = 'dify';
|
||||
form.value.dify_app_type = 'workflow';
|
||||
form.value.conversation_mode = 'task_chat';
|
||||
form.value.welcome_message = '';
|
||||
form.value.suggested_questions = [];
|
||||
}
|
||||
trainingExamPdfGuides.value = [];
|
||||
isEditing.value = false;
|
||||
};
|
||||
@@ -403,10 +389,6 @@ export function useAgentsAdmin() {
|
||||
}
|
||||
isEditing.value = true;
|
||||
void loadTrainingExamPdfGuides(agent.id);
|
||||
const governance = asRecord(extra.order_extraction_governance);
|
||||
form.value.executor_provider_max_concurrency = Number(governance.provider_max_concurrency || 4);
|
||||
form.value.executor_circuit_failure_threshold = Number(governance.circuit_failure_threshold || 5);
|
||||
form.value.executor_circuit_cooldown_seconds = Number(governance.circuit_cooldown_seconds || 60);
|
||||
};
|
||||
|
||||
const openDeleteConfirm = (
|
||||
@@ -507,15 +489,6 @@ export function useAgentsAdmin() {
|
||||
trainingExtraPatch: {},
|
||||
typeCatalog: typeCatalog.value,
|
||||
});
|
||||
registryPayload.exposure_mode = form.value.exposure_mode;
|
||||
if (form.value.exposure_mode === 'internal') {
|
||||
extra_config.order_extraction_governance = {
|
||||
provider_max_concurrency: form.value.executor_provider_max_concurrency,
|
||||
circuit_failure_threshold: form.value.executor_circuit_failure_threshold,
|
||||
circuit_cooldown_seconds: form.value.executor_circuit_cooldown_seconds,
|
||||
};
|
||||
registryPayload.extra_config = extra_config;
|
||||
}
|
||||
|
||||
try {
|
||||
const editingId = isEditing.value ? Number(form.value.id) : null;
|
||||
|
||||
@@ -47,14 +47,6 @@ export interface AgentTypeCatalogEntry {
|
||||
progress_contract?: ProgressContract | null;
|
||||
|
||||
handler_config_schema?: Record<string, unknown>;
|
||||
required_runtime_capabilities?: Record<string, {
|
||||
label?: string;
|
||||
required?: boolean;
|
||||
allowed_runtime_providers?: string[];
|
||||
allowed_dify_app_types?: string[];
|
||||
allowed_exposure_modes?: string[];
|
||||
allowed_effective_roles?: string[];
|
||||
}>;
|
||||
|
||||
}
|
||||
|
||||
@@ -394,8 +386,6 @@ export function mapAgentRowToForm(
|
||||
conversation_mode: agent.conversation_mode || 'chat',
|
||||
|
||||
dify_app_type: agent.dify_app_type === 'workflow' ? 'workflow' : 'chatflow',
|
||||
exposure_mode: agent.exposure_mode === 'internal' ? 'internal' : 'workspace',
|
||||
effective_role: agent.effective_role === 'internal_executor' ? 'internal_executor' : 'user_agent',
|
||||
|
||||
api_base_url: agent.api_base_url || '',
|
||||
|
||||
@@ -543,7 +533,6 @@ export function buildAgentRegistryPayload(
|
||||
conversation_mode: form.conversation_mode,
|
||||
|
||||
dify_app_type: form.dify_app_type,
|
||||
exposure_mode: form.exposure_mode,
|
||||
|
||||
dify_app_id: form.dify_app_id,
|
||||
|
||||
|
||||
@@ -95,7 +95,7 @@ export function usePermissionsAdmin() {
|
||||
|
||||
const loadAgents = async (): Promise<void> => {
|
||||
try {
|
||||
agents.value = await listAdminAgents('applications');
|
||||
agents.value = await listAdminAgents();
|
||||
} catch (e) {
|
||||
console.error('Failed to load agents', e);
|
||||
agents.value = [];
|
||||
|
||||
@@ -31,7 +31,7 @@ const uploadError = ref('');
|
||||
|
||||
const fetchAgents = async () => {
|
||||
try {
|
||||
agents.value = await listAdminAgents('applications');
|
||||
agents.value = await listAdminAgents();
|
||||
if (agents.value.length > 0) {
|
||||
selectedAgentId.value = agents.value[0].id;
|
||||
await fetchGuides();
|
||||
|
||||
@@ -65,7 +65,7 @@ export function useHotFaqCandidates() {
|
||||
|
||||
const loadAgents = async (): Promise<void> => {
|
||||
try {
|
||||
agents.value = await listAdminAgents('applications');
|
||||
agents.value = await listAdminAgents();
|
||||
} catch {
|
||||
agents.value = [];
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ export function useQuestionsAdmin() {
|
||||
|
||||
const loadAgents = async (): Promise<void> => {
|
||||
try {
|
||||
agents.value = await listAdminAgents('applications');
|
||||
agents.value = await listAdminAgents();
|
||||
} catch (e) {
|
||||
console.error('Failed to load agents', e);
|
||||
agents.value = [];
|
||||
|
||||
+38
-4
@@ -27,6 +27,8 @@ const error = ref('');
|
||||
|
||||
const formatTime = (value?: string | null) => value ? new Date(value).toLocaleString() : '-';
|
||||
const formatDuration = (value?: number | null) => value == null ? '-' : `${(value / 1000).toFixed(value < 10000 ? 1 : 0)} s`;
|
||||
const translateAutoFreezeReason = (code: string) =>
|
||||
t(`admin.shippingOrderExtractionRuns.autoFreezeReasonCodes.${code}`, code);
|
||||
|
||||
/** 加载安全摘要;服务端已完成管理员鉴权、审计及敏感字段剔除。 */
|
||||
const load = async () => {
|
||||
@@ -82,7 +84,7 @@ onMounted(() => { void load(); });
|
||||
{{ t('admin.shippingOrderExtractionRuns.status') }}
|
||||
<select v-model="status" class="rounded-md border border-default bg-surface px-2 py-1.5" @change="applyStatus">
|
||||
<option value="">{{ t('admin.shippingOrderExtractionRuns.allStatuses') }}</option>
|
||||
<option v-for="value in ['queued', 'running', 'result_persisted', 'completed', 'needs_review', 'failed', 'cancelled']" :key="value" :value="value">
|
||||
<option v-for="value in ['queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled']" :key="value" :value="value">
|
||||
{{ t(`admin.shippingOrderExtractionRuns.statuses.${value}`) }}
|
||||
</option>
|
||||
</select>
|
||||
@@ -98,7 +100,7 @@ onMounted(() => { void load(); });
|
||||
</tr></thead>
|
||||
<tbody><tr v-if="loading"><td colspan="7" class="px-4 py-8 text-center text-muted">{{ t('admin.shippingOrderExtractionRuns.loading') }}</td></tr>
|
||||
<tr v-else-if="!rows.length"><td colspan="7" class="px-4 py-8 text-center text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</td></tr>
|
||||
<tr v-for="row in rows" :key="row.run_no" class="border-b border-default last:border-0"><td class="px-4 py-3 font-mono text-xs">{{ row.run_no }}</td><td class="px-4 py-3">{{ t(`admin.shippingOrderExtractionRuns.statuses.${row.status}`) }}</td><td class="px-4 py-3">{{ row.current_stage_code || '-' }}</td><td class="px-4 py-3">{{ row.attempt_count }}</td><td class="px-4 py-3">{{ formatTime(row.created_at) }}</td><td class="px-4 py-3">{{ formatDuration(row.durations_ms.total) }}</td><td class="px-4 py-3"><button type="button" class="text-brand-600 hover:underline" @click="openDetail(row.run_no)">{{ t('admin.shippingOrderExtractionRuns.viewDetail') }}</button></td></tr>
|
||||
<tr v-for="row in rows" :key="row.run_no" class="border-b border-default last:border-0"><td class="px-4 py-3 font-mono text-xs">{{ row.run_no }}</td><td class="px-4 py-3">{{ t(`admin.shippingOrderExtractionRuns.statuses.${row.status}`) }}</td><td class="px-4 py-3">{{ row.current_event_code || '-' }}</td><td class="px-4 py-3">{{ row.attempt_count }}</td><td class="px-4 py-3">{{ formatTime(row.created_at) }}</td><td class="px-4 py-3">{{ formatDuration(row.durations_ms.total) }}</td><td class="px-4 py-3"><button type="button" class="text-brand-600 hover:underline" @click="openDetail(row.run_no)">{{ t('admin.shippingOrderExtractionRuns.viewDetail') }}</button></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -108,12 +110,44 @@ onMounted(() => { void load(); });
|
||||
<aside class="h-full w-full max-w-2xl overflow-y-auto bg-surface p-6 shadow-2xl">
|
||||
<div class="flex items-center justify-between"><h2 class="text-lg font-bold">{{ t('admin.shippingOrderExtractionRuns.detailTitle') }}</h2><button type="button" class="text-secondary" @click="detail = null">{{ t('admin.close') }}</button></div>
|
||||
<p v-if="detailLoading" class="mt-6 text-muted">{{ t('admin.shippingOrderExtractionRuns.loading') }}</p>
|
||||
<template v-else-if="detail"><dl class="mt-5 grid grid-cols-2 gap-3 text-sm"><dt>{{ t('admin.shippingOrderExtractionRuns.runNo') }}</dt><dd class="font-mono text-xs">{{ detail.run.run_no }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.workflowRunId') }}</dt><dd class="font-mono text-xs">{{ detail.run.workflow_run_id || '-' }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.errorCode') }}</dt><dd>{{ detail.run.error_code || '-' }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.totalDuration') }}</dt><dd>{{ formatDuration(detail.run.durations_ms.total) }}</dd></dl>
|
||||
<template v-else-if="detail"><dl class="mt-5 grid grid-cols-2 gap-3 text-sm"><dt>{{ t('admin.shippingOrderExtractionRuns.runNo') }}</dt><dd class="font-mono text-xs">{{ detail.run.run_no }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.currentEvent') }}</dt><dd class="font-mono text-xs">{{ detail.run.current_event_code || '-' }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.candidateMaterializedAt') }}</dt><dd>{{ formatTime(detail.run.candidate_materialized_at) }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.errorCode') }}</dt><dd>{{ detail.run.error_code || '-' }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.totalDuration') }}</dt><dd>{{ formatDuration(detail.run.durations_ms.total) }}</dd></dl>
|
||||
<section class="mt-6 rounded-lg border border-default p-4 text-sm">
|
||||
<div class="font-semibold">{{ t('admin.shippingOrderExtractionRuns.autoFreezePolicy') }}</div>
|
||||
<dl class="mt-3 grid grid-cols-2 gap-x-3 gap-y-2">
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.autoFreezeEnabled') }}</dt>
|
||||
<dd>{{ t(detail.run.auto_freeze_policy.enabled ? 'admin.shippingOrderExtractionRuns.yes' : 'admin.shippingOrderExtractionRuns.no') }}</dd>
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.autoFreezeMode') }}</dt>
|
||||
<dd>{{ t(`admin.shippingOrderExtractionRuns.autoFreezeModes.${detail.run.auto_freeze_policy.mode}`) }}</dd>
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.autoFreezeQualificationStatus') }}</dt>
|
||||
<dd>{{ detail.run.auto_freeze_policy.qualification_status ? t(`admin.shippingOrderExtractionRuns.autoFreezeQualificationStatuses.${detail.run.auto_freeze_policy.qualification_status}`) : '-' }}</dd>
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.autoFreezeProfile') }}</dt>
|
||||
<dd>{{ detail.run.auto_freeze_policy.selected_profile_code || '-' }}</dd>
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.autoFreezeCustomerScopeStatus') }}</dt>
|
||||
<dd>{{ detail.run.auto_freeze_policy.customer_scope_status ? t(`admin.shippingOrderExtractionRuns.autoFreezeCustomerScopeStatuses.${detail.run.auto_freeze_policy.customer_scope_status}`) : '-' }}</dd>
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.autoFreezeBusinessScenarioStatus') }}</dt>
|
||||
<dd>{{ detail.run.auto_freeze_policy.business_scenario_status ? t(`admin.shippingOrderExtractionRuns.autoFreezeBusinessScenarioStatuses.${detail.run.auto_freeze_policy.business_scenario_status}`) : '-' }}</dd>
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.autoFreezeCustomerConfirmation') }}</dt>
|
||||
<dd>{{ t(detail.run.auto_freeze_policy.customer_confirmation_required ? 'admin.shippingOrderExtractionRuns.yes' : 'admin.shippingOrderExtractionRuns.no') }}</dd>
|
||||
</dl>
|
||||
<div class="mt-3">
|
||||
<div class="text-xs font-medium text-secondary">{{ t('admin.shippingOrderExtractionRuns.autoFreezeBlockingReasons') }}</div>
|
||||
<div v-if="detail.run.auto_freeze_policy.blocking_reason_codes.length" class="mt-2 flex flex-wrap gap-2">
|
||||
<span
|
||||
v-for="code in detail.run.auto_freeze_policy.blocking_reason_codes"
|
||||
:key="code"
|
||||
class="rounded-full border border-default px-2 py-1 text-xs text-secondary"
|
||||
>
|
||||
{{ translateAutoFreezeReason(code) }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-else class="mt-2 text-xs text-muted">{{ t('admin.shippingOrderExtractionRuns.autoFreezeNoBlockingReasons') }}</div>
|
||||
</div>
|
||||
</section>
|
||||
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.jobAttempts') }}</h3><div class="mt-2 space-y-2"><div v-for="job in detail.job_attempts" :key="job.job_id" class="rounded-lg border border-default p-3 text-sm"><b>#{{ job.job_id }}</b> · {{ job.status }} · {{ t('admin.shippingOrderExtractionRuns.attempts') }} {{ job.attempts }}/{{ job.max_attempts }} · {{ formatDuration(job.duration_ms) }}</div><p v-if="!detail.job_attempts.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p></div>
|
||||
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.units') }}</h3><div class="mt-2 space-y-2"><div v-for="unit in detail.units" :key="unit.unit_id" class="rounded-lg border border-default p-3 text-sm"><b>#{{ unit.position + 1 }} {{ unit.unit_type }}</b> · {{ unit.status }} · {{ t('admin.shippingOrderExtractionRuns.attempts') }} {{ unit.attempt_count }} · {{ formatDuration(unit.duration_ms) }}<span v-if="unit.error_code" class="ml-2 font-mono text-xs text-danger">{{ unit.error_code }}</span>
|
||||
<section v-for="route in unit.route_decisions" :key="`${unit.unit_id}:${route.attempt_no}`" class="mt-3 rounded border border-default bg-slate-50 p-3 text-xs dark:bg-slate-900/40"><h4 class="font-semibold text-primary">{{ t('admin.shippingOrderExtractionRuns.routeDecision') }} #{{ route.attempt_no }}</h4><dl class="mt-2 grid grid-cols-2 gap-x-3 gap-y-1"><dt>{{ t('admin.shippingOrderExtractionRuns.executionMode') }}</dt><dd>{{ t(`admin.shippingOrderExtractionRuns.executionModes.${route.execution_mode}`) }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.matchStatus') }}</dt><dd>{{ t(`admin.shippingOrderExtractionRuns.matchStatuses.${route.match_status}`) }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.selectedProfile') }}</dt><dd>{{ route.selected_profile_code ? `${route.selected_profile_code} V${route.selected_profile_version}` : '-' }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.autoCreateApproved') }}</dt><dd>{{ route.auto_create_approved == null ? '-' : t(route.auto_create_approved ? 'admin.shippingOrderExtractionRuns.yes' : 'admin.shippingOrderExtractionRuns.no') }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.fallbackReasons') }}</dt><dd>{{ route.fallback_reason_codes.length ? route.fallback_reason_codes.map(code => t(`admin.shippingOrderExtractionRuns.reasonCodes.${code}`)).join(';') : '-' }}</dd></dl><div v-if="route.candidates.length" class="mt-3"><p class="font-medium">{{ t('admin.shippingOrderExtractionRuns.candidates') }}</p><div v-for="candidate in route.candidates" :key="`${candidate.profile_code}:${candidate.version}`" class="mt-1 flex flex-wrap gap-x-2 text-muted"><span>{{ candidate.profile_code }} V{{ candidate.version }}</span><span>{{ candidate.score.toFixed(2) }}</span><span>{{ candidate.hard_match ? t('admin.shippingOrderExtractionRuns.hardMatch') : t('admin.shippingOrderExtractionRuns.hardMismatch') }}</span><span v-if="candidate.missing_required_anchor_ids?.length">{{ t('admin.shippingOrderExtractionRuns.missingAnchors', { ids: candidate.missing_required_anchor_ids.join(', ') }) }}</span></div></div></section>
|
||||
</div><p v-if="!detail.units.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p></div>
|
||||
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.lifecycle') }}</h3><div class="mt-2 space-y-2"><div v-for="event in detail.progress_events" :key="`${event.node_execution_id}:${event.event_type}:${event.occurred_at}`" class="rounded-lg border border-default p-3 text-sm"><b>{{ event.stage_code || event.event_type }}</b><span class="ml-2 text-secondary">{{ event.status || '-' }}</span><span class="ml-2 font-mono text-xs text-muted">{{ event.node_type || '-' }}</span><time class="ml-2 text-xs text-muted">{{ formatTime(event.occurred_at) }}</time></div><p v-if="!detail.progress_events.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p></div>
|
||||
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.lifecycle') }}</h3><div class="mt-2 space-y-2"><div v-for="event in detail.progress_events" :key="`${event.sequence_no}:${event.event_code}`" class="rounded-lg border border-default p-3 text-sm"><b>{{ event.event_code }}</b><span class="ml-2 text-secondary">{{ event.status || '-' }}</span><span class="ml-2 font-mono text-xs text-muted">{{ t(`admin.shippingOrderExtractionRuns.visibilities.${event.visibility}`) }}</span><span v-if="event.reason_code" class="ml-2 font-mono text-xs text-muted">{{ event.reason_code }}</span><time class="ml-2 text-xs text-muted">{{ formatTime(event.occurred_at) }}</time></div><p v-if="!detail.progress_events.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p></div>
|
||||
</template>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
@@ -128,7 +128,7 @@ export function useUsersAdmin() {
|
||||
|
||||
const loadAgents = async (): Promise<void> => {
|
||||
try {
|
||||
agents.value = await listAdminAgents('applications');
|
||||
agents.value = await listAdminAgents();
|
||||
} catch (e) {
|
||||
console.error('Error loading agents:', e);
|
||||
agents.value = [];
|
||||
|
||||
@@ -7,7 +7,6 @@ import type { TrainingQuestionType } from '@/features/chat/training/training.typ
|
||||
|
||||
export type AgentRuntimeProvider = 'dify' | 'builtin' | 'hybrid' | 'iframe';
|
||||
export type AgentConversationMode = 'chat' | 'task_chat' | 'embedded';
|
||||
export type AgentExposureMode = 'workspace' | 'internal';
|
||||
|
||||
export interface AgentCapabilities {
|
||||
streaming: boolean;
|
||||
@@ -33,8 +32,6 @@ export interface AgentRow {
|
||||
runtime_provider?: AgentRuntimeProvider;
|
||||
conversation_mode?: AgentConversationMode;
|
||||
dify_app_type?: 'chatflow' | 'workflow';
|
||||
exposure_mode?: AgentExposureMode;
|
||||
effective_role?: 'user_agent' | 'internal_executor';
|
||||
api_base_url?: string;
|
||||
iframe_url?: string;
|
||||
welcome_message?: string | null;
|
||||
@@ -104,8 +101,6 @@ export interface AgentFormState {
|
||||
runtime_provider: AgentRuntimeProvider;
|
||||
conversation_mode: AgentConversationMode;
|
||||
dify_app_type: 'chatflow' | 'workflow';
|
||||
exposure_mode: AgentExposureMode;
|
||||
effective_role?: 'user_agent' | 'internal_executor';
|
||||
api_base_url: string;
|
||||
iframe_url: string;
|
||||
welcome_message: string;
|
||||
@@ -132,9 +127,6 @@ export interface AgentFormState {
|
||||
training_hr_chat_questions_text: string;
|
||||
training_question_bank: AgentTrainingQuestionFormItem[];
|
||||
directory_member_ids: number[];
|
||||
executor_provider_max_concurrency: number;
|
||||
executor_circuit_failure_threshold: number;
|
||||
executor_circuit_cooldown_seconds: number;
|
||||
}
|
||||
|
||||
export const createEmptyTrainingQuestionForm = (): AgentTrainingQuestionFormItem => ({
|
||||
@@ -158,7 +150,6 @@ export const createEmptyAgentForm = (
|
||||
runtime_provider: 'dify',
|
||||
conversation_mode: 'chat',
|
||||
dify_app_type: 'chatflow',
|
||||
exposure_mode: 'workspace',
|
||||
api_base_url: '',
|
||||
iframe_url: '',
|
||||
welcome_message: '',
|
||||
@@ -194,31 +185,4 @@ export const createEmptyAgentForm = (
|
||||
training_hr_chat_questions_text: '',
|
||||
training_question_bank: [],
|
||||
directory_member_ids: [],
|
||||
executor_provider_max_concurrency: 4,
|
||||
executor_circuit_failure_threshold: 5,
|
||||
executor_circuit_cooldown_seconds: 60,
|
||||
});
|
||||
|
||||
export interface OrderExtractionQualityBatchOption {
|
||||
id: number;
|
||||
batch_no: string;
|
||||
approved_at: string | null;
|
||||
metrics: {
|
||||
agreed_sample_count: number;
|
||||
precision: number;
|
||||
recall: number;
|
||||
eligible: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface AgentRuntimeBindingRow {
|
||||
id: number;
|
||||
owner_agent_id: number;
|
||||
capability_code: string;
|
||||
provider_agent_id: number;
|
||||
enabled: boolean;
|
||||
config: {
|
||||
timeout_seconds?: number;
|
||||
max_attempts?: number;
|
||||
};
|
||||
}
|
||||
@@ -65,6 +65,12 @@ export interface ShippingOrderDocumentProfile {
|
||||
qualification_id: number | null;
|
||||
parser_version?: string;
|
||||
quality_suite_id?: number | null;
|
||||
customer_ids?: number[];
|
||||
business_scenarios?: string[];
|
||||
customer_scope_configured?: boolean;
|
||||
business_scenario_scope_configured?: boolean;
|
||||
requires_customer_confirmation?: boolean;
|
||||
scope_updated_at?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ export const hydrateShippingOrderExtractionState = (message: ChatMessage): ChatM
|
||||
const state = payload.shipping_order_extraction_state;
|
||||
if (!state || typeof state !== 'object') return message;
|
||||
const status = String((state as Record<string, unknown>).status || '');
|
||||
if (!['extracting', 'completed', 'partially_completed', 'failed'].includes(status)) return message;
|
||||
if (!['queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'].includes(status)) return message;
|
||||
message.shipping_order_extraction_state = state as ShippingOrderExtractionState;
|
||||
return message;
|
||||
};
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
ShippingBatchUiState,
|
||||
ShippingConversationWorkspace,
|
||||
ShippingDecisionResponse,
|
||||
ShippingOrderExtractionDocumentsResponse,
|
||||
ShippingNoticeHeader,
|
||||
ShippingNoticeLine,
|
||||
ShippingNoticeUploadResponse,
|
||||
@@ -160,6 +161,7 @@ export const createWorkspaceShippingOrderExtractionRun = (payload: {
|
||||
agent_id: number;
|
||||
conversation_id?: string | null;
|
||||
intake_nos: string[];
|
||||
upload_batch_id: string;
|
||||
}) => requestJson<ShippingOrderExtractionRunCreateResponse>(
|
||||
'/api/workspace/shipping-notice/order-extraction-runs',
|
||||
jsonPost(payload),
|
||||
@@ -192,6 +194,12 @@ export const reparseWorkspaceShippingOrderExtractionRun = (
|
||||
jsonPost(payload),
|
||||
);
|
||||
|
||||
/** 获取当前订单抽取 Run 的按 PDF 归并详情。 */
|
||||
export const listWorkspaceShippingOrderExtractionDocuments = (runNo: string) =>
|
||||
requestJson<ShippingOrderExtractionDocumentsResponse>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/documents`,
|
||||
);
|
||||
|
||||
/** 用户展开状态卡时获取脱敏进度时间线;不返回节点或Workflow诊断数据。 */
|
||||
export const listWorkspaceShippingOrderExtractionProgressEvents = (runNo: string) =>
|
||||
requestJson<{ items: ShippingOrderExtractionProgressEvent[] }>(
|
||||
@@ -686,12 +694,14 @@ export const SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice';
|
||||
export const createShippingNoticeIntake = (
|
||||
assetNo: string,
|
||||
conversationId?: string | null,
|
||||
uploadBatchId?: string,
|
||||
) => requestJson<ShippingNoticeIntakeResponse>('/api/workspace/shipping-notice/intakes', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
asset_no: assetNo,
|
||||
conversation_id: conversationId || undefined,
|
||||
upload_batch_id: uploadBatchId || undefined,
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -106,24 +106,47 @@ const attachmentUrlInput = ref('');
|
||||
|
||||
/**
|
||||
* 汇总 EML 附件解析进度,供输入栏徽标展示。
|
||||
* 核心逻辑:failed/empty/skipped/超限/文本预算耗尽计为问题;duplicate 单独提示,不记为失败。
|
||||
* 核心逻辑:阶段 1 仅展示快览结果;优先说明发现了多少附件,技术失败/目录不完整再退化为问题提示。
|
||||
*/
|
||||
function shippingNoticeAttachmentHint(attachment: ShippingNoticePendingAttachment): string {
|
||||
const summary = attachment.parseSummary;
|
||||
const total = Number(summary?.attachment_count || 0);
|
||||
const rows = summary?.attachments || [];
|
||||
// 兼容旧摘要:早期快览未标记签名图,按内嵌标记、目录原因和图片 MIME 一并排除。
|
||||
const businessRows = rows.filter((item) => {
|
||||
const mimeType = String(item.mime_type || '').toLowerCase();
|
||||
const catalogReason = String(item.catalog_reason || '').toLowerCase();
|
||||
return !item.is_inline_resource
|
||||
&& !mimeType.startsWith('image/')
|
||||
&& catalogReason !== 'signature_or_logo'
|
||||
&& catalogReason !== 'inline_resource';
|
||||
});
|
||||
const inlineCount = rows.length - businessRows.length;
|
||||
const total = Math.max(0, Number(summary?.attachment_count || 0) - inlineCount);
|
||||
const warnings = summary?.warnings || [];
|
||||
const hasBlockingWarning = warnings.some((w) => isBlockingWarning(String(w || '')));
|
||||
if (!total && !hasBlockingWarning && !rows.length) return '';
|
||||
if (!total && !hasBlockingWarning && !businessRows.length) return '';
|
||||
|
||||
const effectiveTotal = total || rows.length;
|
||||
const ok = rows.filter((item) => item.parse_status === 'parsed').length;
|
||||
const problematic = rows.filter((item) =>
|
||||
const effectiveTotal = total || businessRows.length;
|
||||
const ok = Number(summary?.ready_attachment_count || businessRows.filter((item) => item.ready_for_extraction).length);
|
||||
const problematic = businessRows.filter((item) =>
|
||||
['failed', 'empty', 'skipped'].includes(String(item.parse_status || '')),
|
||||
).length;
|
||||
const duplicates = rows.filter((item) => item.parse_status === 'duplicate').length;
|
||||
const overflow = Math.max(0, effectiveTotal - rows.length);
|
||||
const issues = problematic + overflow + (hasBlockingWarning && problematic === 0 && overflow === 0 ? 1 : 0);
|
||||
const duplicates = Number(
|
||||
summary?.duplicate_attachment_count
|
||||
|| businessRows.filter((item) => item.parse_status === 'duplicate').length,
|
||||
);
|
||||
const overflow = Math.max(0, effectiveTotal - businessRows.length);
|
||||
const previewStatus = String(summary?.preview_status || '').trim().toLowerCase();
|
||||
const issues = problematic
|
||||
+ overflow
|
||||
+ (hasBlockingWarning && problematic === 0 && overflow === 0 ? 1 : 0)
|
||||
+ (
|
||||
(summary?.technical_failure || previewStatus === 'technical_failed' || previewStatus === 'directory_incomplete')
|
||||
&& problematic === 0
|
||||
&& overflow === 0
|
||||
? 1
|
||||
: 0
|
||||
);
|
||||
|
||||
if (issues > 0) {
|
||||
return t('chat.shippingNoticeAttachmentHintPartial', {
|
||||
@@ -132,14 +155,11 @@ function shippingNoticeAttachmentHint(attachment: ShippingNoticePendingAttachmen
|
||||
failed: issues,
|
||||
});
|
||||
}
|
||||
if (attachment.layoutStatus === 'processing') {
|
||||
return t('chat.shippingNoticeAttachmentHintLayoutProcessing', { ok, total: effectiveTotal });
|
||||
}
|
||||
if (duplicates > 0) {
|
||||
return t('chat.shippingNoticeAttachmentHintWithDup', { ok, total: effectiveTotal, duplicates });
|
||||
return t('chat.shippingNoticeAttachmentHintDiscoveredWithDup', { total: effectiveTotal, duplicates });
|
||||
}
|
||||
if (!effectiveTotal) return '';
|
||||
return t('chat.shippingNoticeAttachmentHint', { ok, total: effectiveTotal });
|
||||
return t('chat.shippingNoticeAttachmentHintDiscovered', { total: effectiveTotal });
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,20 +5,16 @@
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;用户附件与文字共用同一气泡,助手正文与特殊交互委托页面 handlers。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
import {
|
||||
Check,
|
||||
CircleCheck,
|
||||
CircleX,
|
||||
Copy,
|
||||
Download,
|
||||
Edit2,
|
||||
Eye,
|
||||
LayoutGrid,
|
||||
LoaderCircle,
|
||||
MessageSquareText,
|
||||
RotateCw,
|
||||
TriangleAlert,
|
||||
X,
|
||||
} from 'lucide-vue-next';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
@@ -33,14 +29,13 @@ import TrainingExamQuestionMessage, { type TrainingHandlers } from './TrainingEx
|
||||
import TrainingVideoMessage from './TrainingVideoMessage.vue';
|
||||
import TrainingSummaryMessage from './TrainingSummaryMessage.vue';
|
||||
import TrainingResultCard from './TrainingResultCard.vue';
|
||||
import ShippingOrderExtractionCard from '../shipping/ShippingOrderExtractionCard.vue';
|
||||
import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../../types/chat.types';
|
||||
import type { ShippingMatchResultPayload } from '../../types/shipping.types';
|
||||
import type { ShippingNoticePendingAttachment } from '../../types/shipping.types';
|
||||
import type { ShippingOrderExtractionReviewAttachment } from '../../types/chat.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;
|
||||
@@ -142,12 +137,7 @@ const showShippingActionsPanel = computed(() =>
|
||||
);
|
||||
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 reviewAttachmentsSection = ref<HTMLElement | null>(null);
|
||||
const shippingOrderExtractionRunNo = computed(() => {
|
||||
const payload = message.payload && typeof message.payload === 'object'
|
||||
? message.payload as Record<string, unknown>
|
||||
@@ -211,89 +201,11 @@ const retryShippingOrderExtraction = async () => {
|
||||
retryingOrderExtraction.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const shippingOrderExtractionTitleKey = computed(() => {
|
||||
switch (shippingOrderExtractionState.value?.status) {
|
||||
case 'completed': return 'chat.shippingOrderExtractionCompleted';
|
||||
case 'partially_completed': return 'chat.shippingOrderExtractionPartiallyCompleted';
|
||||
case 'failed': return 'chat.shippingOrderExtractionFailed';
|
||||
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 enterOrderExtractionManualReview = async () => {
|
||||
if (!shippingOrderExtractionReviewAttachments.value.length) return;
|
||||
await nextTick();
|
||||
reviewAttachmentsSection.value?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
};
|
||||
|
||||
/** 将服务端脱敏事件时间格式化为用户本地时间;无效值不伪造时间。 */
|
||||
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();
|
||||
return !!stateMessage && stateMessage !== assistantContent && !assistantContent.includes(stateMessage);
|
||||
});
|
||||
const isLastMessage = computed(() => index === messageCount - 1 || (message.role === 'assistant' && isLatestAssistantMessage));
|
||||
const isCopied = computed(() => copiedIndex === index);
|
||||
const renderedMarkdown = computed(() => (
|
||||
@@ -816,128 +728,19 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
<div v-if="hasUserContent" class="whitespace-pre-wrap px-2.5 py-1">{{ message.content }}</div>
|
||||
</template>
|
||||
<div v-else>
|
||||
<div
|
||||
<ShippingOrderExtractionCard
|
||||
v-if="shippingOrderExtractionState"
|
||||
class="mb-3 flex min-h-[60px] items-start gap-3 rounded-lg border px-3.5 py-3"
|
||||
:class="{
|
||||
'border-sky-200 bg-sky-50/80 text-sky-900 dark:border-sky-800 dark:bg-sky-950/35 dark:text-sky-100': shippingOrderExtractionState.status === 'extracting',
|
||||
'border-emerald-200 bg-emerald-50/80 text-emerald-900 dark:border-emerald-800 dark:bg-emerald-950/35 dark:text-emerald-100': shippingOrderExtractionState.status === 'completed',
|
||||
'border-amber-200 bg-amber-50/80 text-amber-950 dark:border-amber-800 dark:bg-amber-950/35 dark:text-amber-100': shippingOrderExtractionState.status === 'partially_completed',
|
||||
'border-rose-200 bg-rose-50/80 text-rose-900 dark:border-rose-800 dark:bg-rose-950/35 dark:text-rose-100': shippingOrderExtractionState.status === 'failed',
|
||||
}"
|
||||
:state="shippingOrderExtractionState"
|
||||
:run-no="shippingOrderExtractionRunNo"
|
||||
:has-review-attachments="shippingOrderExtractionReviewAttachments.length > 0"
|
||||
@retry="retryShippingOrderExtraction"
|
||||
@enter-manual-review="enterOrderExtractionManualReview"
|
||||
/>
|
||||
<div
|
||||
v-if="shippingOrderExtractionReviewAttachments.length"
|
||||
ref="reviewAttachmentsSection"
|
||||
class="mb-3 space-y-2"
|
||||
>
|
||||
<LoaderCircle
|
||||
v-if="shippingOrderExtractionState.status === 'extracting'"
|
||||
class="mt-0.5 h-5 w-5 shrink-0 animate-spin"
|
||||
/>
|
||||
<CircleCheck
|
||||
v-else-if="shippingOrderExtractionState.status === 'completed'"
|
||||
class="mt-0.5 h-5 w-5 shrink-0"
|
||||
/>
|
||||
<TriangleAlert
|
||||
v-else-if="shippingOrderExtractionState.status === 'partially_completed'"
|
||||
class="mt-0.5 h-5 w-5 shrink-0"
|
||||
/>
|
||||
<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"
|
||||
role="progressbar"
|
||||
:aria-label="$t(shippingOrderExtractionTitleKey)"
|
||||
aria-valuemin="0"
|
||||
aria-valuemax="100"
|
||||
:aria-valuenow="shippingOrderExtractionState.terminal ? 100 : undefined"
|
||||
:aria-busy="shippingOrderExtractionState.status === 'extracting'"
|
||||
>
|
||||
<div
|
||||
v-if="shippingOrderExtractionState.status === 'extracting'"
|
||||
class="shipping-order-extraction-indeterminate h-full w-2/5 rounded-full bg-sky-500"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="h-full w-full rounded-full"
|
||||
:class="{
|
||||
'bg-emerald-500': shippingOrderExtractionState.status === 'completed',
|
||||
'bg-amber-500': shippingOrderExtractionState.status === 'partially_completed',
|
||||
'bg-rose-500': shippingOrderExtractionState.status === 'failed',
|
||||
}"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-if="shippingOrderExtractionState.terminal"
|
||||
class="mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs"
|
||||
>
|
||||
<span v-if="shippingOrderExtractionState.created_count > 0">
|
||||
{{ $t('chat.shippingOrderExtractionCreatedCount', { count: shippingOrderExtractionState.created_count }) }}
|
||||
</span>
|
||||
<span v-if="shippingOrderExtractionState.opened_existing_count > 0">
|
||||
{{ $t('chat.shippingOrderExtractionOpenedExistingCount', { count: shippingOrderExtractionState.opened_existing_count }) }}
|
||||
</span>
|
||||
<span v-if="shippingOrderExtractionState.pending_count > 0">
|
||||
{{ $t('chat.shippingOrderExtractionPendingCount', { count: shippingOrderExtractionState.pending_count }) }}
|
||||
</span>
|
||||
<span v-if="shippingOrderExtractionState.non_shipping_count > 0">
|
||||
{{ $t('chat.shippingOrderExtractionIgnoredCount', { count: shippingOrderExtractionState.non_shipping_count }) }}
|
||||
</span>
|
||||
<span v-if="shippingOrderExtractionState.created_with_missing_fields_count > 0">
|
||||
{{ $t('chat.shippingOrderExtractionMissingFieldsCount', { count: shippingOrderExtractionState.created_with_missing_fields_count }) }}
|
||||
</span>
|
||||
</div>
|
||||
<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>
|
||||
<div v-if="shippingOrderExtractionReviewAttachments.length" class="mb-3 space-y-2">
|
||||
<ShippingNoticeCandidateReview
|
||||
v-for="attachment in shippingOrderExtractionReviewAttachments"
|
||||
:key="attachment.intakeNo"
|
||||
@@ -1348,28 +1151,6 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.shipping-order-extraction-indeterminate {
|
||||
animation: shipping-order-extraction-progress 1.25s ease-in-out infinite;
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
@keyframes shipping-order-extraction-progress {
|
||||
from {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
|
||||
to {
|
||||
transform: translateX(250%);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.shipping-order-extraction-indeterminate {
|
||||
animation: none;
|
||||
transform: translateX(75%);
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.chat-markdown) {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderDocumentResultItem.vue
|
||||
* 用途:渲染单个 PDF 的订单抽取结果摘要,供详情抽屉按文档逐项展示。
|
||||
* 依赖:订单抽取文档 DTO、vue-i18n。
|
||||
* 逻辑:只显示用户可理解的业务字段;人工复核入口复用现有候选审核区,不直接暴露内部证据细节。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { CircleCheck, CircleX, FileText, LoaderCircle, TriangleAlert } from 'lucide-vue-next';
|
||||
import type { ShippingOrderExtractionDocumentResult } from '../../types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
document: ShippingOrderExtractionDocumentResult;
|
||||
hasReviewAttachments?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
enterManualReview: [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const statusTone = computed(() => {
|
||||
switch (props.document.status) {
|
||||
case 'candidate_ready':
|
||||
return 'border-emerald-200 bg-emerald-50/70 text-emerald-900 dark:border-emerald-800 dark:bg-emerald-950/25 dark:text-emerald-100';
|
||||
case 'review_required':
|
||||
return 'border-amber-200 bg-amber-50/70 text-amber-950 dark:border-amber-800 dark:bg-amber-950/25 dark:text-amber-100';
|
||||
case 'failed':
|
||||
case 'cancelled':
|
||||
return 'border-rose-200 bg-rose-50/70 text-rose-900 dark:border-rose-800 dark:bg-rose-950/25 dark:text-rose-100';
|
||||
default:
|
||||
return 'border-slate-200 bg-slate-50/70 text-slate-900 dark:border-slate-700 dark:bg-slate-900/40 dark:text-slate-100';
|
||||
}
|
||||
});
|
||||
|
||||
const statusLabel = computed(() => t(`chat.shippingOrderExtractionDocumentStatus.${props.document.status}`));
|
||||
const reasonLabel = computed(() => (
|
||||
props.document.reason_code
|
||||
? t(`chat.shippingOrderExtractionReason.${props.document.reason_code}`)
|
||||
: ''
|
||||
));
|
||||
const emailSupplementLabel = computed(() => {
|
||||
const status = props.document.email_supplement?.status || 'none';
|
||||
const key = `chat.shippingOrderExtractionEmailSupplement.${status}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderExtractionEmailSupplement.none');
|
||||
});
|
||||
const emailSupplementRelations = computed(() => (
|
||||
(props.document.email_supplement?.relation_codes || [])
|
||||
.map((code) => {
|
||||
const key = `chat.shippingOrderExtractionEmailSupplementRelation.${code}`;
|
||||
return te(key) ? t(key) : code;
|
||||
})
|
||||
));
|
||||
const reservationStatusLabel = computed(() => {
|
||||
const key = `chat.shippingOrderExtractionEmailSupplementFieldStatus.${props.document.email_supplement?.reservation_id_status || 'none'}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderExtractionEmailSupplementFieldStatus.none');
|
||||
});
|
||||
const sourceTypeStatusLabel = computed(() => {
|
||||
const key = `chat.shippingOrderExtractionEmailSupplementFieldStatus.${props.document.email_supplement?.source_type_status || 'none'}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderExtractionEmailSupplementFieldStatus.none');
|
||||
});
|
||||
const retryStatusLabel = computed(() => {
|
||||
const status = String(props.document.retry_status || '').trim();
|
||||
const key = `chat.shippingOrderExtractionRetryStatus.${status}`;
|
||||
return status && te(key) ? t(key) : '';
|
||||
});
|
||||
const budgetCostLabel = computed(() => {
|
||||
if (!props.document.budget_cost) return '';
|
||||
return t('chat.shippingOrderExtractionBudgetCost', {
|
||||
attachments: props.document.budget_cost.initial_attachment_budget || 0,
|
||||
concurrency: props.document.budget_cost.initial_concurrency_budget || 0,
|
||||
selected: props.document.budget_cost.selected_in_batch || 0,
|
||||
});
|
||||
});
|
||||
const reviewDetails = computed(() => props.document.review_details || []);
|
||||
const reviewFieldLabel = (fieldCode: string | null | undefined): string => {
|
||||
const key = `chat.shippingOrderExtractionReviewField.${fieldCode || ''}`;
|
||||
return fieldCode && te(key) ? t(key) : (fieldCode || t('chat.shippingOrderExtractionReviewField.unknown'));
|
||||
};
|
||||
|
||||
const canEnterManualReview = computed(() => (
|
||||
props.hasReviewAttachments
|
||||
&& props.document.available_actions.some((action) => action === 'review_candidate' || action === 'manual_review')
|
||||
));
|
||||
const canViewEvidence = computed(() => (
|
||||
props.hasReviewAttachments
|
||||
&& props.document.available_actions.includes('view_evidence')
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="rounded-lg border p-3" :class="statusTone">
|
||||
<div class="flex items-start gap-2">
|
||||
<LoaderCircle
|
||||
v-if="['pending', 'routing', 'matching_profile', 'extracting', 'merging_supplement'].includes(document.status)"
|
||||
class="mt-0.5 h-4 w-4 shrink-0 animate-spin"
|
||||
/>
|
||||
<CircleCheck v-else-if="document.status === 'candidate_ready'" class="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<TriangleAlert v-else-if="document.status === 'review_required'" class="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<CircleX v-else class="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<div class="truncate text-sm font-semibold">{{ document.file_name || t('chat.shippingOrderExtractionUnknownDocument') }}</div>
|
||||
<span class="rounded-full bg-black/10 px-2 py-0.5 text-[11px] dark:bg-white/10">{{ statusLabel }}</span>
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs opacity-85">
|
||||
<span v-if="document.selection_batch">
|
||||
{{ t('chat.shippingOrderExtractionSelectionBatch', { batch: document.selection_batch }) }}
|
||||
</span>
|
||||
<span v-if="document.group_key">
|
||||
{{ t('chat.shippingOrderExtractionGroupKey', { key: document.group_key }) }}
|
||||
</span>
|
||||
<span v-if="document.po_number">
|
||||
{{ t('chat.shippingOrderExtractionPoNumber', { value: document.po_number }) }}
|
||||
</span>
|
||||
<span v-if="document.line_count > 0">
|
||||
{{ t('chat.shippingOrderExtractionLineCount', { count: document.line_count }) }}
|
||||
</span>
|
||||
<span v-if="document.profile">
|
||||
{{ t('chat.shippingOrderExtractionProfileSummary', {
|
||||
name: document.profile.name || document.profile.code,
|
||||
version: document.profile.version,
|
||||
}) }}
|
||||
</span>
|
||||
<span>
|
||||
{{ emailSupplementLabel }}
|
||||
</span>
|
||||
<span>
|
||||
{{ t('chat.shippingOrderExtractionEmailSupplementField.reservation') }}{{ reservationStatusLabel }}
|
||||
</span>
|
||||
<span>
|
||||
{{ t('chat.shippingOrderExtractionEmailSupplementField.sourceType') }}{{ sourceTypeStatusLabel }}
|
||||
</span>
|
||||
<span v-for="relation in emailSupplementRelations" :key="relation">
|
||||
{{ relation }}
|
||||
</span>
|
||||
<span v-if="document.email_supplement.conflict_count > 0">
|
||||
{{ t('chat.shippingOrderExtractionEmailSupplementConflictCount', { count: document.email_supplement.conflict_count }) }}
|
||||
</span>
|
||||
<span v-if="retryStatusLabel">
|
||||
{{ retryStatusLabel }}
|
||||
</span>
|
||||
<span v-if="budgetCostLabel">
|
||||
{{ budgetCostLabel }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="reasonLabel" class="mt-2 text-xs font-medium opacity-90">
|
||||
{{ reasonLabel }}
|
||||
</div>
|
||||
<ul v-if="reviewDetails.length" class="mt-2 space-y-1 text-xs font-medium opacity-90">
|
||||
<li v-for="detail in reviewDetails" :key="`${detail.line_number}-${detail.field_code || 'general'}`">
|
||||
{{ t('chat.shippingOrderExtractionReviewDetail', {
|
||||
line: detail.line_number,
|
||||
field: reviewFieldLabel(detail.field_code),
|
||||
}) }}
|
||||
</li>
|
||||
</ul>
|
||||
<div v-if="document.status === 'failed'" class="mt-1 text-xs font-medium opacity-90">
|
||||
{{ t('chat.shippingOrderExtractionTechnicalFailureUserHint') }}
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap gap-2">
|
||||
<button
|
||||
v-if="canViewEvidence"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-current/20 px-2.5 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
@click="emit('enterManualReview')"
|
||||
>
|
||||
<FileText class="h-3.5 w-3.5" />
|
||||
{{ t('chat.shippingOrderExtractionAction.view_evidence') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canEnterManualReview"
|
||||
type="button"
|
||||
class="inline-flex items-center rounded-md border border-current/20 px-2.5 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
@click="emit('enterManualReview')"
|
||||
>
|
||||
{{ t(`chat.shippingOrderExtractionAction.${document.available_actions.includes('review_candidate') ? 'review_candidate' : 'manual_review'}`) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,422 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderExtractionCard.spec.ts
|
||||
* 用途:覆盖订单解析摘要卡、详情抽屉和单 PDF 结果项的关键交互。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n、本域组件与 DTO 类型。
|
||||
* 逻辑:验证按钮由后端 available_actions 驱动,详情抽屉按需加载并支持键盘关闭。
|
||||
*/
|
||||
import { nextTick } from 'vue';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import ShippingOrderDocumentResultItem from './ShippingOrderDocumentResultItem.vue';
|
||||
import ShippingOrderExtractionCard from './ShippingOrderExtractionCard.vue';
|
||||
import ShippingOrderExtractionDetailsDrawer from './ShippingOrderExtractionDetailsDrawer.vue';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
import type {
|
||||
ShippingOrderExtractionDocumentResult,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
} from '../../types/shipping.api.types';
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
listDocuments: vi.fn(),
|
||||
listProgressEvents: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../api/shipping.api', () => ({
|
||||
listWorkspaceShippingOrderExtractionDocuments: api.listDocuments,
|
||||
listWorkspaceShippingOrderExtractionProgressEvents: api.listProgressEvents,
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: chatZhCn,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const flushUi = async () => {
|
||||
await Promise.resolve();
|
||||
await nextTick();
|
||||
};
|
||||
|
||||
const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): ShippingOrderExtractionState => ({
|
||||
status: 'processing',
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 1,
|
||||
completedDocuments: 2,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 2,
|
||||
},
|
||||
currentActivity: {
|
||||
unitId: 12,
|
||||
fileName: 'PO-450003.pdf',
|
||||
eventCode: 'profile_matching',
|
||||
},
|
||||
availableActions: ['view_details'],
|
||||
terminal: false,
|
||||
refreshFailed: false,
|
||||
errorCode: null,
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
...patch,
|
||||
});
|
||||
|
||||
const buildDocument = (
|
||||
patch: Partial<ShippingOrderExtractionDocumentResult> = {},
|
||||
): ShippingOrderExtractionDocumentResult => ({
|
||||
unit_id: 11,
|
||||
document_id: 85,
|
||||
file_name: 'PO-450001.pdf',
|
||||
status: 'candidate_ready',
|
||||
po_number: '450001',
|
||||
line_count: 4,
|
||||
profile: {
|
||||
code: 'vendor_a_po',
|
||||
name: 'Vendor A Purchase Order',
|
||||
version: 2,
|
||||
},
|
||||
email_supplement: {
|
||||
status: 'merged',
|
||||
relation_codes: ['po_mpn'],
|
||||
conflict_count: 0,
|
||||
reservation_id_status: 'merged',
|
||||
source_type_status: 'unavailable',
|
||||
},
|
||||
reason_code: null,
|
||||
available_actions: ['view_evidence', 'review_candidate'],
|
||||
...patch,
|
||||
});
|
||||
|
||||
const buildProgressEvent = (
|
||||
patch: Partial<ShippingOrderExtractionProgressEvent> = {},
|
||||
): ShippingOrderExtractionProgressEvent => ({
|
||||
event_code: 'expansion_wave_started',
|
||||
status: 'completed',
|
||||
unit_id: null,
|
||||
document_id: null,
|
||||
reason_code: null,
|
||||
summary: {
|
||||
selection_batch: 2,
|
||||
reason_codes: ['required_field_missing'],
|
||||
},
|
||||
occurred_at: '2026-07-28T10:30:00Z',
|
||||
...patch,
|
||||
});
|
||||
|
||||
describe('ShippingOrderExtractionCard', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('loads documents once when opening details from server actions', async () => {
|
||||
api.listDocuments.mockResolvedValue({ items: [buildDocument()] });
|
||||
api.listProgressEvents.mockResolvedValue({ items: [buildProgressEvent()] });
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
selectionPlan: {
|
||||
maxInitialAttachments: 2,
|
||||
maxInitialConcurrency: 2,
|
||||
expansionBatchSize: 2,
|
||||
maxTotalAttachments: 6,
|
||||
totalAttachmentCount: 5,
|
||||
eligibleAttachmentCount: 3,
|
||||
selectedAttachmentCount: 2,
|
||||
plannedAttachmentCount: 3,
|
||||
pendingExpansionAttachmentCount: 1,
|
||||
pendingExpansionBatches: { '2': 1 },
|
||||
skippedAttachmentCount: 3,
|
||||
duplicateAttachmentCount: 1,
|
||||
budgetLimitedAttachmentCount: 1,
|
||||
groupCount: 2,
|
||||
},
|
||||
unitSummary: {
|
||||
totalUnits: 2,
|
||||
selectedUnits: 2,
|
||||
retryingUnits: 1,
|
||||
pendingRetryUnits: 0,
|
||||
failedUnits: 0,
|
||||
reviewRequiredUnits: 0,
|
||||
succeededUnits: 0,
|
||||
selectionBatches: { '1': 2 },
|
||||
reviewRequiredReasonCodes: ['required_field_missing'],
|
||||
expansionTriggerReasonCodes: ['missing_reservation_id'],
|
||||
technicalFailureReasonCodes: [],
|
||||
},
|
||||
}),
|
||||
runNo: 'SNER-001',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const detailButton = wrapper.findAll('button').find((item) => item.text().includes('查看处理详情'));
|
||||
expect(detailButton).toBeTruthy();
|
||||
|
||||
await detailButton!.trigger('click');
|
||||
await flushUi();
|
||||
|
||||
expect(api.listDocuments).toHaveBeenCalledTimes(1);
|
||||
expect(api.listProgressEvents).toHaveBeenCalledTimes(1);
|
||||
expect(api.listDocuments).toHaveBeenCalledWith('SNER-001');
|
||||
expect(api.listProgressEvents).toHaveBeenCalledWith('SNER-001');
|
||||
expect(wrapper.text()).toContain('处理详情');
|
||||
expect(wrapper.text()).toContain('运行时间线');
|
||||
expect(wrapper.text()).toContain('系统已开始分析下一轮候选附件。');
|
||||
expect(wrapper.text()).toContain('当前批次:第 2 轮');
|
||||
expect(wrapper.text()).toContain('当前原因:订单关键字段不完整。');
|
||||
expect(wrapper.text()).toContain('PO-450001.pdf');
|
||||
expect(wrapper.text()).toContain('本轮从 5 个附件中规划 2 个订单组');
|
||||
expect(wrapper.text()).toContain('已选 2 个附件');
|
||||
expect(wrapper.text()).toContain('待扩展 1 个附件');
|
||||
expect(wrapper.text()).toContain('预算受限 1 个');
|
||||
expect(wrapper.text()).toContain('技术重试 1 个');
|
||||
expect(wrapper.text()).toContain('待复核原因:订单关键字段不完整。');
|
||||
expect(wrapper.text()).toContain('扩批触发:仍缺少 Reservation 字段,需要后续附件补证。');
|
||||
|
||||
await detailButton!.trigger('click');
|
||||
await flushUi();
|
||||
|
||||
expect(api.listDocuments).toHaveBeenCalledTimes(1);
|
||||
expect(api.listProgressEvents).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('emits manual review directly when attachments are already available', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
availableActions: ['enter_manual_review'],
|
||||
}),
|
||||
runNo: 'SNER-002',
|
||||
hasReviewAttachments: true,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const reviewButton = wrapper.findAll('button').find((item) => item.text().includes('进入人工复核'));
|
||||
expect(reviewButton).toBeTruthy();
|
||||
|
||||
await reviewButton!.trigger('click');
|
||||
|
||||
expect(wrapper.emitted('enterManualReview')).toHaveLength(1);
|
||||
expect(api.listDocuments).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('emits retry for failed attachments without mutating state locally', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
status: 'failed',
|
||||
terminal: true,
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 2,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 1,
|
||||
candidateCount: 2,
|
||||
},
|
||||
currentActivity: null,
|
||||
availableActions: ['retry_failed_attachments'],
|
||||
}),
|
||||
runNo: 'SNER-003',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const retryButton = wrapper.findAll('button').find((item) => item.text().includes('重试失败附件'));
|
||||
expect(retryButton).toBeTruthy();
|
||||
|
||||
await retryButton!.trigger('click');
|
||||
|
||||
expect(wrapper.emitted('retry')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('renders run-level activity text without forcing an unknown file label', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
currentActivity: {
|
||||
unitId: 0,
|
||||
fileName: null,
|
||||
eventCode: 'plan_created',
|
||||
selectionBatch: 2,
|
||||
reasonCodes: ['required_field_missing'],
|
||||
},
|
||||
}),
|
||||
runNo: 'SNER-004',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('识别计划已创建,正在准备首轮附件。');
|
||||
expect(wrapper.text()).toContain('当前批次:第 2 轮');
|
||||
expect(wrapper.text()).toContain('当前原因:订单关键字段不完整。');
|
||||
expect(wrapper.text()).not.toContain('未命名 PDF');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ShippingOrderExtractionDetailsDrawer', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('closes on Escape when the drawer is open', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionDetailsDrawer, {
|
||||
attachTo: document.body,
|
||||
props: {
|
||||
open: false,
|
||||
state: buildState({
|
||||
status: 'partially_completed',
|
||||
terminal: true,
|
||||
availableActions: ['view_details', 'enter_manual_review'],
|
||||
}),
|
||||
documents: [buildDocument()],
|
||||
progressEvents: [buildProgressEvent()],
|
||||
loading: false,
|
||||
loadFailed: false,
|
||||
progressLoading: false,
|
||||
progressLoadFailed: false,
|
||||
hasReviewAttachments: true,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
},
|
||||
});
|
||||
|
||||
await wrapper.setProps({ open: true });
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
|
||||
await nextTick();
|
||||
|
||||
expect(wrapper.emitted('close')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('renders run timeline entries with batch and reason context', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionDetailsDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
state: buildState(),
|
||||
documents: [buildDocument()],
|
||||
progressEvents: [buildProgressEvent()],
|
||||
loading: false,
|
||||
loadFailed: false,
|
||||
progressLoading: false,
|
||||
progressLoadFailed: false,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('运行时间线');
|
||||
expect(wrapper.text()).toContain('业务复核');
|
||||
expect(wrapper.text()).toContain('系统已开始分析下一轮候选附件。');
|
||||
expect(wrapper.text()).toContain('当前批次:第 2 轮');
|
||||
expect(wrapper.text()).toContain('当前原因:订单关键字段不完整。');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ShippingOrderDocumentResultItem', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('renders business reason and server-declared actions for a review-required PDF', async () => {
|
||||
const wrapper = mount(ShippingOrderDocumentResultItem, {
|
||||
props: {
|
||||
document: buildDocument({
|
||||
status: 'review_required',
|
||||
reason_code: 'multiple_po_detected',
|
||||
po_number: null,
|
||||
line_count: 0,
|
||||
email_supplement: {
|
||||
status: 'conflict',
|
||||
relation_codes: ['po_mpn'],
|
||||
conflict_count: 2,
|
||||
reservation_id_status: 'conflict',
|
||||
source_type_status: 'none',
|
||||
},
|
||||
available_actions: ['view_evidence', 'manual_review'],
|
||||
}),
|
||||
hasReviewAttachments: true,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('需要人工复核');
|
||||
expect(wrapper.text()).toContain('一份 PDF 中检测到多个不同 PO');
|
||||
expect(wrapper.text()).toContain('正文冲突 2 项');
|
||||
|
||||
const actionButtons = wrapper.findAll('button');
|
||||
expect(actionButtons.map((item) => item.text())).toEqual(
|
||||
expect.arrayContaining(['查看证据', '人工复核']),
|
||||
);
|
||||
|
||||
await actionButtons[0].trigger('click');
|
||||
|
||||
expect(wrapper.emitted('enterManualReview')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('renders a user-safe retry hint rather than a technical failure code for a failed attachment', async () => {
|
||||
const wrapper = mount(ShippingOrderDocumentResultItem, {
|
||||
props: {
|
||||
document: buildDocument({
|
||||
status: 'failed',
|
||||
reason_code: 'technical_failure',
|
||||
selection_batch: 2,
|
||||
group_key: 'PO-GRP-02',
|
||||
retry_status: 'failed',
|
||||
technical_failure_reason_code: 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
|
||||
budget_cost: {
|
||||
initial_attachment_budget: 2,
|
||||
initial_concurrency_budget: 2,
|
||||
selected_in_batch: 1,
|
||||
},
|
||||
available_actions: [],
|
||||
}),
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('选择批次:第 2 轮');
|
||||
expect(wrapper.text()).toContain('订单组:PO-GRP-02');
|
||||
expect(wrapper.text()).toContain('系统暂未完成处理,您可以稍后重试。');
|
||||
expect(wrapper.text()).toContain('首轮预算:附件 2 个,并发 2 个,本轮已选 1 个');
|
||||
expect(wrapper.text()).not.toContain('SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,302 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
|
||||
* 用途:渲染聊天中的订单抽取摘要卡,并在需要时打开 PDF 详情抽屉。
|
||||
* 依赖:订单抽取 Run 状态卡 DTO、documents API、详情抽屉。
|
||||
* 逻辑:卡片只显示 Run 汇总、当前活动和下一步动作;逐 PDF 结果与 Run 事实时间线延迟到抽屉内按需加载。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { CircleCheck, CircleX, LoaderCircle, TriangleAlert } from 'lucide-vue-next';
|
||||
import {
|
||||
listWorkspaceShippingOrderExtractionDocuments,
|
||||
listWorkspaceShippingOrderExtractionProgressEvents,
|
||||
} from '../../api/shipping.api';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
import type {
|
||||
ShippingOrderExtractionDocumentResult,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
} from '../../types/shipping.api.types';
|
||||
import ShippingOrderExtractionDetailsDrawer from './ShippingOrderExtractionDetailsDrawer.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
state: ShippingOrderExtractionState;
|
||||
runNo?: string;
|
||||
hasReviewAttachments?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
retry: [];
|
||||
enterManualReview: [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const detailsOpen = ref(false);
|
||||
const documents = ref<ShippingOrderExtractionDocumentResult[]>([]);
|
||||
const progressEvents = ref<ShippingOrderExtractionProgressEvent[]>([]);
|
||||
const loadingDocuments = ref(false);
|
||||
const documentsLoadFailed = ref(false);
|
||||
const documentsLoadedForRun = ref('');
|
||||
const loadingProgressEvents = ref(false);
|
||||
const progressEventsLoadFailed = ref(false);
|
||||
const progressEventsLoadedForRun = ref('');
|
||||
|
||||
watch(
|
||||
() => props.runNo,
|
||||
() => {
|
||||
detailsOpen.value = false;
|
||||
documents.value = [];
|
||||
progressEvents.value = [];
|
||||
loadingDocuments.value = false;
|
||||
loadingProgressEvents.value = false;
|
||||
documentsLoadFailed.value = false;
|
||||
progressEventsLoadFailed.value = false;
|
||||
documentsLoadedForRun.value = '';
|
||||
progressEventsLoadedForRun.value = '';
|
||||
},
|
||||
);
|
||||
|
||||
const toneClass = computed(() => {
|
||||
switch (props.state.status) {
|
||||
case 'completed':
|
||||
return 'border-emerald-200 bg-emerald-50/80 text-emerald-950 dark:border-emerald-800 dark:bg-emerald-950/35 dark:text-emerald-100';
|
||||
case 'partially_completed':
|
||||
case 'review_required':
|
||||
return 'border-amber-200 bg-amber-50/80 text-amber-950 dark:border-amber-800 dark:bg-amber-950/35 dark:text-amber-100';
|
||||
case 'failed':
|
||||
case 'cancelled':
|
||||
return 'border-rose-200 bg-rose-50/80 text-rose-900 dark:border-rose-800 dark:bg-rose-950/35 dark:text-rose-100';
|
||||
default:
|
||||
return 'border-sky-200 bg-sky-50/80 text-sky-900 dark:border-sky-800 dark:bg-sky-950/35 dark:text-sky-100';
|
||||
}
|
||||
});
|
||||
|
||||
const titleKey = computed(() => `chat.shippingOrderExtractionCardTitle.${props.state.status}`);
|
||||
const activityKey = computed(() => {
|
||||
const code = String(props.state.currentActivity?.eventCode || '').trim();
|
||||
const key = `chat.shippingOrderExtractionActivity.${code}`;
|
||||
return code && te(key) ? key : 'chat.shippingOrderExtractionActivity.generic_processing';
|
||||
});
|
||||
const completedLabel = computed(() => `${props.state.summary.completedDocuments} / ${props.state.summary.totalDocuments}`);
|
||||
const selectionSummaryItems = computed(() => {
|
||||
const selectionPlan = props.state.selectionPlan;
|
||||
const unitSummary = props.state.unitSummary;
|
||||
return [
|
||||
selectionPlan?.selectedAttachmentCount
|
||||
? t('chat.shippingOrderExtractionPlanSelected', { count: selectionPlan.selectedAttachmentCount })
|
||||
: '',
|
||||
selectionPlan?.pendingExpansionAttachmentCount
|
||||
? t('chat.shippingOrderExtractionPlanPendingExpansion', { count: selectionPlan.pendingExpansionAttachmentCount })
|
||||
: '',
|
||||
selectionPlan?.skippedAttachmentCount
|
||||
? t('chat.shippingOrderExtractionPlanSkipped', { count: selectionPlan.skippedAttachmentCount })
|
||||
: '',
|
||||
selectionPlan?.budgetLimitedAttachmentCount
|
||||
? t('chat.shippingOrderExtractionPlanBudgetLimited', { count: selectionPlan.budgetLimitedAttachmentCount })
|
||||
: '',
|
||||
unitSummary?.retryingUnits
|
||||
? t('chat.shippingOrderExtractionPlanRetrying', { count: unitSummary.retryingUnits })
|
||||
: '',
|
||||
unitSummary?.failedUnits
|
||||
? t('chat.shippingOrderExtractionPlanTechnicalFailures', { count: unitSummary.failedUnits })
|
||||
: '',
|
||||
].filter(Boolean);
|
||||
});
|
||||
const selectionPlanHint = computed(() => {
|
||||
const selectionPlan = props.state.selectionPlan;
|
||||
if (!selectionPlan?.totalAttachmentCount) return '';
|
||||
return t('chat.shippingOrderExtractionPlanSummary', {
|
||||
total: selectionPlan.totalAttachmentCount,
|
||||
groups: selectionPlan.groupCount || 0,
|
||||
attachments: selectionPlan.maxInitialAttachments || 0,
|
||||
concurrency: selectionPlan.maxInitialConcurrency || 0,
|
||||
});
|
||||
});
|
||||
|
||||
const translateReasonCodes = (codes: string[] | undefined): string[] => (
|
||||
(codes || [])
|
||||
.map((code) => {
|
||||
const normalized = String(code || '').trim();
|
||||
if (!normalized) return '';
|
||||
const key = `chat.shippingOrderExtractionReason.${normalized}`;
|
||||
return te(key) ? t(key) : normalized;
|
||||
})
|
||||
.filter(Boolean)
|
||||
);
|
||||
|
||||
const reviewReasonSummary = computed(() => {
|
||||
const labels = translateReasonCodes(props.state.unitSummary?.reviewRequiredReasonCodes);
|
||||
return labels.length
|
||||
? t('chat.shippingOrderExtractionReviewReasonCodes', { codes: labels.join(' / ') })
|
||||
: '';
|
||||
});
|
||||
|
||||
const expansionTriggerSummary = computed(() => {
|
||||
const labels = translateReasonCodes(props.state.unitSummary?.expansionTriggerReasonCodes);
|
||||
return labels.length
|
||||
? t('chat.shippingOrderExtractionExpansionTriggerCodes', { codes: labels.join(' / ') })
|
||||
: '';
|
||||
});
|
||||
|
||||
const currentActivityContextSummary = computed(() => {
|
||||
const parts: string[] = [];
|
||||
const batch = Number(props.state.currentActivity?.selectionBatch || 0);
|
||||
if (batch > 0) {
|
||||
parts.push(t('chat.shippingOrderExtractionActivitySelectionBatch', { batch }));
|
||||
}
|
||||
const labels = translateReasonCodes(props.state.currentActivity?.reasonCodes);
|
||||
if (labels.length) {
|
||||
parts.push(t('chat.shippingOrderExtractionActivityReasonCodes', { codes: labels.join(' / ') }));
|
||||
}
|
||||
return parts.join(' · ');
|
||||
});
|
||||
|
||||
const openDetails = async () => {
|
||||
if (!props.runNo) return;
|
||||
detailsOpen.value = true;
|
||||
const tasks: Promise<void>[] = [];
|
||||
if (documentsLoadedForRun.value !== props.runNo && !loadingDocuments.value) {
|
||||
loadingDocuments.value = true;
|
||||
documentsLoadFailed.value = false;
|
||||
tasks.push(
|
||||
listWorkspaceShippingOrderExtractionDocuments(props.runNo)
|
||||
.then((response) => {
|
||||
documents.value = response.items;
|
||||
documentsLoadedForRun.value = props.runNo || '';
|
||||
})
|
||||
.catch(() => {
|
||||
documentsLoadFailed.value = true;
|
||||
})
|
||||
.finally(() => {
|
||||
loadingDocuments.value = false;
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (progressEventsLoadedForRun.value !== props.runNo && !loadingProgressEvents.value) {
|
||||
loadingProgressEvents.value = true;
|
||||
progressEventsLoadFailed.value = false;
|
||||
tasks.push(
|
||||
listWorkspaceShippingOrderExtractionProgressEvents(props.runNo)
|
||||
.then((response) => {
|
||||
progressEvents.value = response.items;
|
||||
progressEventsLoadedForRun.value = props.runNo || '';
|
||||
})
|
||||
.catch(() => {
|
||||
progressEventsLoadFailed.value = true;
|
||||
})
|
||||
.finally(() => {
|
||||
loadingProgressEvents.value = false;
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (tasks.length) {
|
||||
await Promise.all(tasks);
|
||||
}
|
||||
};
|
||||
|
||||
const handleActionClick = async (action: string) => {
|
||||
switch (action) {
|
||||
case 'view_details':
|
||||
await openDetails();
|
||||
return;
|
||||
case 'enter_manual_review':
|
||||
if (props.hasReviewAttachments) {
|
||||
emit('enterManualReview');
|
||||
} else {
|
||||
await openDetails();
|
||||
}
|
||||
return;
|
||||
case 'retry_failed_attachments':
|
||||
emit('retry');
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mb-3 rounded-lg border px-3.5 py-3" :class="toneClass">
|
||||
<div class="flex items-start gap-3">
|
||||
<LoaderCircle
|
||||
v-if="state.status === 'queued' || state.status === 'processing'"
|
||||
class="mt-0.5 h-5 w-5 shrink-0 animate-spin"
|
||||
/>
|
||||
<CircleCheck v-else-if="state.status === 'completed'" class="mt-0.5 h-5 w-5 shrink-0" />
|
||||
<TriangleAlert
|
||||
v-else-if="state.status === 'partially_completed' || state.status === 'review_required'"
|
||||
class="mt-0.5 h-5 w-5 shrink-0"
|
||||
/>
|
||||
<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(titleKey) }}</div>
|
||||
<div class="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs opacity-90">
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.total', { count: state.summary.totalDocuments }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.completedProgress', { value: completedLabel }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.candidates', { count: state.summary.candidateCount }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.reviewRequired', { count: state.summary.reviewRequiredDocuments }) }}</span>
|
||||
<span v-if="state.summary.failedDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.failed', { count: state.summary.failedDocuments }) }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="state.currentActivity?.fileName" class="mt-2 text-xs font-medium opacity-90">
|
||||
{{ t('chat.shippingOrderExtractionCurrentFile', { fileName: state.currentActivity.fileName || t('chat.shippingOrderExtractionUnknownDocument') }) }}
|
||||
</div>
|
||||
<div v-if="state.currentActivity" class="mt-1 text-xs opacity-80">
|
||||
{{ t(activityKey) }}
|
||||
</div>
|
||||
<div v-if="currentActivityContextSummary" class="mt-1 text-xs opacity-80">
|
||||
{{ currentActivityContextSummary }}
|
||||
</div>
|
||||
<div v-if="selectionPlanHint" class="mt-2 text-xs opacity-85">
|
||||
{{ selectionPlanHint }}
|
||||
</div>
|
||||
<div v-if="reviewReasonSummary" class="mt-2 text-xs opacity-85">
|
||||
{{ reviewReasonSummary }}
|
||||
</div>
|
||||
<div v-if="expansionTriggerSummary" class="mt-1 text-xs opacity-85">
|
||||
{{ expansionTriggerSummary }}
|
||||
</div>
|
||||
<div v-if="selectionSummaryItems.length" class="mt-2 flex flex-wrap gap-2 text-[11px] font-medium opacity-90">
|
||||
<span
|
||||
v-for="item in selectionSummaryItems"
|
||||
:key="item"
|
||||
class="rounded-full bg-black/10 px-2 py-0.5 dark:bg-white/10"
|
||||
>
|
||||
{{ item }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="state.refreshFailed" class="mt-2 text-xs font-medium opacity-90">
|
||||
{{ t('chat.shippingOrderExtractionRefreshFailed') }}
|
||||
</div>
|
||||
<div class="mt-3 flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="action in state.availableActions"
|
||||
:key="action"
|
||||
type="button"
|
||||
class="inline-flex items-center rounded-md border border-current/20 px-2.5 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
@click="handleActionClick(action)"
|
||||
>
|
||||
{{ t(`chat.shippingOrderExtractionAction.${action}`) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ShippingOrderExtractionDetailsDrawer
|
||||
:open="detailsOpen"
|
||||
:state="state"
|
||||
:documents="documents"
|
||||
:progress-events="progressEvents"
|
||||
:loading="loadingDocuments"
|
||||
:load-failed="documentsLoadFailed"
|
||||
:progress-loading="loadingProgressEvents"
|
||||
:progress-load-failed="progressEventsLoadFailed"
|
||||
:has-review-attachments="hasReviewAttachments"
|
||||
@close="detailsOpen = false"
|
||||
@enter-manual-review="emit('enterManualReview')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderExtractionDetailsDrawer.vue
|
||||
* 用途:以抽屉形式展示一次订单抽取 Run 的按 PDF 归并详情和事实时间线。
|
||||
* 依赖:订单抽取状态卡、文档结果项、订单抽取 progress-events DTO、vue-i18n。
|
||||
* 逻辑:聊天摘要卡只显示概览;需要查看逐文档结果和每轮事件原因时由本抽屉承接新的 Run 级事实时间线。
|
||||
*/
|
||||
import { onBeforeUnmount, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { X } from 'lucide-vue-next';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
import type {
|
||||
ShippingOrderExtractionDocumentResult,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
} from '../../types/shipping.api.types';
|
||||
import { classifyOrderExtractionTimelineEvent } from '../../shipping/orderExtractionTimeline';
|
||||
import ShippingOrderDocumentResultItem from './ShippingOrderDocumentResultItem.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
state: ShippingOrderExtractionState;
|
||||
documents: ShippingOrderExtractionDocumentResult[];
|
||||
progressEvents: ShippingOrderExtractionProgressEvent[];
|
||||
loading: boolean;
|
||||
loadFailed: boolean;
|
||||
progressLoading: boolean;
|
||||
progressLoadFailed: boolean;
|
||||
hasReviewAttachments?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
enterManualReview: [];
|
||||
}>();
|
||||
|
||||
const { t, te, locale } = useI18n();
|
||||
let removeKeydownListener: (() => void) | null = null;
|
||||
|
||||
const translateReasonCodes = (codes: string[] | undefined): string[] => (
|
||||
(codes || [])
|
||||
.map((code) => {
|
||||
const normalized = String(code || '').trim();
|
||||
if (!normalized) return '';
|
||||
const key = `chat.shippingOrderExtractionReason.${normalized}`;
|
||||
return te(key) ? t(key) : normalized;
|
||||
})
|
||||
.filter(Boolean)
|
||||
);
|
||||
|
||||
const eventActivityLabel = (event: ShippingOrderExtractionProgressEvent): string => {
|
||||
const key = `chat.shippingOrderExtractionActivity.${String(event.event_code || '').trim()}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderExtractionActivity.generic_processing');
|
||||
};
|
||||
|
||||
const eventOccurredAtLabel = (value: string | undefined): string => {
|
||||
const raw = String(value || '').trim();
|
||||
if (!raw) return '';
|
||||
const date = new Date(raw);
|
||||
if (Number.isNaN(date.getTime())) return raw;
|
||||
return new Intl.DateTimeFormat(String(locale.value || 'zh-CN'), {
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
}).format(date);
|
||||
};
|
||||
|
||||
const eventContextLabel = (event: ShippingOrderExtractionProgressEvent): string => {
|
||||
const summary = event.summary && typeof event.summary === 'object'
|
||||
? event.summary as Record<string, unknown>
|
||||
: {};
|
||||
const parts: string[] = [];
|
||||
const batch = Number(summary.selection_batch || 0);
|
||||
if (batch > 0) {
|
||||
parts.push(t('chat.shippingOrderExtractionActivitySelectionBatch', { batch }));
|
||||
}
|
||||
const labels = translateReasonCodes([
|
||||
...(Array.isArray(summary.reason_codes) ? summary.reason_codes.map((item) => String(item || '').trim()) : []),
|
||||
String(event.reason_code || '').trim(),
|
||||
].filter(Boolean));
|
||||
if (labels.length) {
|
||||
parts.push(t('chat.shippingOrderExtractionActivityReasonCodes', { codes: labels.join(' / ') }));
|
||||
}
|
||||
return parts.join(' · ');
|
||||
};
|
||||
|
||||
const eventCategoryKey = (event: ShippingOrderExtractionProgressEvent): string =>
|
||||
`chat.shippingOrderExtractionTimelineTag.${classifyOrderExtractionTimelineEvent(event)}`;
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
(open) => {
|
||||
removeKeydownListener?.();
|
||||
removeKeydownListener = null;
|
||||
if (!open) return;
|
||||
const handleKeydown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') emit('close');
|
||||
};
|
||||
window.addEventListener('keydown', handleKeydown);
|
||||
removeKeydownListener = () => window.removeEventListener('keydown', handleKeydown);
|
||||
},
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
removeKeydownListener?.();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-50 flex justify-end bg-slate-950/40"
|
||||
@click.self="emit('close')"
|
||||
>
|
||||
<aside
|
||||
class="flex h-full w-full max-w-[560px] flex-col bg-white shadow-2xl dark:bg-slate-900"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="t('chat.shippingOrderExtractionDetailsTitle')"
|
||||
>
|
||||
<header class="flex items-start justify-between border-b border-slate-200 px-4 py-3 dark:border-slate-800">
|
||||
<div class="min-w-0">
|
||||
<h3 class="text-sm font-semibold text-slate-900 dark:text-slate-100">
|
||||
{{ t('chat.shippingOrderExtractionDetailsTitle') }}
|
||||
</h3>
|
||||
<div class="mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs text-slate-600 dark:text-slate-300">
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.total', { count: state.summary.totalDocuments }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.completed', { count: state.summary.completedDocuments }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.reviewRequired', { count: state.summary.reviewRequiredDocuments }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.failed', { count: state.summary.failedDocuments }) }}</span>
|
||||
<span v-if="state.selectionPlan?.selectedAttachmentCount">
|
||||
{{ t('chat.shippingOrderExtractionPlanSelected', { count: state.selectionPlan.selectedAttachmentCount }) }}
|
||||
</span>
|
||||
<span v-if="state.selectionPlan?.pendingExpansionAttachmentCount">
|
||||
{{ t('chat.shippingOrderExtractionPlanPendingExpansion', { count: state.selectionPlan.pendingExpansionAttachmentCount }) }}
|
||||
</span>
|
||||
<span v-if="state.selectionPlan?.budgetLimitedAttachmentCount">
|
||||
{{ t('chat.shippingOrderExtractionPlanBudgetLimited', { count: state.selectionPlan.budgetLimitedAttachmentCount }) }}
|
||||
</span>
|
||||
<span v-if="state.unitSummary?.retryingUnits">
|
||||
{{ t('chat.shippingOrderExtractionPlanRetrying', { count: state.unitSummary.retryingUnits }) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-md p-1 text-slate-500 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-slate-100"
|
||||
:aria-label="t('chat.shippingOrderExtractionCloseDetails')"
|
||||
@click="emit('close')"
|
||||
>
|
||||
<X class="h-4 w-4" />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div class="flex-1 space-y-3 overflow-y-auto px-4 py-4">
|
||||
<div
|
||||
v-if="state.selectionPlan?.totalAttachmentCount || state.unitSummary?.technicalFailureReasonCodes?.length"
|
||||
class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-3 text-xs text-slate-700 dark:border-slate-700 dark:bg-slate-900/60 dark:text-slate-200"
|
||||
>
|
||||
<div v-if="state.selectionPlan?.totalAttachmentCount">
|
||||
{{ t('chat.shippingOrderExtractionPlanSummary', {
|
||||
total: state.selectionPlan.totalAttachmentCount,
|
||||
groups: state.selectionPlan.groupCount || 0,
|
||||
attachments: state.selectionPlan.maxInitialAttachments || 0,
|
||||
concurrency: state.selectionPlan.maxInitialConcurrency || 0,
|
||||
}) }}
|
||||
</div>
|
||||
<div v-if="state.unitSummary?.reviewRequiredReasonCodes?.length" class="mt-1">
|
||||
{{ t('chat.shippingOrderExtractionReviewReasonCodes', {
|
||||
codes: translateReasonCodes(state.unitSummary.reviewRequiredReasonCodes).join(' / '),
|
||||
}) }}
|
||||
</div>
|
||||
<div v-if="state.unitSummary?.expansionTriggerReasonCodes?.length" class="mt-1">
|
||||
{{ t('chat.shippingOrderExtractionExpansionTriggerCodes', {
|
||||
codes: translateReasonCodes(state.unitSummary.expansionTriggerReasonCodes).join(' / '),
|
||||
}) }}
|
||||
</div>
|
||||
<div v-if="state.unitSummary?.technicalFailureReasonCodes?.length" class="mt-1">
|
||||
{{ t('chat.shippingOrderExtractionTechnicalFailureCodes', {
|
||||
codes: state.unitSummary.technicalFailureReasonCodes.join(', '),
|
||||
}) }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-lg border border-slate-200 bg-white px-3 py-3 dark:border-slate-700 dark:bg-slate-950/40">
|
||||
<div class="text-xs font-semibold text-slate-900 dark:text-slate-100">
|
||||
{{ t('chat.shippingOrderExtractionTimelineTitle') }}
|
||||
</div>
|
||||
<div
|
||||
v-if="progressLoading"
|
||||
class="mt-2 text-sm text-slate-600 dark:text-slate-300"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionTimelineLoading') }}
|
||||
</div>
|
||||
<div
|
||||
v-else-if="progressLoadFailed"
|
||||
class="mt-2 text-sm text-amber-700 dark:text-amber-200"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionTimelineUnavailable') }}
|
||||
</div>
|
||||
<div
|
||||
v-else-if="progressEvents.length === 0"
|
||||
class="mt-2 text-sm text-slate-600 dark:text-slate-300"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionTimelineEmpty') }}
|
||||
</div>
|
||||
<ol v-else class="mt-3 space-y-3">
|
||||
<li
|
||||
v-for="event in progressEvents"
|
||||
:key="`${event.event_code}-${event.unit_id || 0}-${event.document_id || 0}-${event.occurred_at}`"
|
||||
class="border-l-2 border-slate-200 pl-3 text-xs text-slate-700 dark:border-slate-700 dark:text-slate-200"
|
||||
>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-medium text-slate-700 dark:bg-slate-800 dark:text-slate-200">
|
||||
{{ t(eventCategoryKey(event)) }}
|
||||
</span>
|
||||
<div class="font-medium text-slate-900 dark:text-slate-100">
|
||||
{{ eventActivityLabel(event) }}
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="eventContextLabel(event)" class="mt-1 opacity-85">
|
||||
{{ eventContextLabel(event) }}
|
||||
</div>
|
||||
<div class="mt-1 opacity-70">
|
||||
{{ eventOccurredAtLabel(event.occurred_at) }}
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div v-if="loading" class="rounded-lg border border-dashed border-slate-300 px-3 py-4 text-sm text-slate-600 dark:border-slate-700 dark:text-slate-300">
|
||||
{{ t('chat.shippingOrderExtractionDocumentsLoading') }}
|
||||
</div>
|
||||
<div v-else-if="loadFailed" class="rounded-lg border border-amber-300 bg-amber-50 px-3 py-4 text-sm text-amber-900 dark:border-amber-700 dark:bg-amber-950/30 dark:text-amber-100">
|
||||
{{ t('chat.shippingOrderExtractionDocumentsUnavailable') }}
|
||||
</div>
|
||||
<div v-else-if="documents.length === 0" class="rounded-lg border border-dashed border-slate-300 px-3 py-4 text-sm text-slate-600 dark:border-slate-700 dark:text-slate-300">
|
||||
{{ t('chat.shippingOrderExtractionNoDocuments') }}
|
||||
</div>
|
||||
<ShippingOrderDocumentResultItem
|
||||
v-for="document in documents"
|
||||
:key="document.unit_id"
|
||||
:document="document"
|
||||
:has-review-attachments="hasReviewAttachments"
|
||||
@enter-manual-review="emit('enterManualReview')"
|
||||
/>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -137,47 +137,81 @@ describe('useChat shipping_order_extraction_state SSE', () => {
|
||||
|
||||
applyShippingOrderExtractionStateToMessage(message, {
|
||||
event: 'shipping_order_extraction_state',
|
||||
status: 'extracting',
|
||||
phase: 'llm_extraction',
|
||||
message: '正在识别邮件及附件中的订单',
|
||||
created_count: -1,
|
||||
status: 'processing',
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 2,
|
||||
completedDocuments: 1,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 1,
|
||||
},
|
||||
currentActivity: {
|
||||
unitId: 12,
|
||||
fileName: 'PO-450001.pdf',
|
||||
eventCode: 'profile_matching',
|
||||
},
|
||||
selectionPlan: {
|
||||
maxInitialAttachments: 2,
|
||||
pendingExpansionAttachmentCount: 1,
|
||||
},
|
||||
unitSummary: {
|
||||
reviewRequiredReasonCodes: ['required_field_missing'],
|
||||
expansionTriggerReasonCodes: ['missing_reservation_id'],
|
||||
technicalFailureReasonCodes: ['SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT'],
|
||||
},
|
||||
availableActions: ['view_details'],
|
||||
terminal: false,
|
||||
});
|
||||
expect(message.shipping_order_extraction_state?.status).toBe('extracting');
|
||||
expect(message.shipping_order_extraction_state?.created_count).toBe(0);
|
||||
expect(message.shipping_order_extraction_state?.status).toBe('processing');
|
||||
expect(message.shipping_order_extraction_state?.summary.processingDocuments).toBe(2);
|
||||
expect(message.shipping_order_extraction_state?.selectionPlan?.pendingExpansionAttachmentCount).toBe(1);
|
||||
expect(message.shipping_order_extraction_state?.unitSummary?.reviewRequiredReasonCodes).toEqual(['required_field_missing']);
|
||||
|
||||
applyShippingOrderExtractionStateToMessage(message, {
|
||||
event: 'shipping_order_extraction_state',
|
||||
status: 'completed',
|
||||
phase: 'result_persisted',
|
||||
message: '已创建 1 个发货任务',
|
||||
created_count: 1,
|
||||
opened_existing_count: 2,
|
||||
pending_count: 0,
|
||||
non_shipping_count: 3,
|
||||
created_with_missing_fields_count: 1,
|
||||
batch_no: 'SB-STATE-001',
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 3,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 3,
|
||||
},
|
||||
currentActivity: null,
|
||||
availableActions: ['view_details'],
|
||||
terminal: true,
|
||||
});
|
||||
|
||||
expect(message.content).toBe('Dify 最终正文保持不变');
|
||||
expect(message.shipping_order_extraction_state).toMatchObject({
|
||||
status: 'completed',
|
||||
created_count: 1,
|
||||
opened_existing_count: 2,
|
||||
non_shipping_count: 3,
|
||||
batch_no: 'SB-STATE-001',
|
||||
summary: {
|
||||
completedDocuments: 3,
|
||||
candidateCount: 3,
|
||||
},
|
||||
terminal: true,
|
||||
});
|
||||
expect((message.payload as Record<string, unknown>).existing_key).toBe('kept');
|
||||
expect((message.payload as { shipping_order_extraction_state?: { created_count?: number } })
|
||||
.shipping_order_extraction_state?.created_count).toBe(1);
|
||||
expect((message.payload as { shipping_order_extraction_state?: { summary?: { candidateCount?: number } } })
|
||||
.shipping_order_extraction_state?.summary?.candidateCount).toBe(3);
|
||||
|
||||
// 关键断言:网络重排导致的迟到进行态不能覆盖已经展示的终态。
|
||||
applyShippingOrderExtractionStateToMessage(message, {
|
||||
status: 'extracting',
|
||||
phase: 'llm_extraction',
|
||||
message: '迟到事件',
|
||||
status: 'processing',
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 1,
|
||||
completedDocuments: 2,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 2,
|
||||
},
|
||||
availableActions: ['view_details'],
|
||||
terminal: false,
|
||||
});
|
||||
expect(message.shipping_order_extraction_state?.status).toBe('completed');
|
||||
@@ -196,14 +230,22 @@ describe('useChat shipping_order_extraction_state SSE', () => {
|
||||
payload: {
|
||||
shipping_order_extraction_state: {
|
||||
status: 'partially_completed',
|
||||
phase: 'result_persisted',
|
||||
message: '仍有 1 个订单需要补充信息',
|
||||
created_count: 1,
|
||||
opened_existing_count: 0,
|
||||
pending_count: 1,
|
||||
non_shipping_count: 0,
|
||||
created_with_missing_fields_count: 0,
|
||||
batch_no: 'SB-HISTORY-001',
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 2,
|
||||
reviewRequiredDocuments: 1,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 2,
|
||||
},
|
||||
selectionPlan: {
|
||||
pendingExpansionAttachmentCount: 2,
|
||||
},
|
||||
unitSummary: {
|
||||
reviewRequiredReasonCodes: ['multiple_po_detected'],
|
||||
},
|
||||
availableActions: ['view_details', 'enter_manual_review'],
|
||||
terminal: true,
|
||||
},
|
||||
},
|
||||
@@ -212,7 +254,9 @@ describe('useChat shipping_order_extraction_state SSE', () => {
|
||||
hydrateShippingOrderExtractionState(message);
|
||||
|
||||
expect(message.shipping_order_extraction_state?.status).toBe('partially_completed');
|
||||
expect(message.shipping_order_extraction_state?.pending_count).toBe(1);
|
||||
expect(message.shipping_order_extraction_state?.batch_no).toBe('SB-HISTORY-001');
|
||||
expect(message.shipping_order_extraction_state?.summary.reviewRequiredDocuments).toBe(1);
|
||||
expect(message.shipping_order_extraction_state?.selectionPlan?.pendingExpansionAttachmentCount).toBe(2);
|
||||
expect(message.shipping_order_extraction_state?.unitSummary?.reviewRequiredReasonCodes).toEqual(['multiple_po_detected']);
|
||||
expect(message.shipping_order_extraction_state?.availableActions).toEqual(['view_details', 'enter_manual_review']);
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import type {
|
||||
ChatMessageAttachment,
|
||||
ChatRun,
|
||||
RetrieverResource,
|
||||
ShippingOrderExtractionState,
|
||||
} from '../types/chat.types';
|
||||
import type { ShippingBatchUiState, ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||||
@@ -166,9 +167,125 @@ export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<str
|
||||
};
|
||||
|
||||
export const isAllowedAfterStreamTerminal = (eventName: string): boolean => (
|
||||
eventName === 'shipping_ui_state'
|
||||
eventName === 'shipping_ui_state' || eventName === 'shipping_order_extraction_state'
|
||||
);
|
||||
|
||||
const normalizeShippingOrderExtractionState = (
|
||||
data: Record<string, unknown>,
|
||||
): ShippingOrderExtractionState | null => {
|
||||
const status = String(data.status || '').trim();
|
||||
if (!['queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'].includes(status)) {
|
||||
return null;
|
||||
}
|
||||
const rawSummary = data.summary && typeof data.summary === 'object'
|
||||
? data.summary as Record<string, unknown>
|
||||
: {};
|
||||
const rawActivity = data.currentActivity && typeof data.currentActivity === 'object'
|
||||
? data.currentActivity as Record<string, unknown>
|
||||
: null;
|
||||
const rawSelectionPlan = data.selectionPlan && typeof data.selectionPlan === 'object'
|
||||
? data.selectionPlan as Record<string, unknown>
|
||||
: null;
|
||||
const rawUnitSummary = data.unitSummary && typeof data.unitSummary === 'object'
|
||||
? data.unitSummary as Record<string, unknown>
|
||||
: null;
|
||||
return {
|
||||
status: status as ShippingOrderExtractionState['status'],
|
||||
summary: {
|
||||
totalDocuments: Math.max(0, Number(rawSummary.totalDocuments || 0)),
|
||||
pendingDocuments: Math.max(0, Number(rawSummary.pendingDocuments || 0)),
|
||||
processingDocuments: Math.max(0, Number(rawSummary.processingDocuments || 0)),
|
||||
completedDocuments: Math.max(0, Number(rawSummary.completedDocuments || 0)),
|
||||
reviewRequiredDocuments: Math.max(0, Number(rawSummary.reviewRequiredDocuments || 0)),
|
||||
failedDocuments: Math.max(0, Number(rawSummary.failedDocuments || 0)),
|
||||
candidateCount: Math.max(0, Number(rawSummary.candidateCount || 0)),
|
||||
},
|
||||
currentActivity: rawActivity
|
||||
? {
|
||||
unitId: Math.max(0, Number(rawActivity.unitId || 0)),
|
||||
fileName: String(rawActivity.fileName || '').trim() || null,
|
||||
eventCode: String(rawActivity.eventCode || '').trim(),
|
||||
selectionBatch: rawActivity.selectionBatch != null
|
||||
? Math.max(0, Number(rawActivity.selectionBatch || 0)) || null
|
||||
: null,
|
||||
reasonCodes: Array.isArray(rawActivity.reasonCodes)
|
||||
? rawActivity.reasonCodes.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
}
|
||||
: null,
|
||||
selectionPlan: rawSelectionPlan
|
||||
? {
|
||||
selectionVersion: String(rawSelectionPlan.selectionVersion || '').trim() || null,
|
||||
maxInitialAttachments: Math.max(0, Number(rawSelectionPlan.maxInitialAttachments || 0)),
|
||||
maxInitialConcurrency: Math.max(0, Number(rawSelectionPlan.maxInitialConcurrency || 0)),
|
||||
expansionBatchSize: Math.max(0, Number(rawSelectionPlan.expansionBatchSize || 0)),
|
||||
maxTotalAttachments: Math.max(0, Number(rawSelectionPlan.maxTotalAttachments || 0)),
|
||||
totalAttachmentCount: Math.max(0, Number(rawSelectionPlan.totalAttachmentCount || 0)),
|
||||
eligibleAttachmentCount: Math.max(0, Number(rawSelectionPlan.eligibleAttachmentCount || 0)),
|
||||
selectedAttachmentCount: Math.max(0, Number(rawSelectionPlan.selectedAttachmentCount || 0)),
|
||||
plannedAttachmentCount: Math.max(0, Number(rawSelectionPlan.plannedAttachmentCount || 0)),
|
||||
pendingExpansionAttachmentCount: Math.max(0, Number(rawSelectionPlan.pendingExpansionAttachmentCount || 0)),
|
||||
pendingExpansionBatches: rawSelectionPlan.pendingExpansionBatches && typeof rawSelectionPlan.pendingExpansionBatches === 'object'
|
||||
? rawSelectionPlan.pendingExpansionBatches as Record<string, number>
|
||||
: {},
|
||||
skippedAttachmentCount: Math.max(0, Number(rawSelectionPlan.skippedAttachmentCount || 0)),
|
||||
duplicateAttachmentCount: Math.max(0, Number(rawSelectionPlan.duplicateAttachmentCount || 0)),
|
||||
budgetLimitedAttachmentCount: Math.max(0, Number(rawSelectionPlan.budgetLimitedAttachmentCount || 0)),
|
||||
groupCount: Math.max(0, Number(rawSelectionPlan.groupCount || 0)),
|
||||
}
|
||||
: null,
|
||||
unitSummary: rawUnitSummary
|
||||
? {
|
||||
totalUnits: Math.max(0, Number(rawUnitSummary.totalUnits || 0)),
|
||||
selectedUnits: Math.max(0, Number(rawUnitSummary.selectedUnits || 0)),
|
||||
retryingUnits: Math.max(0, Number(rawUnitSummary.retryingUnits || 0)),
|
||||
pendingRetryUnits: Math.max(0, Number(rawUnitSummary.pendingRetryUnits || 0)),
|
||||
failedUnits: Math.max(0, Number(rawUnitSummary.failedUnits || 0)),
|
||||
reviewRequiredUnits: Math.max(0, Number(rawUnitSummary.reviewRequiredUnits || 0)),
|
||||
succeededUnits: Math.max(0, Number(rawUnitSummary.succeededUnits || 0)),
|
||||
selectionBatches: rawUnitSummary.selectionBatches && typeof rawUnitSummary.selectionBatches === 'object'
|
||||
? rawUnitSummary.selectionBatches as Record<string, number>
|
||||
: {},
|
||||
reviewRequiredReasonCodes: Array.isArray(rawUnitSummary.reviewRequiredReasonCodes)
|
||||
? rawUnitSummary.reviewRequiredReasonCodes.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
expansionTriggerReasonCodes: Array.isArray(rawUnitSummary.expansionTriggerReasonCodes)
|
||||
? rawUnitSummary.expansionTriggerReasonCodes.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
technicalFailureReasonCodes: Array.isArray(rawUnitSummary.technicalFailureReasonCodes)
|
||||
? rawUnitSummary.technicalFailureReasonCodes.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
}
|
||||
: null,
|
||||
availableActions: Array.isArray(data.availableActions)
|
||||
? data.availableActions.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
terminal: Boolean(data.terminal),
|
||||
refreshFailed: Boolean(data.refreshFailed),
|
||||
errorCode: String(data.errorCode || '').trim() || null,
|
||||
startedAt: String(data.startedAt || '').trim() || null,
|
||||
finishedAt: String(data.finishedAt || '').trim() || null,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 将订单抽取状态消息同步到当前助手消息。
|
||||
*
|
||||
* 说明:订单抽取已经迁移为 HXOPS 自有 Run 事实;即使流式正文已完成,
|
||||
* 服务端后续补发的领域状态也允许继续覆盖当前卡片,但迟到的非终态不得回退终态展示。
|
||||
*/
|
||||
export const applyShippingOrderExtractionStateToMessage = (msg: ChatMessage, data: Record<string, unknown>) => {
|
||||
const next = normalizeShippingOrderExtractionState(data);
|
||||
if (!next) return;
|
||||
const previous = msg.shipping_order_extraction_state;
|
||||
if (previous?.terminal && !next.terminal) return;
|
||||
msg.shipping_order_extraction_state = next;
|
||||
msg.payload = {
|
||||
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
|
||||
shipping_order_extraction_state: next,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 把 SSE 事件附带的元数据同步到当前消息对象。
|
||||
*
|
||||
@@ -605,7 +722,10 @@ export function useChat() {
|
||||
const botMsg = ensureBotMessage();
|
||||
if (!botMsg) continue;
|
||||
applyShippingUiStateToMessage(botMsg, data);
|
||||
|
||||
} else if (eventName === 'shipping_order_extraction_state') {
|
||||
const botMsg = ensureBotMessage();
|
||||
if (!botMsg) continue;
|
||||
applyShippingOrderExtractionStateToMessage(botMsg, data);
|
||||
} else if (eventName === 'message' || eventName === 'agent_message') {
|
||||
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||||
const botMsg = ensureBotMessage();
|
||||
|
||||
@@ -52,15 +52,22 @@ const extractionMessage: ChatMessage = {
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
shipping_order_extraction_state: {
|
||||
status: 'extracting',
|
||||
phase: 'llm_extraction',
|
||||
message: '正在识别邮件及附件中的订单',
|
||||
created_count: 0,
|
||||
opened_existing_count: 0,
|
||||
pending_count: 0,
|
||||
non_shipping_count: 0,
|
||||
created_with_missing_fields_count: 0,
|
||||
batch_no: null,
|
||||
status: 'processing',
|
||||
summary: {
|
||||
totalDocuments: 2,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 1,
|
||||
completedDocuments: 1,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 1,
|
||||
},
|
||||
currentActivity: {
|
||||
unitId: 8,
|
||||
fileName: 'PO-450001.pdf',
|
||||
eventCode: 'profile_matching',
|
||||
},
|
||||
availableActions: ['view_details'],
|
||||
terminal: false,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* features/chat/shipping/orderExtractionTimeline.spec.ts
|
||||
* 用途:验证订单抽取 Run 时间线事件分类纯函数。
|
||||
* 依赖:Vitest、progress-event DTO 类型、orderExtractionTimeline 纯函数。
|
||||
* 逻辑:卡住业务复核、技术失败、预算停止和普通进度的最小分类契约。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { ShippingOrderExtractionProgressEvent } from '../types/shipping.api.types';
|
||||
import { classifyOrderExtractionTimelineEvent } from './orderExtractionTimeline';
|
||||
|
||||
const event = (patch: Partial<ShippingOrderExtractionProgressEvent> = {}): ShippingOrderExtractionProgressEvent => ({
|
||||
event_code: 'initial_wave_started',
|
||||
status: 'completed',
|
||||
occurred_at: '2026-07-28T10:00:00Z',
|
||||
...patch,
|
||||
});
|
||||
|
||||
describe('classifyOrderExtractionTimelineEvent', () => {
|
||||
it('classifies review and expansion reasons as business timeline items', () => {
|
||||
expect(classifyOrderExtractionTimelineEvent(event({
|
||||
event_code: 'expansion_wave_started',
|
||||
summary: { reason_codes: ['required_field_missing'] },
|
||||
}))).toBe('business');
|
||||
});
|
||||
|
||||
it('classifies technical failure codes as technical timeline items', () => {
|
||||
expect(classifyOrderExtractionTimelineEvent(event({
|
||||
event_code: 'technical_failed',
|
||||
reason_code: 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
|
||||
}))).toBe('technical');
|
||||
});
|
||||
|
||||
it('classifies budget stop reasons as budget timeline items', () => {
|
||||
expect(classifyOrderExtractionTimelineEvent(event({
|
||||
event_code: 'budget_stopped',
|
||||
reason_code: 'budget_initial_limit',
|
||||
}))).toBe('budget');
|
||||
});
|
||||
|
||||
it('keeps neutral progress events in the progress bucket', () => {
|
||||
expect(classifyOrderExtractionTimelineEvent(event({
|
||||
event_code: 'plan_created',
|
||||
summary: { selection_batch: 1 },
|
||||
}))).toBe('progress');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* features/chat/shipping/orderExtractionTimeline.ts
|
||||
* 用途:归类订单抽取 Run 时间线事件,供卡片/抽屉统一展示标签。
|
||||
* 依赖:订单抽取 progress-event DTO(纯函数,不依赖 Vue)。
|
||||
* 逻辑:区分业务复核、技术失败、预算停止与普通进度,避免组件散落条件分支。
|
||||
*/
|
||||
import type { ShippingOrderExtractionProgressEvent } from '../types/shipping.api.types';
|
||||
|
||||
export type OrderExtractionTimelineCategory = 'business' | 'technical' | 'budget' | 'progress';
|
||||
|
||||
const TECHNICAL_EVENT_CODES = new Set([
|
||||
'technical_retrying',
|
||||
'technical_failed',
|
||||
]);
|
||||
|
||||
const BUDGET_EVENT_CODES = new Set([
|
||||
'budget_stopped',
|
||||
]);
|
||||
|
||||
const BUSINESS_EVENT_CODES = new Set([
|
||||
'review_required',
|
||||
'expansion_wave_started',
|
||||
]);
|
||||
|
||||
const BUDGET_REASON_CODES = new Set([
|
||||
'budget_initial_limit',
|
||||
'budget_total_limit',
|
||||
]);
|
||||
|
||||
const TECHNICAL_REASON_PREFIXES = [
|
||||
'SHIPPING_NOTICE.',
|
||||
'SYSTEM.',
|
||||
];
|
||||
|
||||
const collectEventReasonCodes = (event: ShippingOrderExtractionProgressEvent): string[] => {
|
||||
const summary = event.summary && typeof event.summary === 'object'
|
||||
? event.summary as Record<string, unknown>
|
||||
: {};
|
||||
const reasonCodes = [
|
||||
String(event.reason_code || '').trim(),
|
||||
...(Array.isArray(summary.reason_codes) ? summary.reason_codes.map((item) => String(item || '').trim()) : []),
|
||||
].filter(Boolean);
|
||||
return Array.from(new Set(reasonCodes));
|
||||
};
|
||||
|
||||
export function classifyOrderExtractionTimelineEvent(
|
||||
event: ShippingOrderExtractionProgressEvent,
|
||||
): OrderExtractionTimelineCategory {
|
||||
const eventCode = String(event.event_code || '').trim();
|
||||
const reasonCodes = collectEventReasonCodes(event);
|
||||
|
||||
if (
|
||||
TECHNICAL_EVENT_CODES.has(eventCode)
|
||||
|| reasonCodes.some((code) => TECHNICAL_REASON_PREFIXES.some((prefix) => code.startsWith(prefix)))
|
||||
) {
|
||||
return 'technical';
|
||||
}
|
||||
|
||||
if (
|
||||
BUDGET_EVENT_CODES.has(eventCode)
|
||||
|| reasonCodes.some((code) => BUDGET_REASON_CODES.has(code))
|
||||
) {
|
||||
return 'budget';
|
||||
}
|
||||
|
||||
if (
|
||||
BUSINESS_EVENT_CODES.has(eventCode)
|
||||
|| reasonCodes.some((code) => !TECHNICAL_REASON_PREFIXES.some((prefix) => code.startsWith(prefix)))
|
||||
) {
|
||||
return 'business';
|
||||
}
|
||||
|
||||
return 'progress';
|
||||
}
|
||||
@@ -38,6 +38,16 @@ export function isShippingNoticeAttachmentParseIncomplete(
|
||||
summary?: ShippingNoticeParseSummary | null,
|
||||
): boolean {
|
||||
if (!summary) return false;
|
||||
const previewStatus = String(summary.preview_status || '').trim().toLowerCase();
|
||||
if (summary.technical_failure) {
|
||||
return true;
|
||||
}
|
||||
if (previewStatus === 'technical_failed' || previewStatus === 'directory_incomplete') {
|
||||
return true;
|
||||
}
|
||||
if (summary.attachment_directory_complete === false || summary.ready_for_extraction === false) {
|
||||
return true;
|
||||
}
|
||||
const warnings = summary.warnings || [];
|
||||
if (warnings.some((item) => isBlockingWarning(String(item || '')))) {
|
||||
return true;
|
||||
|
||||
@@ -1,17 +1,11 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingSendHandler.spec.ts
|
||||
* 用途:验证上传预处理与点击发送完整抽取链路,以及建批提交中的并发拦截。
|
||||
* 用途:验证阶段 2 发送语义,只冻结当前输入框这批 Intake,并允许空备注启动识别。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createShippingSendHandlers, type ShippingSendHandlerContext } from './useChatShippingSendHandler';
|
||||
|
||||
const isShippingNoticeBatchSubmitting = vi.hoisted(() => vi.fn(() => false));
|
||||
|
||||
vi.mock('./useChatShippingUploadHandler', () => ({
|
||||
isShippingNoticeBatchSubmitting,
|
||||
}));
|
||||
|
||||
const createContext = (
|
||||
overrides: Partial<ShippingSendHandlerContext> = {},
|
||||
): ShippingSendHandlerContext => ({
|
||||
@@ -22,14 +16,7 @@ const createContext = (
|
||||
conversationId: ref('conv-send'),
|
||||
history: ref([]),
|
||||
input: ref(''),
|
||||
attachments: ref([{
|
||||
id: 'local-notice',
|
||||
kind: 'local',
|
||||
file: new File(['notice'], 'notice.txt', { type: 'text/plain' }),
|
||||
type: 'document',
|
||||
uploadStatus: 'waiting',
|
||||
uploadProgress: 0,
|
||||
}]),
|
||||
attachments: ref([]),
|
||||
shippingAutoFlowRequested: ref(true),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
getActiveShippingBatchNo: () => '',
|
||||
@@ -39,7 +26,7 @@ const createContext = (
|
||||
getActiveShippingTaskId: () => '',
|
||||
lastAssistantMessageContent: () => '',
|
||||
lastAssistantShippingActions: () => [],
|
||||
sendMessage: vi.fn(async () => true),
|
||||
sendMessage: vi.fn(async () => ({ ok: true } as never)),
|
||||
buildFileSpecsForSend: vi.fn(async () => []),
|
||||
loadHistory: vi.fn(async () => undefined),
|
||||
sendShippingMenuMessage: vi.fn(async () => undefined),
|
||||
@@ -50,9 +37,17 @@ const createContext = (
|
||||
handleShippingMenuAction: vi.fn(async () => undefined),
|
||||
handleShippingAutoUploadFile: vi.fn(async () => undefined),
|
||||
handleShippingAutoUploadNoticeBatch: vi.fn(async () => undefined),
|
||||
isShippingNoticeBatchSubmitting: () => isShippingNoticeBatchSubmitting(),
|
||||
markOrderExtractionStarted: vi.fn(),
|
||||
rollbackOrderExtractionStarted: vi.fn(),
|
||||
isShippingNoticeBatchSubmitting: () => false,
|
||||
hasBlockingNoticeIntake: () => false,
|
||||
hasNoticeIntakeFailures: () => false,
|
||||
hasBlockingNoticeDuplicates: () => false,
|
||||
hasCandidateReviewIssues: () => false,
|
||||
hasSelectedNoticeCandidates: () => false,
|
||||
openShippingDuplicateDialog: vi.fn(),
|
||||
getParsedIntakeNos: () => [],
|
||||
startOrderExtractionRun: vi.fn(async () => true),
|
||||
applyShippingMessageRecovery: vi.fn(async () => false),
|
||||
applyShippingBatchSnapshot: vi.fn(() => false),
|
||||
syncShippingConversationWorkspace: vi.fn(async () => true),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
shippingSuggestedPrompt: computed(() => ''),
|
||||
@@ -65,211 +60,158 @@ const createContext = (
|
||||
|
||||
describe('useChatShippingSendHandler', () => {
|
||||
beforeEach(() => {
|
||||
isShippingNoticeBatchSubmitting.mockReset();
|
||||
isShippingNoticeBatchSubmitting.mockReturnValue(false);
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('consumes send while notice batch is submitting and does not call sendMessage', async () => {
|
||||
isShippingNoticeBatchSubmitting.mockReturnValue(true);
|
||||
const ctx = createContext();
|
||||
it('blocks send while current notice attachments are still previewing', async () => {
|
||||
const ctx = createContext({
|
||||
attachments: ref([{
|
||||
id: 'notice-waiting',
|
||||
kind: 'shipping_notice',
|
||||
type: 'document',
|
||||
uploadStatus: 'uploaded',
|
||||
parseStatus: 'parsing',
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-WAITING',
|
||||
}]),
|
||||
hasBlockingNoticeIntake: () => true,
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(ctx.sendMessage).not.toHaveBeenCalled();
|
||||
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
|
||||
expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeBatchSubmitting');
|
||||
expect(ctx.startOrderExtractionRun).not.toHaveBeenCalled();
|
||||
expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeWaitingForParse');
|
||||
});
|
||||
|
||||
it('sends parsed intakes to the existing Chatflow without requiring upload-time candidates', async () => {
|
||||
const completionOrder: string[] = [];
|
||||
const attachment = {
|
||||
id: 'notice-1',
|
||||
it('starts extraction only for the current parsed intake batch and removes only submitted notice attachments', async () => {
|
||||
const currentNotice = {
|
||||
id: 'notice-current',
|
||||
kind: 'shipping_notice' as const,
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: 'parsed' as const,
|
||||
orderExtractionStatus: 'not_started' as const,
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
originalFilename: 'orders-current.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-1',
|
||||
intakeNo: 'SNI-CURRENT',
|
||||
uploadBatchId: 'batch-current',
|
||||
};
|
||||
const ctx = createContext({
|
||||
attachments: ref([attachment]),
|
||||
hasCandidateReviewIssues: () => true,
|
||||
hasSelectedNoticeCandidates: () => true,
|
||||
getParsedIntakeNos: () => ['SNI-1'],
|
||||
applyShippingBatchSnapshot: vi.fn(() => { completionOrder.push('snapshot'); return true; }),
|
||||
refreshNoticeIntakeStatuses: vi.fn(async () => { completionOrder.push('intakes'); }),
|
||||
syncShippingConversationWorkspace: vi.fn(async () => { completionOrder.push('workspace'); return true; }),
|
||||
clearConsumedNoticeAttachments: vi.fn(() => { completionOrder.push('clear'); }),
|
||||
refreshShippingActions: vi.fn(async () => { completionOrder.push('actions'); }),
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
|
||||
expect(ctx.sendMessage).toHaveBeenCalledWith(
|
||||
'chat.shippingOrderExtractionDefaultPrompt',
|
||||
1,
|
||||
'',
|
||||
[],
|
||||
{
|
||||
shipping_intake_nos: ['SNI-1'],
|
||||
display_query: 'chat.shippingOrderExtractionDefaultPrompt',
|
||||
},
|
||||
expect.objectContaining({
|
||||
userAttachments: [{
|
||||
name: 'orders.eml',
|
||||
size: 100,
|
||||
extension: 'eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
onAssistantMessageFinished: expect.any(Function),
|
||||
}),
|
||||
);
|
||||
expect(ctx.markOrderExtractionStarted).toHaveBeenCalledWith(['SNI-1']);
|
||||
|
||||
const hooks = vi.mocked(ctx.sendMessage).mock.calls[0]?.[5];
|
||||
const assistantMessage = { role: 'assistant', content: '已打开已有任务' } as const;
|
||||
await hooks?.onAssistantMessageFinished?.(assistantMessage, []);
|
||||
expect(ctx.applyShippingBatchSnapshot).toHaveBeenCalledWith(assistantMessage);
|
||||
expect(completionOrder).toEqual(['snapshot', 'intakes', 'workspace', 'clear', 'actions']);
|
||||
expect(ctx.syncShippingConversationWorkspace).toHaveBeenCalledWith({ preferLatest: true });
|
||||
});
|
||||
|
||||
it('uses the user query for full extraction even when no candidate exists before send', async () => {
|
||||
const attachment = {
|
||||
id: 'notice-1',
|
||||
const laterNotice = {
|
||||
id: 'notice-later',
|
||||
kind: 'shipping_notice' as const,
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: 'parsed' as const,
|
||||
orderExtractionStatus: 'not_started' as const,
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-1',
|
||||
originalFilename: 'orders-later.eml',
|
||||
fileSize: 120,
|
||||
intakeNo: 'SNI-LATER',
|
||||
uploadBatchId: 'batch-later',
|
||||
};
|
||||
const otherAttachment = {
|
||||
id: 'local-note',
|
||||
kind: 'local' as const,
|
||||
file: new File(['inventory'], 'inventory.xlsx', { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }),
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'waiting' as const,
|
||||
uploadProgress: 0,
|
||||
};
|
||||
const attachments = ref([currentNotice, laterNotice, otherAttachment]);
|
||||
const startOrderExtractionRun = vi.fn(async () => true);
|
||||
const ctx = createContext({
|
||||
attachments: ref([attachment]),
|
||||
hasCandidateReviewIssues: () => false,
|
||||
hasSelectedNoticeCandidates: () => false,
|
||||
getParsedIntakeNos: () => ['SNI-1'],
|
||||
attachments,
|
||||
getParsedIntakeNos: () => ['SNI-CURRENT'],
|
||||
startOrderExtractionRun,
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '请解析这些附件', '请解析这些附件');
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '请优先处理当前批次', '请优先处理当前批次');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
|
||||
expect(ctx.sendMessage).toHaveBeenCalledWith(
|
||||
'请解析这些附件',
|
||||
1,
|
||||
expect(startOrderExtractionRun).toHaveBeenCalledWith(
|
||||
'请优先处理当前批次',
|
||||
['SNI-CURRENT'],
|
||||
[{
|
||||
name: 'orders-current.eml',
|
||||
size: 100,
|
||||
extension: 'eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
'batch-current',
|
||||
);
|
||||
expect(attachments.value).toEqual([laterNotice, otherAttachment]);
|
||||
});
|
||||
|
||||
it('allows an empty note when the user only authorizes attachment analysis', async () => {
|
||||
const startOrderExtractionRun = vi.fn(async () => true);
|
||||
const ctx = createContext({
|
||||
attachments: ref([{
|
||||
id: 'notice-empty-note',
|
||||
kind: 'shipping_notice',
|
||||
type: 'document',
|
||||
uploadStatus: 'uploaded',
|
||||
parseStatus: 'parsed',
|
||||
orderExtractionStatus: 'not_started',
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-EMPTY-NOTE',
|
||||
uploadBatchId: 'batch-empty-note',
|
||||
}]),
|
||||
getParsedIntakeNos: () => ['SNI-EMPTY-NOTE'],
|
||||
startOrderExtractionRun,
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(startOrderExtractionRun).toHaveBeenCalledWith(
|
||||
'',
|
||||
[],
|
||||
{
|
||||
shipping_intake_nos: ['SNI-1'],
|
||||
display_query: '请解析这些附件',
|
||||
},
|
||||
expect.objectContaining({
|
||||
userAttachments: [{
|
||||
name: 'orders.eml',
|
||||
size: 100,
|
||||
extension: 'eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
onAssistantMessageFinished: expect.any(Function),
|
||||
}),
|
||||
['SNI-EMPTY-NOTE'],
|
||||
[{
|
||||
name: 'orders.eml',
|
||||
size: 100,
|
||||
extension: 'eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
'batch-empty-note',
|
||||
);
|
||||
});
|
||||
|
||||
it('retries the conversation workspace once when the first refresh fails', async () => {
|
||||
const syncWorkspace = vi.fn()
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(true);
|
||||
it('keeps attachments in the input when starting the run fails', async () => {
|
||||
const attachment = {
|
||||
id: 'notice-start-failed',
|
||||
kind: 'shipping_notice' as const,
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: 'parsed' as const,
|
||||
orderExtractionStatus: 'not_started' as const,
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-START-FAILED',
|
||||
};
|
||||
const attachments = ref([attachment]);
|
||||
const ctx = createContext({
|
||||
attachments: ref([{
|
||||
id: 'notice-retry',
|
||||
kind: 'shipping_notice' as const,
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: 'parsed' as const,
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-RETRY',
|
||||
}]),
|
||||
getParsedIntakeNos: () => ['SNI-RETRY'],
|
||||
syncShippingConversationWorkspace: syncWorkspace,
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
const hooks = vi.mocked(ctx.sendMessage).mock.calls[0]?.[5];
|
||||
await hooks?.onAssistantMessageFinished?.({} as never, []);
|
||||
|
||||
expect(syncWorkspace).toHaveBeenCalledTimes(2);
|
||||
expect(syncWorkspace).toHaveBeenNthCalledWith(1, { preferLatest: true });
|
||||
expect(syncWorkspace).toHaveBeenNthCalledWith(2, { preferLatest: true });
|
||||
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('rolls back the local extracting state when the chat request fails', async () => {
|
||||
const rollback = vi.fn();
|
||||
const ctx = createContext({
|
||||
attachments: ref([{
|
||||
id: 'notice-failed-send',
|
||||
kind: 'shipping_notice' as const,
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: 'parsed' as const,
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-FAILED-SEND',
|
||||
}]),
|
||||
getParsedIntakeNos: () => ['SNI-FAILED-SEND'],
|
||||
sendMessage: vi.fn(async () => { throw new Error('network failed'); }),
|
||||
rollbackOrderExtractionStarted: rollback,
|
||||
attachments,
|
||||
getParsedIntakeNos: () => ['SNI-START-FAILED'],
|
||||
startOrderExtractionRun: vi.fn(async () => { throw new Error('run create failed'); }),
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(rollback).toHaveBeenCalledWith(['SNI-FAILED-SEND']);
|
||||
expect(ctx.msg.warning).toHaveBeenCalledWith('network failed');
|
||||
});
|
||||
|
||||
it('rolls back extraction state when sendMessage reports a handled stream failure', async () => {
|
||||
const rollback = vi.fn();
|
||||
const ctx = createContext({
|
||||
attachments: ref([{
|
||||
id: 'notice-handled-failure',
|
||||
kind: 'shipping_notice' as const,
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: 'parsed' as const,
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-HANDLED-FAILURE',
|
||||
}]),
|
||||
getParsedIntakeNos: () => ['SNI-HANDLED-FAILURE'],
|
||||
sendMessage: vi.fn(async () => false),
|
||||
rollbackOrderExtractionStarted: rollback,
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(rollback).toHaveBeenCalledWith(['SNI-HANDLED-FAILURE']);
|
||||
expect(ctx.loadHistory).not.toHaveBeenCalled();
|
||||
expect(attachments.value).toEqual([attachment]);
|
||||
expect(ctx.msg.warning).toHaveBeenCalledWith('run create failed');
|
||||
});
|
||||
});
|
||||
@@ -72,7 +72,12 @@ export interface ShippingSendHandlerContext {
|
||||
hasSelectedNoticeCandidates?: () => boolean;
|
||||
openShippingDuplicateDialog?: (attachmentId?: string) => void;
|
||||
getParsedIntakeNos?: () => string[];
|
||||
startOrderExtractionRun?: (query: string, intakeNos: string[], attachments: ReturnType<typeof createChatMessageAttachmentSnapshots>) => Promise<boolean>;
|
||||
startOrderExtractionRun?: (
|
||||
query: string,
|
||||
intakeNos: string[],
|
||||
attachments: ReturnType<typeof createChatMessageAttachmentSnapshots>,
|
||||
uploadBatchId?: string,
|
||||
) => Promise<boolean>;
|
||||
applyShippingMessageRecovery?: (message: ChatMessage) => Promise<boolean>;
|
||||
applyShippingBatchSnapshot?: (message: ChatMessage) => boolean;
|
||||
syncShippingConversationWorkspace: (options?: { preferLatest?: boolean }) => Promise<boolean>;
|
||||
@@ -214,14 +219,33 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
}
|
||||
const intakeNos = ctx.getParsedIntakeNos?.() || [];
|
||||
if (intakeNos.length) {
|
||||
const userAttachments = createChatMessageAttachmentSnapshots(noticeItems);
|
||||
const query = trimmed || ctx.t('chat.shippingOrderExtractionDefaultPrompt');
|
||||
const submittedIntakes = new Set(intakeNos.map((item) => item.trim().toUpperCase()));
|
||||
const batchIds = new Set(
|
||||
noticeItems
|
||||
.filter((item) => item.intakeNo && submittedIntakes.has(item.intakeNo.trim().toUpperCase()))
|
||||
.map((item) => String(item.uploadBatchId || '').trim())
|
||||
.filter(Boolean),
|
||||
);
|
||||
if (batchIds.size > 1) {
|
||||
ctx.msg.warning('当前发送批次不一致,请重新上传需要一起识别的文件');
|
||||
return true;
|
||||
}
|
||||
const userAttachments = createChatMessageAttachmentSnapshots(
|
||||
noticeItems.filter((item) =>
|
||||
item.intakeNo
|
||||
&& submittedIntakes.has(item.intakeNo.trim().toUpperCase()),
|
||||
),
|
||||
);
|
||||
// 阶段 2:发送是“授权开始识别”,备注允许为空,不能再偷偷注入默认提示词。
|
||||
const query = trimmed;
|
||||
ctx.shippingAutoFlowRequested.value = false;
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
try {
|
||||
const started = await ctx.startOrderExtractionRun?.(query, intakeNos, userAttachments);
|
||||
const uploadBatchId = [...batchIds][0];
|
||||
const started = uploadBatchId
|
||||
? await ctx.startOrderExtractionRun?.(query, intakeNos, userAttachments, uploadBatchId)
|
||||
: await ctx.startOrderExtractionRun?.(query, intakeNos, userAttachments);
|
||||
if (!started) return true;
|
||||
const submittedIntakes = new Set(intakeNos.map((item) => item.trim().toUpperCase()));
|
||||
ctx.attachments.value = ctx.attachments.value.filter(
|
||||
(item) => item.kind !== 'shipping_notice'
|
||||
|| !item.intakeNo
|
||||
|
||||
@@ -31,8 +31,14 @@ describe('shipping notice order extraction state', () => {
|
||||
expect(isOrderExtractionEligibleIntake({ ...base, orderExtractionStatus: 'partially_completed' })).toBe(false);
|
||||
expect(isOrderExtractionEligibleIntake({ ...base, orderExtractionStatus: 'completed' })).toBe(false);
|
||||
expect(isOrderExtractionEligibleIntake({ ...base, orderExtractionStatus: 'failed' })).toBe(true);
|
||||
expect(isOrderExtractionEligibleIntake({ ...base, layoutStatus: 'processing' })).toBe(false);
|
||||
expect(isOrderExtractionEligibleIntake({ ...base, layoutStatus: 'completed' })).toBe(true);
|
||||
expect(isOrderExtractionEligibleIntake({
|
||||
...base,
|
||||
parseSummary: {
|
||||
preview_status: 'directory_incomplete',
|
||||
ready_for_extraction: false,
|
||||
attachment_directory_complete: false,
|
||||
},
|
||||
})).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps polling after preprocessing is parsed while order extraction is active', () => {
|
||||
@@ -52,7 +58,7 @@ describe('shipping notice order extraction state', () => {
|
||||
parseStatus: 'parsed',
|
||||
orderExtractionStatus: 'not_started',
|
||||
layoutStatus: 'processing',
|
||||
})).toBe(true);
|
||||
})).toBe(false);
|
||||
});
|
||||
|
||||
it('preserves the immediate extracting state until the backend leaves not_started', () => {
|
||||
@@ -66,12 +72,21 @@ describe('shipping notice order extraction state', () => {
|
||||
expect(shouldRestoreShippingNoticeIntake('queued')).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsing')).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parse_failed')).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'not_started', 0, {
|
||||
preview_status: 'ready_for_extraction',
|
||||
ready_for_extraction: true,
|
||||
attachment_directory_complete: true,
|
||||
})).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'failed', 0)).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'partially_completed', 2)).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'not_started', 0, 'processing')).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'not_started', 0, {
|
||||
preview_status: 'directory_incomplete',
|
||||
ready_for_extraction: false,
|
||||
attachment_directory_complete: false,
|
||||
})).toBe(false);
|
||||
|
||||
// 已完成且没有待审核 Candidate 的文件仅保留在用户消息气泡中。
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed')).toBe(false);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'completed')).toBe(false);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'partially_completed', 0)).toBe(false);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'completed', 2)).toBe(false);
|
||||
expect(shouldRestoreShippingNoticeIntake('consumed')).toBe(false);
|
||||
|
||||
@@ -40,8 +40,8 @@ const ACTIVE_ORDER_EXTRACTION = new Set(['extracting']);
|
||||
/**
|
||||
* 判断服务端 Intake 是否应恢复到输入栏。
|
||||
* AI 触发时机:无;页面刷新或重新打开会话时调用。
|
||||
* 已解析文件已作为用户消息附件固化在对话气泡中,不能再次显示在输入栏;但存在待审核
|
||||
* Candidate 的部分完成 Intake 必须恢复,否则用户无法补充字段并继续建单。
|
||||
* 上传快览与发送授权已拆分:未发送但已快览成功的附件,刷新后也必须恢复到输入栏;
|
||||
* 已进入订单抽取终态的附件仅保留在消息气泡中,避免把旧批次误带回当前输入框。
|
||||
* @param parseStatus - 服务端返回的预解析状态。
|
||||
* @param orderExtractionStatus - 服务端返回的订单抽取状态。
|
||||
* @param candidateCount - 当前仍可审核的订单 Candidate 数量。
|
||||
@@ -51,13 +51,17 @@ export function shouldRestoreShippingNoticeIntake(
|
||||
parseStatus: string | null | undefined,
|
||||
orderExtractionStatus?: string | null,
|
||||
candidateCount = 0,
|
||||
layoutStatus?: ShippingNoticePendingAttachment['layoutStatus'],
|
||||
parseSummary?: ShippingNoticePendingAttachment['parseSummary'],
|
||||
): boolean {
|
||||
const status = String(parseStatus || '').trim().toLowerCase();
|
||||
const extractionStatus = String(orderExtractionStatus || '').trim().toLowerCase();
|
||||
return ACTIVE_PARSE.has(status)
|
||||
|| status === 'parse_failed'
|
||||
|| layoutStatus === 'processing'
|
||||
|| (
|
||||
status === 'parsed'
|
||||
&& (!extractionStatus || extractionStatus === 'not_started')
|
||||
&& !isShippingNoticeAttachmentParseIncomplete(parseSummary)
|
||||
)
|
||||
|| extractionStatus === 'failed'
|
||||
|| (extractionStatus === 'partially_completed' && candidateCount > 0);
|
||||
}
|
||||
@@ -67,8 +71,7 @@ export function shouldPollShippingNoticeIntake(
|
||||
item: Pick<ShippingNoticePendingAttachment, 'parseStatus' | 'orderExtractionStatus' | 'layoutStatus'>,
|
||||
): boolean {
|
||||
return !TERMINAL_PARSE.has(item.parseStatus)
|
||||
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase())
|
||||
|| item.layoutStatus === 'processing';
|
||||
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase());
|
||||
}
|
||||
|
||||
/** 判断附件是否仍可作为新一轮完整订单抽取的输入。 */
|
||||
@@ -79,7 +82,6 @@ export function isOrderExtractionEligibleIntake(
|
||||
return item.parseStatus === 'parsed'
|
||||
&& Boolean(item.intakeNo)
|
||||
&& (extractionStatus === 'not_started' || extractionStatus === 'failed')
|
||||
&& item.layoutStatus !== 'processing'
|
||||
&& !isShippingNoticeAttachmentParseIncomplete(item.parseSummary);
|
||||
}
|
||||
|
||||
@@ -222,7 +224,7 @@ export function mapServerCandidate(remote: ShippingNoticeCandidateResponse): Shi
|
||||
};
|
||||
}
|
||||
|
||||
function createPendingAttachment(file: File): ShippingNoticePendingAttachment {
|
||||
function createPendingAttachment(file: File, uploadBatchId: string): ShippingNoticePendingAttachment {
|
||||
return {
|
||||
id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
|
||||
kind: 'shipping_notice',
|
||||
@@ -233,6 +235,7 @@ function createPendingAttachment(file: File): ShippingNoticePendingAttachment {
|
||||
uploadProgress: 0,
|
||||
originalFilename: file.name,
|
||||
fileSize: file.size,
|
||||
uploadBatchId,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -246,6 +249,8 @@ export interface UseShippingNoticeIntakesOptions {
|
||||
export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOptions) {
|
||||
const pollTimer = ref<ReturnType<typeof setTimeout> | null>(null);
|
||||
const pollRound = ref(0);
|
||||
// 新文件选择显式推进当前批次;恢复历史卡片不能覆盖它。
|
||||
const currentUploadBatchId = ref<string | null>(null);
|
||||
|
||||
const noticeAttachments = computed(() =>
|
||||
options.attachments.value.filter(
|
||||
@@ -253,20 +258,26 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
),
|
||||
);
|
||||
|
||||
const currentBatchAttachments = computed(() => {
|
||||
const batchId = currentUploadBatchId.value;
|
||||
return batchId
|
||||
? noticeAttachments.value.filter((item) => item.uploadBatchId === batchId)
|
||||
: noticeAttachments.value;
|
||||
});
|
||||
|
||||
const hasBlockingUploadOrParse = computed(() =>
|
||||
noticeAttachments.value.some((item) =>
|
||||
currentBatchAttachments.value.some((item) =>
|
||||
item.uploadStatus === 'uploading'
|
||||
|| item.uploadStatus === 'waiting'
|
||||
|| ACTIVE_PARSE.has(item.parseStatus)
|
||||
|| item.parseStatus === 'queued'
|
||||
|| item.parseStatus === 'parsing'
|
||||
|| item.layoutStatus === 'processing'
|
||||
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase()),
|
||||
),
|
||||
);
|
||||
|
||||
const hasParseFailures = computed(() =>
|
||||
noticeAttachments.value.some(
|
||||
currentBatchAttachments.value.some(
|
||||
(item) =>
|
||||
item.parseStatus === 'failed'
|
||||
|| isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
|
||||
@@ -274,8 +285,8 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
);
|
||||
|
||||
const allParsedReady = computed(() =>
|
||||
noticeAttachments.value.length > 0
|
||||
&& noticeAttachments.value.every(
|
||||
currentBatchAttachments.value.length > 0
|
||||
&& currentBatchAttachments.value.every(
|
||||
(item) =>
|
||||
item.parseStatus === 'parsed'
|
||||
&& !isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
|
||||
@@ -283,7 +294,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
);
|
||||
|
||||
const hasBlockingDuplicates = computed(() =>
|
||||
noticeAttachments.value.some(
|
||||
currentBatchAttachments.value.some(
|
||||
(item) => (item.candidates?.length
|
||||
? item.candidates.some((candidate) =>
|
||||
candidate.selected && candidate.duplicate?.blocking && !candidate.duplicateResolution?.action,
|
||||
@@ -293,7 +304,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
);
|
||||
|
||||
const hasCandidateReviewIssues = computed(() =>
|
||||
noticeAttachments.value.some((item) =>
|
||||
currentBatchAttachments.value.some((item) =>
|
||||
(item.candidates || []).some((candidate) =>
|
||||
candidate.selected && candidate.validationStatus !== 'ready',
|
||||
),
|
||||
@@ -305,7 +316,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
&& !hasBlockingDuplicates.value
|
||||
&& !hasCandidateReviewIssues.value
|
||||
&& !hasParseFailures.value
|
||||
&& noticeAttachments.value.some((item) => (item.candidates || []).some((candidate) => candidate.selected)),
|
||||
&& currentBatchAttachments.value.some((item) => (item.candidates || []).some((candidate) => candidate.selected)),
|
||||
);
|
||||
|
||||
const stopPolling = () => {
|
||||
@@ -386,9 +397,11 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
const intake = await createShippingNoticeIntake(
|
||||
asset.asset_no,
|
||||
options.conversationId.value,
|
||||
attachment.uploadBatchId,
|
||||
);
|
||||
patchAttachment(attachment.id, {
|
||||
intakeNo: intake.intake_no,
|
||||
uploadBatchId: intake.upload_batch_id || attachment.uploadBatchId,
|
||||
parseStatus: mapServerParseStatus(intake.parse_status),
|
||||
orderExtractionStatus: intake.order_extraction_status || undefined,
|
||||
parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
|
||||
@@ -412,8 +425,12 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
};
|
||||
|
||||
const enqueueNoticeFiles = async (files: File[]) => {
|
||||
// 同一次选择共享一个持久化批次;后续发送只会自动取这个最新批次。
|
||||
const uploadBatchId = globalThis.crypto?.randomUUID?.()
|
||||
|| `${Date.now()}-${Math.random().toString(36).slice(2, 12)}`;
|
||||
currentUploadBatchId.value = uploadBatchId;
|
||||
for (const file of files) {
|
||||
const attachment = createPendingAttachment(file);
|
||||
const attachment = createPendingAttachment(file, uploadBatchId);
|
||||
options.attachments.value = [...options.attachments.value, attachment];
|
||||
await processSingleFile(attachment);
|
||||
}
|
||||
@@ -452,10 +469,14 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
schedulePoll();
|
||||
};
|
||||
|
||||
const getParsedIntakeNos = () =>
|
||||
noticeAttachments.value
|
||||
.filter(isOrderExtractionEligibleIntake)
|
||||
const getParsedIntakeNos = () => {
|
||||
const eligible = noticeAttachments.value.filter(isOrderExtractionEligibleIntake);
|
||||
const currentBatchId = currentUploadBatchId.value
|
||||
|| [...noticeAttachments.value].reverse().find((item) => item.uploadBatchId)?.uploadBatchId;
|
||||
return eligible
|
||||
.filter((item) => item.uploadBatchId === currentBatchId)
|
||||
.map((item) => String(item.intakeNo));
|
||||
};
|
||||
|
||||
/** 点击发送后立即展示订单识别阶段,并启动 Intake 状态轮询。 */
|
||||
const markOrderExtractionStarted = (intakeNos: string[]) => {
|
||||
@@ -497,7 +518,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
item.parse_status,
|
||||
item.order_extraction_status,
|
||||
item.candidates?.length || 0,
|
||||
item.layout_status,
|
||||
(item.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
|
||||
))
|
||||
.map((item) => ({
|
||||
id: `restored_${item.intake_no}`,
|
||||
@@ -505,6 +526,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
type: 'document' as const,
|
||||
assetNo: item.asset_no || undefined,
|
||||
intakeNo: item.intake_no,
|
||||
uploadBatchId: item.upload_batch_id || undefined,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: mapServerParseStatus(item.parse_status),
|
||||
orderExtractionStatus: item.order_extraction_status || undefined,
|
||||
|
||||
@@ -37,6 +37,17 @@ const run = (patch: Partial<ShippingOrderExtractionRun>): ShippingOrderExtractio
|
||||
intake_nos: ['SNI-1'],
|
||||
schema_version_id: 1,
|
||||
attempt_count: 0,
|
||||
summary: {
|
||||
total_documents: 1,
|
||||
pending_documents: 1,
|
||||
processing_documents: 0,
|
||||
completed_documents: 0,
|
||||
review_required_documents: 0,
|
||||
failed_documents: 0,
|
||||
candidate_count: 0,
|
||||
},
|
||||
current_activity: null,
|
||||
available_actions: ['view_details'],
|
||||
...patch,
|
||||
});
|
||||
|
||||
@@ -86,7 +97,8 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
api.getRun.mockResolvedValue(queued);
|
||||
const harness = createHarness();
|
||||
|
||||
await harness.runs.startRun('解析附件', ['SNI-1'], []);
|
||||
await harness.runs.startRun('解析附件', ['SNI-1'], [], 'batch-1');
|
||||
expect(api.createRun).toHaveBeenCalledWith(expect.objectContaining({ upload_batch_id: 'batch-1' }));
|
||||
expect(harness.conversationId.value).toBe('conv-created');
|
||||
expect(harness.options.onConversationResolved).toHaveBeenCalledWith('conv-created');
|
||||
expect(harness.messages.value.map((item) => item.payload?.formId)).toEqual([
|
||||
@@ -101,10 +113,42 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('persists an attachment-only user message when the run starts without a text note', async () => {
|
||||
const queued = run({ run_no: 'SNER-EMPTY-NOTE', conversation_id: 'conv-empty-note' });
|
||||
api.createRun.mockResolvedValue({ run: queued, reused: false });
|
||||
const harness = createHarness();
|
||||
|
||||
await harness.runs.startRun('', ['SNI-1'], [{
|
||||
name: 'orders.eml',
|
||||
size: 128,
|
||||
extension: 'eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}]);
|
||||
|
||||
expect(harness.messages.value[0]).toMatchObject({
|
||||
role: 'user',
|
||||
content: '',
|
||||
attachments: [{
|
||||
name: 'orders.eml',
|
||||
size: 128,
|
||||
extension: 'eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
});
|
||||
expect(harness.options.saveLocalMessageToBackend).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({ content: '' }),
|
||||
undefined,
|
||||
);
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('absorbs restore failures and ignores an old conversation late response', async () => {
|
||||
const pending = deferred<ShippingOrderExtractionRun>();
|
||||
api.listRuns
|
||||
.mockResolvedValueOnce({ items: [run({ run_no: 'SNER-OLD', conversation_id: 'conv-old', status: 'running' })] })
|
||||
.mockResolvedValueOnce({ items: [run({ run_no: 'SNER-OLD', conversation_id: 'conv-old', status: 'processing' })] })
|
||||
.mockRejectedValueOnce(new Error('offline'));
|
||||
api.getRun.mockReturnValueOnce(pending.promise);
|
||||
const harness = createHarness();
|
||||
@@ -118,7 +162,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
await Promise.resolve();
|
||||
expect(harness.runs.getActiveRunNo()).toBe('');
|
||||
expect(harness.messages.value).toHaveLength(1);
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('extracting');
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('processing');
|
||||
});
|
||||
|
||||
it('aborts a hanging Run query after ten seconds and keeps polling as a transport failure', async () => {
|
||||
@@ -132,7 +176,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
await vi.advanceTimersByTimeAsync(11000);
|
||||
expect(api.getRun).toHaveBeenCalledWith('SNER-TIMEOUT', expect.any(AbortSignal));
|
||||
expect(harness.runs.getActiveRunNo()).toBe('SNER-TIMEOUT');
|
||||
expect(harness.messages.value[1]?.shipping_order_extraction_state?.status).toBe('extracting');
|
||||
expect(harness.messages.value[1]?.shipping_order_extraction_state?.status).toBe('queued');
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
@@ -151,7 +195,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
expect(api.retryRun).toHaveBeenCalledWith('SNER-RETRY');
|
||||
expect(harness.options.refreshNoticeIntakeStatuses).toHaveBeenCalledTimes(2);
|
||||
expect(harness.messages.value).toHaveLength(1);
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('extracting');
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('queued');
|
||||
expect(harness.runs.getActiveRunNo()).toBe('SNER-RETRY');
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
@@ -167,7 +211,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
});
|
||||
|
||||
it('creates a new Run for reidentification and switches polling to the new version', async () => {
|
||||
const source = run({ run_no: 'SNER-SOURCE', status: 'needs_review' });
|
||||
const source = run({ run_no: 'SNER-SOURCE', status: 'review_required' });
|
||||
const replacement = run({
|
||||
run_no: 'SNER-REPLACEMENT', status: 'queued',
|
||||
reparse: { source_run_no: 'SNER-SOURCE', reason: 'field_mapping_error' },
|
||||
@@ -190,34 +234,75 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
|
||||
|
||||
describe('mapOrderExtractionRunToMessageState', () => {
|
||||
it('maps queued/running to indeterminate extracting state', () => {
|
||||
it('maps queued and processing to the new Run summary state', () => {
|
||||
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',
|
||||
status: 'processing',
|
||||
selection_plan: {
|
||||
max_initial_attachments: 2,
|
||||
max_initial_concurrency: 2,
|
||||
expansion_batch_size: 2,
|
||||
max_total_attachments: 6,
|
||||
total_attachment_count: 5,
|
||||
eligible_attachment_count: 4,
|
||||
selected_attachment_count: 2,
|
||||
planned_attachment_count: 4,
|
||||
pending_expansion_attachment_count: 2,
|
||||
pending_expansion_batches: { '2': 2 },
|
||||
skipped_attachment_count: 1,
|
||||
duplicate_attachment_count: 1,
|
||||
budget_limited_attachment_count: 0,
|
||||
group_count: 2,
|
||||
},
|
||||
current_activity: { unit_id: 7, file_name: 'PO-1.pdf', event_code: 'profile_matching' },
|
||||
summary: {
|
||||
total_documents: 3,
|
||||
pending_documents: 0,
|
||||
processing_documents: 1,
|
||||
completed_documents: 2,
|
||||
review_required_documents: 0,
|
||||
failed_documents: 0,
|
||||
candidate_count: 2,
|
||||
},
|
||||
}))).toMatchObject({
|
||||
status: 'extracting', terminal: false, phase: 'llm_extraction',
|
||||
current_stage_code: 'document_processing', health: 'normal',
|
||||
last_activity_at: '2026-07-21T03:24:51Z',
|
||||
status: 'processing',
|
||||
terminal: false,
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
processingDocuments: 1,
|
||||
completedDocuments: 2,
|
||||
candidateCount: 2,
|
||||
},
|
||||
selectionPlan: {
|
||||
expansionBatchSize: 2,
|
||||
maxTotalAttachments: 6,
|
||||
plannedAttachmentCount: 4,
|
||||
pendingExpansionAttachmentCount: 2,
|
||||
pendingExpansionBatches: { '2': 2 },
|
||||
},
|
||||
currentActivity: { unitId: 7, fileName: 'PO-1.pdf', eventCode: 'profile_matching' },
|
||||
});
|
||||
});
|
||||
|
||||
it('persists a changed progress projection even when Run status and result are unchanged', async () => {
|
||||
it('persists a changed summary projection even when Run status is unchanged', async () => {
|
||||
vi.useFakeTimers();
|
||||
const first = run({
|
||||
run_no: 'SNER-PROGRESS',
|
||||
status: 'running',
|
||||
progress: { version: 1, current_stage_code: 'workflow_accepted' },
|
||||
status: 'processing',
|
||||
current_activity: { unit_id: 1, file_name: 'PO-A.pdf', event_code: 'document_queued' },
|
||||
});
|
||||
const second = run({
|
||||
run_no: 'SNER-PROGRESS',
|
||||
status: 'running',
|
||||
progress: { version: 2, current_stage_code: 'order_recognition' },
|
||||
status: 'processing',
|
||||
current_activity: { unit_id: 1, file_name: 'PO-A.pdf', event_code: 'profile_matching' },
|
||||
summary: {
|
||||
total_documents: 2,
|
||||
pending_documents: 0,
|
||||
processing_documents: 1,
|
||||
completed_documents: 1,
|
||||
review_required_documents: 0,
|
||||
failed_documents: 0,
|
||||
candidate_count: 1,
|
||||
},
|
||||
});
|
||||
api.listRuns.mockResolvedValue({ items: [first] });
|
||||
api.getRun.mockResolvedValueOnce(second);
|
||||
@@ -229,14 +314,15 @@ describe('mapOrderExtractionRunToMessageState', () => {
|
||||
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');
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.currentActivity?.eventCode).toBe('profile_matching');
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.summary.completedDocuments).toBe(1);
|
||||
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 active = run({ run_no: 'SNER-DUPLICATE', status: 'processing' });
|
||||
const failed = run({
|
||||
run_no: 'SNER-DUPLICATE', status: 'failed', phase: 'failed', error: { code: 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_FAILED' },
|
||||
});
|
||||
@@ -262,8 +348,22 @@ describe('mapOrderExtractionRunToMessageState', () => {
|
||||
|
||||
it('refreshes Intake candidates and persists them on the terminal Run card without page reload', async () => {
|
||||
vi.useFakeTimers();
|
||||
const active = run({ run_no: 'SNER-REVIEW', status: 'running' });
|
||||
const terminal = run({ run_no: 'SNER-REVIEW', status: 'needs_review', result: { pending_count: 1 } });
|
||||
const active = run({ run_no: 'SNER-REVIEW', status: 'processing' });
|
||||
const terminal = run({
|
||||
run_no: 'SNER-REVIEW',
|
||||
status: 'review_required',
|
||||
summary: {
|
||||
total_documents: 1,
|
||||
pending_documents: 0,
|
||||
processing_documents: 0,
|
||||
completed_documents: 0,
|
||||
review_required_documents: 1,
|
||||
failed_documents: 0,
|
||||
candidate_count: 0,
|
||||
},
|
||||
result: { pending_count: 1 },
|
||||
available_actions: ['view_details', 'enter_manual_review'],
|
||||
});
|
||||
api.listRuns.mockResolvedValue({ items: [active] });
|
||||
api.getRun.mockResolvedValue(terminal);
|
||||
const harness = createHarness();
|
||||
@@ -287,22 +387,49 @@ describe('mapOrderExtractionRunToMessageState', () => {
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('maps completed result counters without guessing from text', () => {
|
||||
it('maps completed summaries without guessing from text', () => {
|
||||
expect(mapOrderExtractionRunToMessageState(run({
|
||||
status: 'completed',
|
||||
result: { batch_no: 'SB-1', created_count: 2, opened_existing_count: 1, pending_count: 0 },
|
||||
summary: {
|
||||
total_documents: 3,
|
||||
pending_documents: 0,
|
||||
processing_documents: 0,
|
||||
completed_documents: 3,
|
||||
review_required_documents: 0,
|
||||
failed_documents: 0,
|
||||
candidate_count: 3,
|
||||
},
|
||||
available_actions: ['view_details'],
|
||||
}))).toMatchObject({
|
||||
status: 'completed', terminal: true, batch_no: 'SB-1', created_count: 2, opened_existing_count: 1,
|
||||
status: 'completed',
|
||||
terminal: true,
|
||||
summary: { completedDocuments: 3, candidateCount: 3 },
|
||||
availableActions: ['view_details'],
|
||||
});
|
||||
});
|
||||
|
||||
it('maps needs_review and failed to distinct terminal states', () => {
|
||||
it('maps review_required and failed to distinct terminal states', () => {
|
||||
expect(mapOrderExtractionRunToMessageState(run({
|
||||
status: 'needs_review', result: { pending_count: 3 },
|
||||
}))).toMatchObject({ status: 'partially_completed', pending_count: 3, terminal: true });
|
||||
status: 'review_required',
|
||||
summary: {
|
||||
total_documents: 3,
|
||||
pending_documents: 0,
|
||||
processing_documents: 0,
|
||||
completed_documents: 0,
|
||||
review_required_documents: 3,
|
||||
failed_documents: 0,
|
||||
candidate_count: 0,
|
||||
},
|
||||
available_actions: ['view_details', 'enter_manual_review'],
|
||||
}))).toMatchObject({
|
||||
status: 'review_required',
|
||||
terminal: true,
|
||||
summary: { reviewRequiredDocuments: 3 },
|
||||
availableActions: ['view_details', 'enter_manual_review'],
|
||||
});
|
||||
expect(mapOrderExtractionRunToMessageState(run({
|
||||
status: 'failed', error: { code: 'X' },
|
||||
}))).toMatchObject({ status: 'failed', message: '', terminal: true });
|
||||
}))).toMatchObject({ status: 'failed', errorCode: 'X', terminal: true });
|
||||
});
|
||||
|
||||
it('acknowledges a terminal Run only after it is restored into the active conversation', async () => {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* 依赖:shipping.api Run 接口、chat.types、Vue refs。
|
||||
* 逻辑:发送处理器调用 startRun;本模块持久化本地消息并轮询 Run,终态后刷新 Intake、批次工作台与动作。
|
||||
*/
|
||||
import { onBeforeUnmount, type ComputedRef, type Ref } from 'vue';
|
||||
import { getCurrentInstance, onBeforeUnmount, type ComputedRef, type Ref } from 'vue';
|
||||
import {
|
||||
createWorkspaceShippingOrderExtractionRun,
|
||||
getWorkspaceShippingOrderExtractionRun,
|
||||
@@ -34,30 +34,80 @@ interface UseShippingOrderExtractionRunsOptions {
|
||||
t: (key: string, params?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
const ACTIVE_RUN_STATUSES = new Set(['queued', 'running', 'result_persisted']);
|
||||
const ACTIVE_RUN_STATUSES = new Set(['queued', 'processing']);
|
||||
|
||||
/** 把领域 Run 转为聊天组件既有的订单抽取状态卡契约。 */
|
||||
export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtractionRun): ShippingOrderExtractionState {
|
||||
const result = run.result || {};
|
||||
const failed = run.status === 'failed' || run.status === 'cancelled';
|
||||
const partial = run.status === 'needs_review';
|
||||
const completed = run.status === 'completed';
|
||||
return {
|
||||
status: failed ? 'failed' : partial ? 'partially_completed' : completed ? 'completed' : 'extracting',
|
||||
phase: failed ? 'failed' : run.status === 'result_persisted' ? 'result_persisted' : 'llm_extraction',
|
||||
// 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),
|
||||
non_shipping_count: Number(result.non_shipping_count || 0),
|
||||
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,
|
||||
status: run.status,
|
||||
summary: {
|
||||
totalDocuments: Number(run.summary?.total_documents || 0),
|
||||
pendingDocuments: Number(run.summary?.pending_documents || 0),
|
||||
processingDocuments: Number(run.summary?.processing_documents || 0),
|
||||
completedDocuments: Number(run.summary?.completed_documents || 0),
|
||||
reviewRequiredDocuments: Number(run.summary?.review_required_documents || 0),
|
||||
failedDocuments: Number(run.summary?.failed_documents || 0),
|
||||
candidateCount: Number(run.summary?.candidate_count || 0),
|
||||
},
|
||||
currentActivity: run.current_activity
|
||||
? {
|
||||
unitId: Number(run.current_activity.unit_id || 0),
|
||||
fileName: run.current_activity.file_name || null,
|
||||
eventCode: String(run.current_activity.event_code || ''),
|
||||
selectionBatch: run.current_activity.selection_batch != null
|
||||
? Number(run.current_activity.selection_batch || 0) || null
|
||||
: null,
|
||||
reasonCodes: Array.isArray(run.current_activity.reason_codes)
|
||||
? run.current_activity.reason_codes.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
}
|
||||
: null,
|
||||
selectionPlan: run.selection_plan
|
||||
? {
|
||||
selectionVersion: run.selection_plan.selection_version || null,
|
||||
maxInitialAttachments: Number(run.selection_plan.max_initial_attachments || 0),
|
||||
maxInitialConcurrency: Number(run.selection_plan.max_initial_concurrency || 0),
|
||||
expansionBatchSize: Number(run.selection_plan.expansion_batch_size || 0),
|
||||
maxTotalAttachments: Number(run.selection_plan.max_total_attachments || 0),
|
||||
totalAttachmentCount: Number(run.selection_plan.total_attachment_count || 0),
|
||||
eligibleAttachmentCount: Number(run.selection_plan.eligible_attachment_count || 0),
|
||||
selectedAttachmentCount: Number(run.selection_plan.selected_attachment_count || 0),
|
||||
plannedAttachmentCount: Number(run.selection_plan.planned_attachment_count || 0),
|
||||
pendingExpansionAttachmentCount: Number(run.selection_plan.pending_expansion_attachment_count || 0),
|
||||
pendingExpansionBatches: run.selection_plan.pending_expansion_batches || {},
|
||||
skippedAttachmentCount: Number(run.selection_plan.skipped_attachment_count || 0),
|
||||
duplicateAttachmentCount: Number(run.selection_plan.duplicate_attachment_count || 0),
|
||||
budgetLimitedAttachmentCount: Number(run.selection_plan.budget_limited_attachment_count || 0),
|
||||
groupCount: Number(run.selection_plan.group_count || 0),
|
||||
}
|
||||
: null,
|
||||
unitSummary: run.unit_summary
|
||||
? {
|
||||
totalUnits: Number(run.unit_summary.total_units || 0),
|
||||
selectedUnits: Number(run.unit_summary.selected_units || 0),
|
||||
retryingUnits: Number(run.unit_summary.retrying_units || 0),
|
||||
pendingRetryUnits: Number(run.unit_summary.pending_retry_units || 0),
|
||||
failedUnits: Number(run.unit_summary.failed_units || 0),
|
||||
reviewRequiredUnits: Number(run.unit_summary.review_required_units || 0),
|
||||
succeededUnits: Number(run.unit_summary.succeeded_units || 0),
|
||||
selectionBatches: run.unit_summary.selection_batches || {},
|
||||
reviewRequiredReasonCodes: Array.isArray(run.unit_summary.review_required_reason_codes)
|
||||
? [...run.unit_summary.review_required_reason_codes]
|
||||
: [],
|
||||
expansionTriggerReasonCodes: Array.isArray(run.unit_summary.expansion_trigger_reason_codes)
|
||||
? [...run.unit_summary.expansion_trigger_reason_codes]
|
||||
: [],
|
||||
technicalFailureReasonCodes: Array.isArray(run.unit_summary.technical_failure_reason_codes)
|
||||
? [...run.unit_summary.technical_failure_reason_codes]
|
||||
: [],
|
||||
}
|
||||
: null,
|
||||
availableActions: Array.isArray(run.available_actions) ? [...run.available_actions] : [],
|
||||
terminal: !ACTIVE_RUN_STATUSES.has(run.status),
|
||||
refreshFailed: false,
|
||||
errorCode: run.error?.code || null,
|
||||
startedAt: run.started_at || null,
|
||||
finishedAt: run.finished_at || null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -80,6 +130,20 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
pollGeneration += 1;
|
||||
};
|
||||
|
||||
/** 网络轮询失败只更新本地提示,不得把后台业务 Run 误判为失败。 */
|
||||
const setRunRefreshFailed = (runNo: string, refreshFailed: boolean) => {
|
||||
const normalizedRunNo = String(runNo || '').trim();
|
||||
if (!normalizedRunNo) return;
|
||||
for (const message of options.messages.value) {
|
||||
const payload = message.payload && typeof message.payload === 'object' ? message.payload as Record<string, unknown> : {};
|
||||
if (payload.order_extraction_run_no !== normalizedRunNo || !message.shipping_order_extraction_state) continue;
|
||||
message.shipping_order_extraction_state = {
|
||||
...message.shipping_order_extraction_state,
|
||||
refreshFailed,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 查找或创建当前 Run 的助手状态消息,仅在业务状态真正变化时持久化。
|
||||
* @param run - 用户态 Run 摘要,不包含 Provider 快照或原始文档。
|
||||
@@ -122,7 +186,16 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
order_extraction_reparse: run.reparse || null,
|
||||
shipping_order_extraction_review: reviewAttachments || [],
|
||||
};
|
||||
const signature = JSON.stringify({ status: run.status, phase: run.phase, result: run.result, error: run.error, progress: run.progress, reparse: run.reparse, reviewAttachments });
|
||||
const signature = JSON.stringify({
|
||||
status: run.status,
|
||||
summary: run.summary,
|
||||
current_activity: run.current_activity,
|
||||
available_actions: run.available_actions,
|
||||
result: run.result,
|
||||
error: run.error,
|
||||
reparse: run.reparse,
|
||||
reviewAttachments,
|
||||
});
|
||||
if (persistedSignatures.get(run.run_no) !== signature) {
|
||||
const persisted = await options.saveLocalMessageToBackend(message);
|
||||
if (persisted) persistedSignatures.set(run.run_no, signature);
|
||||
@@ -203,6 +276,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
const run = await getWorkspaceShippingOrderExtractionRun(runNo, request.signal).finally(request.release);
|
||||
if (generation !== pollGeneration || activeRunNo !== runNo) return;
|
||||
pollFailureCount = 0;
|
||||
setRunRefreshFailed(run.run_no, false);
|
||||
if (!ACTIVE_RUN_STATUSES.has(run.status)) {
|
||||
const reviewAttachments = await refreshTerminalFacts(run);
|
||||
if (generation !== pollGeneration || activeRunNo !== runNo) return;
|
||||
@@ -218,6 +292,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
} catch {
|
||||
if (generation !== pollGeneration || activeRunNo !== runNo) return;
|
||||
pollFailureCount += 1;
|
||||
setRunRefreshFailed(runNo, true);
|
||||
const delayMs = Math.min(15000, 2000 * (2 ** Math.min(pollFailureCount, 3)));
|
||||
pollTimer = setTimeout(() => void pollRun(runNo, generation), delayMs);
|
||||
}
|
||||
@@ -233,7 +308,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
|
||||
/**
|
||||
* 启动订单抽取后台 Run,并把用户操作和状态卡持久化到本地会话。
|
||||
* @param query - 用户本次展示文本;不发送给 Dify Chatflow。
|
||||
* @param query - 用户本次备注;允许为空,不发送给 Dify Chatflow。
|
||||
* @param intakeNos - 本次冻结的 Intake 编号。
|
||||
* @param attachments - 用户消息中的安全附件快照。
|
||||
* @returns Run 已成功创建或幂等复用时为 true。
|
||||
@@ -242,12 +317,14 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
query: string,
|
||||
intakeNos: string[],
|
||||
attachments: ChatMessageAttachment[],
|
||||
uploadBatchId?: string,
|
||||
): Promise<boolean> => {
|
||||
stopPolling();
|
||||
const response = await createWorkspaceShippingOrderExtractionRun({
|
||||
agent_id: options.currentAgentId.value,
|
||||
conversation_id: options.conversationId.value || undefined,
|
||||
intake_nos: intakeNos,
|
||||
upload_batch_id: uploadBatchId || '',
|
||||
});
|
||||
const run = response.run;
|
||||
if (!options.conversationId.value) options.conversationId.value = run.conversation_id;
|
||||
@@ -265,7 +342,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
},
|
||||
};
|
||||
options.messages.value.push(userMessage);
|
||||
await options.saveLocalMessageToBackend(userMessage, query);
|
||||
await options.saveLocalMessageToBackend(userMessage, query || undefined);
|
||||
await upsertRunMessage(run);
|
||||
await acknowledgeTerminalRunWhenVisible(run);
|
||||
await options.onConversationResolved(run.conversation_id);
|
||||
@@ -369,6 +446,6 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
}
|
||||
};
|
||||
|
||||
onBeforeUnmount(stopPolling);
|
||||
if (getCurrentInstance()) onBeforeUnmount(stopPolling);
|
||||
return { startRun, retryRun, reparseRun, restoreForConversation, stopPolling, updateCandidateReviewSnapshot, getActiveRunNo: () => activeRunNo };
|
||||
}
|
||||
@@ -21,23 +21,77 @@ export interface RetrieverResource {
|
||||
|
||||
export type ShippingOrderExtractionStatus = 'extracting' | 'completed' | 'partially_completed' | 'failed';
|
||||
|
||||
export type ShippingOrderExtractionStateStatus =
|
||||
| 'queued'
|
||||
| 'processing'
|
||||
| 'completed'
|
||||
| 'partially_completed'
|
||||
| 'review_required'
|
||||
| 'failed'
|
||||
| 'cancelled';
|
||||
|
||||
export interface ShippingOrderExtractionStateSummary {
|
||||
totalDocuments: number;
|
||||
pendingDocuments: number;
|
||||
processingDocuments: number;
|
||||
completedDocuments: number;
|
||||
reviewRequiredDocuments: number;
|
||||
failedDocuments: number;
|
||||
candidateCount: number;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionCurrentActivityState {
|
||||
unitId: number;
|
||||
fileName?: string | null;
|
||||
eventCode: string;
|
||||
selectionBatch?: number | null;
|
||||
reasonCodes?: string[];
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionSelectionPlanState {
|
||||
selectionVersion?: string | null;
|
||||
maxInitialAttachments?: number;
|
||||
maxInitialConcurrency?: number;
|
||||
expansionBatchSize?: number;
|
||||
maxTotalAttachments?: number;
|
||||
totalAttachmentCount?: number;
|
||||
eligibleAttachmentCount?: number;
|
||||
selectedAttachmentCount?: number;
|
||||
plannedAttachmentCount?: number;
|
||||
pendingExpansionAttachmentCount?: number;
|
||||
pendingExpansionBatches?: Record<string, number>;
|
||||
skippedAttachmentCount?: number;
|
||||
duplicateAttachmentCount?: number;
|
||||
budgetLimitedAttachmentCount?: number;
|
||||
groupCount?: number;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionUnitSummaryState {
|
||||
totalUnits?: number;
|
||||
selectedUnits?: number;
|
||||
retryingUnits?: number;
|
||||
pendingRetryUnits?: number;
|
||||
failedUnits?: number;
|
||||
reviewRequiredUnits?: number;
|
||||
succeededUnits?: number;
|
||||
selectionBatches?: Record<string, number>;
|
||||
reviewRequiredReasonCodes?: string[];
|
||||
expansionTriggerReasonCodes?: string[];
|
||||
technicalFailureReasonCodes?: string[];
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionState {
|
||||
status: ShippingOrderExtractionStatus;
|
||||
phase: 'llm_extraction' | 'result_persisted' | 'failed';
|
||||
message: string;
|
||||
created_count: number;
|
||||
opened_existing_count: number;
|
||||
pending_count: number;
|
||||
non_shipping_count: number;
|
||||
created_with_missing_fields_count: number;
|
||||
batch_no?: string | null;
|
||||
status: ShippingOrderExtractionStateStatus;
|
||||
summary: ShippingOrderExtractionStateSummary;
|
||||
currentActivity?: ShippingOrderExtractionCurrentActivityState | null;
|
||||
selectionPlan?: ShippingOrderExtractionSelectionPlanState | null;
|
||||
unitSummary?: ShippingOrderExtractionUnitSummaryState | null;
|
||||
availableActions: string[];
|
||||
terminal: boolean;
|
||||
/** 当前服务端阶段,仅用于状态卡展示。 */
|
||||
current_stage_code?: string | null;
|
||||
/** 服务端健康提示,不包含诊断详情。 */
|
||||
health?: 'normal' | 'slow' | 'idle' | string;
|
||||
last_activity_at?: string | null;
|
||||
started_at?: string | null;
|
||||
refreshFailed?: boolean;
|
||||
errorCode?: string | null;
|
||||
startedAt?: string | null;
|
||||
finishedAt?: string | null;
|
||||
}
|
||||
|
||||
/** 订单识别终态卡保存的候选审核快照,仅含用户可见业务字段。 */
|
||||
|
||||
@@ -526,6 +526,7 @@ export interface ShippingNoticeIntakeResponse {
|
||||
intake_no: string;
|
||||
asset_no?: string | null;
|
||||
conversation_id?: string | null;
|
||||
upload_batch_id?: string | null;
|
||||
parse_status: string;
|
||||
parser_version?: string;
|
||||
order_extraction_status?: string | null;
|
||||
@@ -620,13 +621,79 @@ export interface ShippingUploadAttempt {
|
||||
|
||||
export type ShippingOrderExtractionRunStatus =
|
||||
| 'queued'
|
||||
| 'running'
|
||||
| 'result_persisted'
|
||||
| 'processing'
|
||||
| 'completed'
|
||||
| 'needs_review'
|
||||
| 'partially_completed'
|
||||
| 'review_required'
|
||||
| 'failed'
|
||||
| 'cancelled';
|
||||
|
||||
export type ShippingOrderExtractionDocumentStatus =
|
||||
| 'pending'
|
||||
| 'routing'
|
||||
| 'matching_profile'
|
||||
| 'extracting'
|
||||
| 'merging_supplement'
|
||||
| 'candidate_ready'
|
||||
| 'review_required'
|
||||
| 'failed'
|
||||
| 'cancelled';
|
||||
|
||||
export interface ShippingOrderExtractionRunSummary {
|
||||
total_documents: number;
|
||||
pending_documents: number;
|
||||
processing_documents: number;
|
||||
completed_documents: number;
|
||||
review_required_documents: number;
|
||||
failed_documents: number;
|
||||
candidate_count: number;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionCurrentActivity {
|
||||
unit_id: number;
|
||||
file_name?: string | null;
|
||||
event_code: string;
|
||||
selection_batch?: number | null;
|
||||
reason_codes?: string[];
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionProfileSummary {
|
||||
code: string;
|
||||
name?: string | null;
|
||||
version: number;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionEmailSupplementResult {
|
||||
status: 'none' | 'merged' | 'conflict' | string;
|
||||
relation_codes: string[];
|
||||
conflict_count: number;
|
||||
reservation_id_status?: 'none' | 'merged' | 'conflict' | 'unavailable' | string;
|
||||
source_type_status?: 'none' | 'merged' | 'conflict' | 'unavailable' | string;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionDocumentResult {
|
||||
unit_id: number;
|
||||
document_id: number;
|
||||
file_name?: string | null;
|
||||
status: ShippingOrderExtractionDocumentStatus;
|
||||
selection_batch?: number | null;
|
||||
group_key?: string | null;
|
||||
retry_status?: string | null;
|
||||
technical_failure_reason_code?: string | null;
|
||||
budget_cost?: {
|
||||
initial_attachment_budget?: number;
|
||||
initial_concurrency_budget?: number;
|
||||
selected_in_batch?: number;
|
||||
} | null;
|
||||
po_number?: string | null;
|
||||
line_count: number;
|
||||
profile?: ShippingOrderExtractionProfileSummary | null;
|
||||
email_supplement: ShippingOrderExtractionEmailSupplementResult;
|
||||
reason_code?: string | null;
|
||||
review_details?: Array<{ line_number: number; field_code?: string | null; reason_code: string }>;
|
||||
available_actions: string[];
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionRun {
|
||||
run_no: string;
|
||||
agent_id: number;
|
||||
@@ -644,15 +711,43 @@ export interface ShippingOrderExtractionRun {
|
||||
reason?: string | null;
|
||||
superseded_at?: string | null;
|
||||
} | null;
|
||||
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;
|
||||
summary: ShippingOrderExtractionRunSummary;
|
||||
selection_plan?: {
|
||||
selection_version?: string | null;
|
||||
max_initial_attachments?: number;
|
||||
max_initial_concurrency?: number;
|
||||
expansion_batch_size?: number;
|
||||
max_total_attachments?: number;
|
||||
max_total_bytes?: number;
|
||||
max_runtime_seconds?: number;
|
||||
input_total_bytes?: number;
|
||||
planned_total_bytes?: number;
|
||||
total_attachment_count?: number;
|
||||
eligible_attachment_count?: number;
|
||||
selected_attachment_count?: number;
|
||||
planned_attachment_count?: number;
|
||||
pending_expansion_attachment_count?: number;
|
||||
pending_expansion_batches?: Record<string, number>;
|
||||
skipped_attachment_count?: number;
|
||||
duplicate_attachment_count?: number;
|
||||
budget_limited_attachment_count?: number;
|
||||
group_count?: number;
|
||||
} | null;
|
||||
unit_summary?: {
|
||||
total_units?: number;
|
||||
selected_units?: number;
|
||||
retrying_units?: number;
|
||||
pending_retry_units?: number;
|
||||
failed_units?: number;
|
||||
review_required_units?: number;
|
||||
succeeded_units?: number;
|
||||
selection_batches?: Record<string, number>;
|
||||
review_required_reason_codes?: string[];
|
||||
expansion_trigger_reason_codes?: string[];
|
||||
technical_failure_reason_codes?: string[];
|
||||
} | null;
|
||||
current_activity?: ShippingOrderExtractionCurrentActivity | null;
|
||||
available_actions: string[];
|
||||
result?: {
|
||||
batch_no?: string | null;
|
||||
created_count?: number;
|
||||
@@ -670,8 +765,12 @@ export interface ShippingOrderExtractionRun {
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionProgressEvent {
|
||||
stage_code: string;
|
||||
event_code: string;
|
||||
status: string;
|
||||
unit_id?: number | null;
|
||||
document_id?: number | null;
|
||||
reason_code?: string | null;
|
||||
summary?: Record<string, unknown> | null;
|
||||
occurred_at: string;
|
||||
}
|
||||
|
||||
@@ -680,6 +779,10 @@ export interface ShippingOrderExtractionRunCreateResponse {
|
||||
reused: boolean;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionDocumentsResponse {
|
||||
items: ShippingOrderExtractionDocumentResult[];
|
||||
}
|
||||
|
||||
export interface ShippingNoticeDocumentResponse {
|
||||
id: number;
|
||||
document_type: string;
|
||||
|
||||
@@ -102,6 +102,9 @@ export interface ShippingNoticeParseAttachmentSummary {
|
||||
size?: number;
|
||||
content_hash?: string;
|
||||
parse_status?: string;
|
||||
ready_for_extraction?: boolean;
|
||||
is_inline_resource?: boolean;
|
||||
catalog_reason?: string;
|
||||
/** 详情接口才有;状态轮询为瘦身摘要不含全文 */
|
||||
extracted_text?: string;
|
||||
/** 原始解析文本长度 */
|
||||
@@ -121,6 +124,8 @@ export interface ShippingNoticeParseEmailMeta {
|
||||
body_text?: string;
|
||||
body_text_length?: number;
|
||||
stored_body_text_length?: number;
|
||||
body_html_tables?: string[];
|
||||
body_html_table_count?: number;
|
||||
}
|
||||
|
||||
export interface ShippingNoticeParseSummary {
|
||||
@@ -130,6 +135,14 @@ export interface ShippingNoticeParseSummary {
|
||||
line_count?: number;
|
||||
warnings?: string[];
|
||||
parser_version?: string;
|
||||
eml_attachment_mode?: 'deep' | 'preview' | string;
|
||||
technical_failure?: boolean;
|
||||
preview_status?: 'ready_for_extraction' | 'directory_incomplete' | 'technical_failed' | string;
|
||||
ready_for_extraction?: boolean;
|
||||
attachment_directory_complete?: boolean;
|
||||
ready_attachment_count?: number;
|
||||
directory_only_attachment_count?: number;
|
||||
duplicate_attachment_count?: number;
|
||||
email?: ShippingNoticeParseEmailMeta;
|
||||
/** 发现的真实附件总数(含因上限未登记的) */
|
||||
attachment_count?: number;
|
||||
@@ -145,6 +158,8 @@ export type ShippingNoticePendingAttachment = {
|
||||
type: 'document';
|
||||
assetNo?: string;
|
||||
intakeNo?: string;
|
||||
/** 同一次文件选择生成的服务端上传批次,发送时用于拒绝历史附件混入。 */
|
||||
uploadBatchId?: string;
|
||||
uploadStatus: ShippingNoticeUploadStatus;
|
||||
parseStatus: ShippingNoticeParseStatus;
|
||||
uploadProgress: number;
|
||||
@@ -158,7 +173,7 @@ export type ShippingNoticePendingAttachment = {
|
||||
duplicate?: ShippingDuplicateResult;
|
||||
duplicateResolution?: ShippingDuplicateResolution;
|
||||
candidates?: ShippingNoticeCandidate[];
|
||||
/** 文档版面任务汇总;processing 时不得创建订单识别 Run。 */
|
||||
/** 文档版面任务汇总;上传快览不依赖该状态,真正的深度解析由发送后的 Run 驱动。 */
|
||||
layoutStatus?: 'processing' | 'completed' | 'not_required';
|
||||
layoutSummary?: {
|
||||
total: number;
|
||||
|
||||
@@ -71,8 +71,11 @@ describe('attachment card utils', () => {
|
||||
|
||||
it('preserves shipping parsing, failure and duplicate attention states', () => {
|
||||
expect(getAttachmentCardStatus(shippingAttachment({ parseStatus: 'parsing' })).state).toBe('processing');
|
||||
expect(getAttachmentCardStatus(shippingAttachment({ layoutStatus: 'processing' }))).toEqual({
|
||||
state: 'processing', labelKey: 'chat.attachment.layoutProcessing',
|
||||
expect(getAttachmentCardStatus(shippingAttachment({
|
||||
layoutStatus: 'processing',
|
||||
parseSummary: { preview_status: 'ready_for_extraction', ready_for_extraction: true },
|
||||
}))).toEqual({
|
||||
state: 'ready', labelKey: 'chat.shippingNoticeReady',
|
||||
});
|
||||
expect(getAttachmentCardStatus(shippingAttachment({ parseStatus: 'failed' }))).toEqual({
|
||||
state: 'failed', labelKey: 'chat.attachment.parseFailed',
|
||||
@@ -89,6 +92,29 @@ describe('attachment card utils', () => {
|
||||
expect(getAttachmentCardStatus(shippingAttachment()).state).toBe('ready');
|
||||
});
|
||||
|
||||
it('surfaces preview directory issues without falling back to fake processing', () => {
|
||||
expect(getAttachmentCardStatus(shippingAttachment({
|
||||
parseSummary: {
|
||||
preview_status: 'directory_incomplete',
|
||||
ready_for_extraction: false,
|
||||
attachment_directory_complete: false,
|
||||
},
|
||||
}))).toEqual({
|
||||
state: 'attention',
|
||||
labelKey: 'chat.shippingNoticeAttachmentIncompleteWarn',
|
||||
});
|
||||
expect(getAttachmentCardStatus(shippingAttachment({
|
||||
parseSummary: {
|
||||
preview_status: 'technical_failed',
|
||||
technical_failure: true,
|
||||
ready_for_extraction: false,
|
||||
},
|
||||
}))).toEqual({
|
||||
state: 'failed',
|
||||
labelKey: 'chat.attachment.parseFailed',
|
||||
});
|
||||
});
|
||||
|
||||
it('shows the order extraction lifecycle separately from attachment parsing', () => {
|
||||
expect(getAttachmentCardStatus(shippingAttachment({ orderExtractionStatus: 'extracting' }))).toEqual({
|
||||
state: 'processing', labelKey: 'chat.shippingOrderExtractionProcessing',
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
import type { ChatMessageAttachment } from '../types/chat.types';
|
||||
import type { AttachmentUiStatus, PendingAttachment } from '../types/shipping.types';
|
||||
import { isShippingNoticeAttachmentParseIncomplete } from '../shipping/shippingNoticeAttachmentIntegrity';
|
||||
|
||||
export interface AttachmentCardStatus {
|
||||
state: AttachmentUiStatus;
|
||||
@@ -70,9 +71,6 @@ export function getAttachmentCardStatus(attachment: PendingAttachment): Attachme
|
||||
return { state: 'processing', labelKey: 'chat.attachment.processing' };
|
||||
}
|
||||
if (attachment.parseStatus === 'failed') return { state: 'failed', labelKey: 'chat.attachment.parseFailed' };
|
||||
if (attachment.layoutStatus === 'processing') {
|
||||
return { state: 'processing', labelKey: 'chat.attachment.layoutProcessing' };
|
||||
}
|
||||
const extractionStatus = String(attachment.orderExtractionStatus || '').trim().toLowerCase();
|
||||
if (extractionStatus === 'extracting') {
|
||||
return { state: 'processing', labelKey: 'chat.shippingOrderExtractionProcessing' };
|
||||
@@ -87,6 +85,13 @@ export function getAttachmentCardStatus(attachment: PendingAttachment): Attachme
|
||||
return { state: 'ready', labelKey: 'chat.shippingOrderExtractionCompleted' };
|
||||
}
|
||||
if (attachment.parseStatus === 'parsed' && !attachment.duplicateResolution?.action) {
|
||||
if (isShippingNoticeAttachmentParseIncomplete(attachment.parseSummary)) {
|
||||
const previewStatus = String(attachment.parseSummary?.preview_status || '').trim().toLowerCase();
|
||||
if (attachment.parseSummary?.technical_failure || previewStatus === 'technical_failed') {
|
||||
return { state: 'failed', labelKey: 'chat.attachment.parseFailed' };
|
||||
}
|
||||
return { state: 'attention', labelKey: 'chat.shippingNoticeAttachmentIncompleteWarn' };
|
||||
}
|
||||
if (attachment.duplicate?.blocking) {
|
||||
return { state: 'attention', labelKey: 'chat.shippingNoticeDuplicateBlockingBadge' };
|
||||
}
|
||||
@@ -95,7 +100,7 @@ export function getAttachmentCardStatus(attachment: PendingAttachment): Attachme
|
||||
}
|
||||
}
|
||||
if (attachment.parseStatus === 'parsed' || attachment.parseStatus === 'consumed') {
|
||||
return { state: 'ready', labelKey: 'chat.attachment.ready' };
|
||||
return { state: 'ready', labelKey: 'chat.shippingNoticeReady' };
|
||||
}
|
||||
return { state: 'pending', labelKey: 'chat.attachment.pending' };
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user