Merge branch 'hugo-shipping-notice' into dev

# Conflicts:
#	backend/app/api/__init__.py
#	backend/app/jobs/types.py
#	backend/app/models/__init__.py
#	backend/app/services/schedule/job_registry.py
#	docs/features/README.md
#	docs/funclist.md
#	docs/tec.md
#	frontend/src/locales/zh-CN/admin.json
This commit is contained in:
hugo committed 2026-09-07 10:15:13 +08:00
commit dac31e48bd
691 files changed
+53341 -14863

No files matched your search

@@ -85,6 +85,8 @@ const ProcurementContractPage = () =>
import("@/features/admin/modules/procurement-contract/ProcurementContractPage.vue");
const TrainingConfigPage = () =>
import("@/features/admin/modules/training-config/TrainingConfigPage.vue");
const IntegrationConnectorPage = () =>
import("@/features/admin/modules/integration-connector/IntegrationConnectorPage.vue");
export const adminRoutes: RouteRecordRaw[] = [
{
@@ -355,6 +357,16 @@ export const adminRoutes: RouteRecordRaw[] = [
title: "admin.nav.trainingConfig",
},
},
{
path: "integration-connector",
name: "AdminIntegrationConnector",
component: IntegrationConnectorPage,
meta: {
requiresAdmin: true,
adminModule: "integration_connector",
title: "admin.nav.integrationConnector",
},
},
{
path: "reports/:table?",
name: "AdminReports",
+1
View File
@@ -74,6 +74,7 @@ export const config = {
shipping_inventory: true, // 货代配置
procurement_contract: true, // 采购合同审查(模板库 + 历史)
training_config: true,
integration_connector: true, // 集成连接器配置
}
}
};
@@ -24,8 +24,6 @@ export type ShippingActionId = (typeof SHIPPING_ACTION_IDS)[number];
export const SHIPPING_KNOWN_ACTION_ID_SET = new Set<string>(SHIPPING_ACTION_IDS);
/** Backend state-machine codes — must never appear in user-visible chat text. */
export const SHIPPING_TERMINAL_CHECKPOINTS = new Set(['uploaded', 'completed', 'rejected']);
export const SHIPPING_INTERNAL_STATUS_TOKENS = [
'rpa_pending',
'upload_rpa_pending',
@@ -8,10 +8,6 @@
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import type {
ShippingOrderDerivationRule,
ShippingOrderDerivationSimulateRequest,
ShippingOrderDerivationSimulateResult,
ShippingOrderDerivationSimulateSampleItem,
ShippingOrderField,
ShippingOrderFieldConfig,
ShippingOrderSchemaAuditEventPage,
@@ -158,13 +154,12 @@ export const getShippingOrderExtractionAudit = (extractionId: number) =>
auth(),
);
/** 整体保存草稿字段配置、自动建单策略、派生规则及每个字段的版本纳入状态。 */
/** 整体保存草稿字段配置、自动建单策略及每个字段的版本纳入状态。 */
export const saveShippingOrderSchemaDraft = (
versionId: number,
payload: {
fields: ShippingOrderFieldConfig[];
auto_creation_policy?: { enabled: boolean };
derivation_rules?: ShippingOrderDerivationRule[];
change_note?: string;
expected_lock_version: number;
},
@@ -177,34 +172,6 @@ export const saveShippingOrderSchemaDraft = (
},
);
/**
* 对 Schema 版本派生规则做样本模拟(不改订单)。
* @param versionId - Schema 版本 ID
* @param payload - 样本行与可选规则覆盖 / sample_ref
*/
export const simulateShippingOrderSchemaDerivation = (
versionId: number,
payload: ShippingOrderDerivationSimulateRequest,
) =>
requestJson<ShippingOrderDerivationSimulateResult>(
`/api/admin/shipping-order-schema/versions/${versionId}/simulate-derivation`,
{
method: 'POST',
body: JSON.stringify(payload),
...jsonAuth(),
},
);
/**
* 列出可供派生规则模拟的历史 Extraction 样本。
* @param limit - 返回条数上限
*/
export const listShippingOrderSchemaDerivationSimulateSamples = (limit = 20) =>
requestJson<{ items: ShippingOrderDerivationSimulateSampleItem[] }>(
`/api/admin/shipping-order-schema/derivation-simulate-samples?limit=${limit}`,
auth(),
);
/** 删除错误草稿;发布版本由服务端拒绝删除。 */
export const deleteShippingOrderSchemaDraft = (versionId: number) =>
requestJson<void>(`/api/admin/shipping-order-schema/versions/${versionId}`, {
@@ -11,7 +11,7 @@ import { useRoute, useRouter } from 'vue-router';
import {
LayoutDashboard, UserPlus, UserCog, Building, Bot, FileText,
Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2, AppWindow,
ScrollText, ExternalLink, PackageSearch, GraduationCap,
ScrollText, ExternalLink, PackageSearch, GraduationCap, Cable,
} from 'lucide-vue-next';
import type { Component } from 'vue';
import { config } from '@/config';
@@ -44,6 +44,7 @@ const iconMap: Record<AdminModuleId, Component> = {
platform_apps: AppWindow,
procurement_contract: ScrollText,
training_config: GraduationCap,
integration_connector: Cable,
requests: ShieldCheck,
reports: BarChart2,
shipping_inventory: PackageSearch,
@@ -129,6 +130,8 @@ watch(
isShippingActive,
(active) => {
if (!active) return;
// 进入任一货代子路由时自动展开父菜单,保证当前子页可见。
navStore.shippingMenuExpanded = true;
let matched = false;
for (const groupKey of shippingGroups.value) {
const groupHasActiveSub = SHIPPING_CONFIG_SUB_MODULE_METAS.some(
@@ -210,14 +213,14 @@ watch(
type="button"
class="admin-nav-btn group justify-between"
:class="{ 'admin-nav-btn--active': isShippingActive }"
@click="navigateModule('AdminShippingInventory')"
@click="navStore.shippingMenuExpanded = !navStore.shippingMenuExpanded"
>
<div class="flex items-center gap-3">
<PackageSearch class="w-5 h-5 flex-shrink-0" :class="isShippingActive ? 'text-brand-600' : 'text-muted'" />
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t('admin.nav.shippingConfig') }}</span>
</div>
</button>
<div v-if="isShippingActive && !navStore.sidebarCollapsed" class="pl-4 space-y-1 mt-1 border-l-2 border-subtle ml-6">
<div v-if="navStore.shippingMenuExpanded && !navStore.sidebarCollapsed" class="pl-4 space-y-1 mt-1 border-l-2 border-subtle ml-6">
<div v-for="groupKey in shippingGroups" :key="groupKey" class="flex flex-col">
<button
type="button"
@@ -40,7 +40,7 @@ export interface ShippingConfigSubModuleMeta {
/** 已独立拆分的模块(全部 admin 模块均已拆分) */
export const STANDALONE_ADMIN_MODULES = new Set<AdminModuleId>([
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'linked_services', 'platform_apps', 'shipping_inventory', 'procurement_contract', 'reports','training_config'
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'linked_services', 'platform_apps', 'shipping_inventory', 'procurement_contract', 'reports','training_config', 'integration_connector'
]);
export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
@@ -60,6 +60,7 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
{ id: 'platform_apps', routeName: 'AdminPlatformApps', path: 'platform-apps', labelKey: 'admin.nav.platformApps', configKey: 'platform_apps' },
{ id: 'procurement_contract', routeName: 'AdminProcurementContract', path: 'procurement-contract', labelKey: 'admin.nav.procurementContract', configKey: 'procurement_contract' },
{ id: 'training_config', routeName: 'AdminTrainingConfig', path: 'training-config', labelKey: 'admin.nav.trainingConfig', configKey: 'training_config' },
{ id: 'integration_connector', routeName: 'AdminIntegrationConnector', path: 'integration-connector', labelKey: 'admin.nav.integrationConnector', configKey: 'integration_connector' },
{ id: 'requests', routeName: 'AdminRequests', path: 'requests', labelKey: 'admin.nav.requests', configKey: 'requests' },
];
@@ -0,0 +1,275 @@
<!--
features/admin/modules/integration-connector/IntegrationConnectorPage.vue
用途:集成连接器管理页——四个配置实体(客户端实例/接口定义/绑定/凭据引用)tab 列表 +
能力清单与手动调用测试;创建/编辑弹窗 + 连接测试。
依赖:useIntegrationConnectorAdmin、两个弹窗组件、useI18n。
逻辑:按 tab 展示列表与「新增」;配置「绑定」是让自动调拨跑起来的最小闭环核心。
-->
<script setup lang="ts">
import { computed, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Plus, Edit, Trash2, Plug, PlayCircle } from 'lucide-vue-next';
import IntegrationConnectorFormModal from './components/IntegrationConnectorFormModal.vue';
import IntegrationCapabilityCallModal from './components/IntegrationCapabilityCallModal.vue';
import { useIntegrationConnectorAdmin } from './composables/useIntegrationConnectorAdmin';
const { t } = useI18n();
const {
clients, interfaces, bindings, credentials, capabilities,
isLoading, activeEntity, showFormModal, isSaving,
clientForm, interfaceForm, bindingForm, credentialForm,
showCallModal, callCapability, callParamsText, callContextText, callResult, callBusy,
testResultText,
loadAll, openCreateModal, openEditModal, closeFormModal, saveActive,
testConnection, openCallModal, closeCallModal, runCall, deleteClient,
} = useIntegrationConnectorAdmin();
onMounted(() => { void loadAll(); });
type TabKey = 'client' | 'interface' | 'binding' | 'credential' | 'capability';
const tabs: Array<{ key: TabKey; labelKey: string }> = [
{ key: 'client', labelKey: 'admin.integrationConnector.tabs.client' },
{ key: 'interface', labelKey: 'admin.integrationConnector.tabs.interface' },
{ key: 'binding', labelKey: 'admin.integrationConnector.tabs.binding' },
{ key: 'credential', labelKey: 'admin.integrationConnector.tabs.credential' },
{ key: 'capability', labelKey: 'admin.integrationConnector.tabs.capability' },
];
const activeTab = computed<TabKey>(() => (activeEntity.value === 'credential' ? 'credential' : activeEntity.value));
const clientOptions = computed(() => clients.value.map((c) => ({ code: c.code, name: c.name })));
const interfaceOptions = computed(() => interfaces.value.map((i) => ({ code: i.code, name: i.name })));
const capabilityOptions = computed(() => capabilities.value.map((c) => ({ name: c.name })));
function selectTab(key: TabKey) {
// capability tab 只读展示,不进入表单实体;其余映射到可编辑实体。
if (key === 'capability') return;
activeEntity.value = key;
}
</script>
<template>
<section class="admin-table-section animate-fade-in-up">
<div class="admin-table-header admin-table-header--stacked">
<div>
<h2 class="section-title">{{ t('admin.integrationConnector.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.integrationConnector.subtitle') }}</p>
</div>
<button
v-if="activeTab !== 'capability'"
type="button"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
@click="openCreateModal(activeEntity)"
>
<Plus class="w-4 h-4" />
<span>{{ t('admin.integrationConnector.add') }}</span>
</button>
</div>
<div class="flex gap-1 border-b border-default" role="tablist">
<button
v-for="tab in tabs"
:key="tab.key"
type="button"
role="tab"
class="px-4 py-2.5 text-sm font-medium border-b-2 -mb-px transition-colors"
:class="activeTab === tab.key ? 'border-brand-600 text-brand-600' : 'border-transparent text-muted hover:text-secondary'"
:aria-selected="activeTab === tab.key"
@click="selectTab(tab.key)"
>
{{ t(tab.labelKey) }}
</button>
</div>
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<!-- 客户端实例 -->
<div v-if="activeTab === 'client'" class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.code') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.name') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.connectorType') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.environment') }}</th>
<th class="px-6 py-4 text-right text-xs w-40">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="clients.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in clients" :key="row.code">
<td class="px-6 py-4 text-sm font-medium text-primary mono">{{ row.code }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.name }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.connector_type }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.environment }}</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<button type="button" class="p-2 rounded-lg text-muted hover:bg-brand-50 hover:text-brand-600" :title="t('admin.integrationConnector.test')" @click="testConnection(row.code)">
<Plug class="w-4 h-4" />
</button>
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('client', row)">
<Edit class="w-4 h-4" />
</button>
<button type="button" class="p-2 rounded-lg text-muted hover:bg-red-50 hover:text-red-600" :title="t('admin.delete')" @click="deleteClient(row.code)">
<Trash2 class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
<p v-if="testResultText" class="mt-3 rounded-lg bg-surface-soft p-3 text-xs font-mono text-secondary whitespace-pre-wrap break-all">{{ testResultText }}</p>
</div>
<!-- 接口定义 -->
<div v-else-if="activeTab === 'interface'" class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.code') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.name') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.clientInstance') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.status') }}</th>
<th class="px-6 py-4 text-right text-xs w-24">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="interfaces.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in interfaces" :key="row.code">
<td class="px-6 py-4 text-sm font-medium text-primary mono">{{ row.code }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.name }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.client_instance_code }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.status }}</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('interface', row)">
<Edit class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- 绑定 -->
<div v-else-if="activeTab === 'binding'" class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.capability') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.clientInstance') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.interfaceDef') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.status') }}</th>
<th class="px-6 py-4 text-right text-xs w-24">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="bindings.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in bindings" :key="row.id">
<td class="px-6 py-4 text-sm font-medium text-primary">{{ row.capability }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.client_instance_code }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.interface_definition_code }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.status }}</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('binding', row)">
<Edit class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- 凭据引用 -->
<div v-else-if="activeTab === 'credential'" class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.code') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.secretRef') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.secretProvider') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.status') }}</th>
<th class="px-6 py-4 text-right text-xs w-24">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="credentials.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in credentials" :key="row.code">
<td class="px-6 py-4 text-sm font-medium text-primary mono">{{ row.code }}</td>
<td class="px-6 py-4 text-sm text-secondary mono">{{ row.secret_ref }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.secret_provider }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.status }}</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('credential', row)">
<Edit class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- 能力清单 -->
<div v-else class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.name') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.write') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.idempotency') }}</th>
<th class="px-6 py-4 text-right text-xs w-28">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="capabilities.length === 0"><td colspan="4" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in capabilities" :key="row.name">
<td class="px-6 py-4 text-sm font-medium text-primary">{{ row.name }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.write ? 'yes' : 'no' }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.idempotency }}</td>
<td class="px-6 py-4 text-right">
<button type="button" class="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm font-medium text-brand-600 hover:bg-brand-50" @click="openCallModal(row.name)">
<PlayCircle class="w-4 h-4" />
{{ t('admin.integrationConnector.call') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<IntegrationConnectorFormModal
:visible="showFormModal"
:active-entity="activeEntity"
:client-form="clientForm"
:interface-form="interfaceForm"
:binding-form="bindingForm"
:credential-form="credentialForm"
:is-saving="isSaving"
:client-options="clientOptions"
:interface-options="interfaceOptions"
:capability-options="capabilityOptions"
@close="closeFormModal"
@save="saveActive"
/>
<IntegrationCapabilityCallModal
:visible="showCallModal"
:capability="callCapability"
:params-text="callParamsText"
:context-text="callContextText"
:result="callResult"
:busy="callBusy"
@close="closeCallModal"
@run="runCall"
/>
</section>
</template>
@@ -0,0 +1,105 @@
/**
* features/admin/modules/integration-connector/api/integration-connector.api.ts
* 集成连接器管理 API 客户端:客户端实例/接口定义/绑定/凭据引用 CRUD + 能力清单 + 连接测试。
* 依赖:@/shared/api/client(requestJson / BusinessError)、@/shared/utils/auth。
* 逻辑:薄封装后端 /api/integration-connector/* 全部端点;JSON 写请求带 Content-Type。
* 错误码(INTEGRATION.*)由 requestJson 解析到四语言文案。
*/
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import type {
IntegrationBindingRow,
IntegrationCallResultRow,
IntegrationCapabilityRow,
IntegrationClientInstanceRow,
IntegrationCredentialReferenceRow,
IntegrationInterfaceDefinitionRow,
} from '../types/integration-connector.types';
const BASE = '/api/integration-connector';
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
// ---- 能力清单与调用 ----
/** 能力清单(写/幂等/入出参 Schema)。 */
export const listIntegrationCapabilities = () =>
requestJson<IntegrationCapabilityRow[]>(`${BASE}/capabilities`, auth());
/** 手动调用一个已注册能力(入参 + 路由上下文)。 */
export const callIntegrationCapability = (capability: string, payload: { params?: Record<string, unknown>; context?: Record<string, unknown>; operation_id?: string; idempotency_key?: string }) =>
requestJson<IntegrationCallResultRow>(`${BASE}/capabilities/${encodeURIComponent(capability)}`, {
method: 'POST',
...jsonAuth(),
body: JSON.stringify(payload),
});
// ---- 客户端实例 ----
export const listIntegrationClientInstances = () =>
requestJson<IntegrationClientInstanceRow[]>(`${BASE}/client-instances`, auth());
export const createIntegrationClientInstance = (payload: Record<string, unknown>) =>
requestJson<IntegrationClientInstanceRow>(`${BASE}/client-instances`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
});
export const updateIntegrationClientInstance = (code: string, payload: Record<string, unknown>) =>
requestJson<IntegrationClientInstanceRow>(`${BASE}/client-instances/${encodeURIComponent(code)}`, {
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
});
export const deleteIntegrationClientInstance = (code: string) =>
requestJson(`${BASE}/client-instances/${encodeURIComponent(code)}`, { method: 'DELETE', ...auth() });
/** 连接测试(返回底层传输 raw 结果)。 */
export const testIntegrationClientConnection = (code: string) =>
requestJson<Record<string, unknown>>(`${BASE}/client-instances/${encodeURIComponent(code)}/test`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify({}),
});
// ---- 接口定义 ----
export const listIntegrationInterfaceDefinitions = () =>
requestJson<IntegrationInterfaceDefinitionRow[]>(`${BASE}/interface-definitions`, auth());
export const createIntegrationInterfaceDefinition = (payload: Record<string, unknown>) =>
requestJson<IntegrationInterfaceDefinitionRow>(`${BASE}/interface-definitions`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
});
export const updateIntegrationInterfaceDefinition = (code: string, payload: Record<string, unknown>) =>
requestJson<IntegrationInterfaceDefinitionRow>(`${BASE}/interface-definitions/${encodeURIComponent(code)}`, {
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
});
// ---- 绑定 ----
export const listIntegrationBindings = () =>
requestJson<IntegrationBindingRow[]>(`${BASE}/bindings`, auth());
export const createIntegrationBinding = (payload: Record<string, unknown>) =>
requestJson<IntegrationBindingRow>(`${BASE}/bindings`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
});
export const updateIntegrationBinding = (id: number, payload: Record<string, unknown>) =>
requestJson<IntegrationBindingRow>(`${BASE}/bindings/${id}`, {
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
});
// ---- 凭据引用 ----
export const listIntegrationCredentialReferences = () =>
requestJson<IntegrationCredentialReferenceRow[]>(`${BASE}/credential-references`, auth());
export const createIntegrationCredentialReference = (payload: Record<string, unknown>) =>
requestJson<IntegrationCredentialReferenceRow>(`${BASE}/credential-references`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
});
export const updateIntegrationCredentialReference = (code: string, payload: Record<string, unknown>) =>
requestJson<IntegrationCredentialReferenceRow>(`${BASE}/credential-references/${encodeURIComponent(code)}`, {
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
});
@@ -0,0 +1,59 @@
<!--
features/admin/modules/integration-connector/components/IntegrationCapabilityCallModal.vue
用途:手动调用一个已注册能力(输入 params / context JSON),展示调用结果与 trace。
依赖:showCallModal、callParamsText、callContextText、callResult、callBusy。
逻辑:由 IntegrationConnectorPage 打开;emit close/run。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { IntegrationCallResultRow } from '../types/integration-connector.types';
const props = defineProps<{
visible: boolean;
capability: string;
paramsText: string;
contextText: string;
result: IntegrationCallResultRow | null;
busy: boolean;
}>();
const emit = defineEmits<{
close: [];
run: [];
}>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
<div class="admin-modal-panel max-w-2xl max-h-[92vh] scale-100">
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
<h3 class="section-title">{{ t('admin.integrationConnector.callModal.title', { capability }) }}</h3>
<p class="section-desc mt-1">{{ t('admin.integrationConnector.callModal.hint') }}</p>
</div>
<div class="px-5 sm:px-8 py-5 space-y-4 overflow-y-auto">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.callModal.params') }}</label>
<textarea :value="props.paramsText" rows="6" class="input-field text-sm font-mono" spellcheck="false" readonly />
<p class="text-xs text-muted">{{ t('admin.integrationConnector.callModal.paramsHint') }}</p>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.callModal.context') }}</label>
<textarea :value="props.contextText" rows="4" class="input-field text-sm font-mono" spellcheck="false" readonly />
<p class="text-xs text-muted">{{ t('admin.integrationConnector.callModal.contextHint') }}</p>
</div>
<div v-if="result" class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.callModal.result') }}</label>
<pre class="rounded-lg bg-surface-soft p-3 text-xs font-mono text-secondary whitespace-pre-wrap break-all">{{ JSON.stringify(result, null, 2) }}</pre>
</div>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-70" :disabled="busy" @click="emit('run')">
{{ busy ? t('admin.integrationConnector.callModal.running') : t('admin.integrationConnector.callModal.run') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,96 @@
/**
* features/admin/modules/integration-connector/components/IntegrationConnectorFormModal.spec.ts
* 用途:锁定表单按连接器类型动态显示字段——REST 显示超时/HTTP方法/请求路径,
* SOAP 显示 WSDL;关键字段从 JSON 拆出独立输入框,JSON 收进高级配置折叠。
* 依赖:@vue/test-utils、i18n。
* 逻辑:切换 connector_type 后断言对应字段的可见性;高级配置折叠默认收起。
*/
import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import i18n from '@/i18n';
import IntegrationConnectorFormModal from './IntegrationConnectorFormModal.vue';
import {
createEmptyClientInstanceForm,
createEmptyInterfaceDefinitionForm,
createEmptyBindingForm,
createEmptyCredentialReferenceForm,
} from '../types/integration-connector.types';
function mountModal() {
return mount(IntegrationConnectorFormModal, {
props: {
visible: true,
activeEntity: 'client',
clientForm: createEmptyClientInstanceForm(),
interfaceForm: createEmptyInterfaceDefinitionForm(),
bindingForm: createEmptyBindingForm(),
credentialForm: createEmptyCredentialReferenceForm(),
isSaving: false,
clientOptions: [],
interfaceOptions: [],
capabilityOptions: [],
},
global: { plugins: [i18n] },
});
}
describe('IntegrationConnectorFormModal connector-type fields', () => {
it('REST 默认显示接口地址与超时字段', () => {
const wrapper = mountModal();
expect(wrapper.find('[data-testid="client-endpoint"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="client-timeout"]').exists()).toBe(true);
});
it('切换到 SOAP 后连接地址 label 变为 WSDL,超时仍显示;同一 endpoint 字段', async () => {
const wrapper = mountModal();
await wrapper.find('[data-testid="client-connector-type"]').setValue('soap');
await wrapper.vm.$nextTick();
// 连接地址仍是同一 client-endpoint 字段,仅 label 变 WSDL
expect(wrapper.find('[data-testid="client-endpoint"]').exists()).toBe(true);
// 超时在 SOAP 下也显示
expect(wrapper.find('[data-testid="client-timeout"]').exists()).toBe(true);
const labels = wrapper.findAll('label').map((l) => l.text());
expect(labels.some((t) => t.includes('WSDL'))).toBe(true);
});
it('接口定义 REST 显示 HTTP 方法与请求路径', () => {
const wrapper = mount(IntegrationConnectorFormModal, {
props: {
visible: true,
activeEntity: 'interface',
clientForm: createEmptyClientInstanceForm(),
interfaceForm: createEmptyInterfaceDefinitionForm(),
bindingForm: createEmptyBindingForm(),
credentialForm: createEmptyCredentialReferenceForm(),
isSaving: false,
clientOptions: [],
interfaceOptions: [],
capabilityOptions: [],
},
global: { plugins: [i18n] },
});
const labels = wrapper.findAll('label').map((l) => l.text());
expect(labels.some((t) => t.includes('HTTP 方法'))).toBe(true);
expect(labels.some((t) => t.includes('请求路径'))).toBe(true);
});
it('绑定显示来源实例编码独立字段', () => {
const wrapper = mount(IntegrationConnectorFormModal, {
props: {
visible: true,
activeEntity: 'binding',
clientForm: createEmptyClientInstanceForm(),
interfaceForm: createEmptyInterfaceDefinitionForm(),
bindingForm: createEmptyBindingForm(),
credentialForm: createEmptyCredentialReferenceForm(),
isSaving: false,
clientOptions: [],
interfaceOptions: [],
capabilityOptions: [],
},
global: { plugins: [i18n] },
});
const labels = wrapper.findAll('label').map((l) => l.text());
expect(labels.some((t) => t.includes('来源实例编码'))).toBe(true);
});
});
@@ -0,0 +1,277 @@
<!--
features/admin/modules/integration-connector/components/IntegrationConnectorFormModal.vue
用途:集成连接器四实体(客户端实例/接口定义/绑定/凭据引用)创建与编辑弹窗。
依赖:activeEntity 对应的表单 state、useI18n。
逻辑:由 IntegrationConnectorPage 打开;按 activeEntity 渲染对应字段;提交 emit save。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type {
BindingFormState,
ClientInstanceFormState,
CredentialReferenceFormState,
InterfaceDefinitionFormState,
} from '../types/integration-connector.types';
const props = defineProps<{
visible: boolean;
activeEntity: 'client' | 'interface' | 'binding' | 'credential';
clientForm: ClientInstanceFormState;
interfaceForm: InterfaceDefinitionFormState;
bindingForm: BindingFormState;
credentialForm: CredentialReferenceFormState;
isSaving: boolean;
clientOptions: Array<{ code: string; name: string }>;
interfaceOptions: Array<{ code: string; name: string }>;
capabilityOptions: Array<{ name: string }>;
}>();
const emit = defineEmits<{
close: [];
save: [];
}>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
<div class="admin-modal-panel max-w-2xl max-h-[92vh] scale-100">
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
<h3 class="section-title">{{ t(`admin.integrationConnector.tabs.${activeEntity}`) }}</h3>
<p class="section-desc mt-1">{{ t('admin.integrationConnector.formHint') }}</p>
</div>
<div class="px-5 sm:px-8 py-5 space-y-5 overflow-y-auto">
<!-- 客户端实例 -->
<template v-if="activeEntity === 'client'">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.code') }}</label>
<input v-model="clientForm.code" type="text" class="input-field text-sm" :disabled="Boolean(clientForm.id)" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.name') }}</label>
<input v-model="clientForm.name" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.connectorType') }}</label>
<select v-model="clientForm.connector_type" class="input-field text-sm" data-testid="client-connector-type">
<option value="rest">rest</option>
<option value="soap">soap</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.environment') }}</label>
<input v-model="clientForm.environment" type="text" class="input-field text-sm" />
</div>
</div>
<!-- 连接地址:endpoint 合一字段;label 按连接器类型显示(REST=接口地址,SOAP=WSDL 地址) -->
<div class="space-y-1.5">
<label class="label-field">{{ clientForm.connector_type === 'soap' ? t('admin.integrationConnector.fields.wsdl') : t('admin.integrationConnector.fields.endpoint') }}</label>
<input v-model="clientForm.endpoint" type="text" class="input-field text-sm" :placeholder="t(clientForm.connector_type === 'soap' ? 'admin.integrationConnector.placeholders.wsdl' : 'admin.integrationConnector.placeholders.endpoint')" data-testid="client-endpoint" />
</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.timeout') }}</label>
<input v-model="clientForm.timeout_seconds" type="number" class="input-field text-sm" min="0" data-testid="client-timeout" />
</div>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.credentialRef') }}</label>
<input v-model="clientForm.credential_ref_code" type="text" class="input-field text-sm" />
</div>
<details class="rounded-lg border border-slate-200 px-3 py-2">
<summary class="cursor-pointer text-xs font-bold text-secondary">{{ t('admin.integrationConnector.advancedConfig') }}</summary>
<div class="mt-2 space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.configJson') }}</label>
<textarea v-model="clientForm.config_json" rows="6" class="input-field text-sm font-mono" spellcheck="false" />
</div>
</details>
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
<input v-model="clientForm.enabled" type="checkbox" class="w-4 h-4 rounded text-brand-600 border-default" />
{{ t('admin.integrationConnector.fields.enabled') }}
</label>
</template>
<!-- 接口定义 -->
<template v-else-if="activeEntity === 'interface'">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.code') }}</label>
<input v-model="interfaceForm.code" type="text" class="input-field text-sm" :disabled="Boolean(interfaceForm.id)" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.name') }}</label>
<input v-model="interfaceForm.name" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.clientInstance') }}</label>
<select v-model="interfaceForm.client_instance_code" class="input-field text-sm">
<option v-for="opt in clientOptions" :key="opt.code" :value="opt.code">{{ opt.code }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.connectorType') }}</label>
<select v-model="interfaceForm.connector_type" class="input-field text-sm">
<option value="rest">rest</option>
<option value="soap">soap</option>
</select>
</div>
</div>
<div v-if="interfaceForm.connector_type === 'rest'" class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.httpMethod') }}</label>
<select v-model="interfaceForm.http_method" class="input-field text-sm">
<option value="">—</option>
<option value="GET">GET</option>
<option value="POST">POST</option>
<option value="PUT">PUT</option>
<option value="DELETE">DELETE</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.requestPath') }}</label>
<input v-model="interfaceForm.request_path" type="text" class="input-field text-sm font-mono" :placeholder="t('admin.integrationConnector.placeholders.requestPath')" />
</div>
</div>
<details class="rounded-lg border border-slate-200 px-3 py-2">
<summary class="cursor-pointer text-xs font-bold text-secondary">{{ t('admin.integrationConnector.advancedConfig') }}</summary>
<div class="mt-2 grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.requestSpec') }}</label>
<textarea v-model="interfaceForm.request_spec_json" rows="5" class="input-field text-sm font-mono" spellcheck="false" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.inputSchema') }}</label>
<textarea v-model="interfaceForm.input_schema_json" rows="5" class="input-field text-sm font-mono" spellcheck="false" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.responseMapping') }}</label>
<textarea v-model="interfaceForm.response_mapping_json" rows="5" class="input-field text-sm font-mono" spellcheck="false" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.outputSchema') }}</label>
<textarea v-model="interfaceForm.output_schema_json" rows="5" class="input-field text-sm font-mono" spellcheck="false" />
</div>
</div>
</details>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.status') }}</label>
<select v-model="interfaceForm.status" class="input-field text-sm">
<option value="draft">draft</option>
<option value="published">published</option>
<option value="retired">retired</option>
</select>
</div>
<div class="flex items-end pb-1">
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
<input v-model="interfaceForm.enabled" type="checkbox" class="w-4 h-4 rounded text-brand-600 border-default" />
{{ t('admin.integrationConnector.fields.enabled') }}
</label>
</div>
</div>
</template>
<!-- 绑定 -->
<template v-else-if="activeEntity === 'binding'">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.capability') }}</label>
<select v-model="bindingForm.capability" class="input-field text-sm">
<option v-for="cap in capabilityOptions" :key="cap.name" :value="cap.name">{{ cap.name }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.environment') }}</label>
<input v-model="bindingForm.environment" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.clientInstance') }}</label>
<select v-model="bindingForm.client_instance_code" class="input-field text-sm">
<option v-for="opt in clientOptions" :key="opt.code" :value="opt.code">{{ opt.code }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.interfaceDef') }}</label>
<select v-model="bindingForm.interface_definition_code" class="input-field text-sm">
<option v-for="opt in interfaceOptions" :key="opt.code" :value="opt.code">{{ opt.code }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.mappingVersion') }}</label>
<input v-model.number="bindingForm.mapping_version" type="number" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.priority') }}</label>
<input v-model.number="bindingForm.priority" type="number" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.effectiveFrom') }}</label>
<input v-model="bindingForm.effective_from" type="datetime-local" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.effectiveTo') }}</label>
<input v-model="bindingForm.effective_to" type="datetime-local" class="input-field text-sm" />
</div>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.contextSourceCode') }}</label>
<input v-model="bindingForm.context_source_code" type="text" class="input-field text-sm" :placeholder="t('admin.integrationConnector.placeholders.contextSourceCode')" />
</div>
<details class="rounded-lg border border-slate-200 px-3 py-2">
<summary class="cursor-pointer text-xs font-bold text-secondary">{{ t('admin.integrationConnector.advancedConfig') }}</summary>
<div class="mt-2 space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.contextSelector') }}</label>
<textarea v-model="bindingForm.context_selector_json" rows="4" class="input-field text-sm font-mono" spellcheck="false" />
</div>
</details>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.status') }}</label>
<select v-model="bindingForm.status" class="input-field text-sm">
<option value="draft">draft</option>
<option value="published">published</option>
<option value="retired">retired</option>
</select>
</div>
</template>
<!-- 凭据引用 -->
<template v-else>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.code') }}</label>
<input v-model="credentialForm.code" type="text" class="input-field text-sm" :disabled="Boolean(credentialForm.id)" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.secretRef') }}</label>
<input v-model="credentialForm.secret_ref" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.secretProvider') }}</label>
<input v-model="credentialForm.secret_provider" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.credentialType') }}</label>
<input v-model="credentialForm.credential_type" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.status') }}</label>
<select v-model="credentialForm.status" class="input-field text-sm">
<option value="active">active</option>
<option value="rotating">rotating</option>
<option value="retired">retired</option>
</select>
</div>
</div>
</template>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-70" :disabled="isSaving" @click="emit('save')">
{{ isSaving ? t('admin.save') + '...' : t('admin.save') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,148 @@
/**
* features/admin/modules/integration-connector/composables/useIntegrationConnectorAdmin.spec.ts
* 用途:锁定集成连接器管理编排——四实体保存(create/update 分支)、JSON 字段解析校验、
* 必填校验拦截、能力调用与连接测试调用 API。
* 依赖:vi.mock(integration-connector.api)、@vue/test-utils、i18n。
* 逻辑:通过 setup 挂载 harness 组件访问 useIntegrationConnectorAdmin(useI18n 需在 setup 内);
* Mock API 断言 payload 构造与调用;非法 JSON 触发拦截且不调 API。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { defineComponent, h } from 'vue';
import { mount } from '@vue/test-utils';
import i18n from '@/i18n';
import { useIntegrationConnectorAdmin } from './useIntegrationConnectorAdmin';
const api = vi.hoisted(() => ({
listIntegrationClientInstances: vi.fn(),
createIntegrationClientInstance: vi.fn(),
updateIntegrationClientInstance: vi.fn(),
deleteIntegrationClientInstance: vi.fn(),
testIntegrationClientConnection: vi.fn(),
listIntegrationInterfaceDefinitions: vi.fn(),
createIntegrationInterfaceDefinition: vi.fn(),
updateIntegrationInterfaceDefinition: vi.fn(),
listIntegrationBindings: vi.fn(),
createIntegrationBinding: vi.fn(),
updateIntegrationBinding: vi.fn(),
listIntegrationCredentialReferences: vi.fn(),
createIntegrationCredentialReference: vi.fn(),
updateIntegrationCredentialReference: vi.fn(),
listIntegrationCapabilities: vi.fn(),
callIntegrationCapability: vi.fn(),
}));
vi.mock('@/features/admin/modules/integration-connector/api/integration-connector.api', () => api);
function makeHarness() {
let exposed: ReturnType<typeof useIntegrationConnectorAdmin> | null = null;
const Harness = defineComponent({
setup() {
exposed = useIntegrationConnectorAdmin();
return () => h('div');
},
});
mount(Harness, { global: { plugins: [i18n] } });
return exposed!;
}
describe('useIntegrationConnectorAdmin', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('loadAll 拉取五个列表', async () => {
api.listIntegrationClientInstances.mockResolvedValue([]);
api.listIntegrationInterfaceDefinitions.mockResolvedValue([]);
api.listIntegrationBindings.mockResolvedValue([]);
api.listIntegrationCredentialReferences.mockResolvedValue([]);
api.listIntegrationCapabilities.mockResolvedValue([]);
const c = makeHarness();
await c.loadAll();
expect(api.listIntegrationClientInstances).toHaveBeenCalled();
expect(api.listIntegrationCapabilities).toHaveBeenCalled();
});
it('新建客户端实例:关键字段独立列 + config_json 解析为对象并 POST', async () => {
const c = makeHarness();
c.openCreateModal('client');
c.clientForm.value.code = 'ERP-X';
c.clientForm.value.name = 'ERP X';
c.clientForm.value.endpoint = 'https://x.invalid';
c.clientForm.value.timeout_seconds = '90';
c.clientForm.value.config_json = '{"headers":{"X-Tenant":"A"}}';
await c.saveActive();
expect(api.createIntegrationClientInstance).toHaveBeenCalledWith({
code: 'ERP-X', name: 'ERP X', connector_type: 'rest', environment: 'prod',
endpoint: 'https://x.invalid', timeout_seconds: 90,
config_json: { headers: { 'X-Tenant': 'A' } }, credential_ref_code: null, enabled: true,
});
});
it('编辑客户端实例:有 id 走 PUT', async () => {
const c = makeHarness();
c.openEditModal('client', {
id: 1, code: 'ERP-X', name: 'old', connector_type: 'rest', environment: 'prod',
config_json: {}, credential_ref_code: null, enabled: true,
});
c.clientForm.value.name = 'new';
await c.saveActive();
expect(api.updateIntegrationClientInstance).toHaveBeenCalled();
});
it('非法 JSON 字段触发拦截且不调 API', async () => {
const c = makeHarness();
c.openCreateModal('client');
c.clientForm.value.code = 'ERP-X';
c.clientForm.value.name = 'ERP X';
c.clientForm.value.config_json = '{bad json';
await c.saveActive();
expect(api.createIntegrationClientInstance).not.toHaveBeenCalled();
});
it('客户端实例必填:缺 code 不调 API', async () => {
const c = makeHarness();
c.openCreateModal('client');
c.clientForm.value.name = 'ERP X';
await c.saveActive();
expect(api.createIntegrationClientInstance).not.toHaveBeenCalled();
});
it('绑定:必填校验与 POST payload', async () => {
const c = makeHarness();
c.openCreateModal('binding');
c.bindingForm.value.capability = 'in_transit_transfer.query_inventory';
c.bindingForm.value.client_instance_code = 'CLI-A';
c.bindingForm.value.interface_definition_code = 'IF-A';
await c.saveActive();
expect(api.createIntegrationBinding).toHaveBeenCalledWith({
capability: 'in_transit_transfer.query_inventory', context_selector_json: {},
context_source_code: null,
client_instance_code: 'CLI-A', interface_definition_code: 'IF-A',
mapping_version: 1, priority: 0, environment: 'prod',
effective_from: null, effective_to: null, status: 'draft',
});
});
it('凭据引用:创建 payload 不含明文 secret', async () => {
const c = makeHarness();
c.openCreateModal('credential');
c.credentialForm.value.code = 'CRED-A';
c.credentialForm.value.secret_ref = 'IN_TRANSIT_ERP_PASSWORD';
await c.saveActive();
expect(api.createIntegrationCredentialReference).toHaveBeenCalledWith({
code: 'CRED-A', secret_ref: 'IN_TRANSIT_ERP_PASSWORD', secret_provider: 'env',
credential_type: 'password', status: 'active',
});
});
it('连接测试与能力调用走对应 API', async () => {
const c = makeHarness();
api.testIntegrationClientConnection.mockResolvedValue({ ok: true });
api.callIntegrationCapability.mockResolvedValue({ status: 'success', data: { found: true }, error_code: null, error_message: null, document_no: null, trace_id: null });
await c.testConnection('CLI-A');
expect(api.testIntegrationClientConnection).toHaveBeenCalledWith('CLI-A');
c.openCallModal('in_transit_transfer.query_inventory');
await c.runCall();
expect(api.callIntegrationCapability).toHaveBeenCalled();
});
});
@@ -0,0 +1,296 @@
/**
* features/admin/modules/integration-connector/composables/useIntegrationConnectorAdmin.ts
* 集成连接器管理编排:客户端实例/接口定义/绑定/凭据引用四实体列表与增改表单,
* 以及能力清单与手动调用测试。
* 依赖:integration-connector.api、types、useMessage、useI18n。
* 逻辑:各列表独立 loadAll;新增/编辑共用表单弹窗态(form.id 区分);能力测试
* 独立于配置表单(CapabilityCall 弹窗)。保存/删除后刷新对应列表。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '@/shared/composables/useMessage';
import {
callIntegrationCapability,
createIntegrationBinding,
createIntegrationClientInstance,
createIntegrationCredentialReference,
createIntegrationInterfaceDefinition,
deleteIntegrationClientInstance,
listIntegrationBindings,
listIntegrationCapabilities,
listIntegrationClientInstances,
listIntegrationCredentialReferences,
listIntegrationInterfaceDefinitions,
testIntegrationClientConnection,
updateIntegrationBinding,
updateIntegrationClientInstance,
updateIntegrationCredentialReference,
updateIntegrationInterfaceDefinition,
} from '../api/integration-connector.api';
import {
bindingRowToForm,
clientInstanceRowToForm,
createEmptyBindingForm,
createEmptyClientInstanceForm,
createEmptyCredentialReferenceForm,
createEmptyInterfaceDefinitionForm,
credentialReferenceRowToForm,
interfaceDefinitionRowToForm,
type BindingFormState,
type ClientInstanceFormState,
type CredentialReferenceFormState,
type IntegrationBindingRow,
type IntegrationCallResultRow,
type IntegrationCapabilityRow,
type IntegrationClientInstanceRow,
type IntegrationCredentialReferenceRow,
type IntegrationInterfaceDefinitionRow,
type InterfaceDefinitionFormState,
} from '../types/integration-connector.types';
type EditableEntity = 'client' | 'interface' | 'binding' | 'credential';
export function useIntegrationConnectorAdmin() {
const { t } = useI18n();
const msg = useMessage();
// ---- 列表与加载态 ----
const clients = ref<IntegrationClientInstanceRow[]>([]);
const interfaces = ref<IntegrationInterfaceDefinitionRow[]>([]);
const bindings = ref<IntegrationBindingRow[]>([]);
const credentials = ref<IntegrationCredentialReferenceRow[]>([]);
const capabilities = ref<IntegrationCapabilityRow[]>([]);
const isLoading = ref(true);
// ---- 表单弹窗态 ----
const activeEntity = ref<EditableEntity>('client');
const showFormModal = ref(false);
const isSaving = ref(false);
const clientForm = ref<ClientInstanceFormState>(createEmptyClientInstanceForm());
const interfaceForm = ref<InterfaceDefinitionFormState>(createEmptyInterfaceDefinitionForm());
const bindingForm = ref<BindingFormState>(createEmptyBindingForm());
const credentialForm = ref<CredentialReferenceFormState>(createEmptyCredentialReferenceForm());
// ---- 能力调用测试弹窗态 ----
const showCallModal = ref(false);
const callCapability = ref('');
const callParamsText = ref('');
const callContextText = ref('');
const callResult = ref<IntegrationCallResultRow | null>(null);
const callBusy = ref(false);
// ---- 连接测试 ----
const testingClientCode = ref('');
const testResultText = ref('');
const loadClients = async () => { clients.value = await listIntegrationClientInstances(); };
const loadInterfaces = async () => { interfaces.value = await listIntegrationInterfaceDefinitions(); };
const loadBindings = async () => { bindings.value = await listIntegrationBindings(); };
const loadCredentials = async () => { credentials.value = await listIntegrationCredentialReferences(); };
const loadCapabilities = async () => { capabilities.value = await listIntegrationCapabilities(); };
const loadAll = async () => {
isLoading.value = true;
try {
await Promise.all([loadClients(), loadInterfaces(), loadBindings(), loadCredentials(), loadCapabilities()]);
} catch (e) {
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isLoading.value = false;
}
};
const reloadOne = async (entity: EditableEntity) => {
if (entity === 'client') await loadClients();
else if (entity === 'interface') await loadInterfaces();
else if (entity === 'binding') await loadBindings();
else await loadCredentials();
};
// ---- 弹窗打开/关闭 ----
const openCreateModal = (entity: EditableEntity) => {
activeEntity.value = entity;
if (entity === 'client') clientForm.value = createEmptyClientInstanceForm();
else if (entity === 'interface') interfaceForm.value = createEmptyInterfaceDefinitionForm();
else if (entity === 'binding') bindingForm.value = createEmptyBindingForm();
else credentialForm.value = createEmptyCredentialReferenceForm();
showFormModal.value = true;
};
const openEditModal = (entity: EditableEntity, row: IntegrationClientInstanceRow | IntegrationInterfaceDefinitionRow | IntegrationBindingRow | IntegrationCredentialReferenceRow) => {
activeEntity.value = entity;
if (entity === 'client') clientForm.value = clientInstanceRowToForm(row as IntegrationClientInstanceRow);
else if (entity === 'interface') interfaceForm.value = interfaceDefinitionRowToForm(row as IntegrationInterfaceDefinitionRow);
else if (entity === 'binding') bindingForm.value = bindingRowToForm(row as IntegrationBindingRow);
else credentialForm.value = credentialReferenceRowToForm(row as IntegrationCredentialReferenceRow);
showFormModal.value = true;
};
const closeFormModal = () => {
showFormModal.value = false;
clientForm.value = createEmptyClientInstanceForm();
interfaceForm.value = createEmptyInterfaceDefinitionForm();
bindingForm.value = createEmptyBindingForm();
credentialForm.value = createEmptyCredentialReferenceForm();
};
/** 解析 JSON 文本;空串返回 {},非法 JSON 抛错并提示。 */
const parseJsonField = (text: string, fieldLabel: string): Record<string, unknown> => {
const trimmed = String(text || '').trim();
if (!trimmed) return {};
try {
const parsed = JSON.parse(trimmed);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
throw new Error('must be an object');
} catch {
msg.warning(t('admin.integrationConnector.msg.invalidJson', { field: fieldLabel }));
throw new Error('invalid JSON');
}
};
// ---- 保存 ----
const saveActive = async () => {
isSaving.value = true;
try {
if (activeEntity.value === 'client') {
const form = clientForm.value;
if (!form.code.trim() || !form.name.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillClient'));
return;
}
const configJson = parseJsonField(form.config_json, 'config_json');
const payload = {
code: form.code.trim(), name: form.name.trim(), connector_type: form.connector_type,
environment: form.environment,
endpoint: form.endpoint.trim() || null,
timeout_seconds: form.timeout_seconds.trim() ? Number(form.timeout_seconds) : null,
config_json: configJson,
credential_ref_code: form.credential_ref_code.trim() || null, enabled: form.enabled,
};
if (form.id) await updateIntegrationClientInstance(form.code, payload);
else await createIntegrationClientInstance(payload);
} else if (activeEntity.value === 'interface') {
const form = interfaceForm.value;
if (!form.code.trim() || !form.client_instance_code.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillInterface'));
return;
}
const payload = {
code: form.code.trim(), name: form.name.trim() || form.code.trim(),
client_instance_code: form.client_instance_code.trim(), connector_type: form.connector_type,
http_method: form.http_method.trim() || null,
request_path: form.request_path.trim() || null,
request_spec_json: parseJsonField(form.request_spec_json, 'request_spec_json'),
input_schema_json: parseJsonField(form.input_schema_json, 'input_schema_json'),
response_mapping_json: parseJsonField(form.response_mapping_json, 'response_mapping_json'),
output_schema_json: parseJsonField(form.output_schema_json, 'output_schema_json'),
status: form.status, enabled: form.enabled,
};
if (form.id) await updateIntegrationInterfaceDefinition(form.code, payload);
else await createIntegrationInterfaceDefinition(payload);
} else if (activeEntity.value === 'binding') {
const form = bindingForm.value;
if (!form.capability.trim() || !form.client_instance_code.trim() || !form.interface_definition_code.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillBinding'));
return;
}
const payload = {
capability: form.capability.trim(), context_selector_json: parseJsonField(form.context_selector_json, 'context_selector_json'),
context_source_code: form.context_source_code.trim() || null,
client_instance_code: form.client_instance_code.trim(), interface_definition_code: form.interface_definition_code.trim(),
mapping_version: Number(form.mapping_version || 1), priority: Number(form.priority || 0),
environment: form.environment, effective_from: form.effective_from || null, effective_to: form.effective_to || null,
status: form.status,
};
if (form.id) await updateIntegrationBinding(form.id, payload);
else await createIntegrationBinding(payload);
} else {
const form = credentialForm.value;
if (!form.code.trim() || !form.secret_ref.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillCredential'));
return;
}
const payload = {
code: form.code.trim(), secret_ref: form.secret_ref.trim(), secret_provider: form.secret_provider,
credential_type: form.credential_type, status: form.status,
};
if (form.id) await updateIntegrationCredentialReference(form.code, payload);
else await createIntegrationCredentialReference(payload);
}
closeFormModal();
await reloadOne(activeEntity.value);
msg.success(t('admin.integrationConnector.msg.saved'));
} catch (e) {
// parseJsonField 已在内部提示;这里兜底 API 错误。
if (!(e instanceof Error && e.message === 'invalid JSON')) {
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
} finally {
isSaving.value = false;
}
};
// ---- 连接测试 ----
const testConnection = async (code: string) => {
testingClientCode.value = code;
testResultText.value = '';
try {
const result = await testIntegrationClientConnection(code);
testResultText.value = JSON.stringify(result, null, 2);
msg.success(t('admin.integrationConnector.msg.testOk'));
} catch (e) {
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
testingClientCode.value = '';
}
};
// ---- 能力调用测试 ----
const openCallModal = (capability: string) => {
callCapability.value = capability;
callParamsText.value = JSON.stringify({ invoice_no: '', from_warehouse: '', to_warehouse: '', quantity: 0 }, null, 2);
callContextText.value = '{}';
callResult.value = null;
showCallModal.value = true;
};
const closeCallModal = () => {
showCallModal.value = false;
callResult.value = null;
};
const runCall = async () => {
callBusy.value = true;
try {
const params = parseJsonField(callParamsText.value, 'params');
const context = parseJsonField(callContextText.value, 'context');
callResult.value = await callIntegrationCapability(callCapability.value, { params, context });
} catch (e) {
if (!(e instanceof Error && e.message === 'invalid JSON')) {
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
} finally {
callBusy.value = false;
}
};
const deleteClient = async (code: string) => {
try {
await deleteIntegrationClientInstance(code);
await loadClients();
msg.success(t('admin.integrationConnector.msg.deleted'));
} catch (e) {
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
};
return {
clients, interfaces, bindings, credentials, capabilities,
isLoading, activeEntity, showFormModal, isSaving,
clientForm, interfaceForm, bindingForm, credentialForm,
showCallModal, callCapability, callParamsText, callContextText, callResult, callBusy,
testingClientCode, testResultText,
loadAll, openCreateModal, openEditModal, closeFormModal, saveActive,
testConnection, openCallModal, closeCallModal, runCall, deleteClient,
};
}
@@ -0,0 +1,287 @@
/**
* features/admin/modules/integration-connector/types/integration-connector.types.ts
* 集成连接器管理域类型:客户端实例、接口定义、绑定、凭据引用、能力清单、调用结果。
* 依赖:无(纯类型与表单构建函数)。
* 逻辑:与后端 /api/integration-connector/* 序列化契约对齐;JSON 配置字段以 Record 承载
* 具体结构由表单/JSON 编辑器负责,前端不硬编码外部系统差异。
*/
/** 连接器类型:与后端 CONNECTOR_TYPES 对齐。 */
export type IntegrationConnectorType = 'rest' | 'soap';
/** 配置状态:draft 草稿 / published 已发布 / retired 已退役。 */
export type IntegrationConfigStatus = 'draft' | 'published' | 'retired';
/** 凭据状态。 */
export type IntegrationCredentialStatus = 'active' | 'rotating' | 'retired';
/** 能力清单项(后端 capability 注册表)。 */
export interface IntegrationCapabilityRow {
name: string;
write: boolean;
idempotency: string;
input_schema: Record<string, unknown>;
output_schema: Record<string, unknown>;
}
/** 能力调用结果(后端 IntegrationCallResult 序列化)。 */
export interface IntegrationCallResultRow {
status: string;
data: Record<string, unknown> | null;
error_code: string | null;
error_message: string | null;
document_no: string | null;
trace_id: string | null;
}
/** 客户端实例(接口地址/凭据引用/连接配置)。 */
export interface IntegrationClientInstanceRow {
id: number;
code: string;
name: string;
connector_type: IntegrationConnectorType;
environment: string;
endpoint: string | null;
timeout_seconds: number | null;
config_json: Record<string, unknown>;
credential_ref_code: string | null;
enabled: boolean;
}
/** 接口定义(接口模板/入参字段/回传映射/出参 Schema)。 */
export interface IntegrationInterfaceDefinitionRow {
id: number;
code: string;
name: string;
client_instance_code: string;
connector_type: IntegrationConnectorType;
http_method: string | null;
request_path: string | null;
request_spec_json: Record<string, unknown>;
input_schema_json: Record<string, unknown>;
response_mapping_json: Record<string, unknown>;
output_schema_json: Record<string, unknown>;
version: number;
status: IntegrationConfigStatus;
enabled: boolean;
}
/** 绑定(能力 → 客户端 + 接口 + 映射版本)。 */
export interface IntegrationBindingRow {
id: number;
capability: string;
context_selector_json: Record<string, unknown>;
context_source_code: string | null;
client_instance_code: string;
interface_definition_code: string;
mapping_version: number;
priority: number;
environment: string;
effective_from: string | null;
effective_to: string | null;
status: IntegrationConfigStatus;
}
/** 凭据引用(只存 secret_ref,不落明文)。 */
export interface IntegrationCredentialReferenceRow {
id: number;
code: string;
secret_ref: string;
secret_provider: string;
credential_type: string;
version: number;
status: IntegrationCredentialStatus;
last_verified_at: string | null;
}
/** 客户端实例表单。 */
export interface ClientInstanceFormState {
id: number | null;
code: string;
name: string;
connector_type: IntegrationConnectorType;
environment: string;
endpoint: string;
timeout_seconds: string;
config_json: string;
credential_ref_code: string;
enabled: boolean;
}
/** 接口定义表单(JSON 字段以文本承载,提交时解析)。 */
export interface InterfaceDefinitionFormState {
id: number | null;
code: string;
name: string;
client_instance_code: string;
connector_type: IntegrationConnectorType;
http_method: string;
request_path: string;
request_spec_json: string;
input_schema_json: string;
response_mapping_json: string;
output_schema_json: string;
status: IntegrationConfigStatus;
enabled: boolean;
}
/** 绑定表单。 */
export interface BindingFormState {
id: number | null;
capability: string;
context_selector_json: string;
context_source_code: string;
client_instance_code: string;
interface_definition_code: string;
mapping_version: number;
priority: number;
environment: string;
effective_from: string;
effective_to: string;
status: IntegrationConfigStatus;
}
/** 凭据引用表单。 */
export interface CredentialReferenceFormState {
id: number | null;
code: string;
secret_ref: string;
secret_provider: string;
credential_type: string;
status: IntegrationCredentialStatus;
}
const toJsonText = (value: Record<string, unknown> | null | undefined): string => {
if (!value || Object.keys(value).length === 0) return '';
return JSON.stringify(value, null, 2);
};
/** 创建空的客户端实例表单。 */
export function createEmptyClientInstanceForm(): ClientInstanceFormState {
return {
id: null,
code: '',
name: '',
connector_type: 'rest',
environment: 'prod',
endpoint: '',
timeout_seconds: '60',
config_json: '',
credential_ref_code: '',
enabled: true,
};
}
/** 列表行回填为客户端实例编辑表单。 */
export function clientInstanceRowToForm(row: IntegrationClientInstanceRow): ClientInstanceFormState {
return {
id: row.id,
code: row.code,
name: row.name,
connector_type: row.connector_type,
environment: row.environment,
endpoint: row.endpoint ?? '',
timeout_seconds: String(row.timeout_seconds ?? ''),
config_json: toJsonText(row.config_json),
credential_ref_code: row.credential_ref_code ?? '',
enabled: Boolean(row.enabled),
};
}
/** 创建空的接口定义表单。 */
export function createEmptyInterfaceDefinitionForm(): InterfaceDefinitionFormState {
return {
id: null,
code: '',
name: '',
client_instance_code: '',
connector_type: 'rest',
http_method: '',
request_path: '',
request_spec_json: '',
input_schema_json: '',
response_mapping_json: '',
output_schema_json: '',
status: 'draft',
enabled: true,
};
}
/** 列表行回填为接口定义编辑表单。 */
export function interfaceDefinitionRowToForm(row: IntegrationInterfaceDefinitionRow): InterfaceDefinitionFormState {
return {
id: row.id,
code: row.code,
name: row.name,
client_instance_code: row.client_instance_code,
connector_type: row.connector_type,
http_method: row.http_method ?? '',
request_path: row.request_path ?? '',
request_spec_json: toJsonText(row.request_spec_json),
input_schema_json: toJsonText(row.input_schema_json),
response_mapping_json: toJsonText(row.response_mapping_json),
output_schema_json: toJsonText(row.output_schema_json),
status: row.status,
enabled: Boolean(row.enabled),
};
}
/** 创建空的绑定表单。 */
export function createEmptyBindingForm(): BindingFormState {
return {
id: null,
capability: '',
context_selector_json: '',
context_source_code: '',
client_instance_code: '',
interface_definition_code: '',
mapping_version: 1,
priority: 0,
environment: 'prod',
effective_from: '',
effective_to: '',
status: 'draft',
};
}
/** 列表行回填为绑定编辑表单。 */
export function bindingRowToForm(row: IntegrationBindingRow): BindingFormState {
return {
id: row.id,
capability: row.capability,
context_selector_json: toJsonText(row.context_selector_json),
context_source_code: row.context_source_code ?? '',
client_instance_code: row.client_instance_code,
interface_definition_code: row.interface_definition_code,
mapping_version: Number(row.mapping_version || 1),
priority: Number(row.priority || 0),
environment: row.environment,
effective_from: row.effective_from ?? '',
effective_to: row.effective_to ?? '',
status: row.status,
};
}
/** 创建空的凭据引用表单。 */
export function createEmptyCredentialReferenceForm(): CredentialReferenceFormState {
return {
id: null,
code: '',
secret_ref: '',
secret_provider: 'env',
credential_type: 'password',
status: 'active',
};
}
/** 列表行回填为凭据引用编辑表单。 */
export function credentialReferenceRowToForm(row: IntegrationCredentialReferenceRow): CredentialReferenceFormState {
return {
id: row.id,
code: row.code,
secret_ref: row.secret_ref,
secret_provider: row.secret_provider,
credential_type: row.credential_type,
status: row.status,
};
}
@@ -75,7 +75,8 @@ export function useOrderProfileValueAdapter(options: UseOrderProfileValueAdapter
const profileId = computed(() => Number(toValue(options.profileId) || 0));
const saveState = computed(() => toValue(options.saveState));
const readonly = computed(() => saveState.value === 'readonly');
const loading = ref(true);
// 坐标模板不会启用该 adapter;初始状态必须是非加载,避免共享画布误显示 XFA loading。
const loading = ref(false);
const loadError = ref(false);
const lockVersion = ref(0);
const schemaFields = ref<ShippingOrderFieldConfig[]>([]);
@@ -977,7 +978,10 @@ export function useOrderProfileValueAdapter(options: UseOrderProfileValueAdapter
const enabled = computed(() => toValue(options.enabled) !== false);
watch(enabled, (isEnabled) => {
if (isEnabled && profileId.value > 0) void load();
if (isEnabled && profileId.value > 0) {
loading.value = true;
void load();
}
}, { immediate: true });
watch(diagnosticsOpen, async (open) => {
@@ -3,7 +3,7 @@
用途:单一发货订单 Schema 的版本采用与版本级识别规则编辑;字段身份由全局字段资产库维护。
依赖:shipping-order-schema.api、shipping-field-assets.api、FieldImpactDrawer、版本/审计抽屉组件、Vue I18n。
逻辑:左侧勾选采用资产目录,右侧编辑已采用字段规则;草稿保存/发布与历史追溯由服务端冻结。无多族切换。
「Schema 级策略」分组收纳自动建单总开关与字段派生规则;仅草稿可改,随保存/发布生效;支持样本模拟。
「Schema 级策略」仅收纳自动建单总开关;订单项次由系统按单据内顺序生成。
-->
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
@@ -26,8 +26,6 @@ import {
listShippingOrderSchemaVersions,
publishShippingOrderSchemaDraft,
saveShippingOrderSchemaDraft,
simulateShippingOrderSchemaDerivation,
listShippingOrderSchemaDerivationSimulateSamples,
} from '@/features/admin/api/shipping-order-schema.api';
import FieldImpactDrawer from '@/features/admin/modules/shipping-field-assets/components/FieldImpactDrawer.vue';
import SchemaExtractionAuditDrawer from '@/features/admin/modules/shipping-order-schema/components/SchemaExtractionAuditDrawer.vue';
@@ -36,9 +34,6 @@ import SchemaVersionHistoryDrawer from '@/features/admin/modules/shipping-order-
import SchemaVersionUsageDrawer from '@/features/admin/modules/shipping-order-schema/components/SchemaVersionUsageDrawer.vue';
import type { ShippingFieldAsset, ShippingFieldAssetImpact } from '@/features/admin/types/shipping-field-assets.types';
import type {
ShippingOrderDerivationRule,
ShippingOrderDerivationSimulateResult,
ShippingOrderDerivationSimulateSampleItem,
ShippingOrderField,
ShippingOrderFieldConfig,
ShippingOrderExtractionAudit,
@@ -75,20 +70,6 @@ const autoCreationConfirmOpen = ref(false);
const pendingAutoCreationEnabled = ref(false);
const changeNote = ref('');
const selectedDraftFieldId = ref<string | null>(null);
const derivationRules = ref<ShippingOrderDerivationRule[]>([]);
const derivationPanelOpen = ref(true);
const simulateOpen = ref(false);
const simulating = ref(false);
const simulateMode = ref<'history' | 'inline'>('history');
const simulateSamples = ref<ShippingOrderDerivationSimulateSampleItem[]>([]);
const simulateSampleRef = ref('');
const simulateSamplesLoading = ref(false);
const simulateSampleJson = ref(`[
{"customer_po_line_no": "00010", "line_no": null},
{"customer_po_line_no": "00020", "line_no": "20"},
{"customer_po_line_no": "ABC", "line_no": null}
]`);
const simulateResult = ref<ShippingOrderDerivationSimulateResult | null>(null);
const fieldSearch = ref('');
const expandedGroups = reactive<Record<AdoptionGroupKey, boolean>>({
headerStandard: true,
@@ -271,19 +252,6 @@ const syncDraftFields = (): void => {
autoCreationEnabled.value = typeof draftPolicy === 'boolean'
? draftPolicy
: state.value?.schema?.auto_creation_policy?.enabled === true;
const sourceRules = draft.value?.definition?.derivation_rules
|| published.value?.definition?.derivation_rules
|| [];
derivationRules.value = sourceRules.length
? sourceRules.map((rule) => ({ ...rule }))
: [{
rule_id: 'R-LINE-NO-FROM-CUSTOMER-PO',
enabled: false,
source_field_code: 'customer_po_line_no',
target_field_code: 'line_no',
strategy: 'copy_if_empty',
scope: 'line',
}];
const existing = draft.value?.definition?.fields || published.value?.definition?.fields || [];
const byId = new Map(existing.map((item) => [item.field_id, item]));
draftFields.value = (state.value?.fields || [])
@@ -441,7 +409,7 @@ const toggleAdoption = (field: ShippingOrderField, enabled: boolean): void => {
}
};
/** 保存草稿的全部已采用字段规则、派生规则与自动建单策略;未采用字段不会进入发布契约。 */
/** 保存草稿的全部已采用字段规则与自动建单策略;订单项次不属于可编辑 Schema 配置。 */
const saveDraft = async (): Promise<void> => {
if (!draft.value) return;
saving.value = true;
@@ -450,16 +418,12 @@ const saveDraft = async (): Promise<void> => {
const saved = await saveShippingOrderSchemaDraft(draft.value.id, {
fields,
auto_creation_policy: { enabled: autoCreationEnabled.value },
derivation_rules: derivationRules.value.map((item) => ({ ...item })),
change_note: changeNote.value,
expected_lock_version: draft.value.lock_version,
});
if (state.value) {
state.value.versions = state.value.versions.map((item) => (item.id === saved.id ? saved : item));
}
if (saved.definition?.derivation_rules) {
derivationRules.value = saved.definition.derivation_rules.map((item) => ({ ...item }));
}
message.success(t('admin.shippingOrderSchema.draftSaved'));
} catch (error) {
await handleWriteError(error);
@@ -468,82 +432,6 @@ const saveDraft = async (): Promise<void> => {
}
};
/**
* 切换派生规则启用状态(仅草稿可改)。
* @param index - 规则下标
* @param event - checkbox 事件
*/
const onDerivationEnabledChange = (index: number, event: Event): void => {
if (!draft.value) return;
const checked = (event.target as HTMLInputElement).checked;
const current = derivationRules.value[index];
if (!current) return;
derivationRules.value[index] = { ...current, enabled: checked };
};
/**
* 打开派生规则模拟弹窗并加载历史 Extraction 样本列表。
*/
const openDerivationSimulate = async (): Promise<void> => {
simulateResult.value = null;
simulateMode.value = 'history';
simulateOpen.value = true;
simulateSamplesLoading.value = true;
try {
const response = await listShippingOrderSchemaDerivationSimulateSamples(20);
simulateSamples.value = response.items || [];
simulateSampleRef.value = simulateSamples.value[0]?.sample_ref || '';
if (!simulateSamples.value.length) {
simulateMode.value = 'inline';
}
} catch (error) {
await handleWriteError(error);
simulateMode.value = 'inline';
} finally {
simulateSamplesLoading.value = false;
}
};
/**
* 运行派生规则模拟:优先使用历史 Extraction 样本,亦可手工 JSON。
*/
const runDerivationSimulate = async (): Promise<void> => {
if (!draft.value && !published.value) return;
const versionId = draft.value?.id || published.value?.id;
if (!versionId) return;
simulating.value = true;
try {
if (simulateMode.value === 'history') {
if (!simulateSampleRef.value) {
message.error(t('admin.shippingOrderSchema.derivationSimulateSampleRequired'));
return;
}
simulateResult.value = await simulateShippingOrderSchemaDerivation(versionId, {
sample_ref: simulateSampleRef.value,
derivation_rules: derivationRules.value,
});
return;
}
const lines = JSON.parse(simulateSampleJson.value) as Array<Record<string, string | number | null>>;
if (!Array.isArray(lines)) {
throw new Error('invalid sample');
}
simulateResult.value = await simulateShippingOrderSchemaDerivation(versionId, {
lines,
derivation_rules: derivationRules.value,
sample_ref: 'schema-admin-inline-sample',
});
} catch (error) {
if (error instanceof SyntaxError || (error instanceof Error && error.message === 'invalid sample')) {
message.error(t('admin.shippingOrderSchema.derivationSimulateSampleInvalid'));
} else {
await handleWriteError(error);
}
} finally {
simulating.value = false;
}
};
/**
* 拦截自动建单开关变更:仅草稿可改,且须二次确认;确认后仅写入本地,随保存草稿/发布生效。
* @param event - checkbox change 事件
@@ -1049,48 +937,6 @@ onMounted(async () => {
</label>
<p class="schema-gate-note">{{ t('admin.shippingOrderSchema.effectiveReservationGate') }}</p>
<details class="derivation-panel" :open="derivationPanelOpen" @toggle="derivationPanelOpen = ($event.target as HTMLDetailsElement).open">
<summary>
<strong>{{ t('admin.shippingOrderSchema.derivationRulesTitle') }}</strong>
<span>{{ t('admin.shippingOrderSchema.derivationRulesHint') }}</span>
</summary>
<div class="derivation-toolbar">
<button
type="button"
class="btn-secondary btn-sm"
:disabled="simulating || (!draft && !published)"
@click="openDerivationSimulate"
>
{{ t('admin.shippingOrderSchema.derivationSimulate') }}
</button>
</div>
<table class="derivation-table">
<thead>
<tr>
<th>{{ t('admin.shippingOrderSchema.derivationEnabled') }}</th>
<th>{{ t('admin.shippingOrderSchema.derivationSource') }}</th>
<th>{{ t('admin.shippingOrderSchema.derivationTarget') }}</th>
<th>{{ t('admin.shippingOrderSchema.derivationStrategy') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(rule, index) in derivationRules" :key="rule.rule_id">
<td>
<input
type="checkbox"
:checked="rule.enabled"
:disabled="!draft || saving"
@change="onDerivationEnabledChange(index, $event)"
>
</td>
<td><code>{{ rule.source_field_code }}</code></td>
<td><code>{{ rule.target_field_code }}</code></td>
<td>{{ t('admin.shippingOrderSchema.derivationStrategyCopyIfEmpty') }}</td>
</tr>
</tbody>
</table>
<p class="derivation-note">{{ t('admin.shippingOrderSchema.derivationRulesNote') }}</p>
</details>
</section>
<div class="schema-workbench">
@@ -1508,96 +1354,6 @@ onMounted(async () => {
</section>
</div>
<div v-if="simulateOpen" class="impact-overlay" @click.self="simulateOpen = false">
<section class="impact-dialog derivation-simulate-dialog">
<header>
<h2>{{ t('admin.shippingOrderSchema.derivationSimulateTitle') }}</h2>
<button type="button" class="btn-ghost btn-sm" @click="simulateOpen = false">{{ t('common.close') }}</button>
</header>
<p class="simulate-hint">{{ t('admin.shippingOrderSchema.derivationSimulateNoMutate') }}</p>
<div class="simulate-mode-row">
<label>
<input v-model="simulateMode" type="radio" value="history">
{{ t('admin.shippingOrderSchema.derivationSimulateModeHistory') }}
</label>
<label>
<input v-model="simulateMode" type="radio" value="inline">
{{ t('admin.shippingOrderSchema.derivationSimulateModeInline') }}
</label>
</div>
<label v-if="simulateMode === 'history'" class="simulate-sample">
<span>{{ t('admin.shippingOrderSchema.derivationSimulateHistorySample') }}</span>
<select v-model="simulateSampleRef" :disabled="simulateSamplesLoading || !simulateSamples.length">
<option disabled value="">
{{ simulateSamplesLoading
? t('admin.shippingOrderSchema.derivationSimulateSamplesLoading')
: t('admin.shippingOrderSchema.derivationSimulateSamplesEmpty') }}
</option>
<option
v-for="item in simulateSamples"
:key="item.sample_ref"
:value="item.sample_ref"
>
{{ t('admin.shippingOrderSchema.derivationSimulateSampleOption', {
id: item.extraction_id,
lines: item.line_count,
status: item.status,
}) }}
</option>
</select>
</label>
<label v-else class="simulate-sample">
<span>{{ t('admin.shippingOrderSchema.derivationSimulateSample') }}</span>
<textarea v-model="simulateSampleJson" rows="8" />
</label>
<footer>
<button type="button" class="btn-secondary" @click="simulateOpen = false">{{ t('common.cancel') }}</button>
<button type="button" class="btn-primary" :disabled="simulating" @click="runDerivationSimulate">
{{ t('admin.shippingOrderSchema.derivationSimulateRun') }}
</button>
</footer>
<div v-if="simulateResult" class="simulate-result">
<p>
{{ t('admin.shippingOrderSchema.derivationSimulateSummary', {
version: simulateResult.schema_version,
checksum: simulateResult.rules_checksum.slice(0, 12),
derived: simulateResult.derived_count,
skipped: simulateResult.skipped_count,
}) }}
</p>
<div class="simulate-result-scroll" data-testid="derivation-simulate-result-scroll">
<table class="derivation-table">
<thead>
<tr>
<th>#</th>
<th>{{ t('admin.shippingOrderSchema.derivationSource') }}</th>
<th>{{ t('admin.shippingOrderSchema.derivationBefore') }}</th>
<th>{{ t('admin.shippingOrderSchema.derivationAfter') }}</th>
<th>{{ t('admin.shippingOrderSchema.derivationResult') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in simulateResult.results" :key="`${row.line_index}-${row.rule_id}`">
<td>{{ row.line_index + 1 }}</td>
<td>{{ row.before_source ?? '—' }}</td>
<td>{{ row.before_target ?? '—' }}</td>
<td>{{ row.after_target ?? '—' }}</td>
<td>
<template v-if="row.status === 'derived'">
{{ t('admin.shippingOrderSchema.derivationStatusDerived') }}
</template>
<template v-else>
{{ t('admin.shippingOrderSchema.derivationStatusSkipped', { reason: row.skip_reason || '' }) }}
</template>
</td>
</tr>
</tbody>
</table>
</div>
<p class="muted">{{ t('admin.shippingOrderSchema.derivationSimulateNoMutate') }}</p>
</div>
</section>
</div>
<div v-if="profileImpactOpen && profileImpact" class="impact-overlay" @click.self="profileImpactOpen = false">
<section class="impact-dialog">
@@ -1725,38 +1481,6 @@ onMounted(async () => {
.auto-creation-switch small { color: #64748b; font-size: 11px; }
.auto-creation-effective { display: block; color: #0f766e; }
.schema-gate-note { margin: 0 0 12px; color: #475569; font-size: 12px; line-height: 1.5; }
.derivation-panel { margin: 0 0 8px; border: 1px solid #dbe6ef; border-radius: 8px; background: #fff; padding: 12px 14px; }
.derivation-panel summary { cursor: pointer; display: grid; gap: 4px; color: #334155; }
.derivation-panel summary span { color: #64748b; font-size: 12px; }
.derivation-toolbar { display: flex; justify-content: flex-end; margin: 12px 0; }
.derivation-table { width: 100%; border-collapse: collapse; font-size: 12px; }
.derivation-table th, .derivation-table td { border-bottom: 1px solid #e2e8f0; padding: 8px 6px; text-align: left; vertical-align: middle; }
.derivation-note { margin: 10px 0 0; color: #64748b; font-size: 12px; }
.simulate-hint { margin: 0 0 10px; color: #64748b; font-size: 12px; }
.simulate-mode-row { display: flex; gap: 16px; margin-bottom: 10px; font-size: 13px; color: #334155; }
.simulate-mode-row label { display: inline-flex; align-items: center; gap: 6px; }
.derivation-simulate-dialog {
max-width: 760px;
width: min(760px, 92vw);
overflow: auto;
align-content: start;
}
.simulate-sample { display: grid; gap: 8px; margin: 12px 0; color: #475569; font-size: 13px; }
.simulate-sample textarea,
.simulate-sample select { width: 100%; font-size: 12px; border: 1px solid #cbd5e1; border-radius: 8px; padding: 10px; box-sizing: border-box; }
.simulate-sample textarea { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
.simulate-result { margin-top: 14px; display: grid; gap: 10px; min-width: 0; }
.simulate-result-scroll {
max-width: 100%;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
border: 1px solid #e2e8f0;
border-radius: 8px;
}
.simulate-result-scroll .derivation-table {
margin: 0;
min-width: 520px;
}
.muted { margin: 0; color: #64748b; font-size: 12px; }
.field-panel { display: flex; min-width: 0; min-height: 0; flex-direction: column; border-right: 1px solid #e5ebf1; background: #fbfcfe; }
.panel-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 16px 16px 10px; }
@@ -1,4 +1,4 @@
/**
/**
* features/admin/stores/admin-nav.store.ts
* 管理后台导航 UI 状态(侧栏折叠、报表/企微子菜单展开、角标)。
*
@@ -20,6 +20,8 @@ export const useAdminNavStore = defineStore('adminNav', () => {
const reportsExpanded = ref(false);
/** 企业微信子菜单:默认折叠 */
const wecomExpanded = ref(false);
/** 货代管理子菜单:默认折叠;父项点击仅展开/收起,子项负责导航 */
const shippingMenuExpanded = ref(false);
/** 「用户审批」导航角标:pending 注册用户数 */
const pendingApprovalsCount = ref(0);
/** 「权限申请」导航角标:pending 权限申请数 */
@@ -88,6 +90,7 @@ export const useAdminNavStore = defineStore('adminNav', () => {
sidebarCollapsed,
reportsExpanded,
wecomExpanded,
shippingMenuExpanded,
pendingApprovalsCount,
pendingRequestsCount,
toggleSidebar,
@@ -22,6 +22,7 @@ export type AdminModuleId =
| 'shipping_inventory'
| 'procurement_contract'
| 'training_config'
| 'integration_connector'
| 'reports';
/** 货代管理领域下可由侧栏展示和高亮的稳定业务页面。 */
@@ -91,69 +91,9 @@ export interface ShippingOrderSchemaVersion {
definition?: {
fields: ShippingOrderFieldConfig[];
auto_creation_policy?: { enabled: boolean };
derivation_rules?: ShippingOrderDerivationRule[];
derivation_rules_checksum?: string;
};
}
/** Schema 级明细字段派生规则(首期仅 copy_if_empty → line_no)。 */
export interface ShippingOrderDerivationRule {
rule_id: string;
enabled: boolean;
source_field_code: string;
target_field_code: string;
strategy: 'copy_if_empty';
scope: 'line';
}
export interface ShippingOrderDerivationSimulateRequest {
lines?: Array<Record<string, string | number | null | undefined>>;
derivation_rules?: ShippingOrderDerivationRule[];
/** 可追溯样本;`extraction:<id>` 时后端加载历史明细,可省略 lines。 */
sample_ref?: string;
}
export interface ShippingOrderDerivationSimulateSampleItem {
sample_ref: string;
extraction_id: number;
line_count: number;
status: string;
schema_version_id: number;
created_at?: string | null;
}
export interface ShippingOrderDerivationSimulateResult {
schema_version_id: number;
schema_version: number;
schema_version_status: string;
rules_checksum: string;
rules: ShippingOrderDerivationRule[];
derived_count: number;
skipped_count: number;
results: Array<{
line_index: number;
rule_id: string;
source_field_code: string;
target_field_code: string;
strategy: string;
before_source: unknown;
before_target: unknown;
after_target: unknown;
status: 'derived' | 'skipped';
skip_reason: string | null;
}>;
lines_after: Array<Record<string, unknown>>;
sample_ref?: string | null;
sample_source?: {
kind?: string;
extraction_id?: number;
schema_version_id?: number;
intake_id?: number;
status?: string;
} | null;
mutates_orders: boolean;
}
export interface SchemaVersionActor {
id: number;
display_name: string;
@@ -266,7 +206,7 @@ export interface ShippingOrderExtractionAudit {
raw_llm_output: unknown;
normalized_result: unknown;
validation_result: unknown;
lines: Array<{ id: number; position: number; line_key?: string | null }>;
lines: Array<{ id: number; position: number; line_no: number }>;
observations: Array<Record<string, unknown>>;
decisions: Array<Record<string, unknown>>;
field_values: Array<Record<string, unknown>>;
+15 -12
View File
@@ -541,11 +541,11 @@ export const patchWorkspaceShippingOrderReviewHeaderField = (
{ method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
);
/** 保存一个复核订单行字段;line_key 仅接受当前 Case DTO 返回的稳定标识。 */
/** 保存一个复核订单行字段;draft_line_id 仅接受当前 Case DTO 返回的草稿身份。 */
export const patchWorkspaceShippingOrderReviewLineField = (
caseNo: string, lineKey: string, fieldId: string, payload: ShippingOrderReviewDraftWrite,
caseNo: string, draftLineId: string, fieldId: string, payload: ShippingOrderReviewDraftWrite,
) => requestJson<ShippingOrderReviewCase>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}/fields/${encodeURIComponent(fieldId)}`,
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(draftLineId)}/fields/${encodeURIComponent(fieldId)}`,
{ method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
);
@@ -555,15 +555,15 @@ export const addWorkspaceShippingOrderReviewLine = (caseNo: string, expectedDraf
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
);
export const copyWorkspaceShippingOrderReviewLine = (caseNo: string, lineKey: string, expectedDraftVersion: number) =>
export const copyWorkspaceShippingOrderReviewLine = (caseNo: string, draftLineId: string, expectedDraftVersion: number) =>
requestJson<ShippingOrderReviewCase>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}/copy`,
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(draftLineId)}/copy`,
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
);
export const deleteWorkspaceShippingOrderReviewLine = (caseNo: string, lineKey: string, expectedDraftVersion: number) =>
export const deleteWorkspaceShippingOrderReviewLine = (caseNo: string, draftLineId: string, expectedDraftVersion: number) =>
requestJson<ShippingOrderReviewCase>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}`,
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(draftLineId)}`,
{ method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
);
@@ -598,7 +598,7 @@ export const retryWorkspaceShippingOrderStpAutoCreate = (caseNo: string) =>
* 为复核明细人工选定一个或多个已启用库存源候选。
* 核心逻辑:携带 expected_draft_version 乐观锁;服务端写入行级 inventory_routing 后重跑资格校验。
* @param caseNo - 复核 Case 编号
* @param lineKey - Draft 行稳定标识 line_key
* @param draftLineId - Draft 行稳定标识 draft_line_id
* @param payload - 候选编码与强制说明
*/
/**
@@ -619,7 +619,7 @@ export const getWorkspaceTaskInventoryCandidates = (
/**
* 重新匹配整单或指定明细的库存路由规则。
* 核心逻辑:携带 expected_draft_version 与幂等键;可选 line_key 限定单行。
* 核心逻辑:携带 expected_draft_version 与幂等键;可选 draft_line_id 限定单行。
* @param caseNo - 复核 Case 编号
* @param payload - 版本锁、幂等键与可选行键
*/
@@ -905,7 +905,7 @@ export const listWorkspaceShippingOrderReviewAuditTimeline = (
export const decideWorkspaceShippingOrderReviewLineFulfillment = (
caseNo: string,
payload: {
line_key: string;
draft_line_id: string;
decision_code: ShippingOrderReviewLineFulfillmentDecisionCode | string;
reason?: string;
release_field_values?: Record<string, string>;
@@ -927,7 +927,7 @@ export const decideWorkspaceShippingOrderReviewLineFulfillment = (
export const waveWorkspaceShippingOrderReviewLineFulfillment = (
caseNo: string,
payload: {
line_keys: string[];
snapshot_line_ids: number[];
expected_draft_version: number;
idempotency_key: string;
reason?: string;
@@ -939,6 +939,9 @@ export const waveWorkspaceShippingOrderReviewLineFulfillment = (
task_no?: string | null;
wave_no?: number | null;
notice_no?: string | null;
/** 是否已调度异步后置波次推进(生成 Excel → OT 进入货代上传);前端据此决定是否起投影轮询。 */
auto_progress_started?: boolean;
confirm_outcome?: string;
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/line-fulfillment/wave`,
{
@@ -958,7 +961,7 @@ export const closeWorkspaceShippingOrderReviewLineFulfillment = (
caseNo: string,
payload: {
reason: string;
line_keys?: string[];
draft_line_ids?: string[];
expected_draft_version?: number;
},
) => requestJson<{
@@ -0,0 +1,78 @@
/**
* features/chat/api/transfer.api.spec.ts
* 用途:锁定在途仓自动调拨 JSON POST 请求头契约——必须携带 Content-Type: application/json,
* 否则后端 Flask request.get_json 解析不到 body,导致默认 source_codes=[] 返回 400。
* 依赖:Vitest、vi.mock(@/shared/api/client)、transfer.api、getAuthHeaders。
* 逻辑:POST(create/execute/cancel/retry/manual-close)断言 headers 含 application/json,
* 且 body 序列化正确;GET/blob 端点不强制 Content-Type。
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
const requestJson = vi.hoisted(() => vi.fn());
const requestBlob = vi.hoisted(() => vi.fn());
vi.mock('@/shared/api/client', () => ({
BusinessError: class BusinessError extends Error {},
requestJson,
requestBlob,
}));
vi.mock('@/shared/utils/auth', () => ({
getAuthHeaders: () => ({ Authorization: 'Bearer TEST-TOKEN' }),
}));
import {
cancelTransferRun,
createTransferPrecheck,
executeTransferPrecheck,
getTransferBacklogSummary,
getTransferPrecheck,
getTransferRun,
listTransferSources,
manualCloseTransferItem,
retryTransferItem,
} from './transfer.api';
describe('transfer.api JSON request contract', () => {
beforeEach(() => {
requestJson.mockReset();
requestBlob.mockReset();
});
it('创建预检 POST 带 Content-Type: application/json 与序列化 source_codes', () => {
createTransferPrecheck({ source_codes: ['DBS-AWSBI'], business_date: '2026-08-18' });
const [url, init] = requestJson.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/in-transit-transfer/prechecks');
expect(init.method).toBe('POST');
expect((init.headers as Record<string, string>)['Content-Type']).toBe('application/json');
expect(init.body).toBe(JSON.stringify({ source_codes: ['DBS-AWSBI'], business_date: '2026-08-18' }));
});
it('直接生成调拨单 POST 带 application/json', () => {
executeTransferPrecheck('TPC-1', ['INV-001']);
const [, init] = requestJson.mock.calls[0] as [string, RequestInit];
expect(init.method).toBe('POST');
expect((init.headers as Record<string, string>)['Content-Type']).toBe('application/json');
expect(init.body).toBe(JSON.stringify({ invoice_nos: ['INV-001'] }));
});
it('重试/关闭/取消 POST 带 application/json', () => {
retryTransferItem(7);
manualCloseTransferItem(7, '线下已处理');
cancelTransferRun('RUN-1', '紧急');
for (const [, init] of requestJson.mock.calls as [string, RequestInit][]) {
expect(init.method).toBe('POST');
expect((init.headers as Record<string, string>)['Content-Type']).toBe('application/json');
}
});
it('GET 端点只需鉴权头,不需要强制 Content-Type', () => {
getTransferPrecheck('TPC-1');
getTransferRun('RUN-1');
getTransferBacklogSummary();
listTransferSources();
for (const [, init] of requestJson.mock.calls as [string, RequestInit][]) {
expect(init.headers).toBeDefined();
}
});
});
@@ -0,0 +1,112 @@
/**
* features/chat/api/transfer.api.ts
* 用途:在途仓自动调拨 API 客户端(统一 requestJson / requestBlob,不重复造客户端)。
* 依赖:@/shared/api/client(requestJson / requestBlob / BusinessError)、getAuthHeaders。
* 逻辑:薄封装后端 /api/in-transit-transfer 全部端点;二进制下载走 requestBlob。
*/
import { requestBlob, requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import type {
TransferActionResult,
TransferBacklogItem,
TransferBacklogSummary,
TransferExecuteResponse,
TransferPrecheckDetail,
TransferPrecheckSummary,
TransferRunResult,
TransferSourceFileStatus,
TransferSourceOption,
} from '../types/transfer.types';
const BASE = '/api/in-transit-transfer';
/** JSON 请求头:除鉴权外必须带 Content-Type: application/json,否则 Flask request.get_json 解析不到 body。 */
const jsonHeaders = () => ({ 'Content-Type': 'application/json', ...getAuthHeaders() });
export interface CreatePrecheckPayload {
source_codes: string[];
business_date?: string;
}
/** 创建预检(只读) */
export const createTransferPrecheck = (payload: CreatePrecheckPayload) =>
requestJson<TransferPrecheckSummary>(BASE + '/prechecks', {
method: 'POST',
headers: jsonHeaders(),
body: JSON.stringify(payload),
});
/** 恢复预检进度与明细 */
export const getTransferPrecheck = (precheckId: string) =>
requestJson<TransferPrecheckDetail>(`${BASE}/prechecks/${precheckId}`, {
headers: getAuthHeaders(),
});
/** 确认选择范围并直接生成执行 Run */
export const executeTransferPrecheck = (precheckId: string, invoiceNos: string[]) =>
requestJson<TransferExecuteResponse>(`${BASE}/prechecks/${precheckId}/execute`, {
method: 'POST',
headers: jsonHeaders(),
body: JSON.stringify({ invoice_nos: invoiceNos }),
});
/** 恢复 Run 最终结果 */
export const getTransferRun = (runNo: string) =>
requestJson<TransferRunResult>(`${BASE}/runs/${runNo}`, {
headers: getAuthHeaders(),
});
/** 请求停止剩余任务 */
export const cancelTransferRun = (runNo: string, reason: string) =>
requestJson<TransferActionResult>(`${BASE}/runs/${runNo}/cancel`, {
method: 'POST',
headers: jsonHeaders(),
body: JSON.stringify({ reason }),
});
/** 人工重试异常项(仅重新查询 ERP,新 Attempt) */
export const retryTransferItem = (itemId: number) =>
requestJson<TransferActionResult>(`${BASE}/items/${itemId}/retry`, {
method: 'POST',
headers: jsonHeaders(),
body: JSON.stringify({ kind: 'erp_recheck' }),
});
/** 人工关闭异常项 */
export const manualCloseTransferItem = (itemId: number, reason: string) =>
requestJson<TransferActionResult>(`${BASE}/items/${itemId}/manual-close`, {
method: 'POST',
headers: jsonHeaders(),
body: JSON.stringify({ reason }),
});
/** 下载收料来源文件(zip) */
export const downloadTransferReceiptFiles = (runNo: string) =>
requestBlob(`${BASE}/runs/${runNo}/receipt-files`, { headers: getAuthHeaders() });
/** 下载预检冻结的 ERP 库存表(csv) */
export const downloadTransferErpInventory = (runNo: string) =>
requestBlob(`${BASE}/runs/${runNo}/erp-inventory`, { headers: getAuthHeaders() });
/** 下载七 Sheet 异常 Excel */
export const downloadTransferExceptions = (runNo: string) =>
requestBlob(`${BASE}/runs/${runNo}/exceptions.xlsx`, { headers: getAuthHeaders() });
/** 待处理异常列表(可恢复/已关闭/结果未知 + 老化等级) */
export const listTransferBacklog = () =>
requestJson<TransferBacklogItem[]>(`${BASE}/backlog`, { headers: getAuthHeaders() });
/** 待处理异常汇总(含 3/5/7 天老化分级) */
export const getTransferBacklogSummary = () =>
requestJson<TransferBacklogSummary>(`${BASE}/backlog/summary`, { headers: getAuthHeaders() });
/** 来源实例列表(平台 DBS/Crane 仅分组,每来源附收料文件状态) */
export const listTransferSources = () =>
requestJson<TransferSourceOption[]>(`${BASE}/sources`, { headers: getAuthHeaders() });
/** 对指定来源重新触发一次收料 RPA 抓取 */
export const retryTransferSourceRpa = (sourceCode: string) =>
requestJson<TransferSourceFileStatus>(`${BASE}/sources/${encodeURIComponent(sourceCode)}/retry-rpa`, {
method: 'POST',
headers: jsonHeaders(),
});
@@ -38,7 +38,7 @@ const emit = defineEmits<{
>
<div
class="absolute inset-y-0 left-1/2 w-px -translate-x-1/2 transition-colors"
:class="isResizing ? 'bg-brand-500' : 'bg-slate-200'"
:class="isResizing ? 'bg-brand-500' : 'bg-surface-strong'"
/>
</div>
@@ -94,7 +94,7 @@ const emit = defineEmits<{
</button>
</div>
<div class="min-h-0 flex-1 bg-slate-100">
<div class="min-h-0 flex-1 bg-surface-strong">
<div
v-if="!currentUrl"
class="flex h-full flex-col items-center justify-center gap-3 px-8 text-center text-sm text-muted"
@@ -93,7 +93,7 @@ defineProps<{
v-else-if="activeGuide.file_type === 'pdf'"
:key="'pdf-' + activeGuide.id"
:src="activeGuide.file_url || activeGuide.file_path"
class="h-full w-full border-none bg-white"
class="h-full w-full border-none bg-surface"
/>
<img
v-else
@@ -417,7 +417,7 @@ watch(
role="tab"
class="rounded-full px-3 py-1.5 text-xs font-bold transition-all"
:class="procurementReviewMode === 'compare'
? 'bg-white text-[#2f80d1] shadow-[0_1px_4px_rgba(23,32,51,0.08)]'
? 'bg-surface text-[#2f80d1] shadow-[0_1px_4px_rgba(23,32,51,0.08)]'
: 'bg-transparent text-[#667792] hover:text-[#172033]'"
:aria-selected="procurementReviewMode === 'compare'"
@click="procurementReviewMode = 'compare'"
@@ -429,7 +429,7 @@ watch(
role="tab"
class="rounded-full px-3 py-1.5 text-xs font-bold transition-all"
:class="procurementReviewMode === 'solo'
? 'bg-white text-[#2f80d1] shadow-[0_1px_4px_rgba(23,32,51,0.08)]'
? 'bg-surface text-[#2f80d1] shadow-[0_1px_4px_rgba(23,32,51,0.08)]'
: 'bg-transparent text-[#667792] hover:text-[#172033]'"
:aria-selected="procurementReviewMode === 'solo'"
@click="procurementReviewMode = 'solo'"
@@ -542,7 +542,7 @@ watch(
</p>
<div class="mt-1 flex min-w-0 items-center gap-1.5 text-[11px] leading-none">
<span v-if="getAttachmentSize(a)" class="shrink-0 text-muted">{{ getAttachmentSize(a) }}</span>
<span v-if="getAttachmentSize(a)" class="text-slate-300">·</span>
<span v-if="getAttachmentSize(a)" class="text-muted">·</span>
<span
class="flex min-w-0 items-center gap-1 truncate"
:class="{
@@ -656,7 +656,7 @@ watch(
v-for="action in procurementQuickActions"
:key="action.label"
type="button"
class="rounded-full border border-[#d8e0ec] bg-white px-3 py-1.5 text-xs font-semibold text-[#31445f] transition-colors hover:border-[#2f80d1] hover:bg-[#eef6ff] hover:text-[#1f5f99] disabled:cursor-not-allowed disabled:opacity-50"
class="rounded-full border border-[#d8e0ec] bg-surface px-3 py-1.5 text-xs font-semibold text-[#31445f] transition-colors hover:border-[#2f80d1] hover:bg-[#eef6ff] hover:text-[#1f5f99] disabled:cursor-not-allowed disabled:opacity-50"
:disabled="isThinking || isUploadingAttachments"
@click="runProcurementQuickAction(action.prompt)"
>
@@ -858,7 +858,7 @@ watch(
:disabled="!canSendMessage"
class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full border shadow-sm transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-50"
:class="!canSendMessage
? 'border-default bg-slate-100 text-muted'
? 'border-default bg-surface-strong text-muted'
: 'border-brand-500 bg-brand-500 text-white shadow-[0_0_0_4px_rgba(59,130,246,0.18)] hover:scale-105 hover:bg-brand-600 hover:shadow-[0_0_0_6px_rgba(59,130,246,0.24)] active:scale-95'"
@click="emit('send')"
>
@@ -7,6 +7,7 @@ import type { Ref } from 'vue';
import ChatWelcomePanel, { type WelcomeQuestionItem, type WelcomeQuestionSection } from './ChatWelcomePanel.vue';
import ChatThinkingBubble from './ChatThinkingBubble.vue';
import ChatMessageBubble, { type ChatMessageBubbleHandlers } from './messages/ChatMessageBubble.vue';
import TransferHomePanel from './messages/TransferHomePanel.vue';
import ToolRunProgressCard from './ToolRunProgressCard.vue';
import type { LeaveMessageHandlers } from './messages/LeaveMessageBlock.vue';
import type { ShippingMessageHandlers } from './messages/shippingMessageHandlers';
@@ -45,6 +46,8 @@ const {
toolRunProgressTitle: string;
showScrollToBottom: boolean;
hideWelcomePanel?: boolean;
/** 在途仓自动调拨 Agent:无消息时渲染专属首页入口区(替代通用欢迎面板)。 */
isInTransitTransferAgent?: boolean;
pinMessagesToBottom?: boolean;
/** 供父级滚动逻辑绑定 main 元素 */
scrollContainerHolder: { el: Ref<HTMLElement | null> };
@@ -63,6 +66,8 @@ const emit = defineEmits<{
'maintenance-view-record-history': [device: MaintenanceDevice];
'maintenance-create-record-for-device': [device: MaintenanceDevice];
'open-batch-workbench': [];
/** 在途仓自动调拨:业务流激活时向上冒泡,父级据此隐藏聊天输入框。 */
'transfer-flow-active': [active: boolean];
}>();
const bindScrollContainer = (node: unknown) => {
@@ -144,7 +149,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
>
<div :class="messages.length === 0 ? 'h-full' : pinMessagesToBottom === false ? 'min-h-full' : 'flex min-h-full flex-col justify-end'">
<ChatWelcomePanel
v-if="messages.length === 0 && !hideWelcomePanel"
v-if="messages.length === 0 && !hideWelcomePanel && !isInTransitTransferAgent"
:agent-name="agentName"
:suggested-questions-style="suggestedQuestionsStyle"
:styled-sections="styledSections"
@@ -153,6 +158,12 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
@select-question="emit('select-question', $event)"
/>
<TransferHomePanel
v-if="messages.length === 0 && !hideWelcomePanel && isInTransitTransferAgent"
:agent-name="agentName"
@flow-active="emit('transfer-flow-active', $event)"
/>
<template v-for="(msg, index) in messages" :key="getMessageKey(msg, index)">
<ChatMessageBubble
v-if="shouldRenderMessage(msg) && !isDuplicateShippingExtractionMessage(messages, index)"
@@ -196,7 +207,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
<button
v-if="showScrollToBottom"
type="button"
class="sticky bottom-4 left-1/2 z-30 flex h-10 w-10 -translate-x-1/2 items-center justify-center rounded-full border border-slate-100 bg-white text-[28px] font-light leading-none text-slate-500 shadow-[0_10px_28px_rgba(15,23,42,0.16)] transition hover:-translate-y-0.5 hover:border-slate-200 hover:text-slate-700 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-300 dark:shadow-black/30 md:bottom-6"
class="sticky bottom-4 left-1/2 z-30 flex h-10 w-10 -translate-x-1/2 items-center justify-center rounded-full border border-subtle bg-surface text-[28px] font-light leading-none text-muted shadow-[0_10px_28px_rgba(15,23,42,0.16)] transition hover:-translate-y-0.5 hover:border-slate-200 hover:text-slate-700 dark:shadow-black/30 md:bottom-6"
:title="$t('chat.scrollToLatest')"
@click="emit('scroll-to-bottom')"
>
@@ -1,4 +1,4 @@
/**
/**
* features/chat/components/ChatSidebar.vue
* 用途:桌面端聊天侧栏,承载 Agent 信息、会话历史、Agent 切换面板与底部用户菜单。
* 依赖:lucide-vue-next、LocaleToggleButton、ExternalSystemLinks、AgentCategoryList、chat.types。
@@ -205,11 +205,11 @@ const orderExtractionAttentionClass = (item: DisplayHistoryItem) => {
</div>
<div class="flex items-center justify-between px-4 py-2">
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">{{ $t('chat.history') }}</span>
<span class="text-xs font-semibold text-muted">{{ $t('chat.history') }}</span>
<button
v-if="displayHistory.length > 0"
type="button"
class="text-xs text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200"
class="text-xs text-muted transition-colors hover:text-slate-600 dark:hover:text-slate-200"
@click="emit('clear-all-history')"
>
{{ $t('chat.clearAll') }}
@@ -217,7 +217,7 @@ const orderExtractionAttentionClass = (item: DisplayHistoryItem) => {
</div>
<div class="scrollbar-thin flex-1 overflow-y-auto px-2">
<div v-if="displayHistory.length === 0" class="py-8 text-center text-sm italic text-slate-400">
<div v-if="displayHistory.length === 0" class="py-8 text-center text-sm italic text-muted">
{{ $t('chat.noHistory') }}
</div>
<div v-else class="space-y-0.5">
@@ -225,14 +225,14 @@ const orderExtractionAttentionClass = (item: DisplayHistoryItem) => {
v-for="item in displayHistory"
:key="item.conversation_id"
class="group relative flex w-full items-center justify-between rounded-lg transition-colors"
:class="activeHistoryKey === item.conversation_id ? 'bg-brand-50 dark:bg-brand-900/20' : 'hover:bg-slate-50 dark:hover:bg-slate-800/50'"
:class="activeHistoryKey === item.conversation_id ? 'bg-brand-50 dark:bg-brand-900/20' : 'hover-surface-soft dark:hover:bg-slate-800/50'"
>
<button
type="button"
class="flex-1 truncate px-3 py-2.5 pr-8 text-left text-sm"
:class="activeHistoryKey === item.conversation_id
? 'font-medium text-brand-700 dark:text-brand-300'
: 'text-slate-600 dark:text-slate-300'"
: 'text-secondary '"
@click="emit('history-select', item)"
>
{{ item.title || $t('chat.newChat') }}
@@ -44,7 +44,7 @@ import { useChatPageContext } from '@/features/chat/composables/chat.context';
import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils';
import { agentHasIntentUiProfile } from '@/shared/utils/agent-registry.utils';
import { agentHasIntentUiProfile, resolveAgentCode, AGENT_CODE_IN_TRANSIT_TRANSFER } from '@/shared/utils/agent-registry.utils';
import {
SHIPPING_WORKFLOW_KEY,
@@ -111,6 +111,13 @@ const isTrainingAgentPage = computed(() => matchesTrainingAgent(page.currentAgen
const isMaintenanceAgentPage = computed(() => agentHasIntentUiProfile(page.currentAgent, 'maintenance'));
/** 在途仓自动调拨 Agent:无消息时展示专属首页入口区(决策:补 Chat 首页入口 A 方案)。 */
const isInTransitTransferAgent = computed(() => resolveAgentCode(page.currentAgent) === AGENT_CODE_IN_TRANSIT_TRANSFER);
/** 在途仓自动调拨业务流激活(来源选择/待处理等子视图)时隐藏聊天输入框,模拟业务页。 */
const transferFlowActive = ref(false);
watch(isInTransitTransferAgent, (isTransfer) => { if (!isTransfer) transferFlowActive.value = false; });
/** 批次进度工作台按需打开;关闭时不占用对话区右侧布局。 */
const batchWorkbenchOpen = ref(false);
@@ -542,6 +549,8 @@ watch(() => page.currentAgentId, () => {
:hide-welcome-title="hideWelcomeTitle"
:is-in-transit-transfer-agent="isInTransitTransferAgent"
:pin-messages-to-bottom="!isTrainingAgentPage"
:scroll-container-holder="page.scrollContainerHolder"
@@ -570,13 +579,15 @@ watch(() => page.currentAgentId, () => {
@open-batch-workbench="openBatchWorkbench"
@transfer-flow-active="transferFlowActive = $event"
/>
<ChatInputBar
v-show="!isTrainingWorkspaceExpanded"
v-show="!isTrainingWorkspaceExpanded && !transferFlowActive"
:key="`${page.currentAgentId}-${page.conversationId || 'draft'}-${page.messages.length}`"
@@ -47,7 +47,7 @@ const items = computed(() =>
</div>
<blockquote
v-if="item.quote"
class="rounded border border-slate-200 bg-slate-50 px-2 py-1.5 font-mono text-[11px] leading-5 text-slate-700"
class="rounded border border-default bg-surface-soft px-2 py-1.5 font-mono text-[11px] leading-5 text-secondary"
>
{{ item.quote }}
</blockquote>
@@ -79,7 +79,7 @@ async function resolveConflict(
<span v-if="conflict.position != null">#{{ Number(conflict.position) + 1 }} · </span>
<span class="font-mono">{{ conflict.field_name }}</span>
</div>
<div class="mt-1 grid gap-1 text-slate-700 sm:grid-cols-2">
<div class="mt-1 grid gap-1 text-secondary sm:grid-cols-2">
<div>
<span class="text-muted">{{ t('chat.shippingFieldConflict.existing') }}:</span>
<span class="ml-1 font-mono">{{ conflict.existing_value || '—' }}</span>
@@ -92,7 +92,7 @@ async function resolveConflict(
<div class="mt-2 flex flex-wrap gap-2">
<button
type="button"
class="rounded border border-slate-300 bg-white px-2 py-1 text-[11px] font-medium hover:bg-slate-50 disabled:opacity-50"
class="rounded border border-default bg-surface px-2 py-1 text-[11px] font-medium hover-surface-soft disabled:opacity-50"
:disabled="resolvingId != null"
@click="resolveConflict(conflict, 'keep_existing')"
>
@@ -116,7 +116,7 @@ function issueReasonLabel(reason?: string | null): string {
class="rounded-xl border p-3 text-xs"
:class="hasBlocking
? 'border-amber-200 bg-amber-50/70'
: 'border-slate-200 bg-surface-soft/80'"
: 'border-default bg-surface-soft/80'"
>
<button
type="button"
@@ -139,7 +139,7 @@ function issueReasonLabel(reason?: string | null): string {
</button>
<div v-if="expanded" class="mt-3 space-y-3">
<div class="rounded-lg border border-slate-200/80 bg-white/80 px-2.5 py-2 text-[11px] leading-5 text-slate-700">
<div class="rounded-lg border border-slate-200/80 bg-white/80 px-2.5 py-2 text-[11px] leading-5 text-secondary">
{{ t('chat.shippingParsedResult.impactHint') }}
</div>
@@ -152,11 +152,11 @@ function issueReasonLabel(reason?: string | null): string {
/>
<div v-if="orderedHeaderFields.length" class="rounded-xl border border-default bg-white/90 p-2.5">
<div class="mb-2 font-semibold text-slate-700">{{ t('chat.shippingParsedResult.orderInformation') }}</div>
<div class="mb-2 font-semibold text-secondary">{{ t('chat.shippingParsedResult.orderInformation') }}</div>
<dl class="grid gap-2 sm:grid-cols-2">
<div v-for="field in orderedHeaderFields" :key="field.field_code" class="rounded-lg bg-slate-50 px-2.5 py-2">
<div v-for="field in orderedHeaderFields" :key="field.field_code" class="rounded-lg bg-surface-soft px-2.5 py-2">
<dt class="text-[10px] text-muted">{{ field.display_name }}</dt>
<dd class="mt-0.5 break-words text-xs text-slate-800">{{ displayValue(orderHeader?.[field.field_code]) }}</dd>
<dd class="mt-0.5 break-words text-xs text-primary">{{ displayValue(orderHeader?.[field.field_code]) }}</dd>
</div>
</dl>
</div>
@@ -64,9 +64,9 @@ const kbSyncMeta = (status?: string | null) => {
return { label: '知识库同步中', tone: 'border-sky-200 bg-sky-50 text-sky-700', icon: 'syncing' };
}
if (value === 'skipped') {
return { label: '知识库未同步', tone: 'border-slate-200 bg-slate-50 text-slate-600', icon: 'skipped' };
return { label: '知识库未同步', tone: 'border-default bg-surface-soft text-secondary', icon: 'skipped' };
}
return { label: `知识库:${status || '未知'}`, tone: 'border-slate-200 bg-slate-50 text-slate-600', icon: 'skipped' };
return { label: `知识库:${status || '未知'}`, tone: 'border-default bg-surface-soft text-secondary', icon: 'skipped' };
};
const parseDownloadFilename = (disposition: string | null, fallback: string) => {
@@ -128,14 +128,14 @@ const downloadExcel = async () => {
>
<div class="flex items-start justify-between gap-3 border-b border-sky-100/80 px-4 py-3">
<div>
<div class="flex items-center gap-2 text-sm font-semibold text-slate-800">
<div class="flex items-center gap-2 text-sm font-semibold text-primary">
<Loader2 v-if="run?.status === 'running'" class="h-4 w-4 animate-spin text-sky-600" />
<CheckCircle2 v-else-if="run?.status === 'success'" class="h-4 w-4 text-emerald-600" />
<AlertCircle v-else-if="run?.status === 'failed' || run?.status === 'partial_failed'" class="h-4 w-4 text-amber-600" />
<Clock3 v-else class="h-4 w-4 text-sky-600" />
{{ run?.title || fallbackTitle || '任务进度' }}
</div>
<p class="mt-1 text-xs text-slate-500">
<p class="mt-1 text-xs text-muted">
<template v-if="run">
批次:{{ run.run_no }} · 状态:{{ statusLabel(run.status) }}
<span v-if="run.error_message" class="ml-2 text-rose-700">错误信息:{{ run.error_message }}</span>
@@ -181,48 +181,48 @@ const downloadExcel = async () => {
{{ downloadError }}
</div>
<div class="h-2.5 overflow-hidden rounded-full bg-slate-200">
<div class="h-2.5 overflow-hidden rounded-full bg-surface-strong">
<div
class="h-full rounded-full bg-gradient-to-r from-sky-500 to-emerald-500 transition-all duration-500"
:style="{ width: `${percent()}%` }"
></div>
</div>
<div class="flex flex-wrap items-center justify-between gap-2 text-xs text-slate-500">
<div class="flex flex-wrap items-center justify-between gap-2 text-xs text-muted">
<span>进度 {{ percent() }}%</span>
<span>开始:{{ formatTime(run.started_at) }} · 完成:{{ formatTime(run.finished_at) }}</span>
</div>
<div class="grid grid-cols-2 gap-1.5 sm:grid-cols-4 lg:grid-cols-8">
<div class="rounded-lg bg-white/80 px-2 py-1.5">
<div class="whitespace-nowrap text-xs text-slate-500">总数</div>
<div class="text-base font-bold text-slate-800">{{ run.total_count }}</div>
<div class="whitespace-nowrap text-xs text-muted">总数</div>
<div class="text-base font-bold text-primary">{{ run.total_count }}</div>
</div>
<div class="rounded-lg bg-white/80 px-2 py-1.5">
<div class="whitespace-nowrap text-xs text-slate-500">已处理</div>
<div class="whitespace-nowrap text-xs text-muted">已处理</div>
<div class="text-base font-bold text-sky-700">{{ run.processed_count }}</div>
</div>
<div class="rounded-lg bg-white/80 px-2 py-1.5">
<div class="whitespace-nowrap text-xs text-slate-500">成功</div>
<div class="whitespace-nowrap text-xs text-muted">成功</div>
<div class="text-base font-bold text-emerald-700">{{ run.success_count }}</div>
</div>
<div class="rounded-lg bg-white/80 px-2 py-1.5">
<div class="whitespace-nowrap text-xs text-slate-500">失败</div>
<div class="whitespace-nowrap text-xs text-muted">失败</div>
<div class="text-base font-bold text-rose-700">{{ run.failed_count }}</div>
</div>
<div class="rounded-lg bg-white/80 px-2 py-1.5">
<div class="whitespace-nowrap text-xs text-slate-500">跳过</div>
<div class="whitespace-nowrap text-xs text-muted">跳过</div>
<div class="text-base font-bold text-amber-700">{{ run.skipped_count }}</div>
</div>
<div class="rounded-lg bg-white/80 px-2 py-1.5">
<div class="whitespace-nowrap text-xs text-slate-500">合格笔数</div>
<div class="whitespace-nowrap text-xs text-muted">合格笔数</div>
<div class="text-base font-bold text-emerald-700">{{ run.judgement?.qualified_count ?? 0 }}</div>
</div>
<div class="rounded-lg bg-white/80 px-2 py-1.5">
<div class="whitespace-nowrap text-xs text-slate-500">不合格笔数</div>
<div class="whitespace-nowrap text-xs text-muted">不合格笔数</div>
<div class="text-base font-bold text-rose-700">{{ run.judgement?.unqualified_count ?? 0 }}</div>
</div>
<div class="rounded-lg bg-white/80 px-2 py-1.5">
<div class="whitespace-nowrap text-xs text-slate-500">人工判定笔数</div>
<div class="whitespace-nowrap text-xs text-muted">人工判定笔数</div>
<div class="text-base font-bold text-amber-700">{{ run.judgement?.manual_count ?? 0 }}</div>
</div>
</div>
@@ -233,10 +233,10 @@ const downloadExcel = async () => {
</div>
<div v-else-if="waiting || loading" class="space-y-3 px-4 py-4">
<div class="h-2.5 overflow-hidden rounded-full bg-slate-200">
<div class="h-2.5 overflow-hidden rounded-full bg-surface-strong">
<div class="h-full w-1/3 animate-pulse rounded-full bg-gradient-to-r from-sky-400 to-emerald-400" />
</div>
<p class="text-xs text-slate-500">检核启动后,这里会显示实时进度。</p>
<p class="text-xs text-muted">检核启动后,这里会显示实时进度。</p>
</div>
</section>
</template>
@@ -14,6 +14,7 @@ import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBloc
import ChatMessageAttachmentList from './ChatMessageAttachmentList.vue';
import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue';
import ContractReviewResultCard from './ContractReviewResultCard.vue';
import TransferMessageView from './TransferMessageView.vue';
import ShippingMatchResultCard from './ShippingMatchResultCard.vue';
import ShippingParseReviewMessage, { type ShippingParseReviewHandlers } from './ShippingParseReviewMessage.vue';
import type { ShippingMessageHandlers } from './shippingMessageHandlers';
@@ -94,6 +95,12 @@ const RESTRICTED_INLINE_DOWNLOAD_FILE_NAME = '资产明细全量导出表.csv';
/** 合同审查结果卡:自身已是完整卡片,外层只需透明容器。 */
const isContractReviewMessage = computed(() => message.type === 'procurement-contract-review');
const isTransferMessage = computed(
() =>
message.type === 'transfer-precheck'
|| message.type === 'transfer-progress'
|| message.type === 'transfer-result',
);
const isLeaveMessage = computed(() =>
message.type === 'leave-form'
@@ -770,6 +777,10 @@ function handleInlineDownload(file: InlineDownloadFile): void {
v-else-if="message.type === 'procurement-contract-review'"
:message="message"
/>
<TransferMessageView
v-else-if="isTransferMessage"
:payload="(message.payload as Record<string, unknown> | undefined)"
/>
<TrainingExamQuestionMessage
v-else-if="isTrainingExamMessage && trainingHandlers.getQuestion()"
:question="trainingHandlers.getQuestion()!"
@@ -0,0 +1,90 @@
<!--
features/chat/components/messages/TransferBacklogSummaryCard.vue
用途:待处理异常卡(可恢复/已关闭/结果未知三组)+ 人工重试/人工关闭入口。
依赖:props.items、i18n chat.transfer.*。
逻辑:result_unknown 只读(无重试/关闭按钮);人工关闭由父组件弹窗处理。
-->
<script setup lang="ts">
import type { TransferBacklogItem } from '../../types/transfer.types';
defineProps<{
items: TransferBacklogItem[];
}>();
const emit = defineEmits<{
retry: [itemId: number];
close: [item: TransferBacklogItem];
refresh: [];
}>();
function agingLabel(level: string): string {
const map: Record<string, string> = {
warn_3d: 'chat.transfer.agingWarn',
escalate_5d: 'chat.transfer.agingEscalate',
critical_7d: 'chat.transfer.agingCritical',
result_unknown: 'chat.transfer.resultUnknown',
closed: 'chat.transfer.statusClosed',
};
return map[level] ?? 'chat.transfer.agingNormal';
}
</script>
<template>
<div class="my-2 rounded-2xl border border-brand-100 bg-surface p-4 shadow-sm" data-testid="transfer-backlog-card">
<div class="mb-2 flex items-center justify-between">
<h3 class="text-sm font-bold text-primary">{{ $t('chat.transfer.backlogTitle') }}</h3>
<button
type="button"
class="rounded-lg border border-default px-2 py-1 text-xs text-secondary hover-surface-soft"
data-testid="transfer-backlog-refresh"
@click="emit('refresh')"
>
{{ $t('chat.transfer.refreshProgress') }}
</button>
</div>
<ul v-if="items.length" class="flex flex-col gap-1.5">
<li
v-for="item in items"
:key="item.item_id"
class="flex items-center justify-between gap-2 rounded-lg border border-subtle px-3 py-2 text-xs"
:data-testid="`transfer-backlog-${item.invoice_no}`"
>
<div class="min-w-0">
<div class="font-semibold text-secondary">
{{ item.invoice_no }}
<span class="ml-1 text-muted">{{ item.source_code }}</span>
</div>
<div class="text-[11px] text-muted">
{{ item.reason }} · {{ $t(agingLabel(item.aging_level)) }}
</div>
</div>
<div class="flex shrink-0 gap-1.5">
<template v-if="item.status === 'blocked_recoverable'">
<button
type="button"
class="rounded-lg border border-brand-200 px-2 py-1 font-bold text-brand-700 hover:bg-brand-50"
data-testid="transfer-backlog-retry"
@click="emit('retry', item.item_id)"
>
{{ $t('chat.transfer.retryErp') }}
</button>
<button
type="button"
class="rounded-lg border border-red-200 px-2 py-1 font-bold text-red-600 hover:bg-red-50"
data-testid="transfer-backlog-close"
@click="emit('close', item)"
>
{{ $t('chat.transfer.manualClose') }}
</button>
</template>
<span v-else-if="item.status === 'result_unknown'" class="text-[11px] text-muted">
{{ $t('chat.transfer.resultUnknownReadonly') }}
</span>
</div>
</li>
</ul>
<div v-else class="rounded-lg bg-surface-soft p-3 text-xs text-muted">
{{ $t('chat.transfer.noBacklog') }}
</div>
</div>
</template>
@@ -0,0 +1,50 @@
<!--
features/chat/components/messages/TransferFileProgressCard.vue
用途:来源实例级收料文件准备进度(决策 18:来源隔离展示,不伪造总百分比)。
依赖:props.sources、i18n chat.transfer.*。
逻辑:按来源显示 file_ready / waiting_rpa_callback / failed 阶段与文件信息。
-->
<script setup lang="ts">
import type { TransferSourceProgress } from '../../types/transfer.types';
defineProps<{
sources: TransferSourceProgress[];
}>();
</script>
<template>
<div
class="my-2 rounded-2xl border border-brand-100 bg-surface p-4 shadow-sm"
data-testid="transfer-file-progress-card"
>
<h3 class="mb-3 text-sm font-bold text-primary">{{ $t('chat.transfer.fileProgressTitle') }}</h3>
<ul class="flex flex-col gap-2">
<li
v-for="source in sources"
:key="source.source_code"
class="flex items-center justify-between rounded-lg border border-subtle px-3 py-2"
:data-testid="`transfer-source-${source.source_code}`"
>
<div class="min-w-0">
<div class="text-sm font-semibold text-secondary">{{ source.source_code }}</div>
<div v-if="source.file_no" class="truncate text-xs text-muted">
{{ source.file_no }}<template v-if="source.file_version"> · v{{ source.file_version }}</template>
</div>
<div v-else-if="source.error_message" class="truncate text-xs text-red-500">{{ source.error_message }}</div>
</div>
<span
class="shrink-0 rounded-full px-2 py-0.5 text-xs font-bold"
:class="{
'bg-emerald-50 text-emerald-700': source.stage === 'file_ready',
'bg-amber-50 text-amber-700': source.stage === 'waiting_rpa_callback',
'bg-red-50 text-red-700': source.stage === 'failed',
}"
>
<template v-if="source.stage === 'file_ready'">{{ $t('chat.transfer.stageFileReady') }}</template>
<template v-else-if="source.stage === 'waiting_rpa_callback'">{{ $t('chat.transfer.stageWaitingRpa') }}</template>
<template v-else>{{ $t('chat.transfer.stageFailed') }}</template>
</span>
</li>
</ul>
</div>
</template>
@@ -0,0 +1,131 @@
/**
* features/chat/components/messages/TransferHomePanel.spec.ts
* 用途:验证在途仓自动调拨 Agent 的 Chat 首页入口区——
* home 视图渲染“今日待办 + 历史待办”计数卡;点击入口独立触发
* source-select / backlog 卡片(复用自驱动的 TransferMessageView,不注入消息流)。
* 依赖:vi.mock(transfer.api)、@vue/test-utils、i18n。
* 逻辑:Mock API 断言入口切换与计数展示;对应后端 backlog/summary 契约面。
*/
import { mount, flushPromises } from '@vue/test-utils';
import { describe, expect, it, vi, beforeEach } from 'vitest';
import i18n from '@/i18n';
const api = vi.hoisted(() => ({
createTransferPrecheck: vi.fn(),
getTransferPrecheck: vi.fn(),
executeTransferPrecheck: vi.fn(),
getTransferRun: vi.fn(),
retryTransferItem: vi.fn(),
manualCloseTransferItem: vi.fn(),
downloadTransferReceiptFiles: vi.fn(),
downloadTransferErpInventory: vi.fn(),
downloadTransferExceptions: vi.fn(),
listTransferBacklog: vi.fn(),
getTransferBacklogSummary: vi.fn(),
listTransferSources: vi.fn(),
}));
vi.mock('@/features/chat/api/transfer.api', () => api);
import TransferHomePanel from './TransferHomePanel.vue';
function mountHome() {
return mount(TransferHomePanel, {
props: { agentName: '在途仓自动调拨' },
global: { plugins: [i18n] },
});
}
describe('TransferHomePanel chat home entry', () => {
beforeEach(() => {
vi.clearAllMocks();
api.getTransferBacklogSummary.mockResolvedValue({
recoverable: 6, closed: 2, unknown: 1, aging: { warn_3d: 3, escalate_5d: 2, critical_7d: 1 },
});
api.listTransferBacklog.mockResolvedValue([]);
api.listTransferSources.mockResolvedValue([
{ source_code: 'DBS-AWSBI', display_name: 'AWSBI', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' },
]);
});
it('home 视图渲染标题、今日待办入口与三张历史待办计数卡', async () => {
const wrapper = mountHome();
await flushPromises();
expect(wrapper.find('[data-testid="transfer-home"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="transfer-home-today"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="transfer-home-recoverable"]').text()).toContain('6');
expect(wrapper.find('[data-testid="transfer-home-closed"]').text()).toContain('2');
expect(wrapper.find('[data-testid="transfer-home-unknown"]').text()).toContain('1');
expect(api.getTransferBacklogSummary).toHaveBeenCalled();
});
it('点击“发起今日调拨预检”独立触发来源选择卡(复用 TransferMessageView)', async () => {
api.createTransferPrecheck.mockResolvedValue({
precheck_id: 'TPC-1', status: 'ready_to_execute', business_date: '2026-08-06',
eligible_receipt_date_to: '2026-08-05', expires_at: '',
counts: { file_invoice_count: 1, not_matured_count: 0, prechecked_count: 1, executable_count: 1, blocked_count: 0 },
estimated_transfer_quantity: '1200', estimated_erp_write_count: 1, precheck_hash: 'sha256:x',
});
api.getTransferPrecheck.mockResolvedValue({
summary: {
precheck_id: 'TPC-1', status: 'ready_to_execute', business_date: '2026-08-06',
eligible_receipt_date_to: '2026-08-05', expires_at: '',
counts: { file_invoice_count: 1, not_matured_count: 0, prechecked_count: 1, executable_count: 1, blocked_count: 0 },
estimated_transfer_quantity: '1200', estimated_erp_write_count: 1, precheck_hash: 'sha256:x',
},
items: [{
source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器组件', specification: 'A',
invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200',
to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable',
}],
sources: [{ source_code: 'DBS-AWSBI', stage: 'file_ready', file_no: 'REC-1' }],
});
const wrapper = mountHome();
await flushPromises();
await wrapper.find('[data-testid="transfer-home-today"]').trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="transfer-source-select-card"]').exists()).toBe(true);
expect(api.listTransferSources).toHaveBeenCalled();
});
it('点击历史待办计数卡独立触发 backlog 卡片', async () => {
api.listTransferBacklog.mockResolvedValue([
{ item_id: 7, source_code: 'DBS-AWSBI', invoice_no: 'INV-001', material_no: 'MAT-1',
status: 'blocked_recoverable', reason: '收料 1200 / ERP 1000', age_days: 1, aging_level: 'normal' },
]);
const wrapper = mountHome();
await flushPromises();
await wrapper.find('[data-testid="transfer-home-recoverable"]').trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="transfer-backlog-card"]').exists()).toBe(true);
expect(api.listTransferBacklog).toHaveBeenCalled();
});
it('子视图提供“返回首页”并切回 home', async () => {
const wrapper = mountHome();
await flushPromises();
await wrapper.find('[data-testid="transfer-home-today"]').trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="transfer-source-select-card"]').exists()).toBe(true);
await wrapper.find('[data-testid="transfer-home-back"]').trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="transfer-home"]').exists()).toBe(true);
});
it('进入子流程时冒泡 flow-active=true,返回首页时 false(父级据此隐藏聊天输入框)', async () => {
const wrapper = mountHome();
await flushPromises();
expect(wrapper.emitted('flow-active')?.[0]?.[0]).toBe(false);
await wrapper.find('[data-testid="transfer-home-today"]').trigger('click');
await flushPromises();
expect(wrapper.emitted('flow-active')?.at(-1)?.[0]).toBe(true);
await wrapper.find('[data-testid="transfer-home-back"]').trigger('click');
await flushPromises();
expect(wrapper.emitted('flow-active')?.at(-1)?.[0]).toBe(false);
});
});
@@ -0,0 +1,134 @@
<!--
features/chat/components/messages/TransferHomePanel.vue
用途:在途仓自动调拨 Agent 的 Chat 首页入口区——home 视图展示标题、今日待办
入口与三张历史待办计数卡;点击入口独立触发 source-select / backlog 卡片。
依赖:TransferMessageView(复用自驱动卡片)、useChatTransfer、i18n chat.transfer.*。
逻辑:home 时只消费 backlogSummary 计数;非 home 时渲染 TransferMessageView。
卡片不注入消息流,因此无需后端 ChatLog 消息(决策:补首页入口 A 方案)。
-->
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import TransferMessageView from './TransferMessageView.vue';
import { useChatTransfer } from '../../composables/useChatTransfer';
const props = defineProps<{
agentName?: string;
}>();
const emit = defineEmits<{
/** 业务流激活状态:true 表示进入来源选择/待处理等子视图(父级据此隐藏聊天输入框)。 */
'flow-active': [active: boolean];
}>();
type HomeView = 'home' | 'source-select' | 'backlog';
const transfer = useChatTransfer();
const view = ref<HomeView>('home');
/** 进入非 home 时通知父级隐藏聊天输入框(决策:来源选择为业务页,无对话输入区)。 */
watch(view, (value) => emit('flow-active', value !== 'home'), { immediate: true });
/** home 视图仅需要待办汇总;进入时拉取计数。 */
async function loadHomeSummary() {
if (view.value !== 'home') return;
await transfer.loadBacklog();
}
onMounted(() => { void loadHomeSummary(); });
watch(view, () => { void loadHomeSummary(); });
const displayAgentName = computed(() => props.agentName || '在途仓自动调拨');
/** 非 home 视图把当前入口透传给自驱动的 TransferMessageView(决定 source-select 或 backlog)。 */
const childPayload = computed(() => (
view.value === 'source-select'
? { kind: 'source-select' }
: { kind: 'backlog' }
));
function goBack() {
view.value = 'home';
}
</script>
<template>
<div class="flex w-full flex-col items-center px-4 pb-2 pt-6 md:pb-4">
<!-- home:标题 + 今日/历史待办入口 -->
<template v-if="view === 'home'">
<h2 data-testid="transfer-home" class="mb-8 mt-6 shrink-0 text-center text-2xl font-bold text-primary md:mt-10 md:text-3xl">
{{ $t('chat.transfer.homeWelcome') }}
<span class="mx-1 text-brand-600">{{ displayAgentName }}</span>
</h2>
<div class="w-full max-w-3xl space-y-4">
<!-- 今日待办 -->
<section aria-label="今日待办">
<p class="mb-2 text-sm font-bold text-secondary">{{ $t('chat.transfer.homeTodayLabel') }}</p>
<button
type="button"
data-testid="transfer-home-today"
class="flex w-full items-center gap-3 rounded-2xl border border-brand-200 bg-brand-50 p-4 text-left transition-colors hover:bg-brand-100"
@click="view = 'source-select'"
>
<span class="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-brand-600 text-lg font-bold text-white">+</span>
<span class="min-w-0 flex-1">
<b class="block text-sm font-bold text-brand-700">{{ $t('chat.transfer.homeTodayAction') }}</b>
<span class="mt-1 block text-xs text-brand-600/80">{{ $t('chat.transfer.homeTodayHint') }}</span>
</span>
<span class="shrink-0 text-xl text-brand-600">›</span>
</button>
</section>
<!-- 历史待办 -->
<section aria-label="历史待办">
<p class="mb-2 text-sm font-bold text-secondary">{{ $t('chat.transfer.homeHistoryLabel') }}</p>
<div class="grid grid-cols-1 gap-3 sm:grid-cols-3">
<button
type="button"
data-testid="transfer-home-recoverable"
class="rounded-2xl border border-brand-200 bg-brand-50 p-4 text-left transition-colors hover:bg-brand-100"
@click="view = 'backlog'"
>
<b class="block text-2xl leading-none text-brand-600">{{ transfer.backlogSummary.value?.recoverable ?? 0 }}</b>
<b class="mt-2 block text-sm font-bold text-primary">{{ $t('chat.transfer.homeRecoverable') }}</b>
<span class="mt-1 block text-xs text-secondary">{{ $t('chat.transfer.homeRecoverableHint') }}</span>
</button>
<button
type="button"
data-testid="transfer-home-closed"
class="rounded-2xl border border-default bg-surface p-4 text-left transition-colors hover:border-brand-200 hover:bg-brand-50"
@click="view = 'backlog'"
>
<b class="block text-2xl leading-none text-secondary">{{ transfer.backlogSummary.value?.closed ?? 0 }}</b>
<b class="mt-2 block text-sm font-bold text-primary">{{ $t('chat.transfer.homeClosed') }}</b>
<span class="mt-1 block text-xs text-secondary">{{ $t('chat.transfer.homeClosedHint') }}</span>
</button>
<button
type="button"
data-testid="transfer-home-unknown"
class="rounded-2xl border border-amber-200 bg-amber-50 p-4 text-left transition-colors hover:bg-amber-100"
@click="view = 'backlog'"
>
<b class="block text-2xl leading-none text-amber-600">{{ transfer.backlogSummary.value?.unknown ?? 0 }}</b>
<b class="mt-2 block text-sm font-bold text-primary">{{ $t('chat.transfer.homeUnknown') }}</b>
<span class="mt-1 block text-xs text-secondary">{{ $t('chat.transfer.homeUnknownHint') }}</span>
</button>
</div>
</section>
</div>
</template>
<!-- 子流程:复用自驱动的 TransferMessageView -->
<div v-else class="w-full max-w-4xl pr-2">
<button
type="button"
data-testid="transfer-home-back"
class="mb-2 rounded-lg px-2 py-1 text-sm font-bold text-brand-600 transition-colors hover:bg-brand-50"
@click="goBack"
>
← {{ $t('chat.transfer.homeBack') }}
</button>
<TransferMessageView :payload="childPayload" />
</div>
</div>
</template>
@@ -0,0 +1,67 @@
<!--
features/chat/components/messages/TransferManualCloseDialog.vue
用途:人工关闭弹窗(原因必填;关闭后永久排除,历史保留)。
依赖:props(open/invoiceNo)、i18n chat.transfer.*。
逻辑:原因为空时确认按钮禁用;确认时 emit confirm(reason)。
-->
<script setup lang="ts">
import { ref, watch } from 'vue';
const props = defineProps<{
open: boolean;
invoiceNo: string;
}>();
const emit = defineEmits<{
confirm: [reason: string];
cancel: [];
}>();
const reason = ref('');
watch(
() => props.open,
(open) => {
if (open) reason.value = '';
},
);
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-4"
data-testid="transfer-manual-close-dialog"
>
<div class="w-full max-w-md rounded-2xl bg-surface p-5 shadow-xl">
<h3 class="text-base font-bold text-primary">{{ $t('chat.transfer.manualCloseTitle') }}</h3>
<p class="mt-1 text-xs text-muted">{{ invoiceNo }} · {{ $t('chat.transfer.manualCloseHint') }}</p>
<textarea
v-model="reason"
rows="3"
class="mt-3 w-full rounded-lg border border-default p-2 text-sm"
:placeholder="$t('chat.transfer.closeReasonPlaceholder')"
data-testid="transfer-close-reason"
/>
<div class="mt-4 flex justify-end gap-2">
<button
type="button"
class="rounded-lg border border-default px-4 py-1.5 text-sm text-secondary hover-surface-soft"
data-testid="transfer-close-cancel"
@click="emit('cancel')"
>
{{ $t('chat.transfer.cancel') }}
</button>
<button
type="button"
class="rounded-lg bg-brand-600 px-4 py-1.5 text-sm font-bold text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
:disabled="!reason.trim()"
data-testid="transfer-close-confirm"
@click="emit('confirm', reason.trim())"
>
{{ $t('chat.transfer.confirmClose') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,173 @@
/**
* features/chat/components/messages/TransferMessageView.spec.ts
* 用途:验证卡片自驱动接线——预检卡渲染、点“直接生成调拨单”真实调 API 并切换结果卡、
* 下载按钮调 requestBlob 封装、结果页无审计入口。
* 依赖:vi.mock(transfer.api)、@vue/test-utils、i18n。
* 逻辑:Mock API 断言调用参数与状态切换(对应后端 197 项测试的契约面)。
*/
import { mount, flushPromises } from '@vue/test-utils';
import { describe, expect, it, vi, beforeEach } from 'vitest';
import i18n from '@/i18n';
const api = vi.hoisted(() => ({
createTransferPrecheck: vi.fn(),
getTransferPrecheck: vi.fn(),
executeTransferPrecheck: vi.fn(),
getTransferRun: vi.fn(),
retryTransferItem: vi.fn(),
manualCloseTransferItem: vi.fn(),
downloadTransferReceiptFiles: vi.fn(),
downloadTransferErpInventory: vi.fn(),
downloadTransferExceptions: vi.fn(),
listTransferBacklog: vi.fn(),
getTransferBacklogSummary: vi.fn(),
listTransferSources: vi.fn(),
}));
vi.mock('@/features/chat/api/transfer.api', () => api);
import TransferMessageView from './TransferMessageView.vue';
const payload = {
kind: 'precheck',
summary: {
precheck_id: 'TPC-1',
status: 'ready_to_execute',
business_date: '2026-08-06',
eligible_receipt_date_to: '2026-08-05',
expires_at: '',
counts: { file_invoice_count: 1, not_matured_count: 0, prechecked_count: 1, executable_count: 1, blocked_count: 0 },
estimated_transfer_quantity: '1200',
estimated_erp_write_count: 1,
precheck_hash: 'sha256:x',
},
items: [{
source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器组件', specification: 'A',
invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200',
to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable',
}],
sources: [{ source_code: 'DBS-AWSBI', stage: 'file_ready', file_no: 'REC-1' }],
};
const runPayload = {
kind: 'result',
run_no: 'RUN-1',
status: 'success',
run: {
run_no: 'RUN-1',
status: 'success',
result: {
erp_documents: [{
document_no: 'TRF-10001', from_warehouse: 'DBS-TRANSIT', to_warehouse: 'HUB-CN01',
material_count: 1, total_quantity: '1200', posting_status: 'posted',
lines: [{ material_no: 'MAT-1', material_name: '连接器组件', specification: 'A', invoice_no: 'INV-001', quantity: '1200' }],
}],
exceptions: [],
},
},
};
describe('TransferMessageView self-driving wiring', () => {
beforeEach(() => {
vi.clearAllMocks();
api.executeTransferPrecheck.mockResolvedValue({ run_no: 'RUN-1', status: 'success' });
api.getTransferRun.mockResolvedValue(runPayload.run);
api.downloadTransferReceiptFiles.mockResolvedValue({ blob: new Blob(['z']), filename: 'r.zip' });
api.downloadTransferErpInventory.mockResolvedValue({ blob: new Blob(['c']), filename: 'e.csv' });
});
it('预检 payload 渲染预检卡,且默认勾选可执行项', () => {
const wrapper = mount(TransferMessageView, {
props: { payload },
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="transfer-precheck-card"]').exists()).toBe(true);
expect((wrapper.find('[data-testid="transfer-check-INV-001"]').element as HTMLInputElement).checked).toBe(true);
});
it('点击“直接生成调拨单”调用 execute API 并切换为结果卡', async () => {
const wrapper = mount(TransferMessageView, {
props: { payload },
global: { plugins: [i18n] },
});
await wrapper.find('[data-testid="transfer-generate-button"]').trigger('click');
await flushPromises();
expect(api.executeTransferPrecheck).toHaveBeenCalledWith('TPC-1', ['INV-001']);
expect(wrapper.find('[data-testid="transfer-result-card"]').exists()).toBe(true);
});
it('结果卡下载按钮调用下载 API(收料来源文件 + ERP 库存表)', async () => {
const wrapper = mount(TransferMessageView, {
props: { payload: runPayload },
global: { plugins: [i18n] },
});
await wrapper.find('[data-testid="transfer-download-receipt"]').trigger('click');
await wrapper.find('[data-testid="transfer-download-erp"]').trigger('click');
await flushPromises();
expect(api.downloadTransferReceiptFiles).toHaveBeenCalledWith('RUN-1');
expect(api.downloadTransferErpInventory).toHaveBeenCalledWith('RUN-1');
});
it('结果卡不出现执行审计入口(决策 19)', () => {
const wrapper = mount(TransferMessageView, {
props: { payload: runPayload },
global: { plugins: [i18n] },
});
expect(wrapper.text()).not.toContain('审计');
});
it('backlog 视图拉取待处理列表,重试/关闭调用对应 API', async () => {
api.listTransferBacklog.mockResolvedValue([{
item_id: 7, source_code: 'DBS-AWSBI', invoice_no: 'INV-001', material_no: 'MAT-1',
status: 'blocked_recoverable', reason: '收料 1200 / ERP 1000', age_days: 1, aging_level: 'normal',
}]);
api.getTransferBacklogSummary.mockResolvedValue({
recoverable: 1, closed: 0, unknown: 0, aging: { warn_3d: 0, escalate_5d: 0, critical_7d: 0 },
});
api.retryTransferItem.mockResolvedValue({ item_id: 7, status: 'ready_to_execute', attempt_no: 2 });
api.manualCloseTransferItem.mockResolvedValue({ item_id: 7, status: 'manually_closed' });
const wrapper = mount(TransferMessageView, {
props: { payload: { kind: 'backlog' } },
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="transfer-backlog-card"]').exists()).toBe(true);
expect(wrapper.text()).toContain('INV-001');
await wrapper.find('[data-testid="transfer-backlog-retry"]').trigger('click');
await flushPromises();
expect(api.retryTransferItem).toHaveBeenCalledWith(7);
await wrapper.find('[data-testid="transfer-backlog-close"]').trigger('click');
await wrapper.find('[data-testid="transfer-close-reason"]').setValue('线下已处理');
await wrapper.find('[data-testid="transfer-close-confirm"]').trigger('click');
await flushPromises();
expect(api.manualCloseTransferItem).toHaveBeenCalledWith(7, '线下已处理');
});
it('来源实例选择:加载列表 → 确认范围 → 创建预检并切换预检卡', async () => {
api.listTransferSources.mockResolvedValue([
{ source_code: 'DBS-AWSBI', display_name: 'AWSBI', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' },
]);
api.createTransferPrecheck.mockResolvedValue(payload.summary);
api.getTransferPrecheck.mockResolvedValue({
summary: payload.summary,
items: payload.items,
sources: payload.sources,
});
const wrapper = mount(TransferMessageView, {
props: { payload: { kind: 'source-select' } },
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="transfer-source-select-card"]').exists()).toBe(true);
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
await flushPromises();
expect(api.createTransferPrecheck).toHaveBeenCalledWith({ source_codes: ['DBS-AWSBI'] });
expect(wrapper.find('[data-testid="transfer-precheck-card"]').exists()).toBe(true);
});
});
@@ -0,0 +1,243 @@
<!--
features/chat/components/messages/TransferMessageView.vue
用途:在途调拨消息卡片的自驱动挂载视图——按 payload 形态渲染卡片,并把卡片按钮
(直接生成调拨单 / 下载 / 重试 / 关闭)经 useChatTransfer 真实调用 API。
依赖:Transfer*Card、useChatTransfer、i18n chat.transfer.*。
逻辑:payload 作为初始状态(ChatLog 回放);执行后切换为结果卡;下载走 requestBlob;
不展示执行审计入口(决策 19)。
-->
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import TransferPrecheckCard from './TransferPrecheckCard.vue';
import TransferFileProgressCard from './TransferFileProgressCard.vue';
import TransferProgressCard from './TransferProgressCard.vue';
import TransferResultCard from './TransferResultCard.vue';
import TransferBacklogSummaryCard from './TransferBacklogSummaryCard.vue';
import TransferManualCloseDialog from './TransferManualCloseDialog.vue';
import TransferSourceSelectCard from './TransferSourceSelectCard.vue';
import { useChatTransfer } from '../../composables/useChatTransfer';
import { useMessage } from '@/shared/composables/useMessage';
import type {
TransferBacklogItem,
TransferPrecheckItem,
TransferPrecheckSummary,
TransferRunResult,
TransferSourceProgress,
} from '../../types/transfer.types';
const props = defineProps<{
payload?: Record<string, unknown> | null;
}>();
const { error: notifyError } = useMessage();
/** 统一错误提示:BusinessError 带本地化 message,其余回退到 String(e)。 */
function reportError(e: unknown) {
notifyError(e instanceof Error ? e.message : String(e));
}
const kind = computed(() => String(props.payload?.kind ?? 'precheck'));
const mode = ref(kind.value);
const summaryRef = ref<TransferPrecheckSummary | null>((props.payload?.summary as TransferPrecheckSummary) ?? null);
const items = ref<TransferPrecheckItem[]>((props.payload?.items as TransferPrecheckItem[]) ?? []);
const runNo = ref(String(props.payload?.run_no ?? ''));
const status = ref(String(props.payload?.status ?? 'executing'));
const run = ref<TransferRunResult | null>((props.payload?.run as TransferRunResult) ?? null);
const busy = ref(false);
const closeTarget = ref<TransferBacklogItem | null>(null);
/** 正在重试收料 RPA 的来源编码集合(按来源独立展示重试中)。 */
const retryingSource = ref<Set<string>>(new Set());
const transfer = useChatTransfer();
/** 待处理异常视图:进入时拉取列表与汇总 */
onMounted(() => {
if (kind.value === 'backlog') {
void transfer.loadBacklog();
}
if (kind.value === 'source-select') {
void transfer.loadSources();
}
});
/** payload 更新时重置本地状态(历史回放/刷新);初始化组合式函数上下文 */
function applyPayload(payload?: Record<string, unknown> | null) {
if (!payload) return;
mode.value = String(payload.kind ?? 'precheck');
summaryRef.value = (payload.summary as TransferPrecheckSummary) ?? null;
items.value = (payload.items as TransferPrecheckItem[]) ?? [];
runNo.value = String(payload.run_no ?? '');
status.value = String(payload.status ?? 'executing');
run.value = (payload.run as TransferRunResult) ?? null;
const summaryValue = (payload.summary as TransferPrecheckSummary) ?? null;
if (summaryValue) {
transfer.precheckId.value = summaryValue.precheck_id;
transfer.selected.value = new Set(
(payload.items as TransferPrecheckItem[] ?? [])
.filter((item) => item.result === 'executable')
.map((item) => item.invoice_no),
);
}
if (runNo.value) {
transfer.runNo.value = runNo.value;
}
}
applyPayload(props.payload);
watch(() => props.payload, applyPayload);
/** 直接生成调拨单(决策 4/5:无独立确认页) */
async function onExecute(invoiceNos: string[]) {
busy.value = true;
try {
transfer.selected.value = new Set(invoiceNos);
const outcome = await transfer.execute();
if (outcome) {
mode.value = 'result';
runNo.value = outcome.run_no;
status.value = outcome.status;
run.value = transfer.run.value;
}
} catch (e) {
reportError(e);
} finally {
busy.value = false;
}
}
async function onDownloadReceipt() {
try {
await transfer.downloadReceiptFiles();
} catch (e) {
reportError(e);
}
}
async function onDownloadErp() {
try {
await transfer.downloadErpInventory();
} catch (e) {
reportError(e);
}
}
async function onDownloadExceptions() {
try {
await transfer.downloadExceptions();
} catch (e) {
reportError(e);
}
}
async function onBacklogRetry(itemId: number) {
busy.value = true;
try {
await transfer.retry(itemId);
await transfer.loadBacklog();
} catch (e) {
reportError(e);
} finally {
busy.value = false;
}
}
function onBacklogClose(item: TransferBacklogItem) {
closeTarget.value = item;
}
async function onCloseConfirm(reason: string) {
if (!closeTarget.value) return;
busy.value = true;
try {
await transfer.manualClose(closeTarget.value.item_id, reason);
closeTarget.value = null;
await transfer.loadBacklog();
} catch (e) {
reportError(e);
} finally {
busy.value = false;
}
}
/** 来源实例选择确认 → 创建预检并切换预检卡(决策 4:两步第一步) */
async function onSourceConfirm(sourceCodes: string[]) {
busy.value = true;
try {
await transfer.createPrecheck(sourceCodes);
mode.value = 'precheck';
summaryRef.value = transfer.precheck.value;
items.value = transfer.items.value;
run.value = null;
} catch (e) {
reportError(e);
} finally {
busy.value = false;
}
}
/** 对来源(单个或批量)重新触发收料 RPA 抓取,重试期间标记该来源(busy 独立于 confirm busy)。 */
async function onSourceRetry(sourceCodes: string[]) {
const codes = Array.isArray(sourceCodes) ? sourceCodes : [sourceCodes];
retryingSource.value = new Set([...retryingSource.value, ...codes]);
try {
// 逐来源触发,避免一次并发 EPR/RPA 竞态;失败中断剩余。
for (const code of codes) {
await transfer.retrySourceRpa(code);
}
} catch (e) {
reportError(e);
} finally {
const next = new Set(retryingSource.value);
for (const code of codes) next.delete(code);
retryingSource.value = next;
}
}
</script>
<template>
<div>
<TransferFileProgressCard
v-if="mode === 'file-progress'"
:sources="(props.payload?.sources as TransferSourceProgress[]) ?? []"
/>
<TransferSourceSelectCard
v-else-if="mode === 'source-select'"
:sources="transfer.sourceOptions.value"
:busy="busy"
:retrying="retryingSource"
@confirm="onSourceConfirm"
@retry="onSourceRetry"
/>
<TransferPrecheckCard
v-else-if="mode === 'precheck' && summaryRef"
:summary="summaryRef"
:items="items"
:selected="transfer.selected.value"
:busy="busy"
@toggle="(invoiceNo, checked) => transfer.toggleSelect(invoiceNo, checked)"
@execute="onExecute"
/>
<TransferProgressCard v-else-if="mode === 'progress'" :run-no="runNo" :status="status" :busy="busy" />
<TransferResultCard
v-else-if="mode === 'result' && run"
:run="run"
@download-receipt="onDownloadReceipt"
@download-erp="onDownloadErp"
@download-exceptions="onDownloadExceptions"
/>
<TransferBacklogSummaryCard
v-else-if="mode === 'backlog'"
:items="transfer.backlog.value"
@retry="onBacklogRetry"
@close="onBacklogClose"
@refresh="() => transfer.loadBacklog()"
/>
<TransferManualCloseDialog
v-if="closeTarget"
:open="Boolean(closeTarget)"
:invoice-no="closeTarget.invoice_no"
@confirm="onCloseConfirm"
@cancel="closeTarget = null"
/>
</div>
</template>
@@ -0,0 +1,157 @@
<!--
features/chat/components/messages/TransferPrecheckCard.vue
用途:预检卡——计数 + 调拨明细表(决策 6 十列)+ 勾选 + “直接生成调拨单”按钮。
依赖:props(summary/items/selected/busy)、i18n chat.transfer.*。
逻辑:阻断/未成熟项 checkbox 禁用;无选择或 busy 时生成按钮禁用;
emit execute(invoiceNos)(决策 4/5:无独立确认页)。
-->
<script setup lang="ts">
import { computed } from 'vue';
import type { TransferPrecheckItem, TransferPrecheckSummary } from '../../types/transfer.types';
const props = defineProps<{
summary: TransferPrecheckSummary;
items: TransferPrecheckItem[];
selected: Set<string>;
busy?: boolean;
}>();
const emit = defineEmits<{
toggle: [invoiceNo: string, checked: boolean];
execute: [invoiceNos: string[]];
}>();
const selectedCount = computed(() =>
props.items.filter((item) => item.result === 'executable' && props.selected.has(item.invoice_no)).length,
);
const executeDisabled = computed(() => props.busy || selectedCount.value === 0);
function isSelectable(item: TransferPrecheckItem): boolean {
return item.result === 'executable';
}
function isChecked(item: TransferPrecheckItem): boolean {
return props.selected.has(item.invoice_no);
}
function resultLabel(result: string): string {
const map: Record<string, string> = {
executable: 'chat.transfer.resultExecutable',
not_matured: 'chat.transfer.resultNotMatured',
blocked_quantity_mismatch: 'chat.transfer.resultBlocked',
blocked_inventory_not_found: 'chat.transfer.resultBlocked',
blocked_future_date: 'chat.transfer.resultBlocked',
erp_query_timeout: 'chat.transfer.resultUnknown',
result_unknown: 'chat.transfer.resultUnknown',
};
return map[result] ?? 'chat.transfer.resultBlocked';
}
</script>
<template>
<div class="my-2 rounded-2xl border border-brand-100 bg-surface p-4 shadow-sm" data-testid="transfer-precheck-card">
<div class="mb-3 flex flex-wrap items-center justify-between gap-3">
<h3 class="text-sm font-bold text-primary">{{ $t('chat.transfer.precheckTitle') }}</h3>
<span class="text-xs text-muted">{{ $t('chat.transfer.businessDate') }}:{{ summary.business_date }}</span>
</div>
<div class="mb-3 grid grid-cols-2 gap-2 sm:grid-cols-5" data-testid="transfer-precheck-counts">
<div class="rounded-lg bg-surface-soft p-2 text-center">
<div class="text-lg font-black text-brand-600">{{ summary.counts.executable_count }}</div>
<div class="text-[11px] text-muted">{{ $t('chat.transfer.executableCount') }}</div>
</div>
<div class="rounded-lg bg-surface-soft p-2 text-center">
<div class="text-lg font-black text-secondary">{{ summary.counts.not_matured_count }}</div>
<div class="text-[11px] text-muted">{{ $t('chat.transfer.notMaturedCount') }}</div>
</div>
<div class="rounded-lg bg-surface-soft p-2 text-center">
<div class="text-lg font-black text-secondary">{{ summary.counts.blocked_count }}</div>
<div class="text-[11px] text-muted">{{ $t('chat.transfer.blockedCount') }}</div>
</div>
<div class="rounded-lg bg-surface-soft p-2 text-center">
<div class="text-lg font-black text-brand-600">{{ summary.estimated_transfer_quantity }}</div>
<div class="text-[11px] text-muted">{{ $t('chat.transfer.estimatedQuantity') }}</div>
</div>
<div class="rounded-lg bg-surface-soft p-2 text-center">
<div class="text-lg font-black text-brand-600">{{ summary.estimated_erp_write_count }}</div>
<div class="text-[11px] text-muted">{{ $t('chat.transfer.estimatedErpWrites') }}</div>
</div>
</div>
<div class="overflow-x-auto">
<table class="w-full min-w-[1100px] text-xs" data-testid="transfer-precheck-table">
<thead>
<tr class="border-b border-default bg-surface-soft text-left text-[11px] text-muted">
<th class="p-2"></th>
<th class="p-2">{{ $t('chat.transfer.colSource') }}</th>
<th class="p-2">{{ $t('chat.transfer.colMaterial') }}</th>
<th class="p-2">{{ $t('chat.transfer.colName') }}</th>
<th class="p-2">{{ $t('chat.transfer.colSpec') }}</th>
<th class="p-2">{{ $t('chat.transfer.colInvoice') }}</th>
<th class="p-2">{{ $t('chat.transfer.colFromWarehouse') }}</th>
<th class="p-2">{{ $t('chat.transfer.colFromQty') }}</th>
<th class="p-2">{{ $t('chat.transfer.colToWarehouse') }}</th>
<th class="p-2">{{ $t('chat.transfer.colToQty') }}</th>
<th class="p-2">{{ $t('chat.transfer.colResult') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="item in items"
:key="item.invoice_no"
class="border-b border-subtle"
:class="{ 'bg-surface-soft text-muted': !isSelectable(item) }"
:data-testid="`transfer-item-${item.invoice_no}`"
>
<td class="p-2">
<input
type="checkbox"
:checked="isChecked(item)"
:disabled="!isSelectable(item) || busy"
:data-testid="`transfer-check-${item.invoice_no}`"
@change="emit('toggle', item.invoice_no, ($event.target as HTMLInputElement).checked)"
/>
</td>
<td class="p-2">{{ item.source_code }}</td>
<td class="p-2">{{ item.material_no }}</td>
<td class="p-2">{{ item.material_name }}</td>
<td class="p-2">{{ item.specification }}</td>
<td class="p-2 font-semibold">{{ item.invoice_no }}</td>
<td class="p-2">{{ item.from_warehouse }}</td>
<td class="p-2">{{ item.from_quantity ?? '—' }}</td>
<td class="p-2">{{ item.to_warehouse }}</td>
<td class="p-2">{{ item.to_quantity }}</td>
<td class="p-2">
<span
class="rounded-full px-2 py-0.5 font-bold"
:class="{
'bg-emerald-50 text-emerald-700': item.result === 'executable',
'bg-amber-50 text-amber-700': item.result === 'not_matured',
'bg-red-50 text-red-700': !isSelectable(item) && item.result !== 'not_matured',
}"
>
{{ $t(resultLabel(item.result)) }}
</span>
</td>
</tr>
</tbody>
</table>
</div>
<div class="mt-3 flex items-center justify-end gap-3 border-t border-subtle pt-3">
<span class="text-xs text-muted">
{{ $t('chat.transfer.selectedCount', { count: selectedCount }) }} ·
{{ $t('chat.transfer.estimatedErpWrites') }}:{{ summary.estimated_erp_write_count }}
</span>
<button
type="button"
class="rounded-lg bg-brand-600 px-4 py-1.5 text-sm font-bold text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
:disabled="executeDisabled"
:data-testid="'transfer-generate-button'"
@click="emit('execute', items.filter(isSelectable).filter(isChecked).map((item) => item.invoice_no))"
>
{{ $t('chat.transfer.generateTransfer') }}
</button>
</div>
</div>
</template>
@@ -0,0 +1,60 @@
<!--
features/chat/components/messages/TransferProgressCard.vue
用途:Run 执行进度卡(页面关闭/刷新后经 run_no 恢复)。
依赖:props(runNo/status/busy)、i18n chat.transfer.*。
逻辑:展示 Run 编号与状态,提供刷新按钮;页面刷新不取消后台 Run。
-->
<script setup lang="ts">
defineProps<{
runNo: string;
status: string;
busy?: boolean;
}>();
const emit = defineEmits<{
refresh: [];
}>();
function statusLabel(status: string): string {
const map: Record<string, string> = {
executing: 'chat.transfer.runExecuting',
success: 'chat.transfer.runSuccess',
partial_failed: 'chat.transfer.runPartialFailed',
failed: 'chat.transfer.runFailed',
cancelled: 'chat.transfer.runCancelled',
};
return map[status] ?? 'chat.transfer.runExecuting';
}
</script>
<template>
<div class="my-2 rounded-2xl border border-brand-100 bg-surface p-4 shadow-sm" data-testid="transfer-progress-card">
<div class="flex items-center justify-between">
<div>
<div class="text-sm font-bold text-primary">{{ $t('chat.transfer.runProgress') }}</div>
<div class="mt-1 text-xs text-muted">{{ runNo }}</div>
</div>
<span
class="rounded-full px-2 py-0.5 text-xs font-bold"
:class="{
'bg-blue-50 text-blue-700': status === 'executing',
'bg-emerald-50 text-emerald-700': status === 'success',
'bg-amber-50 text-amber-700': status === 'partial_failed',
'bg-red-50 text-red-700': status === 'failed' || status === 'cancelled',
}"
data-testid="transfer-run-status"
>
{{ $t(statusLabel(status)) }}
</span>
<button
type="button"
class="rounded-lg border border-default px-3 py-1 text-xs font-bold text-secondary hover-surface-soft"
:disabled="busy"
data-testid="transfer-run-refresh"
@click="emit('refresh')"
>
{{ $t('chat.transfer.refreshProgress') }}
</button>
</div>
</div>
</template>
@@ -0,0 +1,131 @@
<!--
features/chat/components/messages/TransferResultCard.vue
用途:结果卡——按 ERP 单号聚合(决策 20)、可展开物料明细、未生成单据异常区、
下载收料来源文件 / ERP 库存表(决策 21)。不展示执行审计入口(决策 19)。
依赖:props.run、i18n chat.transfer.*。
逻辑:<details> 展开/收起物料行;异常单独分区;两个下载按钮 + 异常 Excel。
-->
<script setup lang="ts">
import type { TransferRunResult } from '../../types/transfer.types';
defineProps<{
run: TransferRunResult;
}>();
const emit = defineEmits<{
downloadReceipt: [];
downloadErp: [];
downloadExceptions: [];
}>();
function reasonLabel(reason: string): string {
const map: Record<string, string> = {
blocked_quantity_mismatch: 'chat.transfer.resultBlocked',
blocked_inventory_not_found: 'chat.transfer.resultBlocked',
business_failed: 'chat.transfer.exceptionBusinessFailed',
technical_failed: 'chat.transfer.exceptionTechnicalFailed',
result_unknown: 'chat.transfer.resultUnknown',
precheck_expired: 'chat.transfer.exceptionPrecheckExpired',
};
return map[reason] ?? 'chat.transfer.resultBlocked';
}
</script>
<template>
<div class="my-2 rounded-2xl border border-brand-100 bg-surface p-4 shadow-sm" data-testid="transfer-result-card">
<div class="mb-3 flex items-center justify-between">
<h3 class="text-sm font-bold text-primary">{{ $t('chat.transfer.resultTitle') }}</h3>
<span class="text-xs text-muted">{{ run.run_no }}</span>
</div>
<!-- 已生成 ERP 单据:按单号聚合 + 可展开物料明细 -->
<div v-if="run.result.erp_documents.length" class="flex flex-col gap-2">
<details
v-for="doc in run.result.erp_documents"
:key="doc.document_no"
class="rounded-lg border border-default"
data-testid="transfer-erp-document"
>
<summary class="flex cursor-pointer flex-wrap items-center justify-between gap-2 px-3 py-2 text-xs">
<span class="font-bold text-brand-700">{{ doc.document_no }}</span>
<span class="text-secondary">{{ doc.from_warehouse }} → {{ doc.to_warehouse }}</span>
<span class="text-muted">{{ $t('chat.transfer.materialCount', { count: doc.material_count }) }}</span>
<span class="font-bold text-secondary">{{ doc.total_quantity }}</span>
<span class="rounded-full bg-emerald-50 px-2 py-0.5 font-bold text-emerald-700">
{{ $t('chat.transfer.posted') }}
</span>
</summary>
<div class="border-t border-subtle px-3 py-2">
<table class="w-full text-xs" data-testid="transfer-erp-document-lines">
<thead>
<tr class="text-left text-[11px] text-muted">
<th class="p-1">{{ $t('chat.transfer.colMaterial') }}</th>
<th class="p-1">{{ $t('chat.transfer.colName') }}</th>
<th class="p-1">{{ $t('chat.transfer.colSpec') }}</th>
<th class="p-1">{{ $t('chat.transfer.colInvoice') }}</th>
<th class="p-1">{{ $t('chat.transfer.colToQty') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="line in doc.lines" :key="line.invoice_no" class="border-t border-subtle">
<td class="p-1">{{ line.material_no }}</td>
<td class="p-1">{{ line.material_name }}</td>
<td class="p-1">{{ line.specification }}</td>
<td class="p-1">{{ line.invoice_no }}</td>
<td class="p-1">{{ line.quantity }}</td>
</tr>
</tbody>
</table>
</div>
</details>
</div>
<div v-else class="mb-3 rounded-lg bg-surface-soft p-3 text-xs text-muted">
{{ $t('chat.transfer.noDocuments') }}
</div>
<!-- 未生成 ERP 单据的异常区(决策 20 单独展示) -->
<div v-if="run.result.exceptions.length" class="mt-3" data-testid="transfer-exceptions-area">
<h4 class="mb-1 text-xs font-bold text-secondary">{{ $t('chat.transfer.exceptionsTitle') }}</h4>
<ul class="flex flex-col gap-1">
<li
v-for="exc in run.result.exceptions"
:key="exc.invoice_no"
class="rounded-lg bg-red-50 px-3 py-1.5 text-xs text-red-700"
data-testid="transfer-exception-item"
>
<span class="font-bold">{{ exc.invoice_no }}</span>
<span class="mx-1 text-red-400">·</span>{{ exc.source_code }} · {{ $t(reasonLabel(exc.reason)) }}
<div class="text-[11px] text-red-500">{{ exc.facts }}</div>
</li>
</ul>
</div>
<!-- 下载:收料来源文件 + ERP 库存表(决策 21);无审计入口(决策 19) -->
<div class="mt-3 flex flex-wrap gap-2 border-t border-subtle pt-3" data-testid="transfer-result-downloads">
<button
type="button"
class="rounded-lg border border-brand-200 px-3 py-1.5 text-xs font-bold text-brand-700 hover:bg-brand-50"
data-testid="transfer-download-receipt"
@click="emit('downloadReceipt')"
>
{{ $t('chat.transfer.downloadReceiptFiles') }}
</button>
<button
type="button"
class="rounded-lg border border-brand-200 px-3 py-1.5 text-xs font-bold text-brand-700 hover:bg-brand-50"
data-testid="transfer-download-erp"
@click="emit('downloadErp')"
>
{{ $t('chat.transfer.downloadErpInventory') }}
</button>
<button
type="button"
class="rounded-lg border border-default px-3 py-1.5 text-xs font-bold text-secondary hover-surface-soft"
data-testid="transfer-download-exceptions"
@click="emit('downloadExceptions')"
>
{{ $t('chat.transfer.downloadExceptions') }}
</button>
</div>
</div>
</template>
@@ -0,0 +1,89 @@
/**
* features/chat/components/messages/TransferSourceSelectCard.spec.ts
* 用途:来源实例选择卡——平台分组、全选已启用、清空、按收料文件状态门禁确认、
* 确认提交、重试收料 RPA。
* 依赖:@vue/test-utils、i18n。
* 逻辑:平台 DBS/Crane 仅分组;实例为选择与执行边界(决策 2/3/4);
* 所选来源需至少一个 has_ready_file 才能确认预检(决策:无 ready 文件禁止确认)。
*/
import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import i18n from '@/i18n';
import TransferSourceSelectCard from './TransferSourceSelectCard.vue';
const readySources = [
{ source_code: 'DBS-AWSBI', display_name: 'AWSBI 在途仓', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' },
{ source_code: 'DBS-AWSSG', display_name: 'AWSSG 在途仓', platform: 'dbs', enabled: true, file_status: 'none' },
{ source_code: 'CRANE-SZ', display_name: '深圳在途仓', platform: 'crane', enabled: true, has_ready_file: true, file_status: 'ready' },
];
function mountCard(props = {}, sources = readySources) {
return mount(TransferSourceSelectCard, {
props: { sources, ...props },
global: { plugins: [i18n] },
});
}
describe('TransferSourceSelectCard', () => {
it('按平台分组展示来源实例', () => {
const wrapper = mountCard();
expect(wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"]').text()).toContain('DBS-AWSBI');
expect(wrapper.find('[data-testid="transfer-source-option-CRANE-SZ"]').text()).toContain('CRANE-SZ');
});
it('未选任何来源时确认按钮禁用(需至少一个 ready 文件来源)', () => {
const wrapper = mountCard();
expect((wrapper.find('[data-testid="transfer-source-confirm"]').element as HTMLButtonElement).disabled).toBe(true);
});
it('勾选含 ready 文件来源后确认提交所选来源', async () => {
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-option-CRANE-SZ"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
expect(wrapper.emitted('confirm')?.[0][0]).toEqual(['DBS-AWSBI', 'CRANE-SZ']);
});
it('仅勾选无 ready 文件来源时不提交(门禁)', async () => {
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSSG"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
expect(wrapper.emitted('confirm')).toBeUndefined();
});
it('“全选可见”勾选全部启用实例', async () => {
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-select-visible"]').trigger('click');
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
expect(wrapper.emitted('confirm')?.[0][0]).toEqual(['DBS-AWSBI', 'DBS-AWSSG', 'CRANE-SZ']);
});
it('“清空”清空已选实例', async () => {
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-select-visible"]').trigger('click');
await wrapper.find('[data-testid="transfer-source-clear"]').trigger('click');
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
expect(wrapper.emitted('confirm')).toBeUndefined();
});
it('“只选可重试”勾选无文件/失败来源', async () => {
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-select-retryable"]').trigger('click');
const selected = (wrapper.find('[data-testid="transfer-source-confirm"]').element as HTMLButtonElement).disabled;
// 可重试来源为 DBS-AWSSG(none);选中它但无 ready 文件 → 确认仍禁用(门禁)。
expect(selected).toBe(true);
});
it('点击行尾重试图标 emit retry([sourceCode])', async () => {
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-retry-DBS-AWSSG"]').trigger('click');
expect(wrapper.emitted('retry')?.[0][0]).toEqual(['DBS-AWSSG']);
});
it('批量重试仅传可重试来源', async () => {
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-select-retryable"]').trigger('click');
await wrapper.find('[data-testid="transfer-source-batch-retry"]').trigger('click');
expect(wrapper.emitted('retry')?.[0][0]).toEqual(['DBS-AWSSG']);
});
});
@@ -0,0 +1,246 @@
<!--
features/chat/components/messages/TransferSourceSelectCard.vue
用途:来源实例选择卡(决策 2/3/4:手工两步第一步)——按平台 DBS/Crane 分组勾选实例,
“确认范围并预检”发起预检。
依赖:props.sources、i18n chat.transfer.*。
逻辑:平台仅分组不可直接执行;未选任何实例时确认按钮禁用。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '@/shared/composables/useMessage';
import type { TransferSourceOption } from '../../types/transfer.types';
const props = defineProps<{
sources: TransferSourceOption[];
busy?: boolean;
/** 正在重试收料 RPA 的来源编码集合 */
retrying?: Set<string>;
}>();
const emit = defineEmits<{
confirm: [sourceCodes: string[]];
/** 批量重试收料 RPA:传来源编码列表 */
retry: [sourceCodes: string[]];
}>();
const { warning: notifyWarning } = useMessage();
const { t } = useI18n();
const selected = ref<Set<string>>(new Set());
const platforms = computed(() => [...new Set(props.sources.map((source) => source.platform))]);
const selectedCount = computed(() => selected.value.size);
/** 可重试判定:仅 待抓取(none) / 抓取失败(failed) 的来源可重试(ready/fetching 不重复触发)。 */
function isRetryable(source: TransferSourceOption): boolean {
return source.file_status === 'none' || source.file_status === 'failed';
}
/** 全部可重试来源。 */
const retryableSources = computed(() => props.sources.filter(isRetryable));
/** 已选来源中可重试的数量。 */
const selectedRetryableCount = computed(() =>
[...selected.value].filter((code) => props.sources.some((s) => s.source_code === code && isRetryable(s))).length,
);
const batchRetryDisabled = computed(() => props.busy || selectedRetryableCount.value === 0);
/** 已选来源中是否有具备 ready 文件的(门禁:都无 ready 文件则禁止确认预检)。 */
const selectedHasReadyFile = computed(() =>
[...selected.value].some((code) => props.sources.find((s) => s.source_code === code)?.has_ready_file),
);
const confirmDisabled = computed(() => props.busy || selectedCount.value === 0 || !selectedHasReadyFile.value);
function toggle(sourceCode: string, checked: boolean) {
const next = new Set(selected.value);
if (checked) next.add(sourceCode);
else next.delete(sourceCode);
selected.value = next;
}
function togglePlatform(platform: string, checked: boolean) {
const next = new Set(selected.value);
for (const source of props.sources) {
if (source.platform === platform) {
if (checked) next.add(source.source_code);
else next.delete(source.source_code);
}
}
selected.value = next;
}
/** 全选当前可见来源(已启用实例)。 */
function selectVisible() {
selected.value = new Set(props.sources.filter((source) => source.enabled).map((source) => source.source_code));
}
/** 只选可重试来源(待抓取/抓取失败),来源多时一键收敛。 */
function selectRetryable() {
selected.value = new Set(retryableSources.value.map((source) => source.source_code));
}
/** 清空选择。 */
function clearSelected() {
selected.value = new Set();
}
/** 批量重试收料 RPA:仅触发所选来源中可重试的那部分。 */
function batchRetry() {
const codes = [...selected.value].filter(
(code) => props.sources.some((s) => s.source_code === code && isRetryable(s)),
);
if (codes.length === 0) {
notifyWarning(t('chat.transfer.noRetryable'), t('chat.transfer.sourceSelectTitle'));
return;
}
emit('retry', codes);
}
function confirm() {
if (selectedCount.value === 0) {
notifyWarning(t('chat.transfer.needSelectSource'), t('chat.transfer.sourceSelectTitle'));
return;
}
if (!selectedHasReadyFile.value) {
notifyWarning(t('chat.transfer.needReadyFile'), t('chat.transfer.sourceSelectTitle'));
return;
}
emit('confirm', [...selected.value]);
}
</script>
<template>
<div class="my-2 rounded-2xl border border-brand-100 bg-surface p-4 shadow-sm" data-testid="transfer-source-select-card">
<h3 class="mb-1 text-sm font-bold text-primary">{{ $t('chat.transfer.sourceSelectTitle') }}</h3>
<p class="mb-3 text-xs text-muted">{{ $t('chat.transfer.sourceSelectHint') }}</p>
<div class="mb-3 flex flex-wrap items-center gap-2">
<button
type="button"
class="rounded-lg border border-brand-200 px-3 py-1.5 text-xs font-bold text-brand-700 hover:bg-brand-50 disabled:opacity-50"
:disabled="busy"
data-testid="transfer-source-select-visible"
@click="selectVisible"
>
{{ $t('chat.transfer.selectVisible') }}
</button>
<button
type="button"
class="rounded-lg border border-brand-200 px-3 py-1.5 text-xs font-bold text-brand-700 hover:bg-brand-50 disabled:opacity-50"
:disabled="busy"
data-testid="transfer-source-select-retryable"
@click="selectRetryable"
>
{{ $t('chat.transfer.selectRetryable') }}
</button>
<button
type="button"
class="rounded-lg bg-brand-600 px-3 py-1.5 text-xs font-bold text-white hover:bg-brand-700 disabled:opacity-50"
:disabled="batchRetryDisabled"
data-testid="transfer-source-batch-retry"
@click="batchRetry"
>
{{ $t('chat.transfer.batchRetry') }}
</button>
<button
type="button"
class="rounded-lg border border-default px-3 py-1.5 text-xs font-bold text-secondary hover-surface-soft disabled:opacity-50"
:disabled="busy"
data-testid="transfer-source-clear"
@click="clearSelected"
>
{{ $t('chat.transfer.clearSources') }}
</button>
<span class="ml-auto text-xs text-muted">
{{ $t('chat.transfer.selectedSourceCount', { count: selectedCount }) }}
<span v-if="selectedRetryableCount > 0" class="text-amber-600"> · {{ $t('chat.transfer.selectedRetryableCount', { count: selectedRetryableCount }) }}</span>
</span>
</div>
<div v-for="platform in platforms" :key="platform" class="mb-3 rounded-lg border border-subtle">
<div class="flex items-center justify-between rounded-t-lg bg-surface-soft px-3 py-1.5">
<b class="text-xs text-secondary">{{ platform.toUpperCase() }}</b>
<label class="text-[11px] text-muted">
<input
type="checkbox"
:checked="props.sources.filter((source) => source.platform === platform).every((source) => selected.has(source.source_code))"
@change="togglePlatform(platform, ($event.target as HTMLInputElement).checked)"
/>
{{ $t('chat.transfer.selectAll') }}
</label>
</div>
<div class="grid grid-cols-1 gap-1 p-2 sm:grid-cols-2">
<div
v-for="source in props.sources.filter((item) => item.platform === platform)"
:key="source.source_code"
class="flex items-center gap-2 rounded-lg px-2 py-1.5 hover-surface-soft"
:data-testid="`transfer-source-option-${source.source_code}`"
>
<input
type="checkbox"
:checked="selected.has(source.source_code)"
:disabled="busy"
@change="toggle(source.source_code, ($event.target as HTMLInputElement).checked)"
/>
<span class="min-w-0 flex-1">
<span class="block truncate text-xs font-semibold text-secondary">{{ source.source_code }}</span>
<span class="block truncate text-[11px] text-muted">{{ source.display_name }}</span>
</span>
<span class="shrink-0">
<span
v-if="source.has_ready_file"
class="inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2 py-0.5 text-[10px] font-bold text-emerald-700"
:data-testid="`transfer-source-status-${source.source_code}`"
>
{{ t('chat.transfer.fileReady') }}
</span>
<span
v-else-if="source.file_status === 'fetching'"
class="inline-flex items-center gap-1 rounded-full bg-amber-50 px-2 py-0.5 text-[10px] font-bold text-amber-700"
:data-testid="`transfer-source-status-${source.source_code}`"
>
{{ t('chat.transfer.fileFetching') }}
</span>
<span
v-else-if="source.file_status === 'failed'"
class="inline-flex items-center gap-1 rounded-full bg-red-50 px-2 py-0.5 text-[10px] font-bold text-red-700"
:data-testid="`transfer-source-status-${source.source_code}`"
>
{{ t('chat.transfer.fileFailed') }}
</span>
<span
v-else
class="inline-flex items-center gap-1 rounded-full bg-surface-strong px-2 py-0.5 text-[10px] font-bold text-muted"
:data-testid="`transfer-source-status-${source.source_code}`"
>
{{ t('chat.transfer.fileNone') }}
</span>
<button
type="button"
class="ml-1 inline-flex h-6 w-6 items-center justify-center rounded-md border border-default text-sm text-muted hover:border-brand-200 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
:disabled="busy || !isRetryable(source) || retrying?.has(source.source_code)"
:title="t('chat.transfer.retryReceipt')"
:data-testid="`transfer-source-retry-${source.source_code}`"
@click.stop="emit('retry', [source.source_code])"
>
<span aria-hidden="true">{{ retrying?.has(source.source_code) ? '…' : '↻' }}</span>
</button>
</span>
</div>
</div>
</div>
<div class="flex items-center justify-end gap-3 border-t border-subtle pt-3">
<span class="text-xs text-muted">{{ $t('chat.transfer.selectedCount', { count: selectedCount }) }}</span>
<button
type="button"
class="rounded-lg bg-brand-600 px-4 py-1.5 text-sm font-bold text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
:disabled="confirmDisabled"
data-testid="transfer-source-confirm"
@click="confirm"
>
{{ $t('chat.transfer.confirmScopeAndPrecheck') }}
</button>
</div>
</div>
</template>
@@ -0,0 +1,147 @@
/**
* features/chat/components/messages/transferCards.spec.ts
* 用途:验证在途调拨三张核心卡片(文件进度/预检/结果)+ 关闭弹窗的交互与禁用语义。
* 依赖:@vue/test-utils、i18n、transfer.types。
* 逻辑:断言按钮禁用、勾选禁用、ERP 单号展开/收起、异常展示、下载按钮与
* 结果页不出现“查看执行审计”入口(决策 19)。
*/
import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import i18n from '@/i18n';
import TransferFileProgressCard from './TransferFileProgressCard.vue';
import TransferPrecheckCard from './TransferPrecheckCard.vue';
import TransferResultCard from './TransferResultCard.vue';
import TransferManualCloseDialog from './TransferManualCloseDialog.vue';
const mountOptions = { global: { plugins: [i18n] } };
const summary = {
precheck_id: 'TPC-1',
status: 'ready_to_execute',
business_date: '2026-08-06',
eligible_receipt_date_to: '2026-08-05',
expires_at: '',
counts: { file_invoice_count: 3, not_matured_count: 1, prechecked_count: 2, executable_count: 2, blocked_count: 0 },
estimated_transfer_quantity: '2400',
estimated_erp_write_count: 2,
precheck_hash: 'sha256:x',
};
const items = [
{ source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器', specification: 'A', invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable' },
{ source_code: 'DBS-AWSBI', material_no: 'MAT-2', material_name: '控制器', specification: 'B', invoice_no: 'INV-041', from_warehouse: '', from_quantity: null, to_warehouse: '', to_quantity: '400', result: 'not_matured' },
];
describe('TransferFileProgressCard', () => {
it('按来源显示阶段,不伪造总百分比', () => {
const wrapper = mount(TransferFileProgressCard, {
props: { sources: [
{ source_code: 'DBS-AWSBI', stage: 'file_ready', file_no: 'REC-1', file_version: 'v3' },
{ source_code: 'CRANE-SZ', stage: 'waiting_rpa_callback' },
] },
...mountOptions,
});
expect(wrapper.find('[data-testid="transfer-source-DBS-AWSBI"]').text()).toContain('REC-1');
expect(wrapper.find('[data-testid="transfer-source-CRANE-SZ"]').text()).toContain('RPA');
});
});
describe('TransferPrecheckCard', () => {
it('阻断/未成熟项 checkbox 禁用;可执行项可选', () => {
const wrapper = mount(TransferPrecheckCard, {
props: { summary, items, selected: new Set(['INV-001']) },
...mountOptions,
});
const executableCheck = wrapper.find('[data-testid="transfer-check-INV-001"]');
const maturedCheck = wrapper.find('[data-testid="transfer-check-INV-041"]');
expect((executableCheck.element as HTMLInputElement).disabled).toBe(false);
expect((maturedCheck.element as HTMLInputElement).disabled).toBe(true);
});
it('未选择任何项时生成按钮禁用', () => {
const wrapper = mount(TransferPrecheckCard, {
props: { summary, items, selected: new Set() },
...mountOptions,
});
expect((wrapper.find('[data-testid="transfer-generate-button"]').element as HTMLButtonElement).disabled).toBe(true);
});
it('busy 时生成按钮禁用', () => {
const wrapper = mount(TransferPrecheckCard, {
props: { summary, items, selected: new Set(['INV-001']), busy: true },
...mountOptions,
});
expect((wrapper.find('[data-testid="transfer-generate-button"]').element as HTMLButtonElement).disabled).toBe(true);
});
it('点击生成按钮仅提交可执行勾选项', async () => {
const wrapper = mount(TransferPrecheckCard, {
props: { summary, items, selected: new Set(['INV-001']) },
...mountOptions,
});
await wrapper.find('[data-testid="transfer-generate-button"]').trigger('click');
expect(wrapper.emitted('execute')?.[0][0]).toEqual(['INV-001']);
});
});
describe('TransferResultCard', () => {
const run = {
run_no: 'RUN-1',
status: 'partial_failed',
result: {
erp_documents: [{
document_no: 'TRF-10001',
from_warehouse: 'DBS-TRANSIT',
to_warehouse: 'HUB-CN01',
material_count: 1,
total_quantity: '1200',
posting_status: 'posted',
lines: [{ material_no: 'MAT-1', material_name: '连接器', specification: 'A', invoice_no: 'INV-001', quantity: '1200' }],
}],
exceptions: [{ source_code: 'DBS-AWSBI', invoice_no: 'INV-999', material_no: 'MAT-9', reason: 'business_failed', facts: '收料 300 / ERP 280' }],
},
};
it('按 ERP 单号聚合展示,物料明细可展开/收起', async () => {
const wrapper = mount(TransferResultCard, { props: { run }, ...mountOptions });
const doc = wrapper.find('[data-testid="transfer-erp-document"]');
expect(doc.text()).toContain('TRF-10001');
expect(doc.attributes('open')).toBeUndefined();
await doc.find('summary').trigger('click');
expect(doc.attributes('open')).toBeDefined();
expect(wrapper.find('[data-testid="transfer-erp-document-lines"]').text()).toContain('INV-001');
});
it('未生成单据异常单独展示', () => {
const wrapper = mount(TransferResultCard, { props: { run }, ...mountOptions });
expect(wrapper.find('[data-testid="transfer-exceptions-area"]').text()).toContain('INV-999');
});
it('提供两个下载按钮(收料来源文件 + ERP 库存表)', async () => {
const wrapper = mount(TransferResultCard, { props: { run }, ...mountOptions });
await wrapper.find('[data-testid="transfer-download-receipt"]').trigger('click');
await wrapper.find('[data-testid="transfer-download-erp"]').trigger('click');
expect(wrapper.emitted('downloadReceipt')).toBeTruthy();
expect(wrapper.emitted('downloadErp')).toBeTruthy();
});
it('结果页不出现“查看执行审计”入口(决策 19)', () => {
const wrapper = mount(TransferResultCard, { props: { run }, ...mountOptions });
expect(wrapper.text()).not.toContain('审计');
});
});
describe('TransferManualCloseDialog', () => {
it('原因为空时确认按钮禁用;填写后可提交', async () => {
const wrapper = mount(TransferManualCloseDialog, {
props: { open: true, invoiceNo: 'INV-001' },
...mountOptions,
});
const confirm = wrapper.find('[data-testid="transfer-close-confirm"]');
expect((confirm.element as HTMLButtonElement).disabled).toBe(true);
await wrapper.find('[data-testid="transfer-close-reason"]').setValue('线下已处理');
expect((confirm.element as HTMLButtonElement).disabled).toBe(false);
await confirm.trigger('click');
expect(wrapper.emitted('confirm')?.[0][0]).toBe('线下已处理');
});
});
@@ -183,15 +183,15 @@ function loadMore() {
data-testid="review-audit-trail-drawer"
@click.self="emit('close')"
>
<aside class="flex h-full w-full max-w-xl flex-col bg-white shadow-xl dark:bg-slate-900">
<header class="flex items-center justify-between gap-2 border-b border-slate-200 px-4 py-3 dark:border-slate-800">
<aside class="flex h-full w-full max-w-xl flex-col bg-surface shadow-xl">
<header class="flex items-center justify-between gap-2 border-b border-default px-4 py-3">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.auditTrail.title') }}</h2>
<p class="text-[11px] text-muted">{{ t('chat.shippingOrderReview.auditTrail.subtitle') }}</p>
</div>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
data-testid="review-audit-trail-close"
@click="emit('close')"
>
@@ -209,7 +209,7 @@ function loadMore() {
<li
v-for="item in items"
:key="item.id"
class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-xs dark:border-slate-800 dark:bg-slate-950/40"
class="rounded-lg border border-default bg-surface-soft px-3 py-2 text-xs dark:bg-slate-950/40"
:data-testid="`review-audit-item-${item.id}`"
>
<button
@@ -239,7 +239,7 @@ function loadMore() {
</div>
<div
v-if="expandedId === item.id"
class="mt-2 space-y-2 border-t border-slate-200 pt-2 dark:border-slate-800"
class="mt-2 space-y-2 border-t border-default pt-2"
data-testid="review-audit-item-details"
>
<p v-if="item.sensitive_redacted" class="text-amber-800 dark:text-amber-200">
@@ -254,7 +254,7 @@ function loadMore() {
<li
v-for="(row, idx) in normalizeDiffRows(item.diff)"
:key="idx"
class="rounded bg-white px-2 py-1.5 text-[11px] dark:bg-slate-900"
class="rounded bg-surface px-2 py-1.5 text-[11px]"
>
<p class="font-medium text-primary">{{ diffFieldLabel(row) }}</p>
<p class="mt-0.5 text-muted">
@@ -271,39 +271,39 @@ function loadMore() {
<p v-if="item.reason" class="text-[11px] text-secondary">
{{ t('chat.shippingOrderReview.auditTrail.reason') }}:{{ item.reason }}
</p>
<details class="rounded border border-slate-200 dark:border-slate-800">
<details class="rounded border border-default">
<summary class="cursor-pointer px-2 py-1 text-[11px] text-muted">
{{ t('chat.shippingOrderReview.auditTrail.technicalDetails') }}
</summary>
<div class="space-y-2 border-t border-slate-200 p-2 dark:border-slate-800">
<div class="space-y-2 border-t border-default p-2">
<div class="flex items-center justify-between gap-2">
<p class="font-medium text-secondary">
{{ t('chat.shippingOrderReview.auditTrail.before') }}
</p>
<button
type="button"
class="rounded border border-slate-300 px-1.5 py-0.5 text-[11px] hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
class="rounded border border-default px-1.5 py-0.5 text-[11px] hover-surface-soft"
data-testid="review-audit-copy-before"
@click="copyJson(item.before_snapshot)"
>
{{ t('chat.shippingOrderReview.auditTrail.copyJson') }}
</button>
</div>
<pre class="max-h-32 overflow-auto rounded bg-white p-2 text-xs leading-relaxed dark:bg-slate-900">{{ formatJson(item.before_snapshot) }}</pre>
<pre class="max-h-32 overflow-auto rounded bg-surface p-2 text-xs leading-relaxed">{{ formatJson(item.before_snapshot) }}</pre>
<div class="flex items-center justify-between gap-2">
<p class="font-medium text-secondary">
{{ t('chat.shippingOrderReview.auditTrail.after') }}
</p>
<button
type="button"
class="rounded border border-slate-300 px-1.5 py-0.5 text-[11px] hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
class="rounded border border-default px-1.5 py-0.5 text-[11px] hover-surface-soft"
data-testid="review-audit-copy-after"
@click="copyJson(item.after_snapshot)"
>
{{ t('chat.shippingOrderReview.auditTrail.copyJson') }}
</button>
</div>
<pre class="max-h-32 overflow-auto rounded bg-white p-2 text-xs leading-relaxed dark:bg-slate-900">{{ formatJson(item.after_snapshot) }}</pre>
<pre class="max-h-32 overflow-auto rounded bg-surface p-2 text-xs leading-relaxed">{{ formatJson(item.after_snapshot) }}</pre>
</div>
</details>
</template>
@@ -313,7 +313,7 @@ function loadMore() {
<button
v-if="items.length < total"
type="button"
class="mt-3 w-full rounded border border-slate-300 px-2 py-1.5 text-xs hover:bg-slate-50 disabled:opacity-50 dark:border-slate-600 dark:hover:bg-slate-800"
class="mt-3 w-full rounded border border-default px-2 py-1.5 text-xs hover-surface-soft disabled:opacity-50"
data-testid="review-audit-trail-load-more"
:disabled="loading"
@click="loadMore"
@@ -66,7 +66,7 @@ function statusClass(status: string): string {
<template>
<section
v-if="visible"
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
class="rounded-xl border border-default bg-surface p-3 shadow-sm"
data-testid="review-automation-status-panel"
>
<header class="mb-2">
@@ -152,12 +152,12 @@ const hasDiagnosticDetails = computed(() => Boolean(
data-testid="review-eligibility-details-drawer"
@click.self="emit('close')"
>
<aside class="flex h-full w-full max-w-md flex-col bg-white shadow-xl dark:bg-slate-900">
<header class="flex items-center justify-between gap-2 border-b border-slate-200 px-4 py-3 dark:border-slate-800">
<aside class="flex h-full w-full max-w-md flex-col bg-surface shadow-xl">
<header class="flex items-center justify-between gap-2 border-b border-default px-4 py-3">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.workbench.fullChecksTitle') }}</h2>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
data-testid="review-eligibility-details-close"
@click="emit('close')"
>
@@ -168,7 +168,7 @@ const hasDiagnosticDetails = computed(() => Boolean(
<section
class="rounded-lg border px-3 py-2 text-xs"
:class="eligibility.can_build === null
? 'border-slate-200 bg-slate-50 text-slate-800 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100'
? 'border-default bg-surface-soft text-primary '
: eligibility.can_build
? 'border-emerald-200 bg-emerald-50 text-emerald-900 dark:border-emerald-900 dark:bg-emerald-950/30 dark:text-emerald-100'
: 'border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100'"
@@ -176,8 +176,8 @@ const hasDiagnosticDetails = computed(() => Boolean(
>
<div class="flex flex-wrap items-center justify-between gap-2">
<span class="font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.overallResult') }}</span>
<span class="text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.buildEligibility.manualBuildLabel') }}</span>
<span class="rounded-full px-2 py-0.5 font-medium" :class="eligibility.can_build === null ? 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-100' : eligibility.can_build ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/60 dark:text-emerald-100' : 'bg-amber-100 text-amber-900 dark:bg-amber-900/60 dark:text-amber-100'">
<span class="text-secondary">{{ t('chat.shippingOrderReview.buildEligibility.manualBuildLabel') }}</span>
<span class="rounded-full px-2 py-0.5 font-medium" :class="eligibility.can_build === null ? 'bg-surface-strong text-secondary ' : eligibility.can_build ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/60 dark:text-emerald-100' : 'bg-amber-100 text-amber-900 dark:bg-amber-900/60 dark:text-amber-100'">
<span data-testid="review-eligibility-manual-status">{{ eligibility.can_build === null
? t('chat.shippingOrderReview.buildEligibility.notValidated')
: eligibility.can_build
@@ -186,7 +186,7 @@ const hasDiagnosticDetails = computed(() => Boolean(
</span>
</div>
<div class="mt-2 flex flex-wrap items-center justify-between gap-2">
<span class="text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.buildEligibility.autoBuildLabel') }}</span>
<span class="text-secondary">{{ t('chat.shippingOrderReview.buildEligibility.autoBuildLabel') }}</span>
<span
class="rounded-full px-2 py-0.5 font-medium"
:class="eligibility.can_auto_create
@@ -213,7 +213,7 @@ const hasDiagnosticDetails = computed(() => Boolean(
</section>
<section
v-if="hasDiagnosticDetails"
class="rounded-lg border border-slate-200 bg-slate-50 p-3 text-xs dark:border-slate-700 dark:bg-slate-950/40"
class="rounded-lg border border-default bg-surface-soft p-3 text-xs dark:bg-slate-950/40"
>
<div v-if="eligibility.assessment?.missing_required_fields?.length" class="mt-2">
<div class="font-medium">{{ t('chat.shippingOrderReview.workbench.requiredFields') }}</div>
@@ -230,7 +230,7 @@ const hasDiagnosticDetails = computed(() => Boolean(
<ul class="mt-1 list-disc pl-4">
<li v-for="(issue, index) in nonConflictIssues" :key="index">
{{ issueLabel(issue) }}
<span v-if="issue.explainability?.message || issue.message" class="text-slate-600 dark:text-slate-300">
<span v-if="issue.explainability?.message || issue.message" class="text-secondary">
— {{ issue.explainability?.message || issue.message }}
</span>
</li>
@@ -249,7 +249,7 @@ const hasDiagnosticDetails = computed(() => Boolean(
<li
v-for="conflict in props.fieldConflicts"
:key="conflict.conflict_key"
class="rounded border border-rose-200 bg-white px-2 py-1.5 dark:border-rose-900 dark:bg-slate-900"
class="rounded border border-rose-200 bg-surface px-2 py-1.5 dark:border-rose-900"
>
<div class="font-semibold">
<span v-if="conflict.line_index != null">{{ t('chat.shippingOrderReview.line', { index: conflict.line_index + 1 }) }} · </span>
@@ -273,9 +273,9 @@ const hasDiagnosticDetails = computed(() => Boolean(
</section>
<article
v-for="line in orderedLines"
:key="String(line.line_key || line.line_index)"
class="rounded-lg border border-slate-200 p-3 text-xs dark:border-slate-700"
:data-testid="`review-eligibility-detail-line-${line.line_key || line.line_index}`"
:key="String(line.line_no)"
class="rounded-lg border border-default p-3 text-xs"
:data-testid="`review-eligibility-detail-line-${line.line_no}`"
>
<div class="flex flex-wrap items-center justify-between gap-2">
<button
@@ -302,20 +302,20 @@ const hasDiagnosticDetails = computed(() => Boolean(
</div>
<dl class="mt-2 grid gap-1">
<div>
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.routingStatusLabel') }}:</dt>
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.routingStatusLabel') }}:</dt>
<dd class="inline">{{ routingStatusLabel(line.routing_status) }}</dd>
</div>
<div v-if="line.block_reason">
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.blockReason') }}:</dt>
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.blockReason') }}:</dt>
<dd class="inline">{{ blockReasonLabel(line.block_reason) }}</dd>
</div>
<div v-if="line.candidate_inventory_source_codes?.length">
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.candidates') }}:</dt>
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.candidates') }}:</dt>
<dd class="inline font-mono">{{ line.candidate_inventory_source_codes.join(', ') }}</dd>
</div>
</dl>
</article>
<p v-if="!orderedLines.length" class="text-xs text-slate-500">
<p v-if="!orderedLines.length" class="text-xs text-muted">
{{ t('chat.shippingOrderReview.workbench.noLineChecks') }}
</p>
</div>
@@ -87,13 +87,13 @@ const blockingSummary = computed(() => {
/>
<section
v-if="eligibility"
class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900"
class="rounded-xl border border-default bg-surface p-4 shadow-sm"
data-testid="review-build-eligibility-panel"
>
<header class="mb-3 flex flex-wrap items-center justify-between gap-2">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.title') }}</h2>
<p class="mt-0.5 text-xs text-slate-500 dark:text-slate-400">
<p class="mt-0.5 text-xs text-muted">
{{ t('chat.shippingOrderReview.buildEligibility.subtitle') }}
</p>
</div>
@@ -112,7 +112,7 @@ const blockingSummary = computed(() => {
</span>
</header>
<dl class="grid gap-2 text-xs text-slate-600 dark:text-slate-400 sm:grid-cols-2">
<dl class="grid gap-2 text-xs text-secondary sm:grid-cols-2">
<div>
<dt class="inline font-medium">{{ t('chat.shippingOrderReview.buildEligibility.statusLabel') }}:</dt>
<dd class="inline">{{ statusLabel(eligibility.status) }}</dd>
@@ -134,14 +134,14 @@ const blockingSummary = computed(() => {
</div>
<div v-if="eligibility.line_projections.length" class="mt-3 space-y-2">
<div class="text-xs font-semibold text-slate-500 dark:text-slate-400">
<div class="text-xs font-semibold text-muted">
{{ t('chat.shippingOrderReview.buildEligibility.lineProjections') }}
</div>
<article
v-for="line in eligibility.line_projections"
:key="String(line.line_key || line.line_index)"
class="rounded-lg border border-slate-200 p-3 text-xs dark:border-slate-700"
:data-testid="`review-build-eligibility-line-${line.line_key || line.line_index}`"
:key="String(line.line_no)"
class="rounded-lg border border-default p-3 text-xs"
:data-testid="`review-build-eligibility-line-${line.line_no}`"
>
<div class="flex flex-wrap items-center justify-between gap-2">
<span class="font-medium">
@@ -162,27 +162,27 @@ const blockingSummary = computed(() => {
</div>
<dl class="mt-2 grid gap-1 sm:grid-cols-2">
<div>
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.reservation') }}:</dt>
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.reservation') }}:</dt>
<dd class="inline font-mono">{{ line.effective_reservation_id || '—' }}</dd>
</div>
<div>
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.routingStatusLabel') }}:</dt>
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.routingStatusLabel') }}:</dt>
<dd class="inline">{{ routingStatusLabel(line.routing_status) }}</dd>
</div>
<div v-if="line.inventory_source_hint" class="sm:col-span-2">
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.sourceHint') }}:</dt>
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.sourceHint') }}:</dt>
<dd class="inline">{{ line.inventory_source_hint }}</dd>
</div>
<div v-if="line.candidate_inventory_source_codes?.length" class="sm:col-span-2">
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.candidates') }}:</dt>
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.candidates') }}:</dt>
<dd class="inline font-mono">{{ line.candidate_inventory_source_codes.join(', ') }}</dd>
</div>
<div v-if="line.block_reason" class="sm:col-span-2">
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.blockReason') }}:</dt>
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.blockReason') }}:</dt>
<dd class="inline">{{ blockReasonLabel(line.block_reason) }}</dd>
</div>
<div v-if="line.selection_mode === 'manual' && line.manual_reason" class="sm:col-span-2">
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.manualReason') }}:</dt>
<dt class="inline text-muted">{{ t('chat.shippingOrderReview.buildEligibility.manualReason') }}:</dt>
<dd class="inline">{{ line.manual_reason }}</dd>
</div>
</dl>
@@ -206,7 +206,7 @@ const gateChecklist = computed(() => {
<template>
<section
v-if="eligibility"
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
class="rounded-xl border border-default bg-surface p-3 shadow-sm"
data-testid="review-build-eligibility-summary"
>
<header class="flex flex-wrap items-center justify-between gap-2">
@@ -214,7 +214,7 @@ const gateChecklist = computed(() => {
<span
class="rounded-full px-2.5 py-1 text-xs font-medium"
:class="eligibility.can_build === null
? 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-200'
? 'bg-surface-strong text-secondary '
: eligibility.can_build
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
: 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'"
@@ -325,7 +325,7 @@ const gateChecklist = computed(() => {
<button
type="button"
class="mt-2 w-full rounded border border-slate-300 px-2 py-1.5 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
class="mt-2 w-full rounded border border-default px-2 py-1.5 text-xs hover-surface-soft"
data-testid="review-open-eligibility-details"
@click="emit('open-details')"
>
@@ -56,7 +56,7 @@ async function onConfirm() {
try {
const result = await closeWorkspaceShippingOrderReviewLineFulfillment(props.caseNo, {
reason: trimmed,
line_keys: props.lineKeys.length ? props.lineKeys : undefined,
draft_line_ids: props.lineKeys.length ? props.lineKeys : undefined,
expected_draft_version: props.draftVersion ?? undefined,
});
showReviewResumeOutcome(
@@ -92,7 +92,7 @@ function onCancel() {
data-testid="review-close-fulfillment-dialog"
@click.self="onCancel"
>
<div class="w-full max-w-md rounded-xl border border-slate-200 bg-white p-4 shadow-xl dark:border-slate-800 dark:bg-slate-900">
<div class="w-full max-w-md rounded-xl border border-default bg-surface p-4 shadow-xl">
<h2 class="text-sm font-semibold">{{ title }}</h2>
<p class="mt-1 text-xs text-muted">{{ t('chat.shippingOrderReview.closeFulfillment.subtitle') }}</p>
<label class="mt-3 block text-xs font-medium text-secondary">
@@ -36,7 +36,7 @@ function checkLabel(code: string): string {
<template>
<details
v-if="visible"
class="rounded-xl border border-slate-200 bg-white p-2 text-xs dark:border-slate-800 dark:bg-slate-900"
class="rounded-xl border border-default bg-surface p-2 text-xs"
:open="defaultOpen"
data-testid="review-completed-checks"
>
@@ -99,7 +99,9 @@ describe('ReviewCurrentProcessingCard', () => {
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true);
});
it('renders reload inventory result as the timeout primary action', () => {
it('renders a code-agnostic primary action label from a registered recovery code', () => {
// 卡片是 code-agnostic 渲染器:只要后端下发了受控文案键,就渲染对应业务动作文案。
// 此用例用 reload_inventory_result(仍为写契约有效码)验证卡片对库存动作文案的渲染。
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'inventory_preparation', userStatus: 'retryable', retryable: true,
@@ -309,4 +311,30 @@ describe('ReviewCurrentProcessingCard', () => {
expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toBe('正在获取最新状态…');
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toBe('待机');
});
it('renders an embedded status detail line when provided', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
userStatus: 'running',
stageCode: 'intake_parse',
statusDetail: { text: '正在等待解析任务启动' },
},
global: { plugins: [i18n] },
});
// 关键断言:说明内嵌于状态行下方(弱文本一行),带 aria-live 与固定 testid;
// 状态行仍为短标签(系统处理中),长句不进入状态位。
const detail = wrapper.get('[data-testid="review-current-task-status-detail"]');
expect(detail.text()).toBe('正在等待解析任务启动');
expect(detail.attributes('aria-live')).toBe('polite');
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toContain('系统处理中');
});
it('renders no status detail line without the prop', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: { userStatus: 'waiting_human', stageCode: 'order_review' },
global: { plugins: [i18n] },
});
// 关键断言:无 statusDetail 时说明行完全不渲染,不留空壳。
expect(wrapper.find('[data-testid="review-current-task-status-detail"]').exists()).toBe(false);
});
});
@@ -9,7 +9,8 @@
(与投影同源或后端 automation 运行态),空态自然落到「待机/状态待确认」,
禁止把读取占位误述为「系统处理中」,也不做骨架→真值的二次刷新;
loading 仅在挂载期抑制可执行动作,等权威投影到达后再放行(fail-closed);
由 ShippingOrderReviewView 在 mountCurrentProcessingCard 时挂载。
由 ShippingOrderReviewView 在 mountCurrentProcessingCard 时挂载;
v2 新增 statusDetail:状态块内嵌动态说明(隐藏裁决在视图侧,见 spec §5.2)。
-->
<script setup lang="ts">
import { computed } from 'vue';
@@ -61,10 +62,12 @@ const props = defineProps<{
} | null;
showRetry?: boolean;
loading?: boolean;
/** 状态块内嵌动态说明(Run 级 lifecycle_progress 解析结果);null/空文本不渲染,显隐裁决在视图侧。 */
statusDetail?: { text: string } | null;
}>();
const emit = defineEmits<{
locate: [lineKey?: string | null, fieldId?: string | null];
locate: [draftLineId?: string | null, fieldId?: string | null];
action: [code: string, parameters?: Record<string, unknown>];
}>();
@@ -312,20 +315,20 @@ function handleBusinessActionClick() {
}
/**
* 辅助导航「定位明细」:仅当后端在 primary_action.parameters 里提供 line_key 或 field_id 才显示。
* 辅助导航「定位明细」:仅当后端在 primary_action.parameters 里提供 draft_line_id 或 field_id 才显示。
*/
const showLocateAction = computed(() => {
if (props.loading) return false;
if (props.taskMissing) return false;
const params = (props.primaryAction?.parameters ?? {}) as Record<string, unknown>;
const hasLineKey = typeof params.line_key === 'string' && params.line_key.length > 0;
const hasDraftLineId = typeof params.draft_line_id === 'string' && params.draft_line_id.length > 0;
const hasFieldId = typeof params.field_id === 'string' && params.field_id.length > 0;
return hasLineKey || hasFieldId;
return hasDraftLineId || hasFieldId;
});
const locateTargetLineKey = computed(() => {
const locateTargetDraftLineId = computed(() => {
const params = (props.primaryAction?.parameters ?? {}) as Record<string, unknown>;
return typeof params.line_key === 'string' ? params.line_key : null;
return typeof params.draft_line_id === 'string' ? params.draft_line_id : null;
});
const locateTargetFieldId = computed(() => {
@@ -334,7 +337,7 @@ const locateTargetFieldId = computed(() => {
});
function handleLocateClick() {
emit('locate', locateTargetLineKey.value, locateTargetFieldId.value);
emit('locate', locateTargetDraftLineId.value, locateTargetFieldId.value);
}
type ReviewCurrentUserStatus =
@@ -379,6 +382,13 @@ type ReviewCurrentUserStatus =
/>
{{ statusLabel }}
</dd>
<!-- v2:状态块内嵌动态说明(弱文本一行,不加标题/图标/区块;显隐裁决在视图侧)。 -->
<p
v-if="statusDetail?.text"
class="w-full text-[11px] leading-4 text-muted"
data-testid="review-current-task-status-detail"
aria-live="polite"
>{{ statusDetail.text }}</p>
</div>
</dl>
@@ -451,7 +461,7 @@ type ReviewCurrentUserStatus =
v-for="action in recoveryActions"
:key="action.code"
type="button"
class="inline-flex items-center gap-1 rounded-md border border-sky-300 bg-white px-2.5 py-1.5 text-xs font-medium text-sky-800 shadow-sm transition hover:bg-sky-50 disabled:opacity-50 dark:border-sky-700 dark:bg-sky-900 dark:text-sky-100 dark:hover:bg-sky-800"
class="inline-flex items-center gap-1 rounded-md border border-sky-300 bg-surface px-2.5 py-1.5 text-xs font-medium text-sky-800 shadow-sm transition hover:bg-sky-50 disabled:opacity-50 dark:border-sky-700 dark:bg-sky-900 dark:text-sky-100 dark:hover:bg-sky-800"
:data-testid="`review-current-task-recovery-${action.code}`"
:disabled="retrying || locating"
@click="$emit('action', action.code, action.parameters || {})"
@@ -461,7 +471,7 @@ type ReviewCurrentUserStatus =
<button
v-if="showLocateAction"
type="button"
class="inline-flex items-center gap-1 rounded-md border border-sky-300 bg-white px-2.5 py-1.5 text-xs font-medium text-sky-800 shadow-sm transition hover:bg-sky-50 disabled:opacity-50 dark:border-sky-700 dark:bg-sky-900 dark:text-sky-100 dark:hover:bg-sky-800"
class="inline-flex items-center gap-1 rounded-md border border-sky-300 bg-surface px-2.5 py-1.5 text-xs font-medium text-sky-800 shadow-sm transition hover:bg-sky-50 disabled:opacity-50 dark:border-sky-700 dark:bg-sky-900 dark:text-sky-100 dark:hover:bg-sky-800"
data-testid="review-current-task-locate-action"
:disabled="locating"
@click="handleLocateClick"
@@ -175,7 +175,7 @@ async function onRetry() {
<template>
<section
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
class="rounded-xl border border-default bg-surface p-3 shadow-sm"
data-testid="review-customer-resolution-panel"
:data-compact="compact && resolved ? 'true' : 'false'"
>
@@ -240,13 +240,13 @@ const coordinateIssueLabels = computed(() => {
const panelClass = computed(() => {
if (props.docked) {
return [
'relative flex min-h-[320px] min-w-0 flex-col overflow-hidden rounded-xl border border-slate-200',
'bg-white shadow-sm xl:min-h-[520px] dark:border-slate-800 dark:bg-slate-900',
'relative flex min-h-[320px] min-w-0 flex-col overflow-hidden rounded-xl border border-default',
'bg-surface shadow-sm xl:min-h-[520px] ',
].join(' ');
}
return [
'fixed z-30 flex flex-col overflow-hidden rounded-xl border border-slate-200',
'bg-white shadow-2xl dark:border-slate-700 dark:bg-slate-900',
'fixed z-30 flex flex-col overflow-hidden rounded-xl border border-default',
'bg-surface shadow-2xl ',
].join(' ');
});
@@ -590,7 +590,7 @@ onBeforeUnmount(() => {
:data-height="Math.round(geom.height)"
>
<div
class="flex shrink-0 flex-col gap-1.5 border-b border-slate-200 px-3 py-2 dark:border-slate-800"
class="flex shrink-0 flex-col gap-1.5 border-b border-default px-3 py-2"
:class="docked ? '' : 'cursor-grab active:cursor-grabbing select-none'"
data-testid="review-evidence-drag-handle"
@pointerdown="onDragStart"
@@ -599,16 +599,16 @@ onBeforeUnmount(() => {
<div class="min-w-0">
<div
id="review-evidence-drawer-title"
class="text-xs font-semibold text-slate-700 dark:text-slate-200"
class="text-xs font-semibold text-secondary"
>
{{ t('chat.shippingOrderReview.evidenceDrawer.title') }}
</div>
<p class="truncate text-[11px] text-slate-500">{{ pageLabel }}</p>
<p class="truncate text-[11px] text-muted">{{ pageLabel }}</p>
</div>
<button
ref="closeButtonRef"
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
data-testid="review-evidence-close"
@click="emit('close')"
>
@@ -620,19 +620,19 @@ onBeforeUnmount(() => {
<div class="flex items-center gap-1" data-testid="review-evidence-nav-group">
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
data-testid="review-evidence-prev"
:disabled="!canPrev"
@click="emit('prev-evidence')"
>
{{ t('chat.shippingOrderReview.evidenceDrawer.prevEvidence') }}
</button>
<span class="text-[11px] text-slate-500" data-testid="review-evidence-ordinal">
<span class="text-[11px] text-muted" data-testid="review-evidence-ordinal">
{{ evidenceOrdinal }}/{{ evidenceList.length || 0 }}
</span>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
data-testid="review-evidence-next"
:disabled="!canNext"
@click="emit('next-evidence')"
@@ -645,7 +645,7 @@ onBeforeUnmount(() => {
<button
v-if="!docked"
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
data-testid="review-evidence-toggle-expand"
:title="expanded
? t('chat.shippingOrderReview.workbench.collapsePdfHint')
@@ -658,7 +658,7 @@ onBeforeUnmount(() => {
</button>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
data-testid="review-evidence-toggle-dock"
:title="docked
? t('chat.shippingOrderReview.workbench.undockPdfHint')
@@ -672,7 +672,7 @@ onBeforeUnmount(() => {
<div class="relative">
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
data-testid="review-evidence-more"
:aria-expanded="moreOpen ? 'true' : 'false'"
@click="moreOpen = !moreOpen"
@@ -681,13 +681,13 @@ onBeforeUnmount(() => {
</button>
<div
v-if="moreOpen"
class="absolute right-0 z-40 mt-1 min-w-[10rem] rounded-md border border-slate-200 bg-white py-1 text-xs shadow-lg dark:border-slate-700 dark:bg-slate-900"
class="absolute right-0 z-40 mt-1 min-w-[10rem] rounded-md border border-default bg-surface py-1 text-xs shadow-lg"
data-testid="review-evidence-more-menu"
>
<button
v-if="!docked"
type="button"
class="block w-full px-3 py-1.5 text-left hover:bg-slate-50 dark:hover:bg-slate-800"
class="block w-full px-3 py-1.5 text-left hover-surface-soft"
data-testid="review-evidence-toggle-side"
@click="emit('toggle-side'); moreOpen = false"
>
@@ -697,7 +697,7 @@ onBeforeUnmount(() => {
</button>
<button
type="button"
class="block w-full px-3 py-1.5 text-left hover:bg-slate-50 dark:hover:bg-slate-800"
class="block w-full px-3 py-1.5 text-left hover-surface-soft"
data-testid="review-evidence-toggle-pin"
@click="emit('toggle-pin'); moreOpen = false"
>
@@ -708,7 +708,7 @@ onBeforeUnmount(() => {
<button
v-if="showAiActions"
type="button"
class="block w-full px-3 py-1.5 text-left hover:bg-slate-50 dark:hover:bg-slate-800"
class="block w-full px-3 py-1.5 text-left hover-surface-soft"
data-testid="review-evidence-request-ai"
@click="emit('request-ai'); moreOpen = false"
>
@@ -717,7 +717,7 @@ onBeforeUnmount(() => {
<button
v-if="showAiActions"
type="button"
class="block w-full px-3 py-1.5 text-left hover:bg-slate-50 dark:hover:bg-slate-800"
class="block w-full px-3 py-1.5 text-left hover-surface-soft"
data-testid="review-evidence-restore-machine"
@click="emit('restore-machine'); moreOpen = false"
>
@@ -736,10 +736,10 @@ onBeforeUnmount(() => {
sandbox=""
referrerpolicy="no-referrer"
:title="fieldLabel || t('chat.shippingOrderReview.evidenceDrawer.title')"
class="min-h-0 h-full w-full border-0 bg-white"
class="min-h-0 h-full w-full border-0 bg-surface"
data-testid="review-email-evidence-html"
/>
<div v-else-if="emailPreview" class="min-h-0 overflow-auto whitespace-pre-wrap p-4 font-mono text-xs leading-6 text-slate-700 dark:text-slate-200" data-testid="review-email-evidence-preview">
<div v-else-if="emailPreview" class="min-h-0 overflow-auto whitespace-pre-wrap p-4 font-mono text-xs leading-6 text-secondary" data-testid="review-email-evidence-preview">
{{ emailPreview.text }}
</div>
<ReviewDocumentPreview
@@ -754,48 +754,48 @@ onBeforeUnmount(() => {
/>
<div
v-else
class="flex min-h-[140px] items-center justify-center p-4 text-sm text-slate-500"
class="flex min-h-[140px] items-center justify-center p-4 text-sm text-muted"
>
{{ t('chat.shippingOrderReview.previewUnavailable') }}
</div>
<details
class="shrink-0 border-t border-slate-200 text-xs dark:border-slate-800"
class="shrink-0 border-t border-default text-xs"
data-testid="review-evidence-details"
:open="detailsOpen"
@toggle="detailsOpen = ($event.target as HTMLDetailsElement).open"
>
<summary class="cursor-pointer px-3 py-2 font-medium text-slate-700 hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800/60">
<summary class="cursor-pointer px-3 py-2 font-medium text-secondary hover-surface-soft dark:hover:bg-slate-800/60">
{{ t('chat.shippingOrderReview.evidenceDrawer.detailsToggle') }}
<span v-if="fieldLabel" class="ml-1 font-normal text-slate-500">· {{ fieldLabel }}</span>
<span v-if="fieldLabel" class="ml-1 font-normal text-muted">· {{ fieldLabel }}</span>
</summary>
<div class="space-y-2 px-3 pb-2">
<div v-if="fieldLabel" class="font-medium text-slate-700 dark:text-slate-200">
<div v-if="fieldLabel" class="font-medium text-secondary">
{{ t('chat.shippingOrderReview.evidenceDrawer.field', { field: fieldLabel }) }}
</div>
<dl class="grid gap-1 text-slate-600 dark:text-slate-300">
<dl class="grid gap-1 text-secondary">
<div class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.currentValue') }}</dt>
<dt class="shrink-0 text-muted">{{ t('chat.shippingOrderReview.evidenceDrawer.currentValue') }}</dt>
<dd class="min-w-0 break-words">{{ draftValue || t('chat.shippingOrderReview.emptyValue') }}</dd>
</div>
<div class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.machineValue') }}</dt>
<dt class="shrink-0 text-muted">{{ t('chat.shippingOrderReview.evidenceDrawer.machineValue') }}</dt>
<dd class="min-w-0 break-words">{{ machineValue || t('chat.shippingOrderReview.emptyValue') }}</dd>
</div>
<div class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.highlightQuality') }}</dt>
<dt class="shrink-0 text-muted">{{ t('chat.shippingOrderReview.evidenceDrawer.highlightQuality') }}</dt>
<dd data-testid="review-evidence-highlight-quality">{{ highlightQualityLabel }}</dd>
</div>
<div class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.highlightSource') }}</dt>
<dt class="shrink-0 text-muted">{{ t('chat.shippingOrderReview.evidenceDrawer.highlightSource') }}</dt>
<dd data-testid="review-evidence-highlight-source">{{ highlightSourceLabel }}</dd>
</div>
<div v-if="valueSourceLabel" class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.source') }}</dt>
<dt class="shrink-0 text-muted">{{ t('chat.shippingOrderReview.evidenceDrawer.source') }}</dt>
<dd>{{ valueSourceLabel }}</dd>
</div>
<div v-if="evidence?.table_id || evidence?.cell_id" class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.layoutPath') }}</dt>
<dt class="shrink-0 text-muted">{{ t('chat.shippingOrderReview.evidenceDrawer.layoutPath') }}</dt>
<dd class="min-w-0 break-all font-mono text-[11px]">
{{ [evidence?.table_id, evidence?.cell_id].filter(Boolean).join(' / ') }}
</dd>
@@ -180,10 +180,10 @@ function onSelect(caseNo: string) {
data-testid="review-document-navigation"
:data-nav-mode="mode"
:class="mode === 'tabs'
? 'rounded-xl border border-slate-200 bg-white p-2 shadow-sm dark:border-slate-800 dark:bg-slate-900'
? 'rounded-xl border border-default bg-surface p-2 shadow-sm '
: mode === 'narrow'
? ''
: ['sticky top-3 flex max-h-[calc(100vh-6rem)] w-full shrink-0 flex-col rounded-xl border border-slate-200 bg-white shadow-sm transition-[width] duration-200 dark:border-slate-800 dark:bg-slate-900', collapsed ? 'lg:w-20' : 'lg:w-64']"
: ['sticky top-3 flex max-h-[calc(100vh-6rem)] w-full shrink-0 flex-col rounded-xl border border-default bg-surface shadow-sm transition-[width] duration-200 ', collapsed ? 'lg:w-20' : 'lg:w-64']"
>
<!-- 2–4:顶部标签 -->
<div
@@ -198,7 +198,7 @@ function onSelect(caseNo: string) {
class="inline-flex min-w-[9rem] max-w-[240px] shrink-0 flex-col gap-0.5 rounded-lg border px-2.5 py-1.5 text-left text-xs transition-colors"
:class="activeCaseNo === item.case_no
? 'border-sky-500 bg-sky-50 text-sky-950 ring-1 ring-sky-400 dark:border-sky-700 dark:bg-sky-950/40 dark:text-sky-100'
: 'border-slate-200 text-slate-700 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800'"
: 'border-default text-secondary hover-surface-soft '"
:data-testid="`review-doc-nav-${item.case_no}`"
@click="onSelect(item.case_no)"
>
@@ -220,12 +220,12 @@ function onSelect(caseNo: string) {
/>
<Circle
v-else
class="h-3 w-3 shrink-0 text-slate-400"
class="h-3 w-3 shrink-0 text-muted"
aria-hidden="true"
/>
<span class="truncate">{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</span>
</span>
<span class="truncate text-[10px] text-slate-500 dark:text-slate-400">
<span class="truncate text-[10px] text-muted">
{{ [
item.po_number,
lifecycleStageLabel(item),
@@ -238,13 +238,13 @@ function onSelect(caseNo: string) {
<!-- ≥5:左侧列表 -->
<template v-else-if="mode === 'sidebar' || mode === 'sidebar_search'">
<div class="flex items-center justify-between gap-2 border-b border-slate-100 px-2 py-2 dark:border-slate-800">
<div class="flex items-center justify-between gap-2 border-b border-subtle px-2 py-2">
<span class="text-xs font-semibold text-primary">
{{ t('chat.shippingOrderReview.otNav.listTitle', { count: items.length }) }}
</span>
<button
type="button"
class="rounded p-1 text-muted hover:bg-slate-100 dark:hover:bg-slate-800"
class="rounded p-1 text-muted hover-surface-strong"
data-testid="review-doc-nav-collapse"
:aria-label="collapsed ? t('chat.shippingOrderReview.documentNavigation') : t('chat.shippingOrderReview.documentNavigation')"
@click="collapsed = !collapsed"
@@ -262,21 +262,21 @@ function onSelect(caseNo: string) {
<div
v-if="!collapsed && mode === 'sidebar_search'"
class="space-y-2 border-b border-slate-100 px-2 py-2 dark:border-slate-800"
class="space-y-2 border-b border-subtle px-2 py-2"
>
<label class="relative block">
<Search class="pointer-events-none absolute left-2 top-1.5 h-3.5 w-3.5 text-muted" />
<input
v-model="searchQuery"
type="search"
class="w-full rounded-md border border-slate-200 bg-white py-1 pl-7 pr-2 text-[11px] dark:border-slate-700 dark:bg-slate-950"
class="w-full rounded-md border border-default bg-surface py-1 pl-7 pr-2 text-[11px]"
:placeholder="t('chat.shippingOrderReview.otNav.searchPlaceholder')"
data-testid="review-doc-nav-search"
>
</label>
<select
v-model="statusFilter"
class="w-full rounded-md border border-slate-200 bg-white px-2 py-1 text-[11px] dark:border-slate-700 dark:bg-slate-950"
class="w-full rounded-md border border-default bg-surface px-2 py-1 text-[11px]"
data-testid="review-doc-nav-filter"
>
<option value="all">{{ t('chat.shippingOrderReview.otNav.filterAll') }}</option>
@@ -299,7 +299,7 @@ function onSelect(caseNo: string) {
class="mb-1 flex w-full items-start gap-2 rounded-lg border px-2 py-1.5 text-left text-xs transition-colors"
:class="activeCaseNo === item.case_no
? 'border-sky-500 bg-sky-50 dark:border-sky-700 dark:bg-sky-950/40'
: 'border-transparent hover:bg-slate-50 dark:hover:bg-slate-800'"
: 'border-transparent hover-surface-soft '"
:title="collapsed
? `${item.file_name || item.case_no} · ${caseStatusLabel(item.status)}`
: undefined"
@@ -308,11 +308,11 @@ function onSelect(caseNo: string) {
>
<span
v-if="collapsed"
class="flex h-12 w-full min-w-0 flex-col items-center justify-center rounded-md bg-slate-100 px-1 text-[10px] dark:bg-slate-800"
class="flex h-12 w-full min-w-0 flex-col items-center justify-center rounded-md bg-surface-strong px-1 text-[10px]"
:title="`${index + 1}. ${item.file_name || item.case_no}`"
>
<span class="font-semibold">{{ index + 1 }}</span>
<span class="mt-0.5 w-full truncate text-center text-[9px] font-medium text-slate-600 dark:text-slate-300">
<span class="mt-0.5 w-full truncate text-center text-[9px] font-medium text-secondary">
{{ (item.file_name || item.case_no).replace(/\.[^.]+$/, '').slice(0, 7) }}
</span>
</span>
@@ -331,7 +331,7 @@ function onSelect(caseNo: string) {
/>
<Circle
v-else
class="mt-0.5 h-3 w-3 shrink-0 text-slate-400"
class="mt-0.5 h-3 w-3 shrink-0 text-muted"
/>
<span class="min-w-0 flex-1">
<span class="block truncate font-medium text-primary">
@@ -354,7 +354,7 @@ function onSelect(caseNo: string) {
<template v-else-if="mode === 'narrow'">
<button
type="button"
class="inline-flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs font-medium shadow-sm dark:border-slate-800 dark:bg-slate-900"
class="inline-flex items-center gap-2 rounded-xl border border-default bg-surface px-3 py-2 text-xs font-medium shadow-sm"
data-testid="review-doc-nav-narrow-trigger"
@click="drawerOpen = true"
>
@@ -391,7 +391,7 @@ function onSelect(caseNo: string) {
class="flex w-full flex-col rounded-lg border px-3 py-2 text-left text-xs"
:class="activeCaseNo === item.case_no
? 'border-sky-500 bg-sky-50'
: 'border-slate-200'"
: 'border-default'"
:data-testid="`review-doc-nav-${item.case_no}`"
@click="onSelect(item.case_no)"
>
@@ -373,25 +373,25 @@ watch(
<template>
<div
class="relative flex flex-1 flex-col overflow-hidden bg-slate-100 dark:bg-slate-950"
class="relative flex flex-1 flex-col overflow-hidden bg-surface-strong"
:class="drawerMode ? 'min-h-[200px]' : 'min-h-[180px] xl:min-h-[360px]'"
:data-drawer-mode="drawerMode ? 'true' : 'false'"
>
<div class="flex shrink-0 items-center justify-between gap-1 border-b border-slate-200 bg-white/95 px-2 py-1.5 text-xs dark:border-slate-800 dark:bg-slate-900/95">
<div class="flex shrink-0 items-center justify-between gap-1 border-b border-default bg-white/95 px-2 py-1.5 text-xs dark:bg-slate-900/95">
<div class="flex items-center gap-1">
<button
type="button"
class="rounded border px-2 py-1 hover:bg-slate-50 disabled:opacity-40 dark:border-slate-700 dark:hover:bg-slate-800"
class="rounded border px-2 py-1 hover-surface-soft disabled:opacity-40"
data-testid="review-pdf-prev-page"
:disabled="currentPage <= 1"
@click="prevPage"
>‹</button>
<span class="min-w-16 text-center text-slate-600 dark:text-slate-300" data-testid="review-pdf-page-label">
<span class="min-w-16 text-center text-secondary" data-testid="review-pdf-page-label">
{{ currentPage }} / {{ pageCount || '—' }}
</span>
<button
type="button"
class="rounded border px-2 py-1 hover:bg-slate-50 disabled:opacity-40 dark:border-slate-700 dark:hover:bg-slate-800"
class="rounded border px-2 py-1 hover-surface-soft disabled:opacity-40"
data-testid="review-pdf-next-page"
:disabled="!pageCount || currentPage >= pageCount"
@click="nextPage"
@@ -402,13 +402,13 @@ watch(
type="number"
min="1"
:max="pageCount || undefined"
class="w-12 rounded border border-slate-300 px-1 py-0.5 text-center dark:border-slate-700 dark:bg-slate-950"
class="w-12 rounded border border-default px-1 py-0.5 text-center"
data-testid="review-pdf-page-jump"
:aria-label="t('chat.shippingOrderReview.previewZoom.jumpPage')"
>
<button
type="submit"
class="rounded border px-1.5 py-0.5 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
class="rounded border px-1.5 py-0.5 hover-surface-soft"
data-testid="review-pdf-page-jump-go"
>{{ t('chat.shippingOrderReview.previewZoom.go') }}</button>
</form>
@@ -416,33 +416,33 @@ watch(
<div class="flex flex-wrap items-center gap-1">
<button
type="button"
class="rounded border px-1.5 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
class="rounded border px-1.5 py-1 hover-surface-soft"
data-testid="review-pdf-zoom-fit-width"
:title="t('chat.shippingOrderReview.previewZoom.fitWidth')"
@click="fitWidth"
>{{ t('chat.shippingOrderReview.previewZoom.fitWidthShort') }}</button>
<button
type="button"
class="rounded border px-1.5 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
class="rounded border px-1.5 py-1 hover-surface-soft"
data-testid="review-pdf-zoom-fit-page"
:title="t('chat.shippingOrderReview.previewZoom.fitPage')"
@click="fitPage"
>{{ t('chat.shippingOrderReview.previewZoom.fitPageShort') }}</button>
<button
type="button"
class="rounded border px-1.5 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
class="rounded border px-1.5 py-1 hover-surface-soft"
data-testid="review-pdf-zoom-actual"
:title="t('chat.shippingOrderReview.previewZoom.actual')"
@click="zoomActual"
>100%</button>
<button type="button" class="rounded border px-2 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" data-testid="review-pdf-zoom-out" @click="zoomOut">−</button>
<span class="min-w-12 text-center text-slate-600 dark:text-slate-300" data-testid="review-pdf-zoom-label">{{ zoomLabel }}</span>
<button type="button" class="rounded border px-2 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" data-testid="review-pdf-zoom-in" @click="zoomIn">+</button>
<button type="button" class="rounded border px-2 py-1 hover-surface-soft" data-testid="review-pdf-zoom-out" @click="zoomOut">−</button>
<span class="min-w-12 text-center text-secondary" data-testid="review-pdf-zoom-label">{{ zoomLabel }}</span>
<button type="button" class="rounded border px-2 py-1 hover-surface-soft" data-testid="review-pdf-zoom-in" @click="zoomIn">+</button>
</div>
</div>
<div
v-if="showCandidateBanner || showVerifiedLegend"
class="flex shrink-0 flex-wrap items-center gap-2 border-b border-slate-200 bg-white/90 px-2 py-1 text-[11px] dark:border-slate-800 dark:bg-slate-900/90"
class="flex shrink-0 flex-wrap items-center gap-2 border-b border-default bg-white/90 px-2 py-1 text-[11px] dark:bg-slate-900/90"
data-testid="review-pdf-highlight-legend"
>
<span
@@ -471,8 +471,8 @@ watch(
@pointerdown="onPanStart"
>
<!-- Keep the canvas mounted while PDF.js is loading; otherwise nextTick cannot obtain a render target. -->
<canvas ref="canvas" :aria-label="title" class="bg-white shadow select-none" :class="{ invisible: loading || failed }" />
<span v-if="loading" class="absolute text-sm text-slate-500">{{ loadingText }}</span>
<canvas ref="canvas" :aria-label="title" class="bg-surface shadow select-none" :class="{ invisible: loading || failed }" />
<span v-if="loading" class="absolute text-sm text-muted">{{ loadingText }}</span>
<span v-else-if="failed" class="absolute text-sm text-rose-600">{{ unavailableText }}</span>
<div
v-else-if="showCandidateBanner && !loading && !failed"
@@ -165,7 +165,7 @@ defineExpose({
<div
v-if="primaryMatch"
class="mt-2 rounded-lg border border-amber-200 bg-white/90 px-2.5 py-2 text-xs text-secondary dark:border-amber-900 dark:bg-slate-900"
class="mt-2 rounded-lg border border-amber-200 bg-white/90 px-2.5 py-2 text-xs text-secondary dark:border-amber-900"
data-testid="review-duplicate-match"
>
<div class="font-medium text-primary">
@@ -44,7 +44,7 @@ function fieldLabel(issue: FieldCompletenessIssue): string {
<template>
<section
v-if="visible"
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
class="rounded-xl border border-default bg-surface p-3 shadow-sm"
data-testid="review-field-completeness-panel"
:data-status="status"
>
@@ -24,7 +24,7 @@ const props = defineProps<{
const emit = defineEmits<{
refreshed: [];
'focus-conflict': [payload: { fieldCode: string; lineIndex: number | null; lineKey: string | null }];
'focus-conflict': [payload: { fieldCode: string; lineIndex: number | null; draftLineId: string | null }];
}>();
const { t, te } = useI18n();
@@ -90,7 +90,7 @@ function onFocus(conflict: ShippingOrderReviewFieldConflict) {
emit('focus-conflict', {
fieldCode: conflict.field_code,
lineIndex: conflict.line_index ?? null,
lineKey: conflict.line_key ?? null,
draftLineId: conflict.draft_line_id ?? null,
});
}
@@ -212,7 +212,7 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
<li
v-for="conflict in openConflicts"
:key="conflict.conflict_key"
class="rounded-lg border border-rose-200 bg-white/95 px-2.5 py-2 dark:border-rose-900 dark:bg-slate-900"
class="rounded-lg border border-rose-200 bg-white/95 px-2.5 py-2 dark:border-rose-900"
:data-testid="`review-field-conflict-${conflict.conflict_key}`"
>
<div class="flex flex-wrap items-center justify-between gap-2">
@@ -247,7 +247,7 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
class="rounded px-1 py-0.5 text-[10px] font-medium"
:class="option.evidence_role === 'primary_pdf'
? 'bg-sky-100 text-sky-800 dark:bg-sky-950 dark:text-sky-200'
: 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-200'"
: 'bg-surface-strong text-secondary '"
:data-testid="`review-field-conflict-evidence-role-${idx}`"
:data-evidence-role="option.evidence_role"
>
@@ -315,7 +315,7 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
<li
v-for="issue in openEvidenceIssues"
:key="`${issue.conflict_key}-${issue.reason}`"
class="flex flex-wrap items-center justify-between gap-2 rounded border border-amber-200 bg-white/95 px-2.5 py-2 text-xs dark:border-amber-900 dark:bg-slate-900"
class="flex flex-wrap items-center justify-between gap-2 rounded border border-amber-200 bg-white/95 px-2.5 py-2 text-xs dark:border-amber-900"
>
<span class="text-amber-950 dark:text-amber-50">
<span class="text-muted">{{ scopeLabel(issue.scope) }} · </span>
@@ -5,12 +5,12 @@ import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewLineFulfillment } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{ caseNo: string; draftVersion: number | null | undefined; lineFulfillment: ShippingOrderReviewLineFulfillment | null | undefined; editable: boolean }>();
const emit = defineEmits<{ refreshed: []; 'open-close-dialog': [lineKeys: string[]] }>();
const emit = defineEmits<{ refreshed: []; 'open-close-dialog': [draftLineIds: string[]] }>();
const { t } = useI18n();
const TERMINAL_STATUSES = new Set(['task_created', 'fulfilled', 'closed_unfulfillable']);
const openLines = computed(() => (props.lineFulfillment?.lines || []).filter((line) => !TERMINAL_STATUSES.has(String(line.line_status || ''))));
const visible = computed(() => Boolean(props.lineFulfillment?.has_open_lines || props.lineFulfillment?.has_shortage));
function onCloseRemaining() { emit('open-close-dialog', openLines.value.map((line) => line.line_key)); }
function onCloseRemaining() { emit('open-close-dialog', openLines.value.map((line) => line.draft_line_id)); }
</script>
<template>
@@ -25,6 +25,6 @@ function onCloseRemaining() { emit('open-close-dialog', openLines.value.map((lin
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.autoProgressCount', { count: lineFulfillment?.auto_progress_count ?? 0 }) }}</div>
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.summaryHint') }}</div>
</div>
<div v-if="editable && openLines.length" class="mt-3"><button type="button" class="rounded-xl border border-rose-300 bg-white px-3 py-1.5 text-sm text-rose-800 hover:bg-rose-50 dark:border-rose-800 dark:bg-slate-900 dark:text-rose-200" data-testid="review-fulfillment-close-remaining" @click="onCloseRemaining">{{ t('chat.shippingOrderReview.fulfillmentDecision.closeRemaining') }}</button></div>
<div v-if="editable && openLines.length" class="mt-3"><button type="button" class="rounded-xl border border-rose-300 bg-surface px-3 py-1.5 text-sm text-rose-800 hover:bg-rose-50 dark:border-rose-800 dark:text-rose-200" data-testid="review-fulfillment-close-remaining" @click="onCloseRemaining">{{ t('chat.shippingOrderReview.fulfillmentDecision.closeRemaining') }}</button></div>
</section>
</template>
@@ -47,7 +47,7 @@ watch(
>
<div
v-if="loading"
class="rounded-xl border border-dashed border-slate-300 bg-slate-50 p-4 text-sm text-slate-600 dark:border-slate-700 dark:bg-slate-900/40 dark:text-slate-300"
class="rounded-xl border border-dashed border-default bg-surface-soft p-4 text-sm text-secondary dark:bg-slate-900/40"
data-testid="intake-parse-loading"
>
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.loading') }}
@@ -70,38 +70,38 @@ watch(
</div>
<template v-else-if="context">
<section class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900">
<section class="rounded-xl border border-default bg-surface p-4 shadow-sm">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.lifecycle.intakeParse.email') }}</h2>
<template v-if="context.email">
<p class="mt-1 text-xs text-slate-500">{{ context.email.filename }}</p>
<p class="mt-1 text-xs text-muted">{{ context.email.filename }}</p>
<iframe
v-if="context.email.render_kind === 'safe_html' && context.email.preview_url"
:src="context.email.preview_url"
sandbox=""
referrerpolicy="no-referrer"
:title="t('chat.shippingOrderReview.lifecycle.intakeParse.emailPreviewTitle')"
class="mt-3 h-72 w-full rounded border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-950"
class="mt-3 h-72 w-full rounded border border-default bg-surface"
data-testid="intake-parse-email-html"
/>
<pre
v-else
class="mt-3 max-h-72 overflow-auto whitespace-pre-wrap break-words rounded bg-slate-50 p-3 text-xs text-slate-700 dark:bg-slate-950/50 dark:text-slate-200"
class="mt-3 max-h-72 overflow-auto whitespace-pre-wrap break-words rounded bg-surface-soft p-3 text-xs text-secondary dark:bg-slate-950/50"
data-testid="intake-parse-email-body"
>{{ context.email.text }}</pre>
</template>
<p
v-else
class="mt-2 text-sm text-slate-500"
class="mt-2 text-sm text-muted"
data-testid="intake-parse-no-email"
>
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.noEmail') }}
</p>
</section>
<section class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900">
<section class="rounded-xl border border-default bg-surface p-4 shadow-sm">
<h2 class="text-sm font-semibold" data-testid="intake-parse-attachment-heading">
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.attachment') }} ·
<span class="font-normal text-slate-500 dark:text-slate-400">{{ context.attachment.filename }}</span>
<span class="font-normal text-muted">{{ context.attachment.filename }}</span>
</h2>
<div
@@ -111,7 +111,7 @@ watch(
>
<p
v-if="previewLoading"
class="mt-2 text-sm text-slate-500"
class="mt-2 text-sm text-muted"
data-testid="intake-parse-preview-loading"
>
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.previewLoading') }}
@@ -120,12 +120,12 @@ watch(
v-else-if="previewUrl"
:src="previewUrl"
:title="context.attachment.filename"
class="mt-2 h-[32rem] w-full rounded border border-slate-200 dark:border-slate-700"
class="mt-2 h-[32rem] w-full rounded border border-default"
/>
<button
v-else
type="button"
class="mt-2 rounded border border-slate-300 px-2.5 py-1 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
class="mt-2 rounded border border-default px-2.5 py-1 text-xs hover-surface-soft"
data-testid="intake-parse-load-preview"
@click="emit('load-preview')"
>
@@ -134,7 +134,7 @@ watch(
</div>
<p
v-else
class="mt-4 rounded bg-slate-50 p-3 text-sm text-slate-500 dark:bg-slate-950/50"
class="mt-4 rounded bg-surface-soft p-3 text-sm text-muted dark:bg-slate-950/50"
data-testid="intake-parse-preview-unsupported"
>
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.previewUnsupported') }}
@@ -18,7 +18,7 @@ const props = defineProps<{
}>();
const emit = defineEmits<{
(e: 'reroute', lineKey?: string): void;
(e: 'reroute', draftLineId?: string): void;
}>();
const { t, te } = useI18n();
@@ -84,8 +84,8 @@ function unavailableReasonLabel(line: ShippingOrderReviewBuildEligibilityLinePro
* 触发行级重新匹配路由。
*/
function rerouteLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
const lineKey = String(line.line_key || '').trim();
emit('reroute', lineKey || undefined);
const draftLineId = String(line.draft_line_id || '').trim();
emit('reroute', draftLineId || undefined);
}
</script>
@@ -98,24 +98,24 @@ function rerouteLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
>
<header class="mb-3">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.inventoryCandidates.title') }}</h2>
<p class="mt-0.5 text-xs text-slate-600 dark:text-slate-400">
<p class="mt-0.5 text-xs text-secondary">
{{ t('chat.shippingOrderReview.inventoryCandidates.subtitle') }}
</p>
<p class="mt-1 text-xs text-slate-500 dark:text-slate-400">
<p class="mt-1 text-xs text-muted">
{{ t('chat.shippingOrderReview.inventoryRouting.rerouteHint') }}
</p>
</header>
<article
v-for="line in lines"
:key="String(line.line_key || line.line_index)"
class="mb-3 rounded-lg border border-slate-200 bg-white p-3 last:mb-0 dark:border-slate-700 dark:bg-slate-900"
:data-testid="`review-inventory-candidates-line-${line.line_key || line.line_index}`"
:key="String(line.line_no)"
class="mb-3 rounded-lg border border-default bg-surface p-3 last:mb-0"
:data-testid="`review-inventory-candidates-line-${line.line_no}`"
>
<div class="flex flex-wrap items-center justify-between gap-2 text-sm">
<span class="font-medium">
{{ t('chat.shippingOrderReview.line', { index: (line.line_index ?? 0) + 1 }) }}
<span v-if="line.effective_reservation_id" class="ml-1 text-xs text-slate-500">
<span v-if="line.effective_reservation_id" class="ml-1 text-xs text-muted">
{{ line.effective_reservation_id }}
</span>
</span>
@@ -126,7 +126,7 @@ function rerouteLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
<p
v-if="line.inventory_source_hint"
class="mt-2 text-xs text-slate-600 dark:text-slate-300"
class="mt-2 text-xs text-secondary"
data-testid="review-inventory-routing-hint"
>
{{ t('chat.shippingOrderReview.inventoryRouting.hint') }}:
@@ -138,14 +138,14 @@ function rerouteLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
>{{ sourceCodeLabel(String(line.inventory_source_hint)) }}</span>
</p>
<div class="mt-2 space-y-2 text-xs text-slate-600 dark:text-slate-300">
<div class="mt-2 space-y-2 text-xs text-secondary">
<div v-if="matchedRuleCodes(line).length" data-testid="review-inventory-matched-rules">
<div class="font-medium">{{ t('chat.shippingOrderReview.inventoryRouting.matchedRules') }}</div>
<div class="mt-1 flex flex-wrap gap-1.5">
<span
v-for="ruleCode in matchedRuleCodes(line)"
:key="`rule-${ruleCode}`"
class="rounded border border-slate-200 bg-slate-50 px-1.5 py-0.5 font-mono text-[11px] dark:border-slate-600 dark:bg-slate-800"
class="rounded border border-default bg-surface-soft px-1.5 py-0.5 font-mono text-[11px]"
>{{ ruleCode }}</span>
</div>
</div>
@@ -155,11 +155,11 @@ function rerouteLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
<div
v-for="code in line.raw_rule_source_codes"
:key="`raw-${code}`"
class="rounded-md border border-slate-200 bg-white px-2 py-1.5 dark:border-slate-600 dark:bg-slate-950"
class="rounded-md border border-default bg-surface px-2 py-1.5"
>
<div class="truncate font-medium text-slate-700 dark:text-slate-200">{{ sourceBusinessName(String(code)) }}</div>
<div class="truncate font-medium text-secondary">{{ sourceBusinessName(String(code)) }}</div>
<div
class="mt-0.5 font-mono text-[11px] text-slate-500"
class="mt-0.5 font-mono text-[11px] text-muted"
:data-source-code="sourceCodeLabel(String(code))"
>{{ sourceCodeLabel(String(code)) }}</div>
</div>
@@ -203,7 +203,7 @@ function rerouteLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
<div class="mt-3 flex flex-wrap items-center justify-end gap-2">
<button
type="button"
class="rounded border border-slate-300 bg-white px-3 py-1.5 text-xs text-slate-700 disabled:opacity-50 dark:border-slate-600 dark:bg-slate-950 dark:text-slate-200"
class="rounded border border-default bg-surface px-3 py-1.5 text-xs text-secondary disabled:opacity-50"
data-testid="review-inventory-routing-reroute"
:disabled="!editable || saving"
@click="rerouteLine(line)"
@@ -66,7 +66,7 @@ const reasonLabel = computed(() => {
</p>
<button
type="button"
class="mt-3 w-full rounded-xl border border-amber-300 bg-white px-3 py-1.5 text-sm text-amber-950 hover:bg-amber-100 disabled:opacity-50 dark:border-amber-800 dark:bg-slate-900 dark:text-amber-50"
class="mt-3 w-full rounded-xl border border-amber-300 bg-surface px-3 py-1.5 text-sm text-amber-950 hover:bg-amber-100 disabled:opacity-50 dark:border-amber-800 dark:text-amber-50"
data-testid="review-inventory-fallback-retry"
:disabled="busy"
@click="emit('retry-preparation')"
@@ -40,7 +40,7 @@ function blockReasonLabel(reason?: string | null): string {
<template>
<section
v-if="lines.length"
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
class="rounded-xl border border-default bg-surface p-3 shadow-sm"
data-testid="review-inventory-issue-list"
>
<header class="mb-2 flex items-center justify-between gap-2">
@@ -58,9 +58,9 @@ function blockReasonLabel(reason?: string | null): string {
<ul v-if="!summaryOnly" class="space-y-1.5">
<li
v-for="line in lines"
:key="String(line.line_key || line.line_index)"
:key="String(line.line_no)"
class="rounded-lg border border-amber-200 bg-amber-50/70 px-2.5 py-2 text-xs dark:border-amber-900 dark:bg-amber-950/30"
:data-testid="`review-inventory-issue-${line.line_key || line.line_index}`"
:data-testid="`review-inventory-issue-${line.line_no}`"
>
<button
type="button"
@@ -54,11 +54,11 @@ const showEnterInventory = computed(() => (
<template>
<section
v-if="visible"
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
class="rounded-xl border border-default bg-surface p-3 shadow-sm"
data-testid="review-line-fulfillment-aggregate-card"
>
<header class="mb-2">
<h2 class="text-sm font-semibold text-slate-900 dark:text-slate-50">
<h2 class="text-sm font-semibold text-primary dark:text-slate-50">
{{ t('chat.shippingOrderReview.lineFulfillmentAggregate.title') }}
</h2>
<p class="mt-0.5 text-xs text-muted">
@@ -104,7 +104,7 @@ const showEnterInventory = computed(() => (
<button
v-if="showEnterInventory"
type="button"
class="mt-3 w-full rounded-xl border border-slate-300 bg-slate-50 px-3 py-1.5 text-sm text-slate-900 hover:bg-slate-100 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-50 dark:hover:bg-slate-800"
class="mt-3 w-full rounded-xl border border-default bg-surface-soft px-3 py-1.5 text-sm text-primary hover-surface-strong dark:text-slate-50"
data-testid="review-line-fulfillment-aggregate-enter-inventory"
@click="emit('enter-inventory')"
>
@@ -120,19 +120,19 @@ function formatTime(value: string | null | undefined): string {
<template>
<div
class="rounded-md border border-slate-200 bg-slate-50/80 px-3 py-2 text-xs dark:border-slate-700 dark:bg-slate-950/50"
class="rounded-md border border-default bg-slate-50/80 px-3 py-2 text-xs dark:bg-slate-950/50"
data-testid="review-line-fulfillment-summary"
role="region"
:aria-label="t('chat.shippingOrderReview.lineFulfillmentDetail.title')"
>
<div class="mb-2 flex items-center justify-between gap-2">
<p class="font-medium text-slate-700 dark:text-slate-200">
<p class="font-medium text-secondary">
{{ t('chat.shippingOrderReview.lineFulfillmentDetail.title') }}
</p>
<div class="flex items-center gap-2">
<button
type="button"
class="rounded border border-slate-300 px-2 py-0.5 text-[11px] text-sky-700 hover:bg-white dark:border-slate-600 dark:text-sky-300 dark:hover:bg-slate-900"
class="rounded border border-default px-2 py-0.5 text-[11px] text-sky-700 hover:bg-white dark:text-sky-300"
data-testid="review-line-fulfillment-open-audit"
@click="emit('open-audit')"
>
@@ -140,7 +140,7 @@ function formatTime(value: string | null | undefined): string {
</button>
<button
type="button"
class="rounded px-2 py-0.5 text-[11px] text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-800"
class="rounded px-2 py-0.5 text-[11px] text-muted hover-surface-strong"
data-testid="review-line-fulfillment-summary-close"
@click="emit('close')"
>
@@ -155,9 +155,9 @@ function formatTime(value: string | null | undefined): string {
class="min-w-0 rounded bg-white/70 px-2 py-1.5 dark:bg-slate-900/60"
:data-testid="`review-line-fulfillment-field-${row.key}`"
>
<dt class="text-[10px] font-medium text-slate-500 dark:text-slate-400">{{ row.label }}</dt>
<dt class="text-[10px] font-medium text-muted">{{ row.label }}</dt>
<dd
class="mt-0.5 break-words text-[11px] text-slate-800 dark:text-slate-100"
class="mt-0.5 break-words text-[11px] text-primary"
:class="row.emphasize ? 'font-medium text-rose-700 dark:text-rose-300' : ''"
>
{{ row.value }}
@@ -89,7 +89,7 @@ onBeforeUnmount(() => {
v-if="showMore"
ref="moreBtnRef"
type="button"
class="rounded p-1.5 hover:bg-slate-100 disabled:opacity-50 dark:hover:bg-slate-800"
class="rounded p-1.5 hover-surface-strong disabled:opacity-50"
data-testid="review-line-more-actions"
:disabled="!editable || busy || taskRunning"
:aria-label="t('chat.shippingOrderReview.lineOps.moreActions')"
@@ -103,7 +103,7 @@ onBeforeUnmount(() => {
<Teleport to="body">
<div
v-if="moreMenuOpen && showMore"
class="rounded-md border border-slate-200 bg-white py-1 shadow-lg dark:border-slate-700 dark:bg-slate-900"
class="rounded-md border border-default bg-surface py-1 shadow-lg"
role="menu"
data-testid="review-line-more-menu"
:style="moreMenuStyle"
@@ -1,259 +0,0 @@
<!--
features/chat/components/shipping-review/ReviewLineNoOverrideDialog.vue
用途:复核页编辑内部项次 line_no 时的强制原因弹窗(覆盖须审计)。
依赖:vue-i18n、dialog-overlay / dialog-panel。
逻辑:ShippingOrderReviewView 拦截 line_no 输入变更;确认后携带 reasonCode/reasonText 调用 patchLine。
确认仅发出事件,不自行关闭;父组件成功后再关,失败时保留原因选择与说明。
打开时聚焦原因选择框,Tab 焦点陷阱在弹窗内,关闭后恢复先前焦点。
-->
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
/** 与后端 LINE_NO_OVERRIDE_REASON_CODES 对齐的稳定原因码。 */
const LINE_NO_OVERRIDE_REASON_CODES = [
'recognition_error',
'customer_line_exception',
'business_correction',
'other',
] as const;
type LineNoOverrideReasonCode = (typeof LINE_NO_OVERRIDE_REASON_CODES)[number];
/** 内部项次覆盖确认载荷;供复核页 confirm 事件消费。 */
export type LineNoOverridePayload = {
value: string;
reasonCode: LineNoOverrideReasonCode;
reasonText: string;
};
interface Props {
modelValue: boolean;
/** 用户拟写入的新项次值(已在输入框中编辑)。 */
pendingValue: string;
confirmLoading?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
confirmLoading: false,
});
const emit = defineEmits<{
(e: 'update:modelValue', value: boolean): void;
(e: 'confirm', payload: LineNoOverridePayload): void;
(e: 'cancel'): void;
}>();
const { t } = useI18n();
const reasonCode = ref<LineNoOverrideReasonCode>('recognition_error');
const reasonText = ref('');
const reasonMissing = ref(false);
const textMissing = ref(false);
const panelRef = ref<HTMLElement | null>(null);
const reasonSelectRef = ref<HTMLSelectElement | null>(null);
let previouslyFocused: HTMLElement | null = null;
const FOCUSABLE_SELECTOR = [
'a[href]',
'button:not([disabled])',
'textarea:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'[tabindex]:not([tabindex="-1"])',
].join(',');
const title = computed(() => t('chat.shippingOrderReview.lineNoOverrideDialog.title'));
const impact = computed(() => t('chat.shippingOrderReview.lineNoOverrideDialog.impact'));
/**
* 原因码展示文案。
* @param code - 后端允许的覆盖原因码
*/
const reasonLabel = (code: string) =>
t(`chat.shippingOrderReview.lineNoOverrideDialog.reasons.${code}`);
/** 收集弹窗内可聚焦控件,供 Tab 陷阱使用。 */
const focusableNodes = (): HTMLElement[] => {
if (!panelRef.value) return [];
return Array.from(panelRef.value.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR))
.filter((node) => !node.hasAttribute('disabled') && node.getAttribute('aria-hidden') !== 'true');
};
/** 关闭弹窗并同步 v-model。 */
const closeDialog = () => {
emit('update:modelValue', false);
};
const handleCancel = () => {
if (props.confirmLoading) return;
emit('cancel');
closeDialog();
};
/**
* 校验原因码与「其他」说明后提交覆盖。
* 核心逻辑:other 强制补充说明;确认后不关闭,由父组件在保存成功后再关,失败时保留表单。
*/
const handleConfirm = () => {
if (props.confirmLoading) return;
reasonMissing.value = false;
textMissing.value = false;
if (!reasonCode.value) {
reasonMissing.value = true;
return;
}
const trimmed = reasonText.value.trim();
if (reasonCode.value === 'other' && !trimmed) {
textMissing.value = true;
return;
}
emit('confirm', {
value: String(props.pendingValue ?? '').trim(),
reasonCode: reasonCode.value,
reasonText: trimmed,
});
};
/**
* Escape 关闭;Tab / Shift+Tab 在弹窗内循环,阻止焦点逃逸到背景页。
*/
const onKeydown = (event: KeyboardEvent) => {
if (!props.modelValue) return;
if (event.key === 'Escape' && !props.confirmLoading) {
event.preventDefault();
event.stopPropagation();
handleCancel();
return;
}
if (event.key !== 'Tab') return;
const nodes = focusableNodes();
const first = nodes[0];
const last = nodes[nodes.length - 1];
// noUncheckedIndexedAccess:空数组或下标越界时 first/last 可能为 undefined。
if (!first || !last) {
event.preventDefault();
return;
}
const active = document.activeElement as HTMLElement | null;
const inside = Boolean(active && panelRef.value?.contains(active));
if (event.shiftKey) {
if (!inside || active === first) {
event.preventDefault();
last.focus();
}
return;
}
if (!inside || active === last) {
event.preventDefault();
first.focus();
}
};
watch(
() => props.modelValue,
async (open, wasOpen) => {
if (typeof document === 'undefined') return;
if (open && !wasOpen) {
reasonCode.value = 'recognition_error';
reasonText.value = '';
reasonMissing.value = false;
textMissing.value = false;
previouslyFocused = document.activeElement instanceof HTMLElement
? document.activeElement
: null;
document.addEventListener('keydown', onKeydown, true);
await nextTick();
(reasonSelectRef.value || focusableNodes()[0])?.focus();
return;
}
if (!open && wasOpen) {
document.removeEventListener('keydown', onKeydown, true);
const restoreTarget = previouslyFocused;
previouslyFocused = null;
await nextTick();
restoreTarget?.focus?.();
}
},
);
onBeforeUnmount(() => {
if (typeof document !== 'undefined') {
document.removeEventListener('keydown', onKeydown, true);
}
});
</script>
<template>
<Teleport to="body">
<div
v-if="modelValue"
class="dialog-overlay z-50 flex items-center justify-center p-4"
role="dialog"
aria-modal="true"
:aria-label="title"
data-testid="review-line-no-override-dialog"
@click.self="handleCancel"
>
<div ref="panelRef" class="dialog-panel w-full max-w-md space-y-4 p-5">
<header>
<h2 class="text-base font-semibold text-primary" id="review-line-no-override-title">{{ title }}</h2>
<p class="mt-2 text-sm text-secondary">{{ impact }}</p>
<p class="mt-2 text-sm text-primary">
{{ t('chat.shippingOrderReview.lineNoOverrideDialog.newValue', { value: pendingValue || '—' }) }}
</p>
</header>
<label class="block space-y-1 text-sm">
<span class="text-secondary">{{ t('chat.shippingOrderReview.lineNoOverrideDialog.reasonCodeLabel') }}</span>
<select
ref="reasonSelectRef"
v-model="reasonCode"
class="select-field w-full text-sm"
data-testid="review-line-no-reason-code"
:disabled="confirmLoading"
:aria-labelledby="'review-line-no-override-title'"
@change="reasonMissing = false"
>
<option v-for="code in LINE_NO_OVERRIDE_REASON_CODES" :key="code" :value="code">
{{ reasonLabel(code) }}
</option>
</select>
<p v-if="reasonMissing" class="text-xs text-rose-600 dark:text-rose-400">
{{ t('chat.shippingOrderReview.lineNoOverrideDialog.reasonCodeRequired') }}
</p>
</label>
<label class="block space-y-1 text-sm">
<span class="text-secondary">{{ t('chat.shippingOrderReview.lineNoOverrideDialog.reasonTextLabel') }}</span>
<textarea
v-model="reasonText"
rows="3"
class="input-field w-full resize-y text-sm"
:placeholder="t('chat.shippingOrderReview.lineNoOverrideDialog.reasonTextPlaceholder')"
data-testid="review-line-no-reason-text"
:disabled="confirmLoading"
@input="textMissing = false"
/>
<p v-if="textMissing" class="text-xs text-rose-600 dark:text-rose-400">
{{ t('chat.shippingOrderReview.lineNoOverrideDialog.reasonTextRequired') }}
</p>
</label>
<footer class="flex justify-end gap-2 pt-1">
<button type="button" class="btn-secondary btn-sm" :disabled="confirmLoading" @click="handleCancel">
{{ t('common.deleteDialog.cancel') }}
</button>
<button
type="button"
class="btn-primary btn-sm"
:disabled="confirmLoading"
data-testid="review-line-no-override-submit"
@click="handleConfirm"
>
{{ confirmLoading ? t('chat.shippingOrderReview.saving') : t('chat.shippingOrderReview.lineNoOverrideDialog.confirm') }}
</button>
</footer>
</div>
</div>
</Teleport>
</template>
@@ -54,18 +54,18 @@ const verbatimOk = computed(() => {
<template>
<div class="grid gap-3 md:grid-cols-3" data-testid="review-llm-evidence-comparison">
<div class="rounded-lg border border-slate-200 bg-slate-50 p-3">
<p class="text-xs font-medium uppercase tracking-wide text-slate-500">
<div class="rounded-lg border border-default bg-surface-soft p-3">
<p class="text-xs font-medium uppercase tracking-wide text-muted">
{{ t('chat.shippingOrderReview.llmSuggestion.currentDraft') }}
</p>
<p class="mt-2 text-sm font-semibold text-slate-900">{{ props.fieldLabel }}</p>
<p class="mt-1 text-sm text-slate-700">{{ draftDisplay }}</p>
<p class="mt-2 text-sm font-semibold text-primary">{{ props.fieldLabel }}</p>
<p class="mt-1 text-sm text-secondary">{{ draftDisplay }}</p>
</div>
<div class="rounded-lg border border-indigo-200 bg-indigo-50/60 p-3">
<p class="text-xs font-medium uppercase tracking-wide text-indigo-600">
{{ t('chat.shippingOrderReview.llmSuggestion.aiSuggestion') }}
</p>
<p class="mt-2 text-sm font-semibold text-slate-900">{{ suggestedValue }}</p>
<p class="mt-2 text-sm font-semibold text-primary">{{ suggestedValue }}</p>
<p class="mt-1 text-xs" :class="verbatimOk ? 'text-emerald-700' : 'text-amber-700'">
{{
verbatimOk
@@ -74,12 +74,12 @@ const verbatimOk = computed(() => {
}}
</p>
</div>
<div class="rounded-lg border border-slate-200 bg-white p-3">
<p class="text-xs font-medium uppercase tracking-wide text-slate-500">
<div class="rounded-lg border border-default bg-surface p-3">
<p class="text-xs font-medium uppercase tracking-wide text-muted">
{{ t('chat.shippingOrderReview.llmSuggestion.sourceEvidence') }}
</p>
<p class="mt-2 text-sm text-slate-800">{{ evidenceQuote }}</p>
<p class="mt-1 text-xs text-slate-500">{{ evidenceLocation }}</p>
<p class="mt-2 text-sm text-primary">{{ evidenceQuote }}</p>
<p class="mt-1 text-xs text-muted">{{ evidenceLocation }}</p>
</div>
</div>
</template>
@@ -163,11 +163,11 @@ onBeforeUnmount(() => {
>
<div
ref="panelRef"
class="max-h-[80vh] w-full max-w-3xl overflow-auto rounded-lg bg-white p-4 shadow-lg dark:bg-slate-900"
class="max-h-[80vh] w-full max-w-3xl overflow-auto rounded-lg bg-surface p-4 shadow-lg"
data-testid="review-llm-suggestion-panel"
>
<h3 class="text-base font-semibold">{{ t('chat.shippingOrderReview.llmSuggestion.dialogTitle') }}</h3>
<p class="mt-1 text-xs text-slate-500">
<p class="mt-1 text-xs text-muted">
{{ t('chat.shippingOrderReview.llmSuggestion.dialogHint') }}
· {{ evidenceLevelText }}
</p>
@@ -199,12 +199,12 @@ onBeforeUnmount(() => {
<input
v-if="decision === 'modify'"
v-model="modifiedValue"
class="mt-2 w-full rounded border p-2 text-sm dark:border-slate-700 dark:bg-slate-950"
class="mt-2 w-full rounded border p-2 text-sm"
:placeholder="t('chat.shippingOrderReview.llmSuggestion.modifiedValue')"
/>
<textarea
v-model="reason"
class="mt-2 w-full rounded border p-2 text-sm dark:border-slate-700 dark:bg-slate-950"
class="mt-2 w-full rounded border p-2 text-sm"
rows="2"
:placeholder="
decision === 'accept'
@@ -46,12 +46,12 @@ const { t } = useI18n();
data-testid="review-llm-suggestion-drawer"
@click.self="emit('close')"
>
<aside class="flex h-full w-full max-w-lg flex-col bg-white shadow-xl dark:bg-slate-900">
<header class="flex items-center justify-between gap-2 border-b border-slate-200 px-4 py-3 dark:border-slate-800">
<aside class="flex h-full w-full max-w-lg flex-col bg-surface shadow-xl">
<header class="flex items-center justify-between gap-2 border-b border-default px-4 py-3">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.llmSuggestion.panelTitle') }}</h2>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
data-testid="review-llm-drawer-close"
@click="emit('close')"
>
@@ -3,7 +3,7 @@
用途:AI 建议列表与裁决内容(布局重构后作为抽屉内容组件,非常驻主区大卡片)。
依赖:vue-i18n、ReviewLlmSuggestionDialog、ShippingOrderReview* 类型。
逻辑:由 ReviewLlmSuggestionDrawer 挂载;请求须用户主动触发;仅 validated 可接受;
validation_failed 仅可拒绝;provider_unavailable 明示原因;证据按 field_id + line_key/line_index 绑定。
validation_failed 仅可拒绝;provider_unavailable 明示原因;证据按 field_id + draft_line_id/line_index 绑定。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
@@ -130,8 +130,8 @@ function evidenceMatchesFieldLine(
const selectedEvidence = computed(() => {
const items = props.evidence || [];
const fieldId = String(selected.value?.field_id || props.focusedFieldId || '');
const lineKey = selected.value?.line_key ?? props.focusedLineKey;
return items.find((item) => evidenceMatchesFieldLine(item, fieldId, lineKey)) || null;
const draftLineId = selected.value?.draft_line_id ?? props.focusedLineKey;
return items.find((item) => evidenceMatchesFieldLine(item, fieldId, draftLineId)) || null;
});
/**
@@ -153,12 +153,12 @@ function readContainerDraftValue(container: Record<string, unknown> | null | und
*/
const dialogDraftValue = computed(() => {
const fieldId = String(selected.value?.field_id || props.focusedFieldId || '');
const lineKey = selected.value?.line_key ?? props.focusedLineKey;
const draftLineId = selected.value?.draft_line_id ?? props.focusedLineKey;
const draft = props.activeCase?.draft;
if (!draft || !fieldId) return props.draftValue ?? null;
if (lineKey) {
if (draftLineId) {
const lines = Array.isArray(draft.lines) ? draft.lines : [];
const line = lines.find((item) => String((item as { line_key?: string }).line_key || '') === String(lineKey));
const line = lines.find((item) => String((item as { draft_line_id?: string }).draft_line_id || '') === String(draftLineId));
return readContainerDraftValue(line as Record<string, unknown> | undefined, fieldId);
}
return readContainerDraftValue(draft.header_values as Record<string, unknown> | undefined, fieldId);
@@ -180,8 +180,8 @@ function suggestionFieldLabel(item: ShippingOrderReviewLlmSuggestion): string {
const fields = props.activeCase?.schema?.fields || [];
const hit = fields.find((field) => String(field.field_id || '') === fieldId);
const name = String(hit?.display_name || hit?.field_code || '').trim();
if (name && item.line_key) {
return `${name} · ${item.line_key}`;
if (name && item.draft_line_id) {
return `${name} · ${item.draft_line_id}`;
}
return name || t('chat.shippingOrderReview.unknownField');
}
@@ -214,11 +214,11 @@ function onDecide(payload: { decision: 'accept' | 'modify' | 'reject'; reason: s
</script>
<template>
<section class="rounded-xl border border-slate-200 bg-white p-3 text-sm shadow-sm dark:border-slate-800 dark:bg-slate-900">
<section class="rounded-xl border border-default bg-surface p-3 text-sm shadow-sm">
<div class="flex flex-wrap items-center justify-between gap-2">
<div>
<div class="font-semibold">{{ t('chat.shippingOrderReview.llmSuggestion.panelTitle') }}</div>
<div class="mt-1 text-xs text-slate-500">
<div class="mt-1 text-xs text-muted">
{{ t('chat.shippingOrderReview.llmSuggestion.panelHint') }}
· {{ evidenceLevelLabel(selected?.evidence_level || 'L1_field') }}
· {{ statusLabel }}
@@ -289,7 +289,7 @@ function onDecide(payload: { decision: 'accept' | 'modify' | 'reject'; reason: s
</div>
<button
type="button"
class="shrink-0 rounded border border-sky-300 bg-white px-2 py-0.5 text-xs text-sky-700 dark:border-sky-700 dark:bg-slate-900 dark:text-sky-200"
class="shrink-0 rounded border border-sky-300 bg-surface px-2 py-0.5 text-xs text-sky-700 dark:border-sky-700 dark:text-sky-200"
:disabled="!canRequest"
:aria-label="t('chat.shippingOrderReview.llmSuggestion.request')"
@click="emit('requestSuggestion')"
@@ -301,7 +301,7 @@ function onDecide(payload: { decision: 'accept' | 'modify' | 'reject'; reason: s
</ul>
<p
v-if="!pendingSuggestions.length && !failedSuggestions.length && !unavailableSuggestions.length && !gatedFailedSuggestions.length"
class="mt-3 text-xs text-slate-500"
class="mt-3 text-xs text-muted"
>
{{ t('chat.shippingOrderReview.llmSuggestion.empty') }}
</p>
@@ -309,7 +309,7 @@ function onDecide(payload: { decision: 'accept' | 'modify' | 'reject'; reason: s
<li
v-for="item in pendingSuggestions"
:key="item.suggestion_no"
class="flex items-center justify-between gap-2 rounded border border-slate-200 px-2 py-1.5 dark:border-slate-700"
class="flex items-center justify-between gap-2 rounded border border-default px-2 py-1.5"
>
<div class="min-w-0 truncate text-xs">
<span class="font-medium">{{ suggestionFieldLabel(item) }}</span>
@@ -85,7 +85,7 @@ const selectedLabel = computed(() => {
<template>
<section
v-if="visible"
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
class="rounded-xl border border-default bg-surface p-3 shadow-sm"
data-testid="review-profile-match-panel"
:data-status="String(profileMatch?.status || '')"
>
@@ -126,7 +126,7 @@ const selectedLabel = computed(() => {
<template v-if="isAdminView && candidateCount">
<button
type="button"
class="mt-3 flex w-full items-center justify-between rounded-lg border border-default bg-surface-soft px-2.5 py-2 text-left text-xs font-medium text-secondary transition-colors hover:bg-slate-50 dark:hover:bg-slate-800"
class="mt-3 flex w-full items-center justify-between rounded-lg border border-default bg-surface-soft px-2.5 py-2 text-left text-xs font-medium text-secondary transition-colors hover-surface-soft"
data-testid="review-profile-match-candidates-toggle"
:aria-expanded="candidatesExpanded"
@click="toggleCandidates"
@@ -110,7 +110,7 @@ async function onRevalidate() {
<li
v-for="(issue, idx) in issues"
:key="`${issue.code}-${issue.line_index}-${idx}`"
class="rounded border border-violet-200 bg-white/90 px-2 py-1 dark:border-violet-900 dark:bg-slate-900"
class="rounded border border-violet-200 bg-white/90 px-2 py-1 dark:border-violet-900"
>
<span v-if="issue.line_index != null">#{{ issue.line_index + 1 }} · </span>
{{ issue.message || issueLabel(issue.code) }}
@@ -132,7 +132,7 @@ async function onRevalidate() {
<tbody>
<tr
v-for="line in lines"
:key="String(line.line_key || line.line_index)"
:key="String(line.draft_line_id || line.line_index)"
class="border-t border-violet-100 dark:border-violet-900"
:class="line.needs_attention ? 'bg-amber-50/80 dark:bg-amber-950/20' : ''"
>
@@ -151,7 +151,7 @@ async function onRevalidate() {
<div v-if="editable" class="mt-3 flex flex-wrap gap-2">
<button
type="button"
class="rounded-xl border border-violet-300 bg-white px-3 py-1.5 text-sm text-violet-950 hover:bg-violet-100 disabled:opacity-60 dark:border-violet-800 dark:bg-slate-900 dark:text-violet-100 dark:hover:bg-violet-950"
class="rounded-xl border border-violet-300 bg-surface px-3 py-1.5 text-sm text-violet-950 hover:bg-violet-100 disabled:opacity-60 dark:border-violet-800 dark:text-violet-100 dark:hover:bg-violet-950"
data-testid="review-reservation-revalidate"
:disabled="busy || draftVersion == null"
@click="onRevalidate"
@@ -32,12 +32,12 @@ const { t } = useI18n();
data-testid="review-version-history-drawer"
@click.self="emit('close')"
>
<aside class="flex h-full w-full max-w-md flex-col bg-white shadow-xl dark:bg-slate-900">
<header class="flex items-center justify-between gap-2 border-b border-slate-200 px-4 py-3 dark:border-slate-800">
<aside class="flex h-full w-full max-w-md flex-col bg-surface shadow-xl">
<header class="flex items-center justify-between gap-2 border-b border-default px-4 py-3">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.versionHistory.title') }}</h2>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
class="rounded border border-default px-2 py-1 text-xs hover-surface-soft"
data-testid="review-version-history-close"
@click="emit('close')"
>
@@ -52,25 +52,25 @@ function selectVersion(version: ShippingWorkflowItemVersion) {
<template>
<section
class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900"
class="rounded-xl border border-default bg-surface p-4 shadow-sm"
data-testid="review-version-history-panel"
:aria-label="t('chat.shippingOrderReview.versionHistory.title')"
>
<header class="mb-3 flex items-center justify-between gap-2">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.versionHistory.title') }}</h2>
<p v-if="itemNo" class="mt-0.5 text-xs text-slate-500 dark:text-slate-400">
<p v-if="itemNo" class="mt-0.5 text-xs text-muted">
{{ t('chat.shippingOrderReview.versionHistory.itemNo', { itemNo }) }}
</p>
</div>
</header>
<div v-if="loading" class="py-4 text-sm text-slate-500">{{ t('chat.shippingProcessing.loading') }}</div>
<div v-if="loading" class="py-4 text-sm text-muted">{{ t('chat.shippingProcessing.loading') }}</div>
<template v-else>
<p class="mb-2 text-xs text-slate-500 dark:text-slate-400">
<p class="mb-2 text-xs text-muted">
{{ t('chat.shippingProcessing.versionHistoryNote') }}
</p>
<p v-if="!versions.length" class="py-4 text-sm text-slate-500">
<p v-if="!versions.length" class="py-4 text-sm text-muted">
{{ t('chat.shippingSessionWorkItem.noVersions') }}
</p>
@@ -81,7 +81,7 @@ function selectVersion(version: ShippingWorkflowItemVersion) {
class="rounded-lg border p-3 text-sm"
:class="activeCaseNo === version.case_no
? 'border-sky-500 bg-sky-50 dark:border-sky-700 dark:bg-sky-950/30'
: 'border-slate-200 dark:border-slate-700'"
: 'border-default '"
:data-testid="`review-version-row-${version.case_no}`"
>
<div class="flex flex-wrap items-start justify-between gap-2">
@@ -98,19 +98,19 @@ function selectVersion(version: ShippingWorkflowItemVersion) {
</span>
<span
v-else-if="version.is_readonly"
class="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] text-slate-600 dark:bg-slate-800 dark:text-slate-300"
class="rounded-full bg-surface-strong px-2 py-0.5 text-[11px] text-secondary"
>
{{ t('chat.shippingSessionWorkItem.readonlyVersion') }}
</span>
</div>
<p class="mt-1 truncate text-xs text-slate-500 dark:text-slate-400">
<p class="mt-1 truncate text-xs text-muted">
{{ version.run_no || version.case_no }}
</p>
</div>
<button
v-if="activeCaseNo !== version.case_no"
type="button"
class="shrink-0 rounded border border-slate-200 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
class="shrink-0 rounded border border-default px-2 py-1 text-xs hover-surface-soft"
@click="selectVersion(version)"
>
{{ version.is_readonly
@@ -119,7 +119,7 @@ function selectVersion(version: ShippingWorkflowItemVersion) {
</button>
</div>
<dl class="mt-2 grid gap-1 text-xs text-slate-600 dark:text-slate-400 sm:grid-cols-2">
<dl class="mt-2 grid gap-1 text-xs text-secondary sm:grid-cols-2">
<div>
<dt class="inline">{{ t('chat.shippingOrderReview.versionHistory.result') }}:</dt>
<dd class="inline">{{ resultLabel(version.case_status) }}</dd>
@@ -97,7 +97,7 @@ const canWriteCaseActions = computed(() => props.actionsExecutable && !props.isR
<template>
<footer
v-if="showFooter"
class="sticky bottom-0 z-20 flex shrink-0 flex-col gap-3 border-t border-slate-200 bg-white/95 p-3 shadow-[0_-4px_12px_rgba(15,23,42,0.06)] backdrop-blur sm:flex-row sm:items-center sm:justify-between dark:border-slate-800 dark:bg-slate-900/95"
class="sticky bottom-0 z-20 flex shrink-0 flex-col gap-3 border-t border-default bg-white/95 p-3 shadow-[0_-4px_12px_rgba(15,23,42,0.06)] backdrop-blur sm:flex-row sm:items-center sm:justify-between dark:bg-slate-900/95"
data-testid="review-footer-actions"
:data-automating="automating ? '1' : '0'"
:data-flow-busy="flowBusy ? '1' : '0'"
@@ -127,7 +127,7 @@ const canWriteCaseActions = computed(() => props.actionsExecutable && !props.isR
v-if="showParseDispositions && hasAction('reparse')"
type="button"
:disabled="controlsBusy"
class="inline-flex items-center gap-1 rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 disabled:opacity-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
class="inline-flex items-center gap-1 rounded border border-default px-3 py-2 text-sm text-secondary hover-surface-soft disabled:opacity-50"
@click="emit('reparse')"
>
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.reparse') }}
@@ -139,7 +139,7 @@ const canWriteCaseActions = computed(() => props.actionsExecutable && !props.isR
:key="`${item.intent}-${item.actionCode}`"
type="button"
:disabled="controlsBusy"
class="rounded border border-slate-300 px-3 py-2 text-sm text-slate-700 hover:bg-slate-50 disabled:opacity-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800"
class="rounded border border-default px-3 py-2 text-sm text-secondary hover-surface-soft disabled:opacity-50"
:data-testid="`review-footer-flow-${item.intent}`"
:data-intent="item.intent"
@click="emit('flow-action', item)"
@@ -31,10 +31,10 @@ const { t } = useI18n();
</script>
<template>
<header class="flex shrink-0 items-center gap-3 border-b border-slate-200 bg-white px-4 py-3 dark:border-slate-800 dark:bg-slate-900">
<header class="flex shrink-0 items-center gap-3 border-b border-default bg-surface px-4 py-3">
<button
type="button"
class="rounded-md p-1 hover:bg-slate-100 dark:hover:bg-slate-800"
class="rounded-md p-1 hover-surface-strong"
:aria-label="t('chat.shippingOrderReview.backToSession')"
@click="emit('back')"
>
@@ -44,14 +44,14 @@ const { t } = useI18n();
<h1 class="text-base font-semibold">{{ t('chat.shippingOrderReview.title') }}</h1>
<p
v-if="selectedOrderSummary"
class="truncate text-xs text-slate-600 dark:text-slate-300"
class="truncate text-xs text-secondary"
data-testid="review-selected-order-summary"
>{{ selectedOrderSummary }}</p>
</div>
<button
v-if="showAuditTrail"
type="button"
class="rounded border border-slate-200 px-2.5 py-1.5 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
class="rounded border border-default px-2.5 py-1.5 text-xs hover-surface-soft"
data-testid="review-open-audit-trail"
@click="emit('open-audit-trail')"
>
@@ -60,7 +60,7 @@ const { t } = useI18n();
<button
v-if="showVersionHistory"
type="button"
class="rounded border border-slate-200 px-2.5 py-1.5 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
class="rounded border border-default px-2.5 py-1.5 text-xs hover-surface-soft"
data-testid="review-open-version-history"
@click="emit('open-version-history')"
>
@@ -85,7 +85,7 @@ const { t } = useI18n();
</span>
<span
v-if="isReadOnly"
class="shrink-0 rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-600 dark:bg-slate-800 dark:text-slate-300"
class="shrink-0 rounded-full bg-surface-strong px-2 py-0.5 text-xs text-secondary"
>
{{ t('chat.shippingOrderReview.readOnly') }}
</span>
@@ -38,11 +38,11 @@ function setMode(next: ReviewWorkbenchMode) {
<template>
<!-- 产品契约:工作台模式条始终可见,便于发现库存/证据模式入口。 -->
<div
class="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs dark:border-slate-800 dark:bg-slate-900"
class="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-default bg-surface px-3 py-2 text-xs"
data-testid="review-workbench-mode"
:data-workbench-mode="mode"
>
<span class="font-medium text-slate-600 dark:text-slate-300">
<span class="font-medium text-secondary">
{{ modeLabel }}
</span>
<div class="flex flex-wrap items-center gap-2">
@@ -58,7 +58,7 @@ function setMode(next: ReviewWorkbenchMode) {
<button
v-if="mode === 'evidence' || mode === 'inventory'"
type="button"
class="rounded border border-slate-300 px-2 py-1 text-slate-700 hover:bg-slate-50 dark:border-slate-600 dark:text-slate-300 dark:hover:bg-slate-800"
class="rounded border border-default px-2 py-1 text-secondary hover-surface-soft"
data-testid="review-return-standard-mode"
@click="setMode('standard')"
>
@@ -293,6 +293,51 @@ describe('ShippingConversationProcessingCard', () => {
expect(wrapper.text()).not.toContain('snapshot-attachment.pdf');
});
it('keeps selected but unrecognized EML attachments visible without file actions', async () => {
const projection = buildProjection();
setStatusGroup(projection, 'processing', [{
user_task_no: 'INTAKE:EML-PENDING', group: 'processing', status_label: 'extracting',
title: 'pending-mail.eml', file_count: 2, run_no: 'RUN-EML-PENDING', can_append: false,
}]);
const recognizedLeaf = buildWorkItem('DOCUMENT:91', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-PENDING',
sourceSummary: {
emailSubject: null, filename: 'recognized.pdf', documentId: 91,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: null,
},
});
const pendingLeaf = buildWorkItem('PLAN:EML-PENDING:missing.pdf', {
workItemType: 'order_intake', sourceType: 'eml', rootOrderTaskNo: null,
sourceSummary: {
emailSubject: null, filename: 'missing.pdf', documentId: null,
documentCount: 0, parsedDocumentCount: 0, candidateCount: 0,
customerName: null, poNumber: null,
},
facts: { recognized: false, planState: 'selected_pending' },
uiState: undefined,
});
const root = buildWorkItem('INTAKE:EML-PENDING', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-PENDING',
sourceSummary: {
emailSubject: 'Pending mail', filename: 'pending-mail.eml', documentId: null,
documentCount: 2, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: null,
},
aggregateChildren: [recognizedLeaf, pendingLeaf],
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [root], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
const pendingRow = wrapper.get('[data-testid="shipping-processing-file-INTAKE:EML-PENDING-live-PLAN:EML-PENDING:missing.pdf"]');
expect(pendingRow.text()).toContain('missing.pdf');
expect(pendingRow.text()).toContain('待识别');
expect(pendingRow.find('button').exists()).toBe(false);
});
it('counts only stage-filtered EML leaves in the batch status heading', async () => {
const projection = buildProjection();
setStatusGroup(projection, 'processing', [{
@@ -330,6 +375,91 @@ describe('ShippingConversationProcessingCard', () => {
expect(wrapper.get('[data-testid="shipping-processing-group-processing"]').text()).not.toContain('2 个文件');
});
it('keeps backend processing rows visible while matching work items are still unavailable', async () => {
const processingLeaf = buildWorkItem('DOCUMENT:610', {
sourceType: 'eml', rootOrderTaskNo: 'OT-PROCESSING-SNAPSHOT',
sourceSummary: { ...buildWorkItem('DOCUMENT:610').sourceSummary, documentId: 610, filename: 'processing.pdf' },
uiState: {
status: 'running', stage: 'document_parsing', lifecycleStage: 'intake_parse',
lifecycleEntries: [], blocking_reason: null, primary_action: null, secondary_actions: [],
},
});
const projection = projectionWithGroups(
{ total_tasks: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
{
failed: [], waiting_human: [],
processing: [{
user_task_no: 'OT-PROCESSING-SNAPSHOT', group: 'processing', status_label: 'processing',
title: 'processing.eml', file_count: 1, run_no: 'RUN-PROCESSING-SNAPSHOT', can_append: false,
aggregateChildren: [processingLeaf],
}],
completed: [], cancelled: [], archived: [],
},
);
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
// 状态分组先到达时,须以同次响应的叶子快照保留处理中附件。
const group = wrapper.get('[data-testid="shipping-processing-group-processing"]');
expect(group.text()).toContain('处理中 · 1 个文件');
expect(group.text()).toContain('processing.pdf');
});
it('shows a mixed-status EML once per PDF status without mixing completed files', async () => {
const completedLeaf = buildWorkItem('DOCUMENT:501', {
sourceType: 'eml', rootOrderTaskNo: 'OT-MIXED-STATUS',
sourceSummary: { ...buildWorkItem('DOCUMENT:501').sourceSummary, documentId: 501, filename: 'done.pdf' },
uiState: {
status: 'completed', stage: 'completed', lifecycleStage: 'upload_complete',
lifecycleEntries: [], blocking_reason: null, primary_action: null, secondary_actions: [],
},
});
const processingLeaf = buildWorkItem('DOCUMENT:502', {
sourceType: 'eml', rootOrderTaskNo: 'OT-MIXED-STATUS',
sourceSummary: { ...buildWorkItem('DOCUMENT:502').sourceSummary, documentId: 502, filename: 'running.pdf' },
uiState: {
status: 'running', stage: 'freight_upload', lifecycleStage: 'freight_upload',
lifecycleEntries: [], blocking_reason: null, primary_action: null, secondary_actions: [],
},
});
const root = buildWorkItem('INTAKE:MIXED-STATUS', {
sourceType: 'eml', rootOrderTaskNo: 'OT-MIXED-STATUS',
sourceSummary: { ...buildWorkItem('INTAKE:MIXED-STATUS').sourceSummary, filename: 'mixed.eml', documentId: null },
aggregateChildren: [completedLeaf, processingLeaf],
});
const task = {
user_task_no: 'OT-MIXED-STATUS', title: 'mixed.eml', file_count: 1, run_no: 'RUN-MIXED-STATUS', can_append: false,
aggregateSummary: { intakeNo: 'SNI-MIXED-STATUS', total: 2, in_group: 1 },
};
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: projectionWithGroups(
{ total_tasks: 2, processing: 1, needs_action: 0, completed: 1, history: 0 },
{
failed: [], waiting_human: [],
processing: [{ ...task, group: 'processing', status_label: 'processing', aggregateChildren: [processingLeaf] }],
completed: [{ ...task, group: 'completed', status_label: 'completed', aggregateChildren: [completedLeaf] }],
cancelled: [], archived: [],
},
),
workItems: [root], workbenchMode: true,
},
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.get('[data-testid="shipping-processing-group-processing"]').text()).toContain('running.pdf');
expect(wrapper.get('[data-testid="shipping-processing-group-processing"]').text()).not.toContain('done.pdf');
expect(wrapper.get('[data-testid="shipping-processing-group-processing"]').text()).toContain('本组 1/共 2 个文件');
await wrapper.get('[data-testid="shipping-processing-history-toggle"]').trigger('click');
expect(wrapper.get('[data-testid="shipping-processing-history-completed"]').text()).toContain('done.pdf');
expect(wrapper.get('[data-testid="shipping-processing-history-completed"]').text()).not.toContain('running.pdf');
expect(wrapper.get('[data-testid="shipping-processing-history-completed"]').text()).toContain('本组 1/共 2 个文件');
});
it('keeps an EML attachment when it has a linked child order task', async () => {
const projection = buildProjection();
setStatusGroup(projection, 'processing', [{
@@ -386,15 +516,15 @@ describe('ShippingConversationProcessingCard', () => {
expect(wrapper.find('[data-testid="shipping-conversation-processing-card"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-failed"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-processing"]').exists()).toBe(true);
// 批次中心统一按文件计数;旧任务数文案不再是页面统计口径。
expect(wrapper.text()).toContain('异常 · 0 个文件');
expect(wrapper.text()).toContain('处理中 · 0 个文件');
// 状态组与对话流一致,未展开附件时仍按后端 file_count 统计。
expect(wrapper.text()).toContain('异常 · 2 个文件');
expect(wrapper.text()).toContain('处理中 · 1 个文件');
expect(wrapper.text()).toContain('刚刚创建');
// 处理记录默认折叠;标题 count = completed + history 返回条数。
// 处理记录默认折叠;标题按文件数而非 EML / 任务行数统计。
const historyGroup = wrapper.find('[data-testid="shipping-processing-group-history"]');
expect(historyGroup.exists()).toBe(true);
expect(historyGroup.text()).toContain('处理记录 · 3');
expect(historyGroup.text()).toContain('处理记录 · 3 个文件');
expect(wrapper.find('[data-testid="shipping-processing-history-body"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-processing-task-OT-DONE"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-processing-task-OT-HIST"]').exists()).toBe(false);
@@ -464,7 +594,7 @@ describe('ShippingConversationProcessingCard', () => {
const doneCard = wrapper.find('[data-testid="shipping-processing-task-OT-DONE"]');
expect(doneCard.find('[data-testid="sidebar-progress-inline"]').exists()).toBe(false);
expect(doneCard.find('[data-testid="shipping-processing-task-actions"]').exists()).toBe(false);
expect(doneCard.find('[data-testid="shipping-processing-action-view_result"]').exists()).toBe(true);
expect(doneCard.find('[data-testid="shipping-processing-action-view_result"]').exists()).toBe(false);
expect(doneCard.find('[data-testid="shipping-processing-action-cancel_task"]').exists()).toBe(false);
});
@@ -490,11 +620,11 @@ describe('ShippingConversationProcessingCard', () => {
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.text()).toContain('订单识别任务');
expect(wrapper.text()).toContain('本次订单文件处理');
expect(wrapper.text()).toContain('2 个 PDF');
expect(wrapper.text()).toContain('主文件:4518838152.pdf');
const titleEl = wrapper.find('[data-testid="shipping-processing-task-OT-MULTI"] .text-sm.font-semibold');
expect(titleEl.text()).toContain('订单识别任务');
expect(titleEl.text()).toContain('本次订单文件处理');
expect(titleEl.text()).not.toContain('4518838152.pdf');
// UI-02:有文件对象时不双开「查看详情」与「展开文件详情」。
@@ -554,14 +684,14 @@ describe('ShippingConversationProcessingCard', () => {
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.text()).toContain('订单识别任务');
expect(wrapper.text()).toContain('本次订单文件处理');
expect(wrapper.text()).toContain('2 个 PDF');
const titleEl = wrapper.find('[data-testid="shipping-processing-task-OT-MULTI"] .text-sm.font-semibold');
expect(titleEl.text()).toContain('订单识别任务');
expect(titleEl.text()).toContain('本次订单文件处理');
expect(titleEl.text()).not.toContain('4518838152.pdf');
});
it('uses unified order recognition title instead of internal OT number', async () => {
it('uses unified order file processing title instead of internal OT number', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: projectionWithGroups(
@@ -580,7 +710,7 @@ describe('ShippingConversationProcessingCard', () => {
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.text()).toContain('订单识别任务');
expect(wrapper.text()).toContain('本次订单文件处理');
expect(wrapper.text()).not.toContain('20260803-A13F95D2');
});
@@ -597,7 +727,7 @@ describe('ShippingConversationProcessingCard', () => {
expect(wrapper.emitted('expandFiles')).toBeUndefined();
});
it('opens local task details without emitting a viewed write event', async () => {
it('does not show a view-result action for completed records', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: {
@@ -620,15 +750,87 @@ describe('ShippingConversationProcessingCard', () => {
await wrapper.find('[data-testid="shipping-processing-history-toggle"]').trigger('click');
await wrapper.find('[data-testid="shipping-processing-action-view_result"]').trigger('click');
expect(wrapper.emitted('taskAction')?.[0]?.[0]).toMatchObject({
task: { user_task_no: 'OT-DETAIL' },
action: 'view_result',
});
expect(wrapper.find('[data-testid="shipping-processing-action-view_result"]').exists()).toBe(false);
expect(wrapper.emitted('taskAction')).toBeUndefined();
expect(wrapper.emitted('viewed')).toBeUndefined();
});
it('marks an unrecognized Excel attachment as ignored but keeps a pending PDF recognizable', async () => {
const projection = buildProjection();
setStatusGroup(projection, 'processing', [{
user_task_no: 'INTAKE:EML-EXCEL', group: 'processing', status_label: 'extracting',
title: 'mail.eml', file_count: 2, run_no: 'RUN-EML-EXCEL', can_append: false,
aggregateChildren: [],
}]);
const pendingPdf = buildWorkItem('PLAN:EML-EXCEL:pending', {
workItemType: 'order_intake', sourceType: 'eml', rootOrderTaskNo: null,
sourceSummary: { emailSubject: null, filename: 'pending.pdf', documentId: null, documentCount: 0, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null },
facts: { recognized: false, planState: 'selected_pending' }, uiState: undefined,
});
const ignoredExcel = buildWorkItem('PLAN:EML-EXCEL:report', {
workItemType: 'order_intake', sourceType: 'eml', rootOrderTaskNo: null,
sourceSummary: { emailSubject: null, filename: 'report.xlsx', documentId: null, documentCount: 0, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null },
facts: { recognized: false, planState: 'selected_pending' }, uiState: undefined,
});
const root = buildWorkItem('INTAKE:EML-EXCEL', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-EXCEL',
aggregateChildren: [pendingPdf, ignoredExcel],
});
projection.status_groups!.processing![0]!.aggregateChildren = [pendingPdf, ignoredExcel];
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [root], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
const processingGroup = wrapper.get('[data-testid="shipping-processing-group-processing"]');
expect(processingGroup.text()).toContain('pending.pdf');
expect(processingGroup.text()).not.toContain('report.xlsx');
expect(wrapper.get('[data-testid="shipping-processing-file-INTAKE:EML-EXCEL-live-PLAN:EML-EXCEL:pending"]').text()).toContain('待识别');
const ignoredGroup = wrapper.get('[data-testid="shipping-processing-group-ignored"]');
expect(ignoredGroup.text()).toContain('已忽略 · 1 个文件');
expect(wrapper.find('[data-testid="shipping-processing-ignored-body"]').exists()).toBe(false);
await ignoredGroup.get('[data-testid="shipping-processing-ignored-toggle"]').trigger('click');
const excelRow = ignoredGroup.get('[data-testid="shipping-processing-file-INTAKE:EML-EXCEL-live-PLAN:EML-EXCEL:report"]');
expect(excelRow.text()).toContain('已忽略');
expect(excelRow.text()).not.toContain('待识别');
});
it('keeps an ignored Excel row when its EML parent originates from completed', async () => {
const ignoredExcel = buildWorkItem('PLAN:EML-COMPLETED:report', {
workItemType: 'order_intake', sourceType: 'eml', rootOrderTaskNo: null,
sourceSummary: { emailSubject: null, filename: 'report.xlsx', documentId: null, documentCount: 0, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null },
facts: { recognized: false, planState: 'selected_pending' }, uiState: undefined,
});
const root = buildWorkItem('INTAKE:EML-COMPLETED', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-COMPLETED',
aggregateChildren: [ignoredExcel],
});
const projection = projectionWithGroups(
{ total_tasks: 1, processing: 0, needs_action: 0, completed: 1, history: 0 },
{
failed: [], waiting_human: [], processing: [],
completed: [{
user_task_no: 'INTAKE:EML-COMPLETED', group: 'completed', status_label: 'completed',
title: 'mail.eml', file_count: 1, run_no: 'RUN-EML-COMPLETED', can_append: false,
aggregateChildren: [ignoredExcel],
}],
cancelled: [], archived: [],
},
);
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [root], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
const ignoredGroup = wrapper.get('[data-testid="shipping-processing-group-ignored"]');
expect(ignoredGroup.text()).toContain('已忽略 · 1 个文件');
expect(wrapper.find('[data-testid="shipping-processing-ignored-body"]').exists()).toBe(false);
await ignoredGroup.get('[data-testid="shipping-processing-ignored-toggle"]').trigger('click');
expect(ignoredGroup.get('[data-testid="shipping-processing-file-INTAKE:EML-COMPLETED-live-PLAN:EML-COMPLETED:report"]').text()).toContain('report.xlsx');
});
it('applies visible focus ring on needs_action card when focused', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
@@ -800,7 +1002,7 @@ describe('ShippingConversationProcessingCard', () => {
expect(wrapper.findAll('[data-testid="sidebar-progress-inline"]')).toHaveLength(2);
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]').text()).toContain('待人工处理');
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]').text()).toContain('库存匹配');
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]').text()).toContain('通知准备');
expect(wrapper.findAll('[data-testid="shipping-processing-task-actions"]')).toHaveLength(0);
const task = wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]');
expect(task.find('[data-testid="unified-action-primary"]').exists()).toBe(true);
@@ -4,7 +4,7 @@
* 依赖:vue-i18n、ConversationProcessingProjection、conversationProcessingState、
* conversationProcessingDisplay、actionPresentation、shippingProcessingLabels、SidebarProgressInline。
* 逻辑:由 ShippingWorkflowTimeline 嵌入;只消费统一 projection / workItems;
* 统一「订单识别任务」+ 主文件副标题;处理记录默认折叠(已完成/历史版本/已取消);
* 统一「本次订单文件处理」+ 主文件副标题;处理记录默认折叠(已完成/历史版本/已取消);
* UI-02:有文件对象时次要入口仅为「展开文件详情」,无文件对象时才「查看详情」;
* 有 workItem 时由其统一 Gate / Action 投影常驻渲染人工恢复按钮;
* 点击/展开任务只更新本地焦点与详情,不写服务端 viewed/focus 审计,不得改变同一 Gate 的按钮可见性;
@@ -42,6 +42,12 @@ import {
} from '@/features/shipping-progress/actionPresentation';
import SidebarProgressInline from '@/features/shipping-progress/components/SidebarProgressInline.vue';
import type { ActionPresentation, ActionPresentationItem } from '@/features/shipping-progress/types';
// [统一阶段口径] 5 段业务标签映射唯一来自共享模块(后端 LIFECYCLE_STAGE_BY_PROCESSING_STAGE 镜像)。
import {
LIFECYCLE_STAGE_CODES,
LIFECYCLE_STAGE_LABEL_KEYS,
type LifecycleStageCode,
} from '@/features/shipping-progress/stageMapping';
const props = defineProps<{
projection: ConversationProcessingProjection | null;
@@ -85,6 +91,8 @@ const { t, te } = useI18n();
const uiState = createConversationProcessingUiState();
/** 处理记录整组默认折叠。 */
const historySectionExpanded = ref(false);
/** 已忽略附件默认折叠,避免干扰仍需处理的订单文件。 */
const ignoredSectionExpanded = ref(false);
/** 批次中心文件叶子行;EML 仅是聚合容器,文件状态、原因与动作必须取叶子自身投影。 */
type WorkbenchFileRow = {
@@ -97,16 +105,9 @@ type WorkbenchFileRow = {
po_number?: string | null;
projection?: ShippingProcessingProjection;
};
const LIFECYCLE_STAGE_CODES = ['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'] as const;
type LifecycleStageCode = typeof LIFECYCLE_STAGE_CODES[number];
const LIFECYCLE_STAGE_LABEL_KEYS: Record<string, string> = {
intake_parse: 'intakeParse',
order_review: 'orderReview',
fulfillment_prep: 'fulfillmentPrep',
freight_upload: 'freightUpload',
upload_complete: 'uploadComplete',
};
/** 批次分区状态来自后端 PDF 叶子事实,EML 父卡不可反向决定文件归属。 */
type WorkbenchFileGroup = 'failed' | 'waiting_human' | 'processing' | 'completed' | 'cancelled' | 'archived' | 'ignored';
/** 唯一进度源:统一 conversation_processing / work_items 合成投影。 */
const activeProjection = computed((): ConversationProcessingProjection | null => (
props.projection || null
@@ -117,22 +118,59 @@ const hasContent = computed(() => Boolean(
));
const statusGroups = computed(() => activeProjection.value?.status_groups || null);
const completedTasks = computed(() => statusGroups.value?.completed || []);
const historyTasks = computed(() => [
...(statusGroups.value?.cancelled || []),
...(statusGroups.value?.archived || []),
]);
/** EML 卡的状态分区必须完全遵循后端 status_groups,禁止旧四组回退重判。 */
const failedTasks = computed(() => statusGroups.value?.failed || []);
const waitingHumanTasks = computed(() => statusGroups.value?.waiting_human || []);
const processingTasks = computed(() => statusGroups.value?.processing || []);
function partitionIgnoredTasks(
tasks: ConversationProcessingUserTask[],
includeIgnored: boolean,
): ConversationProcessingUserTask[] {
return tasks.flatMap((task) => {
const children = task.aggregateChildren || [];
if (!children.length) {
const projection = projectionForTask(task);
return Boolean(projection && isIgnoredNonOrderAttachment(projection)) === includeIgnored ? [task] : [];
}
const selectedChildren = children.filter((child) => isIgnoredNonOrderAttachment(child) === includeIgnored);
if (!selectedChildren.length) return [];
return [{
...task,
// 已忽略是前端只读视觉分区;必须同步父任务标识,供工作台叶子过滤按同一分区保留 Excel。
// ignored is a presentation-only bucket; keep the domain task group type intact.
group: task.group,
userGroup: task.userGroup,
file_count: selectedChildren.length,
aggregateChildren: selectedChildren,
aggregateSummary: task.aggregateSummary
? { ...task.aggregateSummary, inGroup: selectedChildren.length }
: task.aggregateSummary,
}];
});
}
const processingTasks = computed(() => partitionIgnoredTasks(statusGroups.value?.processing || [], false));
const completedTasks = computed(() => partitionIgnoredTasks(statusGroups.value?.completed || [], false));
const historyTasks = computed(() => partitionIgnoredTasks([
...(statusGroups.value?.cancelled || []),
...(statusGroups.value?.archived || []),
], false));
const ignoredTasks = computed(() => partitionIgnoredTasks([
...(statusGroups.value?.failed || []),
...(statusGroups.value?.waiting_human || []),
...(statusGroups.value?.processing || []),
...(statusGroups.value?.completed || []),
...(statusGroups.value?.cancelled || []),
...(statusGroups.value?.archived || []),
], true));
/** 任务只要含一个命中附件即保留,避免筛选后打散同一封 EML 的上下文。 */
function taskMatchesLifecycleFilter(task: ConversationProcessingUserTask): boolean {
const filter = props.lifecycleFilter || 'all';
const query = String(props.fileSearchQuery || '').trim().toLowerCase();
// 非批次中心保留历史任务卡兼容展示;只有批次中心才按叶子文件筛选。
if (!props.workbenchMode && filter === 'all' && !query) return true;
// 未筛选时优先信任 status_groups;若实时 work_items 尚未同步,允许其显式叶子快照
// 兜底,但历史 document_names 不能伪造成可操作文件行。
if (filter === 'all' && !query) {
return !props.workbenchMode || Boolean(task.aggregateChildren?.length || workbenchFileRows(task).length);
}
return workbenchFileRows(task).some((file) => {
if (filter !== 'all' && String(file.projection?.uiState?.lifecycleStage || '') !== filter) return false;
return !query || [file.filename, file.label, file.po_number]
@@ -142,6 +180,7 @@ function taskMatchesLifecycleFilter(task: ConversationProcessingUserTask): boole
const visibleFailedTasks = computed(() => failedTasks.value.filter(taskMatchesLifecycleFilter));
const visibleWaitingHumanTasks = computed(() => waitingHumanTasks.value.filter(taskMatchesLifecycleFilter));
const visibleProcessingTasks = computed(() => processingTasks.value.filter(taskMatchesLifecycleFilter));
const visibleIgnoredTasks = computed(() => ignoredTasks.value.filter(taskMatchesLifecycleFilter));
const visibleCompletedTasks = computed(() => completedTasks.value.filter(taskMatchesLifecycleFilter));
/** history 中非取消 →「历史版本」。 */
@@ -156,10 +195,11 @@ const cancelledHistoryTasks = computed(() => historyTasks.value.filter(
const visibleHistoryVersionTasks = computed(() => historyVersionTasks.value.filter(taskMatchesLifecycleFilter));
const visibleCancelledHistoryTasks = computed(() => cancelledHistoryTasks.value.filter(taskMatchesLifecycleFilter));
/** 处理记录标题计数:当前返回的 completed + history。 */
const recordTaskCount = computed(() => (
completedTasks.value.length + historyTasks.value.length
));
/** 处理记录标题按 PDF 文件数统计,与对话流状态分区和批次总览保持同一口径。 */
const recordFileCount = computed(() => groupFileCount([
...completedTasks.value,
...historyTasks.value,
]));
/**
* history 未返回条数:summary.history - 当前 history[];不可靠时为 0(不猜数)。
@@ -195,6 +235,7 @@ watch(
if (next === prev) return;
resetConversationProcessingUiState(uiState);
historySectionExpanded.value = false;
ignoredSectionExpanded.value = false;
},
);
@@ -292,12 +333,22 @@ function groupTitle(task: ConversationProcessingUserTask): string {
return task.title || taskLabel(task);
}
/** 工作台文件行:只展示后端 document objects,避免用任务标题冒充文件。 */
/** 状态区内的 EML 标题显示局部/总附件数,明确同一邮件跨区是展示分组而非重复处理。 */
function workbenchGroupTitle(task: ConversationProcessingUserTask): string {
const title = groupTitle(task);
const summary = task.aggregateSummary;
const total = Number(summary?.total || 0);
const inGroup = Number(summary?.inGroup ?? (summary as typeof summary & { in_group?: number } | null)?.in_group ?? 0);
return total > 0 && inGroup > 0 && inGroup < total
? `${title} · ${t('chat.shippingProcessing.batchWorkbench.inGroupCount', { inGroup, total })}`
: title;
}
/** 工作台文件行:展示实时正式文件与后端明确标记的未识别诊断附件,避免用任务标题冒充文件。 */
function workbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileRow[] {
const children = task.aggregateChildren || [];
// [AUTHORITY] 批次模式只以实时 work_items 作为文件行真相。Conversation task 的
// children / objects / document_names 是 Run 级兼容快照,可用于非批次卡历史展示,
// 但不得重建批次中的文件名、状态、阶段或操作。
// [AUTHORITY] 批次模式优先以实时 work_items 作为文件行真相。若其尚未同步,才使用
// 同次响应 status_groups 已裁决的 aggregate_children 只读兜底,避免概览有数而状态区空白。
if (props.workbenchMode) {
const taskNo = String(task.user_task_no || '').trim();
const liveLeaves = (props.workItems || []).flatMap((item) => {
@@ -311,15 +362,37 @@ function workbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileR
: [item];
}).filter((item) => (
Number(item.sourceSummary?.documentId || 0) > 0
// 已选但未物化的附件没有 documentId;后端显式标记后才允许作为只读诊断行展示。
|| item.facts?.recognized === false
));
const seenLiveDocumentIds = new Set<number>();
const seenLiveLeafKeys = new Set<string>();
const uniqueLiveLeaves = liveLeaves.filter((item) => {
const documentId = Number(item.sourceSummary?.documentId || 0);
if (seenLiveDocumentIds.has(documentId)) return false;
seenLiveDocumentIds.add(documentId);
const key = documentId > 0
? `document:${documentId}`
: `pending:${String(item.workItemNo || item.sourceSummary?.filename || '').trim()}`;
if (!key || seenLiveLeafKeys.has(key)) return false;
seenLiveLeafKeys.add(key);
return true;
});
return uniqueLiveLeaves.map((item, index) => {
const groupedLeafKeys = new Set((task.aggregateChildren || []).map((child) => {
const documentId = Number(child.sourceSummary?.documentId || 0);
return documentId > 0
? `document:${documentId}`
: `pending:${String(child.workItemNo || child.sourceSummary?.filename || '').trim()}`;
}).filter(Boolean));
const groupedLiveLeaves = uniqueLiveLeaves.filter((item) => {
if (!groupedLeafKeys.size) return true;
const documentId = Number(item.sourceSummary?.documentId || 0);
const key = documentId > 0
? `document:${documentId}`
: `pending:${String(item.workItemNo || item.sourceSummary?.filename || '').trim()}`;
return groupedLeafKeys.has(key);
});
const displayLeaves = groupedLiveLeaves.length
? groupedLiveLeaves
: flattenBusinessFileProjections(children);
return displayLeaves.map((item, index) => {
const documentId = Number(item.sourceSummary?.documentId || 0);
const filename = String(item.sourceSummary?.filename || '').trim();
return {
@@ -406,12 +479,31 @@ function workbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileR
}));
}
/** 将后端叶子状态映射为批次分区;未知状态不进入任何状态区,避免误报完成。 */
function workbenchFileGroup(file: WorkbenchFileRow): WorkbenchFileGroup | null {
if (isIgnoredNonOrderAttachment(file.projection)) return 'ignored';
const status = String(file.projection?.uiState?.status || file.projection?.userStatus || file.projection?.status || file.status_label || '')
.trim().toLowerCase();
if (status === 'retryable' || status === 'failed') return 'failed';
if (status === 'waiting_human') return 'waiting_human';
if (status === 'running' || status === 'processing') return 'processing';
if (status === 'completed') return 'completed';
if (status === 'cancelled') return 'cancelled';
if (status === 'archived') return 'archived';
return null;
}
/** 阶段筛选只收窄附件行,EML 卡本身仍保留以便用户识别邮件来源。 */
function visibleWorkbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileRow[] {
const filter = props.lifecycleFilter || 'all';
const rows = workbenchFileRows(task);
const query = String(props.fileSearchQuery || '').trim().toLowerCase();
const taskGroup = String(task.userGroup || task.group || '').trim().toLowerCase();
const hasBackendLeafPartition = (task.aggregateChildren || []).length > 0;
return rows.filter((file) => {
// 新投影已由后端下发本分区的叶子白名单;旧夹具/旧响应没有该白名单时保留
// 原兼容展示,避免前端凭不完整字段重判并把文件错误隐藏。
if (props.workbenchMode && hasBackendLeafPartition && workbenchFileGroup(file) !== taskGroup) return false;
if (filter !== 'all' && String(file.projection?.uiState?.lifecycleStage || '') !== filter) return false;
if (!query) return true;
return [file.filename, file.label, file.po_number].some((value) => String(value || '').toLowerCase().includes(query));
@@ -426,8 +518,27 @@ function isDownloadSelected(taskNo: string): boolean {
return (props.selectedDownloadTaskNos || []).includes(taskNo);
}
/** 状态组标题按文件计数,与批次总览保持同一口径。 */
/** 单个状态任务的文件数与对话流一致:优先数后端已裁决的叶子,否则回退 file_count。 */
function taskStatusFileCount(task: ConversationProcessingUserTask): number {
const children = (task.aggregateChildren || []).filter((child) => !String(
child.sourceSummary?.filename || '',
).trim().toLowerCase().endsWith('.eml'));
if (children.length) {
const ids = new Set(children.map((child) => String(
child.sourceSummary?.documentId || child.workItemNo || '',
).trim()).filter(Boolean));
return ids.size || children.length;
}
return Math.max(0, Number(task.file_count || 0));
}
/** 状态组标题按文件计数,与对话流和批次总览保持同一口径。 */
function groupFileCount(tasks: ConversationProcessingUserTask[]): number {
const filter = props.lifecycleFilter || 'all';
const query = String(props.fileSearchQuery || '').trim();
if (filter === 'all' && !query) {
return tasks.reduce((total, task) => total + taskStatusFileCount(task), 0);
}
const seen = new Set<string>();
return tasks.reduce((total, task) => total + visibleWorkbenchFileRows(task).reduce((count, file) => {
const filename = String(file.filename || file.label || '').trim().toLowerCase();
@@ -441,12 +552,42 @@ function groupFileCount(tasks: ConversationProcessingUserTask[]): number {
}
function workbenchFileStatus(file: WorkbenchFileRow, task: ConversationProcessingUserTask): string {
if (isIgnoredNonOrderAttachment(file.projection)) {
return t('chat.shippingProcessing.ignoredNonOrderAttachment');
}
if (file.projection?.facts?.recognized === false) {
return t('chat.shippingProcessing.notRecognized');
}
const status = file.projection
? (file.projection.uiState?.status || file.projection.userStatus || file.projection.status)
: (file.status_label || task.status_label || '');
return resolveShippingProcessingStatusLabel(String(status), te, t);
}
/**
* 忽略分区文件行:不走 status 组与 taskGroup 对齐过滤(ignored 是展示桶,
* 父任务仍保留 domain group=processing/completed)。
*/
function ignoredWorkbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileRow[] {
const filter = props.lifecycleFilter || 'all';
const query = String(props.fileSearchQuery || '').trim().toLowerCase();
return workbenchFileRows(task)
.filter((file) => isIgnoredNonOrderAttachment(file.projection))
.filter((file) => {
if (filter !== 'all' && String(file.projection?.uiState?.lifecycleStage || '') !== filter) return false;
if (!query) return true;
return [file.filename, file.label, file.po_number]
.some((value) => String(value || '').toLowerCase().includes(query));
});
}
/** Excel 附件不进入订单 PDF 识别;仅作为只读诊断行展示。 */
function isIgnoredNonOrderAttachment(item?: ShippingProcessingProjection): boolean {
if (item?.facts?.recognized !== false) return false;
const filename = String(item.sourceSummary?.filename || '').trim().toLowerCase();
return filename.endsWith('.xls') || filename.endsWith('.xlsx');
}
function workbenchFileReason(file: WorkbenchFileRow, task: ConversationProcessingUserTask): string {
if (file.projection) {
const reason = file.projection.uiState
@@ -683,6 +824,7 @@ function shouldShowTaskLevelActions(task: ConversationProcessingUserTask): boole
*/
function recordViewDetailsItem(task: ConversationProcessingUserTask): ActionPresentationItem | null {
if (String(task.status_label || '').trim().toLowerCase() === 'cancelled') return null;
if (String(task.group || '').trim().toLowerCase() === 'completed') return null;
const presentation = taskActionPresentation(task);
const candidates = [
presentation.primary,
@@ -692,9 +834,7 @@ function recordViewDetailsItem(task: ConversationProcessingUserTask): ActionPres
return candidates.find((item) => {
const code = String(item.actionCode || '').trim().toLowerCase();
return code === 'view_details' || code === 'view_result';
}) || (String(task.group || '') === 'completed'
? { intent: 'view_result', actionCode: 'view_result', labelKey: 'chat.shippingProcessing.action.view_result' }
: null);
}) || null;
}
/**
@@ -759,6 +899,14 @@ function toggleHistorySection() {
historySectionExpanded.value = !historySectionExpanded.value;
}
/**
* 切换只读已忽略附件分区。
* 核心逻辑:已忽略附件不参与订单处理,默认收起;用户需要核对时才展开明细。
*/
function toggleIgnoredSection() {
ignoredSectionExpanded.value = !ignoredSectionExpanded.value;
}
/**
* Intake 阶段文案。
*/
@@ -770,7 +918,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
<template>
<div
v-if="hasContent"
class="space-y-3"
class="flex flex-col gap-3"
data-testid="shipping-conversation-processing-card"
>
<section
@@ -800,7 +948,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
@click="onSelectTask(task)"
>
<div class="text-sm font-semibold text-primary">
{{ workbenchMode ? groupTitle(task) : resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
{{ workbenchMode ? workbenchGroupTitle(task) : resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
</div>
<div v-if="!workbenchMode" class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
@@ -904,7 +1052,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
:data-focused="focusedTaskNo === task.user_task_no ? '1' : '0'"
>
<button type="button" class="w-full text-left" @click="onSelectTask(task)">
<div class="text-sm font-semibold text-primary">{{ workbenchMode ? groupTitle(task) : resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}</div>
<div class="text-sm font-semibold text-primary">{{ workbenchMode ? workbenchGroupTitle(task) : resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}</div>
<div v-if="!workbenchMode" class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
</div>
@@ -963,7 +1111,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
@click="onSelectTask(task)"
>
<div class="text-sm font-semibold text-primary">
{{ workbenchMode ? groupTitle(task) : resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
{{ workbenchMode ? workbenchGroupTitle(task) : resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
</div>
<div v-if="!workbenchMode" class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
@@ -1077,19 +1225,62 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</section>
<section
v-if="recordTaskCount > 0"
v-if="visibleIgnoredTasks.length"
class="order-last"
data-testid="shipping-processing-group-ignored"
>
<button
type="button"
class="mb-1.5 flex w-full items-center gap-1 text-left text-[11px] font-semibold uppercase tracking-wide text-muted"
data-testid="shipping-processing-ignored-toggle"
@click="toggleIgnoredSection"
>
<ChevronDown v-if="ignoredSectionExpanded" class="h-3 w-3 shrink-0" />
<ChevronRight v-else class="h-3 w-3 shrink-0" />
<span>{{ t('chat.shippingProcessing.groupIgnored', { count: groupFileCount(visibleIgnoredTasks) }) }}</span>
</button>
<div v-if="ignoredSectionExpanded" class="space-y-2" data-testid="shipping-processing-ignored-body">
<article
v-for="task in visibleIgnoredTasks"
:key="task.user_task_no"
class="rounded-lg border border-default bg-surface-soft px-2.5 py-2 dark:bg-slate-900/50"
:data-testid="`shipping-processing-task-ignored-${task.user_task_no}`"
>
<div class="text-sm font-semibold text-primary">
{{ workbenchMode ? workbenchGroupTitle(task) : resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
</div>
<div class="mt-2 space-y-1 border-t border-default pt-2">
<div
v-for="file in ignoredWorkbenchFileRows(task)"
:key="file.object_key"
class="flex items-start justify-between gap-3 rounded-md bg-white/70 px-2 py-1.5 text-[11px] dark:bg-slate-950/30"
:data-testid="`shipping-processing-file-${file.object_key}`"
>
<div class="min-w-0">
<div class="truncate font-medium text-primary">{{ file.filename || file.label }}</div>
<div class="text-secondary">{{ t('chat.shippingProcessing.ignoredNonOrderAttachmentHint') }}</div>
</div>
<span class="shrink-0 rounded-full bg-surface-strong px-2 py-0.5 font-medium text-secondary">{{ workbenchFileStatus(file, task) }}</span>
</div>
</div>
</article>
</div>
</section>
<section
v-if="recordFileCount > 0"
data-testid="shipping-processing-group-history"
>
<button
type="button"
class="mb-1.5 flex w-full items-center justify-between gap-2 text-left text-[11px] font-semibold uppercase tracking-wide text-slate-600 dark:text-slate-300"
class="mb-1.5 flex w-full items-center justify-between gap-2 text-left text-[11px] font-semibold uppercase tracking-wide text-secondary"
data-testid="shipping-processing-history-toggle"
@click="toggleHistorySection"
>
<span class="inline-flex min-w-0 items-center gap-1">
<ChevronDown v-if="historySectionExpanded" class="h-3 w-3 shrink-0" />
<ChevronRight v-else class="h-3 w-3 shrink-0" />
<span>{{ resolveShippingProcessingMessage('groupProcessingRecords', te, t, { count: recordTaskCount }) }}</span>
<span>{{ resolveShippingProcessingMessage('groupProcessingRecords', te, t, { count: recordFileCount }) }}</span>
</span>
<span
v-if="hiddenHistoryCount > 0"
@@ -1119,9 +1310,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
:data-testid="`shipping-processing-task-${task.user_task_no}`"
data-record="1"
>
<div class="text-sm font-semibold text-primary">
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
</div>
<div class="text-sm font-semibold text-primary">{{ workbenchMode ? workbenchGroupTitle(task) : resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}</div>
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
<span>{{ statusLabel(task) }}</span>
@@ -1162,7 +1351,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
v-if="visibleHistoryVersionTasks.length"
data-testid="shipping-processing-history-versions"
>
<div class="mb-1 text-[11px] font-medium text-slate-600 dark:text-slate-300">
<div class="mb-1 text-[11px] font-medium text-secondary">
{{ resolveShippingProcessingMessage('groupRecordHistoryVersions', te, t) }}
</div>
<div class="space-y-2">
@@ -1204,7 +1393,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
v-if="visibleCancelledHistoryTasks.length"
data-testid="shipping-processing-history-cancelled"
>
<div class="mb-1 text-[11px] font-medium text-slate-500 dark:text-slate-400">
<div class="mb-1 text-[11px] font-medium text-muted">
{{ resolveShippingProcessingMessage('groupRecordCancelled', te, t) }}
</div>
<div class="space-y-2">
@@ -42,7 +42,7 @@ const statusTone = computed(() => {
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';
return 'border-default bg-slate-50/70 text-primary dark:bg-slate-900/40 ';
}
});
@@ -183,7 +183,7 @@ describe('ShippingOrderExtractionCard', () => {
// 旧快照缺少会话级用户状态;candidate_ready 只能作为附件阶段,不能升格为顶层分组。
expect(wrapper.text()).toContain('共 3 个文件');
expect(wrapper.text()).toContain('0/3 已处理');
expect(wrapper.text()).not.toContain('已处理');
expect(wrapper.text()).not.toContain('已生成候选 3 个文件');
expect(wrapper.text()).toContain('4210020274.pdf');
expect(wrapper.text()).not.toContain('23/20 已处理');
@@ -300,12 +300,52 @@ describe('ShippingOrderExtractionCard', () => {
await wrapper.get('[data-testid="shipping-order-extraction-eml-failed-INTAKE:SNI-DETAIL"] button').trigger('click');
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-children"]').text()).toContain('failed.pdf');
expect(wrapper.text()).toContain('异常 1');
expect(wrapper.text()).toContain('当前步骤需要人工处理');
// 通用兜底原因(当前步骤需要人工处理)与右侧状态芯片语义重复,统一隐藏。
expect(wrapper.text()).not.toContain('当前步骤需要人工处理');
expect(wrapper.text()).not.toContain('PARSE_FAILED');
expect(wrapper.get('[data-testid="shipping-order-extraction-child-status-OT-CHILD-1"]')
.classes()).toContain('text-rose-600');
});
it('splits a mixed-status EML into its matching status sections', async () => {
const completedA = {
workItemNo: 'DOCUMENT:4210022658', sourceSummary: { filename: '4210022658.pdf', documentId: 2658 },
userStatus: 'completed', status: 'completed', uiState: { status: 'completed', stage: 'completed' },
} as any;
const completedB = {
workItemNo: 'DOCUMENT:4210022657', sourceSummary: { filename: '4210022657.pdf', documentId: 2657 },
userStatus: 'completed', status: 'completed', uiState: { status: 'completed', stage: 'completed' },
} as any;
const processing = {
workItemNo: 'DOCUMENT:4210022656', sourceSummary: { filename: '4210022656.pdf', documentId: 2656 },
userStatus: 'running', status: 'processing', uiState: { status: 'processing', stage: 'freight_upload' },
} as any;
// 模拟热更新前/兼容后端仍把三份 PDF 放在 completed EML 根行的真实输入。
const mixedTask = {
user_task_no: 'INTAKE:SNI-HOXIN', title: 'NEW PO HOXIN.eml', file_count: 3,
userGroup: 'completed', group: 'completed',
aggregateChildren: [completedA, completedB, processing],
aggregateSummary: { intakeNo: 'SNI-HOXIN', total: 3, completed: 2, processing: 1, needsAction: 0, failed: 0, stages: [], reasonCodes: [] },
} as any;
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState() },
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref({ status_groups: { failed: [], waiting_human: [], processing: [], completed: [mixedTask], cancelled: [], archived: [] } }),
processingWorkItems: ref([]),
} } },
});
const completedSection = wrapper.findAll('[data-testid="shipping-order-extraction-status-groups"] section')
.find((section) => section.text().includes('已完成'))!;
await completedSection.get('button').trigger('click');
await wrapper.get('[data-testid="shipping-order-extraction-eml-completed-INTAKE:SNI-HOXIN"] button').trigger('click');
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-completed-INTAKE:SNI-HOXIN"]').text()).toContain('2 个文件');
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-completed-INTAKE:SNI-HOXIN"]').text()).toContain('4210022658.pdf');
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-completed-INTAKE:SNI-HOXIN"]').text()).not.toContain('4210022656.pdf');
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-processing-INTAKE:SNI-HOXIN"]').text()).toContain('4210022656.pdf');
});
it('does not supplement an authoritative EML group from a second work-item snapshot', async () => {
const child = {
workItemType: 'order_task', workItemNo: 'OT-FALLBACK-1', sourceType: 'eml', rootOrderTaskNo: 'OT-FALLBACK',
@@ -347,8 +387,8 @@ describe('ShippingOrderExtractionCard', () => {
});
expect(wrapper.text()).toContain('共 2 个文件');
// 关键断言:待人工处理不是完成,聊天摘要必须与批次中心 completed_files 同口径。
expect(wrapper.text()).toContain('0/2 已处理');
// 关键断言:待人工处理不是完成,头部按状态计数显示"待人工",不显示完成的"已处理"。
expect(wrapper.text()).toContain('待人工 2');
expect(wrapper.text()).not.toContain('共 6 个文件');
expect(wrapper.text()).not.toContain('stale.pdf');
});
@@ -407,7 +447,7 @@ describe('ShippingOrderExtractionCard', () => {
// 关键断言:有权威会话投影时,只能显示附件总数,禁止回退历史邮件任务数。
expect(wrapper.text()).toContain('共 30 个文件');
expect(wrapper.text()).toContain('0/30 已处理');
expect(wrapper.text()).toContain('待人工 30');
expect(wrapper.text()).not.toContain('共 18 个文件');
});
@@ -419,7 +459,8 @@ describe('ShippingOrderExtractionCard', () => {
props: { state: buildState(), runNo: 'SNER-COUNT' },
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processing: ref({ status_groups: { failed: [], waiting_human: [], processing: [task], completed: [], cancelled: [], archived: [] } }), processingWorkItems: ref([]) } } },
});
expect(wrapper.text()).toContain('2 个文件');
// 状态分组标题必须按两个 PDF 附件计数,不能按一个 EML 容器计为“1 个任务”。
expect(wrapper.get('[data-testid="shipping-order-extraction-status-groups"]').text()).toContain('系统处理中 · 2 个文件');
});
it('renders every projected file when the batch has two documents', () => {
@@ -598,7 +639,7 @@ describe('ShippingOrderExtractionCard', () => {
global: { plugins: [i18n] },
});
// 关键断言:对话卡只保留摘要标题与系统处理中状态。
expect(wrapper.text()).toContain('订单识别任务');
expect(wrapper.text()).toContain('本次订单文件处理');
expect(wrapper.text()).toContain('3 个文件');
expect(wrapper.text()).toContain('系统处理中');
expect(wrapper.text()).toContain('处理时间偏长');
@@ -612,6 +653,21 @@ describe('ShippingOrderExtractionCard', () => {
expect(wrapper.findAll('[data-testid="shipping-order-document-result"]').length).toBe(0);
}, 30_000);
it('keeps file row copy identical when routed through the shared stage key', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
documents: [
{ unitId: 21, documentId: 21, intakeId: 21, documentType: 'attachment', fileName: 'layout.pdf', status: 'processing', userVisibleStage: 'layout_parsing_started' },
],
}),
},
global: { plugins: [i18n] },
});
// 输出不变契约:rowStatusLabel 改走共享 key 出口后,文案仍为 UserStage 短语。
expect(wrapper.text()).toContain('正在解析版面');
}, 30_000);
it('renders duplicate-linked notice when only open_existing results remain', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
@@ -635,7 +691,7 @@ describe('ShippingOrderExtractionCard', () => {
},
global: { plugins: [i18n] },
});
expect(wrapper.text()).toContain('订单识别任务');
expect(wrapper.text()).toContain('本次订单文件处理');
expect(wrapper.text()).toContain('已关联已有任务');
expect(wrapper.text()).not.toContain('需人工处理');
});
@@ -876,4 +932,237 @@ describe('ShippingOrderExtractionCard', () => {
expect(details.exists()).toBe(false);
expect(wrapper.findAll('[data-testid="shipping-order-extraction-primary-action"]').length).toBe(0);
});
it('uses the submitted_files (batch-size) count for the header chip, not the recognized total', () => {
// [回归] 提交基主计数 submitted_files=1 优先于已识别 total_files=3 作为「共 N 个文件」。
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState() },
global: {
plugins: [i18n],
provide: {
[SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref({
ui_state: { status: 'running' },
summary: { total_files: 3, submitted_files: 1 },
status_groups: {
failed: [], waiting_human: [], processing: [
{ user_task_no: 'INTAKE:SNI-BATCH', title: 'batch.eml', file_count: 3,
userGroup: 'processing', group: 'processing', aggregateChildren: [] },
], completed: [], cancelled: [], archived: [],
},
}),
processingWorkItems: ref([]),
},
},
},
});
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
expect(wrapper.text()).toContain('共 1 个文件');
});
it('shows the recognized count inside the file-count chip during the pre-materialization window', () => {
// [回归] 识别进度必须与「共 N 个文件」同一标签展示,不能单独占一行。
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState() },
global: {
plugins: [i18n],
provide: {
[SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref({
ui_state: { status: 'running' },
summary: { total_files: 0, submitted_files: 1 },
status_groups: {
failed: [], waiting_human: [], processing: [], completed: [], cancelled: [], archived: [],
},
}),
processingWorkItems: ref([]),
},
},
},
});
expect(wrapper.get('[data-testid="shipping-order-extraction-recognizing-placeholder"]').text()).toContain('正在识别附件');
expect(wrapper.text()).toContain('共 1 个文件 · 已识别 0/1');
expect(wrapper.find('[data-testid="shipping-order-extraction-recognized-hint"]').exists()).toBe(false);
});
it('renders an unrecognized plan attachment as a distinct pending row inside the EML task', async () => {
// [回归] 批次「已识别 1/2」时 EML 列表须展示全部计划附件(含未识别行),
// 未识别行标记为「待识别」,便于排查「为什么这份没识别」。
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState() },
global: {
plugins: [i18n],
provide: {
[SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref({
ui_state: { status: 'running' },
summary: { total_files: 1, submitted_files: 2 },
status_groups: {
failed: [], waiting_human: [], processing: [{
user_task_no: 'INTAKE:SNI-UNRECOGNIZED', title: 'batch.eml', file_count: 2,
userGroup: 'processing', group: 'processing',
aggregateChildren: [
{
workItemNo: 'DOC-10', sourceType: 'eml', intakeNo: 'SNI-UNRECOGNIZED',
sourceSummary: { filename: 'F91D1.pdf', documentId: 10 },
userStatus: 'waiting_human', userStage: 'order_review', status: 'waiting_human',
},
{
workItemNo: 'PLAN:SNI-UNRECOGNIZED:f92', sourceType: 'eml', intakeNo: 'SNI-UNRECOGNIZED',
sourceSummary: { filename: 'F92.pdf' },
userStatus: 'processing', userStage: 'intake_parse', status: 'processing',
facts: { recognized: false, planState: 'selected_pending' },
},
],
}], completed: [], cancelled: [], archived: [],
},
}),
processingWorkItems: ref([]),
},
},
},
});
await wrapper.get('[data-testid="shipping-order-extraction-eml-processing-INTAKE:SNI-UNRECOGNIZED"] button').trigger('click');
const status = wrapper.find('[data-testid="shipping-order-extraction-child-status-PLAN:SNI-UNRECOGNIZED:f92"]');
expect(status.exists()).toBe(true);
expect(status.text()).toContain('待识别');
expect(wrapper.text()).toContain('F92.pdf');
expect(wrapper.text()).toContain('尚未识别');
});
it('marks unrecognized Excel attachments as ignored instead of pending recognition', async () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState() },
global: {
plugins: [i18n],
provide: {
[SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref({
ui_state: { status: 'running' },
summary: { total_files: 1, submitted_files: 2 },
status_groups: {
failed: [], waiting_human: [], processing: [{
user_task_no: 'INTAKE:SNI-EXCEL', title: 'batch.eml', file_count: 2,
userGroup: 'processing', group: 'processing',
aggregateChildren: [
{
workItemNo: 'DOC-11', sourceType: 'eml', intakeNo: 'SNI-EXCEL',
sourceSummary: { filename: 'order.pdf', documentId: 11 },
userStatus: 'processing', userStage: 'intake_parse', status: 'processing',
},
{
workItemNo: 'PLAN:SNI-EXCEL:report', sourceType: 'eml', intakeNo: 'SNI-EXCEL',
sourceSummary: { filename: 'report.xlsx' },
userStatus: 'processing', userStage: 'intake_parse', status: 'processing',
facts: { recognized: false, planState: 'selected_pending' },
},
],
}], completed: [], cancelled: [], archived: [],
},
}),
processingWorkItems: ref([]),
},
},
},
});
await wrapper.get('[data-testid="shipping-order-extraction-eml-processing-INTAKE:SNI-EXCEL"] button').trigger('click');
const processingCard = wrapper.get('[data-testid="shipping-order-extraction-eml-processing-INTAKE:SNI-EXCEL"]');
expect(processingCard.text()).toContain('order.pdf');
expect(processingCard.text()).not.toContain('report.xlsx');
expect(wrapper.find('[data-testid="shipping-order-extraction-eml-ignored-INTAKE:SNI-EXCEL"]').exists()).toBe(false);
const ignoredSection = wrapper.findAll('[data-testid="shipping-order-extraction-status-groups"] section')
.find((section) => section.text().includes('已忽略'))!;
await ignoredSection.get('button').trigger('click');
const ignoredCard = wrapper.get('[data-testid="shipping-order-extraction-eml-ignored-INTAKE:SNI-EXCEL"]');
const status = ignoredCard.get('[data-testid="shipping-order-extraction-child-status-PLAN:SNI-EXCEL:report"]');
expect(status.text()).toContain('已忽略');
expect(ignoredCard.text()).toContain('非订单 PDF,不参与订单识别');
expect(status.text()).not.toContain('待识别');
});
it('completes the header when only ignored Excel attachments remain', () => {
const completedPdf = {
workItemNo: 'DOC-COMPLETED', sourceType: 'eml', intakeNo: 'SNI-HEADER-COMPLETE',
sourceSummary: { filename: 'order.pdf', documentId: 12 },
userStatus: 'completed', userStage: 'intake_parse', status: 'completed',
};
const ignoredExcel = {
workItemNo: 'PLAN:SNI-HEADER-COMPLETE:excel', sourceType: 'eml', intakeNo: 'SNI-HEADER-COMPLETE',
sourceSummary: { filename: 'PO_INFO.xlsx' },
userStatus: 'processing', userStage: 'intake_parse', status: 'processing',
facts: { recognized: false, planState: 'selected_pending' },
};
const task = (children: unknown[]) => ({
user_task_no: 'INTAKE:SNI-HEADER-COMPLETE', title: 'batch.eml', file_count: 1,
userGroup: 'processing', group: 'processing', aggregateChildren: children,
});
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState() },
global: {
plugins: [i18n],
provide: {
[SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref({
ui_state: { status: 'running', lifecycleStage: 'intake_parse' },
summary: { total_files: 1, submitted_files: 2 },
status_groups: {
failed: [], waiting_human: [], processing: [task([ignoredExcel])],
completed: [task([completedPdf])], cancelled: [], archived: [],
},
}),
processingWorkItems: ref([]),
},
},
},
});
expect(wrapper.text()).toContain('本次订单文件处理');
expect(wrapper.text()).toContain('订单文件 1 个已完成 · 1 个已忽略');
expect(wrapper.text()).toContain('处理完成');
expect(wrapper.text()).not.toContain('系统处理中');
expect(wrapper.text()).not.toContain('当前阶段:');
expect(wrapper.findAll('.animate-spin')).toHaveLength(0);
});
it('keeps the header processing when an unrecognized PDF remains', () => {
const unrecognizedPdf = {
workItemNo: 'PLAN:SNI-HEADER-PENDING:pdf', sourceType: 'eml', intakeNo: 'SNI-HEADER-PENDING',
sourceSummary: { filename: 'PO_INFO.pdf' },
userStatus: 'processing', userStage: 'intake_parse', status: 'processing',
facts: { recognized: false, planState: 'selected_pending' },
};
const ignoredExcel = {
workItemNo: 'PLAN:SNI-HEADER-PENDING:excel', sourceType: 'eml', intakeNo: 'SNI-HEADER-PENDING',
sourceSummary: { filename: 'PO_INFO.xlsx' },
userStatus: 'processing', userStage: 'intake_parse', status: 'processing',
facts: { recognized: false, planState: 'selected_pending' },
};
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState() },
global: {
plugins: [i18n],
provide: {
[SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref({
ui_state: { status: 'running', lifecycleStage: 'intake_parse' },
summary: { total_files: 1, submitted_files: 2 },
status_groups: {
failed: [], waiting_human: [], processing: [{
user_task_no: 'INTAKE:SNI-HEADER-PENDING', title: 'batch.eml', file_count: 1,
userGroup: 'processing', group: 'processing', aggregateChildren: [unrecognizedPdf, ignoredExcel],
}], completed: [], cancelled: [], archived: [],
},
}),
processingWorkItems: ref([]),
},
},
},
});
expect(wrapper.text()).toContain('系统处理中');
expect(wrapper.text()).toContain('共 2 个文件 · 已识别 1/2 · 1 个已忽略');
expect(wrapper.text()).not.toContain('当前阶段:');
expect(wrapper.findAll('.animate-spin')).toHaveLength(1);
});
});
@@ -1,6 +1,6 @@
/**
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
* 用途:聊天主区「订单识别任务」摘要卡——标题、文件数+状态、一行 handling 摘要、唯一主 CTA、查看详情。
* 用途:聊天主区「本次订单文件处理」摘要卡——标题、文件数+状态、一行 handling 摘要、唯一主 CTA、查看详情。
* 依赖:订单抽取 Run 状态卡 DTO、shipping.api 文档/进度接口、ShippingOrderExtractionDetailsDrawer、vue-router、vue-i18n。
* 逻辑:对话区默认展示状态-EML 聚合;批次工作台打开后切换为紧凑摘要,长进度/Gate/刷新取消由工作台承接。
*/
@@ -15,14 +15,17 @@ import type {
ShippingOrderExtractionState,
} from '../../types/chat.types';
import type {
ConversationProcessingUserTask,
ShippingOrderExtractionDocumentResult,
ShippingOrderExtractionProgressEvent,
} from '../../types/shipping.api.types';
import type { ShippingProcessingProjection } from '../../types/shipping.api.types';
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
import { resolveOrderExtractionRunStageKey } from '../../shipping/orderExtractionProgressDisplay';
import {
resolveShippingProcessingReasonLabel,
resolveShippingProcessingStageLabel,
resolveShippingLifecycleStageLabel,
isGenericBlockingReason,
} from '../../shipping/shippingProcessingLabels';
import {
listWorkspaceShippingOrderExtractionDocuments,
@@ -70,7 +73,7 @@ const conversationProjectionLoading = computed(() => Boolean(
) || (hasAuthoritativeConversationProvider.value && !conversationProcessing.value));
const conversationStatusGroups = computed<ConversationStatusGroups | null>(() => conversationProcessing.value?.status_groups || null);
const hasConversationStatusGroups = computed(() => Boolean(conversationStatusGroups.value));
const statusGroupDefs = [
const sourceStatusGroupDefs = [
{ key: 'failed', label: 'chat.shippingProcessing.groupFailed' },
{ key: 'waiting_human', label: 'chat.shippingProcessing.groupWaitingHuman' },
{ key: 'processing', label: 'chat.shippingProcessing.groupProcessing' },
@@ -78,13 +81,76 @@ const statusGroupDefs = [
{ key: 'cancelled', label: 'chat.shippingProcessing.groupCancelled' },
{ key: 'archived', label: 'chat.shippingProcessing.groupHistoryRecords' },
] as const;
const statusGroupDefs = [
...sourceStatusGroupDefs,
{ key: 'ignored', label: 'chat.shippingProcessing.groupIgnored' },
] as const;
const expandedStatusGroups = ref(new Set<string>(['failed', 'waiting_human', 'processing']));
const expandedEmlTasks = ref(new Set<string>());
function statusGroupTasks(key: typeof statusGroupDefs[number]['key']) {
return conversationStatusGroups.value?.[key] || [];
type ConversationStatusGroupKey = typeof statusGroupDefs[number]['key'];
/**
* 将兼容响应中的混合状态 EML 防御性拆成 PDF 状态分区。
*
* 触发时机:后端热更新/旧响应暂时仍将同一 EML 的多种状态附件放在一个父行时使用;
* 新响应已拆分时原样保持。该函数只生成聊天展示副本,状态、附件与动作仍来自后端叶子 DTO。
*/
function statusGroupTasks(key: ConversationStatusGroupKey): ConversationProcessingUserTask[] {
const groups = conversationStatusGroups.value;
if (!groups) return [];
const result = new Map<string, ConversationProcessingUserTask>();
for (const sourceGroup of sourceStatusGroupDefs) {
for (const task of groups[sourceGroup.key] || []) {
const children = task.aggregateChildren || [];
if (!children.length) {
if (sourceGroup.key === key) result.set(task.user_task_no, task);
continue;
}
const matchingChildren = children.filter((child) => {
const status = displayProjectionStatus(child);
const childGroup = isIgnoredNonOrderAttachment(child) ? 'ignored'
: status === 'running' ? 'processing'
: status === 'retryable' ? 'failed'
: status;
return childGroup === key;
});
if (!matchingChildren.length) continue;
const existing = result.get(task.user_task_no);
const mergedChildren = existing
? [...(existing.aggregateChildren || []), ...matchingChildren]
: matchingChildren;
const uniqueChildren = [...new Map(mergedChildren.map((child) => [
String(child.sourceSummary?.documentId || child.workItemNo || ''), child,
])).values()];
const summary = task.aggregateSummary
? {
...task.aggregateSummary,
inGroup: uniqueChildren.length,
completed: key === 'completed' ? uniqueChildren.length : 0,
processing: key === 'processing' ? uniqueChildren.length : 0,
needsAction: key === 'waiting_human' ? uniqueChildren.length : 0,
failed: key === 'failed' ? uniqueChildren.length : 0,
}
: task.aggregateSummary;
result.set(task.user_task_no, {
...task,
group: key === 'ignored' ? 'processing'
: key === 'waiting_human' || key === 'failed'
? 'needs_action'
: key === 'cancelled' || key === 'archived' ? 'history' : key,
userGroup: key === 'ignored' ? 'processing' : key,
file_count: uniqueChildren.length,
aggregateChildren: uniqueChildren,
aggregateSummary: summary,
});
}
}
return [...result.values()];
}
function statusGroupLabel(key: typeof statusGroupDefs[number]['key']) {
const count = statusGroupTasks(key).length;
function statusGroupLabel(key: ConversationStatusGroupKey) {
const tasks = statusGroupTasks(key);
// 状态分组按“状态 → EML → 文件”展示,标题必须统计叶子文件而不是 EML 容器数。
const count = tasks.reduce((total, task) => total + taskFileCount(task), 0);
return t(statusGroupDefs.find((item) => item.key === key)!.label, { count });
}
function toggleStatusGroup(key: string) {
@@ -125,11 +191,12 @@ function taskFileCount(task: { aggregateChildren?: ShippingProcessingProjection[
}
function childStatusLabel(child: ShippingProcessingProjection) {
const status = displayProjectionStatus(child);
if (status === 'completed' && child.facts?.uploadState === 'succeeded') return t('chat.shippingProcessing.aggregate.completed', { count: 1 });
if (status === 'completed') return t('chat.shippingProcessing.groupRecordCompleted');
if (status === 'failed' || status === 'retryable') return t('chat.shippingProcessing.aggregate.failed', { count: 1 });
if (status === 'waiting_human') return t('chat.shippingProcessing.aggregate.needsAction', { count: 1 });
return t('chat.shippingProcessing.aggregate.processing', { count: 1 });
if (isIgnoredNonOrderAttachment(child)) return t('chat.shippingProcessing.ignoredNonOrderAttachment');
if (isUnrecognizedProjection(child)) return t('chat.shippingProcessing.notRecognized');
if (status === 'completed') return t('chat.shippingProcessing.statusBadge.completed');
if (status === 'failed' || status === 'retryable') return t('chat.shippingProcessing.statusBadge.failed');
if (status === 'waiting_human') return t('chat.shippingProcessing.statusBadge.needsAction');
return t('chat.shippingProcessing.statusBadge.processing');
}
function displayReason(
reason?: import('../../types/shipping.api.types').ShippingProcessingBlockingReason | null,
@@ -142,6 +209,16 @@ function displayProjectionStatus(item: ShippingProcessingProjection): string {
? item.uiState.status
: (item.userStatus || item.status || '')).trim().toLowerCase();
}
function isUnrecognizedProjection(item: ShippingProcessingProjection): boolean {
// 冻结选择计划中「已选但尚未物化/未识别」的附件诊断标记。
return item.facts?.recognized === false;
}
/** Excel 附件不进入订单 PDF 识别;保留诊断行但明确其不在识别队列中。 */
function isIgnoredNonOrderAttachment(item: ShippingProcessingProjection): boolean {
if (!isUnrecognizedProjection(item)) return false;
const filename = String(item.sourceSummary?.filename || '').trim().toLowerCase();
return filename.endsWith('.xls') || filename.endsWith('.xlsx');
}
function isFailedProjection(item: ShippingProcessingProjection): boolean {
const status = displayProjectionStatus(item);
return status === 'failed' || status === 'retryable';
@@ -156,8 +233,12 @@ function taskReason(task: { uiState?: { blocking_reason: import('../../types/shi
return task.uiState ? task.uiState.blocking_reason : task.blockingReason;
}
function childStageLabel(child: ShippingProcessingProjection) {
const stage = String(child.uiState?.stage || child.userStage || child.stage || '').trim();
return resolveShippingProcessingStageLabel(stage, te, t);
const stage = String(child.uiState?.lifecycleStage || child.uiState?.stage || child.userStage || child.stage || '').trim();
return resolveShippingLifecycleStageLabel(stage, te, t);
}
/** 行内仅展示「具体、非兜底」的阻塞原因,避免与状态芯片重复。 */
function hasSpecificReason(item: Parameters<typeof taskReason>[0]): boolean {
return !isGenericBlockingReason(taskReason(item), te);
}
function statusTaskProjection(task: { user_task_no?: string | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
const items = shippingWorkflow?.processingWorkItems.value || [];
@@ -218,16 +299,15 @@ const emlAggregate = computed(() => (
const emlAggregateChildren = computed(() => emlAggregate.value?.aggregateChildren || []);
const emlAggregateExpanded = ref(false);
function aggregateStageLabel(item: ShippingProcessingProjection): string {
const stage = String(item.uiState ? item.uiState.stage : (item.userStage || item.stage || '')).trim();
return resolveShippingProcessingStageLabel(stage, te, t);
const stage = String(item.uiState?.lifecycleStage || item.uiState?.stage || item.userStage || item.stage || '').trim();
return resolveShippingLifecycleStageLabel(stage, te, t);
}
function aggregateChildStatusLabel(item: ShippingProcessingProjection): string {
const status = displayProjectionStatus(item);
if (status === 'completed' && item.facts?.uploadState === 'succeeded') return t('chat.shippingProcessing.aggregate.completed', { count: 1 });
if (status === 'completed') return t('chat.shippingProcessing.groupRecordCompleted');
if (status === 'failed' || status === 'retryable') return t('chat.shippingProcessing.aggregate.failed', { count: 1 });
if (status === 'waiting_human') return t('chat.shippingProcessing.aggregate.needsAction', { count: 1 });
return t('chat.shippingProcessing.aggregate.processing', { count: 1 });
if (status === 'completed') return t('chat.shippingProcessing.statusBadge.completed');
if (status === 'failed' || status === 'retryable') return t('chat.shippingProcessing.statusBadge.failed');
if (status === 'waiting_human') return t('chat.shippingProcessing.statusBadge.needsAction');
return t('chat.shippingProcessing.statusBadge.processing');
}
function aggregateSummaryLabel(item: ShippingProcessingProjection): string {
const summary = item.aggregateSummary;
@@ -308,33 +388,131 @@ const failedRows = computed(() => fileRows.value.filter((row) => (
isFailedParseRow(row)
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
)));
const processedCount = computed(() => {
if (hasConversationStatusGroups.value) {
const summary = conversationProcessing.value?.summary;
// [AUTHORITY] “已处理/完成率”只表示已经完成通知生命周期的业务文件。
// waiting_human / failed 只是后端裁决出的待处理事项,不能借用历史 Run 的
// “处理过”口径累计为完成,否则会与批次进度中心的 completed_files 冲突。
return Math.max(0, Number(summary?.completed_files || 0));
}
// 当前 Run 仅表达抽取/候选状态,不能把 candidate_ready 或历史复核 Case 伪装成
// 已完成通知生命周期;生命周期完成数只由会话权威投影下发。
if (hasCurrentBusinessFileRows.value) return 0;
return emlAggregate.value?.aggregateSummary?.completed
?? (props.state.summary.completedDocuments + props.state.summary.reviewRequiredDocuments);
});
const progressPercent = computed(() => {
const total = batchFileCount.value;
return total > 0 ? Math.min(100, Math.round((processedCount.value / total) * 100)) : 0;
});
/** 新版会话批次的业务文件数由后端汇总;旧 Run 卡仍保留历史兼容计数。 */
const batchFileCount = computed(() => {
if (hasConversationStatusGroups.value) {
return Math.max(0, Number(conversationProcessing.value?.summary?.total_files || 0));
const summary = conversationProcessing.value?.summary;
// 主计数改用提交基 submitted_files(物化前即 ≥1、单调),旧后端未下发时回退 total_files。
return Math.max(0, Number(summary?.submitted_files ?? summary?.total_files ?? 0));
}
if (hasCurrentBusinessFileRows.value) return currentBusinessFileRows.value.length;
return Math.max(0, Number(emlAggregate.value?.sourceSummary.documentCount ?? props.state.summary.totalDocuments));
});
/**
* 已识别/活跃文件数(total_files):由物化文档裁决,随识别演化;作为完成率分母与「已识别 n/N」的 n。
*/
const recognizedFileCount = computed(() => {
if (!hasConversationStatusGroups.value) return null;
return Math.max(0, Number(conversationProcessing.value?.summary?.total_files || 0));
});
/** 提交基主计数(submitted_files);供「已识别 n/N」与空窗占位裁决。 */
const submittedFileCount = computed(() => {
if (!hasConversationStatusGroups.value) return null;
const summary = conversationProcessing.value?.summary;
return Math.max(0, Number(summary?.submitted_files ?? summary?.total_files ?? 0));
});
/** 任一状态组是否已有任务;空窗期(刚发送、尚未识别出附件)时用于显示识别占位。 */
const hasAnyStatusGroupTask = computed(() => (
statusGroupDefs.some((group) => statusGroupTasks(group.key).length > 0)
));
/**
* 空窗占位:已提交(submitted>0)但尚未识别出任何文件(无任务行)时,
* 正文显示「正在识别附件…」,避免向用户呈现「0 个文件」的误导性状态。
*/
const recognizingPlaceholderVisible = computed(() => (
hasConversationStatusGroups.value
&& !props.compactProgress
&& !hasAnyStatusGroupTask.value
&& (submittedFileCount.value ?? 0) > 0
));
/** 「已识别 n / N」次级提示:识别数落后于提交数时展示。 */
const recognizedHint = computed(() => {
const submitted = submittedFileCount.value;
const recognized = recognizedFileCount.value;
if (submitted == null || recognized == null) return null;
if (submitted <= 0 || recognized >= submitted) return null;
return t('chat.shippingProcessing.recognizedOfTotal', { recognized, submitted });
});
/**
* 收集会话投影中的附件叶子,并按稳定文件标识去重。
* 核心逻辑:只读取 status_groups 自带的 aggregateChildren;EML 父行是容器,不可作为订单文件参与顶部完成态。
* @returns 当前会话的附件叶子数组;缺少叶子时返回空数组,保留后端 ui_state 的展示裁决。
*/
function conversationAttachmentLeaves(): ShippingProcessingProjection[] {
const groups = conversationStatusGroups.value;
if (!groups) return [];
const unique = new Map<string, ShippingProcessingProjection>();
for (const group of sourceStatusGroupDefs) {
for (const task of groups[group.key] || []) {
for (const child of task.aggregateChildren || []) {
const key = String(child.sourceSummary?.documentId || child.workItemNo || '').trim();
if (key && !unique.has(key)) unique.set(key, child);
}
}
}
return [...unique.values()];
}
/** 参与订单处理的附件;Excel 计划附件只作诊断展示,不应阻塞批次完成态。 */
const conversationBusinessFiles = computed(() => (
conversationAttachmentLeaves().filter((file) => !isIgnoredNonOrderAttachment(file))
));
/**
* 会话级后端仍标记 running、但业务订单文件均完成时的顶部展示完成态。
* 核心逻辑:仅覆盖 Excel 已忽略这一前端视觉例外;未识别 PDF、失败或待人工均不满足 completed 条件。
*/
const conversationBusinessFilesCompleted = computed(() => (
hasConversationStatusGroups.value
&& conversationBusinessFiles.value.length > 0
&& conversationBusinessFiles.value.every((file) => displayProjectionStatus(file) === 'completed')
));
/** 已完成订单文件与已忽略附件同时存在时,替换容易误解的“已识别 n/N”摘要。 */
const completedAndIgnoredFileSummary = computed(() => {
if (!conversationBusinessFilesCompleted.value) return '';
const ignored = ignoredAttachmentCount.value;
if (!ignored) return '';
return t('chat.shippingProcessing.completedAndIgnoredFileSummary', {
completed: conversationBusinessFiles.value.length,
ignored,
});
});
/** 已忽略的非订单附件数;顶部摘要在所有会话状态中均须保留该诊断事实。 */
const ignoredAttachmentCount = computed(() => (
conversationAttachmentLeaves().filter(isIgnoredNonOrderAttachment).length
));
const ignoredAttachmentSummary = computed(() => {
if (!ignoredAttachmentCount.value) return '';
return t('chat.shippingProcessing.ignoredFileSummary', { count: ignoredAttachmentCount.value });
});
/**
* 会话投影可用时的批次摘要:仅汇总本批文件数量,绝不展示单个文件的当前阶段。
* 文件阶段由下方展开行分别呈现,避免多个文件处于不同阶段时造成批次误导。
*/
const batchSummaryLine = computed(() => {
if (!hasConversationStatusGroups.value) return null;
const summary = conversationProcessing.value?.summary;
const recognized = Math.max(0, Number(summary?.total_files || 0));
const failed = Number(summary?.failed_files || 0);
if (conversationBusinessFilesCompleted.value) {
return t('chat.shippingProcessing.batchSummaryCompleted', { recognized });
}
if (failed <= 0) {
return t('chat.shippingProcessing.batchSummaryProcessing', { recognized });
}
return t('chat.shippingProcessing.batchSummaryIncomplete', { recognized, failed });
});
/**
* 是否为「仅重复关联已有任务、无需人工复核」终态通知。
*/
@@ -363,7 +541,8 @@ function rowStatusLabel(row: ShippingOrderExtractionFileState): string {
if (row.status === 'candidate_ready') return t('chat.shippingProcessing.candidateReady');
if (isFailedParseRow(row)) return t('chat.shippingProcessing.batchException');
if (row.status === 'review_required') return t('chat.shippingProcessing.waitingReview');
const stageKey = `chat.shippingOrderExtractionUserStage.${String(row.userVisibleStage || '').trim()}`;
// v2:key 构造改走共享出口(输出不变契约),保留 UserStage 文案适配器。
const stageKey = resolveOrderExtractionRunStageKey(row.userVisibleStage, '');
if (row.userVisibleStage && te(stageKey)) return t(stageKey);
return t('chat.shippingProcessing.batchProcessing');
}
@@ -371,7 +550,7 @@ function rowStatusLabel(row: ShippingOrderExtractionFileState): string {
function rowStatusClass(row: ShippingOrderExtractionFileState): string {
if (row.status === 'candidate_ready') return 'text-emerald-500';
if (isFailedParseRow(row)) return 'text-rose-500';
return 'text-blue-500';
return 'text-brand-500';
}
/**
@@ -397,6 +576,7 @@ function handlingTitle(item: ShippingOrderExtractionHandlingItemState): string {
*/
const statusNotice = computed(() => {
if (hasConversationStatusGroups.value) {
if (conversationBusinessFilesCompleted.value) return t('chat.shippingSessionSummary.processNoticeCompleted');
const status = String(conversationProcessing.value?.ui_state?.status || '').trim().toLowerCase();
if (status === 'completed') return t('chat.shippingSessionSummary.processNoticeCompleted');
if (status === 'failed' || status === 'retryable') return t('chat.shippingSessionSummary.processNoticeFailed');
@@ -633,83 +813,85 @@ async function onPrimaryChatAction() {
<template>
<div
v-if="conversationProjectionLoading"
class="mb-3 animate-pulse overflow-hidden rounded-xl border border-slate-200 bg-white/90 shadow-md dark:border-slate-700 dark:bg-slate-900/90"
class="mb-3 animate-pulse overflow-hidden rounded-xl border border-default bg-white/90 shadow-md dark:bg-slate-900/90"
data-testid="shipping-order-extraction-projection-loading"
>
<!-- 读取权威 Projection 不是业务状态;只显示结构骨架,避免伪造“系统处理中”。 -->
<div class="border-b border-slate-200 bg-indigo-50/70 px-5 py-4 dark:border-slate-700 dark:bg-indigo-950/30">
<div class="h-6 w-36 rounded bg-slate-200 dark:bg-slate-700" />
<div class="mt-3 h-4 w-2/3 rounded bg-slate-200 dark:bg-slate-700" />
<div class="mt-5 h-2 w-full rounded bg-slate-200 dark:bg-slate-700" />
<div class="border-b border-default bg-brand-50/70 px-5 py-4 dark:bg-brand-950/30">
<div class="h-6 w-36 rounded bg-surface-strong" />
<div class="mt-3 h-4 w-2/3 rounded bg-surface-strong" />
<div class="mt-5 h-2 w-full rounded bg-surface-strong" />
</div>
<div class="space-y-3 p-4">
<div class="h-12 rounded-lg bg-slate-100 dark:bg-slate-800" />
<div class="h-12 rounded-lg bg-slate-100 dark:bg-slate-800" />
<div class="h-12 rounded-lg bg-surface-strong" />
<div class="h-12 rounded-lg bg-surface-strong" />
</div>
</div>
<div
v-else
class="mb-3 overflow-hidden rounded-xl border border-slate-200 bg-white/90 text-slate-900 shadow-md backdrop-blur-sm dark:border-slate-700 dark:bg-slate-900/90 dark:text-slate-100"
class="mb-3 overflow-hidden rounded-xl border border-default bg-white/90 text-primary shadow-md backdrop-blur-sm dark:bg-slate-900/90"
data-testid="shipping-order-extraction-card"
>
<div class="border-b border-slate-200 bg-indigo-50/70 px-5 py-4 dark:border-slate-700 dark:bg-indigo-950/30">
<div class="border-b border-default bg-brand-50/70 px-5 py-4 dark:bg-brand-950/30">
<div class="flex items-center justify-between gap-3">
<div class="flex items-center gap-2 text-lg font-semibold">
<LoaderCircle v-if="hasConversationStatusGroups ? conversationProcessing?.ui_state?.status === 'running' : emlAggregate ? emlAggregate.userStatus === 'running' : state.status === 'queued' || state.status === 'processing'" class="h-5 w-5 animate-spin text-blue-600" />
<CheckCircle2 v-else-if="hasConversationStatusGroups ? conversationProcessing?.ui_state?.status === 'completed' : emlAggregate ? emlAggregate.userStatus === 'completed' : state.status === 'completed'" class="h-5 w-5 text-emerald-500" />
<LoaderCircle v-if="hasConversationStatusGroups ? !conversationBusinessFilesCompleted && conversationProcessing?.ui_state?.status === 'running' : emlAggregate ? emlAggregate.userStatus === 'running' : state.status === 'queued' || state.status === 'processing'" class="h-5 w-5 animate-spin text-brand-600" />
<CheckCircle2 v-else-if="hasConversationStatusGroups ? conversationBusinessFilesCompleted || conversationProcessing?.ui_state?.status === 'completed' : emlAggregate ? emlAggregate.userStatus === 'completed' : state.status === 'completed'" class="h-5 w-5 text-emerald-500" />
<TriangleAlert v-else class="h-5 w-5 text-amber-500" />
<span>{{ t('chat.shippingProcessing.multiPdfTaskTitle') }}</span>
</div>
<span class="rounded-full bg-slate-200 px-3 py-1 text-xs font-medium text-slate-600 dark:bg-slate-700 dark:text-slate-200">
{{ t('chat.shippingProcessing.batchFilesTotal', { count: batchFileCount }) }}
<span class="rounded-full bg-surface-strong px-3 py-1 text-xs font-medium text-secondary">
<template v-if="completedAndIgnoredFileSummary">{{ completedAndIgnoredFileSummary }}</template>
<template v-else>{{ t('chat.shippingProcessing.batchFilesTotal', { count: batchFileCount }) }}<template v-if="recognizedHint"> · {{ recognizedHint }}</template><template v-if="ignoredAttachmentSummary"> · {{ ignoredAttachmentSummary }}</template></template>
</span>
</div>
<p class="mt-1 text-sm text-slate-600 dark:text-slate-300">{{ t('chat.shippingProcessing.batchStatusTitle') }} · {{ statusNotice }}</p>
<p class="mt-1 text-sm text-secondary">{{ batchSummaryLine || statusNotice }}</p>
<div v-for="tip in healthTips" :key="tip.code" class="mt-1 text-sm font-medium text-amber-600">{{ t(`chat.shippingOrderExtractionHealthTip.${tip.code}`) }}</div>
<div v-if="handlingSummaryLine" class="mt-1 text-sm text-slate-600 dark:text-slate-300">{{ handlingSummaryLine }}</div>
<div class="mt-4 flex items-end justify-between">
<span class="text-lg font-medium text-blue-600">{{ progressPercent }}% {{ t('chat.shippingProcessing.batchComplete') }}</span>
<span class="text-sm text-slate-600 dark:text-slate-300">{{ processedCount }}/{{ batchFileCount }} {{ t('chat.shippingProcessing.batchProcessed') }}</span>
</div>
<div class="mt-3 h-2 overflow-hidden rounded-full bg-slate-200 dark:bg-slate-700">
<div class="h-full rounded-full bg-blue-600 transition-all" :style="{ width: `${progressPercent}%` }" />
</div>
<div v-if="handlingSummaryLine && !hasConversationStatusGroups" class="mt-1 text-sm text-secondary">{{ handlingSummaryLine }}</div>
</div>
<div v-if="hasConversationStatusGroups && !compactProgress" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-status-groups">
<div v-if="hasConversationStatusGroups && !compactProgress" class="flex flex-col gap-2 bg-surface-soft p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-status-groups">
<div v-if="recognizingPlaceholderVisible" class="flex items-center gap-2 rounded-lg border border-default bg-surface p-3 text-sm text-muted">
<LoaderCircle class="h-4 w-4 animate-spin text-brand-500" />
<span data-testid="shipping-order-extraction-recognizing-placeholder">{{ t('chat.shippingProcessing.recognizingAttachments') }}</span>
</div>
<template v-for="group in statusGroupDefs" :key="group.key">
<section v-if="statusGroupTasks(group.key).length" class="overflow-hidden rounded-lg border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-900">
<section v-if="statusGroupTasks(group.key).length" class="overflow-hidden rounded-lg border border-default bg-surface">
<button type="button" class="flex w-full items-center justify-between px-3 py-3 text-left" @click="toggleStatusGroup(group.key)">
<span class="text-sm font-semibold" :class="group.key === 'failed' ? 'text-rose-600' : group.key === 'waiting_human' ? 'text-amber-700' : group.key === 'completed' ? 'text-emerald-600' : 'text-slate-700 dark:text-slate-200'">{{ statusGroupLabel(group.key) }}</span>
<span class="text-sm font-semibold" :class="group.key === 'failed' ? 'text-rose-600' : group.key === 'waiting_human' ? 'text-amber-700' : group.key === 'completed' ? 'text-emerald-600' : group.key === 'ignored' ? 'text-muted' : 'text-secondary '">{{ statusGroupLabel(group.key) }}</span>
<ChevronDown class="h-4 w-4 transition-transform" :class="expandedStatusGroups.has(group.key) ? 'rotate-180' : ''" />
</button>
<div v-if="expandedStatusGroups.has(group.key)" class="space-y-2 border-t border-slate-200 p-2 dark:border-slate-700">
<article v-for="task in statusGroupTasks(group.key)" :key="task.user_task_no" class="overflow-hidden rounded-lg border border-slate-300 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900" :data-testid="`shipping-order-extraction-eml-${group.key}-${task.user_task_no}`">
<div class="flex items-start gap-3 border-b border-slate-200 bg-blue-50/50 p-3 dark:border-slate-700 dark:bg-blue-950/20">
<Mail class="mt-0.5 h-5 w-5 text-blue-600" />
<div v-if="expandedStatusGroups.has(group.key)" class="space-y-2 border-t border-default p-2">
<article v-for="task in statusGroupTasks(group.key)" :key="task.user_task_no" class="overflow-hidden rounded-lg border border-default bg-surface shadow-sm" :data-testid="`shipping-order-extraction-eml-${group.key}-${task.user_task_no}`">
<div class="flex items-start gap-3 border-b border-default bg-surface-soft p-3 dark:bg-slate-950/30">
<Mail class="mt-0.5 h-5 w-5 text-brand-500" />
<div class="min-w-0 flex-1">
<button type="button" class="flex w-full items-center justify-between gap-3 text-left" @click="toggleEmlTask(task.user_task_no)">
<span class="truncate font-medium">{{ task.title || task.user_task_no }}</span>
<ChevronDown class="h-4 w-4 shrink-0 transition-transform" :class="expandedEmlTasks.has(task.user_task_no) ? 'rotate-180' : ''" />
</button>
<div class="mt-1 text-xs text-slate-600 dark:text-slate-300">{{ t('chat.shippingProcessing.taskFiles', { count: taskFileCount(task) }) }}<span v-if="task.aggregateSummary"> · {{ aggregateStatusLabelFromSummary(task.aggregateSummary) }}</span></div>
<div v-if="taskReason(task)" class="mt-1 text-xs text-rose-600">{{ displayReason(taskReason(task)) }}</div>
<div class="mt-1 text-xs text-secondary">{{ t('chat.shippingProcessing.taskFiles', { count: taskFileCount(task) }) }}<span v-if="task.aggregateSummary"> · {{ aggregateStatusLabelFromSummary(task.aggregateSummary) }}</span></div>
<div v-if="hasSpecificReason(task)" class="mt-1 text-xs text-rose-600">{{ displayReason(taskReason(task)) }}</div>
</div>
</div>
<div v-if="expandedEmlTasks.has(task.user_task_no) && taskChildren(task).length" class="mx-4 my-2 space-y-1 border-l-2 border-blue-200 bg-slate-50 p-3 pl-4 dark:border-blue-800 dark:bg-blue-950/30" data-testid="shipping-order-extraction-eml-children">
<div v-if="expandedEmlTasks.has(task.user_task_no) && taskChildren(task).length" class="mx-4 my-2 space-y-1 border-l-2 border-default bg-surface-soft p-3 pl-4 dark:border-slate-700 dark:bg-slate-950/30" data-testid="shipping-order-extraction-eml-children">
<div v-for="child in taskChildren(task).filter((item) => !String(item.sourceSummary?.filename || '').toLowerCase().endsWith('.eml'))" :key="child.workItemNo" class="flex items-start justify-between gap-3 py-1 text-sm">
<div class="flex min-w-0 items-start gap-2">
<LoaderCircle v-if="!isFailedProjection(child) && !isWaitingProjection(child) && !isCompletedProjection(child)" class="mt-0.5 h-4 w-4 shrink-0 animate-spin text-blue-500" />
<FileText v-if="isIgnoredNonOrderAttachment(child)" class="mt-0.5 h-4 w-4 shrink-0 text-muted" />
<AlertCircle v-else-if="isUnrecognizedProjection(child)" class="mt-0.5 h-4 w-4 shrink-0 text-amber-500" />
<LoaderCircle v-else-if="!isFailedProjection(child) && !isWaitingProjection(child) && !isCompletedProjection(child)" class="mt-0.5 h-4 w-4 shrink-0 animate-spin text-brand-500" />
<AlertCircle v-else-if="isFailedProjection(child)" class="mt-0.5 h-4 w-4 shrink-0 text-rose-500" />
<CheckCircle2 v-else-if="isCompletedProjection(child)" class="mt-0.5 h-4 w-4 shrink-0 text-emerald-500" />
<TriangleAlert v-else class="mt-0.5 h-4 w-4 shrink-0 text-amber-500" />
<div class="min-w-0">
<div class="truncate">{{ child.sourceSummary.filename || child.workItemNo }}</div>
<div class="text-xs text-slate-500">{{ childStageLabel(child) }}</div>
<div v-if="taskReason(child)" class="text-xs text-rose-600">{{ displayReason(taskReason(child)) }}</div>
<div class="text-xs text-muted">{{ childStageLabel(child) }}</div>
<div v-if="isIgnoredNonOrderAttachment(child)" class="text-xs text-muted">{{ t('chat.shippingProcessing.ignoredNonOrderAttachmentHint') }}</div>
<div v-else-if="isUnrecognizedProjection(child)" class="text-xs text-amber-600">{{ t('chat.shippingProcessing.notRecognizedHint') }}</div>
<div v-else-if="hasSpecificReason(child)" class="text-xs text-rose-600">{{ displayReason(taskReason(child)) }}</div>
</div>
</div>
<span :data-testid="`shipping-order-extraction-child-status-${child.workItemNo}`" class="shrink-0" :class="isFailedProjection(child) ? 'text-rose-600' : isWaitingProjection(child) ? 'text-amber-700' : isCompletedProjection(child) ? 'text-emerald-600' : 'text-blue-600'">{{ childStatusLabel(child) }}</span>
<span :data-testid="`shipping-order-extraction-child-status-${child.workItemNo}`" class="shrink-0" :class="isIgnoredNonOrderAttachment(child) ? 'text-muted' : isUnrecognizedProjection(child) ? 'text-amber-600' : isFailedProjection(child) ? 'text-rose-600' : isWaitingProjection(child) ? 'text-amber-700' : isCompletedProjection(child) ? 'text-emerald-600' : 'text-brand-600'">{{ childStatusLabel(child) }}</span>
</div>
</div>
</article>
@@ -717,49 +899,49 @@ async function onPrimaryChatAction() {
</section>
</template>
</div>
<div v-else-if="!compactProgress && emlAggregate" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-eml-aggregate">
<article class="overflow-hidden rounded-lg border border-slate-300 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
<div class="flex items-start gap-3 border-b border-slate-200 bg-blue-50/50 p-3 dark:border-slate-700 dark:bg-blue-950/20">
<Mail class="mt-0.5 h-5 w-5 text-blue-600" />
<div v-else-if="!compactProgress && emlAggregate" class="flex flex-col gap-2 bg-surface-soft p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-eml-aggregate">
<article class="overflow-hidden rounded-lg border border-default bg-surface shadow-sm">
<div class="flex items-start gap-3 border-b border-default bg-surface-soft p-3 dark:bg-slate-950/30">
<Mail class="mt-0.5 h-5 w-5 text-brand-500" />
<div class="min-w-0 flex-1">
<div class="flex items-center justify-between gap-3">
<span class="truncate font-medium">{{ t('chat.shippingProcessing.emailPrefix') }}{{ emlAggregate.sourceSummary.filename || emlAggregate.intakeNo }}</span>
<span class="rounded border px-2 py-0.5 text-xs" :class="emlAggregate.userStatus === 'failed' || emlAggregate.userStatus === 'retryable' ? 'border-rose-200 bg-rose-100/70 text-rose-600' : emlAggregate.userStatus === 'waiting_human' ? 'border-amber-200 bg-amber-100/70 text-amber-700' : emlAggregate.userStatus === 'completed' ? 'border-emerald-200 bg-emerald-100/70 text-emerald-600' : 'border-blue-200 bg-blue-100/70 text-blue-600'">
<span class="rounded border px-2 py-0.5 text-xs" :class="emlAggregate.userStatus === 'failed' || emlAggregate.userStatus === 'retryable' ? 'border-rose-200 bg-rose-100/70 text-rose-600' : emlAggregate.userStatus === 'waiting_human' ? 'border-amber-200 bg-amber-100/70 text-amber-700' : emlAggregate.userStatus === 'completed' ? 'border-emerald-200 bg-emerald-100/70 text-emerald-600' : 'border-brand-200 bg-brand-100/70 text-brand-600'">
{{ emlAggregate.userStatus === 'completed' ? t('chat.shippingProcessing.aggregate.completed', { count: emlAggregate.aggregateSummary?.completed || 0 }) : emlAggregate.userStatus === 'failed' || emlAggregate.userStatus === 'retryable' ? t('chat.shippingProcessing.batchException') : emlAggregate.userStatus === 'waiting_human' ? t('chat.shippingProcessing.waitingReview') : t('chat.shippingProcessing.systemProcessing') }}
</span>
</div>
<div class="mt-1 text-xs text-slate-600 dark:text-slate-300">{{ aggregateSummaryLabel(emlAggregate) }}</div>
<div v-if="taskReason(emlAggregate)" class="mt-1 text-xs text-rose-600">{{ displayReason(taskReason(emlAggregate)) }}</div>
<div class="mt-1 text-xs text-secondary">{{ aggregateSummaryLabel(emlAggregate) }}</div>
<div v-if="hasSpecificReason(emlAggregate)" class="mt-1 text-xs text-rose-600">{{ displayReason(taskReason(emlAggregate)) }}</div>
</div>
</div>
<button type="button" class="flex w-full items-center justify-between px-3 py-2 text-left text-sm" @click="emlAggregateExpanded = !emlAggregateExpanded">
<span>{{ t('chat.shippingProcessing.taskFiles', { count: emlAggregate.sourceSummary.documentCount || 0 }) }}</span>
<ChevronDown class="h-4 w-4 transition-transform" :class="emlAggregateExpanded ? 'rotate-180' : ''" />
</button>
<div v-if="emlAggregateExpanded" class="space-y-1 border-t border-slate-200 px-3 py-2 dark:border-slate-700">
<div v-if="emlAggregateExpanded" class="space-y-1 border-t border-default px-3 py-2">
<div v-for="child in emlAggregateChildren" :key="child.workItemNo" class="flex items-center justify-between gap-3 py-1 text-sm">
<span class="min-w-0 truncate">{{ child.sourceSummary.filename || child.workItemNo }}</span>
<span class="shrink-0 text-xs" :class="isFailedProjection(child) ? 'text-rose-600' : isWaitingProjection(child) ? 'text-amber-700' : isCompletedProjection(child) ? 'text-emerald-600' : 'text-blue-600'">{{ aggregateChildStatusLabel(child) }} · {{ aggregateStageLabel(child) }}</span>
<span class="shrink-0 text-xs" :class="isFailedProjection(child) ? 'text-rose-600' : isWaitingProjection(child) ? 'text-amber-700' : isCompletedProjection(child) ? 'text-emerald-600' : 'text-brand-600'">{{ aggregateChildStatusLabel(child) }} · {{ aggregateStageLabel(child) }}</span>
</div>
</div>
</article>
</div>
<div v-else-if="!compactProgress" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30">
<div v-for="row in activeEmailRows" :key="row.unitId" class="overflow-hidden rounded-lg border border-slate-300 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
<div class="flex items-start gap-3 border-b border-slate-200 bg-blue-50/50 p-3 dark:border-slate-700 dark:bg-blue-950/20"><Mail class="mt-0.5 h-5 w-5 text-blue-600" /><div class="min-w-0 flex-1"><div class="flex items-center justify-between gap-3"><span class="font-medium">{{ t('chat.shippingProcessing.emailPrefix') }}{{ row.fileName }}</span><span class="rounded border px-2 py-0.5 text-xs" :class="isFailedParseRow(row) || emailHasFailedChild(row) ? 'border-rose-200 bg-rose-100/70 text-rose-600' : emailIsCompleted(row) ? 'border-emerald-200 bg-emerald-100/70 text-emerald-600' : 'border-blue-200 bg-blue-100/70 text-blue-600'">{{ isFailedParseRow(row) || emailHasFailedChild(row) ? t('chat.shippingProcessing.batchException') : emailIsCompleted(row) ? t('chat.shippingProcessing.batchExtracted') : t('chat.shippingProcessing.parsingAttachments') }}</span></div><span class="mt-1 block font-mono text-xs text-slate-500">{{ t('chat.shippingProcessing.emailMeta') }}</span></div></div>
<div class="mx-4 my-2 flex flex-col gap-2 border-l-2 border-blue-200 bg-slate-50 p-3 pl-4 dark:border-blue-800 dark:bg-blue-950/30"><div v-for="child in childRows(row)" :key="`child-${child.unitId}`" class="flex items-center justify-between gap-3 text-sm"><span class="flex min-w-0 items-center gap-2"><CheckCircle2 v-if="child.status === 'candidate_ready'" class="h-4 w-4 text-emerald-500" /><LoaderCircle v-else-if="!isFailedParseRow(child)" class="h-4 w-4 animate-spin text-blue-500" /><AlertCircle v-else class="h-4 w-4 text-rose-500" /><span class="truncate">{{ child.fileName }}</span></span><span :class="rowStatusClass(child)">{{ rowStatusLabel(child) }}</span></div></div>
<div v-else-if="!compactProgress" class="flex flex-col gap-2 bg-surface-soft p-2 dark:bg-slate-950/30">
<div v-for="row in activeEmailRows" :key="row.unitId" class="overflow-hidden rounded-lg border border-default bg-surface shadow-sm">
<div class="flex items-start gap-3 border-b border-default bg-surface-soft p-3 dark:bg-slate-950/30"><Mail class="mt-0.5 h-5 w-5 text-brand-500" /><div class="min-w-0 flex-1"><div class="flex items-center justify-between gap-3"><span class="font-medium">{{ t('chat.shippingProcessing.emailPrefix') }}{{ row.fileName }}</span><span class="rounded border px-2 py-0.5 text-xs" :class="isFailedParseRow(row) || emailHasFailedChild(row) ? 'border-rose-200 bg-rose-100/70 text-rose-600' : emailIsCompleted(row) ? 'border-emerald-200 bg-emerald-100/70 text-emerald-600' : 'border-brand-200 bg-brand-100/70 text-brand-600'">{{ isFailedParseRow(row) || emailHasFailedChild(row) ? t('chat.shippingProcessing.batchException') : emailIsCompleted(row) ? t('chat.shippingProcessing.batchExtracted') : t('chat.shippingProcessing.parsingAttachments') }}</span></div><span class="mt-1 block font-mono text-xs text-muted">{{ t('chat.shippingProcessing.emailMeta') }}</span></div></div>
<div class="mx-4 my-2 flex flex-col gap-2 border-l-2 border-default bg-surface-soft p-3 pl-4 dark:border-slate-700 dark:bg-slate-950/30"><div v-for="child in childRows(row)" :key="`child-${child.unitId}`" class="flex items-center justify-between gap-3 text-sm"><span class="flex min-w-0 items-center gap-2"><CheckCircle2 v-if="child.status === 'candidate_ready'" class="h-4 w-4 text-emerald-500" /><LoaderCircle v-else-if="!isFailedParseRow(child)" class="h-4 w-4 animate-spin text-brand-500" /><AlertCircle v-else class="h-4 w-4 text-rose-500" /><span class="truncate">{{ child.fileName }}</span></span><span :class="rowStatusClass(child)">{{ rowStatusLabel(child) }}</span></div></div>
</div>
<div v-for="row in standaloneRows" :key="row.unitId" class="flex items-center justify-between gap-3 rounded-lg border border-slate-200 bg-white p-3 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900"><span class="flex min-w-0 items-center gap-3"><FileText class="h-5 w-5 text-slate-500" /><span class="truncate">{{ row.fileName }}</span></span><span class="flex items-center gap-2" :class="rowStatusClass(row)">{{ rowStatusLabel(row) }}<RefreshCw v-if="!isFailedParseRow(row)" class="h-4 w-4 animate-spin" /></span></div>
<div v-if="!fileRows.length" class="rounded-lg border border-slate-200 bg-white p-3 text-sm text-slate-500 dark:border-slate-700 dark:bg-slate-900">{{ t('chat.shippingProcessing.batchFilesUnavailable') }}</div>
<div v-for="row in standaloneRows" :key="row.unitId" class="flex items-center justify-between gap-3 rounded-lg border border-default bg-surface p-3 transition-colors hover-surface-soft"><span class="flex min-w-0 items-center gap-3"><FileText class="h-5 w-5 text-muted" /><span class="truncate">{{ row.fileName }}</span></span><span class="flex items-center gap-2" :class="rowStatusClass(row)">{{ rowStatusLabel(row) }}<RefreshCw v-if="!isFailedParseRow(row)" class="h-4 w-4 animate-spin" /></span></div>
<div v-if="!fileRows.length" class="rounded-lg border border-default bg-surface p-3 text-sm text-muted">{{ t('chat.shippingProcessing.batchFilesUnavailable') }}</div>
<div v-for="row in failedRows" :key="`failed-${row.unitId}`" class="rounded-lg border border-rose-200 bg-rose-50 p-3 dark:border-rose-800 dark:bg-rose-950/30"><div class="flex items-center justify-between text-rose-600"><span class="flex items-center gap-2 font-medium"><AlertCircle class="h-5 w-5" />{{ row.fileName }}</span><span class="rounded bg-rose-100 px-2 py-0.5 text-xs">{{ t('chat.shippingProcessing.batchException') }}</span></div><p class="mt-2 pl-7 text-sm">{{ row.explainability?.message || t('chat.shippingProcessing.batchManualVerify') }}</p></div>
</div>
<div class="flex justify-end border-t border-slate-200 bg-indigo-50/60 p-3 dark:border-slate-700 dark:bg-indigo-950/20">
<div class="flex justify-end border-t border-default bg-brand-50/60 p-3 dark:bg-brand-950/20">
<div class="flex items-center gap-3">
<button
v-if="!compactProgress && (hasConversationStatusGroups || String(props.runNo || '').trim())"
type="button"
class="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-5 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-blue-700"
class="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-5 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-brand-700"
data-testid="shipping-order-extraction-open-batch-workbench"
@click="emit('open-batch-workbench')"
>
@@ -202,17 +202,17 @@ onBeforeUnmount(() => {
>
<aside
ref="panelRef"
class="flex h-full w-full max-w-[560px] flex-col bg-white shadow-2xl dark:bg-slate-900"
class="flex h-full w-full max-w-[560px] flex-col bg-surface shadow-2xl"
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">
<header class="flex items-start justify-between border-b border-default px-4 py-3">
<div class="min-w-0">
<h3 class="text-sm font-semibold text-slate-900 dark:text-slate-100">
<h3 class="text-sm font-semibold text-primary">
{{ 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">
<div class="mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs text-secondary">
<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>
@@ -234,7 +234,7 @@ onBeforeUnmount(() => {
<button
ref="closeButtonRef"
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"
class="rounded-md p-1 text-muted hover-surface-strong hover:text-slate-900 dark:hover:text-slate-100"
:aria-label="t('chat.shippingOrderExtractionCloseDetails')"
data-testid="shipping-order-extraction-details-close"
@click="handleClose"
@@ -244,7 +244,7 @@ onBeforeUnmount(() => {
</header>
<div class="flex-1 space-y-3 overflow-y-auto px-4 py-4">
<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">
<div v-if="loading" class="rounded-lg border border-dashed border-default px-3 py-4 text-sm text-secondary">
{{ t('chat.shippingOrderExtractionDocumentsLoading') }}
</div>
<div
@@ -262,7 +262,7 @@ onBeforeUnmount(() => {
{{ t('chat.shippingOrderExtractionDetailsRetry') }}
</button>
</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">
<div v-else-if="documents.length === 0" class="rounded-lg border border-dashed border-default px-3 py-4 text-sm text-secondary">
{{ t('chat.shippingOrderExtractionNoDocuments') }}
</div>
<ShippingOrderDocumentResultItem
@@ -273,15 +273,15 @@ onBeforeUnmount(() => {
/>
<details
:open="timelineOpen"
class="rounded-lg border border-slate-200 bg-white px-3 py-3 dark:border-slate-700 dark:bg-slate-950/40"
class="rounded-lg border border-default bg-surface px-3 py-3 dark:bg-slate-950/40"
@toggle="timelineOpen = ($event.currentTarget as HTMLDetailsElement).open"
>
<summary class="cursor-pointer text-xs font-semibold text-slate-900 dark:text-slate-100">
<summary class="cursor-pointer text-xs font-semibold text-primary">
{{ t('chat.shippingOrderExtractionTimelineTitle') }}
</summary>
<div
v-if="state.selectionPlan?.totalAttachmentCount || state.unitSummary?.technicalFailureReasonCodes?.length"
class="mt-3 rounded-lg bg-slate-50 px-3 py-3 text-xs text-slate-700 dark:bg-slate-900/60 dark:text-slate-200"
class="mt-3 rounded-lg bg-surface-soft px-3 py-3 text-xs text-secondary dark:bg-slate-900/60"
>
<div v-if="state.selectionPlan?.totalAttachmentCount">
{{ t('chat.shippingOrderExtractionPlanSummary', {
@@ -302,7 +302,7 @@ onBeforeUnmount(() => {
</div>
<div
v-if="progressLoading"
class="mt-2 text-sm text-slate-600 dark:text-slate-300"
class="mt-2 text-sm text-secondary"
>
{{ t('chat.shippingOrderExtractionTimelineLoading') }}
</div>
@@ -323,16 +323,16 @@ onBeforeUnmount(() => {
</div>
<div
v-else-if="progressEvents.length === 0"
class="mt-2 text-sm text-slate-600 dark:text-slate-300"
class="mt-2 text-sm text-secondary"
>
{{ t('chat.shippingOrderExtractionTimelineEmpty') }}
</div>
<div v-else class="mt-3 space-y-3">
<section v-for="group in timelineGroups" :key="group.documentId == null ? 'run' : group.documentId" class="rounded-md border border-slate-200 px-3 py-2 dark:border-slate-700">
<h4 class="text-xs font-semibold text-slate-900 dark:text-slate-100">{{ group.fileName }}</h4>
<section v-for="group in timelineGroups" :key="group.documentId == null ? 'run' : group.documentId" class="rounded-md border border-default px-3 py-2">
<h4 class="text-xs font-semibold text-primary">{{ group.fileName }}</h4>
<ol class="mt-2 space-y-3">
<li v-for="event in group.events" :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>
<li v-for="event in group.events" :key="`${event.event_code}-${event.unit_id || 0}-${event.document_id || 0}-${event.occurred_at}`" class="border-l-2 border-default pl-3 text-xs text-secondary">
<div class="flex flex-wrap items-center gap-2"><span class="rounded-full bg-surface-strong px-2 py-0.5 text-[11px] font-medium text-secondary">{{ t(eventCategoryKey(event)) }}</span><div class="font-medium text-primary">{{ 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>
@@ -143,12 +143,41 @@ describe('ShippingWorkflowTimeline', () => {
expect(progress.text()).toContain('货代上传');
expect(progress.findAll('button')).toHaveLength(5);
const upload = wrapper.get('[data-testid="shipping-workflow-stage-filter-freight_upload"]');
// 五阶段卡仅保留阶段名和后端统计数量,状态由卡片样式表达。
expect(upload.text()).toBe('货代上传1');
// 阶段摘要以服务端计数的最高关注状态呈现,而非仅显示文件数量。
expect(upload.text()).toBe('货代上传1 待处理');
await upload.trigger('click');
expect(wrapper.find('[data-testid="shipping-workflow-download-toolbar"]').exists()).toBe(true);
});
it('separates ignored Excel attachments from order-file progress totals', async () => {
const ignoredExcel = fileProjection({
workItemNo: 'PLAN:EML-EXCEL:report',
sourceType: 'eml',
sourceSummary: {
emailSubject: null, filename: 'report.xlsx', documentId: null, documentCount: 0,
parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null,
},
facts: { recognized: false },
});
const task = {
user_task_no: 'INTAKE:EML-EXCEL', group: 'processing', status_label: 'extracting', title: 'mail.eml',
display_kind: 'aggregate', document_names: ['order.pdf', 'report.xlsx'], file_count: 2,
run_no: 'RUN-EML-EXCEL', can_append: false, aggregateChildren: [ignoredExcel],
};
const processing = processingProjection({
summary: {
total_tasks: 1, total_files: 5, submitted_files: 6, processing: 1, needs_action: 1,
completed: 3, history: 0, processing_files: 1, completed_files: 3, waiting_human_files: 1, failed_files: 0,
},
status_groups: { failed: [], waiting_human: [], processing: [task], completed: [], cancelled: [], archived: [] },
} as Partial<ConversationProcessingProjection>);
const wrapper = mountTimeline(processing, [ignoredExcel]);
await flushPromises();
expect(wrapper.get('[data-testid="shipping-workflow-overview"]').text()).toContain('已忽略1');
expect(wrapper.get('[data-testid="shipping-workflow-overview-progress"]').text()).toContain('3/5 个订单文件已处理 · 1 个文件已忽略');
});
it('removes the obsolete file-detail drawer and expand entry from batch workbench', async () => {
const wrapper = mountTimeline(processingProjection(), [fileProjection()]);
await flushPromises();
@@ -34,6 +34,7 @@ import {
} from '@/features/chat/api/shipping.api';
import type {
ConversationProcessingUserTask,
ConversationProcessingProjection,
LifecycleWorkbenchStage,
ShippingProcessingLifecycleEntry,
ShippingProcessingProjection,
@@ -125,6 +126,26 @@ function statusGroupTasks(...groups: ConversationStatusGroup[]): ConversationPro
if (!statusGroups) return [];
return groups.flatMap((group) => statusGroups[group] || []);
}
/**
* 统计未识别的 Excel 附件,供批次概览与提交文件数对账。
* 核心逻辑:已忽略附件不属于订单文件 summary,只能从各状态组的 EML 子附件读取并按文档去重。
* @param projection - 后端一次返回的会话处理投影。
* @returns 当前批次只读诊断附件数量,不参与订单完成率。
*/
function ignoredAttachmentCount(projection: ConversationProcessingProjection | null): number {
const seen = new Set<string>();
for (const group of ['failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived'] as const) {
for (const task of projection?.status_groups?.[group] || []) {
for (const child of task.aggregateChildren || []) {
const filename = String(child.sourceSummary?.filename || '').trim().toLowerCase();
if (child.facts?.recognized !== false || (!filename.endsWith('.xls') && !filename.endsWith('.xlsx'))) continue;
const key = String(child.sourceSummary?.documentId || child.workItemNo || '').trim();
if (key) seen.add(key);
}
}
}
return seen.size;
}
/** 五阶段后端编码为 snake_case,语言资源键沿用 camelCase;映射仅做展示翻译,不参与状态裁决。 */
const BATCH_LIFECYCLE_I18N_KEYS: Record<string, string> = {
intake_parse: 'intakeParse',
@@ -139,9 +160,18 @@ function batchLifecycleLabelKey(code: string): string {
function selectLifecycleFilter(code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete') {
lifecycleFilter.value = lifecycleFilter.value === code ? 'all' : code;
}
/** 阶段卡仅展示后端统计总数;状态、阻塞和推进语义由颜色与边框表达。 */
/**
* 阶段卡优先展示后端统计中的最高关注状态,避免仅显示数字而无法辨识处理中或待处理。
* @param node - 后端五阶段节点及其汇总。
* @returns 国际化状态摘要。
*/
function stageTotalText(node: NonNullable<typeof batchLifecycleNodes.value>[number]): string {
return String(Number(node.summary?.total || 0));
const summary = node.summary;
const needsAction = Number(summary?.needs_action || 0) + Number(summary?.failed || 0);
if (needsAction > 0) return t('chat.shippingProcessing.batchWorkbench.stageSummary.needsAction', { count: needsAction });
if (Number(summary?.processing || 0) > 0) return t('chat.shippingProcessing.batchWorkbench.stageSummary.processing', { count: summary?.processing });
if (Number(summary?.completed || 0) > 0) return t('chat.shippingProcessing.batchWorkbench.stageSummary.completed', { count: summary?.completed });
return t('chat.shippingProcessing.batchWorkbench.stageSummary.total', { count: Number(summary?.total || 0) });
}
/** 下载资格仅来自后端 output_artifacts 的授权动作;筛选仅影响展示,不缩减授权集合。 */
const downloadableTaskNos = computed(() => {
@@ -202,10 +232,14 @@ const batchOverview = computed(() => {
// [AUTHORITY] 摘要投影的统计与状态组同由服务端一次裁决;不能从展开行重算,
// 否则 EML 聚合、历史版本去重与五阶段筛选会再次发生口径漂移。
return {
// 总文件数卡用「提交基」submitted_files(物化前即 ≥1、单调),与聊天卡全局一致。
totalFiles: Number(summary?.submitted_files ?? summary?.total_files ?? 0),
// 完成率分母保留 total_files(已识别数),避免排除文件导致进度永远到不了 100%。
total: Number(summary?.total_files || 0),
processing: Number(summary?.processing_files || 0),
completed: Number(summary?.completed_files || 0),
needsAction: Number(summary?.failed_files || 0) + Number(summary?.waiting_human_files || 0),
ignored: ignoredAttachmentCount(displayProcessing.value),
};
});
/** 初始加载:首次打开投影仍为空时显示摘要占位。 */
@@ -910,8 +944,8 @@ watch(
class="mb-4 space-y-3"
data-testid="shipping-workflow-loading"
>
<div class="grid grid-cols-2 gap-3 xl:grid-cols-4">
<div v-for="index in 4" :key="index" class="h-24 animate-pulse rounded-xl border border-default bg-surface-muted" />
<div class="grid grid-cols-2 gap-3 xl:grid-cols-5">
<div v-for="index in 5" :key="index" class="h-24 animate-pulse rounded-xl border border-default bg-surface-muted" />
</div>
<div class="h-32 animate-pulse rounded-xl border border-default bg-surface-muted" />
</div>
@@ -927,13 +961,14 @@ watch(
</div>
<div
v-if="displayProcessing"
class="mb-4 grid grid-cols-2 gap-3 xl:grid-cols-4"
class="mb-4 grid grid-cols-2 gap-3 xl:grid-cols-5"
data-testid="shipping-workflow-overview"
>
<div class="rounded-xl border border-default bg-surface p-4"><div class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.overview.totalFiles') }}</div><div class="mt-1 text-2xl font-semibold text-primary">{{ batchOverview.total }}</div></div>
<div class="rounded-xl border border-default bg-surface p-4"><div class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.overview.totalFiles') }}</div><div class="mt-1 text-2xl font-semibold text-primary">{{ batchOverview.totalFiles }}</div></div>
<div class="rounded-xl border border-brand-200 bg-brand-50/60 p-4"><div class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.overview.processing') }}</div><div class="mt-1 text-2xl font-semibold text-brand-700">{{ batchOverview.processing }}</div></div>
<div class="rounded-xl border border-emerald-200 bg-emerald-50/70 p-4"><div class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.overview.completed') }}</div><div class="mt-1 text-2xl font-semibold text-emerald-700">{{ batchOverview.completed }}</div></div>
<div class="rounded-xl border border-rose-200 bg-rose-50/70 p-4"><div class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.overview.needsAction') }}</div><div class="mt-1 text-2xl font-semibold text-rose-700">{{ batchOverview.needsAction }}</div></div>
<div class="rounded-xl border border-default bg-surface-soft p-4 dark:bg-slate-900/50"><div class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.overview.ignored') }}</div><div class="mt-1 text-2xl font-semibold text-secondary">{{ batchOverview.ignored }}</div></div>
</div>
<div
v-if="displayProcessing"
@@ -942,7 +977,7 @@ watch(
>
<div class="mb-2 flex items-center justify-between text-xs font-medium text-secondary">
<span>{{ t('chat.shippingProcessing.batchWorkbench.overview.completion', { percent: Math.min(100, Math.round((batchOverview.completed / Math.max(1, batchOverview.total)) * 100)) }) }}</span>
<span>{{ t('chat.shippingProcessing.batchWorkbench.overview.processedOfTotal', { completed: batchOverview.completed, total: batchOverview.total }) }}</span>
<span>{{ batchOverview.ignored > 0 ? t('chat.shippingProcessing.batchWorkbench.overview.processedOfTotalWithIgnored', { completed: batchOverview.completed, total: batchOverview.total, ignored: batchOverview.ignored }) : t('chat.shippingProcessing.batchWorkbench.overview.processedOfTotal', { completed: batchOverview.completed, total: batchOverview.total }) }}</span>
</div>
<div class="h-3 overflow-hidden rounded-full bg-surface">
<div
@@ -0,0 +1,34 @@
/**
* features/chat/composables/transferLocales.spec.ts
* 用途:四语言 transfer 文案 key 一致性校验(zh-CN/zh-TW/en/th)。
* 依赖:locales 四语言 chat.json。
* 逻辑:四个语言包的 chat.transfer 键集合必须完全一致(防止漏翻译)。
*/
import { describe, expect, it } from 'vitest';
import zhCN from '@/locales/zh-CN/chat.json';
import zhTW from '@/locales/zh-TW/chat.json';
import en from '@/locales/en/chat.json';
import th from '@/locales/th/chat.json';
const packages: Record<string, Record<string, unknown>> = { zhCN, zhTW, en, th };
describe('transfer i18n four-language consistency', () => {
it('四个语言包拥有相同的 transfer 键集合', () => {
const keys = Object.keys(zhCN.transfer as Record<string, unknown>).sort();
expect(keys.length).toBeGreaterThan(30);
for (const [name, pack] of Object.entries(packages)) {
const transfer = (pack as Record<string, { transfer: Record<string, unknown> }>).transfer;
expect(transfer).toBeTruthy();
expect(Object.keys(transfer).sort()).toEqual(keys);
}
});
it('每个 transfer 文案值非空', () => {
for (const [name, pack] of Object.entries(packages)) {
const transfer = (pack as Record<string, { transfer: Record<string, unknown> }>).transfer;
for (const [key, value] of Object.entries(transfer)) {
expect(String(value).trim().length, `${name}.transfer.${key}`).toBeGreaterThan(0);
}
}
});
});
@@ -40,13 +40,13 @@ describe('useChat user attachment snapshots', () => {
const buildTaskUiStateEvent = (
taskNo: string,
actionId: string,
checkpoint = 'ready_export',
position = 'ready_export',
) => ({
event: 'shipping_ui_state',
task_no: taskNo,
ui_state: {
task_no: taskNo,
checkpoint,
position,
match_status: 'matched',
review_status: null,
pending_human_reason: null,
@@ -35,6 +35,7 @@ import {
getShippingParseReviewPayload,
sanitizeShippingConversationText,
} from '../shipping';
import { isShippingUiParseReview } from '../shipping/shippingUiPosition';
import { isShippingSpreadsheetFile } from '../shipping/shippingUploadPrompt';
import { extractExt } from '../constants/shipping';
import {
@@ -310,13 +311,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
const normalizedTaskId = String(taskId || getActiveShippingTaskId() || '').trim().toUpperCase();
if (!conversationKey || !normalizedTaskId || !isShippingNoticeAgent.value || isShippingActionBusy.value) return;
const detail = activeShippingTaskDetail.value;
// 复核同步只消费后端统一 ui_state.checkpoint,不读取 review_status 等领域事实推导。
const checkpoint = String(
detail?.ui_state?.checkpoint?.code
|| detail?.ui_state?.checkpoint_code
|| '',
).trim();
if (checkpoint !== 'parse_review') return;
// 复核同步:优先 review_status / Gate / position(isShippingUiParseReview)。
if (!isShippingUiParseReview(detail?.ui_state || null)) return;
const exists = messages.value.some((msg) => {
if (msg.type !== 'shipping-parse-review' || !msg.payload || typeof msg.payload !== 'object') return false;
return String((msg.payload as { taskId?: string }).taskId || '').trim().toUpperCase() === normalizedTaskId;
@@ -0,0 +1,113 @@
/**
* features/chat/composables/useChatTransfer.spec.ts
* 用途:验证预检创建/恢复、选择范围、直接生成执行 Run、结果恢复与防重复。
* 依赖:vi.mock(transfer.api)、useChatTransfer。
* 逻辑:用 Mock API 驱动组合式函数,断言状态流转与调用参数。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
const api = vi.hoisted(() => ({
createTransferPrecheck: vi.fn(),
getTransferPrecheck: vi.fn(),
executeTransferPrecheck: vi.fn(),
getTransferRun: vi.fn(),
cancelTransferRun: vi.fn(),
retryTransferItem: vi.fn(),
manualCloseTransferItem: vi.fn(),
downloadTransferReceiptFiles: vi.fn(),
downloadTransferErpInventory: vi.fn(),
downloadTransferExceptions: vi.fn(),
}));
vi.mock('../api/transfer.api', () => api);
import { useChatTransfer } from './useChatTransfer';
const summary = {
precheck_id: 'TPC-20260806-001',
status: 'ready_to_execute',
business_date: '2026-08-06',
eligible_receipt_date_to: '2026-08-05',
expires_at: '',
counts: { file_invoice_count: 2, not_matured_count: 0, prechecked_count: 2, executable_count: 2, blocked_count: 0 },
estimated_transfer_quantity: '2400',
estimated_erp_write_count: 2,
precheck_hash: 'sha256:abc',
};
const detail = {
summary,
sources: [{ source_code: 'DBS-AWSBI', stage: 'file_ready', file_no: 'REC-1' }],
items: [
{ source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: 'x', specification: 'y', invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable' },
{ source_code: 'DBS-AWSBI', material_no: 'MAT-2', material_name: 'x', specification: 'y', invoice_no: 'INV-002', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable' },
{ source_code: 'DBS-AWSBI', material_no: 'MAT-3', material_name: 'x', specification: 'y', invoice_no: 'INV-041', from_warehouse: '', from_quantity: null, to_warehouse: '', to_quantity: '400', result: 'not_matured' },
],
};
describe('useChatTransfer', () => {
beforeEach(() => {
vi.clearAllMocks();
api.createTransferPrecheck.mockResolvedValue(summary);
api.getTransferPrecheck.mockResolvedValue(detail);
api.executeTransferPrecheck.mockResolvedValue({ run_no: 'RUN-20260806-1', status: 'success' });
api.getTransferRun.mockResolvedValue({
run_no: 'RUN-20260806-1',
status: 'success',
result: { erp_documents: [], exceptions: [] },
});
});
it('创建预检后默认勾选全部可执行项,未成熟项不可勾选', async () => {
const transfer = useChatTransfer();
await transfer.createPrecheck(['DBS-AWSBI'], '2026-08-06');
expect(transfer.precheckId.value).toBe('TPC-20260806-001');
expect(transfer.executableInvoices.value).toEqual(['INV-001', 'INV-002']);
expect(transfer.selected.value.has('INV-001')).toBe(true);
expect(transfer.selected.value.has('INV-041')).toBe(false);
});
it('执行时提交勾选范围并恢复 Run', async () => {
const transfer = useChatTransfer();
await transfer.createPrecheck(['DBS-AWSBI']);
transfer.toggleSelect('INV-001', false);
await transfer.execute();
expect(api.executeTransferPrecheck).toHaveBeenCalledWith('TPC-20260806-001', ['INV-002']);
expect(transfer.runNo.value).toBe('RUN-20260806-1');
expect(api.getTransferRun).toHaveBeenCalledWith('RUN-20260806-1');
});
it('无选择时执行被拦截(不调用 API)', async () => {
const transfer = useChatTransfer();
await transfer.createPrecheck(['DBS-AWSBI']);
transfer.selected.value = new Set();
const result = await transfer.execute().catch(() => null);
expect(result).toBeNull();
expect(api.executeTransferPrecheck).not.toHaveBeenCalled();
});
it('busy 在请求期间置位,完成后复位(防重复点击)', async () => {
let resolvePrecheck!: (value: unknown) => void;
api.getTransferPrecheck.mockImplementation(
() => new Promise((resolve) => { resolvePrecheck = resolve; }),
);
const transfer = useChatTransfer();
const promise = transfer.createPrecheck(['DBS-AWSBI']);
// 推进微任务链:createTransferPrecheck → getTransferPrecheck(mock 已执行)
await Promise.resolve();
await Promise.resolve();
expect(transfer.busy.value).toBe(true);
resolvePrecheck(detail);
await promise;
expect(transfer.busy.value).toBe(false);
});
it('reset 清空全部状态', async () => {
const transfer = useChatTransfer();
await transfer.createPrecheck(['DBS-AWSBI']);
transfer.reset();
expect(transfer.precheckId.value).toBeNull();
expect(transfer.items.value).toHaveLength(0);
expect(transfer.run.value).toBeNull();
});
});
@@ -0,0 +1,259 @@
/**
* features/chat/composables/useChatTransfer.ts
* 用途:在途仓自动调拨聊天编排入口——预检创建/恢复、选择范围、直接生成执行 Run、
* Run 进度与结果恢复、人工重试/关闭、下载。
* 依赖:transfer.api、transfer.types、useMessage、Vue refs/computed。
* 逻辑:前端只消费稳定 DTO;Run 是异步真相源,刷新/重进由 GET 恢复;
* 防重复点击(busy);错误统一 useMessage 展示 BusinessError。
*/
import { computed, ref, type Ref } from 'vue';
import { useMessage } from '@/shared/composables/useMessage';
import {
cancelTransferRun,
createTransferPrecheck,
downloadTransferErpInventory,
downloadTransferExceptions,
downloadTransferReceiptFiles,
executeTransferPrecheck,
getTransferBacklogSummary,
getTransferPrecheck,
getTransferRun,
listTransferBacklog,
listTransferSources,
manualCloseTransferItem,
retryTransferItem,
retryTransferSourceRpa,
} from '../api/transfer.api';
import type {
TransferBacklogItem,
TransferBacklogSummary,
TransferPrecheckDetail,
TransferPrecheckItem,
TransferPrecheckSummary,
TransferRunResult,
TransferSourceOption,
TransferSourceProgress,
} from '../types/transfer.types';
export function useChatTransfer() {
const { error: notifyError } = useMessage();
const precheckId = ref<string | null>(null);
const precheck = ref<TransferPrecheckSummary | null>(null);
const items = ref<TransferPrecheckItem[]>([]);
const sources = ref<TransferSourceProgress[]>([]);
const runNo = ref<string | null>(null);
const run = ref<TransferRunResult | null>(null);
const backlog = ref<TransferBacklogItem[]>([]);
const backlogSummary = ref<TransferBacklogSummary | null>(null);
const sourceOptions = ref<TransferSourceOption[]>([]);
const selected = ref<Set<string>>(new Set());
const busy = ref(false);
const error = ref('');
/** 全部可执行 Invoice(阻断/未成熟不可勾选) */
const executableInvoices = computed(() =>
items.value.filter((item) => item.result === 'executable').map((item) => item.invoice_no),
);
const selectedCount = computed(() => selected.value.size);
const estimatedQuantity = computed(() => precheck.value?.estimated_transfer_quantity ?? '0');
/** 创建预检(缺文件时来源级阶段展示等待/失败) */
async function createPrecheck(sourceCodes: string[], businessDate?: string) {
busy.value = true;
error.value = '';
try {
const summary = await createTransferPrecheck({ source_codes: sourceCodes, business_date: businessDate });
precheckId.value = summary.precheck_id;
await refreshPrecheck();
return summary;
} catch (e) {
error.value = String(e);
throw e;
} finally {
busy.value = false;
}
}
/** 恢复预检进度(页面刷新/会话恢复) */
async function refreshPrecheck() {
if (!precheckId.value) return null;
const detail = await getTransferPrecheck(precheckId.value);
applyDetail(detail);
return detail;
}
function applyDetail(detail: TransferPrecheckDetail) {
precheck.value = detail.summary;
items.value = detail.items;
sources.value = detail.sources;
// 默认勾选全部可执行项;阻断/未成熟不可选
selected.value = new Set(
detail.items.filter((item) => item.result === 'executable').map((item) => item.invoice_no),
);
}
function toggleSelect(invoiceNo: string, checked: boolean) {
const next = new Set(selected.value);
if (checked) next.add(invoiceNo);
else next.delete(invoiceNo);
selected.value = next;
}
/** 直接生成调拨单(决策 4/5:无独立确认页) */
async function execute() {
if (!precheckId.value) throw new Error('precheck not created');
if (selected.value.size === 0) {
notifyError('请至少选择一个可执行 Invoice');
return null;
}
busy.value = true;
error.value = '';
try {
const result = await executeTransferPrecheck(precheckId.value, [...selected.value]);
runNo.value = result.run_no;
await refreshRun();
return result;
} catch (e) {
error.value = String(e);
throw e;
} finally {
busy.value = false;
}
}
/** 恢复 Run 最终结果 */
async function refreshRun() {
if (!runNo.value) return null;
const data = await getTransferRun(runNo.value);
run.value = data;
return data;
}
/** 请求停止剩余任务 */
async function cancelRun(reason: string) {
if (!runNo.value) return null;
const result = await cancelTransferRun(runNo.value, reason);
await refreshRun();
return result;
}
/** 人工重试异常项 */
async function retry(itemId: number) {
const result = await retryTransferItem(itemId);
await refreshPrecheck();
return result;
}
/** 人工关闭异常项 */
async function manualClose(itemId: number, reason: string) {
const result = await manualCloseTransferItem(itemId, reason);
await refreshPrecheck();
return result;
}
/** 下载收料来源文件(zip) */
async function downloadReceiptFiles() {
if (!runNo.value) return null;
const result = await downloadTransferReceiptFiles(runNo.value);
saveBlob(result.blob, result.filename ?? `receipt-files-${runNo.value}.zip`);
return result;
}
/** 下载预检冻结的 ERP 库存表(csv) */
async function downloadErpInventory() {
if (!runNo.value) return null;
const result = await downloadTransferErpInventory(runNo.value);
saveBlob(result.blob, result.filename ?? `erp-inventory-${runNo.value}.csv`);
return result;
}
/** 下载七 Sheet 异常 Excel */
async function downloadExceptions() {
if (!runNo.value) return null;
const result = await downloadTransferExceptions(runNo.value);
saveBlob(result.blob, result.filename ?? `transfer-exceptions-${runNo.value}.xlsx`);
return result;
}
/** 加载来源实例列表(决策 3:平台仅分组,每来源附收料文件状态) */
async function loadSources() {
sourceOptions.value = await listTransferSources();
return sourceOptions.value;
}
/** 对指定来源重新触发收料 RPA 抓取,并刷新来源状态 */
async function retrySourceRpa(sourceCode: string) {
const status = await retryTransferSourceRpa(sourceCode);
await loadSources();
return status;
}
/** 加载待处理异常列表与汇总 */
async function loadBacklog() {
const [items, summary] = await Promise.all([listTransferBacklog(), getTransferBacklogSummary()]);
backlog.value = items;
backlogSummary.value = summary;
return { items, summary };
}
function saveBlob(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
URL.revokeObjectURL(url);
}
function reset() {
precheckId.value = null;
precheck.value = null;
items.value = [];
sources.value = [];
runNo.value = null;
run.value = null;
backlog.value = [];
backlogSummary.value = null;
sourceOptions.value = [];
selected.value = new Set();
error.value = '';
}
return {
precheckId,
precheck,
items,
sources,
runNo,
run,
backlog,
backlogSummary,
sourceOptions,
selected,
selectedCount,
executableInvoices,
estimatedQuantity,
busy,
error,
createPrecheck,
refreshPrecheck,
toggleSelect,
execute,
refreshRun,
cancelRun,
retry,
manualClose,
loadSources,
retrySourceRpa,
loadBacklog,
downloadReceiptFiles,
downloadErpInventory,
downloadExceptions,
reset,
};
}
export type ChatTransfer = ReturnType<typeof useChatTransfer>;
export type { Ref };
@@ -0,0 +1,117 @@
/**
* features/chat/e2e/in-transit-transfer.spec.ts
* 用途:在途仓自动调拨全链路契约冒烟(对应 TDD §10 主路径)——
* 预检 → 选择子集 → 直接生成调拨单 → Run 恢复 → 下载留底。
* 依赖:Vitest、vi.mock(transfer.api)、useChatTransfer。
* 逻辑:不启浏览器;用组合式函数 + Mock API 断言产品契约,避免 e2e 环境依赖
* (与仓库 shipping e2e 约定一致)。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
const api = vi.hoisted(() => ({
createTransferPrecheck: vi.fn(),
getTransferPrecheck: vi.fn(),
executeTransferPrecheck: vi.fn(),
getTransferRun: vi.fn(),
retryTransferItem: vi.fn(),
manualCloseTransferItem: vi.fn(),
downloadTransferReceiptFiles: vi.fn(),
downloadTransferErpInventory: vi.fn(),
downloadTransferExceptions: vi.fn(),
}));
vi.mock('@/features/chat/api/transfer.api', () => api);
import { useChatTransfer } from '@/features/chat/composables/useChatTransfer';
import type { TransferPrecheckDetail } from '@/features/chat/types/transfer.types';
const detail: TransferPrecheckDetail = {
summary: {
precheck_id: 'TPC-20260806-001',
status: 'ready_to_execute',
business_date: '2026-08-06',
eligible_receipt_date_to: '2026-08-05',
expires_at: '',
counts: { file_invoice_count: 3, not_matured_count: 1, prechecked_count: 2, executable_count: 2, blocked_count: 0 },
estimated_transfer_quantity: '2400',
estimated_erp_write_count: 2,
precheck_hash: 'sha256:abc',
},
sources: [{ source_code: 'DBS-AWSBI', stage: 'file_ready', file_no: 'REC-1', file_version: 'v3' }],
items: [
{ source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器组件', specification: 'A', invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable' },
{ source_code: 'DBS-AWSBI', material_no: 'MAT-2', material_name: '控制器组件', specification: 'B', invoice_no: 'INV-002', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable' },
{ source_code: 'DBS-AWSSG', material_no: 'MAT-41', material_name: '连接器', specification: 'C', invoice_no: 'INV-041', from_warehouse: '', from_quantity: null, to_warehouse: '', to_quantity: '400', result: 'not_matured' },
],
};
const runResult = {
run_no: 'RUN-20260806-001',
status: 'success',
result: {
erp_documents: [{
document_no: 'TRF-10001',
from_warehouse: 'DBS-TRANSIT',
to_warehouse: 'HUB-CN01',
material_count: 2,
total_quantity: '2400',
posting_status: 'posted',
lines: [
{ material_no: 'MAT-1', material_name: '连接器组件', specification: 'A', invoice_no: 'INV-001', quantity: '1200' },
{ material_no: 'MAT-2', material_name: '控制器组件', specification: 'B', invoice_no: 'INV-002', quantity: '1200' },
],
}],
exceptions: [],
},
};
describe('in-transit-transfer e2e contract', () => {
beforeEach(() => {
vi.clearAllMocks();
api.createTransferPrecheck.mockResolvedValue(detail.summary);
api.getTransferPrecheck.mockResolvedValue(detail);
api.executeTransferPrecheck.mockResolvedValue({ run_no: 'RUN-20260806-001', status: 'success' });
api.getTransferRun.mockResolvedValue(runResult);
api.downloadTransferReceiptFiles.mockResolvedValue({ blob: new Blob(['zip']), filename: 'receipt-files.zip' });
api.downloadTransferErpInventory.mockResolvedValue({ blob: new Blob(['csv']), filename: 'erp.csv' });
});
it('主路径:预检 → 只选 INV-001 → 生成调拨单 → 结果按 ERP 单号聚合', async () => {
const transfer = useChatTransfer();
await transfer.createPrecheck(['DBS-AWSBI', 'DBS-AWSSG'], '2026-08-06');
// 未成熟项默认不勾选
expect(transfer.selected.value.has('INV-041')).toBe(false);
// 取消 INV-002,只执行 INV-001
transfer.toggleSelect('INV-002', false);
await transfer.execute();
expect(api.executeTransferPrecheck).toHaveBeenCalledWith('TPC-20260806-001', ['INV-001']);
expect(transfer.run.value?.result.erp_documents[0].document_no).toBe('TRF-10001');
});
it('刷新恢复:重建 composable 后按 run_no 恢复最终结果(决策 17)', async () => {
const transfer = useChatTransfer();
transfer.runNo.value = 'RUN-20260806-001';
await transfer.refreshRun();
expect(transfer.run.value?.status).toBe('success');
expect(transfer.run.value?.result.erp_documents[0].material_count).toBe(2);
});
it('下载:收料来源文件与 ERP 库存表(决策 21/22 前端入口)', async () => {
const transfer = useChatTransfer();
transfer.runNo.value = 'RUN-20260806-001';
await transfer.downloadReceiptFiles();
await transfer.downloadErpInventory();
expect(api.downloadTransferReceiptFiles).toHaveBeenCalledWith('RUN-20260806-001');
expect(api.downloadTransferErpInventory).toHaveBeenCalledWith('RUN-20260806-001');
});
it('异常处理:人工重试与人工关闭走独立 API', async () => {
api.retryTransferItem.mockResolvedValue({ item_id: 1, status: 'ready_to_execute', attempt_no: 2 });
api.manualCloseTransferItem.mockResolvedValue({ item_id: 2, status: 'manually_closed' });
const transfer = useChatTransfer();
await transfer.retry(1);
await transfer.manualClose(2, '线下已处理');
expect(api.retryTransferItem).toHaveBeenCalledWith(1);
expect(api.manualCloseTransferItem).toHaveBeenCalledWith(2, '线下已处理');
});
});
@@ -58,4 +58,15 @@ describe('parseOrderReviewConfirmResponse', () => {
expect(parsed?.taskNo).toBe('SN-NOTICE');
expect(parsed?.orderTaskNo).toBe('OT-ROOT-C102');
});
it('reads auto_progress.position only', () => {
const parsed = parseOrderReviewConfirmResponse(baseResponse({
auto_progress: {
status: 'queued',
position: 'inventory_pending',
user_mode: 'auto_continue',
},
}));
expect(parsed?.position).toBe('inventory_pending');
});
});
@@ -3,18 +3,16 @@
* 用途:统一解析复核确认建单 API 的业务态,禁止调用方仅凭 HTTP/success/confirm_ok 判定推进成功。
* 依赖:ShippingOrderReviewConfirmResponse 类型。
* 逻辑:ShippingOrderReviewView / 其他确认调用方共用;与后端 resolve_confirm_outcome 枚举对齐;
* 同时暴露 shipping_notice_no 与 order_task_no,禁止用 Notice 编号聚焦 OT 卡。
* 同时暴露 shipping_notice_no 与 order_task_no,禁止用 Notice 编号聚焦 OT 卡;
* 位置只读 auto_progress.position。
*/
import type { ShippingOrderReviewConfirmResponse } from '@/features/chat/types/shipping.api.types';
/** 与后端 confirm_outcome 对齐的稳定枚举。 */
export type ShippingOrderReviewConfirmOutcome =
| 'confirmed_and_auto_progress_started'
| 'confirmed_auto_progress_failed'
| 'confirmed_auto_progress_not_scheduled'
| string;
/** 确认响应解析结果:建单与自动推进解耦。 */
export interface ParsedOrderReviewConfirmResult {
/** 正式 ShippingNotice 编号(自动推进 / 工作台)。 */
@@ -29,15 +27,14 @@ export interface ParsedOrderReviewConfirmResult {
progressFailed: boolean;
progressStatus: string;
progressMessage: string;
checkpoint: string;
/** Gate 位置标签(derive_position) */
position: string;
}
const PROGRESS_FAILED_STATUSES = new Set([
'enqueue_failed',
'sync_execution_failed',
'failed',
]);
/**
* 解析复核确认响应的业务态。
* 核心逻辑:confirm_ok 仅表示建单成功;推进成败读 confirm_outcome / auto_progress.status;
@@ -53,13 +50,11 @@ export function parseOrderReviewConfirmResponse(
response?.shipping_notice_no || response?.task_no || '',
).trim();
if (!taskNo) return null;
const orderTaskNo = String(
response?.order_task_no
|| response?.case?.order_task_no
|| '',
).trim();
const progressStatus = String(response?.auto_progress?.status || '').trim();
const confirmOutcome = String(response?.confirm_outcome || '').trim()
|| (PROGRESS_FAILED_STATUSES.has(progressStatus)
@@ -67,13 +62,11 @@ export function parseOrderReviewConfirmResponse(
: response?.auto_progress_started
? 'confirmed_and_auto_progress_started'
: 'confirmed_auto_progress_not_scheduled');
const progressFailed = confirmOutcome === 'confirmed_auto_progress_failed'
|| PROGRESS_FAILED_STATUSES.has(progressStatus);
const autoProgressStarted = Boolean(response?.auto_progress_started)
|| confirmOutcome === 'confirmed_and_auto_progress_started';
const position = String(response?.auto_progress?.position || '').trim();
return {
taskNo,
orderTaskNo,
@@ -83,6 +76,6 @@ export function parseOrderReviewConfirmResponse(
progressFailed,
progressStatus: progressStatus || confirmOutcome,
progressMessage: String(response?.auto_progress?.message || ''),
checkpoint: String(response?.auto_progress?.checkpoint || ''),
position,
};
}
@@ -59,6 +59,7 @@ const api = vi.hoisted(() => ({
confirmCase: vi.fn(),
validateDraft: vi.fn(),
patchHeader: vi.fn(),
}));
@@ -89,7 +90,7 @@ vi.mock('../api/shipping.api', () => ({
confirmWorkspaceShippingOrderReviewCase: api.confirmCase,
patchWorkspaceShippingOrderReviewHeaderField: vi.fn(),
patchWorkspaceShippingOrderReviewHeaderField: api.patchHeader,
patchWorkspaceShippingOrderReviewLineField: vi.fn(),
@@ -135,7 +136,7 @@ const buildCase = (patch: Partial<ShippingOrderReviewCase> = {}): ShippingOrderR
header_values: {},
lines: [{ line_key: 'line-1' }],
lines: [{ draft_line_id: 'line-1' }],
issues: [],
@@ -149,7 +150,7 @@ const buildCase = (patch: Partial<ShippingOrderReviewCase> = {}): ShippingOrderR
line_projections: [{
line_key: 'line-1',
draft_line_id: 'line-1',
line_index: 0,
@@ -403,7 +404,7 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.canConfirmBuild.value).toBe(false);
expect(review.routingRecoveryLines.value).toHaveLength(1);
expect(review.routingRecoveryLines.value[0]?.line_key).toBe('line-1');
expect(review.routingRecoveryLines.value[0]?.draft_line_id).toBe('line-1');
});
@@ -441,6 +442,68 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(resume).toEqual({ outcome: 'auto_create_enqueued' });
});
it('tracks an enqueued validation until the worker creates the formal order task', async () => {
vi.useFakeTimers();
const queuedCase = buildCase({
status: 'ready',
automation: { status: 'queued' },
});
const confirmedCase = buildCase({
status: 'confirmed',
order_task_no: 'OT-1',
confirmed_task_no: 'OT-1',
automation: { status: 'running' },
});
api.validateDraft.mockResolvedValue({
case: queuedCase,
resume_outcome: { outcome: 'auto_create_enqueued' },
});
api.getCase.mockResolvedValueOnce(buildCase()).mockResolvedValue(confirmedCase);
api.getQueue.mockResolvedValue({
summary: { total: 1, needs_action: 0, processing: 1, completed: 0 },
items: [{
case_no: 'CASE-1', document_id: 1, status: 'confirmed',
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [],
}],
});
api.getExtractionRun.mockResolvedValue({ run_no: 'RUN-1', status: 'completed' });
api.getProcessingWorkItem.mockResolvedValue({
work_item_no: 'OT-1', status: 'processing', stage: 'inventory_preparation',
});
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await review.validate();
await vi.advanceTimersByTimeAsync(0);
expect(review.workflowProgressPolling.value).toBe(true);
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
expect(review.reviewProgressContext.value?.user_task_no).toBe('OT-1');
expect(api.getProcessingWorkItem).toHaveBeenCalledWith('order_task', 'OT-1');
review.stopWorkflowProgressPolling();
vi.useRealTimers();
});
it('does not treat a field edit revalidation as a formal-order creation request', async () => {
vi.useFakeTimers();
const revalidatingCase = buildCase({
status: 'draft',
automation: { status: 'queued' },
});
api.patchHeader.mockResolvedValue(revalidatingCase);
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await review.patchHeader('ship_to_name', '新收货方');
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
// 字段编辑后的 queued 是异步重校验,不是用户已确认的建单请求。
expect(api.getCase).toHaveBeenCalledTimes(1);
expect(review.workflowProgressPolling.value).toBe(false);
vi.useRealTimers();
});
it('refreshes the current Case silently without entering the PDF-switch loading state', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
@@ -461,6 +524,36 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.previewUrl.value).toMatch(/^blob:/);
});
it('refreshReviewQueue reloads lifecycle stages without touching Case or PDF preview', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
const blob = new Blob(['%PDF'], { type: 'application/pdf' });
api.getPreview.mockResolvedValue(blob);
await review.ensurePreviewLoaded('CASE-1');
const previewBefore = review.previewUrl.value;
const caseCallsBefore = api.getCase.mock.calls.length;
api.getQueue.mockResolvedValue({
summary: { total: 1, needs_action: 0, processing: 0, completed: 1 },
items: [{
case_no: 'CASE-1',
document_id: 1,
status: 'confirmed',
issue_count: 0,
available_actions: [],
lifecycle_stage: 'upload_complete',
}],
});
const ok = await review.refreshReviewQueue();
// 左侧队列阶段必须可单独刷新;不得顺带切换 Case 或清掉已加载预览。
expect(ok).toBe(true);
expect(review.reviewQueue.value?.items[0]?.lifecycle_stage).toBe('upload_complete');
expect(api.getCase.mock.calls.length).toBe(caseCallsBefore);
expect(review.previewUrl.value).toBe(previewBefore);
expect(review.caseSwitchLoading.value).toBe(false);
});
it('discards a stale preview success after Case A switches to Case B', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
@@ -646,6 +739,38 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.requestedCaseNo.value).toBe('CASE-FAIL');
});
it('beginCrossRunSwitch keeps workbench shell but drops previous OT projection authority', async () => {
// 关键断言:跨 Run 不清空 activeCase(避免大骨架),但必须撤销旧 OT,防止右卡/库存串味。
api.getCase.mockResolvedValueOnce(buildCase({ case_no: 'CASE-OLD' }));
api.getEvidence.mockResolvedValueOnce({ items: [] });
const review = useShippingOrderReview();
await review.selectCase('CASE-OLD');
review.reviewProgressContext.value = {
item_no: 'WI-1',
workflow_no: 'WF-1',
conversation_id: 'conv-1',
root_document_id: 1,
current_document_id: 1,
current_version_no: 1,
current_run_no: 'RUN-1',
current_case_no: 'CASE-OLD',
user_task_no: 'OT-OLD',
user_task_authoritative: true,
lifecycle_status: 'fulfillment_prep',
current_stage: 'fulfillment_prep',
lock_version: 1,
} as any;
review.beginCrossRunSwitch('CASE-NEW');
expect(review.caseSwitchLoading.value).toBe(true);
expect(review.requestedCaseNo.value).toBe('CASE-NEW');
expect(review.activeCase.value?.case_no).toBe('CASE-OLD');
expect(review.reviewProgressContext.value?.current_case_no).toBe('CASE-NEW');
expect(review.reviewProgressContext.value?.user_task_no).toBeNull();
expect(review.reviewProgressContext.value?.user_task_authoritative).toBe(false);
});
it('discards stale selectCase responses when switching PDFs quickly', async () => {
// 关键断言:A 后发先至不得覆盖后选的 B;切换时先清空瞬态。
let resolveA: ((value: ShippingOrderReviewCase) => void) | null = null;
@@ -934,6 +1059,44 @@ describe('useShippingOrderReview build eligibility writes', () => {
vi.useRealTimers();
});
it('stops workflow progress polling once the unified work item is interrupted (waiting_human)', async () => {
vi.useFakeTimers();
const readyCase = buildCase({
status: 'ready',
draft: {
...buildCase().draft!,
build_eligibility: { can_build: true, status: 'ready', line_projections: [] },
},
});
api.getCase.mockResolvedValue(readyCase);
api.getRun.mockResolvedValue({
run_no: 'RUN-1', summary: {},
items: [{ case_no: 'CASE-1', document_id: 1, status: 'ready', available_actions: ['confirm'] }],
});
api.getEvidence.mockResolvedValue({ items: [] });
api.getPreview.mockResolvedValue({ preview_url: '' });
api.getProcessingWorkItem.mockResolvedValue({
work_item_no: 'OT-1', status: 'blocked', user_status: 'waiting_human',
currentGate: { gateCode: 'inventory_matching', status: 'blocked_manual' },
});
api.confirmCase.mockResolvedValue({
task_no: 'SN-1', order_task_no: 'OT-1', shipping_notice_no: 'SN-1', idempotent_replay: false,
case: { ...readyCase, status: 'confirmed', order_task_no: 'OT-1' }, auto_progress_started: true,
});
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'WFI-1' });
await review.confirm();
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
// 中断(waiting_human,即“等待人工处理”)视为线性终态:结果不会自行变化,必须停止轮询。
expect(review.workflowProgressPolling.value).toBe(false);
review.stopWorkflowProgressPolling();
vi.useRealTimers();
});
it('refreshes the active Case and queue while post-confirm automation is still active', async () => {
vi.useFakeTimers();
const readyCase = buildCase({
@@ -1043,6 +1206,53 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.reviewProgressContext.value?.user_task_authoritative).toBe(true);
});
it('uses confirmed OT number when case order_task_no is empty but confirmed_task_no is OT-prefixed', async () => {
// 关键断言:正式任务下游 Case.order_task_no 可能暂空,但 confirmed_task_no 已是 OT 时
// 仍须启动 work-item 投影;否则右卡永久「正在获取最新状态 / 待机」。
api.getCase.mockResolvedValue(buildCase({
candidate_id: 42,
candidate: { candidate_no: 'CAND-42', validation_status: 'ready' },
status: 'confirmed',
has_formal_ot: true,
confirmed_task_no: 'OT-CONFIRMED-ONLY',
order_task_no: null,
}));
api.getRun.mockResolvedValue({
run_no: 'RUN-1',
summary: {},
items: [{ case_no: 'CASE-1', document_id: 1, status: 'confirmed', available_actions: [] }],
});
api.getEvidence.mockResolvedValue({ items: [] });
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1' });
expect(review.reviewProgressContext.value?.user_task_no).toBe('OT-CONFIRMED-ONLY');
expect(review.reviewProgressContext.value?.user_task_authoritative).toBe(true);
});
it('does not treat SN confirmed_task_no as order_task work-item key', async () => {
api.getCase.mockResolvedValue(buildCase({
candidate_id: 42,
candidate: { candidate_no: 'CAND-42', validation_status: 'ready' },
status: 'confirmed',
has_formal_ot: true,
confirmed_task_no: 'SN-NOTICE-1',
order_task_no: null,
}));
api.getRun.mockResolvedValue({
run_no: 'RUN-1',
summary: {},
items: [{ case_no: 'CASE-1', document_id: 1, status: 'confirmed', available_actions: [] }],
});
api.getEvidence.mockResolvedValue({ items: [] });
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1' });
expect(review.reviewProgressContext.value?.user_task_no).toBeNull();
});
it('leaves OT unset while waiting for a reparse Case when candidate-bound case lacks order_task_no', async () => {
vi.useFakeTimers();
api.getCase.mockResolvedValue(buildCase({
@@ -1116,7 +1326,8 @@ describe('useShippingOrderReview build eligibility writes', () => {
run_no: caseNo === 'CASE-2' ? 'RUN-2' : 'RUN-1',
}));
const review = useShippingOrderReview();
const onReparseCaseReady = vi.fn();
const review = useShippingOrderReview({ onReparseCaseReady });
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
await review.reparseDocument('document_quality');
@@ -1125,6 +1336,8 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.reviewRun.value?.run_no).toBe('RUN-2');
expect(review.activeCase.value?.case_no).toBe('CASE-2');
// 关键断言:只有新版 Case 真正落到 activeCase 后,页面才接收可同步深链的目标。
expect(onReparseCaseReady).toHaveBeenCalledWith({ runNo: 'RUN-2', caseNo: 'CASE-2', documentId: 1 });
review.stopReparseCaseRefreshPolling();
vi.useRealTimers();
});
@@ -1250,6 +1463,110 @@ describe('useShippingOrderReview build eligibility writes', () => {
vi.useRealTimers();
});
it('[选法 2] defers review Case + Evidence load on a formal downstream work item', async () => {
api.getRun.mockResolvedValue({ run_no: 'RUN-1', summary: {}, items: [] });
api.getQueue.mockResolvedValue({
summary: { total: 1, needs_action: 0, processing: 0, completed: 1 },
items: [{
case_no: 'CASE-1', document_id: 1, status: 'confirmed',
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [],
has_formal_ot: true, confirmed_task_no: 'SN-1',
}],
});
api.getCase.mockClear();
api.getEvidence.mockClear();
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1' });
// 正式任务下游阶段:首屏不拉复核 Case 快照 + Evidence。
expect(api.getCase).not.toHaveBeenCalled();
expect(api.getEvidence).not.toHaveBeenCalled();
});
it('[选法 2] selectCase skips Case + Evidence on formal downstream nav items', async () => {
api.getRun.mockResolvedValue({
run_no: 'RUN-1',
summary: {},
items: [
{
case_no: 'CASE-1', document_id: 1, status: 'confirmed',
lifecycle_stage: 'freight_upload', lifecycle_entries: [],
has_formal_ot: true, confirmed_task_no: 'OT-1',
},
{
case_no: 'CASE-2', document_id: 2, status: 'confirmed',
lifecycle_stage: 'freight_upload', lifecycle_entries: [],
has_formal_ot: true, confirmed_task_no: 'OT-2',
},
],
});
api.getQueue.mockResolvedValue({
summary: { total: 2, needs_action: 0, processing: 0, completed: 2 },
items: [
{
case_no: 'CASE-1', document_id: 1, status: 'confirmed',
lifecycle_stage: 'freight_upload', lifecycle_entries: [],
has_formal_ot: true, confirmed_task_no: 'OT-1',
},
{
case_no: 'CASE-2', document_id: 2, status: 'confirmed',
lifecycle_stage: 'freight_upload', lifecycle_entries: [],
has_formal_ot: true, confirmed_task_no: 'OT-2',
},
],
});
api.getCase.mockClear();
api.getEvidence.mockClear();
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1' });
api.getCase.mockClear();
api.getEvidence.mockClear();
await review.selectCase('CASE-2');
expect(api.getCase).not.toHaveBeenCalled();
expect(api.getEvidence).not.toHaveBeenCalled();
expect(review.requestedCaseNo.value).toBe('CASE-2');
expect(review.activeCase.value).toBeNull();
expect(review.evidence.value).toEqual([]);
});
it('[选法 2] loadReviewCase lazily fetches review Case + Evidence on demand', async () => {
api.getCase.mockClear();
api.getEvidence.mockClear();
api.getCase.mockResolvedValue({
case: buildCase({ case_no: 'CASE-1' }),
projection_version: 1,
loading_context: null,
});
api.getEvidence.mockResolvedValue({ case_no: 'CASE-1', items: [] });
const review = useShippingOrderReview();
await review.loadReviewCase('CASE-1');
expect(api.getCase).toHaveBeenCalledWith('CASE-1');
expect(api.getEvidence).toHaveBeenCalledWith('CASE-1');
});
it('[选法 2] loadReviewCase can skip Evidence for fulfillment_prep write-path debt', async () => {
api.getCase.mockClear();
api.getEvidence.mockClear();
api.getCase.mockResolvedValue({
case: buildCase({ case_no: 'CASE-1' }),
projection_version: 1,
loading_context: null,
});
const review = useShippingOrderReview();
await review.loadReviewCase('CASE-1', { includeEvidence: false });
expect(api.getCase).toHaveBeenCalledWith('CASE-1');
expect(api.getEvidence).not.toHaveBeenCalled();
expect(review.activeCase.value?.case_no).toBe('CASE-1');
});
});
@@ -1295,7 +1612,7 @@ describe('inventory routing recovery', () => {
can_build: true,
status: 'ready',
line_projections: [{
line_key: 'line-pending',
draft_line_id: 'line-pending',
line_index: 0,
can_build: false,
block_reason: 'inventory_source_unavailable',
@@ -1309,7 +1626,7 @@ describe('inventory routing recovery', () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
expect(review.routingRecoveryLines.value).toHaveLength(1);
expect(review.routingRecoveryLines.value[0]?.line_key).toBe('line-pending');
expect(review.routingRecoveryLines.value[0]?.draft_line_id).toBe('line-pending');
});
it('reroutes inventory routing with idempotency_key and expected_draft_version', async () => {
@@ -1324,7 +1641,7 @@ describe('inventory routing recovery', () => {
expect(api.rerouteInventoryRouting).toHaveBeenCalledWith('CASE-1', {
expected_draft_version: 2,
idempotency_key: 'idem-reroute-1',
line_key: 'line-1',
draft_line_id: 'line-1',
});
expect(review.activeCase.value?.draft?.draft_version).toBe(3);
uuidSpy.mockRestore();
File diff suppressed because it is too large. Load diff
Loaded 100 of 691 files, more files were not shown because too many files have changed in this diff. Show more