Merge branch 'dev' into runny827
feat(training): 新增精益培训视频与周任务管理 # Conflicts: # backend/app/models/__init__.py
This commit is contained in:
1 parent
85d27e9ffa
commit
91b7233872
812 files changed
+73763
-18908
No files matched your search
@@ -8,10 +8,6 @@
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type {
|
||||
ShippingOrderDerivationRule,
|
||||
ShippingOrderDerivationSimulateRequest,
|
||||
ShippingOrderDerivationSimulateResult,
|
||||
ShippingOrderDerivationSimulateSampleItem,
|
||||
ShippingOrderField,
|
||||
ShippingOrderFieldConfig,
|
||||
ShippingOrderSchemaAuditEventPage,
|
||||
@@ -158,13 +154,12 @@ export const getShippingOrderExtractionAudit = (extractionId: number) =>
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 整体保存草稿字段配置、自动建单策略、派生规则及每个字段的版本纳入状态。 */
|
||||
/** 整体保存草稿字段配置、自动建单策略及每个字段的版本纳入状态。 */
|
||||
export const saveShippingOrderSchemaDraft = (
|
||||
versionId: number,
|
||||
payload: {
|
||||
fields: ShippingOrderFieldConfig[];
|
||||
auto_creation_policy?: { enabled: boolean };
|
||||
derivation_rules?: ShippingOrderDerivationRule[];
|
||||
change_note?: string;
|
||||
expected_lock_version: number;
|
||||
},
|
||||
@@ -177,34 +172,6 @@ export const saveShippingOrderSchemaDraft = (
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 对 Schema 版本派生规则做样本模拟(不改订单)。
|
||||
* @param versionId - Schema 版本 ID
|
||||
* @param payload - 样本行与可选规则覆盖 / sample_ref
|
||||
*/
|
||||
export const simulateShippingOrderSchemaDerivation = (
|
||||
versionId: number,
|
||||
payload: ShippingOrderDerivationSimulateRequest,
|
||||
) =>
|
||||
requestJson<ShippingOrderDerivationSimulateResult>(
|
||||
`/api/admin/shipping-order-schema/versions/${versionId}/simulate-derivation`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
...jsonAuth(),
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 列出可供派生规则模拟的历史 Extraction 样本。
|
||||
* @param limit - 返回条数上限
|
||||
*/
|
||||
export const listShippingOrderSchemaDerivationSimulateSamples = (limit = 20) =>
|
||||
requestJson<{ items: ShippingOrderDerivationSimulateSampleItem[] }>(
|
||||
`/api/admin/shipping-order-schema/derivation-simulate-samples?limit=${limit}`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 删除错误草稿;发布版本由服务端拒绝删除。 */
|
||||
export const deleteShippingOrderSchemaDraft = (versionId: number) =>
|
||||
requestJson<void>(`/api/admin/shipping-order-schema/versions/${versionId}`, {
|
||||
|
||||
@@ -11,7 +11,7 @@ import { useRoute, useRouter } from 'vue-router';
|
||||
import {
|
||||
LayoutDashboard, UserPlus, UserCog, Building, Bot, FileText,
|
||||
Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2, AppWindow,
|
||||
ScrollText, ExternalLink, PackageSearch, GraduationCap,
|
||||
ScrollText, ExternalLink, PackageSearch, GraduationCap, Cable,
|
||||
} from 'lucide-vue-next';
|
||||
import type { Component } from 'vue';
|
||||
import { config } from '@/config';
|
||||
@@ -44,6 +44,7 @@ const iconMap: Record<AdminModuleId, Component> = {
|
||||
platform_apps: AppWindow,
|
||||
procurement_contract: ScrollText,
|
||||
training_config: GraduationCap,
|
||||
integration_connector: Cable,
|
||||
requests: ShieldCheck,
|
||||
reports: BarChart2,
|
||||
shipping_inventory: PackageSearch,
|
||||
@@ -129,6 +130,8 @@ watch(
|
||||
isShippingActive,
|
||||
(active) => {
|
||||
if (!active) return;
|
||||
// 进入任一货代子路由时自动展开父菜单,保证当前子页可见。
|
||||
navStore.shippingMenuExpanded = true;
|
||||
let matched = false;
|
||||
for (const groupKey of shippingGroups.value) {
|
||||
const groupHasActiveSub = SHIPPING_CONFIG_SUB_MODULE_METAS.some(
|
||||
@@ -210,14 +213,14 @@ watch(
|
||||
type="button"
|
||||
class="admin-nav-btn group justify-between"
|
||||
:class="{ 'admin-nav-btn--active': isShippingActive }"
|
||||
@click="navigateModule('AdminShippingInventory')"
|
||||
@click="navStore.shippingMenuExpanded = !navStore.shippingMenuExpanded"
|
||||
>
|
||||
<div class="flex items-center gap-3">
|
||||
<PackageSearch class="w-5 h-5 flex-shrink-0" :class="isShippingActive ? 'text-brand-600' : 'text-muted'" />
|
||||
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t('admin.nav.shippingConfig') }}</span>
|
||||
</div>
|
||||
</button>
|
||||
<div v-if="isShippingActive && !navStore.sidebarCollapsed" class="pl-4 space-y-1 mt-1 border-l-2 border-subtle ml-6">
|
||||
<div v-if="navStore.shippingMenuExpanded && !navStore.sidebarCollapsed" class="pl-4 space-y-1 mt-1 border-l-2 border-subtle ml-6">
|
||||
<div v-for="groupKey in shippingGroups" :key="groupKey" class="flex flex-col">
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -40,7 +40,7 @@ export interface ShippingConfigSubModuleMeta {
|
||||
|
||||
/** 已独立拆分的模块(全部 admin 模块均已拆分) */
|
||||
export const STANDALONE_ADMIN_MODULES = new Set<AdminModuleId>([
|
||||
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'linked_services', 'platform_apps', 'shipping_inventory', 'procurement_contract', 'reports','training_config'
|
||||
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'linked_services', 'platform_apps', 'shipping_inventory', 'procurement_contract', 'reports','training_config', 'integration_connector'
|
||||
]);
|
||||
|
||||
export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
|
||||
@@ -60,6 +60,7 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
|
||||
{ id: 'platform_apps', routeName: 'AdminPlatformApps', path: 'platform-apps', labelKey: 'admin.nav.platformApps', configKey: 'platform_apps' },
|
||||
{ id: 'procurement_contract', routeName: 'AdminProcurementContract', path: 'procurement-contract', labelKey: 'admin.nav.procurementContract', configKey: 'procurement_contract' },
|
||||
{ id: 'training_config', routeName: 'AdminTrainingConfig', path: 'training-config', labelKey: 'admin.nav.trainingConfig', configKey: 'training_config' },
|
||||
{ id: 'integration_connector', routeName: 'AdminIntegrationConnector', path: 'integration-connector', labelKey: 'admin.nav.integrationConnector', configKey: 'integration_connector' },
|
||||
{ id: 'requests', routeName: 'AdminRequests', path: 'requests', labelKey: 'admin.nav.requests', configKey: 'requests' },
|
||||
];
|
||||
|
||||
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
<!--
|
||||
features/admin/modules/integration-connector/IntegrationConnectorPage.vue
|
||||
用途:集成连接器管理页——四个配置实体(客户端实例/接口定义/绑定/凭据引用)tab 列表 +
|
||||
能力清单与手动调用测试;创建/编辑弹窗 + 连接测试。
|
||||
依赖:useIntegrationConnectorAdmin、两个弹窗组件、useI18n。
|
||||
逻辑:按 tab 展示列表与「新增」;配置「绑定」是让自动调拨跑起来的最小闭环核心。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Plus, Edit, Trash2, Plug, PlayCircle } from 'lucide-vue-next';
|
||||
import IntegrationConnectorFormModal from './components/IntegrationConnectorFormModal.vue';
|
||||
import IntegrationCapabilityCallModal from './components/IntegrationCapabilityCallModal.vue';
|
||||
import { useIntegrationConnectorAdmin } from './composables/useIntegrationConnectorAdmin';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const {
|
||||
clients, interfaces, bindings, credentials, capabilities,
|
||||
isLoading, activeEntity, showFormModal, isSaving,
|
||||
clientForm, interfaceForm, bindingForm, credentialForm,
|
||||
showCallModal, callCapability, callParamsText, callContextText, callResult, callBusy,
|
||||
testResultText,
|
||||
loadAll, openCreateModal, openEditModal, closeFormModal, saveActive,
|
||||
testConnection, openCallModal, closeCallModal, runCall, deleteClient,
|
||||
} = useIntegrationConnectorAdmin();
|
||||
|
||||
onMounted(() => { void loadAll(); });
|
||||
|
||||
type TabKey = 'client' | 'interface' | 'binding' | 'credential' | 'capability';
|
||||
const tabs: Array<{ key: TabKey; labelKey: string }> = [
|
||||
{ key: 'client', labelKey: 'admin.integrationConnector.tabs.client' },
|
||||
{ key: 'interface', labelKey: 'admin.integrationConnector.tabs.interface' },
|
||||
{ key: 'binding', labelKey: 'admin.integrationConnector.tabs.binding' },
|
||||
{ key: 'credential', labelKey: 'admin.integrationConnector.tabs.credential' },
|
||||
{ key: 'capability', labelKey: 'admin.integrationConnector.tabs.capability' },
|
||||
];
|
||||
const activeTab = computed<TabKey>(() => (activeEntity.value === 'credential' ? 'credential' : activeEntity.value));
|
||||
|
||||
const clientOptions = computed(() => clients.value.map((c) => ({ code: c.code, name: c.name })));
|
||||
const interfaceOptions = computed(() => interfaces.value.map((i) => ({ code: i.code, name: i.name })));
|
||||
const capabilityOptions = computed(() => capabilities.value.map((c) => ({ name: c.name })));
|
||||
|
||||
function selectTab(key: TabKey) {
|
||||
// capability tab 只读展示,不进入表单实体;其余映射到可编辑实体。
|
||||
if (key === 'capability') return;
|
||||
activeEntity.value = key;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="admin-table-section animate-fade-in-up">
|
||||
<div class="admin-table-header admin-table-header--stacked">
|
||||
<div>
|
||||
<h2 class="section-title">{{ t('admin.integrationConnector.title') }}</h2>
|
||||
<p class="section-desc mt-1">{{ t('admin.integrationConnector.subtitle') }}</p>
|
||||
</div>
|
||||
<button
|
||||
v-if="activeTab !== 'capability'"
|
||||
type="button"
|
||||
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
|
||||
@click="openCreateModal(activeEntity)"
|
||||
>
|
||||
<Plus class="w-4 h-4" />
|
||||
<span>{{ t('admin.integrationConnector.add') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-1 border-b border-default" role="tablist">
|
||||
<button
|
||||
v-for="tab in tabs"
|
||||
:key="tab.key"
|
||||
type="button"
|
||||
role="tab"
|
||||
class="px-4 py-2.5 text-sm font-medium border-b-2 -mb-px transition-colors"
|
||||
:class="activeTab === tab.key ? 'border-brand-600 text-brand-600' : 'border-transparent text-muted hover:text-secondary'"
|
||||
:aria-selected="activeTab === tab.key"
|
||||
@click="selectTab(tab.key)"
|
||||
>
|
||||
{{ t(tab.labelKey) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="isLoading" class="flex items-center justify-center py-20">
|
||||
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<!-- 客户端实例 -->
|
||||
<div v-if="activeTab === 'client'" class="admin-table-wrap">
|
||||
<table class="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.code') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.name') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.connectorType') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.environment') }}</th>
|
||||
<th class="px-6 py-4 text-right text-xs w-40">{{ t('admin.integrationConnector.headers.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="clients.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
|
||||
<tr v-for="row in clients" :key="row.code">
|
||||
<td class="px-6 py-4 text-sm font-medium text-primary mono">{{ row.code }}</td>
|
||||
<td class="px-6 py-4 text-sm text-secondary">{{ row.name }}</td>
|
||||
<td class="px-6 py-4 text-sm text-secondary">{{ row.connector_type }}</td>
|
||||
<td class="px-6 py-4 text-sm text-secondary">{{ row.environment }}</td>
|
||||
<td class="px-6 py-4 text-right">
|
||||
<div class="inline-flex items-center gap-1">
|
||||
<button type="button" class="p-2 rounded-lg text-muted hover:bg-brand-50 hover:text-brand-600" :title="t('admin.integrationConnector.test')" @click="testConnection(row.code)">
|
||||
<Plug class="w-4 h-4" />
|
||||
</button>
|
||||
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('client', row)">
|
||||
<Edit class="w-4 h-4" />
|
||||
</button>
|
||||
<button type="button" class="p-2 rounded-lg text-muted hover:bg-red-50 hover:text-red-600" :title="t('admin.delete')" @click="deleteClient(row.code)">
|
||||
<Trash2 class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p v-if="testResultText" class="mt-3 rounded-lg bg-surface-soft p-3 text-xs font-mono text-secondary whitespace-pre-wrap break-all">{{ testResultText }}</p>
|
||||
</div>
|
||||
|
||||
<!-- 接口定义 -->
|
||||
<div v-else-if="activeTab === 'interface'" class="admin-table-wrap">
|
||||
<table class="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.code') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.name') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.clientInstance') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.status') }}</th>
|
||||
<th class="px-6 py-4 text-right text-xs w-24">{{ t('admin.integrationConnector.headers.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="interfaces.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
|
||||
<tr v-for="row in interfaces" :key="row.code">
|
||||
<td class="px-6 py-4 text-sm font-medium text-primary mono">{{ row.code }}</td>
|
||||
<td class="px-6 py-4 text-sm text-secondary">{{ row.name }}</td>
|
||||
<td class="px-6 py-4 text-sm text-secondary">{{ row.client_instance_code }}</td>
|
||||
<td class="px-6 py-4 text-sm text-secondary">{{ row.status }}</td>
|
||||
<td class="px-6 py-4 text-right">
|
||||
<div class="inline-flex items-center gap-1">
|
||||
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('interface', row)">
|
||||
<Edit class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- 绑定 -->
|
||||
<div v-else-if="activeTab === 'binding'" class="admin-table-wrap">
|
||||
<table class="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.capability') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.clientInstance') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.interfaceDef') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.status') }}</th>
|
||||
<th class="px-6 py-4 text-right text-xs w-24">{{ t('admin.integrationConnector.headers.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="bindings.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
|
||||
<tr v-for="row in bindings" :key="row.id">
|
||||
<td class="px-6 py-4 text-sm font-medium text-primary">{{ row.capability }}</td>
|
||||
<td class="px-6 py-4 text-sm text-secondary">{{ row.client_instance_code }}</td>
|
||||
<td class="px-6 py-4 text-sm text-secondary">{{ row.interface_definition_code }}</td>
|
||||
<td class="px-6 py-4 text-sm text-secondary">{{ row.status }}</td>
|
||||
<td class="px-6 py-4 text-right">
|
||||
<div class="inline-flex items-center gap-1">
|
||||
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('binding', row)">
|
||||
<Edit class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- 凭据引用 -->
|
||||
<div v-else-if="activeTab === 'credential'" class="admin-table-wrap">
|
||||
<table class="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.code') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.secretRef') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.secretProvider') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.status') }}</th>
|
||||
<th class="px-6 py-4 text-right text-xs w-24">{{ t('admin.integrationConnector.headers.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="credentials.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
|
||||
<tr v-for="row in credentials" :key="row.code">
|
||||
<td class="px-6 py-4 text-sm font-medium text-primary mono">{{ row.code }}</td>
|
||||
<td class="px-6 py-4 text-sm text-secondary mono">{{ row.secret_ref }}</td>
|
||||
<td class="px-6 py-4 text-sm text-secondary">{{ row.secret_provider }}</td>
|
||||
<td class="px-6 py-4 text-sm text-secondary">{{ row.status }}</td>
|
||||
<td class="px-6 py-4 text-right">
|
||||
<div class="inline-flex items-center gap-1">
|
||||
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('credential', row)">
|
||||
<Edit class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- 能力清单 -->
|
||||
<div v-else class="admin-table-wrap">
|
||||
<table class="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.name') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.write') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.idempotency') }}</th>
|
||||
<th class="px-6 py-4 text-right text-xs w-28">{{ t('admin.integrationConnector.headers.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="capabilities.length === 0"><td colspan="4" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
|
||||
<tr v-for="row in capabilities" :key="row.name">
|
||||
<td class="px-6 py-4 text-sm font-medium text-primary">{{ row.name }}</td>
|
||||
<td class="px-6 py-4 text-sm text-secondary">{{ row.write ? 'yes' : 'no' }}</td>
|
||||
<td class="px-6 py-4 text-sm text-secondary">{{ row.idempotency }}</td>
|
||||
<td class="px-6 py-4 text-right">
|
||||
<button type="button" class="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm font-medium text-brand-600 hover:bg-brand-50" @click="openCallModal(row.name)">
|
||||
<PlayCircle class="w-4 h-4" />
|
||||
{{ t('admin.integrationConnector.call') }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<IntegrationConnectorFormModal
|
||||
:visible="showFormModal"
|
||||
:active-entity="activeEntity"
|
||||
:client-form="clientForm"
|
||||
:interface-form="interfaceForm"
|
||||
:binding-form="bindingForm"
|
||||
:credential-form="credentialForm"
|
||||
:is-saving="isSaving"
|
||||
:client-options="clientOptions"
|
||||
:interface-options="interfaceOptions"
|
||||
:capability-options="capabilityOptions"
|
||||
@close="closeFormModal"
|
||||
@save="saveActive"
|
||||
/>
|
||||
|
||||
<IntegrationCapabilityCallModal
|
||||
:visible="showCallModal"
|
||||
:capability="callCapability"
|
||||
:params-text="callParamsText"
|
||||
:context-text="callContextText"
|
||||
:result="callResult"
|
||||
:busy="callBusy"
|
||||
@close="closeCallModal"
|
||||
@run="runCall"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* features/admin/modules/integration-connector/api/integration-connector.api.ts
|
||||
* 集成连接器管理 API 客户端:客户端实例/接口定义/绑定/凭据引用 CRUD + 能力清单 + 连接测试。
|
||||
* 依赖:@/shared/api/client(requestJson / BusinessError)、@/shared/utils/auth。
|
||||
* 逻辑:薄封装后端 /api/integration-connector/* 全部端点;JSON 写请求带 Content-Type。
|
||||
* 错误码(INTEGRATION.*)由 requestJson 解析到四语言文案。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type {
|
||||
IntegrationBindingRow,
|
||||
IntegrationCallResultRow,
|
||||
IntegrationCapabilityRow,
|
||||
IntegrationClientInstanceRow,
|
||||
IntegrationCredentialReferenceRow,
|
||||
IntegrationInterfaceDefinitionRow,
|
||||
} from '../types/integration-connector.types';
|
||||
|
||||
const BASE = '/api/integration-connector';
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
|
||||
// ---- 能力清单与调用 ----
|
||||
|
||||
/** 能力清单(写/幂等/入出参 Schema)。 */
|
||||
export const listIntegrationCapabilities = () =>
|
||||
requestJson<IntegrationCapabilityRow[]>(`${BASE}/capabilities`, auth());
|
||||
|
||||
/** 手动调用一个已注册能力(入参 + 路由上下文)。 */
|
||||
export const callIntegrationCapability = (capability: string, payload: { params?: Record<string, unknown>; context?: Record<string, unknown>; operation_id?: string; idempotency_key?: string }) =>
|
||||
requestJson<IntegrationCallResultRow>(`${BASE}/capabilities/${encodeURIComponent(capability)}`, {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
// ---- 客户端实例 ----
|
||||
|
||||
export const listIntegrationClientInstances = () =>
|
||||
requestJson<IntegrationClientInstanceRow[]>(`${BASE}/client-instances`, auth());
|
||||
|
||||
export const createIntegrationClientInstance = (payload: Record<string, unknown>) =>
|
||||
requestJson<IntegrationClientInstanceRow>(`${BASE}/client-instances`, {
|
||||
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
export const updateIntegrationClientInstance = (code: string, payload: Record<string, unknown>) =>
|
||||
requestJson<IntegrationClientInstanceRow>(`${BASE}/client-instances/${encodeURIComponent(code)}`, {
|
||||
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
export const deleteIntegrationClientInstance = (code: string) =>
|
||||
requestJson(`${BASE}/client-instances/${encodeURIComponent(code)}`, { method: 'DELETE', ...auth() });
|
||||
|
||||
/** 连接测试(返回底层传输 raw 结果)。 */
|
||||
export const testIntegrationClientConnection = (code: string) =>
|
||||
requestJson<Record<string, unknown>>(`${BASE}/client-instances/${encodeURIComponent(code)}/test`, {
|
||||
method: 'POST', ...jsonAuth(), body: JSON.stringify({}),
|
||||
});
|
||||
|
||||
// ---- 接口定义 ----
|
||||
|
||||
export const listIntegrationInterfaceDefinitions = () =>
|
||||
requestJson<IntegrationInterfaceDefinitionRow[]>(`${BASE}/interface-definitions`, auth());
|
||||
|
||||
export const createIntegrationInterfaceDefinition = (payload: Record<string, unknown>) =>
|
||||
requestJson<IntegrationInterfaceDefinitionRow>(`${BASE}/interface-definitions`, {
|
||||
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
export const updateIntegrationInterfaceDefinition = (code: string, payload: Record<string, unknown>) =>
|
||||
requestJson<IntegrationInterfaceDefinitionRow>(`${BASE}/interface-definitions/${encodeURIComponent(code)}`, {
|
||||
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
// ---- 绑定 ----
|
||||
|
||||
export const listIntegrationBindings = () =>
|
||||
requestJson<IntegrationBindingRow[]>(`${BASE}/bindings`, auth());
|
||||
|
||||
export const createIntegrationBinding = (payload: Record<string, unknown>) =>
|
||||
requestJson<IntegrationBindingRow>(`${BASE}/bindings`, {
|
||||
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
export const updateIntegrationBinding = (id: number, payload: Record<string, unknown>) =>
|
||||
requestJson<IntegrationBindingRow>(`${BASE}/bindings/${id}`, {
|
||||
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
// ---- 凭据引用 ----
|
||||
|
||||
export const listIntegrationCredentialReferences = () =>
|
||||
requestJson<IntegrationCredentialReferenceRow[]>(`${BASE}/credential-references`, auth());
|
||||
|
||||
export const createIntegrationCredentialReference = (payload: Record<string, unknown>) =>
|
||||
requestJson<IntegrationCredentialReferenceRow>(`${BASE}/credential-references`, {
|
||||
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
export const updateIntegrationCredentialReference = (code: string, payload: Record<string, unknown>) =>
|
||||
requestJson<IntegrationCredentialReferenceRow>(`${BASE}/credential-references/${encodeURIComponent(code)}`, {
|
||||
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
|
||||
});
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
<!--
|
||||
features/admin/modules/integration-connector/components/IntegrationCapabilityCallModal.vue
|
||||
用途:手动调用一个已注册能力(输入 params / context JSON),展示调用结果与 trace。
|
||||
依赖:showCallModal、callParamsText、callContextText、callResult、callBusy。
|
||||
逻辑:由 IntegrationConnectorPage 打开;emit close/run。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { IntegrationCallResultRow } from '../types/integration-connector.types';
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean;
|
||||
capability: string;
|
||||
paramsText: string;
|
||||
contextText: string;
|
||||
result: IntegrationCallResultRow | null;
|
||||
busy: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
run: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
|
||||
<div class="admin-modal-panel max-w-2xl max-h-[92vh] scale-100">
|
||||
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
|
||||
<h3 class="section-title">{{ t('admin.integrationConnector.callModal.title', { capability }) }}</h3>
|
||||
<p class="section-desc mt-1">{{ t('admin.integrationConnector.callModal.hint') }}</p>
|
||||
</div>
|
||||
<div class="px-5 sm:px-8 py-5 space-y-4 overflow-y-auto">
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.callModal.params') }}</label>
|
||||
<textarea :value="props.paramsText" rows="6" class="input-field text-sm font-mono" spellcheck="false" readonly />
|
||||
<p class="text-xs text-muted">{{ t('admin.integrationConnector.callModal.paramsHint') }}</p>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.callModal.context') }}</label>
|
||||
<textarea :value="props.contextText" rows="4" class="input-field text-sm font-mono" spellcheck="false" readonly />
|
||||
<p class="text-xs text-muted">{{ t('admin.integrationConnector.callModal.contextHint') }}</p>
|
||||
</div>
|
||||
<div v-if="result" class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.callModal.result') }}</label>
|
||||
<pre class="rounded-lg bg-surface-soft p-3 text-xs font-mono text-secondary whitespace-pre-wrap break-all">{{ JSON.stringify(result, null, 2) }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-modal-footer">
|
||||
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
|
||||
<button type="button" class="btn-primary disabled:opacity-70" :disabled="busy" @click="emit('run')">
|
||||
{{ busy ? t('admin.integrationConnector.callModal.running') : t('admin.integrationConnector.callModal.run') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* features/admin/modules/integration-connector/components/IntegrationConnectorFormModal.spec.ts
|
||||
* 用途:锁定表单按连接器类型动态显示字段——REST 显示超时/HTTP方法/请求路径,
|
||||
* SOAP 显示 WSDL;关键字段从 JSON 拆出独立输入框,JSON 收进高级配置折叠。
|
||||
* 依赖:@vue/test-utils、i18n。
|
||||
* 逻辑:切换 connector_type 后断言对应字段的可见性;高级配置折叠默认收起。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import i18n from '@/i18n';
|
||||
import IntegrationConnectorFormModal from './IntegrationConnectorFormModal.vue';
|
||||
import {
|
||||
createEmptyClientInstanceForm,
|
||||
createEmptyInterfaceDefinitionForm,
|
||||
createEmptyBindingForm,
|
||||
createEmptyCredentialReferenceForm,
|
||||
} from '../types/integration-connector.types';
|
||||
|
||||
function mountModal() {
|
||||
return mount(IntegrationConnectorFormModal, {
|
||||
props: {
|
||||
visible: true,
|
||||
activeEntity: 'client',
|
||||
clientForm: createEmptyClientInstanceForm(),
|
||||
interfaceForm: createEmptyInterfaceDefinitionForm(),
|
||||
bindingForm: createEmptyBindingForm(),
|
||||
credentialForm: createEmptyCredentialReferenceForm(),
|
||||
isSaving: false,
|
||||
clientOptions: [],
|
||||
interfaceOptions: [],
|
||||
capabilityOptions: [],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('IntegrationConnectorFormModal connector-type fields', () => {
|
||||
it('REST 默认显示接口地址与超时字段', () => {
|
||||
const wrapper = mountModal();
|
||||
expect(wrapper.find('[data-testid="client-endpoint"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="client-timeout"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('切换到 SOAP 后连接地址 label 变为 WSDL,超时仍显示;同一 endpoint 字段', async () => {
|
||||
const wrapper = mountModal();
|
||||
await wrapper.find('[data-testid="client-connector-type"]').setValue('soap');
|
||||
await wrapper.vm.$nextTick();
|
||||
// 连接地址仍是同一 client-endpoint 字段,仅 label 变 WSDL
|
||||
expect(wrapper.find('[data-testid="client-endpoint"]').exists()).toBe(true);
|
||||
// 超时在 SOAP 下也显示
|
||||
expect(wrapper.find('[data-testid="client-timeout"]').exists()).toBe(true);
|
||||
const labels = wrapper.findAll('label').map((l) => l.text());
|
||||
expect(labels.some((t) => t.includes('WSDL'))).toBe(true);
|
||||
});
|
||||
|
||||
it('接口定义 REST 显示 HTTP 方法与请求路径', () => {
|
||||
const wrapper = mount(IntegrationConnectorFormModal, {
|
||||
props: {
|
||||
visible: true,
|
||||
activeEntity: 'interface',
|
||||
clientForm: createEmptyClientInstanceForm(),
|
||||
interfaceForm: createEmptyInterfaceDefinitionForm(),
|
||||
bindingForm: createEmptyBindingForm(),
|
||||
credentialForm: createEmptyCredentialReferenceForm(),
|
||||
isSaving: false,
|
||||
clientOptions: [],
|
||||
interfaceOptions: [],
|
||||
capabilityOptions: [],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const labels = wrapper.findAll('label').map((l) => l.text());
|
||||
expect(labels.some((t) => t.includes('HTTP 方法'))).toBe(true);
|
||||
expect(labels.some((t) => t.includes('请求路径'))).toBe(true);
|
||||
});
|
||||
|
||||
it('绑定显示来源实例编码独立字段', () => {
|
||||
const wrapper = mount(IntegrationConnectorFormModal, {
|
||||
props: {
|
||||
visible: true,
|
||||
activeEntity: 'binding',
|
||||
clientForm: createEmptyClientInstanceForm(),
|
||||
interfaceForm: createEmptyInterfaceDefinitionForm(),
|
||||
bindingForm: createEmptyBindingForm(),
|
||||
credentialForm: createEmptyCredentialReferenceForm(),
|
||||
isSaving: false,
|
||||
clientOptions: [],
|
||||
interfaceOptions: [],
|
||||
capabilityOptions: [],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const labels = wrapper.findAll('label').map((l) => l.text());
|
||||
expect(labels.some((t) => t.includes('来源实例编码'))).toBe(true);
|
||||
});
|
||||
});
|
||||
+277
@@ -0,0 +1,277 @@
|
||||
<!--
|
||||
features/admin/modules/integration-connector/components/IntegrationConnectorFormModal.vue
|
||||
用途:集成连接器四实体(客户端实例/接口定义/绑定/凭据引用)创建与编辑弹窗。
|
||||
依赖:activeEntity 对应的表单 state、useI18n。
|
||||
逻辑:由 IntegrationConnectorPage 打开;按 activeEntity 渲染对应字段;提交 emit save。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type {
|
||||
BindingFormState,
|
||||
ClientInstanceFormState,
|
||||
CredentialReferenceFormState,
|
||||
InterfaceDefinitionFormState,
|
||||
} from '../types/integration-connector.types';
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean;
|
||||
activeEntity: 'client' | 'interface' | 'binding' | 'credential';
|
||||
clientForm: ClientInstanceFormState;
|
||||
interfaceForm: InterfaceDefinitionFormState;
|
||||
bindingForm: BindingFormState;
|
||||
credentialForm: CredentialReferenceFormState;
|
||||
isSaving: boolean;
|
||||
clientOptions: Array<{ code: string; name: string }>;
|
||||
interfaceOptions: Array<{ code: string; name: string }>;
|
||||
capabilityOptions: Array<{ name: string }>;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
save: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
|
||||
<div class="admin-modal-panel max-w-2xl max-h-[92vh] scale-100">
|
||||
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
|
||||
<h3 class="section-title">{{ t(`admin.integrationConnector.tabs.${activeEntity}`) }}</h3>
|
||||
<p class="section-desc mt-1">{{ t('admin.integrationConnector.formHint') }}</p>
|
||||
</div>
|
||||
<div class="px-5 sm:px-8 py-5 space-y-5 overflow-y-auto">
|
||||
<!-- 客户端实例 -->
|
||||
<template v-if="activeEntity === 'client'">
|
||||
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.code') }}</label>
|
||||
<input v-model="clientForm.code" type="text" class="input-field text-sm" :disabled="Boolean(clientForm.id)" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.name') }}</label>
|
||||
<input v-model="clientForm.name" type="text" class="input-field text-sm" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.connectorType') }}</label>
|
||||
<select v-model="clientForm.connector_type" class="input-field text-sm" data-testid="client-connector-type">
|
||||
<option value="rest">rest</option>
|
||||
<option value="soap">soap</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.environment') }}</label>
|
||||
<input v-model="clientForm.environment" type="text" class="input-field text-sm" />
|
||||
</div>
|
||||
</div>
|
||||
<!-- 连接地址:endpoint 合一字段;label 按连接器类型显示(REST=接口地址,SOAP=WSDL 地址) -->
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ clientForm.connector_type === 'soap' ? t('admin.integrationConnector.fields.wsdl') : t('admin.integrationConnector.fields.endpoint') }}</label>
|
||||
<input v-model="clientForm.endpoint" type="text" class="input-field text-sm" :placeholder="t(clientForm.connector_type === 'soap' ? 'admin.integrationConnector.placeholders.wsdl' : 'admin.integrationConnector.placeholders.endpoint')" data-testid="client-endpoint" />
|
||||
</div>
|
||||
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.timeout') }}</label>
|
||||
<input v-model="clientForm.timeout_seconds" type="number" class="input-field text-sm" min="0" data-testid="client-timeout" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.credentialRef') }}</label>
|
||||
<input v-model="clientForm.credential_ref_code" type="text" class="input-field text-sm" />
|
||||
</div>
|
||||
<details class="rounded-lg border border-slate-200 px-3 py-2">
|
||||
<summary class="cursor-pointer text-xs font-bold text-secondary">{{ t('admin.integrationConnector.advancedConfig') }}</summary>
|
||||
<div class="mt-2 space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.configJson') }}</label>
|
||||
<textarea v-model="clientForm.config_json" rows="6" class="input-field text-sm font-mono" spellcheck="false" />
|
||||
</div>
|
||||
</details>
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
|
||||
<input v-model="clientForm.enabled" type="checkbox" class="w-4 h-4 rounded text-brand-600 border-default" />
|
||||
{{ t('admin.integrationConnector.fields.enabled') }}
|
||||
</label>
|
||||
</template>
|
||||
|
||||
<!-- 接口定义 -->
|
||||
<template v-else-if="activeEntity === 'interface'">
|
||||
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.code') }}</label>
|
||||
<input v-model="interfaceForm.code" type="text" class="input-field text-sm" :disabled="Boolean(interfaceForm.id)" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.name') }}</label>
|
||||
<input v-model="interfaceForm.name" type="text" class="input-field text-sm" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.clientInstance') }}</label>
|
||||
<select v-model="interfaceForm.client_instance_code" class="input-field text-sm">
|
||||
<option v-for="opt in clientOptions" :key="opt.code" :value="opt.code">{{ opt.code }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.connectorType') }}</label>
|
||||
<select v-model="interfaceForm.connector_type" class="input-field text-sm">
|
||||
<option value="rest">rest</option>
|
||||
<option value="soap">soap</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="interfaceForm.connector_type === 'rest'" class="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.httpMethod') }}</label>
|
||||
<select v-model="interfaceForm.http_method" class="input-field text-sm">
|
||||
<option value="">—</option>
|
||||
<option value="GET">GET</option>
|
||||
<option value="POST">POST</option>
|
||||
<option value="PUT">PUT</option>
|
||||
<option value="DELETE">DELETE</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.requestPath') }}</label>
|
||||
<input v-model="interfaceForm.request_path" type="text" class="input-field text-sm font-mono" :placeholder="t('admin.integrationConnector.placeholders.requestPath')" />
|
||||
</div>
|
||||
</div>
|
||||
<details class="rounded-lg border border-slate-200 px-3 py-2">
|
||||
<summary class="cursor-pointer text-xs font-bold text-secondary">{{ t('admin.integrationConnector.advancedConfig') }}</summary>
|
||||
<div class="mt-2 grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.requestSpec') }}</label>
|
||||
<textarea v-model="interfaceForm.request_spec_json" rows="5" class="input-field text-sm font-mono" spellcheck="false" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.inputSchema') }}</label>
|
||||
<textarea v-model="interfaceForm.input_schema_json" rows="5" class="input-field text-sm font-mono" spellcheck="false" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.responseMapping') }}</label>
|
||||
<textarea v-model="interfaceForm.response_mapping_json" rows="5" class="input-field text-sm font-mono" spellcheck="false" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.outputSchema') }}</label>
|
||||
<textarea v-model="interfaceForm.output_schema_json" rows="5" class="input-field text-sm font-mono" spellcheck="false" />
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.status') }}</label>
|
||||
<select v-model="interfaceForm.status" class="input-field text-sm">
|
||||
<option value="draft">draft</option>
|
||||
<option value="published">published</option>
|
||||
<option value="retired">retired</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="flex items-end pb-1">
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
|
||||
<input v-model="interfaceForm.enabled" type="checkbox" class="w-4 h-4 rounded text-brand-600 border-default" />
|
||||
{{ t('admin.integrationConnector.fields.enabled') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 绑定 -->
|
||||
<template v-else-if="activeEntity === 'binding'">
|
||||
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.capability') }}</label>
|
||||
<select v-model="bindingForm.capability" class="input-field text-sm">
|
||||
<option v-for="cap in capabilityOptions" :key="cap.name" :value="cap.name">{{ cap.name }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.environment') }}</label>
|
||||
<input v-model="bindingForm.environment" type="text" class="input-field text-sm" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.clientInstance') }}</label>
|
||||
<select v-model="bindingForm.client_instance_code" class="input-field text-sm">
|
||||
<option v-for="opt in clientOptions" :key="opt.code" :value="opt.code">{{ opt.code }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.interfaceDef') }}</label>
|
||||
<select v-model="bindingForm.interface_definition_code" class="input-field text-sm">
|
||||
<option v-for="opt in interfaceOptions" :key="opt.code" :value="opt.code">{{ opt.code }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.mappingVersion') }}</label>
|
||||
<input v-model.number="bindingForm.mapping_version" type="number" class="input-field text-sm" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.priority') }}</label>
|
||||
<input v-model.number="bindingForm.priority" type="number" class="input-field text-sm" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.effectiveFrom') }}</label>
|
||||
<input v-model="bindingForm.effective_from" type="datetime-local" class="input-field text-sm" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.effectiveTo') }}</label>
|
||||
<input v-model="bindingForm.effective_to" type="datetime-local" class="input-field text-sm" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.contextSourceCode') }}</label>
|
||||
<input v-model="bindingForm.context_source_code" type="text" class="input-field text-sm" :placeholder="t('admin.integrationConnector.placeholders.contextSourceCode')" />
|
||||
</div>
|
||||
<details class="rounded-lg border border-slate-200 px-3 py-2">
|
||||
<summary class="cursor-pointer text-xs font-bold text-secondary">{{ t('admin.integrationConnector.advancedConfig') }}</summary>
|
||||
<div class="mt-2 space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.contextSelector') }}</label>
|
||||
<textarea v-model="bindingForm.context_selector_json" rows="4" class="input-field text-sm font-mono" spellcheck="false" />
|
||||
</div>
|
||||
</details>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.status') }}</label>
|
||||
<select v-model="bindingForm.status" class="input-field text-sm">
|
||||
<option value="draft">draft</option>
|
||||
<option value="published">published</option>
|
||||
<option value="retired">retired</option>
|
||||
</select>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 凭据引用 -->
|
||||
<template v-else>
|
||||
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.code') }}</label>
|
||||
<input v-model="credentialForm.code" type="text" class="input-field text-sm" :disabled="Boolean(credentialForm.id)" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.secretRef') }}</label>
|
||||
<input v-model="credentialForm.secret_ref" type="text" class="input-field text-sm" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.secretProvider') }}</label>
|
||||
<input v-model="credentialForm.secret_provider" type="text" class="input-field text-sm" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.credentialType') }}</label>
|
||||
<input v-model="credentialForm.credential_type" type="text" class="input-field text-sm" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.integrationConnector.fields.status') }}</label>
|
||||
<select v-model="credentialForm.status" class="input-field text-sm">
|
||||
<option value="active">active</option>
|
||||
<option value="rotating">rotating</option>
|
||||
<option value="retired">retired</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<div class="admin-modal-footer">
|
||||
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
|
||||
<button type="button" class="btn-primary disabled:opacity-70" :disabled="isSaving" @click="emit('save')">
|
||||
{{ isSaving ? t('admin.save') + '...' : t('admin.save') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* features/admin/modules/integration-connector/composables/useIntegrationConnectorAdmin.spec.ts
|
||||
* 用途:锁定集成连接器管理编排——四实体保存(create/update 分支)、JSON 字段解析校验、
|
||||
* 必填校验拦截、能力调用与连接测试调用 API。
|
||||
* 依赖:vi.mock(integration-connector.api)、@vue/test-utils、i18n。
|
||||
* 逻辑:通过 setup 挂载 harness 组件访问 useIntegrationConnectorAdmin(useI18n 需在 setup 内);
|
||||
* Mock API 断言 payload 构造与调用;非法 JSON 触发拦截且不调 API。
|
||||
*/
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { defineComponent, h } from 'vue';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import i18n from '@/i18n';
|
||||
import { useIntegrationConnectorAdmin } from './useIntegrationConnectorAdmin';
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
listIntegrationClientInstances: vi.fn(),
|
||||
createIntegrationClientInstance: vi.fn(),
|
||||
updateIntegrationClientInstance: vi.fn(),
|
||||
deleteIntegrationClientInstance: vi.fn(),
|
||||
testIntegrationClientConnection: vi.fn(),
|
||||
listIntegrationInterfaceDefinitions: vi.fn(),
|
||||
createIntegrationInterfaceDefinition: vi.fn(),
|
||||
updateIntegrationInterfaceDefinition: vi.fn(),
|
||||
listIntegrationBindings: vi.fn(),
|
||||
createIntegrationBinding: vi.fn(),
|
||||
updateIntegrationBinding: vi.fn(),
|
||||
listIntegrationCredentialReferences: vi.fn(),
|
||||
createIntegrationCredentialReference: vi.fn(),
|
||||
updateIntegrationCredentialReference: vi.fn(),
|
||||
listIntegrationCapabilities: vi.fn(),
|
||||
callIntegrationCapability: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/admin/modules/integration-connector/api/integration-connector.api', () => api);
|
||||
|
||||
function makeHarness() {
|
||||
let exposed: ReturnType<typeof useIntegrationConnectorAdmin> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
exposed = useIntegrationConnectorAdmin();
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
return exposed!;
|
||||
}
|
||||
|
||||
describe('useIntegrationConnectorAdmin', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('loadAll 拉取五个列表', async () => {
|
||||
api.listIntegrationClientInstances.mockResolvedValue([]);
|
||||
api.listIntegrationInterfaceDefinitions.mockResolvedValue([]);
|
||||
api.listIntegrationBindings.mockResolvedValue([]);
|
||||
api.listIntegrationCredentialReferences.mockResolvedValue([]);
|
||||
api.listIntegrationCapabilities.mockResolvedValue([]);
|
||||
const c = makeHarness();
|
||||
await c.loadAll();
|
||||
expect(api.listIntegrationClientInstances).toHaveBeenCalled();
|
||||
expect(api.listIntegrationCapabilities).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('新建客户端实例:关键字段独立列 + config_json 解析为对象并 POST', async () => {
|
||||
const c = makeHarness();
|
||||
c.openCreateModal('client');
|
||||
c.clientForm.value.code = 'ERP-X';
|
||||
c.clientForm.value.name = 'ERP X';
|
||||
c.clientForm.value.endpoint = 'https://x.invalid';
|
||||
c.clientForm.value.timeout_seconds = '90';
|
||||
c.clientForm.value.config_json = '{"headers":{"X-Tenant":"A"}}';
|
||||
await c.saveActive();
|
||||
expect(api.createIntegrationClientInstance).toHaveBeenCalledWith({
|
||||
code: 'ERP-X', name: 'ERP X', connector_type: 'rest', environment: 'prod',
|
||||
endpoint: 'https://x.invalid', timeout_seconds: 90,
|
||||
config_json: { headers: { 'X-Tenant': 'A' } }, credential_ref_code: null, enabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('编辑客户端实例:有 id 走 PUT', async () => {
|
||||
const c = makeHarness();
|
||||
c.openEditModal('client', {
|
||||
id: 1, code: 'ERP-X', name: 'old', connector_type: 'rest', environment: 'prod',
|
||||
config_json: {}, credential_ref_code: null, enabled: true,
|
||||
});
|
||||
c.clientForm.value.name = 'new';
|
||||
await c.saveActive();
|
||||
expect(api.updateIntegrationClientInstance).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('非法 JSON 字段触发拦截且不调 API', async () => {
|
||||
const c = makeHarness();
|
||||
c.openCreateModal('client');
|
||||
c.clientForm.value.code = 'ERP-X';
|
||||
c.clientForm.value.name = 'ERP X';
|
||||
c.clientForm.value.config_json = '{bad json';
|
||||
await c.saveActive();
|
||||
expect(api.createIntegrationClientInstance).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('客户端实例必填:缺 code 不调 API', async () => {
|
||||
const c = makeHarness();
|
||||
c.openCreateModal('client');
|
||||
c.clientForm.value.name = 'ERP X';
|
||||
await c.saveActive();
|
||||
expect(api.createIntegrationClientInstance).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('绑定:必填校验与 POST payload', async () => {
|
||||
const c = makeHarness();
|
||||
c.openCreateModal('binding');
|
||||
c.bindingForm.value.capability = 'in_transit_transfer.query_inventory';
|
||||
c.bindingForm.value.client_instance_code = 'CLI-A';
|
||||
c.bindingForm.value.interface_definition_code = 'IF-A';
|
||||
await c.saveActive();
|
||||
expect(api.createIntegrationBinding).toHaveBeenCalledWith({
|
||||
capability: 'in_transit_transfer.query_inventory', context_selector_json: {},
|
||||
context_source_code: null,
|
||||
client_instance_code: 'CLI-A', interface_definition_code: 'IF-A',
|
||||
mapping_version: 1, priority: 0, environment: 'prod',
|
||||
effective_from: null, effective_to: null, status: 'draft',
|
||||
});
|
||||
});
|
||||
|
||||
it('凭据引用:创建 payload 不含明文 secret', async () => {
|
||||
const c = makeHarness();
|
||||
c.openCreateModal('credential');
|
||||
c.credentialForm.value.code = 'CRED-A';
|
||||
c.credentialForm.value.secret_ref = 'IN_TRANSIT_ERP_PASSWORD';
|
||||
await c.saveActive();
|
||||
expect(api.createIntegrationCredentialReference).toHaveBeenCalledWith({
|
||||
code: 'CRED-A', secret_ref: 'IN_TRANSIT_ERP_PASSWORD', secret_provider: 'env',
|
||||
credential_type: 'password', status: 'active',
|
||||
});
|
||||
});
|
||||
|
||||
it('连接测试与能力调用走对应 API', async () => {
|
||||
const c = makeHarness();
|
||||
api.testIntegrationClientConnection.mockResolvedValue({ ok: true });
|
||||
api.callIntegrationCapability.mockResolvedValue({ status: 'success', data: { found: true }, error_code: null, error_message: null, document_no: null, trace_id: null });
|
||||
await c.testConnection('CLI-A');
|
||||
expect(api.testIntegrationClientConnection).toHaveBeenCalledWith('CLI-A');
|
||||
c.openCallModal('in_transit_transfer.query_inventory');
|
||||
await c.runCall();
|
||||
expect(api.callIntegrationCapability).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
/**
|
||||
* features/admin/modules/integration-connector/composables/useIntegrationConnectorAdmin.ts
|
||||
* 集成连接器管理编排:客户端实例/接口定义/绑定/凭据引用四实体列表与增改表单,
|
||||
* 以及能力清单与手动调用测试。
|
||||
* 依赖:integration-connector.api、types、useMessage、useI18n。
|
||||
* 逻辑:各列表独立 loadAll;新增/编辑共用表单弹窗态(form.id 区分);能力测试
|
||||
* 独立于配置表单(CapabilityCall 弹窗)。保存/删除后刷新对应列表。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
callIntegrationCapability,
|
||||
createIntegrationBinding,
|
||||
createIntegrationClientInstance,
|
||||
createIntegrationCredentialReference,
|
||||
createIntegrationInterfaceDefinition,
|
||||
deleteIntegrationClientInstance,
|
||||
listIntegrationBindings,
|
||||
listIntegrationCapabilities,
|
||||
listIntegrationClientInstances,
|
||||
listIntegrationCredentialReferences,
|
||||
listIntegrationInterfaceDefinitions,
|
||||
testIntegrationClientConnection,
|
||||
updateIntegrationBinding,
|
||||
updateIntegrationClientInstance,
|
||||
updateIntegrationCredentialReference,
|
||||
updateIntegrationInterfaceDefinition,
|
||||
} from '../api/integration-connector.api';
|
||||
import {
|
||||
bindingRowToForm,
|
||||
clientInstanceRowToForm,
|
||||
createEmptyBindingForm,
|
||||
createEmptyClientInstanceForm,
|
||||
createEmptyCredentialReferenceForm,
|
||||
createEmptyInterfaceDefinitionForm,
|
||||
credentialReferenceRowToForm,
|
||||
interfaceDefinitionRowToForm,
|
||||
type BindingFormState,
|
||||
type ClientInstanceFormState,
|
||||
type CredentialReferenceFormState,
|
||||
type IntegrationBindingRow,
|
||||
type IntegrationCallResultRow,
|
||||
type IntegrationCapabilityRow,
|
||||
type IntegrationClientInstanceRow,
|
||||
type IntegrationCredentialReferenceRow,
|
||||
type IntegrationInterfaceDefinitionRow,
|
||||
type InterfaceDefinitionFormState,
|
||||
} from '../types/integration-connector.types';
|
||||
|
||||
type EditableEntity = 'client' | 'interface' | 'binding' | 'credential';
|
||||
|
||||
export function useIntegrationConnectorAdmin() {
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
// ---- 列表与加载态 ----
|
||||
const clients = ref<IntegrationClientInstanceRow[]>([]);
|
||||
const interfaces = ref<IntegrationInterfaceDefinitionRow[]>([]);
|
||||
const bindings = ref<IntegrationBindingRow[]>([]);
|
||||
const credentials = ref<IntegrationCredentialReferenceRow[]>([]);
|
||||
const capabilities = ref<IntegrationCapabilityRow[]>([]);
|
||||
const isLoading = ref(true);
|
||||
|
||||
// ---- 表单弹窗态 ----
|
||||
const activeEntity = ref<EditableEntity>('client');
|
||||
const showFormModal = ref(false);
|
||||
const isSaving = ref(false);
|
||||
const clientForm = ref<ClientInstanceFormState>(createEmptyClientInstanceForm());
|
||||
const interfaceForm = ref<InterfaceDefinitionFormState>(createEmptyInterfaceDefinitionForm());
|
||||
const bindingForm = ref<BindingFormState>(createEmptyBindingForm());
|
||||
const credentialForm = ref<CredentialReferenceFormState>(createEmptyCredentialReferenceForm());
|
||||
|
||||
// ---- 能力调用测试弹窗态 ----
|
||||
const showCallModal = ref(false);
|
||||
const callCapability = ref('');
|
||||
const callParamsText = ref('');
|
||||
const callContextText = ref('');
|
||||
const callResult = ref<IntegrationCallResultRow | null>(null);
|
||||
const callBusy = ref(false);
|
||||
|
||||
// ---- 连接测试 ----
|
||||
const testingClientCode = ref('');
|
||||
const testResultText = ref('');
|
||||
|
||||
const loadClients = async () => { clients.value = await listIntegrationClientInstances(); };
|
||||
const loadInterfaces = async () => { interfaces.value = await listIntegrationInterfaceDefinitions(); };
|
||||
const loadBindings = async () => { bindings.value = await listIntegrationBindings(); };
|
||||
const loadCredentials = async () => { credentials.value = await listIntegrationCredentialReferences(); };
|
||||
const loadCapabilities = async () => { capabilities.value = await listIntegrationCapabilities(); };
|
||||
|
||||
const loadAll = async () => {
|
||||
isLoading.value = true;
|
||||
try {
|
||||
await Promise.all([loadClients(), loadInterfaces(), loadBindings(), loadCredentials(), loadCapabilities()]);
|
||||
} catch (e) {
|
||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const reloadOne = async (entity: EditableEntity) => {
|
||||
if (entity === 'client') await loadClients();
|
||||
else if (entity === 'interface') await loadInterfaces();
|
||||
else if (entity === 'binding') await loadBindings();
|
||||
else await loadCredentials();
|
||||
};
|
||||
|
||||
// ---- 弹窗打开/关闭 ----
|
||||
const openCreateModal = (entity: EditableEntity) => {
|
||||
activeEntity.value = entity;
|
||||
if (entity === 'client') clientForm.value = createEmptyClientInstanceForm();
|
||||
else if (entity === 'interface') interfaceForm.value = createEmptyInterfaceDefinitionForm();
|
||||
else if (entity === 'binding') bindingForm.value = createEmptyBindingForm();
|
||||
else credentialForm.value = createEmptyCredentialReferenceForm();
|
||||
showFormModal.value = true;
|
||||
};
|
||||
|
||||
const openEditModal = (entity: EditableEntity, row: IntegrationClientInstanceRow | IntegrationInterfaceDefinitionRow | IntegrationBindingRow | IntegrationCredentialReferenceRow) => {
|
||||
activeEntity.value = entity;
|
||||
if (entity === 'client') clientForm.value = clientInstanceRowToForm(row as IntegrationClientInstanceRow);
|
||||
else if (entity === 'interface') interfaceForm.value = interfaceDefinitionRowToForm(row as IntegrationInterfaceDefinitionRow);
|
||||
else if (entity === 'binding') bindingForm.value = bindingRowToForm(row as IntegrationBindingRow);
|
||||
else credentialForm.value = credentialReferenceRowToForm(row as IntegrationCredentialReferenceRow);
|
||||
showFormModal.value = true;
|
||||
};
|
||||
|
||||
const closeFormModal = () => {
|
||||
showFormModal.value = false;
|
||||
clientForm.value = createEmptyClientInstanceForm();
|
||||
interfaceForm.value = createEmptyInterfaceDefinitionForm();
|
||||
bindingForm.value = createEmptyBindingForm();
|
||||
credentialForm.value = createEmptyCredentialReferenceForm();
|
||||
};
|
||||
|
||||
/** 解析 JSON 文本;空串返回 {},非法 JSON 抛错并提示。 */
|
||||
const parseJsonField = (text: string, fieldLabel: string): Record<string, unknown> => {
|
||||
const trimmed = String(text || '').trim();
|
||||
if (!trimmed) return {};
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
|
||||
throw new Error('must be an object');
|
||||
} catch {
|
||||
msg.warning(t('admin.integrationConnector.msg.invalidJson', { field: fieldLabel }));
|
||||
throw new Error('invalid JSON');
|
||||
}
|
||||
};
|
||||
|
||||
// ---- 保存 ----
|
||||
const saveActive = async () => {
|
||||
isSaving.value = true;
|
||||
try {
|
||||
if (activeEntity.value === 'client') {
|
||||
const form = clientForm.value;
|
||||
if (!form.code.trim() || !form.name.trim()) {
|
||||
msg.warning(t('admin.integrationConnector.msg.fillClient'));
|
||||
return;
|
||||
}
|
||||
const configJson = parseJsonField(form.config_json, 'config_json');
|
||||
const payload = {
|
||||
code: form.code.trim(), name: form.name.trim(), connector_type: form.connector_type,
|
||||
environment: form.environment,
|
||||
endpoint: form.endpoint.trim() || null,
|
||||
timeout_seconds: form.timeout_seconds.trim() ? Number(form.timeout_seconds) : null,
|
||||
config_json: configJson,
|
||||
credential_ref_code: form.credential_ref_code.trim() || null, enabled: form.enabled,
|
||||
};
|
||||
if (form.id) await updateIntegrationClientInstance(form.code, payload);
|
||||
else await createIntegrationClientInstance(payload);
|
||||
} else if (activeEntity.value === 'interface') {
|
||||
const form = interfaceForm.value;
|
||||
if (!form.code.trim() || !form.client_instance_code.trim()) {
|
||||
msg.warning(t('admin.integrationConnector.msg.fillInterface'));
|
||||
return;
|
||||
}
|
||||
const payload = {
|
||||
code: form.code.trim(), name: form.name.trim() || form.code.trim(),
|
||||
client_instance_code: form.client_instance_code.trim(), connector_type: form.connector_type,
|
||||
http_method: form.http_method.trim() || null,
|
||||
request_path: form.request_path.trim() || null,
|
||||
request_spec_json: parseJsonField(form.request_spec_json, 'request_spec_json'),
|
||||
input_schema_json: parseJsonField(form.input_schema_json, 'input_schema_json'),
|
||||
response_mapping_json: parseJsonField(form.response_mapping_json, 'response_mapping_json'),
|
||||
output_schema_json: parseJsonField(form.output_schema_json, 'output_schema_json'),
|
||||
status: form.status, enabled: form.enabled,
|
||||
};
|
||||
if (form.id) await updateIntegrationInterfaceDefinition(form.code, payload);
|
||||
else await createIntegrationInterfaceDefinition(payload);
|
||||
} else if (activeEntity.value === 'binding') {
|
||||
const form = bindingForm.value;
|
||||
if (!form.capability.trim() || !form.client_instance_code.trim() || !form.interface_definition_code.trim()) {
|
||||
msg.warning(t('admin.integrationConnector.msg.fillBinding'));
|
||||
return;
|
||||
}
|
||||
const payload = {
|
||||
capability: form.capability.trim(), context_selector_json: parseJsonField(form.context_selector_json, 'context_selector_json'),
|
||||
context_source_code: form.context_source_code.trim() || null,
|
||||
client_instance_code: form.client_instance_code.trim(), interface_definition_code: form.interface_definition_code.trim(),
|
||||
mapping_version: Number(form.mapping_version || 1), priority: Number(form.priority || 0),
|
||||
environment: form.environment, effective_from: form.effective_from || null, effective_to: form.effective_to || null,
|
||||
status: form.status,
|
||||
};
|
||||
if (form.id) await updateIntegrationBinding(form.id, payload);
|
||||
else await createIntegrationBinding(payload);
|
||||
} else {
|
||||
const form = credentialForm.value;
|
||||
if (!form.code.trim() || !form.secret_ref.trim()) {
|
||||
msg.warning(t('admin.integrationConnector.msg.fillCredential'));
|
||||
return;
|
||||
}
|
||||
const payload = {
|
||||
code: form.code.trim(), secret_ref: form.secret_ref.trim(), secret_provider: form.secret_provider,
|
||||
credential_type: form.credential_type, status: form.status,
|
||||
};
|
||||
if (form.id) await updateIntegrationCredentialReference(form.code, payload);
|
||||
else await createIntegrationCredentialReference(payload);
|
||||
}
|
||||
closeFormModal();
|
||||
await reloadOne(activeEntity.value);
|
||||
msg.success(t('admin.integrationConnector.msg.saved'));
|
||||
} catch (e) {
|
||||
// parseJsonField 已在内部提示;这里兜底 API 错误。
|
||||
if (!(e instanceof Error && e.message === 'invalid JSON')) {
|
||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||
}
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// ---- 连接测试 ----
|
||||
const testConnection = async (code: string) => {
|
||||
testingClientCode.value = code;
|
||||
testResultText.value = '';
|
||||
try {
|
||||
const result = await testIntegrationClientConnection(code);
|
||||
testResultText.value = JSON.stringify(result, null, 2);
|
||||
msg.success(t('admin.integrationConnector.msg.testOk'));
|
||||
} catch (e) {
|
||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||
} finally {
|
||||
testingClientCode.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
// ---- 能力调用测试 ----
|
||||
const openCallModal = (capability: string) => {
|
||||
callCapability.value = capability;
|
||||
callParamsText.value = JSON.stringify({ invoice_no: '', from_warehouse: '', to_warehouse: '', quantity: 0 }, null, 2);
|
||||
callContextText.value = '{}';
|
||||
callResult.value = null;
|
||||
showCallModal.value = true;
|
||||
};
|
||||
|
||||
const closeCallModal = () => {
|
||||
showCallModal.value = false;
|
||||
callResult.value = null;
|
||||
};
|
||||
|
||||
const runCall = async () => {
|
||||
callBusy.value = true;
|
||||
try {
|
||||
const params = parseJsonField(callParamsText.value, 'params');
|
||||
const context = parseJsonField(callContextText.value, 'context');
|
||||
callResult.value = await callIntegrationCapability(callCapability.value, { params, context });
|
||||
} catch (e) {
|
||||
if (!(e instanceof Error && e.message === 'invalid JSON')) {
|
||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||
}
|
||||
} finally {
|
||||
callBusy.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const deleteClient = async (code: string) => {
|
||||
try {
|
||||
await deleteIntegrationClientInstance(code);
|
||||
await loadClients();
|
||||
msg.success(t('admin.integrationConnector.msg.deleted'));
|
||||
} catch (e) {
|
||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
clients, interfaces, bindings, credentials, capabilities,
|
||||
isLoading, activeEntity, showFormModal, isSaving,
|
||||
clientForm, interfaceForm, bindingForm, credentialForm,
|
||||
showCallModal, callCapability, callParamsText, callContextText, callResult, callBusy,
|
||||
testingClientCode, testResultText,
|
||||
loadAll, openCreateModal, openEditModal, closeFormModal, saveActive,
|
||||
testConnection, openCallModal, closeCallModal, runCall, deleteClient,
|
||||
};
|
||||
}
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
/**
|
||||
* features/admin/modules/integration-connector/types/integration-connector.types.ts
|
||||
* 集成连接器管理域类型:客户端实例、接口定义、绑定、凭据引用、能力清单、调用结果。
|
||||
* 依赖:无(纯类型与表单构建函数)。
|
||||
* 逻辑:与后端 /api/integration-connector/* 序列化契约对齐;JSON 配置字段以 Record 承载
|
||||
* 具体结构由表单/JSON 编辑器负责,前端不硬编码外部系统差异。
|
||||
*/
|
||||
|
||||
/** 连接器类型:与后端 CONNECTOR_TYPES 对齐。 */
|
||||
export type IntegrationConnectorType = 'rest' | 'soap';
|
||||
|
||||
/** 配置状态:draft 草稿 / published 已发布 / retired 已退役。 */
|
||||
export type IntegrationConfigStatus = 'draft' | 'published' | 'retired';
|
||||
|
||||
/** 凭据状态。 */
|
||||
export type IntegrationCredentialStatus = 'active' | 'rotating' | 'retired';
|
||||
|
||||
/** 能力清单项(后端 capability 注册表)。 */
|
||||
export interface IntegrationCapabilityRow {
|
||||
name: string;
|
||||
write: boolean;
|
||||
idempotency: string;
|
||||
input_schema: Record<string, unknown>;
|
||||
output_schema: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** 能力调用结果(后端 IntegrationCallResult 序列化)。 */
|
||||
export interface IntegrationCallResultRow {
|
||||
status: string;
|
||||
data: Record<string, unknown> | null;
|
||||
error_code: string | null;
|
||||
error_message: string | null;
|
||||
document_no: string | null;
|
||||
trace_id: string | null;
|
||||
}
|
||||
|
||||
/** 客户端实例(接口地址/凭据引用/连接配置)。 */
|
||||
export interface IntegrationClientInstanceRow {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
connector_type: IntegrationConnectorType;
|
||||
environment: string;
|
||||
endpoint: string | null;
|
||||
timeout_seconds: number | null;
|
||||
config_json: Record<string, unknown>;
|
||||
credential_ref_code: string | null;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
/** 接口定义(接口模板/入参字段/回传映射/出参 Schema)。 */
|
||||
export interface IntegrationInterfaceDefinitionRow {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
client_instance_code: string;
|
||||
connector_type: IntegrationConnectorType;
|
||||
http_method: string | null;
|
||||
request_path: string | null;
|
||||
request_spec_json: Record<string, unknown>;
|
||||
input_schema_json: Record<string, unknown>;
|
||||
response_mapping_json: Record<string, unknown>;
|
||||
output_schema_json: Record<string, unknown>;
|
||||
version: number;
|
||||
status: IntegrationConfigStatus;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
/** 绑定(能力 → 客户端 + 接口 + 映射版本)。 */
|
||||
export interface IntegrationBindingRow {
|
||||
id: number;
|
||||
capability: string;
|
||||
context_selector_json: Record<string, unknown>;
|
||||
context_source_code: string | null;
|
||||
client_instance_code: string;
|
||||
interface_definition_code: string;
|
||||
mapping_version: number;
|
||||
priority: number;
|
||||
environment: string;
|
||||
effective_from: string | null;
|
||||
effective_to: string | null;
|
||||
status: IntegrationConfigStatus;
|
||||
}
|
||||
|
||||
/** 凭据引用(只存 secret_ref,不落明文)。 */
|
||||
export interface IntegrationCredentialReferenceRow {
|
||||
id: number;
|
||||
code: string;
|
||||
secret_ref: string;
|
||||
secret_provider: string;
|
||||
credential_type: string;
|
||||
version: number;
|
||||
status: IntegrationCredentialStatus;
|
||||
last_verified_at: string | null;
|
||||
}
|
||||
|
||||
/** 客户端实例表单。 */
|
||||
export interface ClientInstanceFormState {
|
||||
id: number | null;
|
||||
code: string;
|
||||
name: string;
|
||||
connector_type: IntegrationConnectorType;
|
||||
environment: string;
|
||||
endpoint: string;
|
||||
timeout_seconds: string;
|
||||
config_json: string;
|
||||
credential_ref_code: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
/** 接口定义表单(JSON 字段以文本承载,提交时解析)。 */
|
||||
export interface InterfaceDefinitionFormState {
|
||||
id: number | null;
|
||||
code: string;
|
||||
name: string;
|
||||
client_instance_code: string;
|
||||
connector_type: IntegrationConnectorType;
|
||||
http_method: string;
|
||||
request_path: string;
|
||||
request_spec_json: string;
|
||||
input_schema_json: string;
|
||||
response_mapping_json: string;
|
||||
output_schema_json: string;
|
||||
status: IntegrationConfigStatus;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
/** 绑定表单。 */
|
||||
export interface BindingFormState {
|
||||
id: number | null;
|
||||
capability: string;
|
||||
context_selector_json: string;
|
||||
context_source_code: string;
|
||||
client_instance_code: string;
|
||||
interface_definition_code: string;
|
||||
mapping_version: number;
|
||||
priority: number;
|
||||
environment: string;
|
||||
effective_from: string;
|
||||
effective_to: string;
|
||||
status: IntegrationConfigStatus;
|
||||
}
|
||||
|
||||
/** 凭据引用表单。 */
|
||||
export interface CredentialReferenceFormState {
|
||||
id: number | null;
|
||||
code: string;
|
||||
secret_ref: string;
|
||||
secret_provider: string;
|
||||
credential_type: string;
|
||||
status: IntegrationCredentialStatus;
|
||||
}
|
||||
|
||||
const toJsonText = (value: Record<string, unknown> | null | undefined): string => {
|
||||
if (!value || Object.keys(value).length === 0) return '';
|
||||
return JSON.stringify(value, null, 2);
|
||||
};
|
||||
|
||||
/** 创建空的客户端实例表单。 */
|
||||
export function createEmptyClientInstanceForm(): ClientInstanceFormState {
|
||||
return {
|
||||
id: null,
|
||||
code: '',
|
||||
name: '',
|
||||
connector_type: 'rest',
|
||||
environment: 'prod',
|
||||
endpoint: '',
|
||||
timeout_seconds: '60',
|
||||
config_json: '',
|
||||
credential_ref_code: '',
|
||||
enabled: true,
|
||||
};
|
||||
}
|
||||
|
||||
/** 列表行回填为客户端实例编辑表单。 */
|
||||
export function clientInstanceRowToForm(row: IntegrationClientInstanceRow): ClientInstanceFormState {
|
||||
return {
|
||||
id: row.id,
|
||||
code: row.code,
|
||||
name: row.name,
|
||||
connector_type: row.connector_type,
|
||||
environment: row.environment,
|
||||
endpoint: row.endpoint ?? '',
|
||||
timeout_seconds: String(row.timeout_seconds ?? ''),
|
||||
config_json: toJsonText(row.config_json),
|
||||
credential_ref_code: row.credential_ref_code ?? '',
|
||||
enabled: Boolean(row.enabled),
|
||||
};
|
||||
}
|
||||
|
||||
/** 创建空的接口定义表单。 */
|
||||
export function createEmptyInterfaceDefinitionForm(): InterfaceDefinitionFormState {
|
||||
return {
|
||||
id: null,
|
||||
code: '',
|
||||
name: '',
|
||||
client_instance_code: '',
|
||||
connector_type: 'rest',
|
||||
http_method: '',
|
||||
request_path: '',
|
||||
request_spec_json: '',
|
||||
input_schema_json: '',
|
||||
response_mapping_json: '',
|
||||
output_schema_json: '',
|
||||
status: 'draft',
|
||||
enabled: true,
|
||||
};
|
||||
}
|
||||
|
||||
/** 列表行回填为接口定义编辑表单。 */
|
||||
export function interfaceDefinitionRowToForm(row: IntegrationInterfaceDefinitionRow): InterfaceDefinitionFormState {
|
||||
return {
|
||||
id: row.id,
|
||||
code: row.code,
|
||||
name: row.name,
|
||||
client_instance_code: row.client_instance_code,
|
||||
connector_type: row.connector_type,
|
||||
http_method: row.http_method ?? '',
|
||||
request_path: row.request_path ?? '',
|
||||
request_spec_json: toJsonText(row.request_spec_json),
|
||||
input_schema_json: toJsonText(row.input_schema_json),
|
||||
response_mapping_json: toJsonText(row.response_mapping_json),
|
||||
output_schema_json: toJsonText(row.output_schema_json),
|
||||
status: row.status,
|
||||
enabled: Boolean(row.enabled),
|
||||
};
|
||||
}
|
||||
|
||||
/** 创建空的绑定表单。 */
|
||||
export function createEmptyBindingForm(): BindingFormState {
|
||||
return {
|
||||
id: null,
|
||||
capability: '',
|
||||
context_selector_json: '',
|
||||
context_source_code: '',
|
||||
client_instance_code: '',
|
||||
interface_definition_code: '',
|
||||
mapping_version: 1,
|
||||
priority: 0,
|
||||
environment: 'prod',
|
||||
effective_from: '',
|
||||
effective_to: '',
|
||||
status: 'draft',
|
||||
};
|
||||
}
|
||||
|
||||
/** 列表行回填为绑定编辑表单。 */
|
||||
export function bindingRowToForm(row: IntegrationBindingRow): BindingFormState {
|
||||
return {
|
||||
id: row.id,
|
||||
capability: row.capability,
|
||||
context_selector_json: toJsonText(row.context_selector_json),
|
||||
context_source_code: row.context_source_code ?? '',
|
||||
client_instance_code: row.client_instance_code,
|
||||
interface_definition_code: row.interface_definition_code,
|
||||
mapping_version: Number(row.mapping_version || 1),
|
||||
priority: Number(row.priority || 0),
|
||||
environment: row.environment,
|
||||
effective_from: row.effective_from ?? '',
|
||||
effective_to: row.effective_to ?? '',
|
||||
status: row.status,
|
||||
};
|
||||
}
|
||||
|
||||
/** 创建空的凭据引用表单。 */
|
||||
export function createEmptyCredentialReferenceForm(): CredentialReferenceFormState {
|
||||
return {
|
||||
id: null,
|
||||
code: '',
|
||||
secret_ref: '',
|
||||
secret_provider: 'env',
|
||||
credential_type: 'password',
|
||||
status: 'active',
|
||||
};
|
||||
}
|
||||
|
||||
/** 列表行回填为凭据引用编辑表单。 */
|
||||
export function credentialReferenceRowToForm(row: IntegrationCredentialReferenceRow): CredentialReferenceFormState {
|
||||
return {
|
||||
id: row.id,
|
||||
code: row.code,
|
||||
secret_ref: row.secret_ref,
|
||||
secret_provider: row.secret_provider,
|
||||
credential_type: row.credential_type,
|
||||
status: row.status,
|
||||
};
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
* 常用问题 / FAQ 缓存创建与编辑居中弹窗。
|
||||
* 依赖:QuestionFormState、admin 通用 modal 样式。
|
||||
* 逻辑:QuestionsPage 打开本组件;提交时 emit save,由 composable 调 API。
|
||||
* is_enabled 仅控制工作台首页入口;cache_enabled 单独控制聊天是否跳过 Dify。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
@@ -86,13 +87,16 @@ const isStale = computed(() => Boolean(props.form.stale_at));
|
||||
<label class="label-field">{{ t('admin.question.fields.sortOrder') }}</label>
|
||||
<input v-model.number="form.sort_order" type="number" class="input-field text-sm" />
|
||||
</div>
|
||||
<div class="md:col-span-2 flex flex-wrap gap-6">
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
|
||||
<input v-model="form.is_enabled" type="checkbox" class="accent-brand-600" />
|
||||
<span>{{ t('admin.question.fields.isEnabled') }}</span>
|
||||
<div class="md:col-span-2 space-y-3">
|
||||
<label class="flex items-start gap-2 text-sm text-secondary cursor-pointer">
|
||||
<input v-model="form.is_enabled" type="checkbox" class="mt-0.5 accent-brand-600" />
|
||||
<span>
|
||||
<span class="block">{{ t('admin.question.fields.isEnabled') }}</span>
|
||||
<span class="block text-xs text-muted mt-0.5">{{ t('admin.question.fields.isEnabledHelp') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
|
||||
<input v-model="form.cache_enabled" type="checkbox" class="accent-brand-600" />
|
||||
<label class="flex items-start gap-2 text-sm text-secondary cursor-pointer">
|
||||
<input v-model="form.cache_enabled" type="checkbox" class="mt-0.5 accent-brand-600" />
|
||||
<span>{{ t('admin.question.fields.cacheEnabled') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
+2
-1
@@ -11,6 +11,7 @@ import { useRoute, useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { createRandomUuid } from '@/shared/utils/id';
|
||||
import {
|
||||
approveOrderProfileTestSuite,
|
||||
confirmOrderProfileBlindTestReviews,
|
||||
@@ -36,7 +37,7 @@ const router = useRouter();
|
||||
const message = useMessage();
|
||||
const { t } = useI18n();
|
||||
const profileId = Number(route.params.profileId);
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || createRandomUuid();
|
||||
const suite = ref<OrderProfileTestSuite | null>(null);
|
||||
const availableSamples = ref<OrderProfileBlindTestAvailableSample[]>([]);
|
||||
const selectedSampleKey = ref('');
|
||||
|
||||
+3
-2
@@ -11,6 +11,7 @@ import { useI18n } from 'vue-i18n';
|
||||
import { ArrowLeft, ArrowRight, Check, FileText, Layers3, Sparkles } from 'lucide-vue-next';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { createRandomUuid } from '@/shared/utils/id';
|
||||
import { getShippingOrderSchemaState } from '@/features/admin/api/shipping-order-schema.api';
|
||||
import { completeOrderDocumentProfileWizard, getOrderProfileSampleTables, listOrderProfileSamples } from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type { OrderProfileSampleDocument } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
@@ -33,7 +34,7 @@ const tables = ref<Array<{ table_id: string; page_no: number; row_count: number;
|
||||
const identity = reactive<Identity>({ displayName: '', schemaId: 0 });
|
||||
const documentId = ref(0);
|
||||
const tableId = ref('');
|
||||
const browserSessionId = crypto.randomUUID();
|
||||
const browserSessionId = createRandomUuid();
|
||||
let sampleRefreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const publishedSchemas = computed(() => schemas.value.filter((item) => item.status === 'published'));
|
||||
@@ -140,7 +141,7 @@ async function finish(enterEditor: boolean): Promise<void> {
|
||||
document_id: documentId.value,
|
||||
main_table_id: tableId.value,
|
||||
browser_session_id: browserSessionId,
|
||||
operation_id: crypto.randomUUID(),
|
||||
operation_id: createRandomUuid(),
|
||||
};
|
||||
const profile = await completeOrderDocumentProfileWizard(payload);
|
||||
message.success(t('admin.shippingOrderProfiles.created'));
|
||||
|
||||
+171
-19
@@ -4,11 +4,13 @@
|
||||
依赖:受控预览 API、Schema API、DocumentCanvas、useOrderProfileValueAdapter、
|
||||
XfaDatasetTree、XfaCollectionSelector、XfaSplitRulePanel、shippingOrderField.utils。
|
||||
逻辑:PDF 与 XFA 共用同一 desk DOM(main + aside.config + OrderProfileDocumentCanvas);
|
||||
XFA 仅在属性区插入读取方式/数据源/拆分/样本显示增量;OCR 建议进入普通建议区。
|
||||
XFA 仅在属性区插入读取方式/数据源/拆分/样本显示增量;OCR 建议进入普通建议区;
|
||||
未绑定订单字段框通过横幅 + 画布高亮强制展示,避免空白底图漏看导致发布失败。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
computed,
|
||||
nextTick,
|
||||
onBeforeUnmount,
|
||||
onMounted,
|
||||
reactive,
|
||||
@@ -19,6 +21,7 @@ import { onBeforeRouteLeave, useRoute, useRouter } from "vue-router";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { BusinessError } from "@/shared/api/client";
|
||||
import { useMessage } from "@/shared/composables/useMessage";
|
||||
import { createRandomUuid } from "@/shared/utils/id";
|
||||
import { getShippingOrderSchemaState } from "@/features/admin/api/shipping-order-schema.api";
|
||||
import {
|
||||
authorizeOrderProfilePreviewPages,
|
||||
@@ -104,6 +107,7 @@ import {
|
||||
toOrderProfileHeaderFieldRegion,
|
||||
resolveCoordinateFieldScope,
|
||||
isOrderProfileVisualFieldEligible,
|
||||
isUnboundOrderFieldCanvasRegion,
|
||||
buildAutomarkSuggestionSummary,
|
||||
type AutomarkSuggestionContext,
|
||||
} from "./orderProfileForm.utils";
|
||||
@@ -193,6 +197,7 @@ const documentCanvas = ref<{
|
||||
zoomOut: () => void;
|
||||
resetZoom: () => void;
|
||||
captureRegion: (region: OrderProfileRelativeRegion) => string | null;
|
||||
scrollRegionIntoView?: (regionId: string) => void;
|
||||
} | null>(null);
|
||||
const previewState = ref<"idle" | "updating" | "ready" | "failed">("idle");
|
||||
const canvasUnavailable = ref(false);
|
||||
@@ -214,7 +219,7 @@ const documentAnchorNotice = ref('');
|
||||
const history = ref<OrderProfileCanvasRegion[][]>([]);
|
||||
const future = ref<OrderProfileCanvasRegion[][]>([]);
|
||||
const editLeaseToken = ref<string | null>(null);
|
||||
const editorSessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
|
||||
const editorSessionId = String(route.query.editorSessionId || '').trim() || createRandomUuid();
|
||||
const compactEditor = ref(false);
|
||||
const saveState = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
|
||||
@@ -506,9 +511,42 @@ const headerFields = computed<ShippingOrderFieldConfig[]>(
|
||||
) || [],
|
||||
);
|
||||
const pageRegions = computed(() =>
|
||||
regions.value.filter((item) => item.pageNo === pageNo.value),
|
||||
regions.value.filter((item) => Number(item.pageNo) === Number(pageNo.value)),
|
||||
);
|
||||
/** 草稿中全部未绑定订单字段框(跨页);发布硬门禁同源,编辑时强制列出。 */
|
||||
const unboundOrderFieldRegions = computed(() =>
|
||||
regions.value.filter((item) => isUnboundOrderFieldCanvasRegion(item)),
|
||||
);
|
||||
const activePageHasLines = computed(() => pageRegions.value.some((item) => item.kind === 'line'));
|
||||
|
||||
/**
|
||||
* 切到未绑定框所在页并选中,强制在画布上滚入视野以便删除。
|
||||
* 核心逻辑:先 selectPage 再设 selectedId,并请求画布 scrollRegionIntoView。
|
||||
*/
|
||||
async function focusUnboundOrderFieldRegion(regionId: string): Promise<void> {
|
||||
const target = unboundOrderFieldRegions.value.find((item) => item.id === regionId);
|
||||
if (!target) return;
|
||||
if (Number(target.pageNo) !== Number(pageNo.value)) {
|
||||
await selectPage(Number(target.pageNo));
|
||||
}
|
||||
selectedId.value = target.id;
|
||||
reservationIdRegionSelected.value = false;
|
||||
await nextTick();
|
||||
documentCanvas.value?.scrollRegionIntoView?.(target.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 一键删除全部未绑定订单字段框,避免签名空白区 12 个框只能逐个清。
|
||||
* 核心逻辑:checkpoint 后过滤 regions,保留已绑定与非 order_field 区域。
|
||||
*/
|
||||
function clearUnboundOrderFieldRegions(): void {
|
||||
if (!unboundOrderFieldRegions.value.length || saveState.value === 'readonly') return;
|
||||
checkpoint();
|
||||
const removed = new Set(unboundOrderFieldRegions.value.map((item) => item.id));
|
||||
regions.value = regions.value.filter((item) => !removed.has(item.id));
|
||||
if (selectedId.value && removed.has(selectedId.value)) selectedId.value = null;
|
||||
scheduleAutosave();
|
||||
}
|
||||
const ensureTableRegionSetting = (targetPageNo: number) => {
|
||||
tableRegionSettings[targetPageNo] ||= {
|
||||
visualEvidenceSource: null,
|
||||
@@ -546,7 +584,7 @@ const visualCanvas = computed<OrderProfileVisualCanvasAdapter>(() => {
|
||||
actions: coordinateCanvasActions.value,
|
||||
documentReady: Boolean(form.documentId && form.tableId),
|
||||
preview: pdfPreviewGrant.value,
|
||||
grant: previewPages.value?.pages.find((item) => item.page_no === pageNo.value) || null,
|
||||
grant: previewPages.value?.pages.find((item) => Number(item.page_no) === Number(pageNo.value)) || null,
|
||||
previewPagePath: valueAdapterKey.value === 'xfa_dataset'
|
||||
? `/api/admin/shipping-notice/order-document-profiles/${active.value?.id || 0}/pdf-preview`
|
||||
: `/api/admin/shipping-notice/order-document-profiles/${active.value?.id || 0}/preview-pages`,
|
||||
@@ -719,7 +757,23 @@ const deskCanvasReadonly = computed(() => visualCanvas.value.canvasReadonly);
|
||||
const deskCanvasWarningVisible = computed(() => visualCanvas.value.warningVisible);
|
||||
const deskCanvasWarningText = computed(() => visualCanvas.value.warningText || '');
|
||||
const onDeskCanvasRetry = () => visualCanvas.value.retryCanvas();
|
||||
const onDeskCanvasLoadFailed = () => visualCanvas.value.reportCanvasLoadFailed();
|
||||
/** 页图 token 失效时自动重签一批预览令牌,避免翻页后只能手动点「重试画布」。 */
|
||||
let previewReauthInFlight = false;
|
||||
const onDeskCanvasLoadFailed = async () => {
|
||||
if (previewReauthInFlight) {
|
||||
visualCanvas.value.reportCanvasLoadFailed();
|
||||
return;
|
||||
}
|
||||
previewReauthInFlight = true;
|
||||
try {
|
||||
await loadPages();
|
||||
canvasUnavailable.value = false;
|
||||
} catch {
|
||||
visualCanvas.value.reportCanvasLoadFailed();
|
||||
} finally {
|
||||
previewReauthInFlight = false;
|
||||
}
|
||||
};
|
||||
const deskCanvasCanRender = computed(() => visualCanvas.value.canRender);
|
||||
const deskCanvasRetryLabel = computed(() => visualCanvas.value.retryLabel);
|
||||
const onDeskAcceptSuggestion = () => visualCanvas.value.acceptSuggestion();
|
||||
@@ -1767,7 +1821,7 @@ const save = async (automatic = false) => {
|
||||
expected_lock_version: existingProfile.lock_version,
|
||||
browser_session_id: editorSessionId,
|
||||
lease_token: editLeaseToken.value || '',
|
||||
operation_id: crypto.randomUUID(),
|
||||
operation_id: createRandomUuid(),
|
||||
...(adapterPayload.splitRuleConfirmationTokens
|
||||
? { split_rule_confirmation_tokens: adapterPayload.splitRuleConfirmationTokens }
|
||||
: {}),
|
||||
@@ -2086,7 +2140,7 @@ const decidePendingSuggestion = async (decision: 'accepted' | 'accepted_adjusted
|
||||
await decideOrderDocumentProfileSuggestion(active.value.id, {
|
||||
suggestion_id: item.id, suggestion_checksum: item.checksum, suggestion_summary: item.summary, decision,
|
||||
adjustment_summary: adjustmentSummary,
|
||||
browser_session_id: editorSessionId, lease_token: editLeaseToken.value, operation_id: crypto.randomUUID(),
|
||||
browser_session_id: editorSessionId, lease_token: editLeaseToken.value, operation_id: createRandomUuid(),
|
||||
});
|
||||
if (decision !== 'rejected') {
|
||||
checkpoint();
|
||||
@@ -2336,9 +2390,11 @@ const schedulePreview = () => {
|
||||
* 签发当前样本的受控画布预览。
|
||||
* 核心逻辑:普通坐标 PDF 使用服务端 PDFium PNG,保证内嵌繁体字形一致;只有显式
|
||||
* XFA datasets 模板才保留 PDF.js 原 PDF 渲染,以显示动态表单外观。
|
||||
* 不得把当前页强制打回第 1 页,否则第 2 页未绑定框会从画布过滤掉只剩顶部横幅。
|
||||
*/
|
||||
const loadPages = async () => {
|
||||
if (!active.value || !form.documentId) return;
|
||||
const preferredPageNo = Math.max(1, Number(pageNo.value) || 1);
|
||||
try {
|
||||
if (valueAdapterKey.value === 'xfa_dataset') {
|
||||
previewPages.value = null;
|
||||
@@ -2347,13 +2403,15 @@ const loadPages = async () => {
|
||||
pdfPreviewGrant.value = null;
|
||||
previewPages.value = await authorizeOrderProfilePreviewPages(active.value.id, form.documentId);
|
||||
}
|
||||
pageNo.value = 1;
|
||||
pdfPageCount.value = previewPages.value?.page_count || 1;
|
||||
const pageCount = Math.max(1, Number(previewPages.value?.page_count) || pdfPageCount.value || 1);
|
||||
pdfPageCount.value = pageCount;
|
||||
pageNo.value = Math.min(preferredPageNo, pageCount);
|
||||
canvasUnavailable.value = false;
|
||||
} catch {
|
||||
pdfPreviewGrant.value = null;
|
||||
previewPages.value = null;
|
||||
pdfPageCount.value = 1;
|
||||
pageNo.value = 1;
|
||||
canvasUnavailable.value = true;
|
||||
}
|
||||
};
|
||||
@@ -2374,14 +2432,15 @@ const reprocessCurrentSampleLayout = async (): Promise<void> => {
|
||||
reparsingLayout.value = false;
|
||||
}
|
||||
};
|
||||
/** PDF.js 已在内存中持有原件,切页只切换页码,避免消费新的预览令牌。 */
|
||||
/** PDF.js 已在内存中持有原件,切页只切换页码;PNG 页图由画布按页缓存,避免一次性 token 翻页失效。 */
|
||||
/** 切换 PDF 页时同步选择该页表格,使局部候选与当前标注页使用同一份坐标证据。 */
|
||||
const selectPage = async (nextPageNo: number) => {
|
||||
if (nextPageNo === pageNo.value) return;
|
||||
pageNo.value = nextPageNo;
|
||||
selectedId.value = null;
|
||||
canvasUnavailable.value = false;
|
||||
// 翻页只改变当前页预览表,模板主表仍由 mainTableId 单独冻结。
|
||||
const pageTable = sampleTables.value.find((item) => item.page_no === nextPageNo);
|
||||
const pageTable = sampleTables.value.find((item) => Number(item.page_no) === Number(nextPageNo));
|
||||
form.tableId = pageTable?.table_id || '';
|
||||
await refreshOrderFieldSuggestionValues();
|
||||
};
|
||||
@@ -2567,7 +2626,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
}];
|
||||
}),
|
||||
...(definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
|
||||
const pageNo = item.page_scope === "exact_page" ? item.page_no || 1 : 1;
|
||||
const regionPageNo = item.page_scope === "exact_page" ? Number(item.page_no) || 1 : 1;
|
||||
if (!item.anchor?.region || !item.absolute_value_region) {
|
||||
return [{
|
||||
id: `unbound-${item.layout_id}`,
|
||||
@@ -2575,7 +2634,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
label: item.label,
|
||||
region: item.fallback_value_region || { x0: .1, y0: .1, x1: .2, y1: .15 },
|
||||
fieldCode: null,
|
||||
pageNo,
|
||||
pageNo: regionPageNo,
|
||||
}];
|
||||
}
|
||||
const anchor = item.anchor.region;
|
||||
@@ -2585,7 +2644,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
label: item.anchor.text,
|
||||
region: anchor,
|
||||
orderFieldId: item.layout_id,
|
||||
pageNo,
|
||||
pageNo: regionPageNo,
|
||||
}, {
|
||||
id: `unbound-${item.layout_id}`,
|
||||
kind: "order_field" as const,
|
||||
@@ -2596,7 +2655,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
fieldCode: null,
|
||||
orderFieldId: item.layout_id,
|
||||
valueMode: item.value_mode,
|
||||
pageNo,
|
||||
pageNo: regionPageNo,
|
||||
}];
|
||||
}),
|
||||
...(definition.order_field_layouts || []).filter((item) => !item.anchor).map((item) => ({
|
||||
@@ -2700,7 +2759,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
const acquireEditLease = async (profileId: number): Promise<void> => {
|
||||
const lease = await acquireOrderDocumentProfileEditLease(profileId, {
|
||||
browser_session_id: editorSessionId,
|
||||
operation_id: crypto.randomUUID(),
|
||||
operation_id: createRandomUuid(),
|
||||
});
|
||||
editLeaseToken.value = lease.lease_token;
|
||||
startLeaseRenewal();
|
||||
@@ -2716,7 +2775,7 @@ const renewEditLease = async (): Promise<void> => {
|
||||
const lease = await renewOrderDocumentProfileEditLease(active.value.id, {
|
||||
browser_session_id: editorSessionId,
|
||||
lease_token: editLeaseToken.value,
|
||||
operation_id: crypto.randomUUID(),
|
||||
operation_id: createRandomUuid(),
|
||||
});
|
||||
editLeaseToken.value = lease.lease_token;
|
||||
} catch (error) {
|
||||
@@ -2805,8 +2864,24 @@ const edit = async (profile: ShippingOrderDocumentProfile) => {
|
||||
form.tableId = visualTableId;
|
||||
pageNo.value = sampleTables.value.find((item) => item.table_id === visualTableId)?.page_no || pageNo.value;
|
||||
}
|
||||
// 未绑定订单字段常落在签名页;优先停在含未绑定框的页,再签发预览(loadPages 必须保留该页码)。
|
||||
const firstUnbound = unboundOrderFieldRegions.value[0];
|
||||
if (
|
||||
firstUnbound
|
||||
&& !unboundOrderFieldRegions.value.some((item) => Number(item.pageNo) === Number(pageNo.value))
|
||||
) {
|
||||
pageNo.value = Number(firstUnbound.pageNo) || pageNo.value;
|
||||
}
|
||||
await refreshAutomarkSampleReadiness();
|
||||
await loadPages();
|
||||
// loadPages 保留 preferred 页;若预览页数更短则已钳制。再确保未绑定页仍可见。
|
||||
if (
|
||||
firstUnbound
|
||||
&& !unboundOrderFieldRegions.value.some((item) => Number(item.pageNo) === Number(pageNo.value))
|
||||
&& Number(firstUnbound.pageNo) <= Number(pdfPageCount.value)
|
||||
) {
|
||||
pageNo.value = Number(firstUnbound.pageNo);
|
||||
}
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
} finally {
|
||||
@@ -2887,7 +2962,7 @@ const recoverEditLease = async (confirmTakeover = false) => {
|
||||
try {
|
||||
const lease = await acquireOrderDocumentProfileEditLease(active.value.id, {
|
||||
browser_session_id: editorSessionId,
|
||||
operation_id: crypto.randomUUID(),
|
||||
operation_id: createRandomUuid(),
|
||||
confirm_takeover: confirmTakeover,
|
||||
});
|
||||
editLeaseToken.value = lease.lease_token;
|
||||
@@ -3050,7 +3125,7 @@ onBeforeUnmount(() => {
|
||||
void releaseOrderDocumentProfileEditLease(active.value.id, {
|
||||
browser_session_id: editorSessionId,
|
||||
lease_token: editLeaseToken.value,
|
||||
operation_id: crypto.randomUUID(),
|
||||
operation_id: createRandomUuid(),
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -3167,6 +3242,40 @@ onBeforeUnmount(() => {
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section
|
||||
v-if="unboundOrderFieldRegions.length"
|
||||
class="unbound-regions-banner"
|
||||
:aria-label="t('admin.shippingOrderProfiles.workbench.unboundRegionsBannerAria')"
|
||||
>
|
||||
<div class="unbound-regions-banner__heading">
|
||||
<p>
|
||||
{{ t('admin.shippingOrderProfiles.workbench.unboundRegionsBanner', { count: unboundOrderFieldRegions.length }) }}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-secondary unbound-regions-banner__clear"
|
||||
:disabled="saveState === 'readonly'"
|
||||
@click="clearUnboundOrderFieldRegions"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.workbench.clearUnboundRegions') }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="unbound-regions-banner__list">
|
||||
<button
|
||||
v-for="region in unboundOrderFieldRegions"
|
||||
:key="region.id"
|
||||
type="button"
|
||||
class="unbound-regions-banner__item"
|
||||
:class="{ active: selectedId === region.id }"
|
||||
@click="() => void focusUnboundOrderFieldRegion(region.id)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.workbench.unboundRegionChip', {
|
||||
page: region.pageNo,
|
||||
label: region.label,
|
||||
}) }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
<OrderProfileDocumentCanvas
|
||||
v-if="deskCanvasCanRender"
|
||||
ref="documentCanvas"
|
||||
@@ -4207,6 +4316,49 @@ onBeforeUnmount(() => {
|
||||
.editor-workbench .config { max-height: calc(100vh - 5rem); overflow-y: auto; }
|
||||
.editor-bottom-drawer { max-width: none; border-top: 1px solid #334155; background: #f8fafc; }
|
||||
.automark-status-panel { position: sticky; top: .5rem; z-index: 6; display: grid; gap: .65rem; margin: 0 0 .75rem; border: 1px solid #7dd3fc; border-radius: .45rem; background: #f0f9ff; padding: .75rem .9rem; color: #164e63; box-shadow: 0 8px 20px rgb(14 116 144 / .12); }
|
||||
.unbound-regions-banner {
|
||||
position: sticky;
|
||||
top: .5rem;
|
||||
z-index: 6;
|
||||
display: grid;
|
||||
gap: .55rem;
|
||||
margin: 0 0 .75rem;
|
||||
border: 1px solid #f59e0b;
|
||||
border-radius: .45rem;
|
||||
background: #fffbeb;
|
||||
padding: .75rem .9rem;
|
||||
color: #92400e;
|
||||
box-shadow: 0 8px 20px rgb(180 83 9 / .12);
|
||||
}
|
||||
.unbound-regions-banner p { margin: 0; font-size: .8rem; font-weight: 650; }
|
||||
.unbound-regions-banner__heading {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: .55rem;
|
||||
}
|
||||
.unbound-regions-banner__clear { min-height: 1.9rem; padding-inline: .7rem; font-size: .72rem; }
|
||||
.unbound-regions-banner__list { display: flex; flex-wrap: wrap; gap: .4rem; }
|
||||
.unbound-regions-banner__item {
|
||||
display: inline-flex;
|
||||
max-width: 100%;
|
||||
min-height: 1.8rem;
|
||||
align-items: center;
|
||||
border: 1px solid #d97706;
|
||||
border-radius: .35rem;
|
||||
background: #fff7ed;
|
||||
padding: .2rem .55rem;
|
||||
color: #9a3412;
|
||||
font-size: .72rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.unbound-regions-banner__item:hover,
|
||||
.unbound-regions-banner__item.active {
|
||||
border-color: #b45309;
|
||||
background: #fdba74;
|
||||
color: #7c2d12;
|
||||
}
|
||||
.automark-status-panel__heading { display: flex; align-items: flex-start; justify-content: space-between; gap: .75rem; }
|
||||
.automark-status-panel__heading strong { display: block; color: #0c4a6e; font-size: .82rem; }
|
||||
.automark-status-panel__heading p { margin: .2rem 0 0; color: #475569; font-size: .75rem; }
|
||||
|
||||
+5
-4
@@ -10,6 +10,7 @@ import { useRoute, useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { createRandomUuid } from '@/shared/utils/id';
|
||||
import {
|
||||
acquireOrderDocumentProfileEditLease,
|
||||
confirmOrderProfilePublishCheck,
|
||||
@@ -31,7 +32,7 @@ const runs = ref<OrderProfileValidationRun[]>([]);
|
||||
const report = ref<OrderProfilePublishCheckReport | null>(null);
|
||||
const confirmed = ref<string[]>([]);
|
||||
const busy = ref(false);
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || createRandomUuid();
|
||||
const leaseToken = ref('');
|
||||
|
||||
const validationRun = computed(() => runs.value.find((item) => item.run_type === 'current_sample' && item.status === 'passed') || null);
|
||||
@@ -92,7 +93,7 @@ async function ensureLease(): Promise<boolean> {
|
||||
try {
|
||||
leaseToken.value = (await acquireOrderDocumentProfileEditLease(profileId, {
|
||||
browser_session_id: sessionId,
|
||||
operation_id: crypto.randomUUID(),
|
||||
operation_id: createRandomUuid(),
|
||||
})).lease_token;
|
||||
return true;
|
||||
} catch (error) {
|
||||
@@ -121,7 +122,7 @@ async function createReport(): Promise<void> {
|
||||
overlap_validation_run_id: overlapRun.value?.id,
|
||||
browser_session_id: sessionId,
|
||||
lease_token: leaseToken.value,
|
||||
operation_id: crypto.randomUUID(),
|
||||
operation_id: createRandomUuid(),
|
||||
});
|
||||
confirmed.value = [];
|
||||
await loadRuns();
|
||||
@@ -141,7 +142,7 @@ async function publish(): Promise<void> {
|
||||
confirmed_warning_keys: confirmed.value,
|
||||
browser_session_id: sessionId,
|
||||
lease_token: leaseToken.value,
|
||||
operation_id: crypto.randomUUID(),
|
||||
operation_id: createRandomUuid(),
|
||||
});
|
||||
await router.replace({
|
||||
name: 'AdminShippingOrderDocumentProfileVersionDetail',
|
||||
|
||||
+4
-3
@@ -11,6 +11,7 @@ import { useRoute, useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { createRandomUuid } from '@/shared/utils/id';
|
||||
import { getShippingOrderSchemaVersion } from '@/features/admin/api/shipping-order-schema.api';
|
||||
import {
|
||||
acquireOrderDocumentProfileEditLease,
|
||||
@@ -42,7 +43,7 @@ const leaseToken = ref('');
|
||||
const profile = ref<ShippingOrderDocumentProfile | null>(null);
|
||||
const sample = ref<OrderProfileBoundSample | null>(null);
|
||||
const fieldNames = ref(new Map<string, string>());
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || createRandomUuid();
|
||||
const blindTestSuite = ref<OrderProfileTestSuite | null>(null);
|
||||
const validationEvidence = computed<OrderProfileValidationEvidence | null>(() => {
|
||||
const raw = sampleRun.value?.summary?.validation_evidence;
|
||||
@@ -206,7 +207,7 @@ async function ensureLease(): Promise<boolean> {
|
||||
if (leaseToken.value) return true;
|
||||
try {
|
||||
leaseToken.value = (await acquireOrderDocumentProfileEditLease(profileId, {
|
||||
browser_session_id: sessionId, operation_id: crypto.randomUUID(),
|
||||
browser_session_id: sessionId, operation_id: createRandomUuid(),
|
||||
})).lease_token;
|
||||
return true;
|
||||
} catch (error) { report(error); return false; }
|
||||
@@ -221,7 +222,7 @@ async function validateCurrentDraft(): Promise<void> {
|
||||
}
|
||||
executing.value = true;
|
||||
try {
|
||||
const payload = () => ({ browser_session_id: sessionId, lease_token: leaseToken.value, operation_id: crypto.randomUUID() });
|
||||
const payload = () => ({ browser_session_id: sessionId, lease_token: leaseToken.value, operation_id: createRandomUuid() });
|
||||
await runOrderProfileInstantCheck(profileId, payload());
|
||||
await runOrderProfileCurrentSample(profileId, { ...payload(), sample_binding_id: sample.value.id });
|
||||
await loadRuns();
|
||||
|
||||
+38
@@ -104,6 +104,44 @@ describe('OrderProfileDocumentCanvas PDF preview', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('force-highlights unbound order-field boxes on blank page imagery', async () => {
|
||||
const wrapper = mount(OrderProfileDocumentCanvas, {
|
||||
props: {
|
||||
profileId: 5,
|
||||
grant: { page_no: 2, preview_token: 'page-token' },
|
||||
previewPagePath: '/api/admin/shipping-notice/order-document-profiles/5/preview-pages',
|
||||
regions: [{
|
||||
id: 'unbound-order_field_2__1',
|
||||
kind: 'order_field',
|
||||
label: 'Sign12 · 待绑定列 1',
|
||||
pageNo: 2,
|
||||
fieldCode: null,
|
||||
region: { x0: .02, y0: .89, x1: .15, y1: .92 },
|
||||
}],
|
||||
pageNo: 2,
|
||||
pageCount: 2,
|
||||
},
|
||||
global: {
|
||||
plugins: [createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: { shippingOrderProfiles: { workbench: { unbound: '待绑定', pagePreviewAlt: 'page' } } },
|
||||
},
|
||||
},
|
||||
})],
|
||||
},
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:未绑定框必须带 region--unbound,否则签名空白底图上看不见。
|
||||
const region = wrapper.find('.region--unbound');
|
||||
expect(region.exists()).toBe(true);
|
||||
expect(region.classes()).toContain('region-order_field');
|
||||
expect(region.attributes('aria-label')).toContain('待绑定');
|
||||
});
|
||||
|
||||
it('captures the selected XFA appearance from the unscaled PDF.js canvas', async () => {
|
||||
const drawImage = vi.fn();
|
||||
const toDataURL = vi.fn(() => 'data:image/png;base64,canvas-crop');
|
||||
|
||||
+140
-21
@@ -1,8 +1,10 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue
|
||||
用途:展示受控 PDF/XFA flatten 单页预览,并以相对坐标框支持选择、拖动和缩放区域。
|
||||
依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion。
|
||||
依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion、isUnboundOrderFieldCanvasRegion。
|
||||
逻辑:父级签发单页令牌并提供分页动作;mode=readonly 时只允许查看/缩放/切页,不允许写入任何标注改动;
|
||||
PNG 预览 token 为一次性消费,组件内按页缓存 blob,翻页回访不再重新拉 token;
|
||||
未绑定订单字段框强制高亮(region--unbound),并暴露 scrollRegionIntoView 供横幅定位删除;
|
||||
画布区域 aria-label 走四语言 i18n;可选 emptyHint/loadError 区分 XFA page_unavailable 与 PDF 缺样本空态。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
@@ -11,6 +13,7 @@ import { useI18n } from 'vue-i18n';
|
||||
import { Anchor, ArrowLeft, ArrowRight, Columns3, Copy, Eraser, MessageSquareText, Minus, Plus, Redo2, RotateCcw, Rows3, Save, TableProperties, Tag, TextCursorInput, Trash2, WandSparkles } from 'lucide-vue-next';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { OrderProfileCanvasRegion, OrderProfilePreviewPageGrant } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { isUnboundOrderFieldCanvasRegion } from '../orderProfileForm.utils';
|
||||
import type { PDFDocumentProxy } from 'pdfjs-dist';
|
||||
|
||||
type PdfJsModule = typeof import('pdfjs-dist');
|
||||
@@ -98,6 +101,10 @@ const internalLoadError = ref<string | null>(null);
|
||||
const canvas = ref<HTMLElement | null>(null);
|
||||
const viewport = ref<HTMLElement | null>(null);
|
||||
const zoom = ref(1);
|
||||
/** 按页缓存已消费 token 拉取的 PNG,翻页回访不再触发一次性 token 失效。 */
|
||||
const pageImageCache = new Map<string, string>();
|
||||
let loadGeneration = 0;
|
||||
let cachedProfileId: number | null = null;
|
||||
const zoomPercent = computed(() => Math.round(zoom.value * 100));
|
||||
const pageInput = ref(props.pageNo);
|
||||
type ResizeHandle = 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'nw';
|
||||
@@ -132,26 +139,69 @@ const renderPdfPage = async (pdf: PDFDocumentProxy) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* 下载一次性 PNG 并在组件卸载或切页时回收浏览器 blob。
|
||||
* 核心逻辑:失败时写入 internalLoadError 并 emit loadFailed,避免误导为「未绑定样本」。
|
||||
* 回收某次会话内全部页图 blob;切换样本 Profile 或卸载时调用。
|
||||
*/
|
||||
const clearPageImageCache = () => {
|
||||
for (const url of pageImageCache.values()) URL.revokeObjectURL(url);
|
||||
pageImageCache.clear();
|
||||
inflightPageLoads.clear();
|
||||
};
|
||||
|
||||
/** 同一页的并发拉取共用一个 Promise,成功后必入缓存(即使请求已过期)。 */
|
||||
const inflightPageLoads = new Map<string, Promise<string>>();
|
||||
|
||||
/**
|
||||
* 拉取单页 PNG;命中缓存或 in-flight 时不重复请求。
|
||||
*/
|
||||
const fetchPageImage = async (
|
||||
previewPath: string,
|
||||
grant: { page_no: number; preview_token: string },
|
||||
): Promise<string> => {
|
||||
const cacheKey = String(grant.page_no);
|
||||
const cached = pageImageCache.get(cacheKey);
|
||||
if (cached) return cached;
|
||||
const inflight = inflightPageLoads.get(cacheKey);
|
||||
if (inflight) return inflight;
|
||||
const pending = (async () => {
|
||||
const response = await fetch(
|
||||
`${previewPath}/${grant.page_no}?preview_token=${encodeURIComponent(grant.preview_token)}`,
|
||||
{ headers: getAuthHeaders(), cache: 'no-store' },
|
||||
);
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const blobUrl = URL.createObjectURL(await response.blob());
|
||||
pageImageCache.set(cacheKey, blobUrl);
|
||||
return blobUrl;
|
||||
})().finally(() => {
|
||||
inflightPageLoads.delete(cacheKey);
|
||||
});
|
||||
inflightPageLoads.set(cacheKey, pending);
|
||||
return pending;
|
||||
};
|
||||
|
||||
/**
|
||||
* 下载页 PNG;同页再次展示走缓存。后端 grant 在 TTL 内可重复 get,缓存作防御性加速。
|
||||
* 核心逻辑:generation 守卫丢掉过期 UI 更新;页图本身仍保留在 cache 供回访。
|
||||
*/
|
||||
const loadPage = async () => {
|
||||
if (!props.profileId || (!props.grant && !props.pdfPreview)) {
|
||||
URL.revokeObjectURL(imageUrl.value);
|
||||
const generation = ++loadGeneration;
|
||||
if (cachedProfileId !== props.profileId) {
|
||||
clearPageImageCache();
|
||||
cachedProfileId = props.profileId;
|
||||
}
|
||||
if (!props.profileId || (!props.grant && !props.pdfPreview)) {
|
||||
imageUrl.value = '';
|
||||
pdfRendered.value = false;
|
||||
pdfRendered.value = false;
|
||||
internalLoadError.value = null;
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
URL.revokeObjectURL(imageUrl.value);
|
||||
imageUrl.value = '';
|
||||
pdfRendered.value = false;
|
||||
pdfRendered.value = false;
|
||||
internalLoadError.value = null;
|
||||
try {
|
||||
const previewPath = props.previewPagePath
|
||||
|| `/api/admin/shipping-notice/order-document-profiles/${props.profileId}/preview-pages`;
|
||||
if (props.pdfPreview) {
|
||||
imageUrl.value = '';
|
||||
const response = await fetch(
|
||||
`${previewPath}?preview_token=${encodeURIComponent(props.pdfPreview.preview_token)}`,
|
||||
{ headers: getAuthHeaders(), cache: 'no-store' },
|
||||
@@ -160,31 +210,38 @@ const loadPage = async () => {
|
||||
const pdfjs = await loadPdfJs();
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
pdfDocument = await pdfjs.getDocument({ data: bytes, enableXfa: true }).promise;
|
||||
if (generation !== loadGeneration) return;
|
||||
emit('pageCount', pdfDocument.numPages);
|
||||
await renderPdfPage(pdfDocument);
|
||||
return;
|
||||
}
|
||||
const grant = props.grant;
|
||||
if (!grant) throw new Error('PDF preview grant is unavailable');
|
||||
const response = await fetch(
|
||||
`${previewPath}/${grant.page_no}?preview_token=${encodeURIComponent(grant.preview_token)}`,
|
||||
{ headers: getAuthHeaders(), cache: 'no-store' },
|
||||
);
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
imageUrl.value = URL.createObjectURL(await response.blob());
|
||||
const blobUrl = await fetchPageImage(previewPath, grant);
|
||||
if (generation !== loadGeneration) return;
|
||||
imageUrl.value = blobUrl;
|
||||
} catch {
|
||||
if (generation !== loadGeneration) return;
|
||||
const fallback = props.grant ? pageImageCache.get(String(props.grant.page_no)) : null;
|
||||
if (fallback) {
|
||||
imageUrl.value = fallback;
|
||||
internalLoadError.value = null;
|
||||
return;
|
||||
}
|
||||
imageUrl.value = '';
|
||||
internalLoadError.value = t('admin.shippingOrderProfiles.workbench.canvasUnavailable');
|
||||
emit('loadFailed');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
if (generation === loadGeneration) loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 用户点击画布重试:清除内部错误并通知父级。
|
||||
* 用户点击画布重试:清除内部错误并通知父级重新签发页令牌。
|
||||
*/
|
||||
const onRetryClick = () => {
|
||||
internalLoadError.value = null;
|
||||
clearPageImageCache();
|
||||
emit('retry');
|
||||
};
|
||||
|
||||
@@ -282,6 +339,10 @@ const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
|
||||
}
|
||||
return region.label;
|
||||
}
|
||||
// 未绑定框不拼「样本值不可用」,改用明确的待绑定徽标,避免与空白底图混淆。
|
||||
if (isUnboundOrderFieldCanvasRegion(region)) {
|
||||
return `${region.label} · ${t('admin.shippingOrderProfiles.workbench.unbound')}`;
|
||||
}
|
||||
const state = props.orderFieldValueState || 'idle';
|
||||
const value = region.fieldCode ? props.orderFieldValues?.[region.fieldCode] : null;
|
||||
const suffix = state === 'loading'
|
||||
@@ -321,8 +382,33 @@ const captureRegion = (region: OrderProfileCanvasRegion['region']): string | nul
|
||||
crop.getContext('2d')?.drawImage(source, x, y, clippedWidth, clippedHeight, 0, 0, clippedWidth, clippedHeight);
|
||||
return crop.toDataURL('image/png');
|
||||
};
|
||||
defineExpose({ zoomIn: () => adjustZoom(.25), zoomOut: () => adjustZoom(-.25), resetZoom, captureRegion });
|
||||
watch(() => [props.grant?.preview_token, props.pdfPreview?.preview_token], () => { void loadPage(); }, { immediate: true });
|
||||
defineExpose({
|
||||
zoomIn: () => adjustZoom(.25),
|
||||
zoomOut: () => adjustZoom(-.25),
|
||||
resetZoom,
|
||||
captureRegion,
|
||||
/**
|
||||
* 将指定区域滚入画布视口中央,供未绑定框定位删除。
|
||||
* @param regionId - 画布区域 id。
|
||||
*/
|
||||
scrollRegionIntoView: (regionId: string) => {
|
||||
const viewportEl = viewport.value;
|
||||
const target = canvas.value?.querySelector(`[data-region-id="${CSS.escape(regionId)}"]`) as HTMLElement | null;
|
||||
if (!viewportEl || !target) return;
|
||||
const viewportRect = viewportEl.getBoundingClientRect();
|
||||
const targetRect = target.getBoundingClientRect();
|
||||
const nextTop = viewportEl.scrollTop + (targetRect.top - viewportRect.top)
|
||||
- (viewportRect.height / 2) + (targetRect.height / 2);
|
||||
const nextLeft = viewportEl.scrollLeft + (targetRect.left - viewportRect.left)
|
||||
- (viewportRect.width / 2) + (targetRect.width / 2);
|
||||
viewportEl.scrollTo({
|
||||
top: Math.max(0, nextTop),
|
||||
left: Math.max(0, nextLeft),
|
||||
behavior: 'smooth',
|
||||
});
|
||||
},
|
||||
});
|
||||
watch(() => [props.grant?.page_no, props.grant?.preview_token, props.pdfPreview?.preview_token], () => { void loadPage(); }, { immediate: true });
|
||||
watch(() => props.pageNo, async (value) => {
|
||||
pageInput.value = value;
|
||||
if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument);
|
||||
@@ -330,7 +416,13 @@ watch(() => props.pageNo, async (value) => {
|
||||
watch(zoom, async () => {
|
||||
if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument);
|
||||
});
|
||||
onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(imageUrl.value); });
|
||||
onBeforeUnmount(() => {
|
||||
endMove();
|
||||
endPan();
|
||||
endCreation();
|
||||
clearPageImageCache();
|
||||
imageUrl.value = '';
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -409,7 +501,16 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
role="button"
|
||||
tabindex="0"
|
||||
class="region"
|
||||
:class="[`region-${region.kind}`, { selected: selected.has(region.id), 'region-preview': region.isPreview }, region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '']"
|
||||
:data-region-id="region.id"
|
||||
:class="[
|
||||
`region-${region.kind}`,
|
||||
{
|
||||
selected: selected.has(region.id),
|
||||
'region-preview': region.isPreview,
|
||||
'region--unbound': isUnboundOrderFieldCanvasRegion(region),
|
||||
},
|
||||
region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '',
|
||||
]"
|
||||
:style="{ left: `${region.region.x0 * 100}%`, top: `${region.region.y0 * 100}%`, width: `${(region.region.x1 - region.region.x0) * 100}%`, height: `${(region.region.y1 - region.region.y0) * 100}%` }"
|
||||
:aria-label="displayRegionLabel(region)"
|
||||
@pointerdown.stop="beginDrag($event, region, 'move')"
|
||||
@@ -502,6 +603,24 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
.region-header_field .region-label, .region-header_field .resize-handle { background: #b45309; }
|
||||
.region-order_field { z-index: 2; border: 1.5px solid #22c55e; background: rgb(34 197 94 / .08); }
|
||||
.region-order_field .region-label, .region-order_field .resize-handle { background: #15803d; }
|
||||
/* 未绑定订单字段:底图常为空白(如签名控件),必须用高对比框强制可见。 */
|
||||
.region--unbound {
|
||||
z-index: 6;
|
||||
min-width: 14px;
|
||||
min-height: 14px;
|
||||
border: 2.5px solid #d97706;
|
||||
background: rgb(245 158 11 / .42);
|
||||
box-shadow: 0 0 0 2px rgb(255 255 255 / .95), 0 0 14px rgb(245 158 11 / .75);
|
||||
}
|
||||
.region--unbound .region-label {
|
||||
top: 0;
|
||||
left: 0;
|
||||
max-width: 100%;
|
||||
border-radius: 0;
|
||||
background: #b45309;
|
||||
white-space: normal;
|
||||
}
|
||||
.region--unbound .resize-handle { background: #b45309; }
|
||||
.region-order_anchor { z-index: 2; border: 1.5px solid #a855f7; background: rgb(168 85 247 / .08); }
|
||||
.region-order_anchor .region-label, .region-order_anchor .resize-handle { background: #7e22ce; }
|
||||
.region-document_anchor_label { z-index: 2; border: 1.5px solid #0ea5e9; background: rgb(14 165 233 / .1); }
|
||||
|
||||
+3
-1
@@ -10,6 +10,7 @@ import { computed, onMounted, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { createRandomUuid } from '@/shared/utils/id';
|
||||
import {
|
||||
previewOrderProfileSampleXfaSplitRules,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
@@ -97,9 +98,10 @@ const showUnsavedConfirmBanner = computed(() => (
|
||||
|
||||
/**
|
||||
* 生成 seg-/rule-/stage- 前缀的客户端 UUID(无连字符)。
|
||||
* HTTP 非安全上下文亦可用(经 createRandomUuid 降级)。
|
||||
*/
|
||||
function newClientId(prefix: 'seg' | 'rule' | 'stage'): string {
|
||||
return `${prefix}-${crypto.randomUUID().replace(/-/g, '')}`;
|
||||
return `${prefix}-${createRandomUuid().replace(/-/g, '')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+6
-2
@@ -75,7 +75,8 @@ export function useOrderProfileValueAdapter(options: UseOrderProfileValueAdapter
|
||||
const profileId = computed(() => Number(toValue(options.profileId) || 0));
|
||||
const saveState = computed(() => toValue(options.saveState));
|
||||
const readonly = computed(() => saveState.value === 'readonly');
|
||||
const loading = ref(true);
|
||||
// 坐标模板不会启用该 adapter;初始状态必须是非加载,避免共享画布误显示 XFA loading。
|
||||
const loading = ref(false);
|
||||
const loadError = ref(false);
|
||||
const lockVersion = ref(0);
|
||||
const schemaFields = ref<ShippingOrderFieldConfig[]>([]);
|
||||
@@ -977,7 +978,10 @@ export function useOrderProfileValueAdapter(options: UseOrderProfileValueAdapter
|
||||
const enabled = computed(() => toValue(options.enabled) !== false);
|
||||
|
||||
watch(enabled, (isEnabled) => {
|
||||
if (isEnabled && profileId.value > 0) void load();
|
||||
if (isEnabled && profileId.value > 0) {
|
||||
loading.value = true;
|
||||
void load();
|
||||
}
|
||||
}, { immediate: true });
|
||||
|
||||
watch(diagnosticsOpen, async (open) => {
|
||||
|
||||
+8
@@ -29,10 +29,18 @@ import {
|
||||
toOrderProfileHeaderFieldRegion,
|
||||
resolveCoordinateFieldScope,
|
||||
isOrderProfileVisualFieldEligible,
|
||||
isUnboundOrderFieldCanvasRegion,
|
||||
buildAutomarkSuggestionSummary,
|
||||
} from './orderProfileForm.utils';
|
||||
|
||||
describe('order profile form rules', () => {
|
||||
it('marks order fields without fieldCode as unbound for forced canvas display', () => {
|
||||
// 关键断言:无 Schema 绑定的订单字段框必须被识别,供画布高亮与发布前横幅共用。
|
||||
expect(isUnboundOrderFieldCanvasRegion({ kind: 'order_field', fieldCode: null })).toBe(true);
|
||||
expect(isUnboundOrderFieldCanvasRegion({ kind: 'order_field', fieldCode: 'currency' })).toBe(false);
|
||||
expect(isUnboundOrderFieldCanvasRegion({ kind: 'header_field', fieldCode: null })).toBe(false);
|
||||
});
|
||||
|
||||
it('restores a Reservation ID region from a Vue reactive profile without structured-clone failure', () => {
|
||||
const persisted = reactive({
|
||||
region: { x0: .05, y0: .71, x1: .28, y1: .73 },
|
||||
|
||||
+13
-1
@@ -2,7 +2,8 @@
|
||||
* features/admin/modules/shipping-order-document-profiles/orderProfileForm.utils.ts
|
||||
* 用途:构造可视化订单模板的白名单列规则、明细字段分组,并控制样本表格配置区的安全显示。
|
||||
* 依赖:订单 Profile DTO。
|
||||
* 逻辑:页面状态只允许 direct 或已注册复合解析器;同一目标字段跨列只能出现一次。
|
||||
* 逻辑:页面状态只允许 direct 或已注册复合解析器;同一目标字段跨列只能出现一次;
|
||||
* 另提供「未绑定订单字段」判定,供画布强制高亮与编辑横幅共用。
|
||||
*/
|
||||
|
||||
import type {
|
||||
@@ -39,6 +40,17 @@ export const isOrderProfileVisualFieldEligible = (
|
||||
&& (usesExternalValueSource || Boolean(field.allowed_sources?.includes('pdf_coordinate')))
|
||||
);
|
||||
|
||||
/**
|
||||
* 判断画布区域是否为「未绑定 Schema 字段」的订单字段框。
|
||||
* 核心逻辑:仅 order_field 且无 fieldCode 视为未绑定;这些框会写入
|
||||
* draft_unbound_order_field_layouts 并在发布时硬阻断,必须在画布强制可见。
|
||||
* @param region - 画布区域。
|
||||
* @returns 是否需要未绑定高亮与横幅列出。
|
||||
*/
|
||||
export const isUnboundOrderFieldCanvasRegion = (
|
||||
region: Pick<OrderProfileCanvasRegion, 'kind' | 'fieldCode'>,
|
||||
): boolean => region.kind === 'order_field' && !region.fieldCode;
|
||||
|
||||
/**
|
||||
* 将画布中的视觉表头文字转换为 v2 字段区域。
|
||||
* 核心逻辑:视觉位置不是业务 scope;调用方必须按 Schema 传入 header/line,
|
||||
|
||||
+38
-1
@@ -2,7 +2,8 @@
|
||||
* features/admin/modules/shipping-order-document-profiles/orderProfileReadonlyCanvas.utils.spec.ts
|
||||
* 用途:验证版本只读画布完整恢复模板定义中的诊断区域。
|
||||
* 依赖:Vitest、orderProfileReadonlyCanvas.utils。
|
||||
* 逻辑:已发布版本的必需锚点必须同时显示标签框和值框,且区域 ID 与冻结诊断接口一致。
|
||||
* 逻辑:已发布版本的必需锚点必须同时显示标签框和值框,且区域 ID 与冻结诊断接口一致;
|
||||
* 仅含 fallback 的未绑定订单字段框也必须恢复,供签名空白区强制可见。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
@@ -40,4 +41,40 @@ describe('buildOrderProfileReadonlyRegions', () => {
|
||||
expect.objectContaining({ id: 'plant_address_value', kind: 'document_anchor_value', configuredValue: 'No. 88' }),
|
||||
]));
|
||||
});
|
||||
|
||||
it('restores fallback-only unbound order fields so blank signature areas stay visible', () => {
|
||||
const profile = {
|
||||
definition: {
|
||||
document_match: { required_anchors: [], optional_anchors: [] },
|
||||
table_regions: [],
|
||||
order_field_layouts: [],
|
||||
draft_unbound_order_field_layouts: [{
|
||||
layout_id: 'order_field_2__1',
|
||||
label: 'Sign12 · 待绑定列 1',
|
||||
page_scope: 'exact_page',
|
||||
page_no: 2,
|
||||
anchor: null,
|
||||
absolute_value_region: null,
|
||||
fallback_value_region: { x0: .02, y0: .89, x1: .15, y1: .92 },
|
||||
value_mode: 'single_line',
|
||||
stop_anchors: [],
|
||||
minimum_evidence_level: 'coordinate',
|
||||
}],
|
||||
},
|
||||
} as unknown as ShippingOrderDocumentProfile;
|
||||
|
||||
const regions = buildOrderProfileReadonlyRegions(profile);
|
||||
|
||||
// 关键断言:无 anchor/absolute 时仍用 fallback 恢复未绑定框,否则签名空白区会漏展示。
|
||||
expect(regions).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
id: 'unbound-order_field_2__1',
|
||||
kind: 'order_field',
|
||||
fieldCode: null,
|
||||
pageNo: 2,
|
||||
label: 'Sign12 · 待绑定列 1',
|
||||
region: { x0: .02, y0: .89, x1: .15, y1: .92 },
|
||||
}),
|
||||
]));
|
||||
});
|
||||
});
|
||||
+1
@@ -85,6 +85,7 @@ export const buildOrderProfileReadonlyRegions = (
|
||||
}),
|
||||
...(definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
|
||||
const pageNo = pageNoOf(item.page_scope, item.page_no);
|
||||
// 仅有 fallback 的未绑定框也必须恢复;签名区底图常空白,缺框会导致发布前无法发现。
|
||||
if (!item.anchor?.region || !item.absolute_value_region) {
|
||||
return [{
|
||||
id: `unbound-${item.layout_id}`,
|
||||
|
||||
+2
-278
@@ -3,7 +3,7 @@
|
||||
用途:单一发货订单 Schema 的版本采用与版本级识别规则编辑;字段身份由全局字段资产库维护。
|
||||
依赖:shipping-order-schema.api、shipping-field-assets.api、FieldImpactDrawer、版本/审计抽屉组件、Vue I18n。
|
||||
逻辑:左侧勾选采用资产目录,右侧编辑已采用字段规则;草稿保存/发布与历史追溯由服务端冻结。无多族切换。
|
||||
「Schema 级策略」分组收纳自动建单总开关与字段派生规则;仅草稿可改,随保存/发布生效;支持样本模拟。
|
||||
「Schema 级策略」仅收纳自动建单总开关;订单项次由系统按单据内顺序生成。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue';
|
||||
@@ -26,8 +26,6 @@ import {
|
||||
listShippingOrderSchemaVersions,
|
||||
publishShippingOrderSchemaDraft,
|
||||
saveShippingOrderSchemaDraft,
|
||||
simulateShippingOrderSchemaDerivation,
|
||||
listShippingOrderSchemaDerivationSimulateSamples,
|
||||
} from '@/features/admin/api/shipping-order-schema.api';
|
||||
import FieldImpactDrawer from '@/features/admin/modules/shipping-field-assets/components/FieldImpactDrawer.vue';
|
||||
import SchemaExtractionAuditDrawer from '@/features/admin/modules/shipping-order-schema/components/SchemaExtractionAuditDrawer.vue';
|
||||
@@ -36,9 +34,6 @@ import SchemaVersionHistoryDrawer from '@/features/admin/modules/shipping-order-
|
||||
import SchemaVersionUsageDrawer from '@/features/admin/modules/shipping-order-schema/components/SchemaVersionUsageDrawer.vue';
|
||||
import type { ShippingFieldAsset, ShippingFieldAssetImpact } from '@/features/admin/types/shipping-field-assets.types';
|
||||
import type {
|
||||
ShippingOrderDerivationRule,
|
||||
ShippingOrderDerivationSimulateResult,
|
||||
ShippingOrderDerivationSimulateSampleItem,
|
||||
ShippingOrderField,
|
||||
ShippingOrderFieldConfig,
|
||||
ShippingOrderExtractionAudit,
|
||||
@@ -75,20 +70,6 @@ const autoCreationConfirmOpen = ref(false);
|
||||
const pendingAutoCreationEnabled = ref(false);
|
||||
const changeNote = ref('');
|
||||
const selectedDraftFieldId = ref<string | null>(null);
|
||||
const derivationRules = ref<ShippingOrderDerivationRule[]>([]);
|
||||
const derivationPanelOpen = ref(true);
|
||||
const simulateOpen = ref(false);
|
||||
const simulating = ref(false);
|
||||
const simulateMode = ref<'history' | 'inline'>('history');
|
||||
const simulateSamples = ref<ShippingOrderDerivationSimulateSampleItem[]>([]);
|
||||
const simulateSampleRef = ref('');
|
||||
const simulateSamplesLoading = ref(false);
|
||||
const simulateSampleJson = ref(`[
|
||||
{"customer_po_line_no": "00010", "line_no": null},
|
||||
{"customer_po_line_no": "00020", "line_no": "20"},
|
||||
{"customer_po_line_no": "ABC", "line_no": null}
|
||||
]`);
|
||||
const simulateResult = ref<ShippingOrderDerivationSimulateResult | null>(null);
|
||||
const fieldSearch = ref('');
|
||||
const expandedGroups = reactive<Record<AdoptionGroupKey, boolean>>({
|
||||
headerStandard: true,
|
||||
@@ -271,19 +252,6 @@ const syncDraftFields = (): void => {
|
||||
autoCreationEnabled.value = typeof draftPolicy === 'boolean'
|
||||
? draftPolicy
|
||||
: state.value?.schema?.auto_creation_policy?.enabled === true;
|
||||
const sourceRules = draft.value?.definition?.derivation_rules
|
||||
|| published.value?.definition?.derivation_rules
|
||||
|| [];
|
||||
derivationRules.value = sourceRules.length
|
||||
? sourceRules.map((rule) => ({ ...rule }))
|
||||
: [{
|
||||
rule_id: 'R-LINE-NO-FROM-CUSTOMER-PO',
|
||||
enabled: false,
|
||||
source_field_code: 'customer_po_line_no',
|
||||
target_field_code: 'line_no',
|
||||
strategy: 'copy_if_empty',
|
||||
scope: 'line',
|
||||
}];
|
||||
const existing = draft.value?.definition?.fields || published.value?.definition?.fields || [];
|
||||
const byId = new Map(existing.map((item) => [item.field_id, item]));
|
||||
draftFields.value = (state.value?.fields || [])
|
||||
@@ -441,7 +409,7 @@ const toggleAdoption = (field: ShippingOrderField, enabled: boolean): void => {
|
||||
}
|
||||
};
|
||||
|
||||
/** 保存草稿的全部已采用字段规则、派生规则与自动建单策略;未采用字段不会进入发布契约。 */
|
||||
/** 保存草稿的全部已采用字段规则与自动建单策略;订单项次不属于可编辑 Schema 配置。 */
|
||||
const saveDraft = async (): Promise<void> => {
|
||||
if (!draft.value) return;
|
||||
saving.value = true;
|
||||
@@ -450,16 +418,12 @@ const saveDraft = async (): Promise<void> => {
|
||||
const saved = await saveShippingOrderSchemaDraft(draft.value.id, {
|
||||
fields,
|
||||
auto_creation_policy: { enabled: autoCreationEnabled.value },
|
||||
derivation_rules: derivationRules.value.map((item) => ({ ...item })),
|
||||
change_note: changeNote.value,
|
||||
expected_lock_version: draft.value.lock_version,
|
||||
});
|
||||
if (state.value) {
|
||||
state.value.versions = state.value.versions.map((item) => (item.id === saved.id ? saved : item));
|
||||
}
|
||||
if (saved.definition?.derivation_rules) {
|
||||
derivationRules.value = saved.definition.derivation_rules.map((item) => ({ ...item }));
|
||||
}
|
||||
message.success(t('admin.shippingOrderSchema.draftSaved'));
|
||||
} catch (error) {
|
||||
await handleWriteError(error);
|
||||
@@ -468,82 +432,6 @@ const saveDraft = async (): Promise<void> => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 切换派生规则启用状态(仅草稿可改)。
|
||||
* @param index - 规则下标
|
||||
* @param event - checkbox 事件
|
||||
*/
|
||||
const onDerivationEnabledChange = (index: number, event: Event): void => {
|
||||
if (!draft.value) return;
|
||||
const checked = (event.target as HTMLInputElement).checked;
|
||||
const current = derivationRules.value[index];
|
||||
if (!current) return;
|
||||
derivationRules.value[index] = { ...current, enabled: checked };
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开派生规则模拟弹窗并加载历史 Extraction 样本列表。
|
||||
*/
|
||||
const openDerivationSimulate = async (): Promise<void> => {
|
||||
simulateResult.value = null;
|
||||
simulateMode.value = 'history';
|
||||
simulateOpen.value = true;
|
||||
simulateSamplesLoading.value = true;
|
||||
try {
|
||||
const response = await listShippingOrderSchemaDerivationSimulateSamples(20);
|
||||
simulateSamples.value = response.items || [];
|
||||
simulateSampleRef.value = simulateSamples.value[0]?.sample_ref || '';
|
||||
if (!simulateSamples.value.length) {
|
||||
simulateMode.value = 'inline';
|
||||
}
|
||||
} catch (error) {
|
||||
await handleWriteError(error);
|
||||
simulateMode.value = 'inline';
|
||||
} finally {
|
||||
simulateSamplesLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 运行派生规则模拟:优先使用历史 Extraction 样本,亦可手工 JSON。
|
||||
*/
|
||||
const runDerivationSimulate = async (): Promise<void> => {
|
||||
if (!draft.value && !published.value) return;
|
||||
const versionId = draft.value?.id || published.value?.id;
|
||||
if (!versionId) return;
|
||||
simulating.value = true;
|
||||
try {
|
||||
if (simulateMode.value === 'history') {
|
||||
if (!simulateSampleRef.value) {
|
||||
message.error(t('admin.shippingOrderSchema.derivationSimulateSampleRequired'));
|
||||
return;
|
||||
}
|
||||
simulateResult.value = await simulateShippingOrderSchemaDerivation(versionId, {
|
||||
sample_ref: simulateSampleRef.value,
|
||||
derivation_rules: derivationRules.value,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const lines = JSON.parse(simulateSampleJson.value) as Array<Record<string, string | number | null>>;
|
||||
if (!Array.isArray(lines)) {
|
||||
throw new Error('invalid sample');
|
||||
}
|
||||
simulateResult.value = await simulateShippingOrderSchemaDerivation(versionId, {
|
||||
lines,
|
||||
derivation_rules: derivationRules.value,
|
||||
sample_ref: 'schema-admin-inline-sample',
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof SyntaxError || (error instanceof Error && error.message === 'invalid sample')) {
|
||||
message.error(t('admin.shippingOrderSchema.derivationSimulateSampleInvalid'));
|
||||
} else {
|
||||
await handleWriteError(error);
|
||||
}
|
||||
} finally {
|
||||
simulating.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 拦截自动建单开关变更:仅草稿可改,且须二次确认;确认后仅写入本地,随保存草稿/发布生效。
|
||||
* @param event - checkbox change 事件
|
||||
@@ -1049,48 +937,6 @@ onMounted(async () => {
|
||||
</label>
|
||||
<p class="schema-gate-note">{{ t('admin.shippingOrderSchema.effectiveReservationGate') }}</p>
|
||||
|
||||
<details class="derivation-panel" :open="derivationPanelOpen" @toggle="derivationPanelOpen = ($event.target as HTMLDetailsElement).open">
|
||||
<summary>
|
||||
<strong>{{ t('admin.shippingOrderSchema.derivationRulesTitle') }}</strong>
|
||||
<span>{{ t('admin.shippingOrderSchema.derivationRulesHint') }}</span>
|
||||
</summary>
|
||||
<div class="derivation-toolbar">
|
||||
<button
|
||||
type="button"
|
||||
class="btn-secondary btn-sm"
|
||||
:disabled="simulating || (!draft && !published)"
|
||||
@click="openDerivationSimulate"
|
||||
>
|
||||
{{ t('admin.shippingOrderSchema.derivationSimulate') }}
|
||||
</button>
|
||||
</div>
|
||||
<table class="derivation-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{{ t('admin.shippingOrderSchema.derivationEnabled') }}</th>
|
||||
<th>{{ t('admin.shippingOrderSchema.derivationSource') }}</th>
|
||||
<th>{{ t('admin.shippingOrderSchema.derivationTarget') }}</th>
|
||||
<th>{{ t('admin.shippingOrderSchema.derivationStrategy') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="(rule, index) in derivationRules" :key="rule.rule_id">
|
||||
<td>
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="rule.enabled"
|
||||
:disabled="!draft || saving"
|
||||
@change="onDerivationEnabledChange(index, $event)"
|
||||
>
|
||||
</td>
|
||||
<td><code>{{ rule.source_field_code }}</code></td>
|
||||
<td><code>{{ rule.target_field_code }}</code></td>
|
||||
<td>{{ t('admin.shippingOrderSchema.derivationStrategyCopyIfEmpty') }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p class="derivation-note">{{ t('admin.shippingOrderSchema.derivationRulesNote') }}</p>
|
||||
</details>
|
||||
</section>
|
||||
|
||||
<div class="schema-workbench">
|
||||
@@ -1508,96 +1354,6 @@ onMounted(async () => {
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div v-if="simulateOpen" class="impact-overlay" @click.self="simulateOpen = false">
|
||||
<section class="impact-dialog derivation-simulate-dialog">
|
||||
<header>
|
||||
<h2>{{ t('admin.shippingOrderSchema.derivationSimulateTitle') }}</h2>
|
||||
<button type="button" class="btn-ghost btn-sm" @click="simulateOpen = false">{{ t('common.close') }}</button>
|
||||
</header>
|
||||
<p class="simulate-hint">{{ t('admin.shippingOrderSchema.derivationSimulateNoMutate') }}</p>
|
||||
<div class="simulate-mode-row">
|
||||
<label>
|
||||
<input v-model="simulateMode" type="radio" value="history">
|
||||
{{ t('admin.shippingOrderSchema.derivationSimulateModeHistory') }}
|
||||
</label>
|
||||
<label>
|
||||
<input v-model="simulateMode" type="radio" value="inline">
|
||||
{{ t('admin.shippingOrderSchema.derivationSimulateModeInline') }}
|
||||
</label>
|
||||
</div>
|
||||
<label v-if="simulateMode === 'history'" class="simulate-sample">
|
||||
<span>{{ t('admin.shippingOrderSchema.derivationSimulateHistorySample') }}</span>
|
||||
<select v-model="simulateSampleRef" :disabled="simulateSamplesLoading || !simulateSamples.length">
|
||||
<option disabled value="">
|
||||
{{ simulateSamplesLoading
|
||||
? t('admin.shippingOrderSchema.derivationSimulateSamplesLoading')
|
||||
: t('admin.shippingOrderSchema.derivationSimulateSamplesEmpty') }}
|
||||
</option>
|
||||
<option
|
||||
v-for="item in simulateSamples"
|
||||
:key="item.sample_ref"
|
||||
:value="item.sample_ref"
|
||||
>
|
||||
{{ t('admin.shippingOrderSchema.derivationSimulateSampleOption', {
|
||||
id: item.extraction_id,
|
||||
lines: item.line_count,
|
||||
status: item.status,
|
||||
}) }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label v-else class="simulate-sample">
|
||||
<span>{{ t('admin.shippingOrderSchema.derivationSimulateSample') }}</span>
|
||||
<textarea v-model="simulateSampleJson" rows="8" />
|
||||
</label>
|
||||
<footer>
|
||||
<button type="button" class="btn-secondary" @click="simulateOpen = false">{{ t('common.cancel') }}</button>
|
||||
<button type="button" class="btn-primary" :disabled="simulating" @click="runDerivationSimulate">
|
||||
{{ t('admin.shippingOrderSchema.derivationSimulateRun') }}
|
||||
</button>
|
||||
</footer>
|
||||
<div v-if="simulateResult" class="simulate-result">
|
||||
<p>
|
||||
{{ t('admin.shippingOrderSchema.derivationSimulateSummary', {
|
||||
version: simulateResult.schema_version,
|
||||
checksum: simulateResult.rules_checksum.slice(0, 12),
|
||||
derived: simulateResult.derived_count,
|
||||
skipped: simulateResult.skipped_count,
|
||||
}) }}
|
||||
</p>
|
||||
<div class="simulate-result-scroll" data-testid="derivation-simulate-result-scroll">
|
||||
<table class="derivation-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>{{ t('admin.shippingOrderSchema.derivationSource') }}</th>
|
||||
<th>{{ t('admin.shippingOrderSchema.derivationBefore') }}</th>
|
||||
<th>{{ t('admin.shippingOrderSchema.derivationAfter') }}</th>
|
||||
<th>{{ t('admin.shippingOrderSchema.derivationResult') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="row in simulateResult.results" :key="`${row.line_index}-${row.rule_id}`">
|
||||
<td>{{ row.line_index + 1 }}</td>
|
||||
<td>{{ row.before_source ?? '—' }}</td>
|
||||
<td>{{ row.before_target ?? '—' }}</td>
|
||||
<td>{{ row.after_target ?? '—' }}</td>
|
||||
<td>
|
||||
<template v-if="row.status === 'derived'">
|
||||
{{ t('admin.shippingOrderSchema.derivationStatusDerived') }}
|
||||
</template>
|
||||
<template v-else>
|
||||
{{ t('admin.shippingOrderSchema.derivationStatusSkipped', { reason: row.skip_reason || '' }) }}
|
||||
</template>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="muted">{{ t('admin.shippingOrderSchema.derivationSimulateNoMutate') }}</p>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div v-if="profileImpactOpen && profileImpact" class="impact-overlay" @click.self="profileImpactOpen = false">
|
||||
<section class="impact-dialog">
|
||||
@@ -1725,38 +1481,6 @@ onMounted(async () => {
|
||||
.auto-creation-switch small { color: #64748b; font-size: 11px; }
|
||||
.auto-creation-effective { display: block; color: #0f766e; }
|
||||
.schema-gate-note { margin: 0 0 12px; color: #475569; font-size: 12px; line-height: 1.5; }
|
||||
.derivation-panel { margin: 0 0 8px; border: 1px solid #dbe6ef; border-radius: 8px; background: #fff; padding: 12px 14px; }
|
||||
.derivation-panel summary { cursor: pointer; display: grid; gap: 4px; color: #334155; }
|
||||
.derivation-panel summary span { color: #64748b; font-size: 12px; }
|
||||
.derivation-toolbar { display: flex; justify-content: flex-end; margin: 12px 0; }
|
||||
.derivation-table { width: 100%; border-collapse: collapse; font-size: 12px; }
|
||||
.derivation-table th, .derivation-table td { border-bottom: 1px solid #e2e8f0; padding: 8px 6px; text-align: left; vertical-align: middle; }
|
||||
.derivation-note { margin: 10px 0 0; color: #64748b; font-size: 12px; }
|
||||
.simulate-hint { margin: 0 0 10px; color: #64748b; font-size: 12px; }
|
||||
.simulate-mode-row { display: flex; gap: 16px; margin-bottom: 10px; font-size: 13px; color: #334155; }
|
||||
.simulate-mode-row label { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.derivation-simulate-dialog {
|
||||
max-width: 760px;
|
||||
width: min(760px, 92vw);
|
||||
overflow: auto;
|
||||
align-content: start;
|
||||
}
|
||||
.simulate-sample { display: grid; gap: 8px; margin: 12px 0; color: #475569; font-size: 13px; }
|
||||
.simulate-sample textarea,
|
||||
.simulate-sample select { width: 100%; font-size: 12px; border: 1px solid #cbd5e1; border-radius: 8px; padding: 10px; box-sizing: border-box; }
|
||||
.simulate-sample textarea { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
|
||||
.simulate-result { margin-top: 14px; display: grid; gap: 10px; min-width: 0; }
|
||||
.simulate-result-scroll {
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.simulate-result-scroll .derivation-table {
|
||||
margin: 0;
|
||||
min-width: 520px;
|
||||
}
|
||||
.muted { margin: 0; color: #64748b; font-size: 12px; }
|
||||
.field-panel { display: flex; min-width: 0; min-height: 0; flex-direction: column; border-right: 1px solid #e5ebf1; background: #fbfcfe; }
|
||||
.panel-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 16px 16px 10px; }
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/**
|
||||
* features/admin/modules/wecom/composables/useWecomAdmin.ts
|
||||
* 企业微信:绑定、系统配置、通知、登录审计。
|
||||
* 依赖:admin.api、useMessage、wecom 展示工具、PaginationBar 所需的审计分页状态。
|
||||
* 逻辑:绑定走服务端分页;登录审计仍一次拉取最近 200 条,由前端切片分页。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
@@ -60,7 +62,24 @@ export function useWecomAdmin() {
|
||||
let wecomBindUserCloseTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const wecomAuditSourceFilter = ref<'all' | 'wecom' | 'password'>('all');
|
||||
const wecomAuditStatusFilter = ref<'all' | 'success' | 'failed'>('all');
|
||||
const wecomAuditsPage = ref(1);
|
||||
const wecomAuditsPageSize = ref(20);
|
||||
const wecomAuditsPageSizeOptions = [10, 20, 50, 100] as const;
|
||||
const filteredWecomLoginAudits = computed(() => wecomLoginAudits.value);
|
||||
const wecomAuditsTotal = computed(() => filteredWecomLoginAudits.value.length);
|
||||
|
||||
/**
|
||||
* 对已拉取的审计列表做前端切片,不请求后端分页。
|
||||
* 核心逻辑:按 pageSize 计算安全页码后 slice,避免筛选后落到空页。
|
||||
*/
|
||||
const pagedWecomLoginAudits = computed(() => {
|
||||
const size = Math.max(1, Number(wecomAuditsPageSize.value) || 20);
|
||||
const total = wecomAuditsTotal.value;
|
||||
const pages = Math.max(1, Math.ceil(total / size));
|
||||
const page = Math.min(Math.max(1, wecomAuditsPage.value), pages);
|
||||
const start = (page - 1) * size;
|
||||
return filteredWecomLoginAudits.value.slice(start, start + size);
|
||||
});
|
||||
const wecomNotifySettings = ref<WecomNotifySettings>({
|
||||
enabled: true,
|
||||
base_url: '',
|
||||
@@ -158,6 +177,10 @@ export function useWecomAdmin() {
|
||||
void loadWecomBindings();
|
||||
};
|
||||
|
||||
/**
|
||||
* 拉取登录审计(后端固定最近 200 条,前端再分页)。
|
||||
* 核心逻辑:带上 source/status 筛选调用 listAdminWecomLoginAudits。
|
||||
*/
|
||||
const loadWecomAudits = async (): Promise<void> => {
|
||||
try {
|
||||
const params = new URLSearchParams({ limit: '200' });
|
||||
@@ -466,6 +489,7 @@ export function useWecomAdmin() {
|
||||
});
|
||||
|
||||
watch([wecomAuditSourceFilter, wecomAuditStatusFilter], () => {
|
||||
wecomAuditsPage.value = 1;
|
||||
void loadWecomAudits();
|
||||
});
|
||||
|
||||
@@ -487,7 +511,12 @@ export function useWecomAdmin() {
|
||||
wecomBoundOnly,
|
||||
wecomAuditSourceFilter,
|
||||
wecomAuditStatusFilter,
|
||||
wecomAuditsPage,
|
||||
wecomAuditsPageSize,
|
||||
wecomAuditsPageSizeOptions,
|
||||
wecomAuditsTotal,
|
||||
filteredWecomLoginAudits,
|
||||
pagedWecomLoginAudits,
|
||||
wecomNotifySettings,
|
||||
wecomNotifyEventsText,
|
||||
wecomNotifyMetrics,
|
||||
|
||||
@@ -2,10 +2,13 @@
|
||||
/**
|
||||
* features/admin/modules/wecom/pages/WecomAuditsPage.vue
|
||||
* 企微与密码登录审计列表。
|
||||
* 依赖:WECOM_ADMIN_KEY、PaginationBar、formatLocalDateTime。
|
||||
* 逻辑:表格渲染当前页切片;分页条对已拉取的最近 200 条做前端翻页。
|
||||
*/
|
||||
import { inject } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Download } from 'lucide-vue-next';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
import { WECOM_ADMIN_KEY } from '../wecom.context';
|
||||
|
||||
@@ -13,7 +16,12 @@ const { t } = useI18n();
|
||||
const {
|
||||
wecomAuditSourceFilter,
|
||||
wecomAuditStatusFilter,
|
||||
wecomAuditsPage,
|
||||
wecomAuditsPageSize,
|
||||
wecomAuditsPageSizeOptions,
|
||||
wecomAuditsTotal,
|
||||
filteredWecomLoginAudits,
|
||||
pagedWecomLoginAudits,
|
||||
exportWecomAudits,
|
||||
getWecomAuditReasonText,
|
||||
getWecomAuditMetaText,
|
||||
@@ -57,7 +65,7 @@ const {
|
||||
<tr v-if="filteredWecomLoginAudits.length === 0">
|
||||
<td colspan="6" class="px-4 admin-table-empty">{{ t('admin.wecom.noAuditData') }}</td>
|
||||
</tr>
|
||||
<tr v-for="row in filteredWecomLoginAudits" :key="row.id">
|
||||
<tr v-for="row in pagedWecomLoginAudits" :key="row.id">
|
||||
<td class="px-4 py-3 text-xs text-muted whitespace-nowrap" :title="row.created_at || '-'">{{ formatLocalDateTime(row.created_at) }}</td>
|
||||
<td class="px-4 py-3 text-xs text-secondary">{{ t('admin.wecom.sources.' + row.source) }}</td>
|
||||
<td class="px-4 py-3 text-xs text-secondary">{{ row.username || '-' }}</td>
|
||||
@@ -82,5 +90,13 @@ const {
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="px-4 pb-4 pt-2">
|
||||
<PaginationBar
|
||||
v-model:page="wecomAuditsPage"
|
||||
v-model:page-size="wecomAuditsPageSize"
|
||||
:total="wecomAuditsTotal"
|
||||
:page-size-options="[...wecomAuditsPageSizeOptions]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -2,11 +2,12 @@
|
||||
/**
|
||||
* features/admin/modules/wecom/pages/WecomSettingsPage.vue
|
||||
* 企微系统配置、通知与集成复制。
|
||||
* 依赖:WECOM_ADMIN_KEY、lucide CircleHelp。
|
||||
* 逻辑:绑定概览卡片只在绑定管理页展示,本页仅编辑系统/通知配置。
|
||||
*/
|
||||
import { inject } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { CircleHelp } from 'lucide-vue-next';
|
||||
import WecomOverviewCards from '../components/WecomOverviewCards.vue';
|
||||
import { WECOM_ADMIN_KEY } from '../wecom.context';
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -28,8 +29,6 @@ const {
|
||||
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<WecomOverviewCards />
|
||||
|
||||
<div class="card shadow-sm p-5 space-y-4">
|
||||
<h3 class="font-semibold text-primary">{{ t('admin.wecom.systemSettings') }}</h3>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* features/admin/stores/admin-nav.store.ts
|
||||
* 管理后台导航 UI 状态(侧栏折叠、报表/企微子菜单展开、角标)。
|
||||
*
|
||||
@@ -20,6 +20,8 @@ export const useAdminNavStore = defineStore('adminNav', () => {
|
||||
const reportsExpanded = ref(false);
|
||||
/** 企业微信子菜单:默认折叠 */
|
||||
const wecomExpanded = ref(false);
|
||||
/** 货代管理子菜单:默认折叠;父项点击仅展开/收起,子项负责导航 */
|
||||
const shippingMenuExpanded = ref(false);
|
||||
/** 「用户审批」导航角标:pending 注册用户数 */
|
||||
const pendingApprovalsCount = ref(0);
|
||||
/** 「权限申请」导航角标:pending 权限申请数 */
|
||||
@@ -88,6 +90,7 @@ export const useAdminNavStore = defineStore('adminNav', () => {
|
||||
sidebarCollapsed,
|
||||
reportsExpanded,
|
||||
wecomExpanded,
|
||||
shippingMenuExpanded,
|
||||
pendingApprovalsCount,
|
||||
pendingRequestsCount,
|
||||
toggleSidebar,
|
||||
|
||||
@@ -22,6 +22,7 @@ export type AdminModuleId =
|
||||
| 'shipping_inventory'
|
||||
| 'procurement_contract'
|
||||
| 'training_config'
|
||||
| 'integration_connector'
|
||||
| 'reports';
|
||||
|
||||
/** 货代管理领域下可由侧栏展示和高亮的稳定业务页面。 */
|
||||
|
||||
@@ -91,69 +91,9 @@ export interface ShippingOrderSchemaVersion {
|
||||
definition?: {
|
||||
fields: ShippingOrderFieldConfig[];
|
||||
auto_creation_policy?: { enabled: boolean };
|
||||
derivation_rules?: ShippingOrderDerivationRule[];
|
||||
derivation_rules_checksum?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/** Schema 级明细字段派生规则(首期仅 copy_if_empty → line_no)。 */
|
||||
export interface ShippingOrderDerivationRule {
|
||||
rule_id: string;
|
||||
enabled: boolean;
|
||||
source_field_code: string;
|
||||
target_field_code: string;
|
||||
strategy: 'copy_if_empty';
|
||||
scope: 'line';
|
||||
}
|
||||
|
||||
export interface ShippingOrderDerivationSimulateRequest {
|
||||
lines?: Array<Record<string, string | number | null | undefined>>;
|
||||
derivation_rules?: ShippingOrderDerivationRule[];
|
||||
/** 可追溯样本;`extraction:<id>` 时后端加载历史明细,可省略 lines。 */
|
||||
sample_ref?: string;
|
||||
}
|
||||
|
||||
export interface ShippingOrderDerivationSimulateSampleItem {
|
||||
sample_ref: string;
|
||||
extraction_id: number;
|
||||
line_count: number;
|
||||
status: string;
|
||||
schema_version_id: number;
|
||||
created_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderDerivationSimulateResult {
|
||||
schema_version_id: number;
|
||||
schema_version: number;
|
||||
schema_version_status: string;
|
||||
rules_checksum: string;
|
||||
rules: ShippingOrderDerivationRule[];
|
||||
derived_count: number;
|
||||
skipped_count: number;
|
||||
results: Array<{
|
||||
line_index: number;
|
||||
rule_id: string;
|
||||
source_field_code: string;
|
||||
target_field_code: string;
|
||||
strategy: string;
|
||||
before_source: unknown;
|
||||
before_target: unknown;
|
||||
after_target: unknown;
|
||||
status: 'derived' | 'skipped';
|
||||
skip_reason: string | null;
|
||||
}>;
|
||||
lines_after: Array<Record<string, unknown>>;
|
||||
sample_ref?: string | null;
|
||||
sample_source?: {
|
||||
kind?: string;
|
||||
extraction_id?: number;
|
||||
schema_version_id?: number;
|
||||
intake_id?: number;
|
||||
status?: string;
|
||||
} | null;
|
||||
mutates_orders: boolean;
|
||||
}
|
||||
|
||||
export interface SchemaVersionActor {
|
||||
id: number;
|
||||
display_name: string;
|
||||
@@ -266,7 +206,7 @@ export interface ShippingOrderExtractionAudit {
|
||||
raw_llm_output: unknown;
|
||||
normalized_result: unknown;
|
||||
validation_result: unknown;
|
||||
lines: Array<{ id: number; position: number; line_key?: string | null }>;
|
||||
lines: Array<{ id: number; position: number; line_no: number }>;
|
||||
observations: Array<Record<string, unknown>>;
|
||||
decisions: Array<Record<string, unknown>>;
|
||||
field_values: Array<Record<string, unknown>>;
|
||||
|
||||
Reference in new issue
Block a user