Merge branch 'dev' into runny827

feat(training): 新增精益培训视频与周任务管理

# Conflicts:
#	backend/app/models/__init__.py
This commit is contained in:
runny committed 2026-09-08 18:30:09 +08:00
1 parent 85d27e9ffa
commit 91b7233872
812 files changed
+73763 -18908

No files matched your search

@@ -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,
};
}
@@ -3,6 +3,7 @@
* 常用问题 / FAQ 缓存创建与编辑居中弹窗。
* 依赖:QuestionFormState、admin 通用 modal 样式。
* 逻辑:QuestionsPage 打开本组件;提交时 emit save,由 composable 调 API。
* is_enabled 仅控制工作台首页入口;cache_enabled 单独控制聊天是否跳过 Dify。
*/
<script setup lang="ts">
import { computed } from 'vue';
@@ -86,13 +87,16 @@ const isStale = computed(() => Boolean(props.form.stale_at));
<label class="label-field">{{ t('admin.question.fields.sortOrder') }}</label>
<input v-model.number="form.sort_order" type="number" class="input-field text-sm" />
</div>
<div class="md:col-span-2 flex flex-wrap gap-6">
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
<input v-model="form.is_enabled" type="checkbox" class="accent-brand-600" />
<span>{{ t('admin.question.fields.isEnabled') }}</span>
<div class="md:col-span-2 space-y-3">
<label class="flex items-start gap-2 text-sm text-secondary cursor-pointer">
<input v-model="form.is_enabled" type="checkbox" class="mt-0.5 accent-brand-600" />
<span>
<span class="block">{{ t('admin.question.fields.isEnabled') }}</span>
<span class="block text-xs text-muted mt-0.5">{{ t('admin.question.fields.isEnabledHelp') }}</span>
</span>
</label>
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
<input v-model="form.cache_enabled" type="checkbox" class="accent-brand-600" />
<label class="flex items-start gap-2 text-sm text-secondary cursor-pointer">
<input v-model="form.cache_enabled" type="checkbox" class="mt-0.5 accent-brand-600" />
<span>{{ t('admin.question.fields.cacheEnabled') }}</span>
</label>
</div>
@@ -11,6 +11,7 @@ import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { createRandomUuid } from '@/shared/utils/id';
import {
approveOrderProfileTestSuite,
confirmOrderProfileBlindTestReviews,
@@ -36,7 +37,7 @@ const router = useRouter();
const message = useMessage();
const { t } = useI18n();
const profileId = Number(route.params.profileId);
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
const sessionId = String(route.query.editorSessionId || '').trim() || createRandomUuid();
const suite = ref<OrderProfileTestSuite | null>(null);
const availableSamples = ref<OrderProfileBlindTestAvailableSample[]>([]);
const selectedSampleKey = ref('');
@@ -11,6 +11,7 @@ import { useI18n } from 'vue-i18n';
import { ArrowLeft, ArrowRight, Check, FileText, Layers3, Sparkles } from 'lucide-vue-next';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { createRandomUuid } from '@/shared/utils/id';
import { getShippingOrderSchemaState } from '@/features/admin/api/shipping-order-schema.api';
import { completeOrderDocumentProfileWizard, getOrderProfileSampleTables, listOrderProfileSamples } from '@/features/admin/api/shipping-order-document-profile.api';
import type { OrderProfileSampleDocument } from '@/features/admin/types/shipping-order-document-profile.types';
@@ -33,7 +34,7 @@ const tables = ref<Array<{ table_id: string; page_no: number; row_count: number;
const identity = reactive<Identity>({ displayName: '', schemaId: 0 });
const documentId = ref(0);
const tableId = ref('');
const browserSessionId = crypto.randomUUID();
const browserSessionId = createRandomUuid();
let sampleRefreshTimer: ReturnType<typeof setTimeout> | null = null;
const publishedSchemas = computed(() => schemas.value.filter((item) => item.status === 'published'));
@@ -140,7 +141,7 @@ async function finish(enterEditor: boolean): Promise<void> {
document_id: documentId.value,
main_table_id: tableId.value,
browser_session_id: browserSessionId,
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
};
const profile = await completeOrderDocumentProfileWizard(payload);
message.success(t('admin.shippingOrderProfiles.created'));
@@ -4,11 +4,13 @@
依赖:受控预览 API、Schema API、DocumentCanvas、useOrderProfileValueAdapter、
XfaDatasetTree、XfaCollectionSelector、XfaSplitRulePanel、shippingOrderField.utils。
逻辑:PDF 与 XFA 共用同一 desk DOM(main + aside.config + OrderProfileDocumentCanvas);
XFA 仅在属性区插入读取方式/数据源/拆分/样本显示增量;OCR 建议进入普通建议区。
XFA 仅在属性区插入读取方式/数据源/拆分/样本显示增量;OCR 建议进入普通建议区;
未绑定订单字段框通过横幅 + 画布高亮强制展示,避免空白底图漏看导致发布失败。
-->
<script setup lang="ts">
import {
computed,
nextTick,
onBeforeUnmount,
onMounted,
reactive,
@@ -19,6 +21,7 @@ import { onBeforeRouteLeave, useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { BusinessError } from "@/shared/api/client";
import { useMessage } from "@/shared/composables/useMessage";
import { createRandomUuid } from "@/shared/utils/id";
import { getShippingOrderSchemaState } from "@/features/admin/api/shipping-order-schema.api";
import {
authorizeOrderProfilePreviewPages,
@@ -104,6 +107,7 @@ import {
toOrderProfileHeaderFieldRegion,
resolveCoordinateFieldScope,
isOrderProfileVisualFieldEligible,
isUnboundOrderFieldCanvasRegion,
buildAutomarkSuggestionSummary,
type AutomarkSuggestionContext,
} from "./orderProfileForm.utils";
@@ -193,6 +197,7 @@ const documentCanvas = ref<{
zoomOut: () => void;
resetZoom: () => void;
captureRegion: (region: OrderProfileRelativeRegion) => string | null;
scrollRegionIntoView?: (regionId: string) => void;
} | null>(null);
const previewState = ref<"idle" | "updating" | "ready" | "failed">("idle");
const canvasUnavailable = ref(false);
@@ -214,7 +219,7 @@ const documentAnchorNotice = ref('');
const history = ref<OrderProfileCanvasRegion[][]>([]);
const future = ref<OrderProfileCanvasRegion[][]>([]);
const editLeaseToken = ref<string | null>(null);
const editorSessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
const editorSessionId = String(route.query.editorSessionId || '').trim() || createRandomUuid();
const compactEditor = ref(false);
const saveState = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
@@ -506,9 +511,42 @@ const headerFields = computed<ShippingOrderFieldConfig[]>(
) || [],
);
const pageRegions = computed(() =>
regions.value.filter((item) => item.pageNo === pageNo.value),
regions.value.filter((item) => Number(item.pageNo) === Number(pageNo.value)),
);
/** 草稿中全部未绑定订单字段框(跨页);发布硬门禁同源,编辑时强制列出。 */
const unboundOrderFieldRegions = computed(() =>
regions.value.filter((item) => isUnboundOrderFieldCanvasRegion(item)),
);
const activePageHasLines = computed(() => pageRegions.value.some((item) => item.kind === 'line'));
/**
* 切到未绑定框所在页并选中,强制在画布上滚入视野以便删除。
* 核心逻辑:先 selectPage 再设 selectedId,并请求画布 scrollRegionIntoView。
*/
async function focusUnboundOrderFieldRegion(regionId: string): Promise<void> {
const target = unboundOrderFieldRegions.value.find((item) => item.id === regionId);
if (!target) return;
if (Number(target.pageNo) !== Number(pageNo.value)) {
await selectPage(Number(target.pageNo));
}
selectedId.value = target.id;
reservationIdRegionSelected.value = false;
await nextTick();
documentCanvas.value?.scrollRegionIntoView?.(target.id);
}
/**
* 一键删除全部未绑定订单字段框,避免签名空白区 12 个框只能逐个清。
* 核心逻辑:checkpoint 后过滤 regions,保留已绑定与非 order_field 区域。
*/
function clearUnboundOrderFieldRegions(): void {
if (!unboundOrderFieldRegions.value.length || saveState.value === 'readonly') return;
checkpoint();
const removed = new Set(unboundOrderFieldRegions.value.map((item) => item.id));
regions.value = regions.value.filter((item) => !removed.has(item.id));
if (selectedId.value && removed.has(selectedId.value)) selectedId.value = null;
scheduleAutosave();
}
const ensureTableRegionSetting = (targetPageNo: number) => {
tableRegionSettings[targetPageNo] ||= {
visualEvidenceSource: null,
@@ -546,7 +584,7 @@ const visualCanvas = computed<OrderProfileVisualCanvasAdapter>(() => {
actions: coordinateCanvasActions.value,
documentReady: Boolean(form.documentId && form.tableId),
preview: pdfPreviewGrant.value,
grant: previewPages.value?.pages.find((item) => item.page_no === pageNo.value) || null,
grant: previewPages.value?.pages.find((item) => Number(item.page_no) === Number(pageNo.value)) || null,
previewPagePath: valueAdapterKey.value === 'xfa_dataset'
? `/api/admin/shipping-notice/order-document-profiles/${active.value?.id || 0}/pdf-preview`
: `/api/admin/shipping-notice/order-document-profiles/${active.value?.id || 0}/preview-pages`,
@@ -719,7 +757,23 @@ const deskCanvasReadonly = computed(() => visualCanvas.value.canvasReadonly);
const deskCanvasWarningVisible = computed(() => visualCanvas.value.warningVisible);
const deskCanvasWarningText = computed(() => visualCanvas.value.warningText || '');
const onDeskCanvasRetry = () => visualCanvas.value.retryCanvas();
const onDeskCanvasLoadFailed = () => visualCanvas.value.reportCanvasLoadFailed();
/** 页图 token 失效时自动重签一批预览令牌,避免翻页后只能手动点「重试画布」。 */
let previewReauthInFlight = false;
const onDeskCanvasLoadFailed = async () => {
if (previewReauthInFlight) {
visualCanvas.value.reportCanvasLoadFailed();
return;
}
previewReauthInFlight = true;
try {
await loadPages();
canvasUnavailable.value = false;
} catch {
visualCanvas.value.reportCanvasLoadFailed();
} finally {
previewReauthInFlight = false;
}
};
const deskCanvasCanRender = computed(() => visualCanvas.value.canRender);
const deskCanvasRetryLabel = computed(() => visualCanvas.value.retryLabel);
const onDeskAcceptSuggestion = () => visualCanvas.value.acceptSuggestion();
@@ -1767,7 +1821,7 @@ const save = async (automatic = false) => {
expected_lock_version: existingProfile.lock_version,
browser_session_id: editorSessionId,
lease_token: editLeaseToken.value || '',
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
...(adapterPayload.splitRuleConfirmationTokens
? { split_rule_confirmation_tokens: adapterPayload.splitRuleConfirmationTokens }
: {}),
@@ -2086,7 +2140,7 @@ const decidePendingSuggestion = async (decision: 'accepted' | 'accepted_adjusted
await decideOrderDocumentProfileSuggestion(active.value.id, {
suggestion_id: item.id, suggestion_checksum: item.checksum, suggestion_summary: item.summary, decision,
adjustment_summary: adjustmentSummary,
browser_session_id: editorSessionId, lease_token: editLeaseToken.value, operation_id: crypto.randomUUID(),
browser_session_id: editorSessionId, lease_token: editLeaseToken.value, operation_id: createRandomUuid(),
});
if (decision !== 'rejected') {
checkpoint();
@@ -2336,9 +2390,11 @@ const schedulePreview = () => {
* 签发当前样本的受控画布预览。
* 核心逻辑:普通坐标 PDF 使用服务端 PDFium PNG,保证内嵌繁体字形一致;只有显式
* XFA datasets 模板才保留 PDF.js 原 PDF 渲染,以显示动态表单外观。
* 不得把当前页强制打回第 1 页,否则第 2 页未绑定框会从画布过滤掉只剩顶部横幅。
*/
const loadPages = async () => {
if (!active.value || !form.documentId) return;
const preferredPageNo = Math.max(1, Number(pageNo.value) || 1);
try {
if (valueAdapterKey.value === 'xfa_dataset') {
previewPages.value = null;
@@ -2347,13 +2403,15 @@ const loadPages = async () => {
pdfPreviewGrant.value = null;
previewPages.value = await authorizeOrderProfilePreviewPages(active.value.id, form.documentId);
}
pageNo.value = 1;
pdfPageCount.value = previewPages.value?.page_count || 1;
const pageCount = Math.max(1, Number(previewPages.value?.page_count) || pdfPageCount.value || 1);
pdfPageCount.value = pageCount;
pageNo.value = Math.min(preferredPageNo, pageCount);
canvasUnavailable.value = false;
} catch {
pdfPreviewGrant.value = null;
previewPages.value = null;
pdfPageCount.value = 1;
pageNo.value = 1;
canvasUnavailable.value = true;
}
};
@@ -2374,14 +2432,15 @@ const reprocessCurrentSampleLayout = async (): Promise<void> => {
reparsingLayout.value = false;
}
};
/** PDF.js 已在内存中持有原件,切页只切换页码,避免消费新的预览令牌。 */
/** PDF.js 已在内存中持有原件,切页只切换页码;PNG 页图由画布按页缓存,避免一次性 token 翻页失效。 */
/** 切换 PDF 页时同步选择该页表格,使局部候选与当前标注页使用同一份坐标证据。 */
const selectPage = async (nextPageNo: number) => {
if (nextPageNo === pageNo.value) return;
pageNo.value = nextPageNo;
selectedId.value = null;
canvasUnavailable.value = false;
// 翻页只改变当前页预览表,模板主表仍由 mainTableId 单独冻结。
const pageTable = sampleTables.value.find((item) => item.page_no === nextPageNo);
const pageTable = sampleTables.value.find((item) => Number(item.page_no) === Number(nextPageNo));
form.tableId = pageTable?.table_id || '';
await refreshOrderFieldSuggestionValues();
};
@@ -2567,7 +2626,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
}];
}),
...(definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
const pageNo = item.page_scope === "exact_page" ? item.page_no || 1 : 1;
const regionPageNo = item.page_scope === "exact_page" ? Number(item.page_no) || 1 : 1;
if (!item.anchor?.region || !item.absolute_value_region) {
return [{
id: `unbound-${item.layout_id}`,
@@ -2575,7 +2634,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
label: item.label,
region: item.fallback_value_region || { x0: .1, y0: .1, x1: .2, y1: .15 },
fieldCode: null,
pageNo,
pageNo: regionPageNo,
}];
}
const anchor = item.anchor.region;
@@ -2585,7 +2644,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
label: item.anchor.text,
region: anchor,
orderFieldId: item.layout_id,
pageNo,
pageNo: regionPageNo,
}, {
id: `unbound-${item.layout_id}`,
kind: "order_field" as const,
@@ -2596,7 +2655,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
fieldCode: null,
orderFieldId: item.layout_id,
valueMode: item.value_mode,
pageNo,
pageNo: regionPageNo,
}];
}),
...(definition.order_field_layouts || []).filter((item) => !item.anchor).map((item) => ({
@@ -2700,7 +2759,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
const acquireEditLease = async (profileId: number): Promise<void> => {
const lease = await acquireOrderDocumentProfileEditLease(profileId, {
browser_session_id: editorSessionId,
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
});
editLeaseToken.value = lease.lease_token;
startLeaseRenewal();
@@ -2716,7 +2775,7 @@ const renewEditLease = async (): Promise<void> => {
const lease = await renewOrderDocumentProfileEditLease(active.value.id, {
browser_session_id: editorSessionId,
lease_token: editLeaseToken.value,
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
});
editLeaseToken.value = lease.lease_token;
} catch (error) {
@@ -2805,8 +2864,24 @@ const edit = async (profile: ShippingOrderDocumentProfile) => {
form.tableId = visualTableId;
pageNo.value = sampleTables.value.find((item) => item.table_id === visualTableId)?.page_no || pageNo.value;
}
// 未绑定订单字段常落在签名页;优先停在含未绑定框的页,再签发预览(loadPages 必须保留该页码)。
const firstUnbound = unboundOrderFieldRegions.value[0];
if (
firstUnbound
&& !unboundOrderFieldRegions.value.some((item) => Number(item.pageNo) === Number(pageNo.value))
) {
pageNo.value = Number(firstUnbound.pageNo) || pageNo.value;
}
await refreshAutomarkSampleReadiness();
await loadPages();
// loadPages 保留 preferred 页;若预览页数更短则已钳制。再确保未绑定页仍可见。
if (
firstUnbound
&& !unboundOrderFieldRegions.value.some((item) => Number(item.pageNo) === Number(pageNo.value))
&& Number(firstUnbound.pageNo) <= Number(pdfPageCount.value)
) {
pageNo.value = Number(firstUnbound.pageNo);
}
} catch (error) {
fail(error);
} finally {
@@ -2887,7 +2962,7 @@ const recoverEditLease = async (confirmTakeover = false) => {
try {
const lease = await acquireOrderDocumentProfileEditLease(active.value.id, {
browser_session_id: editorSessionId,
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
confirm_takeover: confirmTakeover,
});
editLeaseToken.value = lease.lease_token;
@@ -3050,7 +3125,7 @@ onBeforeUnmount(() => {
void releaseOrderDocumentProfileEditLease(active.value.id, {
browser_session_id: editorSessionId,
lease_token: editLeaseToken.value,
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
});
}
});
@@ -3167,6 +3242,40 @@ onBeforeUnmount(() => {
</div>
</div>
</section>
<section
v-if="unboundOrderFieldRegions.length"
class="unbound-regions-banner"
:aria-label="t('admin.shippingOrderProfiles.workbench.unboundRegionsBannerAria')"
>
<div class="unbound-regions-banner__heading">
<p>
{{ t('admin.shippingOrderProfiles.workbench.unboundRegionsBanner', { count: unboundOrderFieldRegions.length }) }}
</p>
<button
type="button"
class="btn-secondary unbound-regions-banner__clear"
:disabled="saveState === 'readonly'"
@click="clearUnboundOrderFieldRegions"
>
{{ t('admin.shippingOrderProfiles.workbench.clearUnboundRegions') }}
</button>
</div>
<div class="unbound-regions-banner__list">
<button
v-for="region in unboundOrderFieldRegions"
:key="region.id"
type="button"
class="unbound-regions-banner__item"
:class="{ active: selectedId === region.id }"
@click="() => void focusUnboundOrderFieldRegion(region.id)"
>
{{ t('admin.shippingOrderProfiles.workbench.unboundRegionChip', {
page: region.pageNo,
label: region.label,
}) }}
</button>
</div>
</section>
<OrderProfileDocumentCanvas
v-if="deskCanvasCanRender"
ref="documentCanvas"
@@ -4207,6 +4316,49 @@ onBeforeUnmount(() => {
.editor-workbench .config { max-height: calc(100vh - 5rem); overflow-y: auto; }
.editor-bottom-drawer { max-width: none; border-top: 1px solid #334155; background: #f8fafc; }
.automark-status-panel { position: sticky; top: .5rem; z-index: 6; display: grid; gap: .65rem; margin: 0 0 .75rem; border: 1px solid #7dd3fc; border-radius: .45rem; background: #f0f9ff; padding: .75rem .9rem; color: #164e63; box-shadow: 0 8px 20px rgb(14 116 144 / .12); }
.unbound-regions-banner {
position: sticky;
top: .5rem;
z-index: 6;
display: grid;
gap: .55rem;
margin: 0 0 .75rem;
border: 1px solid #f59e0b;
border-radius: .45rem;
background: #fffbeb;
padding: .75rem .9rem;
color: #92400e;
box-shadow: 0 8px 20px rgb(180 83 9 / .12);
}
.unbound-regions-banner p { margin: 0; font-size: .8rem; font-weight: 650; }
.unbound-regions-banner__heading {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: .55rem;
}
.unbound-regions-banner__clear { min-height: 1.9rem; padding-inline: .7rem; font-size: .72rem; }
.unbound-regions-banner__list { display: flex; flex-wrap: wrap; gap: .4rem; }
.unbound-regions-banner__item {
display: inline-flex;
max-width: 100%;
min-height: 1.8rem;
align-items: center;
border: 1px solid #d97706;
border-radius: .35rem;
background: #fff7ed;
padding: .2rem .55rem;
color: #9a3412;
font-size: .72rem;
cursor: pointer;
}
.unbound-regions-banner__item:hover,
.unbound-regions-banner__item.active {
border-color: #b45309;
background: #fdba74;
color: #7c2d12;
}
.automark-status-panel__heading { display: flex; align-items: flex-start; justify-content: space-between; gap: .75rem; }
.automark-status-panel__heading strong { display: block; color: #0c4a6e; font-size: .82rem; }
.automark-status-panel__heading p { margin: .2rem 0 0; color: #475569; font-size: .75rem; }
@@ -10,6 +10,7 @@ import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { createRandomUuid } from '@/shared/utils/id';
import {
acquireOrderDocumentProfileEditLease,
confirmOrderProfilePublishCheck,
@@ -31,7 +32,7 @@ const runs = ref<OrderProfileValidationRun[]>([]);
const report = ref<OrderProfilePublishCheckReport | null>(null);
const confirmed = ref<string[]>([]);
const busy = ref(false);
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
const sessionId = String(route.query.editorSessionId || '').trim() || createRandomUuid();
const leaseToken = ref('');
const validationRun = computed(() => runs.value.find((item) => item.run_type === 'current_sample' && item.status === 'passed') || null);
@@ -92,7 +93,7 @@ async function ensureLease(): Promise<boolean> {
try {
leaseToken.value = (await acquireOrderDocumentProfileEditLease(profileId, {
browser_session_id: sessionId,
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
})).lease_token;
return true;
} catch (error) {
@@ -121,7 +122,7 @@ async function createReport(): Promise<void> {
overlap_validation_run_id: overlapRun.value?.id,
browser_session_id: sessionId,
lease_token: leaseToken.value,
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
});
confirmed.value = [];
await loadRuns();
@@ -141,7 +142,7 @@ async function publish(): Promise<void> {
confirmed_warning_keys: confirmed.value,
browser_session_id: sessionId,
lease_token: leaseToken.value,
operation_id: crypto.randomUUID(),
operation_id: createRandomUuid(),
});
await router.replace({
name: 'AdminShippingOrderDocumentProfileVersionDetail',
@@ -11,6 +11,7 @@ import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { createRandomUuid } from '@/shared/utils/id';
import { getShippingOrderSchemaVersion } from '@/features/admin/api/shipping-order-schema.api';
import {
acquireOrderDocumentProfileEditLease,
@@ -42,7 +43,7 @@ const leaseToken = ref('');
const profile = ref<ShippingOrderDocumentProfile | null>(null);
const sample = ref<OrderProfileBoundSample | null>(null);
const fieldNames = ref(new Map<string, string>());
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
const sessionId = String(route.query.editorSessionId || '').trim() || createRandomUuid();
const blindTestSuite = ref<OrderProfileTestSuite | null>(null);
const validationEvidence = computed<OrderProfileValidationEvidence | null>(() => {
const raw = sampleRun.value?.summary?.validation_evidence;
@@ -206,7 +207,7 @@ async function ensureLease(): Promise<boolean> {
if (leaseToken.value) return true;
try {
leaseToken.value = (await acquireOrderDocumentProfileEditLease(profileId, {
browser_session_id: sessionId, operation_id: crypto.randomUUID(),
browser_session_id: sessionId, operation_id: createRandomUuid(),
})).lease_token;
return true;
} catch (error) { report(error); return false; }
@@ -221,7 +222,7 @@ async function validateCurrentDraft(): Promise<void> {
}
executing.value = true;
try {
const payload = () => ({ browser_session_id: sessionId, lease_token: leaseToken.value, operation_id: crypto.randomUUID() });
const payload = () => ({ browser_session_id: sessionId, lease_token: leaseToken.value, operation_id: createRandomUuid() });
await runOrderProfileInstantCheck(profileId, payload());
await runOrderProfileCurrentSample(profileId, { ...payload(), sample_binding_id: sample.value.id });
await loadRuns();
@@ -104,6 +104,44 @@ describe('OrderProfileDocumentCanvas PDF preview', () => {
);
});
it('force-highlights unbound order-field boxes on blank page imagery', async () => {
const wrapper = mount(OrderProfileDocumentCanvas, {
props: {
profileId: 5,
grant: { page_no: 2, preview_token: 'page-token' },
previewPagePath: '/api/admin/shipping-notice/order-document-profiles/5/preview-pages',
regions: [{
id: 'unbound-order_field_2__1',
kind: 'order_field',
label: 'Sign12 · 待绑定列 1',
pageNo: 2,
fieldCode: null,
region: { x0: .02, y0: .89, x1: .15, y1: .92 },
}],
pageNo: 2,
pageCount: 2,
},
global: {
plugins: [createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
admin: { shippingOrderProfiles: { workbench: { unbound: '待绑定', pagePreviewAlt: 'page' } } },
},
},
})],
},
});
await flushPromises();
// 关键断言:未绑定框必须带 region--unbound,否则签名空白底图上看不见。
const region = wrapper.find('.region--unbound');
expect(region.exists()).toBe(true);
expect(region.classes()).toContain('region-order_field');
expect(region.attributes('aria-label')).toContain('待绑定');
});
it('captures the selected XFA appearance from the unscaled PDF.js canvas', async () => {
const drawImage = vi.fn();
const toDataURL = vi.fn(() => 'data:image/png;base64,canvas-crop');
@@ -1,8 +1,10 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue
用途:展示受控 PDF/XFA flatten 单页预览,并以相对坐标框支持选择、拖动和缩放区域。
依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion。
依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion、isUnboundOrderFieldCanvasRegion。
逻辑:父级签发单页令牌并提供分页动作;mode=readonly 时只允许查看/缩放/切页,不允许写入任何标注改动;
PNG 预览 token 为一次性消费,组件内按页缓存 blob,翻页回访不再重新拉 token;
未绑定订单字段框强制高亮(region--unbound),并暴露 scrollRegionIntoView 供横幅定位删除;
画布区域 aria-label 走四语言 i18n;可选 emptyHint/loadError 区分 XFA page_unavailable 与 PDF 缺样本空态。
-->
<script setup lang="ts">
@@ -11,6 +13,7 @@ import { useI18n } from 'vue-i18n';
import { Anchor, ArrowLeft, ArrowRight, Columns3, Copy, Eraser, MessageSquareText, Minus, Plus, Redo2, RotateCcw, Rows3, Save, TableProperties, Tag, TextCursorInput, Trash2, WandSparkles } from 'lucide-vue-next';
import { getAuthHeaders } from '@/shared/utils/auth';
import type { OrderProfileCanvasRegion, OrderProfilePreviewPageGrant } from '@/features/admin/types/shipping-order-document-profile.types';
import { isUnboundOrderFieldCanvasRegion } from '../orderProfileForm.utils';
import type { PDFDocumentProxy } from 'pdfjs-dist';
type PdfJsModule = typeof import('pdfjs-dist');
@@ -98,6 +101,10 @@ const internalLoadError = ref<string | null>(null);
const canvas = ref<HTMLElement | null>(null);
const viewport = ref<HTMLElement | null>(null);
const zoom = ref(1);
/** 按页缓存已消费 token 拉取的 PNG,翻页回访不再触发一次性 token 失效。 */
const pageImageCache = new Map<string, string>();
let loadGeneration = 0;
let cachedProfileId: number | null = null;
const zoomPercent = computed(() => Math.round(zoom.value * 100));
const pageInput = ref(props.pageNo);
type ResizeHandle = 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'nw';
@@ -132,26 +139,69 @@ const renderPdfPage = async (pdf: PDFDocumentProxy) => {
};
/**
* 下载一次性 PNG 并在组件卸载或切页时回收浏览器 blob。
* 核心逻辑:失败时写入 internalLoadError 并 emit loadFailed,避免误导为「未绑定样本」。
* 回收某次会话内全部页图 blob;切换样本 Profile 或卸载时调用。
*/
const clearPageImageCache = () => {
for (const url of pageImageCache.values()) URL.revokeObjectURL(url);
pageImageCache.clear();
inflightPageLoads.clear();
};
/** 同一页的并发拉取共用一个 Promise,成功后必入缓存(即使请求已过期)。 */
const inflightPageLoads = new Map<string, Promise<string>>();
/**
* 拉取单页 PNG;命中缓存或 in-flight 时不重复请求。
*/
const fetchPageImage = async (
previewPath: string,
grant: { page_no: number; preview_token: string },
): Promise<string> => {
const cacheKey = String(grant.page_no);
const cached = pageImageCache.get(cacheKey);
if (cached) return cached;
const inflight = inflightPageLoads.get(cacheKey);
if (inflight) return inflight;
const pending = (async () => {
const response = await fetch(
`${previewPath}/${grant.page_no}?preview_token=${encodeURIComponent(grant.preview_token)}`,
{ headers: getAuthHeaders(), cache: 'no-store' },
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const blobUrl = URL.createObjectURL(await response.blob());
pageImageCache.set(cacheKey, blobUrl);
return blobUrl;
})().finally(() => {
inflightPageLoads.delete(cacheKey);
});
inflightPageLoads.set(cacheKey, pending);
return pending;
};
/**
* 下载页 PNG;同页再次展示走缓存。后端 grant 在 TTL 内可重复 get,缓存作防御性加速。
* 核心逻辑:generation 守卫丢掉过期 UI 更新;页图本身仍保留在 cache 供回访。
*/
const loadPage = async () => {
if (!props.profileId || (!props.grant && !props.pdfPreview)) {
URL.revokeObjectURL(imageUrl.value);
const generation = ++loadGeneration;
if (cachedProfileId !== props.profileId) {
clearPageImageCache();
cachedProfileId = props.profileId;
}
if (!props.profileId || (!props.grant && !props.pdfPreview)) {
imageUrl.value = '';
pdfRendered.value = false;
pdfRendered.value = false;
internalLoadError.value = null;
return;
}
loading.value = true;
URL.revokeObjectURL(imageUrl.value);
imageUrl.value = '';
pdfRendered.value = false;
pdfRendered.value = false;
internalLoadError.value = null;
try {
const previewPath = props.previewPagePath
|| `/api/admin/shipping-notice/order-document-profiles/${props.profileId}/preview-pages`;
if (props.pdfPreview) {
imageUrl.value = '';
const response = await fetch(
`${previewPath}?preview_token=${encodeURIComponent(props.pdfPreview.preview_token)}`,
{ headers: getAuthHeaders(), cache: 'no-store' },
@@ -160,31 +210,38 @@ const loadPage = async () => {
const pdfjs = await loadPdfJs();
const bytes = new Uint8Array(await response.arrayBuffer());
pdfDocument = await pdfjs.getDocument({ data: bytes, enableXfa: true }).promise;
if (generation !== loadGeneration) return;
emit('pageCount', pdfDocument.numPages);
await renderPdfPage(pdfDocument);
return;
}
const grant = props.grant;
if (!grant) throw new Error('PDF preview grant is unavailable');
const response = await fetch(
`${previewPath}/${grant.page_no}?preview_token=${encodeURIComponent(grant.preview_token)}`,
{ headers: getAuthHeaders(), cache: 'no-store' },
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
imageUrl.value = URL.createObjectURL(await response.blob());
const blobUrl = await fetchPageImage(previewPath, grant);
if (generation !== loadGeneration) return;
imageUrl.value = blobUrl;
} catch {
if (generation !== loadGeneration) return;
const fallback = props.grant ? pageImageCache.get(String(props.grant.page_no)) : null;
if (fallback) {
imageUrl.value = fallback;
internalLoadError.value = null;
return;
}
imageUrl.value = '';
internalLoadError.value = t('admin.shippingOrderProfiles.workbench.canvasUnavailable');
emit('loadFailed');
} finally {
loading.value = false;
if (generation === loadGeneration) loading.value = false;
}
};
/**
* 用户点击画布重试:清除内部错误并通知父级。
* 用户点击画布重试:清除内部错误并通知父级重新签发页令牌。
*/
const onRetryClick = () => {
internalLoadError.value = null;
clearPageImageCache();
emit('retry');
};
@@ -282,6 +339,10 @@ const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
}
return region.label;
}
// 未绑定框不拼「样本值不可用」,改用明确的待绑定徽标,避免与空白底图混淆。
if (isUnboundOrderFieldCanvasRegion(region)) {
return `${region.label} · ${t('admin.shippingOrderProfiles.workbench.unbound')}`;
}
const state = props.orderFieldValueState || 'idle';
const value = region.fieldCode ? props.orderFieldValues?.[region.fieldCode] : null;
const suffix = state === 'loading'
@@ -321,8 +382,33 @@ const captureRegion = (region: OrderProfileCanvasRegion['region']): string | nul
crop.getContext('2d')?.drawImage(source, x, y, clippedWidth, clippedHeight, 0, 0, clippedWidth, clippedHeight);
return crop.toDataURL('image/png');
};
defineExpose({ zoomIn: () => adjustZoom(.25), zoomOut: () => adjustZoom(-.25), resetZoom, captureRegion });
watch(() => [props.grant?.preview_token, props.pdfPreview?.preview_token], () => { void loadPage(); }, { immediate: true });
defineExpose({
zoomIn: () => adjustZoom(.25),
zoomOut: () => adjustZoom(-.25),
resetZoom,
captureRegion,
/**
* 将指定区域滚入画布视口中央,供未绑定框定位删除。
* @param regionId - 画布区域 id。
*/
scrollRegionIntoView: (regionId: string) => {
const viewportEl = viewport.value;
const target = canvas.value?.querySelector(`[data-region-id="${CSS.escape(regionId)}"]`) as HTMLElement | null;
if (!viewportEl || !target) return;
const viewportRect = viewportEl.getBoundingClientRect();
const targetRect = target.getBoundingClientRect();
const nextTop = viewportEl.scrollTop + (targetRect.top - viewportRect.top)
- (viewportRect.height / 2) + (targetRect.height / 2);
const nextLeft = viewportEl.scrollLeft + (targetRect.left - viewportRect.left)
- (viewportRect.width / 2) + (targetRect.width / 2);
viewportEl.scrollTo({
top: Math.max(0, nextTop),
left: Math.max(0, nextLeft),
behavior: 'smooth',
});
},
});
watch(() => [props.grant?.page_no, props.grant?.preview_token, props.pdfPreview?.preview_token], () => { void loadPage(); }, { immediate: true });
watch(() => props.pageNo, async (value) => {
pageInput.value = value;
if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument);
@@ -330,7 +416,13 @@ watch(() => props.pageNo, async (value) => {
watch(zoom, async () => {
if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument);
});
onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(imageUrl.value); });
onBeforeUnmount(() => {
endMove();
endPan();
endCreation();
clearPageImageCache();
imageUrl.value = '';
});
</script>
<template>
@@ -409,7 +501,16 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
role="button"
tabindex="0"
class="region"
:class="[`region-${region.kind}`, { selected: selected.has(region.id), 'region-preview': region.isPreview }, region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '']"
:data-region-id="region.id"
:class="[
`region-${region.kind}`,
{
selected: selected.has(region.id),
'region-preview': region.isPreview,
'region--unbound': isUnboundOrderFieldCanvasRegion(region),
},
region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '',
]"
:style="{ left: `${region.region.x0 * 100}%`, top: `${region.region.y0 * 100}%`, width: `${(region.region.x1 - region.region.x0) * 100}%`, height: `${(region.region.y1 - region.region.y0) * 100}%` }"
:aria-label="displayRegionLabel(region)"
@pointerdown.stop="beginDrag($event, region, 'move')"
@@ -502,6 +603,24 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
.region-header_field .region-label, .region-header_field .resize-handle { background: #b45309; }
.region-order_field { z-index: 2; border: 1.5px solid #22c55e; background: rgb(34 197 94 / .08); }
.region-order_field .region-label, .region-order_field .resize-handle { background: #15803d; }
/* 未绑定订单字段:底图常为空白(如签名控件),必须用高对比框强制可见。 */
.region--unbound {
z-index: 6;
min-width: 14px;
min-height: 14px;
border: 2.5px solid #d97706;
background: rgb(245 158 11 / .42);
box-shadow: 0 0 0 2px rgb(255 255 255 / .95), 0 0 14px rgb(245 158 11 / .75);
}
.region--unbound .region-label {
top: 0;
left: 0;
max-width: 100%;
border-radius: 0;
background: #b45309;
white-space: normal;
}
.region--unbound .resize-handle { background: #b45309; }
.region-order_anchor { z-index: 2; border: 1.5px solid #a855f7; background: rgb(168 85 247 / .08); }
.region-order_anchor .region-label, .region-order_anchor .resize-handle { background: #7e22ce; }
.region-document_anchor_label { z-index: 2; border: 1.5px solid #0ea5e9; background: rgb(14 165 233 / .1); }
@@ -10,6 +10,7 @@ import { computed, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { createRandomUuid } from '@/shared/utils/id';
import {
previewOrderProfileSampleXfaSplitRules,
} from '@/features/admin/api/shipping-order-document-profile.api';
@@ -97,9 +98,10 @@ const showUnsavedConfirmBanner = computed(() => (
/**
* 生成 seg-/rule-/stage- 前缀的客户端 UUID(无连字符)。
* HTTP 非安全上下文亦可用(经 createRandomUuid 降级)。
*/
function newClientId(prefix: 'seg' | 'rule' | 'stage'): string {
return `${prefix}-${crypto.randomUUID().replace(/-/g, '')}`;
return `${prefix}-${createRandomUuid().replace(/-/g, '')}`;
}
/**
@@ -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) => {
@@ -29,10 +29,18 @@ import {
toOrderProfileHeaderFieldRegion,
resolveCoordinateFieldScope,
isOrderProfileVisualFieldEligible,
isUnboundOrderFieldCanvasRegion,
buildAutomarkSuggestionSummary,
} from './orderProfileForm.utils';
describe('order profile form rules', () => {
it('marks order fields without fieldCode as unbound for forced canvas display', () => {
// 关键断言:无 Schema 绑定的订单字段框必须被识别,供画布高亮与发布前横幅共用。
expect(isUnboundOrderFieldCanvasRegion({ kind: 'order_field', fieldCode: null })).toBe(true);
expect(isUnboundOrderFieldCanvasRegion({ kind: 'order_field', fieldCode: 'currency' })).toBe(false);
expect(isUnboundOrderFieldCanvasRegion({ kind: 'header_field', fieldCode: null })).toBe(false);
});
it('restores a Reservation ID region from a Vue reactive profile without structured-clone failure', () => {
const persisted = reactive({
region: { x0: .05, y0: .71, x1: .28, y1: .73 },
@@ -2,7 +2,8 @@
* features/admin/modules/shipping-order-document-profiles/orderProfileForm.utils.ts
* 用途:构造可视化订单模板的白名单列规则、明细字段分组,并控制样本表格配置区的安全显示。
* 依赖:订单 Profile DTO。
* 逻辑:页面状态只允许 direct 或已注册复合解析器;同一目标字段跨列只能出现一次。
* 逻辑:页面状态只允许 direct 或已注册复合解析器;同一目标字段跨列只能出现一次;
* 另提供「未绑定订单字段」判定,供画布强制高亮与编辑横幅共用。
*/
import type {
@@ -39,6 +40,17 @@ export const isOrderProfileVisualFieldEligible = (
&& (usesExternalValueSource || Boolean(field.allowed_sources?.includes('pdf_coordinate')))
);
/**
* 判断画布区域是否为「未绑定 Schema 字段」的订单字段框。
* 核心逻辑:仅 order_field 且无 fieldCode 视为未绑定;这些框会写入
* draft_unbound_order_field_layouts 并在发布时硬阻断,必须在画布强制可见。
* @param region - 画布区域。
* @returns 是否需要未绑定高亮与横幅列出。
*/
export const isUnboundOrderFieldCanvasRegion = (
region: Pick<OrderProfileCanvasRegion, 'kind' | 'fieldCode'>,
): boolean => region.kind === 'order_field' && !region.fieldCode;
/**
* 将画布中的视觉表头文字转换为 v2 字段区域。
* 核心逻辑:视觉位置不是业务 scope;调用方必须按 Schema 传入 header/line,
@@ -2,7 +2,8 @@
* features/admin/modules/shipping-order-document-profiles/orderProfileReadonlyCanvas.utils.spec.ts
* 用途:验证版本只读画布完整恢复模板定义中的诊断区域。
* 依赖:Vitest、orderProfileReadonlyCanvas.utils。
* 逻辑:已发布版本的必需锚点必须同时显示标签框和值框,且区域 ID 与冻结诊断接口一致。
* 逻辑:已发布版本的必需锚点必须同时显示标签框和值框,且区域 ID 与冻结诊断接口一致;
* 仅含 fallback 的未绑定订单字段框也必须恢复,供签名空白区强制可见。
*/
import { describe, expect, it } from 'vitest';
@@ -40,4 +41,40 @@ describe('buildOrderProfileReadonlyRegions', () => {
expect.objectContaining({ id: 'plant_address_value', kind: 'document_anchor_value', configuredValue: 'No. 88' }),
]));
});
it('restores fallback-only unbound order fields so blank signature areas stay visible', () => {
const profile = {
definition: {
document_match: { required_anchors: [], optional_anchors: [] },
table_regions: [],
order_field_layouts: [],
draft_unbound_order_field_layouts: [{
layout_id: 'order_field_2__1',
label: 'Sign12 · 待绑定列 1',
page_scope: 'exact_page',
page_no: 2,
anchor: null,
absolute_value_region: null,
fallback_value_region: { x0: .02, y0: .89, x1: .15, y1: .92 },
value_mode: 'single_line',
stop_anchors: [],
minimum_evidence_level: 'coordinate',
}],
},
} as unknown as ShippingOrderDocumentProfile;
const regions = buildOrderProfileReadonlyRegions(profile);
// 关键断言:无 anchor/absolute 时仍用 fallback 恢复未绑定框,否则签名空白区会漏展示。
expect(regions).toEqual(expect.arrayContaining([
expect.objectContaining({
id: 'unbound-order_field_2__1',
kind: 'order_field',
fieldCode: null,
pageNo: 2,
label: 'Sign12 · 待绑定列 1',
region: { x0: .02, y0: .89, x1: .15, y1: .92 },
}),
]));
});
});
@@ -85,6 +85,7 @@ export const buildOrderProfileReadonlyRegions = (
}),
...(definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
const pageNo = pageNoOf(item.page_scope, item.page_no);
// 仅有 fallback 的未绑定框也必须恢复;签名区底图常空白,缺框会导致发布前无法发现。
if (!item.anchor?.region || !item.absolute_value_region) {
return [{
id: `unbound-${item.layout_id}`,
@@ -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,6 +1,8 @@
/**
* features/admin/modules/wecom/composables/useWecomAdmin.ts
* 企业微信:绑定、系统配置、通知、登录审计。
* 依赖:admin.api、useMessage、wecom 展示工具、PaginationBar 所需的审计分页状态。
* 逻辑:绑定走服务端分页;登录审计仍一次拉取最近 200 条,由前端切片分页。
*/
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
@@ -60,7 +62,24 @@ export function useWecomAdmin() {
let wecomBindUserCloseTimer: ReturnType<typeof setTimeout> | null = null;
const wecomAuditSourceFilter = ref<'all' | 'wecom' | 'password'>('all');
const wecomAuditStatusFilter = ref<'all' | 'success' | 'failed'>('all');
const wecomAuditsPage = ref(1);
const wecomAuditsPageSize = ref(20);
const wecomAuditsPageSizeOptions = [10, 20, 50, 100] as const;
const filteredWecomLoginAudits = computed(() => wecomLoginAudits.value);
const wecomAuditsTotal = computed(() => filteredWecomLoginAudits.value.length);
/**
* 对已拉取的审计列表做前端切片,不请求后端分页。
* 核心逻辑:按 pageSize 计算安全页码后 slice,避免筛选后落到空页。
*/
const pagedWecomLoginAudits = computed(() => {
const size = Math.max(1, Number(wecomAuditsPageSize.value) || 20);
const total = wecomAuditsTotal.value;
const pages = Math.max(1, Math.ceil(total / size));
const page = Math.min(Math.max(1, wecomAuditsPage.value), pages);
const start = (page - 1) * size;
return filteredWecomLoginAudits.value.slice(start, start + size);
});
const wecomNotifySettings = ref<WecomNotifySettings>({
enabled: true,
base_url: '',
@@ -158,6 +177,10 @@ export function useWecomAdmin() {
void loadWecomBindings();
};
/**
* 拉取登录审计(后端固定最近 200 条,前端再分页)。
* 核心逻辑:带上 source/status 筛选调用 listAdminWecomLoginAudits。
*/
const loadWecomAudits = async (): Promise<void> => {
try {
const params = new URLSearchParams({ limit: '200' });
@@ -466,6 +489,7 @@ export function useWecomAdmin() {
});
watch([wecomAuditSourceFilter, wecomAuditStatusFilter], () => {
wecomAuditsPage.value = 1;
void loadWecomAudits();
});
@@ -487,7 +511,12 @@ export function useWecomAdmin() {
wecomBoundOnly,
wecomAuditSourceFilter,
wecomAuditStatusFilter,
wecomAuditsPage,
wecomAuditsPageSize,
wecomAuditsPageSizeOptions,
wecomAuditsTotal,
filteredWecomLoginAudits,
pagedWecomLoginAudits,
wecomNotifySettings,
wecomNotifyEventsText,
wecomNotifyMetrics,
@@ -2,10 +2,13 @@
/**
* features/admin/modules/wecom/pages/WecomAuditsPage.vue
* 企微与密码登录审计列表。
* 依赖:WECOM_ADMIN_KEY、PaginationBar、formatLocalDateTime。
* 逻辑:表格渲染当前页切片;分页条对已拉取的最近 200 条做前端翻页。
*/
import { inject } from 'vue';
import { useI18n } from 'vue-i18n';
import { Download } from 'lucide-vue-next';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { formatLocalDateTime } from '@/shared/utils/dateTime';
import { WECOM_ADMIN_KEY } from '../wecom.context';
@@ -13,7 +16,12 @@ const { t } = useI18n();
const {
wecomAuditSourceFilter,
wecomAuditStatusFilter,
wecomAuditsPage,
wecomAuditsPageSize,
wecomAuditsPageSizeOptions,
wecomAuditsTotal,
filteredWecomLoginAudits,
pagedWecomLoginAudits,
exportWecomAudits,
getWecomAuditReasonText,
getWecomAuditMetaText,
@@ -57,7 +65,7 @@ const {
<tr v-if="filteredWecomLoginAudits.length === 0">
<td colspan="6" class="px-4 admin-table-empty">{{ t('admin.wecom.noAuditData') }}</td>
</tr>
<tr v-for="row in filteredWecomLoginAudits" :key="row.id">
<tr v-for="row in pagedWecomLoginAudits" :key="row.id">
<td class="px-4 py-3 text-xs text-muted whitespace-nowrap" :title="row.created_at || '-'">{{ formatLocalDateTime(row.created_at) }}</td>
<td class="px-4 py-3 text-xs text-secondary">{{ t('admin.wecom.sources.' + row.source) }}</td>
<td class="px-4 py-3 text-xs text-secondary">{{ row.username || '-' }}</td>
@@ -82,5 +90,13 @@ const {
</tbody>
</table>
</div>
<div class="px-4 pb-4 pt-2">
<PaginationBar
v-model:page="wecomAuditsPage"
v-model:page-size="wecomAuditsPageSize"
:total="wecomAuditsTotal"
:page-size-options="[...wecomAuditsPageSizeOptions]"
/>
</div>
</div>
</template>
@@ -2,11 +2,12 @@
/**
* features/admin/modules/wecom/pages/WecomSettingsPage.vue
* 企微系统配置、通知与集成复制。
* 依赖:WECOM_ADMIN_KEY、lucide CircleHelp。
* 逻辑:绑定概览卡片只在绑定管理页展示,本页仅编辑系统/通知配置。
*/
import { inject } from 'vue';
import { useI18n } from 'vue-i18n';
import { CircleHelp } from 'lucide-vue-next';
import WecomOverviewCards from '../components/WecomOverviewCards.vue';
import { WECOM_ADMIN_KEY } from '../wecom.context';
const { t } = useI18n();
@@ -28,8 +29,6 @@ const {
<template>
<div class="space-y-6">
<WecomOverviewCards />
<div class="card shadow-sm p-5 space-y-4">
<h3 class="font-semibold text-primary">{{ t('admin.wecom.systemSettings') }}</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
@@ -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')"
>
@@ -1,12 +1,16 @@
/**
* features/chat/components/ChatMessageList.vue
* 消息列表主区域:滚动容器、欢迎页、消息气泡与思考中占位。
* 用途:消息列表主区域(滚动容器、欢迎页、气泡与思考中占位)。
* 依赖:ChatMessageBubble、各类进度卡、chat.types。
* 逻辑:按 shouldRenderMessage 过滤;货代抽取卡按 run / upload_batch / client_submission 去重只留最后一张;
* 用户气泡在下方已有抽取进度卡时对附件启用 summaryOnly,避免与进度卡重复堆文件明细。
*/
<script setup lang="ts">
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 +49,8 @@ const {
toolRunProgressTitle: string;
showScrollToBottom: boolean;
hideWelcomePanel?: boolean;
/** 在途仓自动调拨 Agent:无消息时渲染专属首页入口区(替代通用欢迎面板)。 */
isInTransitTransferAgent?: boolean;
pinMessagesToBottom?: boolean;
/** 供父级滚动逻辑绑定 main 元素 */
scrollContainerHolder: { el: Ref<HTMLElement | null> };
@@ -63,6 +69,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) => {
@@ -79,7 +87,7 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
|| `${msg.role}:${msg.run_id || 'none'}:${String(msg.content || '').slice(0, 40)}:${index}`
);
/** 同一 Run 或同一次上传批次只展示最后一张状态卡,避免历史恢复/SSE 补帧造成重复窗口。 */
/** 同一 Run / 上传批次 / 提交幂等键只展示最后一张状态卡,避免历史恢复造成重复窗口。 */
const isDuplicateShippingExtractionMessage = (items: ChatMessage[], index: number): boolean => {
const current = items[index];
if (!current?.shipping_order_extraction_state) return false;
@@ -97,7 +105,12 @@ const isDuplicateShippingExtractionMessage = (items: ChatMessage[], index: numbe
|| current.shipping_order_extraction_state.uploadBatchId
|| '',
).trim();
if (!runIdentity && !batchIdentity) return false;
const submissionIdentity = String(
payload.shipping_order_extraction_client_submission_id
|| current.shipping_order_extraction_state.clientSubmissionId
|| '',
).trim();
if (!runIdentity && !batchIdentity && !submissionIdentity) return false;
return items.slice(index + 1).some((candidate) => {
if (!candidate?.shipping_order_extraction_state) return false;
const candidatePayload = candidate.payload && typeof candidate.payload === 'object'
@@ -114,8 +127,14 @@ const isDuplicateShippingExtractionMessage = (items: ChatMessage[], index: numbe
|| candidate.shipping_order_extraction_state.uploadBatchId
|| '',
).trim();
const candidateSubmissionIdentity = String(
candidatePayload.shipping_order_extraction_client_submission_id
|| candidate.shipping_order_extraction_state.clientSubmissionId
|| '',
).trim();
return Boolean(
(batchIdentity && candidateBatchIdentity === batchIdentity)
|| (submissionIdentity && candidateSubmissionIdentity === submissionIdentity)
|| (runIdentity && candidateRunIdentity === runIdentity),
);
});
@@ -134,6 +153,20 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
}
return true;
};
/**
* 用户消息与下一轮用户输入之间,是否已有货代订单抽取进度卡。
* 核心逻辑:有进度卡时附件区只留摘要,文件明细交给进度卡展示。
*/
const hasFollowingShippingProgressCard = (items: ChatMessage[], index: number): boolean => {
for (let i = index + 1; i < items.length; i += 1) {
const candidate = items[i];
if (!candidate) continue;
if (candidate.role === 'user') break;
if (candidate.shipping_order_extraction_state) return true;
}
return false;
};
</script>
<template>
@@ -144,7 +177,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 +186,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)"
@@ -169,6 +208,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
:shipping-handlers="shippingHandlers"
:training-handlers="trainingHandlers"
:compact-shipping-progress="compactShippingProgress"
:attachment-summary-only="hasFollowingShippingProgressCard(messages, index)"
@copy="emit('copy', { message: msg, index })"
@edit="emit('edit', $event)"
@resend="emit('resend', $event)"
@@ -196,7 +236,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>
@@ -1,22 +1,82 @@
/**
* features/chat/components/messages/ChatMessageAttachmentList.spec.ts
* 用途:校验已发送附件分层展示(chip / 摘要折叠 / 进度卡并存只留摘要)。
* 依赖:Vitest、Vue Test Utils、vue-i18n。
* 逻辑:覆盖 ≤3 chip、>3 摘要可展开、summaryOnly 不可展开。
*/
import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import { createI18n } from 'vue-i18n';
import ChatMessageAttachmentList from './ChatMessageAttachmentList.vue';
import type { ChatMessageAttachment } from '../../types/chat.types';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
attachment: {
summaryCount: '{count} 个附件',
expandList: '展开附件列表',
collapseList: '收起附件列表',
},
},
},
},
});
const makeAttachments = (count: number): ChatMessageAttachment[] =>
Array.from({ length: count }, (_, index) => ({
name: `file-${index + 1}.eml`,
type: 'document' as const,
source: 'local' as const,
size: 1024 * (index + 1),
extension: 'eml',
}));
describe('ChatMessageAttachmentList', () => {
it('keeps many sent attachments in a single horizontally scrollable row', () => {
it('renders compact chips when there are at most three attachments', () => {
const wrapper = mount(ChatMessageAttachmentList, {
props: {
attachments: [
{ name: 'one.eml', type: 'document', source: 'local', size: 1024, extension: 'eml' },
{ name: 'two.eml', type: 'document', source: 'local', size: 2048, extension: 'eml' },
{ name: 'three.eml', type: 'document', source: 'local', size: 3072, extension: 'eml' },
],
},
props: { attachments: makeAttachments(3) },
global: { plugins: [i18n] },
});
const list = wrapper.get('[data-testid="chat-message-attachment-list"]');
expect(list.classes()).toContain('overflow-x-auto');
expect(list.classes()).toContain('flex-nowrap');
expect(wrapper.findAll('article')).toHaveLength(3);
expect(wrapper.find('[data-testid="chat-message-attachment-chips"]').exists()).toBe(true);
expect(wrapper.findAll('[data-testid="chat-message-attachment-chip"]')).toHaveLength(3);
expect(wrapper.find('[data-testid="chat-message-attachment-summary"]').exists()).toBe(false);
});
it('collapses many attachments into a summary that expands into a scrollable list', async () => {
const wrapper = mount(ChatMessageAttachmentList, {
props: { attachments: makeAttachments(5) },
global: { plugins: [i18n] },
});
const summary = wrapper.get('[data-testid="chat-message-attachment-summary"]');
expect(summary.text()).toContain('5 个附件');
expect(wrapper.find('[data-testid="chat-message-attachment-expanded"]').exists()).toBe(false);
await summary.trigger('click');
const expanded = wrapper.get('[data-testid="chat-message-attachment-expanded"]');
expect(expanded.classes()).toContain('max-h-40');
expect(expanded.findAll('article')).toHaveLength(5);
});
it('keeps only the summary when a shipping progress card follows the message', async () => {
const wrapper = mount(ChatMessageAttachmentList, {
props: {
attachments: makeAttachments(2),
summaryOnly: true,
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="chat-message-attachment-chips"]').exists()).toBe(false);
const summary = wrapper.get('[data-testid="chat-message-attachment-summary"]');
expect(summary.text()).toContain('2 个附件');
await summary.trigger('click');
expect(wrapper.find('[data-testid="chat-message-attachment-expanded"]').exists()).toBe(false);
});
});
@@ -1,18 +1,49 @@
/**
* features/chat/components/messages/ChatMessageAttachmentList.vue
* 用途:在用户消息中展示已发送附件快照。
* 依赖:lucide 文件图标、attachmentCard.utils 的大小格式化、chat.types 的消息附件契约。
* 逻辑:ChatMessageBubble 将当前用户消息附件传入;本组件只读展示,不提供删除、重试或上传状态操作。
* 用途:在用户消息中分层展示已发送附件快照(少文件 chip / 多文件摘要折叠)。
* 依赖:lucide 图标、vue-i18n、attachmentCard.utils、chat.types。
* 逻辑:ChatMessageBubble 传入附件与 summaryOnly;≤3 用紧凑 chip,>3 默认摘要条可展开纵向列表;
* 下方已有货代进度卡时 summaryOnly=true,只留摘要避免与进度卡重复。
*/
<script setup lang="ts">
import { FileAudio, FileImage, FileText, FileVideo, Link2 } from 'lucide-vue-next';
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { ChevronDown, ChevronUp, FileAudio, FileImage, FileText, FileVideo, Link2, Paperclip } from 'lucide-vue-next';
import { formatAttachmentSize } from '../../utils/attachmentCard.utils';
import type { ChatMessageAttachment } from '../../types/chat.types';
const { attachments } = defineProps<{
/** 超过该数量后默认折叠为摘要条,避免气泡内横排大卡。 */
const CHIP_LIMIT = 3;
/** 展开列表内部最大高度(约 4~5 行)。 */
const EXPANDED_LIST_MAX_HEIGHT_CLASS = 'max-h-40';
const props = defineProps<{
attachments: ChatMessageAttachment[];
/** 下方已有货代进度卡时为 true:只显示摘要,不展开明细。 */
summaryOnly?: boolean;
}>();
const { t } = useI18n();
const expanded = ref(false);
const attachmentCount = computed(() => props.attachments.length);
const useChips = computed(() => !props.summaryOnly && attachmentCount.value > 0 && attachmentCount.value <= CHIP_LIMIT);
const useCollapsibleSummary = computed(() => !props.summaryOnly && attachmentCount.value > CHIP_LIMIT);
const showSummaryBar = computed(() => Boolean(props.summaryOnly) || useCollapsibleSummary.value);
const totalSizeLabel = computed(() => {
let total = 0;
let known = 0;
for (const item of props.attachments) {
if (typeof item.size === 'number' && Number.isFinite(item.size) && item.size >= 0) {
total += item.size;
known += 1;
}
}
if (!known) return '';
return formatAttachmentSize(total);
});
/** 根据附件来源与业务类型选择只读消息卡片图标。 */
function attachmentIcon(attachment: ChatMessageAttachment) {
if (attachment.source === 'remote') return Link2;
@@ -29,35 +60,104 @@ function attachmentBadge(attachment: ChatMessageAttachment): string {
if (attachment.source === 'remote') return 'URL';
return attachment.type.toUpperCase().slice(0, 5);
}
/** 切换多附件摘要的展开/收起;summaryOnly 时不可展开。 */
function toggleExpanded() {
if (props.summaryOnly) return;
expanded.value = !expanded.value;
}
</script>
<template>
<div
v-if="attachments.length > 0"
v-if="attachmentCount > 0"
data-testid="chat-message-attachment-list"
class="mb-2 flex w-full flex-nowrap justify-end gap-2 overflow-x-auto pb-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
class="mb-2 w-full"
>
<article
v-for="(attachment, attachmentIndex) in attachments"
:key="`${attachment.name}-${attachment.size ?? 'unknown'}-${attachmentIndex}`"
class="flex h-[68px] w-[250px] shrink-0 items-center gap-2.5 rounded-xl border border-default bg-surface px-3 py-2.5 shadow-sm dark:bg-slate-900"
:title="attachment.name"
<!-- ≤3:紧凑 chip,宽度自适应 -->
<div
v-if="useChips"
data-testid="chat-message-attachment-chips"
class="flex w-full flex-wrap justify-end gap-1.5"
>
<div
class="flex h-10 w-9 shrink-0 flex-col items-center justify-center rounded-lg bg-brand-50 text-brand-700 dark:bg-brand-900/30 dark:text-brand-300"
aria-hidden="true"
<article
v-for="(attachment, attachmentIndex) in props.attachments"
:key="`${attachment.name}-${attachment.size ?? 'unknown'}-${attachmentIndex}`"
class="flex h-10 max-w-[220px] items-center gap-2 rounded-lg border border-white/25 bg-white/95 px-2.5 text-slate-800 shadow-sm dark:border-white/10 dark:bg-slate-900/90 dark:text-slate-100"
:title="attachment.name"
data-testid="chat-message-attachment-chip"
>
<component :is="attachmentIcon(attachment)" class="h-4 w-4" />
<span class="mt-0.5 max-w-8 truncate text-[8px] font-bold leading-none">
{{ attachmentBadge(attachment) }}
</span>
</div>
<div class="min-w-0 flex-1">
<div class="truncate text-sm font-semibold text-primary">{{ attachment.name }}</div>
<div v-if="attachment.size !== undefined" class="mt-1 text-[11px] leading-none text-muted">
{{ formatAttachmentSize(attachment.size) }}
<div
class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-brand-50 text-brand-700 dark:bg-brand-900/40 dark:text-brand-300"
aria-hidden="true"
>
<component :is="attachmentIcon(attachment)" class="h-3.5 w-3.5" />
</div>
<div class="min-w-0 flex-1">
<div class="truncate text-xs font-semibold leading-tight">{{ attachment.name }}</div>
<div class="mt-0.5 flex items-center gap-1 text-[10px] leading-none text-slate-500 dark:text-slate-400">
<span>{{ attachmentBadge(attachment) }}</span>
<span v-if="attachment.size !== undefined">· {{ formatAttachmentSize(attachment.size) }}</span>
</div>
</div>
</article>
</div>
<!-- >3 或货代进度卡并存:摘要条 -->
<div v-else-if="showSummaryBar" class="flex w-full flex-col items-end gap-1.5">
<button
type="button"
data-testid="chat-message-attachment-summary"
class="inline-flex max-w-full items-center gap-2 rounded-lg border border-white/25 bg-white/15 px-3 py-2 text-left text-white transition hover:bg-white/20"
:class="props.summaryOnly ? 'cursor-default' : 'cursor-pointer'"
:aria-expanded="props.summaryOnly ? undefined : expanded"
:aria-controls="props.summaryOnly || !expanded ? undefined : 'chat-message-attachment-expanded'"
:aria-label="props.summaryOnly
? t('chat.attachment.summaryCount', { count: attachmentCount })
: (expanded ? t('chat.attachment.collapseList') : t('chat.attachment.expandList'))"
@click="toggleExpanded"
>
<Paperclip class="h-3.5 w-3.5 shrink-0 opacity-90" aria-hidden="true" />
<span class="truncate text-xs font-semibold">
{{ t('chat.attachment.summaryCount', { count: attachmentCount }) }}
</span>
<span v-if="totalSizeLabel" class="shrink-0 text-[11px] opacity-80">· {{ totalSizeLabel }}</span>
<component
:is="expanded ? ChevronUp : ChevronDown"
v-if="!props.summaryOnly"
class="h-3.5 w-3.5 shrink-0 opacity-80"
aria-hidden="true"
/>
</button>
<div
v-if="useCollapsibleSummary && expanded"
id="chat-message-attachment-expanded"
data-testid="chat-message-attachment-expanded"
class="w-full max-w-sm overflow-y-auto rounded-xl border border-white/20 bg-white/95 p-1.5 shadow-sm dark:bg-slate-900/95"
:class="EXPANDED_LIST_MAX_HEIGHT_CLASS"
>
<article
v-for="(attachment, attachmentIndex) in props.attachments"
:key="`expanded-${attachment.name}-${attachment.size ?? 'unknown'}-${attachmentIndex}`"
class="flex items-center gap-2 rounded-lg px-2 py-1.5 text-slate-800 dark:text-slate-100"
:title="attachment.name"
>
<div
class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-brand-50 text-brand-700 dark:bg-brand-900/40 dark:text-brand-300"
aria-hidden="true"
>
<component :is="attachmentIcon(attachment)" class="h-3.5 w-3.5" />
</div>
<div class="min-w-0 flex-1">
<div class="truncate text-xs font-semibold">{{ attachment.name }}</div>
<div class="mt-0.5 text-[10px] text-slate-500 dark:text-slate-400">
<span>{{ attachmentBadge(attachment) }}</span>
<span v-if="attachment.size !== undefined"> · {{ formatAttachmentSize(attachment.size) }}</span>
</div>
</div>
</article>
</div>
</article>
</div>
</div>
</template>
@@ -3,6 +3,7 @@
* 用途:渲染单条聊天消息,统一承接用户气泡、助手 Markdown、内嵌文件下载、请假/出货子组件与操作栏。
* 依赖:Vue computed、lucide 图标、消息附件/Leave/Shipping 子组件、chat.types 与页面级 handlers。
* 逻辑:由 ChatMessageList 按消息逐条挂载;货代履约写按钮不在气泡内渲染,仅展示只读卡与深链通知。
* 用户附件区支持 summaryOnly:下方已有抽取进度卡时只显示附件摘要。
* 兼容:同时承接采购合同审查、库存映射、订单提取和 Mermaid 展示。
*/
<script setup lang="ts">
@@ -14,6 +15,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';
@@ -59,6 +61,7 @@ const {
handlers,
leaveHandlers,
shippingHandlers,
attachmentSummaryOnly = false,
} = defineProps<{
message: ChatMessage;
index: number;
@@ -73,6 +76,8 @@ const {
shippingHandlers: ShippingMessageHandlers;
trainingHandlers: TrainingHandlers;
compactShippingProgress?: boolean;
/** 下方已有货代进度卡时,用户气泡附件只显示摘要。 */
attachmentSummaryOnly?: boolean;
}>();
const emit = defineEmits<{
@@ -94,6 +99,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'
@@ -722,6 +733,7 @@ function handleInlineDownload(file: InlineDownloadFile): void {
<ChatMessageAttachmentList
v-if="message.attachments?.length"
:attachments="message.attachments"
:summary-only="attachmentSummaryOnly"
/>
<div v-if="hasUserContent" class="whitespace-pre-wrap px-2.5 py-1">{{ message.content }}</div>
</template>
@@ -770,6 +782,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 ';
}
});
Loaded 100 of 812 files, more files were not shown because too many files have changed in this diff. Show more