Merge branch 'dev' into snow

# Conflicts:
#	backend/app/api/chat.py
#	backend/app/services/admin/permission_service.py
#	frontend/src/features/user/views/UserProfilePage.vue
This commit is contained in:
HTEWJ\26070045 committed 2026-09-23 14:34:20 +08:00
commit 5faf86b184
691 files changed
+55948 -17728

No files matched your search

@@ -289,6 +289,10 @@ export const createShippingInventoryStructureAnalysis = (file: File) => {
method: 'POST', body: form, ...auth(),
});
};
/** 读取标准异动字段目录(只读领域契约,供收料异动解析规则映射表单)。 */
export const fetchMovementFields = () => requestJson<Array<{ code: string; value_type: string; required: boolean; is_identity: boolean }>>(
'/api/admin/shipping-notice/movement-fields', auth(),
);
/** 用已分析的真实栏位创建库存文件解析方案草稿。 */
export const createShippingInventoryParsingDraftFromAnalysis = (id: number, payload: Record<string, unknown>) => requestJson<unknown>(
`/api/admin/shipping-notice/inventory-structure-analyses/${id}/create-profile-draft`,
@@ -0,0 +1,136 @@
/**
* features/admin/modules/integration-connector/IntegrationConnectorPage.spec.ts
* 用途:锁定凭据引用列表的重设计列——类型/账号/来源/启停开关,以及能力清单 tab 的激活与注册表渲染;
* 不再出现内部实现列(secret_ref 原文)与无行动价值的「更新时间」列。
* 依赖:vi.mock(useIntegrationConnectorAdmin)、@vue/test-utils、i18n。
* 逻辑:mock composable 返回固定 fixture(password 账密 + token 两条),断言
* 列表按类型标签/非密账号/来源本地化与布尔启停开关渲染。
*/
import { describe, expect, it, vi } from 'vitest';
import { defineComponent, h, ref } from 'vue';
import { mount } from '@vue/test-utils';
import { createMemoryHistory, createRouter } from 'vue-router';
import i18n from '@/i18n';
import IntegrationConnectorPage from './IntegrationConnectorPage.vue';
import { createEmptyBindingForm, createEmptyClientInstanceForm, createEmptyCredentialReferenceForm, createEmptyInterfaceDefinitionForm } from './types/integration-connector.types';
const mockState = vi.hoisted(() => {
const capabilities = [
{ name: 'in_transit_transfer.create_transfer', write: true, idempotency: 'invoice' },
{ name: 'in_transit_transfer.query_inventory', write: false, idempotency: 'none' },
{ name: 'in_transit_transfer.verify_duplicate', write: false, idempotency: 'invoice' },
];
const bindings = [
{
id: 1, capability: 'in_transit_transfer.query_inventory', context_selector_json: {},
client_instance_code: '1001', interface_definition_code: 'IF-A',
mapping_version: 1, priority: 0, environment: 'prod',
effective_from: null, effective_to: null, status: 'published',
},
];
const credentials = [
{
id: 1, code: 'tiptop-erp', secret_ref: 'db:tiptop-erp', secret_provider: 'db',
credential_type: 'password', secret_fields: { username: 'tiptop' }, has_secret: true,
version: 1, status: 'active', updated_at: '2026-09-21T18:30:00', last_verified_at: null,
},
{
id: 2, code: 'wms-token', secret_ref: 'db:wms-token', secret_provider: 'env',
credential_type: 'token', secret_fields: {}, has_secret: true,
version: 1, status: 'rotating', updated_at: null, last_verified_at: null,
},
];
const noop = () => vi.fn();
return { credentials, capabilities, bindings };
});
vi.mock('./composables/useIntegrationConnectorAdmin', () => ({
useIntegrationConnectorAdmin: () => ({
clients: ref([]), interfaces: ref([]), bindings: ref(mockState.bindings),
credentials: ref(mockState.credentials), capabilities: ref(mockState.capabilities), credentialTypes: ref([]),
isLoading: ref(false), activeEntity: ref('credential'), showFormModal: ref(false), isSaving: ref(false),
clientForm: ref(createEmptyClientInstanceForm()),
interfaceForm: ref(createEmptyInterfaceDefinitionForm()),
bindingForm: ref(createEmptyBindingForm()),
credentialForm: ref(createEmptyCredentialReferenceForm()),
showCallModal: ref(false), callCapability: ref(''), callParamsText: ref(''), callContextText: ref(''),
callResult: ref(null), callBusy: ref(false),
testingClientCode: ref(''), testResultText: ref(''),
lifecycleBusy: ref(false),
loadAll: vi.fn(), openCreateModal: vi.fn(), openEditModal: vi.fn(), closeFormModal: vi.fn(),
saveActive: vi.fn(), testConnection: vi.fn(), openCallModal: vi.fn(), closeCallModal: vi.fn(),
runCall: vi.fn(), deleteClient: vi.fn(), toggleClient: vi.fn(), toggleCredential: vi.fn(),
changeInterfaceLifecycle: vi.fn(), changeBindingLifecycle: vi.fn(),
}),
}));
function mountPage() {
const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/:pathMatch(.*)*', component: { template: '<div/>' } }] });
const Harness = defineComponent({
setup() {
return () => h('div', { style: 'width: 1400px' }, [h(IntegrationConnectorPage)]);
},
});
return mount(Harness, { global: { plugins: [i18n, router] } });
}
describe('IntegrationConnectorPage credential list', () => {
it('按重设计列渲染:类型徽标 + 非密账号 + 来源徽标 + 启停开关,不再显示 secret_ref 原文', () => {
const wrapper = mountPage();
const text = wrapper.text();
// password 类型:类型标签 + 非密账号(username 值)+ 来源本地化;状态不走文字(开关 + 悬停提示)
expect(text).toContain('tiptop-erp');
expect(text).toContain('账密');
expect(text).toContain('tiptop');
expect(text).toContain('界面维护(加密保存)');
// token 类型:非密字段为空显示占位;env 来源显示 Secret 键名
expect(text).toContain('wms-token');
expect(text).toContain('令牌');
// 内部实现列不再出现:db: 前缀的 secret_ref 原文不渲染
expect(wrapper.findAll('td').some((td) => td.text() === 'db:tiptop-erp')).toBe(false);
// 「更新时间」列已移除:updated_at 只是行保存时间,非最后轮换/验证时间,无行动价值
expect(text).not.toContain('2026-09-21 18:30');
expect(text).not.toContain('更新时间');
// 布尔启停走行内开关(与客户端实例一致),开关后不带状态文字,精确状态走悬停提示
expect(wrapper.findAll('[data-testid="credential-status-toggle"]').length).toBe(2);
expect(wrapper.find('[data-testid="credential-status"]').exists()).toBe(false);
expect(text).not.toContain('启用中');
expect(text).not.toContain('轮换中');
// 表头与客户端实例一致为「启用」(布尔开关列);「状态」留给接口/绑定的多状态徽章列
expect(wrapper.findAll('th').some((th) => th.text() === '启用')).toBe(true);
});
it('能力清单 tab 可激活:渲染注册能力(写/幂等)与调用入口,新增按钮隐藏', async () => {
const wrapper = mountPage();
const capTab = wrapper.findAll('[role="tab"]').find((b) => b.text() === '能力清单')!;
await capTab.trigger('click');
// tab 进入选中态(此前 selectTab 对 capability 直接 return,点击无效)
expect(capTab.attributes('aria-selected')).toBe('true');
const text = wrapper.text();
// 中文名称为主行,注册名保留为次行(绑定引用用精确标识)
expect(text).toContain('创建调拨单');
expect(text).toContain('在途库存查询');
expect(text).toContain('防重校验');
expect(text).toContain('in_transit_transfer.query_inventory');
expect(text).toContain('in_transit_transfer.create_transfer');
// 写入/幂等本地化:不再出现原始 yes/no 与 invoice/none
expect(wrapper.findAll('td').some((td) => td.text() === '是')).toBe(true);
expect(wrapper.findAll('td').some((td) => td.text() === '否')).toBe(true);
expect(text).toContain('按单据号幂等');
expect(text).not.toContain('yes');
expect(text).not.toContain('invoice');
// 只读清单:无「新增」入口;每行提供「调用」按钮(打开手动调用弹窗)
expect(wrapper.findAll('button').some((b) => b.text().includes('新增'))).toBe(false);
expect(wrapper.findAll('button').some((b) => b.text().includes('调用'))).toBe(true);
});
it('绑定列表能力列渲染「中文名 + 注册名」两行', async () => {
const wrapper = mountPage();
const bindTab = wrapper.findAll('[role="tab"]').find((b) => b.text() === '绑定')!;
await bindTab.trigger('click');
const text = wrapper.text();
// 能力引用列与客户端/接口引用列同款:中文名主行 + 注册名次行
expect(text).toContain('在途库存查询');
expect(text).toContain('in_transit_transfer.query_inventory');
});
});
@@ -1,28 +1,39 @@
<!--
features/admin/modules/integration-connector/IntegrationConnectorPage.vue
用途:集成连接器管理页——四个配置实体(客户端实例/接口定义/绑定/凭据引用)tab 列表 +
能力清单与手动调用测试;创建/编辑弹窗 + 连接测试。
依赖:useIntegrationConnectorAdmin、两个弹窗组件、useI18n。
逻辑:按 tab 展示列表与「新增」;配置「绑定」是让自动调拨跑起来的最小闭环核心。
能力清单与手动调用测试;创建/编辑抽屉 + 行内连接测试。
依赖:useIntegrationConnectorAdmin、抽屉与调用测试弹窗组件、useI18n。
逻辑:按 tab 展示列表与「新增」;客户端列表展示类型/环境徽章、行内启停开关与
连接测试结果(徽章 + 可展开详情);接口定义与绑定列表均以状态徽章 + 生命周期行内
按钮(发布/撤回/退役/恢复,绑定发布由后端就绪门禁校验接口已发布且客户端启用)
驱动状态,表单内状态只读;凭据列表布尔启停走行内开关
(与客户端实例一致,表头同为「启用」,开关不带状态文字,精确状态走悬停提示);
能力清单为只读注册表(能力中文名为主行 + 注册名次行,写入/幂等本地化,未注册翻译兜底原值);
接口/绑定列表的客户端与接口
引用列统一展示「名称 + 编码」两行;类型/环境/状态取值均本地化,
未知值兜底原样显示;配置「绑定」是让自动调拨跑起来的最小闭环核心。
-->
<script setup lang="ts">
import { computed, onMounted } from 'vue';
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Plus, Edit, Trash2, Plug, PlayCircle } from 'lucide-vue-next';
import IntegrationConnectorFormModal from './components/IntegrationConnectorFormModal.vue';
import IntegrationConnectorFormDrawer from './components/IntegrationConnectorFormDrawer.vue';
import IntegrationCapabilityCallModal from './components/IntegrationCapabilityCallModal.vue';
import { CONNECTOR_TYPE_OPTIONS, ENVIRONMENT_OPTIONS } from './types/integration-connector.types';
import { useIntegrationConnectorAdmin } from './composables/useIntegrationConnectorAdmin';
const { t } = useI18n();
const {
clients, interfaces, bindings, credentials, capabilities,
clients, interfaces, bindings, credentials, capabilities, credentialTypes,
isLoading, activeEntity, showFormModal, isSaving,
clientForm, interfaceForm, bindingForm, credentialForm,
showCallModal, callCapability, callParamsText, callContextText, callResult, callBusy,
testResultText,
testingClientCode, testResults,
lifecycleBusy,
loadAll, openCreateModal, openEditModal, closeFormModal, saveActive,
testConnection, openCallModal, closeCallModal, runCall, deleteClient,
testConnection, toggleClient, toggleCredential, openCallModal, closeCallModal, runCall, deleteClient,
changeInterfaceLifecycle, changeBindingLifecycle,
} = useIntegrationConnectorAdmin();
onMounted(() => { void loadAll(); });
@@ -35,16 +46,110 @@ const tabs: Array<{ key: TabKey; labelKey: string }> = [
{ key: 'credential', labelKey: 'admin.integrationConnector.tabs.credential' },
{ key: 'capability', labelKey: 'admin.integrationConnector.tabs.capability' },
];
const activeTab = computed<TabKey>(() => (activeEntity.value === 'credential' ? 'credential' : activeEntity.value));
// 当前激活 tab:页面本地状态(capability 为只读注册表 tab,不属于可编辑实体);
// 初始取 activeEntity,保证携带实体态进入页面时列表与 tab 一致。
const activeTab = ref<TabKey>(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 })));
/** 客户端选项带 connector_type:接口表单联动展示连接器类型用。 */
const clientOptions = computed(() => clients.value.map((c) => ({ code: c.code, name: c.name, connector_type: c.connector_type })));
/** 接口选项带 client_instance_code:绑定表单联动带出并锁定客户端实例用。 */
const interfaceOptions = computed(() => interfaces.value.map((i) => ({ code: i.code, name: i.name, client_instance_code: i.client_instance_code })));
const capabilityOptions = computed(() => capabilities.value.map((c) => ({ name: c.name })));
const credentialOptions = computed(() => credentials.value.map((c) => ({ code: c.code })));
/** 编码 → 名称(列表引用列展示「名称 + 编码」用);编码无对应记录时回退空串,由模板兜底显示编码。 */
function clientNameOf(code: string) {
return clients.value.find((c) => c.code === code)?.name ?? '';
}
function interfaceNameOf(code: string) {
return interfaces.value.find((i) => i.code === code)?.name ?? '';
}
/** 行内展开测试详情的客户端编码(同一时刻至多展开一行)。 */
const expandedTestCode = ref('');
/** 连接器类型本地化标签;未注册类型兜底原样显示(不写死类型集合)。 */
function connectorTypeLabel(value: string) {
const opt = CONNECTOR_TYPE_OPTIONS.find((item) => item.value === value);
return opt ? t(opt.labelKey) : value;
}
/** 环境本地化标签;未知值兜底原样显示。 */
function envLabel(value: string) {
return (ENVIRONMENT_OPTIONS as readonly string[]).includes(value)
? t(`admin.integrationConnector.envLabels.${value}`)
: value;
}
/** 状态本地化标签;未知值兜底原样显示。 */
function statusLabel(value: string) {
return t(`admin.integrationConnector.statusLabels.${value}`, value);
}
/** 能力本地化标签;未注册翻译的能力兜底原值(能力名含点号,i18n 按嵌套路径组织)。 */
function capabilityLabelOf(name: string) {
return t(`admin.integrationConnector.capabilityLabels.${name}`, name);
}
/** 幂等语义本地化标签;未知值兜底原样显示。 */
function idempotencyLabel(value: string) {
return t(`admin.integrationConnector.idempotencyLabels.${value}`, value);
}
/** 凭据来源本地化标签(db=界面维护/加密保存,env=环境注入);与状态共用 statusLabels。 */
function secretProviderLabel(value: string) {
return statusLabel(value);
}
/** 凭据类型本地化标签;未注册类型兜底原样显示(不写死类型集合)。 */
function credentialTypeLabel(value: string) {
return t(`admin.integrationConnector.credentialTypeLabels.${value}`, value);
}
/** 账号列文本:db 模式显示非密字段值(类型定义驱动);env 模式显示 Secret 键名。 */
function credentialAccountText(row: { secret_provider: string; secret_fields: Record<string, string>; secret_ref: string }) {
if (row.secret_provider === 'env') return row.secret_ref;
const values = Object.values(row.secret_fields ?? {}).filter(Boolean);
return values.length ? values.join(' / ') : '—';
}
/** 状态徽标配色:启用中绿 / 轮换中橙 / 其余中性。 */
function statusBadgeClass(value: string) {
if (value === 'active' || value === 'published') return 'bg-emerald-50 text-emerald-700';
if (value === 'rotating') return 'bg-amber-50 text-amber-700';
return 'bg-surface-soft text-secondary';
}
/** 行内测试结果(无结果返回 null,供模板 v-if 使用)。 */
function testResultOf(code: string) {
return testResults.value[code] ?? null;
}
/** 测试徽章配色:成功绿 / 失败红。 */
function testBadgeClass(code: string) {
return testResultOf(code)?.ok
? 'bg-green-100 text-green-700 hover:bg-green-200'
: 'bg-red-100 text-red-700 hover:bg-red-200';
}
/** 测试徽章文案。 */
function testBadgeText(code: string) {
return testResultOf(code)?.ok
? t('admin.integrationConnector.testOkBadge')
: t('admin.integrationConnector.testFailBadge');
}
/** 展开行详情文本:原因码 · 脱敏消息。 */
function testDetailText(code: string) {
const r = testResultOf(code);
if (!r) return '';
return r.message ? `${r.code} · ${r.message}` : r.code;
}
function selectTab(key: TabKey) {
// capability tab 只读展示,不进入表单实体;其余映射到可编辑实体。
if (key === 'capability') return;
activeEntity.value = key;
activeTab.value = key;
// capability tab 只读展示注册表(无新增/表单入口),activeEntity 保持最后一个可编辑实体供抽屉复用。
if (key !== 'capability') activeEntity.value = key;
}
</script>
@@ -91,40 +196,92 @@ function selectTab(key: TabKey) {
<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>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.endpoint') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.fields.enabled') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.testStatus') }}</th>
<th class="px-6 py-4 text-right text-xs w-36">{{ 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" />
<tr v-if="clients.length === 0"><td colspan="7" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<template v-for="row in clients" :key="row.code">
<tr>
<td class="px-6 py-4">
<p class="text-sm font-medium text-primary">{{ row.name }}</p>
<p class="text-xs text-muted mono mt-0.5">{{ row.code }}</p>
</td>
<td class="px-6 py-4">
<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-surface-soft text-secondary">{{ connectorTypeLabel(row.connector_type) }}</span>
</td>
<td class="px-6 py-4">
<span
class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium"
:class="row.environment === 'prod' ? 'bg-green-100 text-green-700' : row.environment === 'test' ? 'bg-amber-100 text-amber-700' : 'bg-surface-soft text-secondary'"
>{{ envLabel(row.environment) }}</span>
</td>
<td class="px-6 py-4 max-w-[240px]">
<span v-if="row.endpoint" class="block truncate text-xs font-mono text-secondary" :title="row.endpoint">{{ row.endpoint }}</span>
<span v-else class="text-xs text-muted">—</span>
</td>
<td class="px-6 py-4">
<button
type="button"
role="switch"
:aria-checked="row.enabled"
:title="t('admin.integrationConnector.fields.enabled')"
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors"
:class="row.enabled ? 'bg-brand-600' : 'bg-slate-300'"
data-testid="client-toggle"
:disabled="lifecycleBusy"
@click="toggleClient(row)"
>
<span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform" :class="row.enabled ? 'translate-x-4' : 'translate-x-0.5'" />
</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" />
</td>
<td class="px-6 py-4">
<span v-if="testingClientCode === row.code" class="text-xs text-muted">{{ t('admin.integrationConnector.msg.testing') }}</span>
<button
v-else-if="testResultOf(row.code)"
type="button"
class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium"
:class="testBadgeClass(row.code)"
:title="t('admin.integrationConnector.testDetailToggle')"
data-testid="client-test-badge"
@click="expandedTestCode = expandedTestCode === row.code ? '' : row.code"
>
{{ testBadgeText(row.code) }}
</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>
<span v-else class="text-xs text-muted">—</span>
</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)">
<Trash2 class="w-4 h-4" />
</button>
</div>
</td>
</tr>
<!-- 测试详情展开行:原因码 + 脱敏消息 -->
<tr v-if="expandedTestCode === row.code && testResultOf(row.code)">
<td colspan="7" class="px-6 py-3 bg-surface-soft" data-testid="client-test-detail">
<p class="text-xs font-mono text-secondary break-all">{{ testDetailText(row.code) }}</p>
</td>
</tr>
</template>
</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>
@@ -132,8 +289,8 @@ function selectTab(key: TabKey) {
<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>
<th class="px-6 py-4 text-left text-xs w-28">{{ t('admin.integrationConnector.headers.status') }}</th>
<th class="px-6 py-4 text-right text-xs w-48">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
@@ -141,10 +298,48 @@ function selectTab(key: TabKey) {
<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">
<p class="text-sm text-primary">{{ clientNameOf(row.client_instance_code) || row.client_instance_code }}</p>
<p class="text-xs text-muted mono mt-0.5">{{ row.client_instance_code }}</p>
</td>
<td class="px-6 py-4">
<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium" :class="statusBadgeClass(row.status)" data-testid="interface-status">{{ statusLabel(row.status) }}</span>
</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<!-- 生命周期按钮按当前状态显隐:draft→发布;published→撤回+退役;retired→恢复;按钮不换行防窄列折字 -->
<button
v-if="row.status === 'draft'"
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-brand-600 hover:bg-brand-50 disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="interface-publish"
:disabled="lifecycleBusy"
@click="changeInterfaceLifecycle(row, 'publish')"
>{{ t('admin.integrationConnector.lifecycle.publish') }}</button>
<template v-else-if="row.status === 'published'">
<button
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-secondary hover:bg-surface-soft disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="interface-unpublish"
:disabled="lifecycleBusy"
@click="changeInterfaceLifecycle(row, 'unpublish')"
>{{ t('admin.integrationConnector.lifecycle.unpublish') }}</button>
<button
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-amber-600 hover:bg-amber-50 disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="interface-retire"
:disabled="lifecycleBusy"
@click="changeInterfaceLifecycle(row, 'retire')"
>{{ t('admin.integrationConnector.lifecycle.retire') }}</button>
</template>
<button
v-else-if="row.status === 'retired'"
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-secondary hover:bg-surface-soft disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="interface-reopen"
:disabled="lifecycleBusy"
@click="changeInterfaceLifecycle(row, 'reopen')"
>{{ t('admin.integrationConnector.lifecycle.reopen') }}</button>
<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>
@@ -155,7 +350,7 @@ function selectTab(key: TabKey) {
</table>
</div>
<!-- 绑定 -->
<!-- 绑定:状态徽章 + 生命周期行内按钮(发布/撤回/退役/恢复,后端转移表 + 发布就绪门禁校验) -->
<div v-else-if="activeTab === 'binding'" class="admin-table-wrap">
<table class="admin-table">
<thead>
@@ -163,19 +358,64 @@ function selectTab(key: TabKey) {
<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>
<th class="px-6 py-4 text-left text-xs w-28">{{ t('admin.integrationConnector.headers.status') }}</th>
<th class="px-6 py-4 text-right text-xs w-48">{{ 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">
<p class="text-sm text-primary">{{ capabilityLabelOf(row.capability) }}</p>
<p v-if="capabilityLabelOf(row.capability) !== row.capability" class="text-xs text-muted mono mt-0.5">{{ row.capability }}</p>
</td>
<td class="px-6 py-4">
<p class="text-sm text-primary">{{ clientNameOf(row.client_instance_code) || row.client_instance_code }}</p>
<p class="text-xs text-muted mono mt-0.5">{{ row.client_instance_code }}</p>
</td>
<td class="px-6 py-4">
<p class="text-sm text-primary">{{ interfaceNameOf(row.interface_definition_code) || row.interface_definition_code }}</p>
<p class="text-xs text-muted mono mt-0.5">{{ row.interface_definition_code }}</p>
</td>
<td class="px-6 py-4">
<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium" :class="statusBadgeClass(row.status)" data-testid="binding-status">{{ statusLabel(row.status) }}</span>
</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<!-- 生命周期按钮按当前状态显隐:draft→发布;published→撤回+退役;retired→恢复;按钮不换行防窄列折字 -->
<button
v-if="row.status === 'draft'"
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-brand-600 hover:bg-brand-50 disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="binding-publish"
:disabled="lifecycleBusy"
@click="changeBindingLifecycle(row, 'publish')"
>{{ t('admin.integrationConnector.lifecycle.publish') }}</button>
<template v-else-if="row.status === 'published'">
<button
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-secondary hover:bg-surface-soft disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="binding-unpublish"
:disabled="lifecycleBusy"
@click="changeBindingLifecycle(row, 'unpublish')"
>{{ t('admin.integrationConnector.lifecycle.unpublish') }}</button>
<button
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-amber-600 hover:bg-amber-50 disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="binding-retire"
:disabled="lifecycleBusy"
@click="changeBindingLifecycle(row, 'retire')"
>{{ t('admin.integrationConnector.lifecycle.retire') }}</button>
</template>
<button
v-else-if="row.status === 'retired'"
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-secondary hover:bg-surface-soft disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="binding-reopen"
:disabled="lifecycleBusy"
@click="changeBindingLifecycle(row, 'reopen')"
>{{ t('admin.integrationConnector.lifecycle.reopen') }}</button>
<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>
@@ -192,19 +432,40 @@ function selectTab(key: TabKey) {
<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.connectorType') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.account') }}</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>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.fields.enabled') }}</th>
<th class="px-6 py-4 text-right text-xs w-32">{{ 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-if="credentials.length === 0"><td colspan="6" 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-sm">
<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-surface-soft text-secondary">{{ credentialTypeLabel(row.credential_type) }}</span>
</td>
<td class="px-6 py-4 text-sm text-secondary mono">{{ credentialAccountText(row) }}</td>
<td class="px-6 py-4 text-sm">
<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-surface-soft text-secondary" :title="row.secret_provider === 'db' ? statusLabel('db') : row.secret_ref">{{ secretProviderLabel(row.secret_provider) }}</span>
</td>
<td class="px-6 py-4">
<!-- 行内启停开关:布尔语义,与客户端实例开关完全同款(含 title 用同一 i18n 键);rotating 视为启用侧,点击即停用;解析层只认 active,停用即断流 -->
<button
type="button"
role="switch"
:aria-checked="row.status !== 'retired'"
:title="t('admin.integrationConnector.fields.enabled')"
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors"
:class="row.status !== 'retired' ? 'bg-brand-600' : 'bg-slate-300'"
data-testid="credential-status-toggle"
:disabled="lifecycleBusy"
@click="toggleCredential(row)"
>
<span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform" :class="row.status !== 'retired' ? 'translate-x-4' : 'translate-x-0.5'" />
</button>
</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)">
@@ -231,9 +492,13 @@ function selectTab(key: TabKey) {
<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">
<p class="text-sm font-medium text-primary">{{ capabilityLabelOf(row.name) }}</p>
<p v-if="capabilityLabelOf(row.name) !== row.name" class="text-xs text-muted mono mt-0.5">{{ row.name }}</p>
</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.write ? t('admin.integrationConnector.writeLabels.yes') : t('admin.integrationConnector.writeLabels.no') }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ idempotencyLabel(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" />
@@ -246,7 +511,7 @@ function selectTab(key: TabKey) {
</div>
</template>
<IntegrationConnectorFormModal
<IntegrationConnectorFormDrawer
:visible="showFormModal"
:active-entity="activeEntity"
:client-form="clientForm"
@@ -257,6 +522,8 @@ function selectTab(key: TabKey) {
:client-options="clientOptions"
:interface-options="interfaceOptions"
:capability-options="capabilityOptions"
:credential-type-options="credentialTypes"
:credential-options="credentialOptions"
@close="closeFormModal"
@save="saveActive"
/>
@@ -13,6 +13,7 @@ import type {
IntegrationCapabilityRow,
IntegrationClientInstanceRow,
IntegrationCredentialReferenceRow,
IntegrationCredentialTypeSpec,
IntegrationInterfaceDefinitionRow,
} from '../types/integration-connector.types';
@@ -74,6 +75,13 @@ export const updateIntegrationInterfaceDefinition = (code: string, payload: Reco
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
});
/** 接口定义生命周期动作(publish/unpublish/retire/reopen);状态只能经此流转。 */
export const changeIntegrationInterfaceLifecycle = (code: string, action: 'publish' | 'unpublish' | 'retire' | 'reopen') =>
requestJson<IntegrationInterfaceDefinitionRow>(
`${BASE}/interface-definitions/${encodeURIComponent(code)}/${action}`,
{ method: 'POST', ...jsonAuth(), body: JSON.stringify({}) },
);
// ---- 绑定 ----
export const listIntegrationBindings = () =>
@@ -89,11 +97,21 @@ export const updateIntegrationBinding = (id: number, payload: Record<string, unk
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
});
/** 绑定生命周期动作(publish/unpublish/retire/reopen);状态只能经此流转。 */
export const changeIntegrationBindingLifecycle = (id: number, action: 'publish' | 'unpublish' | 'retire' | 'reopen') =>
requestJson<IntegrationBindingRow>(
`${BASE}/bindings/${id}/${action}`,
{ method: 'POST', ...jsonAuth(), body: JSON.stringify({}) },
);
// ---- 凭据引用 ----
export const listIntegrationCredentialReferences = () =>
requestJson<IntegrationCredentialReferenceRow[]>(`${BASE}/credential-references`, auth());
export const listIntegrationCredentialTypes = () =>
requestJson<IntegrationCredentialTypeSpec[]>(`${BASE}/credential-references/types`, auth());
export const createIntegrationCredentialReference = (payload: Record<string, unknown>) =>
requestJson<IntegrationCredentialReferenceRow>(`${BASE}/credential-references`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
@@ -0,0 +1,410 @@
/**
* features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.spec.ts
* 用途:锁定表单按连接器类型动态显示字段——REST 显示超时/HTTP方法/请求路径,
* SOAP 显示 WSDL;以及抽屉化后的 JSON 编辑字段(格式化/失焦校验)、
* 脏检查关闭确认与 Esc 关闭行为。
* 依赖:@vue/test-utils、vitest、i18n。
* 逻辑:切换 connector_type 断言字段可见性;对 JsonTextareaField 断言格式化改写
* 与非法 JSON 提示;mock window.confirm 断言脏表单关闭拦截与放行。
*/
import { mount, enableAutoUnmount } from '@vue/test-utils';
import { afterEach, describe, expect, it, vi } from 'vitest';
import i18n from '@/i18n';
import IntegrationConnectorFormDrawer from './IntegrationConnectorFormDrawer.vue';
import JsonTextareaField from './JsonTextareaField.vue';
import {
createEmptyClientInstanceForm,
createEmptyInterfaceDefinitionForm,
createEmptyBindingForm,
createEmptyCredentialReferenceForm,
type InterfaceDefinitionFormState,
} from '../types/integration-connector.types';
enableAutoUnmount(afterEach);
function mountDrawer(overrides: Partial<Record<string, unknown>> = {}) {
return mount(IntegrationConnectorFormDrawer, {
props: {
visible: true,
activeEntity: 'client',
clientForm: createEmptyClientInstanceForm(),
interfaceForm: createEmptyInterfaceDefinitionForm(),
bindingForm: createEmptyBindingForm(),
credentialForm: createEmptyCredentialReferenceForm(),
isSaving: false,
clientOptions: [],
interfaceOptions: [],
capabilityOptions: [],
credentialTypeOptions: [
{ type: 'password', fields: [
{ key: 'username', secret: false, required: true },
{ key: 'password', secret: true, required: true },
] },
{ type: 'token', fields: [{ key: 'token', secret: true, required: true }] },
],
...overrides,
},
global: { plugins: [i18n] },
});
}
describe('IntegrationConnectorFormDrawer connector-type fields', () => {
it('REST 默认显示接口地址与超时字段', () => {
const wrapper = mountDrawer();
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 = mountDrawer();
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 = mountDrawer({ activeEntity: 'interface' });
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('接口定义:选客户端实例后编码自动建议为「客户端编码-名称slug」,连接器类型为同款禁用下拉随客户端联动', async () => {
const interfaceForm = createEmptyInterfaceDefinitionForm();
interfaceForm.name = '鼎捷TOPGP库存查询GetItemStockList';
const wrapper = mountDrawer({
activeEntity: 'interface',
interfaceForm,
clientOptions: [{ code: '1001', name: '鼎捷TOPGP', connector_type: 'soap' }],
});
await wrapper.find('[data-testid="interface-client"]').setValue('1001');
// 编码留空 → 按客户端编码 + 名称 slug 自动建议
expect(interfaceForm.code).toBe('1001-topgp-getitemstocklist');
// 连接器类型与客户端实例同款下拉控件,仅禁用只读:随所选客户端联动展示
const typeSelect = wrapper.find('[data-testid="interface-connector-type"]');
expect(typeSelect.text()).toContain('SOAP');
expect(typeSelect.attributes('disabled')).toBeDefined();
// 只渲染当前类型单项,不提供其他选项(不可改选)
expect(typeSelect.findAll('option').length).toBe(1);
});
it('接口定义:状态在底部操作条以状态胶囊只读展示(悬停承载说明),无启用勾选', () => {
const interfaceForm = createEmptyInterfaceDefinitionForm();
interfaceForm.status = 'published';
const wrapper = mountDrawer({ activeEntity: 'interface', interfaceForm });
// 操作条只放安静的状态指示器:彩点胶囊,不放表单控件与多行文案;长说明走悬停 title
const chip = wrapper.find('[data-testid="lifecycle-status-chip"]');
expect(chip.exists()).toBe(true);
expect(chip.text()).toContain('已发布');
expect(chip.attributes('title')).toContain('发布');
// 启用勾选已移除
expect(wrapper.findAll('input[type="checkbox"]').length).toBe(0);
});
it('绑定:无来源实例编码字段,状态在底部操作条以禁用下拉只读展示', () => {
const wrapper = mountDrawer({ activeEntity: 'binding' });
const labels = wrapper.findAll('label').map((l) => l.text());
// 来源快捷列已删除:路由条件统一走高级配置 JSON
expect(labels.some((t) => t.includes('来源实例编码'))).toBe(false);
// 状态胶囊在底部操作条(转移只经列表生命周期按钮)
const chip = wrapper.find('[data-testid="lifecycle-status-chip"]');
expect(chip.exists()).toBe(true);
expect(chip.attributes('title')).toContain('发布');
});
it('绑定:选定接口定义后客户端实例自动带出并锁定', async () => {
const bindingForm = createEmptyBindingForm();
const wrapper = mountDrawer({
activeEntity: 'binding',
bindingForm,
clientOptions: [
{ code: '1001', name: '鼎捷TOPGP' },
{ code: '2001', name: '另一实例' },
],
interfaceOptions: [{ code: '1001-iface', name: '接口A', client_instance_code: '1001' }],
});
// 未选接口定义前客户端实例可维护
expect(wrapper.find('[data-testid="binding-client"]').attributes('disabled')).toBeUndefined();
await wrapper.find('[data-testid="binding-interface"]').setValue('1001-iface');
// 选定接口定义后:客户端实例按接口归属联动带出且锁定
expect(bindingForm.client_instance_code).toBe('1001');
expect(wrapper.find('[data-testid="binding-client"]').attributes('disabled')).toBeDefined();
});
it('绑定能力下拉选项本地化:有翻译显示「中文名(注册名)」,无翻译兜底注册名', () => {
const wrapper = mountDrawer({
activeEntity: 'binding',
capabilityOptions: [
{ name: 'in_transit_transfer.query_inventory' },
{ name: 'unknown.capability' },
],
});
// 能力下拉是绑定表单首个 select;选项不再出现原始注册名裸文案
const capabilitySelect = wrapper.find('select');
expect(capabilitySelect.findAll('option').map((o) => o.text())).toEqual([
'在途库存查询(in_transit_transfer.query_inventory)',
'unknown.capability',
]);
});
});
describe('IntegrationConnectorFormDrawer JSON fields', () => {
function findJsonField(wrapper: ReturnType<typeof mountDrawer>, labelPart: string) {
const field = wrapper
.findAllComponents(JsonTextareaField)
.find((w) => String(w.props('label')).includes(labelPart));
expect(field, `未找到 label 含 ${labelPart} 的 JSON 字段`).toBeDefined();
return field!;
}
it('接口定义 4 个 JSON 字段纵向全宽堆叠渲染', () => {
const wrapper = mountDrawer({ activeEntity: 'interface' });
const labels = wrapper.findAllComponents(JsonTextareaField).map((w) => String(w.props('label')));
expect(labels.some((t) => t.includes('请求模板'))).toBe(true);
expect(labels.some((t) => t.includes('入参 Schema'))).toBe(true);
expect(labels.some((t) => t.includes('回传映射'))).toBe(true);
expect(labels.some((t) => t.includes('出参 Schema'))).toBe(true);
});
it('格式化按钮将合法 JSON pretty-print 写回表单 state', async () => {
const interfaceForm: InterfaceDefinitionFormState = createEmptyInterfaceDefinitionForm();
const wrapper = mountDrawer({ activeEntity: 'interface', interfaceForm });
const field = findJsonField(wrapper, '请求模板');
await field!.find('[data-testid="json-textarea"]').setValue('{"method":"POST","params":["erp_org"]}');
await field!.find('[data-testid="json-format-button"]').trigger('click');
// 断言格式化结果写回父级表单对象(v-model 链路)
expect(interfaceForm.request_spec_json).toBe('{\n "method": "POST",\n "params": [\n "erp_org"\n ]\n}');
});
it('非法 JSON 失焦后显示红字提示,格式化不改写内容', async () => {
const interfaceForm: InterfaceDefinitionFormState = createEmptyInterfaceDefinitionForm();
const wrapper = mountDrawer({ activeEntity: 'interface', interfaceForm });
const field = findJsonField(wrapper, '请求模板');
const textarea = field!.find('[data-testid="json-textarea"]');
await textarea.setValue('{ invalid');
expect(field!.find('[data-testid="json-error"]').exists()).toBe(false);
await textarea.trigger('blur');
// 失焦后才提示,输入过程中不打断
expect(field!.find('[data-testid="json-error"]').exists()).toBe(true);
expect(field!.find('[data-testid="json-error"]').text()).toContain('JSON 格式无效');
// 非法时格式化按钮不改写内容
await field!.find('[data-testid="json-format-button"]').trigger('click');
expect(interfaceForm.request_spec_json).toBe('{ invalid');
});
it('客户端实例与绑定实体的 JSON 字段同样启用格式化能力', () => {
const clientWrapper = mountDrawer({ activeEntity: 'client' });
expect(findJsonField(clientWrapper, '连接配置').find('[data-testid="json-format-button"]').exists()).toBe(true);
const bindingWrapper = mountDrawer({ activeEntity: 'binding' });
expect(findJsonField(bindingWrapper, '高级路由条件').find('[data-testid="json-format-button"]').exists()).toBe(true);
});
});
describe('IntegrationConnectorFormDrawer close guard', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('抽屉带 dialog 语义且打开时渲染标题', () => {
const wrapper = mountDrawer({ activeEntity: 'client' });
const dialog = wrapper.find('[role="dialog"]');
expect(dialog.exists()).toBe(true);
expect(dialog.attributes('aria-modal')).toBe('true');
expect(dialog.attributes('aria-label')).toContain('客户端实例');
});
it('干净表单点击遮罩直接关闭,不弹确认', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
const wrapper = mountDrawer();
await wrapper.find('[data-testid="connector-form-drawer"]').trigger('click');
expect(wrapper.emitted('close')).toHaveLength(1);
expect(confirmSpy).not.toHaveBeenCalled();
});
it('脏表单关闭先确认:拒绝则留在抽屉,允许才 emit close', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
const wrapper = mountDrawer();
await wrapper.find('[data-testid="client-endpoint"]').setValue('https://erp.example.com');
await wrapper.find('[data-testid="connector-form-drawer"]').trigger('click');
// 用户拒绝关闭 → 不 emit
expect(confirmSpy).toHaveBeenCalledTimes(1);
expect(wrapper.emitted('close')).toBeUndefined();
confirmSpy.mockReturnValue(true);
await wrapper.find('[data-testid="connector-form-drawer"]').trigger('click');
// 用户确认放弃 → 放行关闭
expect(wrapper.emitted('close')).toHaveLength(1);
});
it('Esc 关闭走同一确认入口(脏表单拒绝时不关闭)', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
const wrapper = mountDrawer();
await wrapper.find('[data-testid="client-endpoint"]').setValue('https://erp.example.com');
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
expect(confirmSpy).toHaveBeenCalledTimes(1);
expect(wrapper.emitted('close')).toBeUndefined();
// 干净表单 Esc 直接关闭
const cleanWrapper = mountDrawer();
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
expect(cleanWrapper.emitted('close')).toHaveLength(1);
});
});
describe('IntegrationConnectorFormDrawer credential modes', () => {
it('db 模式按类型动态渲染字段(secret 字段为密码框),不显示 Secret 引用键', () => {
const wrapper = mountDrawer({ activeEntity: 'credential' });
const username = wrapper.find('[data-testid="credential-field-username"]');
const password = wrapper.find('[data-testid="credential-field-password"]');
expect(username.exists()).toBe(true);
expect(password.exists()).toBe(true);
expect(password.attributes('type')).toBe('password');
expect(username.attributes('type')).toBe('text');
expect(wrapper.find('[data-testid="credential-secret-ref"]').exists()).toBe(false);
// 占位符提示列出该类型提供的 credential_* 键
expect(wrapper.text()).toContain('{credential_username}');
expect(wrapper.text()).toContain('{credential_password}');
});
it('编辑态密文字段显示留空保持原值提示', () => {
const form = { ...createEmptyCredentialReferenceForm(), id: 7, fields: { username: 'erp_user' } };
const wrapper = mountDrawer({ activeEntity: 'credential', credentialForm: form });
const password = wrapper.find('[data-testid="credential-field-password"]');
expect(password.attributes('placeholder')).toContain('留空');
expect((wrapper.find('[data-testid="credential-field-username"]').element as HTMLInputElement).value).toBe('erp_user');
});
it('切换凭据类型到 token 后按新类型渲染字段', async () => {
const wrapper = mountDrawer({ activeEntity: 'credential' });
await wrapper.find('[data-testid="credential-type"]').setValue('token');
expect(wrapper.find('[data-testid="credential-field-token"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="credential-field-username"]').exists()).toBe(false);
expect(wrapper.text()).toContain('{credential_token}');
});
it('切到 env 模式只显示 Secret 引用键,隐藏类型字段', async () => {
const wrapper = mountDrawer({ activeEntity: 'credential' });
await wrapper.find('[data-testid="credential-provider"]').setValue('env');
expect(wrapper.find('[data-testid="credential-secret-ref"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="credential-field-username"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="credential-field-password"]').exists()).toBe(false);
});
});
describe('IntegrationConnectorFormDrawer credential identity freeze', () => {
it('新建态:类型/来源下拉选项本地化渲染(与列表徽章一致),状态不进表单,无只读信息区', () => {
const wrapper = mountDrawer({ activeEntity: 'credential' });
const typeOptions = wrapper.find('[data-testid="credential-type"]').findAll('option');
expect(typeOptions.map((o) => o.text())).toEqual(['账密', '令牌']);
const providerOptions = wrapper.find('[data-testid="credential-provider"]').findAll('option');
expect(providerOptions.map((o) => o.text())).toEqual(['界面维护(加密保存)', '环境变量']);
// 状态由列表生命周期按钮流转,凭据表单只有来源/类型两个下拉
expect(wrapper.findAll('select').length).toBe(2);
// 新建态没有只读信息区
expect(wrapper.find('[data-testid="credential-meta"]').exists()).toBe(false);
// 正文分组:基本信息 + 凭据值
expect(wrapper.text()).toContain('基本信息');
expect(wrapper.text()).toContain('凭据值');
});
it('编辑态:编码/类型/来源以同款禁用表单控件只读展示(不用徽章形态),启用开关在底部操作条', () => {
const form = { ...createEmptyCredentialReferenceForm(), id: 7, code: 'tiptop-erp', credential_type: 'password', secret_provider: 'db', status: 'active' };
const wrapper = mountDrawer({ activeEntity: 'credential', credentialForm: form });
// 与新建态同款正常控件、禁用只读:编码输入框 + 来源/类型下拉(本地化文案,不出现裸枚举)
const codeInput = wrapper.find('[data-testid="credential-code"]');
expect((codeInput.element as HTMLInputElement).disabled).toBe(true);
expect((codeInput.element as HTMLInputElement).value).toBe('tiptop-erp');
const providerSelect = wrapper.find('[data-testid="credential-provider"]');
expect(providerSelect.attributes('disabled')).toBeDefined();
expect(providerSelect.text()).toContain('界面维护(加密保存)');
const typeSelect = wrapper.find('[data-testid="credential-type"]');
expect(typeSelect.attributes('disabled')).toBeDefined();
expect(typeSelect.text()).toContain('账密');
// 状态 = 底部操作条启用开关(随保存生效),悬停 title 说明停用断流后果
const row = wrapper.find('[data-testid="credential-enabled-row"]');
expect(row.exists()).toBe(true);
expect(row.text()).toContain('随保存操作生效');
const switchBtn = wrapper.find('[data-testid="credential-enabled-switch"]');
expect(switchBtn.attributes('aria-checked')).toBe('true');
expect(switchBtn.attributes('title')).toContain('立即失败');
// 变更路径一句话提示
expect(wrapper.text()).toContain('以上信息创建后不可更改');
});
it('凭据值段占位符逐个以代码徽章展示', () => {
const wrapper = mountDrawer({ activeEntity: 'credential' });
const chips = wrapper.findAll('[data-testid="credential-placeholder-chip"]');
expect(chips.map((c) => c.text())).toEqual(['{credential_username}', '{credential_password}']);
});
});
describe('IntegrationConnectorFormDrawer client form redesign', () => {
it('名称失焦且编码为空时自动建议 kebab-case 编码;已填编码不被覆盖', async () => {
const clientForm = createEmptyClientInstanceForm();
const wrapper = mountDrawer({ clientForm });
await wrapper.find('[data-testid="client-name"]').setValue('ERP X');
await wrapper.find('[data-testid="client-name"]').trigger('blur');
expect(clientForm.code).toBe('erp-x');
await wrapper.find('[data-testid="client-name"]').setValue('Another Name');
await wrapper.find('[data-testid="client-name"]').trigger('blur');
expect(clientForm.code).toBe('erp-x');
});
it('编辑态编码锁定不可改,类型/环境下拉本地化渲染', async () => {
const clientForm = { ...createEmptyClientInstanceForm(), id: 3, code: 'erp-x' };
const wrapper = mountDrawer({ clientForm });
const code = wrapper.find('[data-testid="client-code"]');
expect((code.element as HTMLInputElement).disabled).toBe(true);
const typeOptions = wrapper.find('[data-testid="client-connector-type"]').findAll('option');
expect(typeOptions.map((o) => o.text())).toEqual(['REST API', 'SOAP 服务']);
const envOptions = wrapper.find('[data-testid="client-environment"]').findAll('option');
expect(envOptions.map((o) => o.text())).toEqual(['开发', '测试', '生产']);
});
it('凭据引用为下拉选择(含「无(匿名访问)」空项),高级配置按类型给出生效键提示', async () => {
const wrapper = mountDrawer({
credentialOptions: [{ code: 'tiptop-erp' }, { code: 'wms-token' }],
});
const credOptions = wrapper.find('[data-testid="client-credential-ref"]').findAll('option');
expect(credOptions.map((o) => o.text())).toEqual(['无(匿名访问)', 'tiptop-erp', 'wms-token']);
// REST:高级配置提示列出生效键 headers
expect(wrapper.text()).toContain('"headers"');
// 切到 SOAP:提示变为「暂无额外生效键」语义
await wrapper.find('[data-testid="client-connector-type"]').setValue('soap');
expect(wrapper.text()).toContain('暂无额外生效的配置键');
});
it('启用开关置于底部操作条左侧:小字注明随保存生效,点击翻转 state,非客户端实体不渲染', async () => {
const clientForm = createEmptyClientInstanceForm();
const wrapper = mountDrawer({ clientForm });
const row = wrapper.find('[data-testid="client-enabled-row"]');
// 启用不再是表单体里的孤行复选框,而是底部操作条左侧的 role="switch" 开关
expect(row.exists()).toBe(true);
expect(wrapper.findAll('input[type="checkbox"]').length).toBe(0);
const switchBtn = wrapper.find('[data-testid="client-enabled-switch"]');
expect(switchBtn.attributes('role')).toBe('switch');
// 小字「随保存操作生效」与列表行内开关的即时生效区分;悬停 title 携带停用后果
expect(row.text()).toContain('随保存操作生效');
expect(switchBtn.attributes('title')).toContain('连接测试不受影响');
// 默认启用;点击翻转表单 state,aria 状态同步
expect(clientForm.enabled).toBe(true);
await switchBtn.trigger('click');
expect(clientForm.enabled).toBe(false);
expect(switchBtn.attributes('aria-checked')).toBe('false');
// 凭据实体渲染自己的启用开关(同一底部形态),客户端开关行不出现
const credWrapper = mountDrawer({ activeEntity: 'credential' });
expect(credWrapper.find('[data-testid="client-enabled-row"]').exists()).toBe(false);
expect(credWrapper.find('[data-testid="credential-enabled-row"]').exists()).toBe(true);
// 接口/绑定不渲染启用开关,改为底部状态只读下拉
const ifaceWrapper = mountDrawer({ activeEntity: 'interface' });
expect(ifaceWrapper.find('[data-testid="client-enabled-row"]').exists()).toBe(false);
expect(ifaceWrapper.find('[data-testid="lifecycle-status-row"]').exists()).toBe(true);
});
});
@@ -0,0 +1,565 @@
<!--
features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.vue
用途:集成连接器四实体(客户端实例/接口定义/绑定/凭据引用)创建与编辑抽屉。
依赖:activeEntity 对应的表单 state、useI18n、JsonTextareaField。
逻辑:由 IntegrationConnectorPage 打开;按 activeEntity 渲染对应字段,客户端实例
表单按「基本信息 → 连接配置 → 高级」分组,启用开关置于底部操作条左侧(随保存生效,悬停显示停用后果);
客户端编码留空时按名称自动建议、
接口编码留空时按「客户端实例编码-名称」自动建议(均可手改,已填不覆盖,编辑态编码锁定);
客户端实例的连接器类型/环境/凭据引用均为下拉(选项来自模块常量与凭据列表,未知值兜底);
接口定义的连接器类型随所选客户端实例联动只读展示(提交由后端以客户端为准推导);
绑定的客户端实例随所选接口定义联动带出并锁定(接口归属即客户端归属);
绑定表单的能力下拉选项本地化为「中文名(注册名)」(未注册翻译兜底注册名);
接口与绑定的状态均为只读徽章(发布/退役走列表生命周期按钮),四个 JSON 契约字段常显不折叠;
凭据引用:状态不进表单(由列表生命周期按钮流转);编辑态以「基本信息」只读信息区
展示编码/类型/来源/状态(label+值行,与接口定义只读字段同款式),新建态下拉选项
文案本地化与列表一致;高级配置帮助文案按连接器类型的生效键动态切换。
JSON 配置字段统一走 JsonTextareaField;提交 emit save。右侧抽屉承载(表单长、JSON 面积大),
带未保存离开确认(脏检查)、Esc 关闭与 dialog aria 语义。
-->
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import JsonTextareaField from './JsonTextareaField.vue';
import {
CONNECTOR_CONFIG_KEYS,
CONNECTOR_TYPE_OPTIONS,
ENVIRONMENT_OPTIONS,
suggestClientCode,
suggestInterfaceCode,
} from '../types/integration-connector.types';
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;
/** 客户端实例选项:connector_type 供接口表单联动展示连接器类型。 */
clientOptions: Array<{ code: string; name: string; connector_type?: string }>;
/** 接口定义选项:client_instance_code 供绑定表单联动带出客户端实例。 */
interfaceOptions: Array<{ code: string; name: string; client_instance_code?: string }>;
capabilityOptions: Array<{ name: string }>;
credentialTypeOptions: Array<{ type: string; fields: Array<{ key: string; secret: boolean; required: boolean }> }>;
/** 凭据引用选项(客户端表单下拉用);缺省渲染为空列表。 */
credentialOptions?: Array<{ code: string }>;
}>();
const emit = defineEmits<{
close: [];
save: [];
}>();
const { t } = useI18n();
const panelRef = ref<HTMLElement | null>(null);
/** 打开时刻的表单快照,用于脏检查(表单均为扁平原始值,stringify 比对可靠)。 */
const initialSnapshot = ref('');
const entityTitle = computed(() => t(`admin.integrationConnector.tabs.${props.activeEntity}`));
/** 抽屉顶部提示按实体区分(客户端表单提示编码用途;其余实体提示与自身相关的关键规则)。 */
const entityHint = computed(() => t(`admin.integrationConnector.formHints.${props.activeEntity}`));
/** 名称失焦时若编码仍为空,按名称自动建议(已手填的编码不覆盖;编辑态编码锁定)。 */
function onClientNameBlur() {
if (!props.clientForm.code.trim()) {
props.clientForm.code = suggestClientCode(props.clientForm.name);
}
}
/** 连接器类型本地化标签;未注册类型兜底原样显示(不写死类型集合)。 */
function connectorTypeLabel(value: string) {
const opt = CONNECTOR_TYPE_OPTIONS.find((item) => item.value === value);
return opt ? t(opt.labelKey) : value;
}
/** 状态本地化标签;未知值兜底原样显示。 */
function statusLabel(value: string) {
return t(`admin.integrationConnector.statusLabels.${value}`, value);
}
/** 引用型下拉选项文案:「名称(编码)」;无名称时兜底编码本身(凭据类实体无名称字段)。 */
function optionLabel(name: string, code: string) {
return name ? `${name}(${code})` : code;
}
/** 能力本地化标签;未注册翻译兜底原值(能力名含点号,i18n 按嵌套路径组织)。 */
function capabilityLabel(name: string) {
return t(`admin.integrationConnector.capabilityLabels.${name}`, name);
}
/** 能力下拉选项文案:有中文翻译时「中文名(注册名)」,否则注册名本身(避免重复)。 */
function capabilityOptionLabel(name: string) {
const label = capabilityLabel(name);
return label === name ? name : `${label}(${name})`;
}
/** 接口编码仍为空且已选客户端实例时,按「客户端编码-名称」补建议(已手填不覆盖)。 */
function suggestInterfaceCodeIfEmpty() {
const form = props.interfaceForm;
if (form.code.trim() || !form.client_instance_code) return;
const suggested = suggestInterfaceCode(form.client_instance_code, form.name);
if (suggested) form.code = suggested;
}
/** 接口名称失焦:编码仍为空则补建议。 */
function onInterfaceNameBlur() {
suggestInterfaceCodeIfEmpty();
}
/** 切换接口的客户端实例:联动展示其连接器类型(仅展示,提交由后端以客户端为准推导),并补编码建议。 */
function onInterfaceClientChange() {
const selected = props.clientOptions.find((item) => item.code === props.interfaceForm.client_instance_code);
if (selected?.connector_type === 'rest' || selected?.connector_type === 'soap') {
props.interfaceForm.connector_type = selected.connector_type;
}
suggestInterfaceCodeIfEmpty();
}
/**
* 切换绑定的接口定义:联动带出其所属客户端实例并锁定(接口归属即客户端归属)。
* 后端创建/更新仍做成对校验(INTEGRATION.BINDING_PAIR_MISMATCH)兜底直连 API 的场景。
*/
function onBindingInterfaceChange() {
const selected = props.interfaceOptions.find((item) => item.code === props.bindingForm.interface_definition_code);
if (selected?.client_instance_code) {
props.bindingForm.client_instance_code = selected.client_instance_code;
}
}
/** 高级配置示例(JSON 属代码示例,不入 i18n——字面大括号会破坏 vue-i18n 消息编译)。 */
const CLIENT_CONFIG_EXAMPLE = '{ "headers": { "X-Tenant": "AWSBI" } }';
/** 高级配置帮助文案:按连接器类型列出当前生效键;无生效键时明确说明透传语义。 */
const clientConfigHint = computed(() => {
const keys = CONNECTOR_CONFIG_KEYS[props.clientForm.connector_type] ?? [];
if (keys.length) {
return t('admin.integrationConnector.advancedHints.withKeys', { keys: keys.map((k) => `"${k}"`).join('、') });
}
return t('admin.integrationConnector.advancedHints.none');
});
/** 当前所选凭据类型的字段定义(来自后端注册表;未加载时回退空)。 */
const credentialTypeSpec = computed(() => {
if (props.activeEntity !== 'credential') return null;
return props.credentialTypeOptions.find((item) => item.type === props.credentialForm.credential_type) ?? null;
});
/** 该凭据类型提供的模板占位符(credential_<key>)清单,供接口模板作者参考。 */
const credentialPlaceholderKeys = computed(() =>
(credentialTypeSpec.value?.fields ?? []).map((field) => `{credential_${field.key}}`),
);
function credentialFieldLabel(key: string) {
return t(`admin.integrationConnector.credentialFields.${key}`, key);
}
/** 凭据引用编辑态判定:编辑时编码/类型/来源渲染为禁用表单控件(行业惯例:凭据形态创建后不可变)。 */
const isCredentialEdit = computed(() => Boolean(props.credentialForm.id));
/** 凭据启用态:两态开关(active/retired;rotating 存量视为启用侧,点击即停用)。 */
const credentialEnabled = computed(() => props.credentialForm.status !== 'retired');
/** 凭据 footer 启用开关翻转:active↔retired,随「保存更改」一并提交(PUT 仅接受这两值)。 */
function toggleCredentialEnabled() {
props.credentialForm.status = props.credentialForm.status === 'retired' ? 'active' : 'retired';
}
/** 接口/绑定生命周期状态(footer 只读展示;转移只经列表生命周期按钮,表单不可改)。 */
const lifecycleStatus = computed(() =>
props.activeEntity === 'interface' ? props.interfaceForm.status : props.bindingForm.status,
);
/** 状态胶囊配色:已发布绿 / 其余中性(与列表状态徽章同规则;未知值兜底中性)。 */
const lifecycleChipClass = computed(() => {
if (lifecycleStatus.value === 'published') return 'bg-emerald-50 text-emerald-700';
return 'bg-surface-soft text-secondary';
});
/** 凭据类型本地化标签;未注册类型兜底原样显示(不写死类型集合)。 */
function credentialTypeLabel(value: string) {
return t(`admin.integrationConnector.credentialTypeLabels.${value}`, value);
}
/** 凭据来源本地化标签(与列表徽章共用 statusLabels.db/env)。 */
function credentialProviderLabel(value: string) {
return t(`admin.integrationConnector.statusLabels.${value}`, value);
}
const activeForm = computed(() => {
if (props.activeEntity === 'client') return props.clientForm;
if (props.activeEntity === 'interface') return props.interfaceForm;
if (props.activeEntity === 'binding') return props.bindingForm;
return props.credentialForm;
});
/** 表单相对打开时是否有变更;有变更时关闭需用户确认,防误触丢数据。 */
const isDirty = computed(() => JSON.stringify(activeForm.value) !== initialSnapshot.value);
/** 统一关闭入口:脏表单先弹确认,取消则留在抽屉。 */
function requestClose() {
if (isDirty.value && !window.confirm(t('admin.integrationConnector.msg.unsavedConfirm'))) return;
emit('close');
}
/** Esc 关闭走同一确认入口。 */
function onKeydown(e: KeyboardEvent) {
if (e.key === 'Escape') requestClose();
}
watch(
() => props.visible,
(visible) => {
if (visible) {
initialSnapshot.value = JSON.stringify(activeForm.value);
document.addEventListener('keydown', onKeydown);
void nextTick(() => panelRef.value?.focus());
} else {
document.removeEventListener('keydown', onKeydown);
}
},
{ immediate: true },
);
onBeforeUnmount(() => document.removeEventListener('keydown', onKeydown));
</script>
<template>
<div
v-if="visible"
class="fixed inset-0 z-50 flex justify-end bg-overlay"
data-testid="connector-form-drawer"
@click.self="requestClose"
>
<aside
ref="panelRef"
tabindex="-1"
role="dialog"
aria-modal="true"
:aria-label="entityTitle"
class="h-full w-full max-w-4xl flex flex-col bg-surface shadow-2xl outline-none"
>
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-default shrink-0">
<h3 class="section-title">{{ entityTitle }}</h3>
<p class="section-desc mt-1">{{ entityHint }}</p>
</div>
<div class="px-5 sm:px-8 py-5 space-y-5 overflow-y-auto flex-1">
<!-- 客户端实例:基本信息 → 连接配置 → 高级 三段式 -->
<template v-if="activeEntity === 'client'">
<div class="space-y-4">
<h4 class="text-xs font-bold uppercase tracking-wide text-muted">{{ t('admin.integrationConnector.sections.basic') }}</h4>
<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.name') }}</label>
<input v-model="clientForm.name" type="text" class="input-field text-sm" data-testid="client-name" @blur="onClientNameBlur" />
</div>
<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 font-mono" :disabled="Boolean(clientForm.id)" data-testid="client-code" />
<p class="text-xs text-muted">{{ t('admin.integrationConnector.fields.codeHint') }}</p>
</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 v-for="opt in CONNECTOR_TYPE_OPTIONS" :key="opt.value" :value="opt.value">{{ t(opt.labelKey) }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.environment') }}</label>
<select v-model="clientForm.environment" class="input-field text-sm" data-testid="client-environment">
<option v-for="env in ENVIRONMENT_OPTIONS" :key="env" :value="env">{{ t(`admin.integrationConnector.envLabels.${env}`) }}</option>
</select>
</div>
</div>
</div>
<div class="space-y-4">
<h4 class="text-xs font-bold uppercase tracking-wide text-muted">{{ t('admin.integrationConnector.sections.connection') }}</h4>
<!-- 连接地址: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 class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.credentialRef') }}</label>
<select v-model="clientForm.credential_ref_code" class="input-field text-sm" data-testid="client-credential-ref">
<option value="">{{ t('admin.integrationConnector.fields.credentialNone') }}</option>
<option v-for="opt in credentialOptions || []" :key="opt.code" :value="opt.code">{{ opt.code }}</option>
</select>
<p class="text-xs text-muted">{{ t('admin.integrationConnector.fields.credentialRefHint') }}</p>
</div>
</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.sections.advanced') }}</summary>
<div class="mt-2 space-y-2">
<p class="text-xs text-muted">{{ clientConfigHint }}</p>
<JsonTextareaField
v-model="clientForm.config_json"
:label="t('admin.integrationConnector.fields.configJson')"
:placeholder="CLIENT_CONFIG_EXAMPLE"
/>
</div>
</details>
</template>
<!-- 接口定义:编码自动建议 + 类型随客户端联动(只读徽章)+ 接口契约 JSON 常显 + 状态只读徽章 -->
<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.name') }}</label>
<input v-model="interfaceForm.name" type="text" class="input-field text-sm" data-testid="interface-name" @blur="onInterfaceNameBlur" />
</div>
<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 font-mono" :disabled="Boolean(interfaceForm.id)" data-testid="interface-code" />
<p class="text-xs text-muted">{{ t('admin.integrationConnector.fields.codeHintInterface') }}</p>
</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" data-testid="interface-client" @change="onInterfaceClientChange">
<option v-for="opt in clientOptions" :key="opt.code" :value="opt.code">{{ optionLabel(opt.name, opt.code) }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.connectorType') }}</label>
<!-- 与客户端实例同款下拉控件、仅禁用只读:类型随客户端实例自动确定(后端以其为单一事实源推导),不可单独修改 -->
<select
:value="interfaceForm.connector_type"
class="input-field text-sm disabled:opacity-70"
disabled
data-testid="interface-connector-type"
>
<option :value="interfaceForm.connector_type">{{ connectorTypeLabel(interfaceForm.connector_type) }}</option>
</select>
<p class="text-xs text-muted">{{ t('admin.integrationConnector.fields.connectorTypeHint') }}</p>
</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>
<!-- 接口契约(请求模板/入参 Schema/回传映射/出参 Schema)即接口定义本体:常显纵向全宽,不再折叠 -->
<div class="space-y-4">
<h4 class="text-xs font-bold uppercase tracking-wide text-muted">{{ t('admin.integrationConnector.sections.contract') }}</h4>
<JsonTextareaField v-model="interfaceForm.request_spec_json" :label="t('admin.integrationConnector.fields.requestSpec')" />
<JsonTextareaField v-model="interfaceForm.input_schema_json" :label="t('admin.integrationConnector.fields.inputSchema')" />
<JsonTextareaField v-model="interfaceForm.response_mapping_json" :label="t('admin.integrationConnector.fields.responseMapping')" />
<JsonTextareaField v-model="interfaceForm.output_schema_json" :label="t('admin.integrationConnector.fields.outputSchema')" />
</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">{{ capabilityOptionLabel(cap.name) }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.environment') }}</label>
<select v-model="bindingForm.environment" class="input-field text-sm">
<option v-for="env in ENVIRONMENT_OPTIONS" :key="env" :value="env">{{ t(`admin.integrationConnector.envLabels.${env}`) }}</option>
</select>
</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 disabled:opacity-70" :disabled="Boolean(bindingForm.interface_definition_code)" data-testid="binding-client">
<option v-for="opt in clientOptions" :key="opt.code" :value="opt.code">{{ optionLabel(opt.name, opt.code) }}</option>
</select>
<p class="text-xs text-muted">{{ t('admin.integrationConnector.fields.bindingClientHint') }}</p>
</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" data-testid="binding-interface" @change="onBindingInterfaceChange">
<option v-for="opt in interfaceOptions" :key="opt.code" :value="opt.code">{{ optionLabel(opt.name, 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>
<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-2">
<JsonTextareaField v-model="bindingForm.context_selector_json" :label="t('admin.integrationConnector.fields.contextSelector')" />
<p class="text-xs text-muted">{{ t('admin.integrationConnector.fields.contextSelectorHint') }}</p>
<JsonTextareaField v-model="bindingForm.param_mapping_json" :label="t('admin.integrationConnector.fields.paramMapping')" />
<p class="text-xs text-muted">{{ t('admin.integrationConnector.fields.paramMappingHint') }}</p>
</div>
</details>
<!-- 状态不进表单正文:以底部操作条只读下拉展示(转移只经列表生命周期按钮) -->
</template>
<!-- 凭据引用:基本信息统一为正常表单控件(编辑态禁用只读,不用徽章形态);状态经底部启用开关随保存生效 -->
<template v-else>
<div class="space-y-4">
<h4 class="text-xs font-bold uppercase tracking-wide text-muted">{{ t('admin.integrationConnector.sections.basic') }}</h4>
<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 font-mono disabled:opacity-70" :disabled="isCredentialEdit" data-testid="credential-code" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.secretProvider') }}</label>
<!-- 编辑态禁用:db↔env 切换会让存量密文变孤儿数据或调用期晚失败,变更须新建引用 -->
<select v-model="credentialForm.secret_provider" class="input-field text-sm disabled:opacity-70" :disabled="isCredentialEdit" data-testid="credential-provider">
<option value="db">{{ credentialProviderLabel('db') }}</option>
<option value="env">{{ credentialProviderLabel('env') }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.credentialType') }}</label>
<!-- 编辑态禁用:类型决定密文字段结构,中途改类型会使存量密文失效,变更须新建引用 -->
<select
v-model="credentialForm.credential_type"
class="input-field text-sm disabled:opacity-70"
:disabled="isCredentialEdit || credentialForm.secret_provider !== 'db'"
data-testid="credential-type"
>
<option v-for="spec in credentialTypeOptions" :key="spec.type" :value="spec.type">{{ credentialTypeLabel(spec.type) }}</option>
</select>
</div>
</div>
<p v-if="isCredentialEdit" class="text-xs text-muted">{{ t('admin.integrationConnector.formHints.credentialImmutable') }}</p>
</div>
<!-- 凭据值段:db 按类型动态渲染(secret 字段加密落库不回显,编辑留空 = 保持旧值);env 只登记配置键名 -->
<div class="space-y-4">
<h4 class="text-xs font-bold uppercase tracking-wide text-muted">{{ t('admin.integrationConnector.sections.credentialValues') }}</h4>
<template v-if="credentialForm.secret_provider === 'db'">
<div v-if="credentialTypeSpec" class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div v-for="field in credentialTypeSpec.fields" :key="field.key" class="space-y-1.5">
<label class="label-field">
{{ credentialFieldLabel(field.key) }}
<span v-if="!field.secret" class="text-xs text-muted">({{ t('admin.integrationConnector.fields.visibleField') }})</span>
</label>
<input
v-model="credentialForm.fields[field.key]"
:type="field.secret ? 'password' : 'text'"
class="input-field text-sm"
:autocomplete="field.secret ? 'new-password' : 'off'"
:placeholder="field.secret && credentialForm.id ? t('admin.integrationConnector.placeholders.passwordKeep') : ''"
:data-testid="`credential-field-${field.key}`"
/>
</div>
</div>
<!-- 模板占位符以代码徽章逐个展示,供接口模板作者复制 -->
<div v-if="credentialPlaceholderKeys.length" class="flex flex-wrap items-center gap-2 text-xs text-muted">
<span>{{ t('admin.integrationConnector.msg.credentialPlaceholdersHint') }}</span>
<code
v-for="key in credentialPlaceholderKeys"
:key="key"
class="rounded bg-surface-soft px-1.5 py-0.5 font-mono text-[11px] text-secondary"
data-testid="credential-placeholder-chip"
>{{ key }}</code>
</div>
</template>
<div v-else 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" data-testid="credential-secret-ref" />
</div>
</div>
</template>
</div>
<div class="admin-modal-footer">
<!-- 启用开关置于操作条左侧(仅客户端实体):内容区滚动时始终可见;
小字「随保存操作生效」与列表行内开关的即时生效区分,悬停 title 显示停用的调用期后果 -->
<div v-if="activeEntity === 'client'" class="mr-auto flex items-center gap-2.5" data-testid="client-enabled-row">
<button
type="button"
role="switch"
:aria-checked="clientForm.enabled"
:title="t('admin.integrationConnector.fields.enabledHint')"
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors"
:class="clientForm.enabled ? 'bg-brand-600' : 'bg-slate-300'"
data-testid="client-enabled-switch"
@click="clientForm.enabled = !clientForm.enabled"
>
<span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform" :class="clientForm.enabled ? 'translate-x-4' : 'translate-x-0.5'" />
</button>
<span class="whitespace-nowrap text-sm font-medium text-secondary">{{ t('admin.integrationConnector.fields.enabled') }}</span>
<span class="whitespace-nowrap text-xs text-muted">{{ t('admin.integrationConnector.fields.enabledFooterHint') }}</span>
</div>
<!-- 凭据启用开关:同一底部形态;翻转 active↔retired,随「保存更改」提交(停用即断流,title 说明后果) -->
<div v-else-if="activeEntity === 'credential'" class="mr-auto flex items-center gap-2.5" data-testid="credential-enabled-row">
<button
type="button"
role="switch"
:aria-checked="credentialEnabled"
:title="t('admin.integrationConnector.fields.credentialEnabledHint')"
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors"
:class="credentialEnabled ? 'bg-brand-600' : 'bg-slate-300'"
data-testid="credential-enabled-switch"
@click="toggleCredentialEnabled"
>
<span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform" :class="credentialEnabled ? 'translate-x-4' : 'translate-x-0.5'" />
</button>
<span class="whitespace-nowrap text-sm font-medium text-secondary">{{ t('admin.integrationConnector.fields.enabled') }}</span>
<span class="whitespace-nowrap text-xs text-muted">{{ t('admin.integrationConnector.fields.enabledFooterHint') }}</span>
</div>
<!-- 接口/绑定生命周期状态:安静的状态指示器(彩点胶囊 + 悬停承载长说明)——
操作条不放表单控件与多行文案,转移入口在列表行内按钮 -->
<div v-else-if="activeEntity === 'interface' || activeEntity === 'binding'" class="mr-auto flex items-center gap-2" data-testid="lifecycle-status-row">
<span class="whitespace-nowrap text-xs text-muted">{{ t('admin.integrationConnector.fields.status') }}</span>
<span
class="inline-flex items-center gap-1.5 whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-medium"
:class="lifecycleChipClass"
:title="t('admin.integrationConnector.fields.statusHint')"
data-testid="lifecycle-status-chip"
>
<span class="h-1.5 w-1.5 rounded-full bg-current" />
{{ statusLabel(lifecycleStatus) }}
</span>
</div>
<button type="button" class="btn-ghost" @click="requestClose">{{ 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>
</aside>
</div>
</template>
@@ -1,96 +0,0 @@
/**
* 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);
});
});
@@ -1,277 +0,0 @@
<!--
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,82 @@
<!--
features/admin/modules/integration-connector/components/JsonTextareaField.vue
用途:JSON 配置字段统一编辑器——全宽等宽 textarea + 格式化按钮 + 失焦即时校验,
供本模块四实体表单(请求模板/Schema/映射/连接配置/上下文选择器)复用。
依赖:useI18n。
逻辑:v-model 承载 JSON 文本(由父级表单 state 持有);失焦时校验,非法显示红字
提示;「格式化」仅在合法 JSON 时 pretty-print 改写,非法时只提示不改写内容。
空值视为合法(与保存链路 parseJsonField 的「空串返回 {}」一致)。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
const props = defineProps<{
/** 字段标签,同时用于错误提示中的字段名。 */
label: string;
modelValue: string;
/** 可选占位示例(如高级配置的生效键示例),空内文时展示。 */
placeholder?: string;
}>();
const emit = defineEmits<{
'update:modelValue': [value: string];
}>();
const { t } = useI18n();
const touched = ref(false);
/** 是否为合法 JSON 对象文本;空串合法。 */
const isValid = computed(() => {
const trimmed = props.modelValue.trim();
if (!trimmed) return true;
try {
const parsed = JSON.parse(trimmed);
return Boolean(parsed) && typeof parsed === 'object' && !Array.isArray(parsed);
} catch {
return false;
}
});
function onBlur() {
touched.value = true;
}
/** 格式化(pretty-print);内容为空或非法时仅标记已触碰以显示校验提示。 */
function format() {
touched.value = true;
if (!isValid.value || !props.modelValue.trim()) return;
emit('update:modelValue', JSON.stringify(JSON.parse(props.modelValue.trim()), null, 2));
}
</script>
<template>
<div class="space-y-1.5">
<div class="flex items-center justify-between gap-2">
<label class="label-field">{{ label }}</label>
<button
type="button"
class="text-xs font-medium text-brand-600 hover:text-brand-700 disabled:opacity-50 disabled:cursor-not-allowed"
:disabled="!modelValue.trim()"
data-testid="json-format-button"
@click="format"
>
{{ t('admin.integrationConnector.formatJson') }}
</button>
</div>
<textarea
:value="modelValue"
rows="12"
class="input-field text-sm font-mono leading-5"
spellcheck="false"
:placeholder="placeholder"
data-testid="json-textarea"
@input="emit('update:modelValue', ($event.target as HTMLTextAreaElement).value)"
@blur="onBlur"
/>
<p v-if="touched && !isValid" class="text-xs text-red-600" data-testid="json-error">
{{ t('admin.integrationConnector.invalidJsonHint') }}
</p>
</div>
</template>
@@ -21,10 +21,13 @@ const api = vi.hoisted(() => ({
listIntegrationInterfaceDefinitions: vi.fn(),
createIntegrationInterfaceDefinition: vi.fn(),
updateIntegrationInterfaceDefinition: vi.fn(),
changeIntegrationInterfaceLifecycle: vi.fn(),
listIntegrationBindings: vi.fn(),
createIntegrationBinding: vi.fn(),
updateIntegrationBinding: vi.fn(),
changeIntegrationBindingLifecycle: vi.fn(),
listIntegrationCredentialReferences: vi.fn(),
listIntegrationCredentialTypes: vi.fn(),
createIntegrationCredentialReference: vi.fn(),
updateIntegrationCredentialReference: vi.fn(),
listIntegrationCapabilities: vi.fn(),
@@ -55,6 +58,7 @@ describe('useIntegrationConnectorAdmin', () => {
api.listIntegrationInterfaceDefinitions.mockResolvedValue([]);
api.listIntegrationBindings.mockResolvedValue([]);
api.listIntegrationCredentialReferences.mockResolvedValue([]);
api.listIntegrationCredentialTypes.mockResolvedValue([]);
api.listIntegrationCapabilities.mockResolvedValue([]);
const c = makeHarness();
await c.loadAll();
@@ -65,14 +69,14 @@ describe('useIntegrationConnectorAdmin', () => {
it('新建客户端实例:关键字段独立列 + config_json 解析为对象并 POST', async () => {
const c = makeHarness();
c.openCreateModal('client');
c.clientForm.value.code = 'ERP-X';
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',
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,
});
@@ -81,7 +85,7 @@ describe('useIntegrationConnectorAdmin', () => {
it('编辑客户端实例:有 id 走 PUT', async () => {
const c = makeHarness();
c.openEditModal('client', {
id: 1, code: 'ERP-X', name: 'old', connector_type: 'rest', environment: 'prod',
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';
@@ -92,22 +96,41 @@ describe('useIntegrationConnectorAdmin', () => {
it('非法 JSON 字段触发拦截且不调 API', async () => {
const c = makeHarness();
c.openCreateModal('client');
c.clientForm.value.code = 'ERP-X';
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 () => {
it('客户端实例必填:缺名称不调 API', async () => {
const c = makeHarness();
c.openCreateModal('client');
c.clientForm.value.name = 'ERP X';
c.clientForm.value.code = 'erp-x';
await c.saveActive();
expect(api.createIntegrationClientInstance).not.toHaveBeenCalled();
});
it('绑定:必填校验与 POST payload', async () => {
it('编码留空时按名称自动生成 kebab-case 并提交', async () => {
const c = makeHarness();
c.openCreateModal('client');
c.clientForm.value.name = 'ERP X';
await c.saveActive();
expect(api.createIntegrationClientInstance).toHaveBeenCalledWith(
expect.objectContaining({ code: 'erp-x', name: 'ERP X' }),
);
});
it('编码格式非法(大写/下划线)时不调 API', async () => {
const c = makeHarness();
c.openCreateModal('client');
c.clientForm.value.name = 'ERP X';
c.clientForm.value.code = 'Bad_Code';
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';
@@ -116,25 +139,134 @@ describe('useIntegrationConnectorAdmin', () => {
await c.saveActive();
expect(api.createIntegrationBinding).toHaveBeenCalledWith({
capability: 'in_transit_transfer.query_inventory', context_selector_json: {},
context_source_code: null,
param_mapping_json: {},
client_instance_code: 'CLI-A', interface_definition_code: 'IF-A',
mapping_version: 1, priority: 0, environment: 'prod',
effective_from: null, effective_to: null,
});
const payload = api.createIntegrationBinding.mock.calls[0][0] as Record<string, unknown>;
// 状态走列表生命周期按钮;客户端实例随接口定义联动(仍随 payload 提交)
expect(payload).not.toHaveProperty('status');
expect(payload).not.toHaveProperty('context_source_code');
});
it('绑定生命周期:publish 调动作端点并刷新绑定列表', async () => {
const c = makeHarness();
api.changeIntegrationBindingLifecycle.mockResolvedValue({});
api.listIntegrationBindings.mockResolvedValue([]);
c.bindings.value = [{
id: 7, capability: 'in_transit_transfer.query_inventory', context_selector_json: {},
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',
});
}];
await c.changeBindingLifecycle(c.bindings.value[0], 'publish');
expect(api.changeIntegrationBindingLifecycle).toHaveBeenCalledWith(7, 'publish');
expect(api.listIntegrationBindings).toHaveBeenCalled();
});
it('凭据引用:创建 payload 不含明文 secret', async () => {
it('接口定义:编码留空按「客户端编码-名称」建议;payload 不含 connector_type/status/enabled', async () => {
const c = makeHarness();
c.openCreateModal('interface');
c.interfaceForm.value.name = '鼎捷TOPGP库存查询GetItemStockList';
c.interfaceForm.value.client_instance_code = '1001';
await c.saveActive();
expect(api.createIntegrationInterfaceDefinition).toHaveBeenCalledWith(
expect.objectContaining({ code: '1001-topgp-getitemstocklist', client_instance_code: '1001' }),
);
const payload = api.createIntegrationInterfaceDefinition.mock.calls[0][0] as Record<string, unknown>;
// 类型由后端按客户端推导、状态走生命周期按钮:均不随表单 payload 提交
expect(payload).not.toHaveProperty('connector_type');
expect(payload).not.toHaveProperty('status');
expect(payload).not.toHaveProperty('enabled');
});
it('接口定义生命周期:publish 调动作端点并刷新接口列表', async () => {
const c = makeHarness();
api.changeIntegrationInterfaceLifecycle.mockResolvedValue({});
api.listIntegrationInterfaceDefinitions.mockResolvedValue([]);
c.interfaces.value = [{
id: 9, code: 'IF-LC', name: 'iface', client_instance_code: 'CLI-A', connector_type: 'rest',
http_method: null, request_path: null, request_spec_json: {}, input_schema_json: {},
response_mapping_json: {}, output_schema_json: {}, version: 1, status: 'draft', enabled: true,
}];
await c.changeInterfaceLifecycle(c.interfaces.value[0], 'publish');
expect(api.changeIntegrationInterfaceLifecycle).toHaveBeenCalledWith('IF-LC', 'publish');
expect(api.listIntegrationInterfaceDefinitions).toHaveBeenCalled();
});
it('凭据引用 env 模式:创建 payload 只含 secret_ref,不含明文 secret', async () => {
const c = makeHarness();
c.openCreateModal('credential');
c.credentialForm.value.secret_provider = 'env';
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',
code: 'CRED-A', secret_provider: 'env',
credential_type: 'password', status: 'active',
secret_ref: 'IN_TRANSIT_ERP_PASSWORD',
});
});
it('凭据引用 db 模式:创建 payload 按类型字段组装,不含 secret_ref', async () => {
const c = makeHarness();
c.credentialTypes.value = [
{ type: 'password', fields: [
{ key: 'username', secret: false, required: true },
{ key: 'password', secret: true, required: true },
] },
];
c.openCreateModal('credential');
c.credentialForm.value.code = 'CRED-DB';
c.credentialForm.value.fields = { username: 'erp_user', password: 'erp_pass' };
await c.saveActive();
expect(api.createIntegrationCredentialReference).toHaveBeenCalledWith({
code: 'CRED-DB', secret_provider: 'db',
credential_type: 'password', status: 'active',
username: 'erp_user', password: 'erp_pass',
});
});
it('凭据引用 db 模式:编辑时全部字段留空 → payload 不带凭据键(仅元数据)', async () => {
const c = makeHarness();
c.credentialTypes.value = [{ type: 'password', fields: [
{ key: 'username', secret: false, required: true },
{ key: 'password', secret: true, required: true },
] }];
c.openCreateModal('credential');
c.credentialForm.value.id = 9;
c.credentialForm.value.code = 'CRED-DB';
c.credentialForm.value.fields = {};
await c.saveActive();
expect(api.updateIntegrationCredentialReference).toHaveBeenCalledWith('CRED-DB', {
code: 'CRED-DB', secret_provider: 'db',
credential_type: 'password', status: 'active',
});
});
it('凭据引用 db 模式:新建缺必填字段 → 不调 API', async () => {
const c = makeHarness();
c.credentialTypes.value = [{ type: 'password', fields: [
{ key: 'username', secret: false, required: true },
{ key: 'password', secret: true, required: true },
] }];
c.openCreateModal('credential');
c.credentialForm.value.code = 'CRED-DB';
c.credentialForm.value.fields = { username: 'only-user' };
await c.saveActive();
expect(api.createIntegrationCredentialReference).not.toHaveBeenCalled();
});
it('凭据引用 db 模式:类型未注册 → 不调 API', async () => {
const c = makeHarness();
c.openCreateModal('credential');
c.credentialForm.value.code = 'CRED-X';
c.credentialForm.value.credential_type = 'unknown';
await c.saveActive();
expect(api.createIntegrationCredentialReference).not.toHaveBeenCalled();
});
it('连接测试与能力调用走对应 API', async () => {
const c = makeHarness();
api.testIntegrationClientConnection.mockResolvedValue({ ok: true });
@@ -145,4 +277,102 @@ describe('useIntegrationConnectorAdmin', () => {
await c.runCall();
expect(api.callIntegrationCapability).toHaveBeenCalled();
});
it('连接测试结果按行存放:probe 失败归 ok=false 并带原因码', async () => {
const c = makeHarness();
api.testIntegrationClientConnection.mockResolvedValue({
ok: false, status: 'failed', result: { ok: false, code: 'HTTP_502', message: 'bad gateway' },
});
await c.testConnection('CLI-A');
expect(c.testResults.value['CLI-A']).toEqual({ ok: false, code: 'HTTP_502', message: 'bad gateway' });
});
it('行内启停:切换调用 PUT,失败自动回滚', async () => {
const c = makeHarness();
api.updateIntegrationClientInstance.mockRejectedValue(new Error('network down'));
const row = { code: 'CLI-A', enabled: true };
await c.toggleClient(row);
expect(api.updateIntegrationClientInstance).toHaveBeenCalledWith('CLI-A', { enabled: false });
expect(row.enabled).toBe(true);
api.updateIntegrationClientInstance.mockResolvedValue({});
await c.toggleClient(row);
expect(row.enabled).toBe(false);
});
it('凭据状态行内切换:只传 status 调 PUT,rotating 视为启用侧,失败回滚', async () => {
const c = makeHarness();
api.updateIntegrationCredentialReference.mockResolvedValue({});
const row = { code: 'CRED-A', status: 'active' };
await c.toggleCredential(row);
expect(api.updateIntegrationCredentialReference).toHaveBeenCalledWith('CRED-A', { status: 'retired' });
expect(row.status).toBe('retired');
// rotating 非停用态:点击即停用
const rotating = { code: 'CRED-B', status: 'rotating' };
await c.toggleCredential(rotating);
expect(api.updateIntegrationCredentialReference).toHaveBeenCalledWith('CRED-B', { status: 'retired' });
// 停用态点击切回启用;失败时回滚保持停用
api.updateIntegrationCredentialReference.mockRejectedValue(new Error('network down'));
await c.toggleCredential(row);
expect(row.status).toBe('retired');
});
it('删除客户端实例需确认:拒绝不调 API,确认才删', async () => {
const c = makeHarness();
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
await c.deleteClient({ code: 'CLI-A', name: '客户端A' });
expect(confirmSpy).toHaveBeenCalledTimes(1);
expect(api.deleteIntegrationClientInstance).not.toHaveBeenCalled();
confirmSpy.mockReturnValue(true);
await c.deleteClient({ code: 'CLI-A', name: '客户端A' });
expect(api.deleteIntegrationClientInstance).toHaveBeenCalledWith('CLI-A');
vi.restoreAllMocks();
});
it('接口退役需确认:拒绝不调 API,确认才调', async () => {
const c = makeHarness();
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
api.changeIntegrationInterfaceLifecycle.mockResolvedValue({});
api.listIntegrationInterfaceDefinitions.mockResolvedValue([]);
c.interfaces.value = [{
id: 3, code: 'IF-R', name: 'iface', client_instance_code: 'CLI-A', connector_type: 'rest',
http_method: null, request_path: null, request_spec_json: {}, input_schema_json: {},
response_mapping_json: {}, output_schema_json: {}, version: 1, status: 'published', enabled: true,
}];
// 退役接近终态且使引用绑定同时失效:确认拒绝则不调 API
await c.changeInterfaceLifecycle(c.interfaces.value[0], 'retire');
expect(confirmSpy).toHaveBeenCalledTimes(1);
expect(api.changeIntegrationInterfaceLifecycle).not.toHaveBeenCalled();
confirmSpy.mockReturnValue(true);
await c.changeInterfaceLifecycle(c.interfaces.value[0], 'retire');
expect(api.changeIntegrationInterfaceLifecycle).toHaveBeenCalledWith('IF-R', 'retire');
vi.restoreAllMocks();
});
it('可逆转移(撤回)免确认直达;进行中重复触发被互斥忽略', async () => {
const c = makeHarness();
const confirmSpy = vi.spyOn(window, 'confirm');
let resolveApi!: (value: unknown) => void;
api.changeIntegrationInterfaceLifecycle.mockImplementation(
() => new Promise((resolve) => { resolveApi = resolve; }),
);
api.listIntegrationInterfaceDefinitions.mockResolvedValue([]);
c.interfaces.value = [{
id: 4, code: 'IF-U', name: 'iface', client_instance_code: 'CLI-A', connector_type: 'rest',
http_method: null, request_path: null, request_spec_json: {}, input_schema_json: {},
response_mapping_json: {}, output_schema_json: {}, version: 1, status: 'published', enabled: true,
}];
// 第一次触发占用互斥锁;第二次在其完成前触发应被忽略(防连点)
const first = c.changeInterfaceLifecycle(c.interfaces.value[0], 'unpublish');
const second = c.changeInterfaceLifecycle(c.interfaces.value[0], 'unpublish');
resolveApi({});
await Promise.all([first, second]);
expect(api.changeIntegrationInterfaceLifecycle).toHaveBeenCalledTimes(1);
// 可逆转移不弹确认
expect(confirmSpy).not.toHaveBeenCalled();
vi.restoreAllMocks();
});
});
@@ -3,14 +3,23 @@
* 集成连接器管理编排:客户端实例/接口定义/绑定/凭据引用四实体列表与增改表单,
* 以及能力清单与手动调用测试。
* 依赖:integration-connector.api、types、useMessage、useI18n。
* 逻辑:各列表独立 loadAll;新增/编辑共用表单弹窗态(form.id 区分);能力测试
* 独立于配置表单(CapabilityCall 弹窗)。保存/删除后刷新对应列表。
* 逻辑:各列表独立 loadAll;新增/编辑共用表单弹窗态(form.id 区分);客户端编码
* 可手改、留空按名称自动生成,接口定义编码留空按「客户端编码-名称」自动建议;
* 接口与绑定状态只经 change*Lifecycle 按钮流转(表单内只读徽章);绑定表单的
* 客户端实例随所选接口定义联动带出并锁定(接口归属即客户端归属);
* 凭据状态只经列表行内开关流转(启用↔停用,表单不维护状态);
* 全部行内状态操作经 lifecycleBusy 互斥(进行中忽略新触发);接口/绑定退役
* 接近终态需 window.confirm 二次确认,可逆转移直达;
* 连接测试结果按行存放(列表徽章+展开详情);
* 启停支持行内开关(失败回滚);删除带确认。保存/删除后刷新对应列表。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '@/shared/composables/useMessage';
import {
callIntegrationCapability,
changeIntegrationBindingLifecycle,
changeIntegrationInterfaceLifecycle,
createIntegrationBinding,
createIntegrationClientInstance,
createIntegrationCredentialReference,
@@ -20,6 +29,7 @@ import {
listIntegrationCapabilities,
listIntegrationClientInstances,
listIntegrationCredentialReferences,
listIntegrationCredentialTypes,
listIntegrationInterfaceDefinitions,
testIntegrationClientConnection,
updateIntegrationBinding,
@@ -30,13 +40,18 @@ import {
import {
bindingRowToForm,
clientInstanceRowToForm,
CLIENT_CODE_PATTERN,
createEmptyBindingForm,
createEmptyClientInstanceForm,
createEmptyCredentialReferenceForm,
createEmptyInterfaceDefinitionForm,
credentialReferenceRowToForm,
interfaceDefinitionRowToForm,
normalizeConnectionTestResponse,
suggestClientCode,
suggestInterfaceCode,
type BindingFormState,
type ClientConnectionTestResult,
type ClientInstanceFormState,
type CredentialReferenceFormState,
type IntegrationBindingRow,
@@ -44,12 +59,17 @@ import {
type IntegrationCapabilityRow,
type IntegrationClientInstanceRow,
type IntegrationCredentialReferenceRow,
type IntegrationCredentialTypeSpec,
type IntegrationInterfaceDefinitionRow,
type InterfaceDefinitionFormState,
} from '../types/integration-connector.types';
type EditableEntity = 'client' | 'interface' | 'binding' | 'credential';
/** 接口定义/绑定生命周期动作(与后端 CONFIG_STATUS_TRANSITIONS 一一对应)。 */
export type InterfaceLifecycleAction = 'publish' | 'unpublish' | 'retire' | 'reopen';
export type BindingLifecycleAction = InterfaceLifecycleAction;
export function useIntegrationConnectorAdmin() {
const { t } = useI18n();
const msg = useMessage();
@@ -60,6 +80,7 @@ export function useIntegrationConnectorAdmin() {
const bindings = ref<IntegrationBindingRow[]>([]);
const credentials = ref<IntegrationCredentialReferenceRow[]>([]);
const capabilities = ref<IntegrationCapabilityRow[]>([]);
const credentialTypes = ref<IntegrationCredentialTypeSpec[]>([]);
const isLoading = ref(true);
// ---- 表单弹窗态 ----
@@ -79,14 +100,32 @@ export function useIntegrationConnectorAdmin() {
const callResult = ref<IntegrationCallResultRow | null>(null);
const callBusy = ref(false);
// ---- 连接测试 ----
// ---- 连接测试(结果按客户端编码存放,供列表行内徽章 + 可展开详情) ----
const testingClientCode = ref('');
const testResultText = ref('');
const testResults = ref<Record<string, ClientConnectionTestResult>>({});
// ---- 状态转移互斥锁:任一启停/生命周期转移进行中即忽略新转移,防连点与并发转移 ----
const lifecycleBusy = ref(false);
/** 行内状态操作统一入口:busy 互斥包裹,进行中重复触发直接忽略。 */
const runStateToggle = async (fn: () => Promise<void>) => {
if (lifecycleBusy.value) return;
lifecycleBusy.value = true;
try {
await fn();
} finally {
lifecycleBusy.value = false;
}
};
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 loadCredentials = async () => {
const [rows, typeSpecs] = await Promise.all([listIntegrationCredentialReferences(), listIntegrationCredentialTypes()]);
credentials.value = rows;
credentialTypes.value = typeSpecs;
};
const loadCapabilities = async () => { capabilities.value = await listIntegrationCapabilities(); };
const loadAll = async () => {
@@ -154,37 +193,45 @@ export function useIntegrationConnectorAdmin() {
try {
if (activeEntity.value === 'client') {
const form = clientForm.value;
if (!form.code.trim() || !form.name.trim()) {
if (!form.name.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillClient'));
return;
}
// 编码可由用户手改;留空时按名称兜底自动生成(唯一性由后端 409 兜底)。
const code = form.code.trim() || suggestClientCode(form.name);
if (!CLIENT_CODE_PATTERN.test(code)) {
msg.warning(t('admin.integrationConnector.msg.codeInvalid'));
return;
}
const configJson = parseJsonField(form.config_json, 'config_json');
const payload = {
code: form.code.trim(), name: form.name.trim(), connector_type: form.connector_type,
code, 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);
if (form.id) await updateIntegrationClientInstance(code, payload);
else await createIntegrationClientInstance(payload);
} else if (activeEntity.value === 'interface') {
const form = interfaceForm.value;
if (!form.code.trim() || !form.client_instance_code.trim()) {
if (!form.client_instance_code.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillInterface'));
return;
}
// 编码留空时按「客户端实例编码-名称」自动建议(可手改;全局唯一由后端 409 兜底)。
// 连接器类型/状态/启用不随表单提交:类型由后端按客户端实例推导,状态走生命周期按钮。
const code = form.code.trim() || suggestInterfaceCode(form.client_instance_code, form.name);
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,
code, name: form.name.trim() || code,
client_instance_code: form.client_instance_code.trim(),
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);
@@ -194,26 +241,55 @@ export function useIntegrationConnectorAdmin() {
msg.warning(t('admin.integrationConnector.msg.fillBinding'));
return;
}
// 客户端实例随所选接口定义联动带出(接口归属即客户端归属);
// 状态不随表单提交:新建固定 draft,发布/退役走列表生命周期按钮。
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,
param_mapping_json: parseJsonField(form.param_mapping_json, 'param_mapping_json'),
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()) {
// db 模式:按凭据类型注册表动态字段,界面维护、服务端加密落库;
// 编辑时密文字段留空 = 沿用旧值。env 模式:只存环境配置键名。
if (!form.code.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,
const payload: Record<string, unknown> = {
code: form.code.trim(), secret_provider: form.secret_provider,
credential_type: form.credential_type, status: form.status,
};
if (form.secret_provider === 'db') {
const typeSpec = credentialTypes.value.find((item) => item.type === form.credential_type);
if (!typeSpec) {
msg.warning(t('admin.integrationConnector.msg.credentialTypeMissing'));
return;
}
if (!form.id) {
const missing = typeSpec.fields
.filter((field) => field.required && !(form.fields[field.key] || '').trim())
.map((field) => t(`admin.integrationConnector.credentialFields.${field.key}`, field.key));
if (missing.length) {
msg.warning(t('admin.integrationConnector.msg.fillCredentialDb', { fields: missing.join('、') }));
return;
}
}
for (const field of typeSpec.fields) {
const value = (form.fields[field.key] || '').trim();
if (value) payload[field.key] = value;
}
} else {
if (!form.secret_ref.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillCredential'));
return;
}
payload.secret_ref = form.secret_ref.trim();
}
if (form.id) await updateIntegrationCredentialReference(form.code, payload);
else await createIntegrationCredentialReference(payload);
}
@@ -233,11 +309,11 @@ export function useIntegrationConnectorAdmin() {
// ---- 连接测试 ----
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'));
const normalized = normalizeConnectionTestResponse(await testIntegrationClientConnection(code));
testResults.value = { ...testResults.value, [code]: normalized };
if (normalized.ok) msg.success(t('admin.integrationConnector.msg.testOk'));
else msg.error(t('admin.integrationConnector.msg.testFailed', { code: normalized.code }));
} catch (e) {
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
@@ -245,6 +321,64 @@ export function useIntegrationConnectorAdmin() {
}
};
// ---- 行内启停:直接切换 enabled;失败回滚并提示 ----
const toggleClient = async (row: IntegrationClientInstanceRow) => {
await runStateToggle(async () => {
const target = !row.enabled;
row.enabled = target;
try {
await updateIntegrationClientInstance(row.code, { enabled: target });
} catch (e) {
row.enabled = !target;
msg.error((e as Error).message || t('admin.integrationConnector.msg.toggleFailed'));
}
});
};
// ---- 凭据状态行内切换:启用↔停用(rotating 视为启用侧,点击即停用);解析层只认 active,停用即断流;失败回滚并提示 ----
const toggleCredential = async (row: IntegrationCredentialReferenceRow) => {
await runStateToggle(async () => {
const target = row.status === 'retired' ? 'active' : 'retired';
const prev = row.status;
row.status = target;
try {
await updateIntegrationCredentialReference(row.code, { status: target });
} catch (e) {
row.status = prev;
msg.error((e as Error).message || t('admin.integrationConnector.msg.toggleFailed'));
}
});
};
// ---- 接口定义生命周期:发布/撤回/退役/恢复(状态唯一入口,后端转移表校验) ----
// 退役接近终态且使引用该接口的绑定同时失效 → 二次确认;其余转移可逆,免确认直达。
const changeInterfaceLifecycle = async (row: IntegrationInterfaceDefinitionRow, action: InterfaceLifecycleAction) => {
await runStateToggle(async () => {
if (action === 'retire' && !window.confirm(t('admin.integrationConnector.msg.retireInterfaceConfirm'))) return;
try {
await changeIntegrationInterfaceLifecycle(row.code, action);
await loadInterfaces();
msg.success(t('admin.integrationConnector.msg.statusUpdated'));
} catch (e) {
msg.error((e as Error).message || t('admin.integrationConnector.msg.statusUpdateFailed'));
}
});
};
// ---- 绑定生命周期:发布/撤回/退役/恢复(状态唯一入口,后端转移表 + 发布就绪门禁校验) ----
const changeBindingLifecycle = async (row: IntegrationBindingRow, action: BindingLifecycleAction) => {
await runStateToggle(async () => {
if (action === 'retire' && !window.confirm(t('admin.integrationConnector.msg.retireBindingConfirm'))) return;
try {
await changeIntegrationBindingLifecycle(row.id, action);
await loadBindings();
msg.success(t('admin.integrationConnector.msg.statusUpdated'));
} catch (e) {
msg.error((e as Error).message || t('admin.integrationConnector.msg.statusUpdateFailed'));
}
});
};
// ---- 能力调用测试 ----
const openCallModal = (capability: string) => {
callCapability.value = capability;
@@ -274,9 +408,14 @@ export function useIntegrationConnectorAdmin() {
}
};
const deleteClient = async (code: string) => {
/** 删除客户端实例:先确认(提示语带名称),确认后才调 API。 */
const deleteClient = async (row: IntegrationClientInstanceRow) => {
const summary = t('admin.integrationConnector.msg.deleteConfirm', { code: row.code, name: row.name });
if (!window.confirm(summary)) return;
try {
await deleteIntegrationClientInstance(code);
await deleteIntegrationClientInstance(row.code);
const { [row.code]: _removed, ...rest } = testResults.value;
testResults.value = rest;
await loadClients();
msg.success(t('admin.integrationConnector.msg.deleted'));
} catch (e) {
@@ -285,12 +424,14 @@ export function useIntegrationConnectorAdmin() {
};
return {
clients, interfaces, bindings, credentials, capabilities,
clients, interfaces, bindings, credentials, capabilities, credentialTypes,
isLoading, activeEntity, showFormModal, isSaving,
clientForm, interfaceForm, bindingForm, credentialForm,
showCallModal, callCapability, callParamsText, callContextText, callResult, callBusy,
testingClientCode, testResultText,
testingClientCode, testResults,
lifecycleBusy,
loadAll, openCreateModal, openEditModal, closeFormModal, saveActive,
testConnection, openCallModal, closeCallModal, runCall, deleteClient,
testConnection, toggleClient, toggleCredential, openCallModal, closeCallModal, runCall, deleteClient,
changeInterfaceLifecycle, changeBindingLifecycle,
};
}
@@ -9,12 +9,104 @@
/** 连接器类型:与后端 CONNECTOR_TYPES 对齐。 */
export type IntegrationConnectorType = 'rest' | 'soap';
/** 连接器类型选项(labelKey 为 i18n 键;新增类型在此追加一行并补四语言文案)。 */
export const CONNECTOR_TYPE_OPTIONS: ReadonlyArray<{ value: IntegrationConnectorType; labelKey: string }> = [
{ value: 'rest', labelKey: 'admin.integrationConnector.connectorTypes.rest' },
{ value: 'soap', labelKey: 'admin.integrationConnector.connectorTypes.soap' },
];
/** 环境选项(与发布流程 dev→test→prod 对齐;新增环境在此追加并补四语言文案)。 */
export const ENVIRONMENT_OPTIONS = ['dev', 'test', 'prod'] as const;
/** 各连接器类型当前生效的 config_json 键(高级配置帮助文案依据,与 transports 消费代码对齐)。 */
export const CONNECTOR_CONFIG_KEYS: Readonly<Record<string, ReadonlyArray<string>>> = {
rest: ['headers'],
soap: [],
};
/** 客户端编码规则:小写字母/数字开头,仅小写字母、数字、连字符(保存后不可改)。 */
export const CLIENT_CODE_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
/** 编码最大长度(与后端 String(64) 列宽一致)。 */
const CODE_MAX_LENGTH = 64;
/** 由名称提取编码 slug:拉丁字符转 kebab-case;无拉丁字符(如纯中文)返回空串。 */
function slugifyName(name: string): string {
return String(name || '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
}
/** 由名称建议客户端编码:slug 为空时回退 conn-xxxx(可手改,保存后不可改)。 */
export function suggestClientCode(name: string): string {
const slug = slugifyName(name);
if (slug) return slug.slice(0, CODE_MAX_LENGTH);
return `conn-${Math.random().toString(36).slice(2, 6)}`;
}
/**
* 建议接口定义编码:客户端编码前缀 + 名称 slug(如 1001-topgp-getitemstocklist)。
* 前缀降低跨客户端撞码概率,slug 保证同一客户端下多个接口可区分;
* 仅是建议值(可手改),全局唯一仍由后端 409 兜底。
*/
export function suggestInterfaceCode(clientCode: string, name: string): string {
const prefix = String(clientCode || '').trim();
if (!prefix) return '';
const slug = slugifyName(name);
const suffix = slug || Math.random().toString(36).slice(2, 6);
return `${prefix}-${suffix}`.slice(0, CODE_MAX_LENGTH);
}
/** 行内连接测试结果(列表徽章 + 可展开详情的数据模型)。 */
export interface ClientConnectionTestResult {
ok: boolean;
code: string;
message: string;
}
/** 连接测试接口响应(后端返回 { ok, status, result },result 为传输层 raw dict)。 */
export interface ClientConnectionTestResponse {
ok?: boolean;
status?: string;
result?: Record<string, unknown>;
}
const CALL_FAILURE_STATUSES = ['business_failed', 'technical_failed', 'timeout', 'result_unknown'];
/** 把连接测试响应归一为行内展示模型:优先 probe 结果;回退兼容只实现 call 的传输 raw dict。 */
export function normalizeConnectionTestResponse(response: ClientConnectionTestResponse): ClientConnectionTestResult {
const raw = response.result ?? {};
if (typeof raw.ok === 'boolean') {
return { ok: raw.ok, code: String(raw.code ?? ''), message: String(raw.message ?? '') };
}
const status = String(raw.status ?? response.status ?? '');
return {
ok: !CALL_FAILURE_STATUSES.includes(status),
code: String(raw.code ?? status),
message: String(raw.message ?? ''),
};
}
/** 配置状态:draft 草稿 / published 已发布 / retired 已退役。 */
export type IntegrationConfigStatus = 'draft' | 'published' | 'retired';
/** 凭据状态。 */
export type IntegrationCredentialStatus = 'active' | 'rotating' | 'retired';
/** 凭据类型字段定义(secret=加密落库且永不回显;required 合并旧值后仍必填)。 */
export interface IntegrationCredentialTypeField {
key: string;
secret: boolean;
required: boolean;
}
/** 凭据类型规格(后端代码注册表下发,UI 按其动态渲染字段)。 */
export interface IntegrationCredentialTypeSpec {
type: string;
fields: IntegrationCredentialTypeField[];
}
/** 能力清单项(后端 capability 注册表)。 */
export interface IntegrationCapabilityRow {
name: string;
@@ -71,7 +163,7 @@ export interface IntegrationBindingRow {
id: number;
capability: string;
context_selector_json: Record<string, unknown>;
context_source_code: string | null;
param_mapping_json: Record<string, unknown>;
client_instance_code: string;
interface_definition_code: string;
mapping_version: number;
@@ -82,15 +174,18 @@ export interface IntegrationBindingRow {
status: IntegrationConfigStatus;
}
/** 凭据引用(只存 secret_ref,不落明文)。 */
/** 凭据引用(db 模式按类型加密落库不落明文;env 模式存环境配置键名)。 */
export interface IntegrationCredentialReferenceRow {
id: number;
code: string;
secret_ref: string;
secret_provider: string;
credential_type: string;
secret_fields: Record<string, string>;
has_secret: boolean;
version: number;
status: IntegrationCredentialStatus;
updated_at: string | null;
last_verified_at: string | null;
}
@@ -108,7 +203,11 @@ export interface ClientInstanceFormState {
enabled: boolean;
}
/** 接口定义表单(JSON 字段以文本承载,提交时解析)。 */
/**
* 接口定义表单(JSON 字段以文本承载,提交时解析)。
* connector_type 仅作展示:随所选客户端实例联动回填,提交时后端以客户端实例为单一事实源推导;
* status 仅作徽章展示:新建固定 draft,发布/退役经列表生命周期按钮流转,均不随表单提交。
*/
export interface InterfaceDefinitionFormState {
id: number | null;
code: string;
@@ -122,15 +221,18 @@ export interface InterfaceDefinitionFormState {
response_mapping_json: string;
output_schema_json: string;
status: IntegrationConfigStatus;
enabled: boolean;
}
/** 绑定表单。 */
/**
* 绑定表单(JSON 字段以文本承载,提交时解析)。
* client_instance_code 随所选接口定义联动带出并锁定(接口归属即客户端归属),仍随表单提交;
* status 仅作徽章展示:新建固定 draft,发布/退役经列表生命周期按钮流转,均不随表单提交。
*/
export interface BindingFormState {
id: number | null;
capability: string;
context_selector_json: string;
context_source_code: string;
param_mapping_json: string;
client_instance_code: string;
interface_definition_code: string;
mapping_version: number;
@@ -141,13 +243,14 @@ export interface BindingFormState {
status: IntegrationConfigStatus;
}
/** 凭据引用表单。 */
/** 凭据引用表单(按凭据类型动态字段;fields 值留空 = 编辑时保持旧值)。 */
export interface CredentialReferenceFormState {
id: number | null;
code: string;
secret_ref: string;
secret_provider: string;
credential_type: string;
fields: Record<string, string>;
status: IntegrationCredentialStatus;
}
@@ -188,7 +291,7 @@ export function clientInstanceRowToForm(row: IntegrationClientInstanceRow): Clie
};
}
/** 创建空的接口定义表单。 */
/** 创建空的接口定义表单(新建固定落 draft,上线走列表「发布」按钮)。 */
export function createEmptyInterfaceDefinitionForm(): InterfaceDefinitionFormState {
return {
id: null,
@@ -203,11 +306,10 @@ export function createEmptyInterfaceDefinitionForm(): InterfaceDefinitionFormSta
response_mapping_json: '',
output_schema_json: '',
status: 'draft',
enabled: true,
};
}
/** 列表行回填为接口定义编辑表单。 */
/** 列表行回填为接口定义编辑表单(connector_type/status 仅回显,不随保存提交)。 */
export function interfaceDefinitionRowToForm(row: IntegrationInterfaceDefinitionRow): InterfaceDefinitionFormState {
return {
id: row.id,
@@ -222,7 +324,6 @@ export function interfaceDefinitionRowToForm(row: IntegrationInterfaceDefinition
response_mapping_json: toJsonText(row.response_mapping_json),
output_schema_json: toJsonText(row.output_schema_json),
status: row.status,
enabled: Boolean(row.enabled),
};
}
@@ -232,7 +333,7 @@ export function createEmptyBindingForm(): BindingFormState {
id: null,
capability: '',
context_selector_json: '',
context_source_code: '',
param_mapping_json: '',
client_instance_code: '',
interface_definition_code: '',
mapping_version: 1,
@@ -244,13 +345,13 @@ export function createEmptyBindingForm(): BindingFormState {
};
}
/** 列表行回填为绑定编辑表单。 */
/** 列表行回填为绑定编辑表单(status 仅回显,不随保存提交)。 */
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 ?? '',
param_mapping_json: toJsonText(row.param_mapping_json),
client_instance_code: row.client_instance_code,
interface_definition_code: row.interface_definition_code,
mapping_version: Number(row.mapping_version || 1),
@@ -262,19 +363,20 @@ export function bindingRowToForm(row: IntegrationBindingRow): BindingFormState {
};
}
/** 创建空的凭据引用表单。 */
/** 创建空的凭据引用表单(管理端默认 db 模式 + password 类型:界面维护、加密落库、免重启)。 */
export function createEmptyCredentialReferenceForm(): CredentialReferenceFormState {
return {
id: null,
code: '',
secret_ref: '',
secret_provider: 'env',
secret_provider: 'db',
credential_type: 'password',
fields: {},
status: 'active',
};
}
/** 列表行回填为凭据引用编辑表单。 */
/** 列表行回填为凭据引用编辑表单(密文字段不回填,留空 = 保持旧值)。 */
export function credentialReferenceRowToForm(row: IntegrationCredentialReferenceRow): CredentialReferenceFormState {
return {
id: row.id,
@@ -282,6 +384,7 @@ export function credentialReferenceRowToForm(row: IntegrationCredentialReference
secret_ref: row.secret_ref,
secret_provider: row.secret_provider,
credential_type: row.credential_type,
fields: { ...(row.secret_fields ?? {}) },
status: row.status,
};
}
@@ -124,93 +124,49 @@
<label><span>{{ t('admin.shippingInventory.inventorySiteName') }}</span><input v-model="source.display_name" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.connectorType') }}</span><select v-model="source.connector_type" class="select-field"><option value="dbs">{{ t('admin.shippingInventory.platform.dbs') }}</option><option value="crane">{{ t('admin.shippingInventory.platform.crane') }}</option></select></label>
<label><span>{{ t('admin.shippingInventory.connection') }}</span><select v-model.number="source.rpa_profile_id" class="select-field" required><option :value="0">{{ t('admin.shippingInventory.chooseConnection') }}</option><option v-for="item in compatibleProfiles" :key="String(item.id)" :value="Number(item.id)">{{ item.display_name || item.profile_code }}</option></select></label>
<label><span>{{ t('admin.shippingInventory.parsingProfiles') }}</span><select v-model.number="source.parsing_profile_id" class="select-field" :disabled="source.enabled"><option :value="0">{{ t('admin.shippingInventory.notConfigured') }}</option><option v-for="item in parsingProfiles.filter((row) => row.status === 'published')" :key="String(item.id)" :value="Number(item.id)">{{ item.display_name || item.profile_code }} V{{ item.version }}</option></select></label>
<label><span>{{ t('admin.shippingInventory.parsingProfiles') }}</span><select v-model.number="source.parsing_profile_id" class="select-field" :disabled="source.enabled"><option :value="0">{{ t('admin.shippingInventory.notConfigured') }}</option><option v-for="item in parsingProfiles.filter((row) => row.status === 'published' && row.purpose !== 'movement')" :key="String(item.id)" :value="Number(item.id)">{{ item.display_name || item.profile_code }} V{{ item.version }}</option></select></label>
<label><span>{{ t('admin.shippingInventory.excelTemplates') }}</span><select v-model.number="source.excel_template_id" class="select-field"><option :value="0">{{ t('admin.shippingInventory.notConfigured') }}</option><option v-for="item in excelTemplates.filter((row) => row.status === 'published')" :key="String(item.id)" :value="Number(item.id)">{{ item.display_name || item.template_code }}</option></select></label>
<label><span>{{ t('admin.shippingInventory.warehouseResolution') }}</span><select v-model="source.warehouse_resolution_mode" class="select-field"><option value="fixed">{{ t('admin.shippingInventory.fixedWarehouse') }}</option><option value="inventory_match">{{ t('admin.shippingInventory.inventoryMatch') }}</option></select></label>
<label v-if="source.warehouse_resolution_mode === 'fixed'"><span>{{ t('admin.shippingInventory.warehouse') }}</span><input v-model="source.fixed_warehouse_id" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.snapshotTtl') }}</span><input v-model.number="source.snapshot_ttl_seconds" class="input-field" min="1" type="number" required></label>
<section v-if="selectedId" class="readiness-card full" :class="{ ready: source.enabled }">
<header class="readiness-heading">
<div>
<span class="readiness-kicker">{{ t('admin.shippingInventory.activationStatus') }}</span>
<strong>{{ readinessHeadline }}</strong>
<p>{{ readinessGuidance }}</p>
</div>
<span class="readiness-count">{{ readinessSummary }}</span>
</header>
<section class="readiness-section">
<div class="readiness-section-heading">
<b>{{ t('admin.shippingInventory.activationRequiredTitle') }}</b>
<small>{{ t('admin.shippingInventory.activationRequiredHint') }}</small>
</div>
<ol v-if="firstBlockingCheck && !source.enabled" class="readiness-steps">
<li :class="`is-${firstBlockingCheck.status}`">
<span class="readiness-marker" aria-hidden="true">{{ readinessMarker(firstBlockingCheck.status) }}</span>
<div class="readiness-copy"><b>{{ t(`admin.shippingInventory.activationRequirement.${firstBlockingCheck.code}`) }}</b><small>{{ readinessDetail(firstBlockingCheck) }}</small></div>
<button v-if="readinessActionLabel(firstBlockingCheck)" type="button" class="readiness-action" :disabled="isReadinessActionBlocked(firstBlockingCheck)" :title="isReadinessActionBlocked(firstBlockingCheck) ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined" @click="runReadinessAction(firstBlockingCheck)">{{ readinessActionLabel(firstBlockingCheck) }}</button>
</li>
</ol>
</section>
<details v-if="optionalReadinessChecks.length" class="readiness-optional">
<summary><span>{{ t('admin.shippingInventory.activationOptionalTitle') }}</span><small>{{ t('admin.shippingInventory.activationOptionalHint') }}</small></summary>
<ol class="readiness-steps">
<li v-for="check in optionalReadinessChecks" :key="check.code" :class="`is-${check.status}`">
<span class="readiness-marker" aria-hidden="true">{{ readinessMarker(check.status) }}</span>
<div class="readiness-copy"><b>{{ t(`admin.shippingInventory.activationRequirement.${check.code}`) }}</b><small>{{ readinessDetail(check) }}</small></div>
</li>
</ol>
</details>
<template v-if="configurationTest">
<p class="readiness-run" :class="{ failed: configurationTest.status === 'failed' }">{{ t(`admin.shippingInventory.configurationTestStage.${configurationTest.stage}`) }}</p>
<details class="readiness-audit"><summary>{{ t('admin.shippingInventory.configurationTestRunNo') }} {{ configurationTest.run_no }}</summary><dl><div><dt>{{ t('admin.shippingInventory.configurationTestConfigVersion') }}</dt><dd>{{ configurationTest.source_config_version }}</dd></div><div><dt>{{ t('admin.shippingInventory.configurationTestConnectionVersion') }}</dt><dd>{{ configurationTest.rpa_profile_config_version }}</dd></div><div><dt>{{ t('admin.shippingInventory.configurationTestUpdatedAt') }}</dt><dd>{{ formatDate(configurationTest.completed_at || configurationTest.created_at) }}</dd></div></dl></details>
<p v-if="configurationTest.error_message" class="form-tip">{{ configurationTest.error_message }}</p>
<p v-if="configurationTest.status === 'completed_empty'" class="form-tip">{{ t('admin.shippingInventory.configurationTestEmptyResult') }}</p>
<section v-if="configurationTest.status === 'completed'" class="recommendation-list">
<p v-if="configurationTest.result?.current_profile_verified" class="configuration-test-verified">{{ t(`admin.shippingInventory.currentProfileVerified.${configurationTest.result.profile_match_level || 'compatible'}`) }}</p>
<article v-for="candidate in configurationTest.result?.analysis?.match_result?.candidates || []" :key="candidate.profile_id"><b>{{ candidate.display_name }} V{{ candidate.version }}</b><small>{{ t(`admin.shippingInventory.recommendationLevel.${candidate.level}`) }} · {{ t('admin.shippingInventory.configurationTestCandidateHint') }}</small></article>
<p v-if="!configurationTest.result?.current_profile_verified && !(configurationTest.result?.analysis?.match_result?.candidates || []).length">{{ t('admin.shippingInventory.configurationTestNoRecommendation') }}</p>
</section>
</template>
<footer v-if="source.enabled || source.activation?.ready" class="readiness-footer">
<button v-if="source.enabled" type="button" class="btn-danger btn-sm" @click="requestSourceDeactivation">{{ t('admin.shippingInventory.deactivateSource') }}</button>
<button
v-else
type="button"
class="btn-primary btn-sm"
:disabled="sourceDirty"
:title="sourceDirty ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined"
@click="requestSourceActivation"
>{{ t('admin.shippingInventory.activateSource') }}</button>
</footer>
</section>
<div v-if="!selectedId" class="form-tip full">{{ t('admin.shippingInventory.sourceSavedDisabledHint') }}</div>
<template v-if="source.connector_type === 'dbs'">
<div class="subsection full">{{ t('admin.shippingInventory.reportPath') }}</div>
<label><span>{{ t('admin.shippingInventory.programGroup') }}</span><input v-model="source.report_path_json.program_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.programLabel') }}</span><input v-model="source.report_path_json.program_label" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportGroup') }}</span><input v-model="source.report_path_json.report_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportName') }}</span><input v-model="source.report_path_json.report_name" class="input-field" required></label>
<div class="subsection full">{{ t('admin.shippingInventory.queryParameters') }}</div>
<div v-for="(parameter, index) in source.query_parameters_json" :key="`${index}-${parameter.name}`" class="parameter-row full">
<input v-model="parameter.name" class="input-field" :placeholder="t('admin.shippingInventory.parameterName')">
<select v-model="parameter.mode" class="select-field"><option value="single">{{ t('admin.shippingInventory.single') }}</option><option value="multi_text">{{ t('admin.shippingInventory.multiText') }}</option><option value="multi_select">{{ t('admin.shippingInventory.multiSelect') }}</option></select>
<input class="input-field" :value="parameter.values.join(', ')" :placeholder="t('admin.shippingInventory.parameterValues')" @input="parameter.values = splitValues(($event.target as HTMLInputElement).value)">
<label class="inline-check"><input v-model="parameter.required" type="checkbox">{{ t('admin.shippingInventory.required') }}</label>
<label class="inline-check"><input v-model="parameter.select_all" type="checkbox">{{ t('admin.shippingInventory.selectAll') }}</label>
<button type="button" class="btn-danger btn-sm" @click="source.query_parameters_json.splice(index, 1)">{{ t('admin.delete') }}</button>
<section class="path-card full">
<button type="button" class="path-card-header" :aria-expanded="inventoryPathOpen" @click="inventoryPathOpen = !inventoryPathOpen">
<span class="path-card-title"><b>{{ t('admin.shippingInventory.reportPath') }}</b></span>
<span class="path-card-toggle" aria-hidden="true">{{ inventoryPathOpen ? '▾' : '▸' }}</span>
</button>
<div v-show="inventoryPathOpen" class="path-card-body">
<label><span>{{ t('admin.shippingInventory.programGroup') }}</span><input v-model="source.report_path_json.program_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.programLabel') }}</span><input v-model="source.report_path_json.program_label" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportGroup') }}</span><input v-model="source.report_path_json.report_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportName') }}</span><input v-model="source.report_path_json.report_name" class="input-field" required></label>
<div class="subsection full">{{ t('admin.shippingInventory.queryParameters') }}</div>
<div v-for="(parameter, index) in source.query_parameters_json" :key="`${index}-${parameter.name}`" class="parameter-row full">
<input v-model="parameter.name" class="input-field" :placeholder="t('admin.shippingInventory.parameterName')">
<select v-model="parameter.mode" class="select-field"><option value="single">{{ t('admin.shippingInventory.single') }}</option><option value="multi_text">{{ t('admin.shippingInventory.multiText') }}</option><option value="multi_select">{{ t('admin.shippingInventory.multiSelect') }}</option></select>
<input class="input-field" :value="parameter.values.join(', ')" :placeholder="t('admin.shippingInventory.parameterValues')" @input="parameter.values = splitValues(($event.target as HTMLInputElement).value)">
<label class="inline-check"><input v-model="parameter.required" type="checkbox">{{ t('admin.shippingInventory.required') }}</label>
<label class="inline-check"><input v-model="parameter.select_all" type="checkbox">{{ t('admin.shippingInventory.selectAll') }}</label>
<button type="button" class="btn-danger btn-sm" @click="source.query_parameters_json.splice(index, 1)">{{ t('admin.delete') }}</button>
</div>
<button type="button" class="btn-secondary btn-sm full" @click="addParameter">{{ t('admin.shippingInventory.addParameter') }}</button>
</div>
<button type="button" class="btn-secondary btn-sm full" @click="addParameter">{{ t('admin.shippingInventory.addParameter') }}</button>
</template>
<section v-if="selectedId" class="receipt-report-config full">
<div class="subsection">{{ t('admin.shippingInventory.receiptReportConfig') }}<small>{{ t('admin.shippingInventory.receiptReportConfigHint') }}</small></div>
<div class="switch-field"><span>{{ t('admin.shippingInventory.receiptReportEnabled') }}</span><button type="button" class="status-switch" :class="{ on: receiptConfig.enabled }" role="switch" :aria-checked="receiptConfig.enabled" @click="receiptConfig.enabled = !receiptConfig.enabled"><i></i><b>{{ receiptConfig.enabled ? t('admin.shippingInventory.enabledState') : t('admin.shippingInventory.disabledState') }}</b></button></div>
</section>
</template>
<section v-if="selectedId" class="path-card receipt full" :class="{ configured: receiptConfigExists }">
<button type="button" class="path-card-header" :aria-expanded="receiptSectionOpen" @click="toggleReceiptSection">
<span class="path-card-title"><b>{{ t('admin.shippingInventory.receiptReportConfig') }}</b><small>{{ t('admin.shippingInventory.receiptReportConfigHint') }}</small></span>
<span class="path-badge" :class="receiptConfigExists ? 'on' : 'off'">{{ receiptConfigExists ? t('admin.shippingInventory.pathSectionConfigured') : t('admin.shippingInventory.pathSectionNotConfigured') }}</span>
<span class="path-card-toggle" aria-hidden="true">{{ receiptSectionOpen ? '▾' : '▸' }}</span>
</button>
<div v-show="receiptSectionOpen" class="path-card-body">
<template v-if="source.connector_type === 'dbs'">
<label><span>{{ t('admin.shippingInventory.programGroup') }}</span><input v-model="receiptConfig.report_path_json.program_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.programLabel') }}</span><input v-model="receiptConfig.report_path_json.program_label" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportGroup') }}</span><input v-model="receiptConfig.report_path_json.report_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportName') }}</span><input v-model="receiptConfig.report_path_json.report_name" class="input-field" required></label>
<label class="full"><span>{{ t('admin.shippingInventory.receiptWarehouses') }}</span><input class="input-field" :value="receiptConfig.warehouse_ids_json.join(', ')" :placeholder="t('admin.shippingInventory.receiptWarehousesHint')" @input="receiptConfig.warehouse_ids_json = splitValues(($event.target as HTMLInputElement).value)"></label>
<div class="subsection full">{{ t('admin.shippingInventory.receiptOptionalParameters') }}</div>
<div class="subsection full">{{ t('admin.shippingInventory.queryParameters') }}<small>{{ t('admin.shippingInventory.receiptQueryParametersHint') }}</small></div>
<div v-for="(parameter, index) in receiptConfig.query_parameters_json" :key="`receipt-${index}-${parameter.name}`" class="parameter-row full">
<input v-model="parameter.name" class="input-field" :placeholder="t('admin.shippingInventory.parameterName')">
<select v-model="parameter.mode" class="select-field"><option value="single">{{ t('admin.shippingInventory.single') }}</option><option value="multi_text">{{ t('admin.shippingInventory.multiText') }}</option><option value="multi_select">{{ t('admin.shippingInventory.multiSelect') }}</option></select>
@@ -222,28 +178,40 @@
<button type="button" class="btn-secondary btn-sm full" @click="addReceiptParameter">{{ t('admin.shippingInventory.addParameter') }}</button>
</template>
<p v-else class="form-tip full">{{ t('admin.shippingInventory.receiptCraneFixedPath') }}</p>
<div class="receipt-config-actions full"><button type="button" class="btn-secondary btn-sm" :disabled="receiptConfigLoading || receiptConfigSaving" @click="saveReceiptConfig">{{ receiptConfigSaving ? t('admin.shippingInventory.saving') : t('admin.shippingInventory.saveReceiptReportConfig') }}</button></div>
</section>
<label class="full"><span>{{ t('admin.shippingInventory.movementBindingLabel') }}</span><select v-model.number="receiptConfig.parsing_profile_id" class="select-field"><option :value="null">{{ t('admin.shippingInventory.movementBindingNone') }}</option><option v-for="item in parsingProfiles.filter((row) => row.status === 'published' && row.purpose === 'movement')" :key="`movement-bind-${item.id}`" :value="Number(item.id)">{{ item.display_name || item.profile_code }} V{{ item.version }}</option></select><small>{{ t('admin.shippingInventory.movementBindingHint') }}</small></label>
</div>
</section>
</template>
<template v-else-if="activeTab === 'parsing'">
<template v-if="parsingReadOnly">
<section class="parsing-summary full">
<div><span>{{ t('admin.shippingInventory.parsingPurposeLabel') }}</span><strong>{{ t(`admin.shippingInventory.parsingPurpose.${parsing.purpose === 'movement' ? 'movement' : 'inventory'}`) }}</strong></div>
<div><span>{{ t('admin.shippingInventory.fileFormat') }}</span><strong>{{ parsing.file_format.toUpperCase() }}</strong></div>
<div><span>{{ t('admin.shippingInventory.sheetName') }}</span><strong>{{ parsing.sheet_name || t('admin.shippingInventory.csvFile') }}</strong></div>
<div><span>{{ t('admin.shippingInventory.headerRowIndex') }}</span><strong>{{ t('admin.shippingInventory.headerRowOption', { row: parsing.header_row_index }) }}</strong></div>
</section>
<section class="readonly-mapping-section full">
<div class="subsection">{{ t('admin.shippingInventory.fieldMappings') }}</div>
<p class="section-hint">{{ t('admin.shippingInventory.readonlyFieldMappingsHint') }}</p>
<div v-for="(item, index) in parsing.field_mappings" :key="`readonly-field-${index}`" class="parsing-mapping-card">
<div class="mapping-title"><strong>{{ t('admin.shippingInventory.mappingItem', { number: index + 1 }) }}</strong></div>
<div class="mapping-display"><span>{{ t('admin.shippingInventory.inventoryField') }}</span><b>{{ inventoryFieldName(item.inventory_field) }}</b><small>{{ inventoryFieldDescription(item.inventory_field) }}</small></div>
<div class="mapping-arrow" aria-hidden="true">→</div>
<div class="mapping-display"><span>{{ t('admin.shippingInventory.sourceHeader') }}</span><b>{{ item.source_header }}</b></div>
</div>
<div class="subsection">{{ t(`admin.shippingInventory.${parsingLabelNs}.fieldMappings`) }}</div>
<p class="section-hint">{{ t(parsing.purpose === 'movement' ? 'admin.shippingInventory.movementMappingHint' : 'admin.shippingInventory.readonlyFieldMappingsHint') }}</p>
<template v-if="parsing.purpose === 'movement'">
<div v-for="(item, index) in parsing.movement_mappings" :key="`readonly-movement-${item.code}`" class="parsing-mapping-card">
<div class="mapping-title"><strong>{{ t('admin.shippingInventory.mappingItem', { number: index + 1 }) }}</strong></div>
<div class="mapping-display"><span>{{ t('admin.shippingInventory.movementStandardField') }}</span><b>{{ t(`admin.shippingInventory.movementFields.${item.code}`) }}</b><small><b v-if="item.required">{{ t('admin.shippingInventory.movementRequiredMark') }}</b><template v-if="item.required && item.is_identity"> · </template><b v-if="item.is_identity">{{ t('admin.shippingInventory.movementIdentityMark') }}</b></small></div>
<div class="mapping-arrow" aria-hidden="true">→</div>
<div class="mapping-display"><span>{{ t(`admin.shippingInventory.${parsingLabelNs}.sourceHeader`) }}</span><b>{{ item.alias || '-' }}</b></div>
</div>
</template>
<template v-else>
<div v-for="(item, index) in parsing.field_mappings" :key="`readonly-field-${index}`" class="parsing-mapping-card">
<div class="mapping-title"><strong>{{ t('admin.shippingInventory.mappingItem', { number: index + 1 }) }}</strong></div>
<div class="mapping-display"><span>{{ t('admin.shippingInventory.inventoryField') }}</span><b>{{ inventoryFieldName(item.inventory_field) }}</b><small>{{ inventoryFieldDescription(item.inventory_field) }}</small></div>
<div class="mapping-arrow" aria-hidden="true">→</div>
<div class="mapping-display"><span>{{ t('admin.shippingInventory.sourceHeader') }}</span><b>{{ item.source_header }}</b></div>
</div>
</template>
</section>
<section class="readonly-mapping-section full">
<section v-if="parsing.purpose !== 'movement'" class="readonly-mapping-section full">
<div class="subsection">{{ t('admin.shippingInventory.matchKeys') }}</div>
<p class="section-hint">{{ t('admin.shippingInventory.readonlyMatchKeysHint') }}</p>
<div v-for="(item, index) in parsing.match_keys" :key="`readonly-match-${index}`" class="parsing-mapping-card match-key-card">
@@ -257,12 +225,13 @@
</template>
<template v-else>
<label><span>{{ t('admin.shippingInventory.parsingProfileCode') }}</span><input v-model="parsing.profile_code" class="input-field" :disabled="Boolean(selectedId)" required></label>
<label><span>{{ t('admin.shippingInventory.parsingProfileName') }}</span><input v-model="parsing.display_name" class="input-field" required></label>
<label><span>{{ t(`admin.shippingInventory.${parsingLabelNs}.code`) }}</span><input v-model="parsing.profile_code" class="input-field" :disabled="Boolean(selectedId)" required></label>
<label><span>{{ t(`admin.shippingInventory.${parsingLabelNs}.name`) }}</span><input v-model="parsing.display_name" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.parsingPurposeLabel') }}</span><select v-model="parsing.purpose" class="select-field" :disabled="Boolean(selectedId)" @change="resetMappingRowsForPurpose"><option value="inventory">{{ t('admin.shippingInventory.parsingPurpose.inventory') }}</option><option value="movement">{{ t('admin.shippingInventory.parsingPurpose.movement') }}</option></select><small>{{ t('admin.shippingInventory.parsingPurposeHint') }}</small></label>
<label><span>{{ t('admin.shippingInventory.fileFormat') }}</span><select v-model="parsing.file_format" class="select-field"><option value="xls">xls</option><option value="xlsx">xlsx</option><option value="csv">csv</option></select></label>
<label v-if="!selectedId" class="full"><span>{{ t('admin.shippingInventory.temporaryInventorySession') }}</span><select v-model="selectedTemporaryInventorySession" class="select-field" @change="loadTemporaryInventorySession"><option value="">{{ t('admin.shippingInventory.temporaryInventorySessionNone') }}</option><option v-for="item in temporaryInventorySessions" :key="item.session_no" :value="item.session_no">{{ item.source_file_name }} · {{ item.session_no }}</option></select><small>{{ t('admin.shippingInventory.temporaryInventorySessionHint') }}</small></label>
<label v-if="!selectedId && parsing.purpose !== 'movement'" class="full"><span>{{ t('admin.shippingInventory.temporaryInventorySession') }}</span><select v-model="selectedTemporaryInventorySession" class="select-field" @change="loadTemporaryInventorySession"><option value="">{{ t('admin.shippingInventory.temporaryInventorySessionNone') }}</option><option v-for="item in temporaryInventorySessions" :key="item.session_no" :value="item.session_no">{{ item.source_file_name }} · {{ item.session_no }}</option></select><small>{{ t('admin.shippingInventory.temporaryInventorySessionHint') }}</small></label>
<div v-if="temporaryInventorySessionSelected" class="form-tip full">{{ t('admin.shippingInventory.temporaryInventorySessionSelected', { mapping: temporaryInventorySessionSelected.confirmed_usage?.mapping_origin || '-' }) }}</div>
<label v-if="!selectedId" class="full"><span>{{ t('admin.shippingInventory.inventorySampleFile') }}</span><input type="file" accept=".xls,.xlsx,.csv" :disabled="analysisLoading || Boolean(temporaryInventorySessionSelected)" @change="analyseInventorySample"><small>{{ t('admin.shippingInventory.inventorySampleFileHint') }}</small></label>
<label v-if="!selectedId" class="full"><span>{{ t(`admin.shippingInventory.${parsingLabelNs}.sampleFile`) }}</span><input type="file" accept=".xls,.xlsx,.csv" :disabled="analysisLoading || Boolean(temporaryInventorySessionSelected)" @change="analyseInventorySample"><small>{{ t(`admin.shippingInventory.${parsingLabelNs}.sampleFileHint`) }}</small></label>
<section v-else-if="structureAnalysis" class="sample-evidence-card full">
<div>
<strong>{{ pendingSampleReplacement ? t('admin.shippingInventory.pendingInventorySampleReplacement') : t('admin.shippingInventory.savedInventorySample') }}</strong>
@@ -280,28 +249,37 @@
<template v-if="structureAnalysis">
<label><span>{{ t('admin.shippingInventory.sheetName') }}</span><select v-model="parsing.sheet_name" class="select-field" @change="applyAnalysisCandidate"><option v-for="candidate in analysisCandidates" :key="candidateKey(candidate)" :value="candidate.sheet_name || ''">{{ candidate.sheet_name || t('admin.shippingInventory.csvFile') }}</option></select></label>
<label><span>{{ t('admin.shippingInventory.headerRowIndex') }}</span><select v-model.number="parsing.header_row_index" class="select-field" @change="applyAnalysisCandidate"><option v-for="candidate in analysisCandidatesForSheet" :key="candidateKey(candidate)" :value="candidate.header_row_index">{{ t('admin.shippingInventory.headerRowOption', { row: candidate.header_row_index }) }}</option></select></label>
<section class="analysis-preview full"><strong>{{ t('admin.shippingInventory.inventoryAnalysisPreview') }}</strong><p>{{ t('admin.shippingInventory.inventoryAnalysisSummary', structureAnalysis.validation_summary) }}</p><div class="analysis-columns"><span v-for="column in selectedAnalysisColumns" :key="`${column.index}-${column.header}`"><b>{{ column.header || t('admin.shippingInventory.emptyHeader') }}</b><small>{{ column.inferred_type }} · {{ column.sample_values?.join(' / ') || '-' }}</small></span></div></section>
<section v-if="structureAnalysis.match_result?.candidates?.length" class="analysis-preview full"><strong>{{ t('admin.shippingInventory.parsingPlanRecommendation') }}</strong><div class="recommendation-list"><article v-for="candidate in structureAnalysis.match_result.candidates" :key="candidate.profile_id"><b>{{ candidate.display_name }} V{{ candidate.version }}</b><small>{{ t(`admin.shippingInventory.recommendationLevel.${candidate.level}`) }} · {{ t('admin.shippingInventory.usedBySites', { count: candidate.source_count }) }}</small><p v-if="candidate.difference?.added_columns?.length">{{ t('admin.shippingInventory.addedColumns', { columns: candidate.difference.added_columns.join('、') }) }}</p><p v-if="candidate.difference?.column_order_changed?.length">{{ t('admin.shippingInventory.columnOrderChanged') }}</p><button type="button" class="btn-secondary btn-sm" @click="adoptRecommendedProfile(candidate.profile_id)">{{ t('admin.shippingInventory.adoptParsingPlan') }}</button></article></div></section>
<section class="analysis-preview full"><strong>{{ t(`admin.shippingInventory.${parsingLabelNs}.analysisPreview`) }}</strong><p>{{ t('admin.shippingInventory.inventoryAnalysisSummary', structureAnalysis.validation_summary) }}</p><div class="analysis-columns"><span v-for="column in selectedAnalysisColumns" :key="`${column.index}-${column.header}`"><b>{{ column.header || t('admin.shippingInventory.emptyHeader') }}</b><small>{{ column.inferred_type }} · {{ column.sample_values?.join(' / ') || '-' }}</small></span></div></section>
<section v-if="parsing.purpose !== 'movement' && structureAnalysis.match_result?.candidates?.length" class="analysis-preview full"><strong>{{ t('admin.shippingInventory.parsingPlanRecommendation') }}</strong><div class="recommendation-list"><article v-for="candidate in structureAnalysis.match_result.candidates" :key="candidate.profile_id"><b>{{ candidate.display_name }} V{{ candidate.version }}</b><small>{{ t(`admin.shippingInventory.recommendationLevel.${candidate.level}`) }} · {{ t('admin.shippingInventory.usedBySites', { count: candidate.source_count }) }}</small><p v-if="candidate.difference?.added_columns?.length">{{ t('admin.shippingInventory.addedColumns', { columns: candidate.difference.added_columns.join('、') }) }}</p><p v-if="candidate.difference?.column_order_changed?.length">{{ t('admin.shippingInventory.columnOrderChanged') }}</p><button type="button" class="btn-secondary btn-sm" @click="adoptRecommendedProfile(candidate.profile_id)">{{ t('admin.shippingInventory.adoptParsingPlan') }}</button></article></div></section>
</template>
<div v-else class="form-tip full">{{ t(`admin.shippingInventory.${parsingLabelNs}.sampleRequired`) }}</div>
<template v-if="parsing.purpose === 'movement'">
<div class="subsection full">{{ t(`admin.shippingInventory.${parsingLabelNs}.fieldMappings`) }}<small>{{ t('admin.shippingInventory.movementMappingHint') }}</small></div>
<div v-for="item in parsing.movement_mappings" :key="`movement-${item.code}`" class="parsing-mapping-card full">
<div class="mapping-title"><strong>{{ t(`admin.shippingInventory.movementFields.${item.code}`) }}</strong><small><b v-if="item.required">{{ t('admin.shippingInventory.movementRequiredMark') }}</b><template v-if="item.required && item.is_identity"> · </template><b v-if="item.is_identity">{{ t('admin.shippingInventory.movementIdentityMark') }}</b></small></div>
<label class="full"><span>{{ t(`admin.shippingInventory.${parsingLabelNs}.sourceHeader`) }}</span><select v-model="item.alias" class="select-field" :disabled="!structureAnalysis" :required="item.required"><option value="">{{ t('admin.shippingInventory.chooseSourceHeader') }}</option><option v-for="header in selectedAnalysisHeaders" :key="header" :value="header">{{ header }}</option></select></label>
</div>
</template>
<template v-else>
<div class="subsection full">{{ t('admin.shippingInventory.fieldMappings') }}</div>
<div v-for="(item, index) in parsing.field_mappings" :key="`field-${index}`" class="parsing-mapping-card full">
<div class="mapping-title"><strong>{{ t('admin.shippingInventory.mappingItem', { number: index + 1 }) }}</strong><button type="button" class="btn-danger btn-sm" @click="parsing.field_mappings.splice(index, 1)">{{ t('admin.delete') }}</button></div>
<label><span>{{ t('admin.shippingInventory.inventoryField') }}</span><select v-model="item.inventory_field" class="select-field" required><option value="">{{ t('admin.shippingInventory.chooseInventoryField') }}</option><option v-for="field in activeInventoryFields" :key="field.id" :value="String(field.id)">{{ inventoryFieldOptionLabel(field) }}</option></select></label>
<label><span>{{ t('admin.shippingInventory.sourceHeader') }}</span><select v-model="item.source_header" class="select-field" :disabled="!structureAnalysis" required><option value="">{{ t('admin.shippingInventory.chooseSourceHeader') }}</option><option v-for="header in selectedAnalysisHeaders" :key="header" :value="header">{{ header }}</option></select></label>
<small v-if="item.inventory_field" class="mapping-help">{{ inventoryFieldDescription(item.inventory_field) }}</small>
</div>
<button type="button" class="btn-secondary btn-sm full" :disabled="!structureAnalysis" @click="addParsingFieldMapping">{{ t('admin.shippingInventory.addFieldMapping') }}</button>
<div class="subsection full">{{ t('admin.shippingInventory.matchKeys') }}<small>{{ t('admin.shippingInventory.matchKeysHint') }}</small></div>
<div v-for="(item, index) in parsing.match_keys" :key="`match-${index}`" class="parsing-mapping-card match-key-card full">
<div class="mapping-title"><strong>{{ t('admin.shippingInventory.mappingItem', { number: index + 1 }) }}</strong><button type="button" class="btn-danger btn-sm" @click="parsing.match_keys.splice(index, 1)">{{ t('admin.delete') }}</button></div>
<label><span>{{ t('admin.shippingInventory.orderField') }}</span><select v-model="item.order_field_id" class="select-field" required><option value="">{{ t('admin.shippingInventory.chooseOrderField') }}</option><option v-for="field in matchingOrderFields" :key="field.field_id" :value="field.field_id">{{ orderFieldOptionLabel(field) }}</option></select></label>
<label><span>{{ t('admin.shippingInventory.inventoryField') }}</span><select v-model="item.inventory_field" class="select-field" required><option value="">{{ t('admin.shippingInventory.chooseInventoryField') }}</option><option v-for="field in mappedMatchingInventoryFields" :key="field.id" :value="String(field.id)">{{ inventoryFieldOptionLabel(field) }}</option></select></label>
<small v-if="item.inventory_field" class="mapping-help">{{ inventoryFieldDescription(item.inventory_field) }}</small>
</div>
<button type="button" class="btn-secondary btn-sm full" :disabled="!canAddParsingMatchKey" @click="addParsingMatchKey">{{ t('admin.shippingInventory.addMatchKey') }}</button>
<p v-if="!unusedMatchingInventoryFields.length || !unusedOrderMatchFields.length" class="match-key-tip full">{{ t('admin.shippingInventory.matchKeysComplete') }}</p>
<p v-else-if="!structureAnalysis" class="match-key-tip full">{{ t('admin.shippingInventory.matchKeysAnalysisRequired') }}</p>
</template>
<div v-else class="form-tip full">{{ t('admin.shippingInventory.inventorySampleRequired') }}</div>
<div class="subsection full">{{ t('admin.shippingInventory.fieldMappings') }}</div>
<div v-for="(item, index) in parsing.field_mappings" :key="`field-${index}`" class="parsing-mapping-card full">
<div class="mapping-title"><strong>{{ t('admin.shippingInventory.mappingItem', { number: index + 1 }) }}</strong><button type="button" class="btn-danger btn-sm" @click="parsing.field_mappings.splice(index, 1)">{{ t('admin.delete') }}</button></div>
<label><span>{{ t('admin.shippingInventory.inventoryField') }}</span><select v-model="item.inventory_field" class="select-field" required><option value="">{{ t('admin.shippingInventory.chooseInventoryField') }}</option><option v-for="field in activeInventoryFields" :key="field.id" :value="String(field.id)">{{ inventoryFieldOptionLabel(field) }}</option></select></label>
<label><span>{{ t('admin.shippingInventory.sourceHeader') }}</span><select v-model="item.source_header" class="select-field" :disabled="!structureAnalysis" required><option value="">{{ t('admin.shippingInventory.chooseSourceHeader') }}</option><option v-for="header in selectedAnalysisHeaders" :key="header" :value="header">{{ header }}</option></select></label>
<small v-if="item.inventory_field" class="mapping-help">{{ inventoryFieldDescription(item.inventory_field) }}</small>
</div>
<button type="button" class="btn-secondary btn-sm full" :disabled="!structureAnalysis" @click="addParsingFieldMapping">{{ t('admin.shippingInventory.addFieldMapping') }}</button>
<div class="subsection full">{{ t('admin.shippingInventory.matchKeys') }}<small>{{ t('admin.shippingInventory.matchKeysHint') }}</small></div>
<div v-for="(item, index) in parsing.match_keys" :key="`match-${index}`" class="parsing-mapping-card match-key-card full">
<div class="mapping-title"><strong>{{ t('admin.shippingInventory.mappingItem', { number: index + 1 }) }}</strong><button type="button" class="btn-danger btn-sm" @click="parsing.match_keys.splice(index, 1)">{{ t('admin.delete') }}</button></div>
<label><span>{{ t('admin.shippingInventory.orderField') }}</span><select v-model="item.order_field_id" class="select-field" required><option value="">{{ t('admin.shippingInventory.chooseOrderField') }}</option><option v-for="field in matchingOrderFields" :key="field.field_id" :value="field.field_id">{{ orderFieldOptionLabel(field) }}</option></select></label>
<label><span>{{ t('admin.shippingInventory.inventoryField') }}</span><select v-model="item.inventory_field" class="select-field" required><option value="">{{ t('admin.shippingInventory.chooseInventoryField') }}</option><option v-for="field in mappedMatchingInventoryFields" :key="field.id" :value="String(field.id)">{{ inventoryFieldOptionLabel(field) }}</option></select></label>
<small v-if="item.inventory_field" class="mapping-help">{{ inventoryFieldDescription(item.inventory_field) }}</small>
</div>
<button type="button" class="btn-secondary btn-sm full" :disabled="!canAddParsingMatchKey" @click="addParsingMatchKey">{{ t('admin.shippingInventory.addMatchKey') }}</button>
<p v-if="!unusedMatchingInventoryFields.length || !unusedOrderMatchFields.length" class="match-key-tip full">{{ t('admin.shippingInventory.matchKeysComplete') }}</p>
<p v-else-if="!structureAnalysis" class="match-key-tip full">{{ t('admin.shippingInventory.matchKeysAnalysisRequired') }}</p>
</template>
</template>
@@ -368,15 +346,58 @@
<template v-else-if="activeTab === 'mappings'">
<label><span>{{ t('admin.shippingInventory.source') }}</span><select v-model.number="mapping.inventory_source_id" class="select-field" required><option :value="0">{{ t('admin.shippingInventory.chooseSource') }}</option><option v-for="item in sources" :key="String(item.id)" :value="Number(item.id)">{{ item.display_name || item.source_code }}</option></select></label>
<label><span>{{ t('admin.shippingInventory.freightWarehouse') }}</span><input v-model="mapping.freight_warehouse_id" class="input-field" :placeholder="t('admin.shippingInventory.defaultMapping')"></label>
<label><span>{{ t('admin.shippingInventory.freightWarehouse') }}</span><input v-model="mapping.freight_warehouse_id" class="input-field"></label>
<label><span>{{ t('admin.shippingInventory.externalSystem') }}</span><input v-model="mapping.external_system_code" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.externalOrganization') }}</span><input v-model="mapping.external_organization_code" class="input-field"></label>
<label><span>{{ t('admin.shippingInventory.externalSite') }}</span><input v-model="mapping.external_site_code" class="input-field"></label>
<label><span>{{ t('admin.shippingInventory.inTransitWarehouseCode') }}</span><input v-model="mapping.in_transit_warehouse_code" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.externalWarehouseCode') }}</span><input v-model="mapping.external_warehouse_code" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.externalWarehouseName') }}</span><input v-model="mapping.external_warehouse_name" class="input-field" required></label>
<div class="switch-field"><span>{{ t('admin.shippingInventory.enabled') }}</span><button type="button" class="status-switch" :class="{ on: mapping.enabled }" role="switch" :aria-checked="mapping.enabled" @click="mapping.enabled = !mapping.enabled"><i></i><b>{{ mapping.enabled ? t('admin.shippingInventory.enabledState') : t('admin.shippingInventory.disabledState') }}</b></button></div>
</template>
<section v-if="activeTab === 'sources' && selectedId" class="readiness-card full" :class="{ ready: source.enabled }">
<div class="readiness-inline">
<template v-if="source.enabled">
<span class="readiness-marker is-passed" aria-hidden="true">✓</span>
<div class="readiness-copy"><b>{{ t('admin.shippingInventory.activationReady') }}</b><small v-if="configurationTest?.completed_at">{{ t('admin.shippingInventory.readinessLastVerified', { time: formatDate(configurationTest.completed_at) }) }}</small></div>
<button type="button" class="btn-danger btn-sm" @click="requestSourceDeactivation">{{ t('admin.shippingInventory.deactivateSource') }}</button>
</template>
<template v-else-if="firstBlockingCheck">
<span class="readiness-marker" :class="`is-${firstBlockingCheck.status}`" aria-hidden="true">{{ readinessMarker(firstBlockingCheck.status) }}</span>
<div class="readiness-copy"><b>{{ t('admin.shippingInventory.readinessBlockedBy', { requirement: t(`admin.shippingInventory.activationRequirement.${firstBlockingCheck.code}`) }) }}</b><small>{{ t('admin.shippingInventory.readinessAutoEnableHint') }}</small></div>
<button v-if="readinessActionLabel(firstBlockingCheck)" type="button" class="readiness-action" :disabled="isReadinessActionBlocked(firstBlockingCheck)" :title="isReadinessActionBlocked(firstBlockingCheck) ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined" @click="runReadinessAction(firstBlockingCheck)">{{ readinessActionLabel(firstBlockingCheck) }}</button>
</template>
<template v-else>
<span class="readiness-marker is-passed" aria-hidden="true">✓</span>
<div class="readiness-copy"><b>{{ t('admin.shippingInventory.activationCanEnable') }}</b></div>
<button type="button" class="btn-primary btn-sm" :disabled="sourceDirty" :title="sourceDirty ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined" @click="requestSourceActivation">{{ t('admin.shippingInventory.activateSource') }}</button>
</template>
</div>
<details v-if="optionalReadinessChecks.length" class="readiness-optional">
<summary><span>{{ t('admin.shippingInventory.activationOptionalTitle') }}</span><small>{{ t('admin.shippingInventory.readinessOptionalPending', { count: optionalReadinessPending }) }}</small></summary>
<ol class="readiness-steps">
<li v-for="check in optionalReadinessChecks" :key="check.code" :class="`is-${check.status}`">
<span class="readiness-marker" aria-hidden="true">{{ readinessMarker(check.status) }}</span>
<div class="readiness-copy"><b>{{ t(`admin.shippingInventory.activationRequirement.${check.code}`) }}</b><small>{{ readinessDetail(check) }}</small></div>
</li>
</ol>
</details>
<template v-if="configurationTest">
<p v-if="configurationTest.status === 'failed'" class="readiness-run failed">{{ t(`admin.shippingInventory.configurationTestStage.${configurationTest.stage}`) }}</p>
<p v-if="configurationTest.error_message" class="form-tip">{{ configurationTest.error_message }}</p>
<p v-if="configurationTest.status === 'completed_empty'" class="form-tip">{{ t('admin.shippingInventory.configurationTestEmptyResult') }}</p>
<details v-if="configurationTest.status !== 'failed'" class="readiness-audit">
<summary>{{ t('admin.shippingInventory.configurationTestRunNo') }} {{ configurationTest.run_no }} · {{ t(`admin.shippingInventory.configurationTestStage.${configurationTest.stage}`) }}</summary>
<dl><div><dt>{{ t('admin.shippingInventory.configurationTestConfigVersion') }}</dt><dd>{{ configurationTest.source_config_version }}</dd></div><div><dt>{{ t('admin.shippingInventory.configurationTestConnectionVersion') }}</dt><dd>{{ configurationTest.rpa_profile_config_version }}</dd></div><div><dt>{{ t('admin.shippingInventory.configurationTestUpdatedAt') }}</dt><dd>{{ formatDate(configurationTest.completed_at || configurationTest.created_at) }}</dd></div></dl>
<section v-if="configurationTest.status === 'completed'" class="recommendation-list">
<p v-if="configurationTest.result?.current_profile_verified" class="configuration-test-verified">{{ t(`admin.shippingInventory.currentProfileVerified.${configurationTest.result.profile_match_level || 'compatible'}`) }}</p>
<article v-for="candidate in configurationTest.result?.analysis?.match_result?.candidates || []" :key="candidate.profile_id"><b>{{ candidate.display_name }} V{{ candidate.version }}</b><small>{{ t(`admin.shippingInventory.recommendationLevel.${candidate.level}`) }} · {{ t('admin.shippingInventory.configurationTestCandidateHint') }}</small></article>
<p v-if="!configurationTest.result?.current_profile_verified && !(configurationTest.result?.analysis?.match_result?.candidates || []).length">{{ t('admin.shippingInventory.configurationTestNoRecommendation') }}</p>
</section>
</details>
</template>
</section>
<div v-if="isEditableTab" class="form-actions full">
<button v-if="!parsingReadOnly" type="submit" class="btn-primary" :disabled="saving || ruleReadOnly || templateReadOnly || inventoryFieldReadOnly">{{ saving ? t('admin.shippingInventory.saving') : t('admin.save') }}</button>
<button v-if="activeTab === 'rules' && selectedId && selectedRuleStatus === 'draft'" type="button" class="btn-secondary btn-sm" @click="publishCurrentRule">{{ t('admin.shippingInventory.publish') }}</button>
@@ -425,7 +446,7 @@
<header class="clone-template-header"><div><h3 id="bulk-parsing-binding-title">{{ t('admin.shippingInventory.bulkBindParsingProfile') }}</h3><p>{{ t('admin.shippingInventory.bulkBindParsingProfileHint') }}</p></div><button type="button" class="drawer-close" :aria-label="t('admin.close')" @click="closeBulkParsingBinding">×</button></header>
<form class="clone-template-form" @submit.prevent="submitBulkParsingBinding">
<label><span>{{ t('admin.shippingInventory.inventorySites') }}</span><select v-model="bulkBinding.sourceIds" class="select-field" multiple required><option v-for="item in sources.filter((row) => !row.enabled)" :key="String(item.id)" :value="Number(item.id)">{{ item.display_name || item.source_code }}</option></select></label>
<label><span>{{ t('admin.shippingInventory.parsingProfiles') }}</span><select v-model.number="bulkBinding.profileId" class="select-field" required><option :value="0">{{ t('admin.shippingInventory.notConfigured') }}</option><option v-for="item in parsingProfiles.filter((row) => row.status === 'published')" :key="String(item.id)" :value="Number(item.id)">{{ item.display_name || item.profile_code }} V{{ item.version }}</option></select></label>
<label><span>{{ t('admin.shippingInventory.parsingProfiles') }}</span><select v-model.number="bulkBinding.profileId" class="select-field" required><option :value="0">{{ t('admin.shippingInventory.notConfigured') }}</option><option v-for="item in parsingProfiles.filter((row) => row.status === 'published' && row.purpose !== 'movement')" :key="String(item.id)" :value="Number(item.id)">{{ item.display_name || item.profile_code }} V{{ item.version }}</option></select></label>
<div class="clone-template-actions"><button type="button" class="btn-ghost btn-sm" :disabled="bulkBinding.saving" @click="closeBulkParsingBinding">{{ t('admin.cancel') }}</button><button type="submit" class="btn-primary" :disabled="bulkBinding.saving">{{ bulkBinding.saving ? t('admin.shippingInventory.saving') : t('admin.shippingInventory.bulkBindParsingProfile') }}</button></div>
</form>
</section>
@@ -481,6 +502,7 @@ import {
getShippingExcelTemplateLayout,
createShippingInventoryStructureAnalysis,
createShippingInventoryParsingDraftFromAnalysis,
fetchMovementFields,
previewShippingInventorySampleReplacement,
createShippingParsingDraftFromTemporarySession,
adoptShippingInventoryParsingProfile,
@@ -514,6 +536,7 @@ import type { ShippingInventoryConfigurationTest, ShippingInventoryReadinessChec
import { isConfigurationTestRunning, needsReadinessAction, readinessMarkerKind } from './shippingInventoryReadiness';
import { normaliseInventoryReportPath } from './shippingInventorySourceForm';
import { buildReceiptReportConfigPayload } from './receiptReportConfigForm';
import { buildMovementFieldMapping } from './movementParsingProfileForm';
type TabKey = 'profiles' | 'parsing' | 'inventoryFields' | 'templates' | 'sources' | 'rules' | 'snapshots' | 'exports' | 'mappings';
type Item = Record<string, any>;
@@ -619,7 +642,13 @@ const successTextsInput = computed<string>({
get: () => (profile.upload_config_json.success_texts || []).join('\n'),
set: (value) => { profile.upload_config_json.success_texts = String(value || '').split(/\r?\n/).map((item) => item.trim()).filter(Boolean); },
});
const parsing = reactive({ profile_code: '', display_name: '', file_format: 'xlsx', sheet_name: '', header_row_index: 1, field_mappings: [] as ParsingFieldMapping[], match_keys: [] as ParsingMatchKey[] });
const parsing = reactive({
profile_code: '', display_name: '', file_format: 'xlsx', sheet_name: '', header_row_index: 1,
purpose: 'inventory' as 'inventory' | 'movement',
field_mappings: [] as ParsingFieldMapping[], match_keys: [] as ParsingMatchKey[],
movement_mappings: [] as Array<{ code: string; alias: string; required: boolean; is_identity: boolean }>,
});
const movementFields = ref<Array<{ code: string; value_type: string; required: boolean; is_identity: boolean }>>([]);
const inventoryField = reactive<InventoryFieldForm>({ display_name: '', description: '', value_type: 'text', usage_type: 'general', sort_order: 100, status: 'active' });
const excelTemplate = reactive({ template_code: '', display_name: '', filename_pattern: '{business_no}.xlsx', mappings: [] as TemplateMapping[], file: null as File | null });
const templateClone = reactive({ visible: false, template_code: '', display_name: '', saving: false });
@@ -627,12 +656,15 @@ const bulkBinding = reactive({ visible: false, sourceIds: [] as number[], profil
const batchValidation = reactive({ visible: false, sourceIds: [] as number[], query: '', statusFilter: 'all' as 'all' | 'processing' | 'completed' | 'completed_empty' | 'failed', saving: false, result: null as ShippingInventoryValidationBatch | null });
let batchValidationTimer: number | null = null;
const source = reactive({ source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [] as Parameter[], enabled: false, activation: { ready: false, checks: [] as ShippingInventoryReadinessCheck[], missing_requirements: [] as string[] } as SourceActivation });
const receiptConfig = reactive({ enabled: false, report_path_json: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '' } as Record<string, string>, query_parameters_json: [] as Parameter[], warehouse_ids_json: [] as string[] });
const receiptConfigLoading = ref(false);
const receiptConfigSaving = ref(false);
const receiptConfig = reactive({ report_path_json: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '' } as Record<string, string>, query_parameters_json: [] as Parameter[], parsing_profile_id: null as number | null });
const receiptConfigExists = ref(false);
const receiptSectionTouched = ref(false);
const receiptSectionOpen = ref(false);
const inventoryPathOpen = ref(true);
const receiptBaseline = ref('');
const sourceBaseline = ref('');
const rule = reactive({ rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', operator: 'prefix', expected: '' }] as RuleCondition[], source_codes: [] as string[] });
const mapping = reactive({ inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true });
const mapping = reactive({ inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', in_transit_warehouse_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true });
const compatibleRoutingFields = computed(() => routingFields.value.filter((item) => item.scope === (rule.scope === 'task' ? 'header' : 'line')));
const activeInventoryFields = computed(() => inventoryFields.value.filter((item) => item.status === 'active'));
const matchingInventoryFields = computed(() => activeInventoryFields.value.filter((item) => item.usage_type === 'match_identity'));
@@ -646,26 +678,15 @@ const matchingOrderFields = computed(() => routingFields.value.filter((field) =>
const canAddParsingMatchKey = computed(() => Boolean(
structureAnalysis.value && unusedMatchingInventoryFields.value.length && unusedOrderMatchFields.value.length,
));
const sourceDirty = computed(() => Boolean(selectedId.value && sourceBaseline.value && sourceBaseline.value !== serialiseSourceInput()));
const sourceDirty = computed(() => Boolean(selectedId.value && (
(sourceBaseline.value && sourceBaseline.value !== serialiseSourceInput())
|| (receiptConfigExists.value && receiptBaseline.value && receiptBaseline.value !== serialiseReceiptInput())
)));
const readinessChecks = computed<ShippingInventoryReadinessCheck[]>(() => source.activation?.checks || []);
const requiredReadinessChecks = computed(() => readinessChecks.value.filter((item) => item.blocking));
const firstBlockingCheck = computed(() => requiredReadinessChecks.value.find((item) => item.status !== 'passed'));
const optionalReadinessChecks = computed(() => readinessChecks.value.filter((item) => !item.blocking));
const readinessSummary = computed(() => {
const required = requiredReadinessChecks.value;
const total = required.length;
const passed = required.filter((item) => item.status === 'passed').length;
return t('admin.shippingInventory.readinessProgress', { passed, total });
});
const readinessHeadline = computed(() => {
if (source.enabled) return t('admin.shippingInventory.activationReady');
return source.activation?.ready ? t('admin.shippingInventory.activationCanEnable') : t('admin.shippingInventory.activationDraft');
});
const readinessGuidance = computed(() => source.enabled
? t('admin.shippingInventory.activationEnabledHint')
: source.activation?.ready
? t('admin.shippingInventory.activationCanEnableHint')
: t('admin.shippingInventory.activationMissingHint'));
const optionalReadinessPending = computed(() => optionalReadinessChecks.value.filter((item) => item.status !== 'passed').length);
const sampleReplacementNotice = computed(() => {
const difference = pendingSampleReplacement.value?.difference || {};
const missing = Array.isArray(difference.missing_mapped_headers) ? difference.missing_mapped_headers : [];
@@ -726,10 +747,14 @@ const currentItems = computed<Item[]>(() => {
});
const compatibleProfiles = computed(() => profiles.value.filter((item) => item.connector_type === source.connector_type));
const selectedRuleStatus = computed(() => rules.value.find((item) => Number(item.id) === selectedId.value)?.status || 'draft');
const ruleReadOnly = computed(() => ['published', 'retired'].includes(selectedRuleStatus.value));
// 只读判定必须限定在规则页签:selectedId 是各页签共享的,站点 id 可能与规则 id 相同,
// 不加页签限定时已发布规则会让站点页签的保存按钮被误禁用(点击无任何请求)。
const ruleReadOnly = computed(() => activeTab.value === 'rules' && ['published', 'retired'].includes(selectedRuleStatus.value));
const selectedTemplateStatus = computed(() => excelTemplates.value.find((item) => Number(item.id) === selectedId.value)?.status || 'draft');
const selectedParsingStatus = computed(() => parsingProfiles.value.find((item) => Number(item.id) === selectedId.value)?.status || 'draft');
const parsingReadOnly = computed(() => activeTab.value === 'parsing' && ['published', 'retired'].includes(selectedParsingStatus.value));
/** 按规则用途切换弹窗标签命名空间:收料异动模式下不再出现"库存"措辞。 */
const parsingLabelNs = computed(() => parsing.purpose === 'movement' ? 'movementParsing' : 'inventoryParsing');
const inventoryFieldReadOnly = computed(() => activeTab.value === 'inventoryFields' && inventoryField.status !== 'active');
const analysisCandidates = computed<Item[]>(() => structureAnalysis.value?.structure?.candidates || []);
const analysisCandidatesForSheet = computed<Item[]>(() => analysisCandidates.value.filter((item) => String(item.sheet_name || '') === parsing.sheet_name));
@@ -827,12 +852,13 @@ const filteredBatchValidationRuns = computed(() => {
/** 加载服务端配置与运行审计投影,页面不保留第二份真相。 */
async function load(): Promise<void> {
try {
const [[profileRows, sourceRows, ruleRows, mappingRows, snapshotRows, exportRows, parsingRows, templateRows], inventoryFieldRows, fieldCatalog, configurationCatalog, temporarySessions] = await Promise.all([
getShippingInventoryConfig(), getShippingInventoryFields(), getShippingInventoryRoutingFields(), getShippingInventoryConfigurationCatalog(), listShippingTemporaryInventorySessions(),
const [[profileRows, sourceRows, ruleRows, mappingRows, snapshotRows, exportRows, parsingRows, templateRows], inventoryFieldRows, fieldCatalog, configurationCatalog, temporarySessions, movementFieldRows] = await Promise.all([
getShippingInventoryConfig(), getShippingInventoryFields(), getShippingInventoryRoutingFields(), getShippingInventoryConfigurationCatalog(), listShippingTemporaryInventorySessions(), fetchMovementFields(),
]);
profiles.value = profileRows as Item[]; sources.value = sourceRows as Item[]; rules.value = ruleRows as Item[];
mappings.value = mappingRows as Item[]; snapshots.value = snapshotRows as Item[]; exports.value = exportRows as Item[];
parsingProfiles.value = parsingRows as Item[];
movementFields.value = movementFieldRows;
inventoryFields.value = inventoryFieldRows as Item[];
excelTemplates.value = templateRows as Item[];
temporaryInventorySessions.value = temporarySessions as Item[];
@@ -848,36 +874,39 @@ async function load(): Promise<void> {
}
}
/** 重置当前站点的独立收料表单,不借用库存报表路径或查询条件。 */
/** 重置当前站点的独立收料表单与卡片状态,与库存同构(路径+查询条件)。 */
function resetReceiptConfig(connectorType: unknown): void {
Object.assign(receiptConfig, {
enabled: false,
report_path_json: String(connectorType || '').toLowerCase() === 'crane'
? { report_name: 'Inbound Details' }
: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '' },
query_parameters_json: [],
warehouse_ids_json: [],
parsing_profile_id: null,
});
}
/** 读取收料独立配置;读取失败不影响库存站点配置和既有库存运行。 */
async function loadReceiptConfig(sourceId: number, connectorType: unknown): Promise<void> {
receiptConfigLoading.value = true;
resetReceiptConfig(connectorType);
receiptConfigExists.value = false;
receiptSectionTouched.value = false;
receiptSectionOpen.value = false;
receiptBaseline.value = '';
try {
const config = await getShippingReceiptReportConfig(sourceId);
if (!config) return;
const isCrane = String(connectorType || '').toLowerCase() === 'crane';
Object.assign(receiptConfig, {
enabled: Boolean(config.enabled),
report_path_json: isCrane
? { report_name: 'Inbound Details' }
: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '', ...((config.report_path_json || {}) as Record<string, string>) },
query_parameters_json: Array.isArray(config.query_parameters_json) ? config.query_parameters_json.map((parameter) => ({ ...parameter })) : [],
warehouse_ids_json: Array.isArray(config.warehouse_ids_json) ? [...config.warehouse_ids_json].map(String) : [],
parsing_profile_id: config.parsing_profile_id ? Number(config.parsing_profile_id) : null,
});
receiptConfigExists.value = true;
receiptSectionOpen.value = true;
} catch (cause) { showError(cause, 'loadFailed'); }
finally { receiptConfigLoading.value = false; }
finally { receiptBaseline.value = serialiseReceiptInput(); }
}
/** 新增 DBS 可选收料条件;Crane 固定默认查询,不维护查询条件。 */
@@ -885,16 +914,10 @@ function addReceiptParameter(): void {
receiptConfig.query_parameters_json.push({ name: '', mode: 'single', values: [], required: false, select_all: false });
}
/** 仅提交白名单收料字段到独立 API,绝不调用库存 Source 保存接口。 */
async function saveReceiptConfig(): Promise<void> {
if (!selectedId.value) return;
receiptConfigSaving.value = true;
try {
await saveShippingReceiptReportConfig(selectedId.value, buildReceiptReportConfigPayload(receiptConfig));
await loadReceiptConfig(selectedId.value, source.connector_type);
message.success(t('admin.shippingInventory.receiptReportSaved'));
} catch (cause) { showError(cause, 'saveFailed'); }
finally { receiptConfigSaving.value = false; }
/** 展开收料卡即视为有配置意图:统一保存时会提交收料配置,避免未展开时误建空配置。 */
function toggleReceiptSection(): void {
receiptSectionOpen.value = !receiptSectionOpen.value;
if (receiptSectionOpen.value) receiptSectionTouched.value = true;
}
/** 切换管理对象时同步深链并清空选择,避免不同对象的数据残留在编辑器中。 */
@@ -939,7 +962,7 @@ function selectInventoryMappingTab(tab: 'parsing' | 'inventoryFields'): void {
function createNew(): void {
selectedId.value = null;
if (activeTab.value === 'profiles') Object.assign(profile, { profile_code: '', display_name: '', connector_type: 'dbs', login_url: '', username: '', password: '', login_config_json: { auth_mode: 'password' }, enabled: true, upload_config_json: defaultUploadConfig('dbs') });
if (activeTab.value === 'parsing') { Object.assign(parsing, { profile_code: '', display_name: '', file_format: 'xlsx', sheet_name: '', header_row_index: 1, field_mappings: [], match_keys: [] }); structureAnalysis.value = null; pendingSampleReplacement.value = null; sampleReplacementConfirmed.value = false; selectedTemporaryInventorySession.value = ''; }
if (activeTab.value === 'parsing') { Object.assign(parsing, { profile_code: '', display_name: '', file_format: 'xlsx', sheet_name: '', header_row_index: 1, purpose: 'inventory', field_mappings: [], match_keys: [], movement_mappings: [] }); structureAnalysis.value = null; pendingSampleReplacement.value = null; sampleReplacementConfirmed.value = false; selectedTemporaryInventorySession.value = ''; }
if (activeTab.value === 'inventoryFields') Object.assign(inventoryField, { display_name: '', description: '', value_type: 'text', usage_type: 'general', sort_order: 100, status: 'active' });
if (activeTab.value === 'templates') {
Object.assign(excelTemplate, { template_code: '', display_name: '', filename_pattern: '{business_no}.xlsx', mappings: [], file: null });
@@ -949,10 +972,15 @@ function createNew(): void {
if (activeTab.value === 'sources') {
Object.assign(source, { source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [], enabled: false, activation: { ready: false, checks: [], missing_requirements: ['configuration_test'] } });
resetReceiptConfig('dbs');
receiptConfigExists.value = false;
receiptSectionTouched.value = false;
receiptSectionOpen.value = false;
inventoryPathOpen.value = true;
receiptBaseline.value = '';
sourceBaseline.value = '';
}
if (activeTab.value === 'rules') Object.assign(rule, { rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', operator: 'prefix', expected: '' }], source_codes: [] });
if (activeTab.value === 'mappings') Object.assign(mapping, { inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true });
if (activeTab.value === 'mappings') Object.assign(mapping, { inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', in_transit_warehouse_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true });
drawerOpen.value = true;
}
@@ -963,8 +991,10 @@ function selectItem(item: Item): void {
if (activeTab.value === 'parsing') Object.assign(parsing, {
profile_code: item.profile_code, display_name: item.display_name, file_format: item.file_format,
sheet_name: item.definition?.sheet_name || '', header_row_index: item.definition?.header_row_index ?? 0,
purpose: item.purpose === 'movement' ? 'movement' : 'inventory',
field_mappings: Object.entries(item.definition?.field_mapping || {}).map(([inventory_field, source_header]) => ({ inventory_field, source_header: String(source_header) })),
match_keys: (item.definition?.match_keys || []).map((entry: Record<string, unknown>) => ({ order_field_id: String(entry.order_field_id || ''), inventory_field: String(entry.inventory_field_id || entry.inventory_field || '') })),
movement_mappings: buildMovementMappings(item),
});
if (activeTab.value === 'parsing') {
// 草稿恢复保存的最小化样本证据,而不是要求管理员再次上传原始库存文件。
@@ -1010,7 +1040,7 @@ function selectItem(item: Item): void {
})),
source_codes: item.action_payload_json?.source_codes || [],
});
if (activeTab.value === 'mappings') Object.assign(mapping, { ...item, freight_warehouse_id: item.freight_warehouse_id || '', external_organization_code: item.external_organization_code || '', external_site_code: item.external_site_code || '' });
if (activeTab.value === 'mappings') Object.assign(mapping, { ...item, freight_warehouse_id: item.freight_warehouse_id || '', external_organization_code: item.external_organization_code || '', external_site_code: item.external_site_code || '', in_transit_warehouse_code: item.in_transit_warehouse_code || '' });
drawerOpen.value = true;
}
@@ -1130,7 +1160,13 @@ async function saveCurrent(): Promise<void> {
try {
if (activeTab.value === 'profiles') await saveShippingRpaProfile({ ...profile, display_name: profile.display_name || profile.profile_code, upload_config_json: profile.upload_config_json }, selectedId.value || undefined);
if (activeTab.value === 'parsing') {
const payload = {
const payload = parsing.purpose === 'movement' ? {
profile_code: parsing.profile_code, display_name: parsing.display_name || parsing.profile_code, file_format: parsing.file_format,
purpose: 'movement', sheet_name: parsing.sheet_name || null, header_row_index: parsing.header_row_index,
// 标准异动字段契约:code 由只读目录下发,这里只裁剪/校验别名映射。
field_mapping: buildMovementFieldMapping(parsing.movement_mappings),
match_keys: [] as string[],
} : {
profile_code: parsing.profile_code, display_name: parsing.display_name || parsing.profile_code, file_format: parsing.file_format,
sheet_name: parsing.sheet_name || null, header_row_index: parsing.header_row_index,
field_mapping: Object.fromEntries(parsing.field_mappings.map((item) => [item.inventory_field, item.source_header])),
@@ -1174,7 +1210,21 @@ async function saveCurrent(): Promise<void> {
await createShippingExcelTemplate(form);
}
}
if (activeTab.value === 'sources') await saveShippingInventorySource({ ...source, enabled: false, fixed_warehouse_id: source.warehouse_resolution_mode === 'fixed' ? source.fixed_warehouse_id : null, report_path_json: normaliseInventoryReportPath(source.connector_type, source.report_path_json) }, selectedId.value || undefined);
if (activeTab.value === 'sources') {
await saveShippingInventorySource({ ...source, enabled: false, fixed_warehouse_id: source.warehouse_resolution_mode === 'fixed' ? source.fixed_warehouse_id : null, report_path_json: normaliseInventoryReportPath(source.connector_type, source.report_path_json) }, selectedId.value || undefined);
// 收料与站点同批保存:仅当已有配置或管理员展开过收料卡时才提交,避免未配置站点被误建空收料配置。
if (selectedId.value && (receiptSectionTouched.value || (receiptConfigExists.value && receiptBaseline.value !== serialiseReceiptInput()))) {
try {
await saveShippingReceiptReportConfig(selectedId.value, buildReceiptReportConfigPayload(receiptConfig));
receiptConfigExists.value = true;
receiptBaseline.value = serialiseReceiptInput();
} catch (cause) {
showError(cause, 'saveFailed');
await load();
return; // 站点已保存但收料保存失败:保持抽屉打开,修正后可直接重试统一保存。
}
}
}
if (activeTab.value === 'rules') await saveShippingInventoryRule({ rule_code: rule.rule_code, rule_name: rule.rule_name || rule.rule_code, scope: rule.scope, priority: rule.priority, match_mode: 'all', action_type: 'add_source_candidates', action_payload_json: { source_codes: splitValues(rule.source_codes) }, conditions: rule.conditions.map((condition) => ({ source_kind: 'order_field', order_field_id: condition.order_field_id, operator: condition.operator, expected_value_json: normalizeExpectedValue(condition) })) }, selectedId.value || undefined);
if (activeTab.value === 'mappings') await saveShippingInventoryExternalMapping({ ...mapping, freight_warehouse_id: mapping.freight_warehouse_id || null, external_organization_code: mapping.external_organization_code || null, external_site_code: mapping.external_site_code || null }, selectedId.value || undefined);
await load();
@@ -1360,6 +1410,31 @@ async function refreshSelectedSource(): Promise<void> {
/** 新增一行结构化 DBS 查询参数,避免要求管理员编辑 JSON。 */
function addParameter(): void { source.query_parameters_json.push({ name: '', mode: 'single', values: [], required: false, select_all: false }); }
/** 把已保存 movement 规则的定义与只读字段目录合并为可编辑映射行;目录缺失时退化为纯 code 行。 */
function buildMovementMappings(item: Item) {
const saved = (item.definition?.field_mapping || {}) as Record<string, unknown>;
const catalog = movementFields.value.length
? movementFields.value
: Object.keys(saved).map((code) => ({ code, required: false, is_identity: false }));
return catalog.map((field) => ({
code: field.code, alias: String(saved[field.code] || ''),
required: Boolean(field.required), is_identity: Boolean(field.is_identity),
}));
}
/** 切换用途时初始化对应映射行:movement 预填标准字段目录,inventory 清空自由映射。 */
function resetMappingRowsForPurpose(): void {
if (parsing.purpose === 'movement') {
parsing.movement_mappings = movementFields.value.map((field) => ({
code: field.code, alias: '', required: Boolean(field.required), is_identity: Boolean(field.is_identity),
}));
parsing.field_mappings = [];
parsing.match_keys = [];
} else {
parsing.movement_mappings = [];
}
}
function addParsingFieldMapping(): void {
if (!structureAnalysis.value) {
message.warning(t('admin.shippingInventory.inventorySampleRequired'));
@@ -1527,6 +1602,8 @@ function rowTitle(item: Item): string { return String(item.display_name || item.
function rowMeta(item: Item): string {
if (activeTab.value === 'inventoryFields') return `${t(`admin.shippingInventory.inventoryFieldType.${item.value_type || 'text'}`)} · ${t(`admin.shippingInventory.inventoryFieldPurposeOption.${item.usage_type || 'general'}`)}`;
if (item.connector_type) return String(item.display_name ? t(`admin.shippingInventory.platform.${item.connector_type}`) : item.connector_type);
// 解析规则列表带出用途徽标文案,库存/异动两种规则在列表一眼可分。
if (activeTab.value === 'parsing') return `${t(`admin.shippingInventory.parsingPurpose.${item.purpose === 'movement' ? 'movement' : 'inventory'}`)} · V${item.version ?? '-'}`;
return String(item.source_code || item.profile_code || item.rule_code || item.external_warehouse_code || '-');
}
@@ -1553,6 +1630,16 @@ function serialiseSourceInput(): string {
});
}
/** 将收料配置表单稳定序列化(含异动解析规则绑定),作为统一保存与启用守卫的收料脏检查基线。 */
function serialiseReceiptInput(): string {
return JSON.stringify({
report_path_json: receiptConfig.report_path_json,
query_parameters_json: receiptConfig.query_parameters_json,
// 异动解析绑定必须参与脏检查:否则只改绑定时统一保存会跳过收料配置提交,改动被静默丢弃。
parsing_profile_id: receiptConfig.parsing_profile_id ? Number(receiptConfig.parsing_profile_id) : null,
});
}
/** 返回状态轨道的简洁可视标记,文本状态仍由相邻内容提供,避免颜色成为唯一信息来源。 */
function readinessMarker(status: ShippingInventoryReadinessCheck['status']): string {
const marker = readinessMarkerKind(status);
@@ -1673,10 +1760,10 @@ onMounted(load);
.filename-variable-menu button { display: grid; width: 100%; grid-template-columns: 154px minmax(0, 1fr); gap: 8px; border: 0; border-radius: 4px; background: transparent; padding: 7px 8px; color: #64748b; font: inherit; font-size: 12px; text-align: left; cursor: pointer; }
.filename-variable-menu button:hover, .filename-variable-menu button.active { background: #eef8f7; color: #145f5a; }.filename-variable-menu code { color: #047f76; font-size: 12px; }.filename-variable-menu p { margin: 0; padding: 8px; color: #94a3b8; font-size: 12px; }
.readiness-card { display: grid; gap: 12px; border: 1px solid #cfe2ea; border-radius: 12px; background: #fbfdfe; padding: 16px; }.readiness-card.ready { border-color: #b9dfc4; background: #fcfffd; }
.readiness-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }.readiness-heading > div { display: grid; gap: 5px; }.readiness-kicker { color: #5f798c; font-size: 11px; font-weight: 700; letter-spacing: .04em; }.readiness-heading strong { color: #263b4e; font-size: 14px; line-height: 1.4; }.readiness-heading p { margin: 0; color: #6d8292; font-size: 12px; line-height: 1.45; }.readiness-count { flex: 0 0 auto; border: 1px solid #cce7f1; border-radius: 999px; background: #edf8fc; padding: 5px 9px; color: #176f9f; font-size: 12px; font-weight: 700; white-space: nowrap; }.readiness-card.ready .readiness-count { border-color: #cce8d4; background: #eef9f1; color: #19703a; }
.readiness-section { border: 1px solid #e1edf2; border-radius: 9px; background: #fff; padding: 0 12px; }.readiness-section-heading { display: grid; gap: 2px; padding: 11px 0 8px; }.readiness-section-heading b { color: #385166; font-size: 12px; }.readiness-section-heading small { color: #8192a0; font-size: 11px; }.readiness-steps { display: grid; gap: 0; margin: 0; padding: 0; list-style: none; }.readiness-steps li { display: grid; grid-template-columns: 24px minmax(0, 1fr) auto; align-items: center; gap: 9px; min-height: 46px; border-top: 1px solid #edf2f5; padding: 7px 0; }.readiness-marker { display: inline-grid; width: 20px; height: 20px; place-items: center; border-radius: 50%; background: #e9eef3; color: #6c7d8d; font-size: 12px; font-weight: 800; }.readiness-copy { display: grid; min-width: 0; gap: 2px; }.readiness-copy b { overflow: hidden; color: #425466; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }.readiness-copy small { color: #8190a0; font-size: 11px; line-height: 1.35; }.readiness-steps .is-passed .readiness-marker { background: #dff6e6; color: #16803a; }.readiness-steps .is-passed .readiness-copy b { color: #2d6b40; }.readiness-steps .is-failed .readiness-marker, .readiness-steps .is-stale .readiness-marker { background: #fff0ed; color: #bf4a38; }.readiness-steps .is-failed .readiness-copy b, .readiness-steps .is-stale .readiness-copy b { color: #9d382b; }
.readiness-inline { display: flex; align-items: center; gap: 10px; }.readiness-inline .readiness-copy { flex: 1 1 auto; }.readiness-inline .readiness-copy b { white-space: normal; }.readiness-inline .readiness-copy small { white-space: normal; }.readiness-inline .btn-sm, .readiness-inline .readiness-action { flex: 0 0 auto; }
.readiness-steps { display: grid; gap: 0; margin: 0; padding: 0; list-style: none; }.readiness-steps li { display: grid; grid-template-columns: 24px minmax(0, 1fr) auto; align-items: center; gap: 9px; min-height: 46px; border-top: 1px solid #edf2f5; padding: 7px 0; }.readiness-marker { display: inline-grid; width: 20px; height: 20px; place-items: center; border-radius: 50%; background: #e9eef3; color: #6c7d8d; font-size: 12px; font-weight: 800; }.readiness-copy { display: grid; min-width: 0; gap: 2px; }.readiness-copy b { overflow: hidden; color: #425466; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }.readiness-copy small { color: #8190a0; font-size: 11px; line-height: 1.35; }.readiness-steps .is-passed .readiness-marker { background: #dff6e6; color: #16803a; }.readiness-steps .is-passed .readiness-copy b { color: #2d6b40; }.readiness-steps .is-failed .readiness-marker, .readiness-steps .is-stale .readiness-marker { background: #fff0ed; color: #bf4a38; }.readiness-steps .is-failed .readiness-copy b, .readiness-steps .is-stale .readiness-copy b { color: #9d382b; }.readiness-inline > .readiness-marker.is-passed { background: #dff6e6; color: #16803a; }.readiness-inline > .readiness-marker.is-failed, .readiness-inline > .readiness-marker.is-stale { background: #fff0ed; color: #bf4a38; }
.readiness-optional { border-top: 1px solid #e4edf2; padding-top: 10px; }.readiness-optional summary, .readiness-audit summary { display: flex; align-items: baseline; gap: 8px; color: #61798a; cursor: pointer; list-style: none; }.readiness-optional summary::-webkit-details-marker, .readiness-audit summary::-webkit-details-marker { display: none; }.readiness-optional summary::before, .readiness-audit summary::before { color: #4d849f; content: '›'; font-size: 16px; line-height: .8; transition: transform .15s; }.readiness-optional[open] summary::before, .readiness-audit[open] summary::before { transform: rotate(90deg); }.readiness-optional summary span { color: #516b7d; font-size: 12px; font-weight: 700; }.readiness-optional summary small { color: #8797a5; font-size: 11px; }.readiness-optional .readiness-steps { margin-top: 8px; }
.readiness-action { border: 0; border-radius: 5px; background: #e8f3f9; padding: 6px 8px; color: #16759f; font: inherit; font-size: 11px; font-weight: 700; cursor: pointer; }.readiness-action:hover { background: #d8edf7; }.readiness-run { margin: 0; border-left: 3px solid #74b8d8; background: #f0f8fc; padding: 8px 10px; color: #547185; font-size: 11px; line-height: 1.5; }.readiness-run.failed { border-left-color: #e06a58; background: #fff5f3; color: #9d382b; }.readiness-audit { margin: 0; border-top: 1px solid #e4edf2; padding-top: 10px; }.readiness-audit summary { color: #61798a; font-size: 11px; font-weight: 700; }.readiness-audit dl { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1px; margin: 9px 0 0; overflow: hidden; border: 1px solid #dce8ef; border-radius: 7px; background: #dce8ef; }.readiness-audit dl > div { min-width: 0; background: #fff; padding: 8px 9px; }.readiness-audit dt { color: #7b8998; font-size: 11px; font-weight: 700; }.readiness-audit dd { overflow: hidden; margin: 4px 0 0; color: #3d5366; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11px; font-variant-numeric: tabular-nums; text-overflow: ellipsis; white-space: nowrap; }.readiness-footer { display: flex; justify-content: flex-end; border-top: 1px solid #e6eef4; padding-top: 11px; }
.readiness-action { border: 0; border-radius: 5px; background: #e8f3f9; padding: 6px 8px; color: #16759f; font: inherit; font-size: 11px; font-weight: 700; cursor: pointer; }.readiness-action:hover { background: #d8edf7; }.readiness-run { margin: 0; border-left: 3px solid #74b8d8; background: #f0f8fc; padding: 8px 10px; color: #547185; font-size: 11px; line-height: 1.5; }.readiness-run.failed { border-left-color: #e06a58; background: #fff5f3; color: #9d382b; }.readiness-audit { margin: 0; border-top: 1px solid #e4edf2; padding-top: 10px; }.readiness-audit summary { color: #61798a; font-size: 11px; font-weight: 700; }.readiness-audit dl { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1px; margin: 9px 0 0; overflow: hidden; border: 1px solid #dce8ef; border-radius: 7px; background: #dce8ef; }.readiness-audit dl > div { min-width: 0; background: #fff; padding: 8px 9px; }.readiness-audit dt { color: #7b8998; font-size: 11px; font-weight: 700; }.readiness-audit dd { overflow: hidden; margin: 4px 0 0; color: #3d5366; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11px; font-variant-numeric: tabular-nums; text-overflow: ellipsis; white-space: nowrap; }
.form-tip { border-radius: 8px; background: #f1f6fa; padding: 11px; color: #5d7084; font-size: 12px; line-height: 1.55; }
.upload-config-section { grid-column: 1 / -1; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; border: 1px solid #e1edf2; border-radius: 9px; background: #fff; padding: 0 12px 12px; }.upload-config-heading { display: grid; gap: 2px; grid-column: 1 / -1; padding: 11px 0 8px; }.upload-config-heading b { color: #385166; font-size: 12px; }.upload-config-heading small { color: #8192a0; font-size: 11px; }.upload-config-section .full { grid-column: 1 / -1; }.upload-config-section textarea.input-field { resize: vertical; }
.configuration-test-verified { margin: 0; border-left: 3px solid #34a56b; background: #effaf3; padding: 9px 10px; color: #256b43; font-size: 12px; font-weight: 600; line-height: 1.45; }
@@ -1685,9 +1772,12 @@ onMounted(load);
.sample-evidence-card dl { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px 16px; margin: 0; }.sample-evidence-card dl div { min-width: 0; }.sample-evidence-card dt { color: #8190a0; font-size: 11px; }.sample-evidence-card dd { margin: 3px 0 0; overflow-wrap: anywhere; color: #475569; font-size: 12px; font-weight: 600; }
.sample-replacement-input { display: grid; gap: 6px; border-top: 1px solid #e5edf3; padding-top: 11px; color: #52677a; font-size: 12px; font-weight: 600; }.sample-replacement-input input { max-width: 100%; }.sample-replacement-warning { border-left: 3px solid #e5a21a; background: #fff9eb; padding: 8px 10px; color: #855e00 !important; }.sample-replacement-warning p { margin: 0; }.sample-replacement-warning ul { display: grid; gap: 3px; margin: 7px 0 0; padding-left: 17px; }
.parameter-row { display: grid; align-items: center; grid-template-columns: 1.1fr .9fr 1.25fr auto auto auto; gap: 8px; border-radius: 8px; background: #f8fafc; padding: 9px; }
.receipt-report-config { display: grid; grid-column: 1 / -1; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; border-top: 1px solid #dbe8ee; margin-top: 8px; padding-top: 14px; }
.receipt-report-config .subsection, .receipt-report-config .full { grid-column: 1 / -1; }
.receipt-config-actions { display: flex; justify-content: flex-end; }
.path-card { display: grid; grid-column: 1 / -1; border: 1px solid #dbe8ee; border-radius: 10px; background: #fff; overflow: hidden; }
.path-card-header { display: flex; align-items: center; gap: 10px; border: 0; background: #f7fbfd; padding: 10px 12px; cursor: pointer; font: inherit; text-align: left; }.path-card-header:hover { background: #eff7fa; }
.path-card-title { display: grid; flex: 1 1 auto; min-width: 0; gap: 2px; }.path-card-title b { color: #145f5a; font-size: 12px; font-weight: 800; }.path-card-title small { color: #94a3b8; font-size: 11px; font-weight: 400; }
.path-badge { flex: 0 0 auto; border-radius: 999px; background: #eef2f5; padding: 3px 8px; color: #7b8998; font-size: 11px; font-weight: 700; }.path-card.configured .path-badge.on { background: #e6f6ec; color: #19703a; }
.path-card-toggle { flex: 0 0 auto; color: #4d849f; font-size: 14px; line-height: 1; }
.path-card-body { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; border-top: 1px solid #e6eef4; padding: 14px 12px; }.path-card-body .full { grid-column: 1 / -1; }
.condition-row, .mapping-row, .template-mapping { display: grid; align-items: center; gap: 8px; border-radius: 8px; background: #f8fafc; padding: 9px; }
.condition-row { grid-template-columns: 1.15fr .9fr 1fr auto; }
.mapping-row { grid-template-columns: 1fr 1fr auto; }
@@ -1728,5 +1818,5 @@ onMounted(load);
.object-list .empty-state { grid-column: 1 / -1; display: grid; min-height: 260px; place-items: center; }
.empty-state { border: 1px dashed #c9d7e5; border-radius: 10px; background: #f9fbfd; padding: 38px 18px; color: #7b899a; font-size: 13px; text-align: center; }
@media (max-width: 980px) { .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card { grid-template-columns: 1fr 1fr; } .mapping-value-row { grid-template-columns: minmax(0, 1.6fr) minmax(180px, 1fr); }.readiness-audit { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 640px) { .inventory-console { padding: 18px; } .editor-form, .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card, .mapping-value-row, .parsing-mapping-card, .readonly-mapping-section .parsing-mapping-card, .parsing-summary, .receipt-report-config { grid-template-columns: 1fr; } .mapping-arrow { transform: rotate(90deg); }.workbench-heading { display: block; } .workbench-heading .btn-primary { margin-top: 12px; }.batch-source-list { grid-template-columns: 1fr; }.batch-stat-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }.batch-run { grid-template-columns: 9px minmax(0, 1fr); }.batch-run-error { grid-column: 2; }.readiness-heading { display: grid; }.readiness-count { justify-self: start; }.readiness-steps li { grid-template-columns: 24px minmax(0, 1fr); }.readiness-action { grid-column: 2; justify-self: start; }.readiness-footer { justify-content: stretch; }.readiness-footer .btn-primary { width: 100%; } }
@media (max-width: 640px) { .inventory-console { padding: 18px; } .editor-form, .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card, .mapping-value-row, .parsing-mapping-card, .readonly-mapping-section .parsing-mapping-card, .parsing-summary, .path-card-body { grid-template-columns: 1fr; } .mapping-arrow { transform: rotate(90deg); }.workbench-heading { display: block; } .workbench-heading .btn-primary { margin-top: 12px; }.batch-source-list { grid-template-columns: 1fr; }.batch-stat-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }.batch-run { grid-template-columns: 9px minmax(0, 1fr); }.batch-run-error { grid-column: 2; }.readiness-inline { flex-wrap: wrap; }.readiness-steps li { grid-template-columns: 24px minmax(0, 1fr); }.readiness-action { grid-column: 2; justify-self: start; } }
</style>
@@ -0,0 +1,37 @@
/**
* features/admin/modules/shipping-inventory/movementParsingProfileForm.spec.ts
* 用途:覆盖收料异动解析规则映射的组装边界。
* 依赖:movementParsingProfileForm、vitest。
* 逻辑:标准异动字段是只读领域契约——映射键必须是契约 code,必填字段缺失要阻断保存。
*/
import { describe, expect, it } from 'vitest';
import { buildMovementFieldMapping, REQUIRED_MOVEMENT_FIELD_CODES } from './movementParsingProfileForm';
describe('movementParsingProfileForm', () => {
it('exports the fixed required movement field codes', () => {
// 关键断言:必填集是后端契约的镜像,变更必须显式同步。
expect(REQUIRED_MOVEMENT_FIELD_CODES).toEqual(['doc_no', 'material_code', 'quantity', 'movement_date']);
});
it('builds code-keyed mapping, trims aliases and drops empty optional rows', () => {
const mapping = buildMovementFieldMapping([
{ code: 'doc_no', alias: ' 单据编号 ', required: true, is_identity: true },
{ code: 'line_no', alias: '', required: false, is_identity: false },
{ code: 'material_code', alias: '料号', required: true, is_identity: true },
{ code: 'quantity', alias: '数量', required: true, is_identity: false },
{ code: 'movement_date', alias: '异动日期', required: true, is_identity: true },
]);
expect(mapping).toEqual({ doc_no: '单据编号', material_code: '料号', quantity: '数量', movement_date: '异动日期' });
});
it('rejects saving when a required movement field has no alias', () => {
// 关键断言:缺必填映射必须抛错并点名缺失字段,不允许带着残缺契约提交。
expect(() => buildMovementFieldMapping([
{ code: 'doc_no', alias: '单据编号', required: true, is_identity: true },
{ code: 'material_code', alias: '', required: true, is_identity: true },
{ code: 'quantity', alias: '数量', required: true, is_identity: false },
{ code: 'movement_date', alias: '', required: true, is_identity: true },
])).toThrowError(/material_code, movement_date/);
});
});
@@ -0,0 +1,38 @@
/**
* features/admin/modules/shipping-inventory/movementParsingProfileForm.ts
* 用途:组装收料异动解析规则(purpose='movement')的标准字段映射载荷。
* 依赖:无外部依赖。
* 逻辑:标准异动字段目录由后端 /admin/shipping-notice/movement-fields 只读下发,
* 本模块只做裁剪与校验——映射键是契约 code,必填字段缺失阻断保存;
* 不提供任何自定义字段的入口(业务领域字段不允许用户自定义)。
*/
/** 与后端 movement_contract.MOVEMENT_FIELDS 的 required 标记保持一致,变更必须双向同步。 */
export const REQUIRED_MOVEMENT_FIELD_CODES = ['doc_no', 'material_code', 'quantity', 'movement_date'] as const;
/** 标准异动字段映射行(目录行 + 管理员选择的报表表头别名)。 */
export type MovementFieldMapping = {
code: string;
alias: string;
required: boolean;
is_identity: boolean;
};
/**
* 构造异动解析定义的 field_mapping({契约code: 报表表头别名})。
* 核心逻辑:别名 trim 后为空的行视为未映射——可选字段直接剔除,
* 必填字段缺失则抛错点名,禁止带着残缺契约提交到后端。
* @param mappings - 异动字段映射行(来自只读字段目录 + 用户选择)。
* @returns 可直接放入保存载荷的 field_mapping 对象。
*/
export function buildMovementFieldMapping(mappings: MovementFieldMapping[]): Record<string, string> {
const mapping: Record<string, string> = {};
for (const item of mappings || []) {
const alias = String(item.alias || '').trim();
if (!alias) continue;
mapping[String(item.code).trim()] = alias;
}
const missing = REQUIRED_MOVEMENT_FIELD_CODES.filter((code) => !mapping[code]);
if (missing.length) throw new Error(`missing required movement fields: ${missing.join(', ')}`);
return mapping;
}
@@ -2,7 +2,8 @@
* features/admin/modules/shipping-inventory/receiptReportConfigForm.spec.ts
* 用途:覆盖收料报表表单的独立载荷边界。
* 依赖:receiptReportConfigForm、vitest。
* 逻辑:防止收料配置保存时把库存站点路径、库存查询条件或启停状态误发到库存接口。
* 逻辑:防止收料配置保存时把库存站点路径、库存查询条件或启停状态误发到库存接口;
* 收料无独立启停字段,载荷不得包含 enabled。
*/
import { describe, expect, it } from 'vitest';
@@ -10,24 +11,48 @@ import { buildReceiptReportConfigPayload } from './receiptReportConfigForm';
describe('receiptReportConfigForm', () => {
it('builds a receipt-only payload without inventory source fields', () => {
// 关键断言:收料路径、条件与仓库必须走独立 API,不能夹带库存 RPA 配置。
// 关键断言:收料路径与条件必须走独立 API,不能夹带库存 RPA 配置或启停字段。
const payload = buildReceiptReportConfigPayload({
enabled: true,
report_path_json: { program_group: 'Bison', program_label: 'AWSBI', report_group: 'Inbound', report_name: 'Receipt Detail' },
query_parameters_json: [{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false }],
warehouse_ids_json: ['A', 'B'],
query_parameters_json: [
{ name: 'Warehouse', mode: 'multi_text', values: ['AWSDU', 'AWSDU-02'], required: false, select_all: false },
{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false },
],
source_code: 'INVENTORY-SHOULD-NOT-LEAK',
snapshot_ttl_seconds: 86400,
enabled: true,
warehouse_ids_json: ['SHOULD-NOT-LEAK'],
inventory_report_path_json: { report_name: 'On Hand' },
});
} as Parameters<typeof buildReceiptReportConfigPayload>[0] & Record<string, unknown>);
expect(payload).toEqual({
enabled: true,
report_path_json: { program_group: 'Bison', program_label: 'AWSBI', report_group: 'Inbound', report_name: 'Receipt Detail' },
query_parameters_json: [{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false }],
warehouse_ids_json: ['A', 'B'],
query_parameters_json: [
{ name: 'Warehouse', mode: 'multi_text', values: ['AWSDU', 'AWSDU-02'], required: false, select_all: false },
{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false },
],
// 关键断言:载荷契约固定三元——未绑定时异动解析绑定显式为 null,不缺键。
parsing_profile_id: null,
});
expect(payload).not.toHaveProperty('source_code');
expect(payload).not.toHaveProperty('snapshot_ttl_seconds');
expect(payload).not.toHaveProperty('enabled');
expect(payload).not.toHaveProperty('warehouse_ids_json');
});
it('carries movement profile binding and normalizes absent id to explicit unbind', () => {
// 关键断言:异动解析绑定随配置提交;未绑定时必须显式提交 null(解绑),不能省略键。
const bound = buildReceiptReportConfigPayload({
report_path_json: { report_name: 'Inbound Details' },
query_parameters_json: [],
parsing_profile_id: 7,
});
expect(bound.parsing_profile_id).toBe(7);
const unbound = buildReceiptReportConfigPayload({
report_path_json: { report_name: 'Inbound Details' },
query_parameters_json: [],
});
expect(unbound.parsing_profile_id).toBeNull();
});
});
@@ -2,27 +2,28 @@
* features/admin/modules/shipping-inventory/receiptReportConfigForm.ts
* 用途:构建独立收料报表配置的受限保存载荷。
* 依赖:无外部依赖。
* 逻辑:页面仅将收料路径、可选条件和 Warehouse 列表提交到收料配置 API,隔离库存站点字段。
* 逻辑:页面仅将收料路径与查询条件提交到收料配置 API,与库存同构(Warehouse 为条件之一),
* 隔离库存站点字段;收料无独立启停字段,是否运行统一由库存站点 enabled 决定。
*/
export type ReceiptReportConfigInput = {
enabled: boolean;
report_path_json: Record<string, unknown>;
query_parameters_json: Array<Record<string, unknown>>;
warehouse_ids_json: string[];
/** 收料异动解析规则绑定;0/undefined 视为未绑定并归一为 null(显式解绑)。 */
parsing_profile_id?: number | null;
};
/**
* 构造独立收料配置保存载荷。
* 核心逻辑:白名单复制可配置业务字段,不允许调用方把库存源、Profile 或启停字段带入收料 API。
* 核心逻辑:白名单复制可配置业务字段,不允许调用方把库存源、Profile 或启停字段带入收料 API;
* 异动解析绑定随配置一并提交(null=解绑)。
* @param input - 抽屉中的收料配置表单状态。
* @returns 仅包含收料配置 API 支持字段的深拷贝载荷。
*/
export function buildReceiptReportConfigPayload(input: ReceiptReportConfigInput): ReceiptReportConfigInput {
return {
enabled: Boolean(input.enabled),
report_path_json: { ...(input.report_path_json || {}) },
query_parameters_json: (input.query_parameters_json || []).map((item) => ({ ...item })),
warehouse_ids_json: [...(input.warehouse_ids_json || [])],
parsing_profile_id: input.parsing_profile_id ? Number(input.parsing_profile_id) : null,
};
}
@@ -613,6 +613,14 @@ const coordinateCanvasActions = computed<OrderProfileCanvasActions>(() => ({
page: (nextPageNo) => { void selectPage(nextPageNo); },
draw: (kind) => startDrawing(kind),
}));
/** 页图 token 失效时自动重签;客户端渲染失败(如 worker MIME)不得超过预算。 */
let previewReauthInFlight = false;
let previewAutoReauthCount = 0;
const PREVIEW_AUTO_REAUTH_LIMIT = 2;
const resetPreviewAutoReauthBudget = () => {
previewAutoReauthCount = 0;
};
/**
* 共享视觉画布模型:模板差异在此处一次性被 adapter 吸收,之后所有画布事件和 props
* 均只消费 visualCanvas。datasets path、集合与拆分规则不属于视觉模型,继续留在 XFA
@@ -659,7 +667,10 @@ const visualCanvas = computed<OrderProfileVisualCanvasAdapter>(() => {
warningVisible: adapterWarningVisible || canvasUnavailable.value,
warningText: adapterWarningText
|| (canvasUnavailable.value ? t('admin.shippingOrderProfiles.workbench.canvasUnavailable') : null),
retryCanvas: () => { void loadPages(); },
retryCanvas: () => {
resetPreviewAutoReauthBudget();
void loadPages();
},
reportCanvasLoadFailed: () => { canvasUnavailable.value = true; },
applyAutomarkCandidates: () => false,
canRender: true,
@@ -814,13 +825,13 @@ const deskCanvasReadonly = computed(() => visualCanvas.value.canvasReadonly);
const deskCanvasWarningVisible = computed(() => visualCanvas.value.warningVisible);
const deskCanvasWarningText = computed(() => visualCanvas.value.warningText || '');
const onDeskCanvasRetry = () => visualCanvas.value.retryCanvas();
/** 页图 token 失效时自动重签一批预览令牌,避免翻页后只能手动点「重试画布」。 */
let previewReauthInFlight = false;
/** 页图/原 PDF 令牌 HTTP 失效时自动重签;客户端渲染失败不得走此路径(见 DocumentCanvas)。 */
const onDeskCanvasLoadFailed = async () => {
if (previewReauthInFlight) {
if (previewReauthInFlight || previewAutoReauthCount >= PREVIEW_AUTO_REAUTH_LIMIT) {
visualCanvas.value.reportCanvasLoadFailed();
return;
}
previewAutoReauthCount += 1;
previewReauthInFlight = true;
try {
await loadPages();
@@ -14,11 +14,12 @@ const { getDocumentMock, getPageMock, renderMock } = vi.hoisted(() => ({
renderMock: vi.fn(),
}));
vi.mock('pdfjs-dist', () => ({
GlobalWorkerOptions: {},
getDocument: (...args: unknown[]) => getDocumentMock(...args),
vi.mock('@/shared/utils/pdfjs', () => ({
loadPdfJs: async () => ({
GlobalWorkerOptions: {},
getDocument: (...args: unknown[]) => getDocumentMock(...args),
}),
}));
vi.mock('pdfjs-dist/build/pdf.worker.min.mjs?url', () => ({ default: '/pdf.worker.min.mjs' }));
vi.mock('@/shared/utils/auth', () => ({ getAuthHeaders: () => ({ Authorization: 'Bearer test' }) }));
describe('OrderProfileDocumentCanvas PDF preview', () => {
@@ -274,4 +275,89 @@ describe('OrderProfileDocumentCanvas PDF preview', () => {
// 使用 PDF.js 原始像素而不是 CSS 缩放后的大小,保证回读与用户框选区域一致。
expect(drawImage).toHaveBeenCalledWith(source, 60, 160, 181, 240, 0, 0, 181, 240);
});
it('keeps pdfCanvas mounted under pdfPreview error overlay and does not reauth on render failure', async () => {
getDocumentMock.mockReturnValue({
promise: Promise.resolve({
numPages: 1,
getPage: vi.fn(async () => {
throw new Error('PDF canvas is unavailable');
}),
}),
});
const wrapper = mount(OrderProfileDocumentCanvas, {
props: {
profileId: 71,
pdfPreview: { preview_token: 'single-use-token' },
regions: [], pageNo: 1, pageCount: 1,
},
global: {
plugins: [createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
admin: { shippingOrderProfiles: { workbench: { canvasUnavailable: '受控 PDF 画布暂不可用', retryCanvas: '重试' } } },
},
},
})],
},
});
await flushPromises();
await flushPromises();
// 关键断言:原 PDF 路径失败不得卸掉 canvas,否则重试/reauth 后 render 仍读到 null。
expect(wrapper.find('canvas.pdf-page').exists()).toBe(true);
expect(wrapper.find('.canvas-error-overlay').exists()).toBe(true);
expect(wrapper.emitted('loadFailed')).toBeUndefined();
});
it('reuses in-memory PDF bytes for the same single-use preview token', async () => {
const wrapper = mount(OrderProfileDocumentCanvas, {
props: {
profileId: 71,
pdfPreview: { preview_token: 'single-use-token' },
regions: [], pageNo: 1, pageCount: 1,
},
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] },
});
await flushPromises();
await flushPromises();
expect(fetch).toHaveBeenCalledTimes(1);
// 改 grant 依赖重入 watch,但 pdfPreview token 不变;必须走内存缓存,否则 getdel 二次 GET=404。
await wrapper.setProps({
grant: { page_no: 1, preview_token: 'png-ignored' },
pdfPreview: { preview_token: 'single-use-token' },
});
await flushPromises();
await flushPromises();
expect(fetch).toHaveBeenCalledTimes(1);
});
it('emits loadFailed only for preview-token HTTP failures', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response('', { status: 404 })));
const wrapper = mount(OrderProfileDocumentCanvas, {
props: {
profileId: 71,
pdfPreview: { preview_token: 'dead-token' },
regions: [], pageNo: 1, pageCount: 1,
},
global: {
plugins: [createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
admin: { shippingOrderProfiles: { workbench: { canvasUnavailable: '受控 PDF 画布暂不可用', retryCanvas: '重试' } } },
},
},
})],
},
});
await flushPromises();
await flushPromises();
expect(wrapper.emitted('loadFailed')).toHaveLength(1);
expect(wrapper.find('canvas.pdf-page').exists()).toBe(true);
});
});
@@ -4,6 +4,9 @@
依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion、isUnboundOrderFieldCanvasRegion。
逻辑:父级签发单页令牌并提供分页动作;mode=readonly 时只允许查看/缩放/切页,不允许写入任何标注改动;
PNG 预览 token 为一次性消费,组件内按页缓存 blob,翻页回访不再重新拉 token;
原 PDF(pdf-preview)令牌亦为 Redis getdel 单次消费:同 token 字节必须缓存,且仅 HTTP 401/403/404
才 emit loadFailed 触发父级 reauth;画布/渲染失败不得重签,否则会空转授权风暴;
pdfPreview 错误态用 overlay,禁止 v-if 卸掉 pdfCanvas(否则 renderPdfPage 必失败);
未绑定订单字段框强制高亮(region--unbound),并暴露 scrollRegionIntoView 供横幅定位删除;
选中框用 top/right/bottom/left 定位(避免 height% 在内容撑高容器上失效);
拖拽/缩放进行中忽略滚轮缩放,避免触控板纵向手势把高度调整抢走;
@@ -16,28 +19,11 @@ import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
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 { loadPdfJs } from '@/shared/utils/pdfjs';
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');
let pdfjsLoader: Promise<PdfJsModule> | null = null;
/** 动态加载 PDF.js 与 worker;坐标 PDF 与 XFA 在受控管理员画布按需共用。 */
async function loadPdfJs(): Promise<PdfJsModule> {
if (!pdfjsLoader) {
pdfjsLoader = (async () => {
const [pdfjs, workerMod] = await Promise.all([
import('pdfjs-dist'),
import('pdfjs-dist/build/pdf.worker.min.mjs?url'),
]);
pdfjs.GlobalWorkerOptions.workerSrc = workerMod.default;
return pdfjs;
})();
}
return pdfjsLoader;
}
const props = defineProps<{
profileId: number | null;
grant?: OrderProfilePreviewPageGrant | null;
@@ -107,6 +93,12 @@ const viewport = ref<HTMLElement | null>(null);
const zoom = ref(1);
/** 按页缓存已消费 token 拉取的 PNG,翻页回访不再触发一次性 token 失效。 */
const pageImageCache = new Map<string, string>();
/**
* 原 PDF 字节缓存:pdf-preview 令牌是 Redis getdel 单次消费。
* 同 token 的并发/重入 loadPage 若再次 GET 会 404,并误触发父级 reauth 风暴。
*/
let cachedPdfBytes: Uint8Array | null = null;
let cachedPdfToken: string | null = null;
let loadGeneration = 0;
let cachedProfileId: number | null = null;
const zoomPercent = computed(() => Math.round(zoom.value * 100));
@@ -123,17 +115,34 @@ const emptyStateText = computed(() => (
props.emptyHint || t('admin.shippingOrderProfiles.workbench.selectBoundPdf')
));
/**
* 等待 pdfCanvas 进入 DOM。
* 错误态曾用 v-if 卸掉 canvas;清错后仅一次 nextTick 仍可能读到 null,
* 进而抛 "PDF canvas is unavailable",被空 catch 吃掉且 0 console error。
*/
const ensurePdfCanvas = async (): Promise<{ canvas: HTMLCanvasElement; context: CanvasRenderingContext2D }> => {
for (let attempt = 0; attempt < 10; attempt += 1) {
await nextTick();
const el = pdfCanvas.value;
const context = el?.getContext('2d');
if (el && context) return { canvas: el, context };
await new Promise<void>((resolve) => {
if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => resolve());
else window.setTimeout(() => resolve(), 16);
});
}
throw new Error('PDF canvas is unavailable');
};
/**
* 将内存中的原 PDF 按真实页面外观流绘制到 Canvas。
* 核心逻辑:坐标 PDF 与 hybrid XFA 都用 page.render(),不生成可下载 URL。
*/
const renderPdfPage = async (pdf: PDFDocumentProxy) => {
await nextTick();
const targetPage = Math.min(Math.max(props.pageNo, 1), pdf.numPages);
const targetPage = Math.min(Math.max(props.pageNo, 1), pdf.numPages || 1);
if (pdf.numPages < 1) throw new Error('PDF has no pages');
const page = await pdf.getPage(targetPage);
const canvas = pdfCanvas.value;
const context = canvas?.getContext('2d');
if (!canvas || !context) throw new Error('PDF canvas is unavailable');
const { canvas, context } = await ensurePdfCanvas();
const viewport = page.getViewport({ scale: zoom.value });
pdfPageSize.value = { width: viewport.width, height: viewport.height };
canvas.width = Math.ceil(viewport.width);
@@ -142,6 +151,12 @@ const renderPdfPage = async (pdf: PDFDocumentProxy) => {
pdfRendered.value = true;
};
/** 令牌失效类 HTTP 才值得父级 reauth;画布未挂载/渲染失败重签只会空转。 */
const isPreviewTokenHttpError = (error: unknown): boolean => {
if (!(error instanceof Error)) return false;
return /^HTTP (401|403|404)\b/.test(error.message);
};
/**
* 回收某次会话内全部页图 blob;切换样本 Profile 或卸载时调用。
*/
@@ -149,6 +164,8 @@ const clearPageImageCache = () => {
for (const url of pageImageCache.values()) URL.revokeObjectURL(url);
pageImageCache.clear();
inflightPageLoads.clear();
cachedPdfBytes = null;
cachedPdfToken = null;
};
/** 同一页的并发拉取共用一个 Promise,成功后必入缓存(即使请求已过期)。 */
@@ -206,13 +223,21 @@ const loadPage = async () => {
|| `/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' },
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const token = props.pdfPreview.preview_token;
let bytes: Uint8Array;
if (cachedPdfToken === token && cachedPdfBytes) {
bytes = cachedPdfBytes;
} else {
const response = await fetch(
`${previewPath}?preview_token=${encodeURIComponent(token)}`,
{ headers: getAuthHeaders(), cache: 'no-store' },
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
bytes = new Uint8Array(await response.arrayBuffer());
cachedPdfBytes = bytes;
cachedPdfToken = token;
}
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);
@@ -224,7 +249,7 @@ const loadPage = async () => {
const blobUrl = await fetchPageImage(previewPath, grant);
if (generation !== loadGeneration) return;
imageUrl.value = blobUrl;
} catch {
} catch (error) {
if (generation !== loadGeneration) return;
const fallback = props.grant ? pageImageCache.get(String(props.grant.page_no)) : null;
if (fallback) {
@@ -234,7 +259,10 @@ const loadPage = async () => {
}
imageUrl.value = '';
internalLoadError.value = t('admin.shippingOrderProfiles.workbench.canvasUnavailable');
emit('loadFailed');
// 仅令牌 HTTP 失效才通知父级重签;画布未挂载/PDF.js 渲染失败重签只会烧掉单次 token。
if (isPreviewTokenHttpError(error) || (props.grant && error instanceof Error && /^HTTP \d+/.test(error.message))) {
emit('loadFailed');
}
} finally {
if (generation === loadGeneration) loading.value = false;
}
@@ -442,10 +470,20 @@ defineExpose({
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);
if (!(props.pdfPreview && pdfDocument)) return;
try {
await renderPdfPage(pdfDocument);
} catch {
/* 翻页时画布可能短暂卸载;下一次 load/retry 会恢复 */
}
});
watch(zoom, async () => {
if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument);
if (!(props.pdfPreview && pdfDocument)) return;
try {
await renderPdfPage(pdfDocument);
} catch {
/* 缩放同翻页:避免未捕获 Promise 干扰控制台 */
}
});
onBeforeUnmount(() => {
endMove();
@@ -494,7 +532,8 @@ onBeforeUnmount(() => {
</div>
</header>
<div v-if="loading && !pdfPreview" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}</div>
<div v-else-if="displayLoadError" class="canvas-state canvas-state--error" role="alert">
<!-- PNG 路径仍可用整页错误态;原 PDF 路径必须保留 canvas 挂载,否则 renderPdfPage 必抛 canvas unavailable。 -->
<div v-else-if="displayLoadError && !pdfPreview" class="canvas-state canvas-state--error" role="alert">
<p>{{ displayLoadError }}</p>
<button type="button" class="canvas-retry" @click="onRetryClick">
{{ t('admin.shippingOrderProfiles.workbench.retryCanvas') }}
@@ -592,6 +631,12 @@ onBeforeUnmount(() => {
/>
</div>
</div>
<div v-if="displayLoadError && pdfPreview" class="canvas-error-overlay" role="alert">
<p>{{ displayLoadError }}</p>
<button type="button" class="canvas-retry" @click="onRetryClick">
{{ t('admin.shippingOrderProfiles.workbench.retryCanvas') }}
</button>
</div>
</div>
</section>
</template>
@@ -635,7 +680,20 @@ onBeforeUnmount(() => {
cursor: pointer;
}
.canvas-retry:hover { border-color: #60a5fa; background: #26364f; }
.canvas-work-area { display: flex; min-height: 0; flex: 1; gap: .6rem; }
.canvas-work-area { position: relative; display: flex; min-height: 0; flex: 1; gap: .6rem; }
.canvas-error-overlay {
position: absolute;
inset: 0;
z-index: 8;
display: grid;
place-content: center;
gap: .75rem;
background: rgb(15 23 42 / .82);
color: #fecaca;
font-size: .875rem;
text-align: center;
padding: 1rem;
}
.canvas-work-area.readonly { gap: 0; }
.canvas-viewport { position: relative; min-width: 0; flex: 1; overflow: auto; }
.canvas-viewport.panning { cursor: grab; }
@@ -10,7 +10,9 @@ import { useI18n } from 'vue-i18n';
import {
BookOpen,
CheckCircle2,
ChevronDown,
ChevronRight,
ChevronUp,
ClipboardCheck,
Edit,
FileQuestion,
@@ -105,6 +107,19 @@ const directVideoResources = computed(() => contentResources.value.filter((resou
resource.resource_type === 'agent_guide'
&& videoGuideCandidates.value.some((guide) => guide.id === resource.agent_guide_id)
)));
// 培训视频上传列表默认收起:超过阈值仅展示前 N 条,底部按钮可展开查看全部,避免视频过多时页面过长
const DIRECT_VIDEO_PREVIEW_COUNT = 3;
const isDirectVideoExpanded = ref(false);
const hasMoreDirectVideos = computed(() => directVideoResources.value.length > DIRECT_VIDEO_PREVIEW_COUNT);
const directVideoVisibleResources = computed(() => (
hasMoreDirectVideos.value && !isDirectVideoExpanded.value
? directVideoResources.value.slice(0, DIRECT_VIDEO_PREVIEW_COUNT)
: directVideoResources.value
));
/** 切换培训视频上传列表展开/收起:收起仅保留前 N 条,其余视频仍在表单资源中参与保存。 */
const toggleDirectVideoExpanded = () => {
isDirectVideoExpanded.value = !isDirectVideoExpanded.value;
};
const contentResources = computed(() => form.value.resources.filter((resource) => resource.resource_type !== 'inline_questions'));
const trainingLevels: TrainingLevel[] = ['company', 'department', 'team'];
const guideGroups = computed(() => {
@@ -263,6 +278,18 @@ const pushLeanTaskNow = async () => {
if (!leanTask.value || isPushingLeanTask.value) return;
isPushingLeanTask.value = true;
try {
// [STEP] 表单与已保存任务不一致(如刚勾选新视频未发布)时自动先保存再补推:
// 补推只作用于服务端冻结清单,不先保存会按旧清单推送而误报“全部视频已推送完毕”
if (isLeanTaskFormDirty()) {
try {
await persistLeanTask();
msg.success(t('admin.trainingConfig.lean.autoSavedBeforePush'));
} catch (error) {
// 自动保存失败(含周次校验拦截)时终止补推,具体原因已提示
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.saveFailed'));
return;
}
}
const log = await pushAdminLeanTrainingWeeklyTask(leanTask.value.id);
if (log.status === 'completed') {
msg.warning(t('admin.trainingConfig.lean.pushCompleted'));
@@ -318,27 +345,53 @@ const toggleLeanVideo = (resourceId: number) => {
: [...leanVideoResourceIds.value, resourceId];
};
const saveLeanTask = async () => {
/**
* 判断精益周任务表单是否与已保存任务不一致(勾选/周次/截止/对象/每周数量任一变更即视为脏)。
* AI 触发时机:点击【立即新增任务补推】时必须先感知未保存变更并自动保存——补推只作用于服务端冻结清单,
* 不自动保存会按旧清单推送而误报“全部视频已推送完毕”。
*/
const isLeanTaskFormDirty = (): boolean => {
const task = leanTask.value;
if (!task) return false;
if (JSON.stringify(leanVideoResourceIds.value) !== JSON.stringify(task.video_resource_ids || [])) return true;
if (leanWeekKey.value !== (task.week_key || '')) return true;
if (Number(leanWeeklyCount.value) !== Number(task.weekly_count || 1)) return true;
const savedDueAtMs = Date.parse(task.due_at || '');
if (!Number.isNaN(savedDueAtMs) && Math.abs(Date.parse(leanDueAt.value) - savedDueAtMs) > 1000) return true;
const normalizeTargets = (values: Array<string | number> | undefined) => JSON.stringify([...(values || [])].map(String).sort());
if (normalizeTargets(leanTargetRoles.value) !== normalizeTargets(task.target_roles)) return true;
if (normalizeTargets(leanTargetUserIds.value) !== normalizeTargets(task.target_user_ids)) return true;
return false;
};
/**
* 保存精益周任务表单到服务端(【发布周任务】与【补推前自动保存】共用同一持久化入口)。
* 校验失败或接口失败时抛出异常,由调用方决定提示方式与是否继续后续动作。
*/
const persistLeanTask = async () => {
// 任务周必须为周一:date input 允许选任意日期,前端先行拦截,后端同规则兜底校验
if (!leanWeekKey.value || new Date(`${leanWeekKey.value}T00:00:00`).getDay() !== 1) {
msg.warning(t('admin.trainingConfig.lean.weekMustBeMonday'));
return;
throw new Error(t('admin.trainingConfig.lean.weekMustBeMonday'));
}
leanTask.value = await createOrUpdateAdminLeanTrainingWeeklyTask({
// 任务周/截止时间支持修改:按表单所选周创建或更新,发布/补推均作用于所选周任务(周任务规则 7)
week_key: leanWeekKey.value,
due_at: new Date(leanDueAt.value).toISOString(),
// 未勾选任何视频时传空数组,服务端自动按上传时间倒序冻结全部视频(周任务规则 6)
video_resource_ids: leanVideoResourceIds.value,
target_roles: leanTargetRoles.value,
target_user_ids: leanTargetUserIds.value,
weekly_count: leanWeeklyCount.value,
});
// 保存后回填勾选状态(空选择时服务端可能已自动填充全部视频)
leanVideoResourceIds.value = leanTask.value?.video_resource_ids ? [...leanTask.value.video_resource_ids] : [];
await loadLeanPushLogs();
};
const saveLeanTask = async () => {
isSavingLeanTask.value = true;
try {
leanTask.value = await createOrUpdateAdminLeanTrainingWeeklyTask({
// 任务周/截止时间支持修改:按表单所选周创建或更新,发布/补推均作用于所选周任务(周任务规则 7)
week_key: leanWeekKey.value,
due_at: new Date(leanDueAt.value).toISOString(),
// 未勾选任何视频时传空数组,服务端自动按上传时间倒序冻结全部视频(周任务规则 6)
video_resource_ids: leanVideoResourceIds.value,
target_roles: leanTargetRoles.value,
target_user_ids: leanTargetUserIds.value,
weekly_count: leanWeeklyCount.value,
});
// 保存后回填勾选状态(空选择时服务端可能已自动填充全部视频)
leanVideoResourceIds.value = leanTask.value?.video_resource_ids ? [...leanTask.value.video_resource_ids] : [];
await loadLeanPushLogs();
await persistLeanTask();
msg.success(t('admin.trainingConfig.messages.leanTaskSaved'));
} catch (error) {
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.saveFailed'));
@@ -414,6 +467,8 @@ const selectConfig = (config: TrainingConfig) => {
questionJsonText.value = JSON.stringify(questions, null, 2);
questionSourceVersionId.value = null;
questionParseMeta.value = null;
// 切换培训类型时培训视频上传列表恢复默认收起,避免上一配置的展开状态带入
isDirectVideoExpanded.value = false;
void loadLeanTask();
};
@@ -702,6 +757,8 @@ const uploadTrainingVideo = async (event: Event) => {
required_duration: 0,
sort_order: form.value.resources.length,
});
// 新上传的视频排在列表末尾,自动展开避免用户以为上传失败找不到新视频
isDirectVideoExpanded.value = true;
msg.success(t('admin.trainingConfig.messages.videoUploaded'));
} catch (error) {
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.videoUploadFailed'));
@@ -907,11 +964,19 @@ onMounted(() => void load());
</div>
<div class="space-y-3 p-4 md:p-5">
<div v-if="!directVideoResources.length" class="rounded-xl border border-dashed border-default bg-surface-soft/50 px-3 py-8 text-center text-xs text-muted">{{ t('admin.trainingConfig.directVideo.empty') }}</div>
<div v-for="(resource, index) in directVideoResources" v-else :key="resource.id || `direct-video-${index}`" class="grid gap-3 rounded-xl border border-default bg-white p-4 md:grid-cols-[minmax(0,1fr)_180px_auto] md:items-end">
<div class="flex min-w-0 items-center gap-2 text-sm font-medium text-primary"><Video class="h-4 w-4 shrink-0 text-violet-500" /><span class="truncate">{{ resource.title || videoGuideCandidates.find((guide) => guide.id === resource.agent_guide_id)?.file_name || t('admin.trainingConfig.directVideo.unnamed') }}</span></div>
<label class="label-field">{{ t('admin.trainingConfig.fields.requiredDuration') }}<input v-model.number="resource.required_duration" type="number" min="0" class="input-field mt-2" /></label>
<button class="btn-danger btn-sm" type="button" @click="removeResource(resource)"><Trash2 class="h-4 w-4" />{{ t('admin.delete') }}</button>
</div>
<!-- 培训视频上传列表默认收起:超过阈值仅展示前 N 条,底部可展开查看全部 -->
<template v-else>
<div v-for="(resource, index) in directVideoVisibleResources" :key="resource.id || `direct-video-${index}`" class="grid gap-3 rounded-xl border border-default bg-white p-4 md:grid-cols-[minmax(0,1fr)_180px_auto] md:items-end">
<div class="flex min-w-0 items-center gap-2 text-sm font-medium text-primary"><Video class="h-4 w-4 shrink-0 text-violet-500" /><span class="truncate">{{ resource.title || videoGuideCandidates.find((guide) => guide.id === resource.agent_guide_id)?.file_name || t('admin.trainingConfig.directVideo.unnamed') }}</span></div>
<label class="label-field">{{ t('admin.trainingConfig.fields.requiredDuration') }}<input v-model.number="resource.required_duration" type="number" min="0" class="input-field mt-2" /></label>
<button class="btn-danger btn-sm" type="button" @click="removeResource(resource)"><Trash2 class="h-4 w-4" />{{ t('admin.delete') }}</button>
</div>
<button v-if="hasMoreDirectVideos" class="flex w-full items-center justify-center gap-1.5 rounded-xl border border-dashed border-default bg-surface-soft/50 px-3 py-2.5 text-xs font-medium text-secondary transition hover:bg-surface-soft" type="button" @click="toggleDirectVideoExpanded">
<ChevronDown v-if="!isDirectVideoExpanded" class="h-4 w-4" />
<ChevronUp v-else class="h-4 w-4" />
{{ isDirectVideoExpanded ? t('admin.trainingConfig.directVideo.collapseList') : t('admin.trainingConfig.directVideo.expandAll', { count: directVideoResources.length }) }}
</button>
</template>
</div>
</article>
<article
@@ -218,19 +218,13 @@ onMounted(() => {
>
{{ t('admin.role.' + user.role) }}
</span>
<div v-if="user.feature_permissions?.training_hr_manage || user.feature_permissions?.['contract_payment.access']" class="mt-2 flex flex-wrap gap-1.5">
<div v-if="user.feature_permissions?.training_hr_manage" class="mt-2 flex flex-wrap gap-1.5">
<span
v-if="user.feature_permissions?.training_hr_manage"
class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700"
>
{{ t('admin.user.fields.trainingHrManage') }}
</span>
<span
v-if="user.feature_permissions?.['contract_payment.access']"
class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700"
>
{{ t('admin.user.fields.contractPaymentAccess') }}
</span>
</div>
</td>
<td class="px-6 py-4 text-right">
@@ -1,6 +1,6 @@
/**
* features/admin/modules/users/components/UserFormModal.vue
* 创建/编辑用户弹窗,含角色与功能权限勾选(培训 HR、合同付款预警访问)。
* 创建/编辑用户弹窗,含角色与培训 HR 功能权限勾选。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
@@ -105,17 +105,6 @@ const { t } = useI18n();
<span class="block text-xs leading-5 text-muted">{{ t('admin.user.fields.trainingHrManageHint') }}</span>
</span>
</label>
<label class="flex items-start gap-3 rounded-xl border border-default bg-white px-4 py-3">
<input
v-model="form.feature_permissions['contract_payment.access']"
type="checkbox"
class="mt-0.5 h-4 w-4 rounded border-default text-brand-600 focus:ring-brand-500"
/>
<span class="space-y-1">
<span class="block text-sm font-medium text-primary">{{ t('admin.user.fields.contractPaymentAccess') }}</span>
<span class="block text-xs leading-5 text-muted">{{ t('admin.user.fields.contractPaymentAccessHint') }}</span>
</span>
</label>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
@@ -205,7 +205,6 @@ export function useUsersAdmin() {
phone_number: user.phone_number || '',
feature_permissions: {
training_hr_manage: Boolean(user.feature_permissions?.training_hr_manage),
'contract_payment.access': Boolean(user.feature_permissions?.['contract_payment.access']),
},
agent_ids: user.agent_ids || [],
};
@@ -15,7 +15,6 @@ export interface UserFormState {
phone_number: string;
feature_permissions: {
training_hr_manage: boolean;
'contract_payment.access': boolean;
};
agent_ids: number[];
}
@@ -54,7 +53,6 @@ export const createEmptyUserForm = (): UserFormState => ({
phone_number: '',
feature_permissions: {
training_hr_manage: false,
'contract_payment.access': false,
},
agent_ids: [],
});