Merge branch 'dev' into snow

# Conflicts:
#	backend/app/api/chat.py
#	backend/app/services/admin/permission_service.py
#	backend/app/services/knowledge_cleaning/dify_sync_service.py
#	backend/app/services/knowledge_cleaning/settings_service.py
#	backend/tests/test_dify_sync_process_rule.py
#	docker-compose.yml
#	docs/funclist.md
#	frontend/package-lock.json
#	frontend/src/config.ts
#	frontend/src/features/admin/components/AdminNav.vue
#	frontend/src/features/admin/constants/modules.ts
#	frontend/src/features/admin/stores/admin-nav.store.ts
#	frontend/src/features/chat/components/messages/ChatMessageBubble.vue
#	frontend/src/features/user/views/UserProfilePage.vue
#	frontend/src/locales/en/admin.json
#	frontend/src/locales/en/auth.json
#	frontend/src/locales/en/errors.json
#	frontend/src/locales/th/admin.json
#	frontend/src/locales/th/auth.json
#	frontend/src/locales/th/errors.json
#	frontend/src/locales/zh-CN/admin.json
#	frontend/src/locales/zh-CN/auth.json
#	frontend/src/locales/zh-CN/errors.json
#	frontend/src/locales/zh-TW/admin.json
#	frontend/src/locales/zh-TW/auth.json
#	frontend/src/locales/zh-TW/errors.json
This commit is contained in:
HTEWJ\26070045 committed 2026-09-11 14:55:20 +08:00
commit ca9c174f29
2050 files changed
+511839 -42320

No files matched your search

@@ -207,6 +207,7 @@ watch(
},
);
watch(
() => props.form.is_aggregate,
(enabled) => {
@@ -301,7 +302,6 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
</option>
</select>
</div>
<template v-if="showDifyFields">
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.difyAppType') }}</label>
@@ -0,0 +1,275 @@
<!--
features/admin/modules/integration-connector/IntegrationConnectorPage.vue
用途:集成连接器管理页——四个配置实体(客户端实例/接口定义/绑定/凭据引用)tab 列表 +
能力清单与手动调用测试;创建/编辑弹窗 + 连接测试。
依赖:useIntegrationConnectorAdmin、两个弹窗组件、useI18n。
逻辑:按 tab 展示列表与「新增」;配置「绑定」是让自动调拨跑起来的最小闭环核心。
-->
<script setup lang="ts">
import { computed, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Plus, Edit, Trash2, Plug, PlayCircle } from 'lucide-vue-next';
import IntegrationConnectorFormModal from './components/IntegrationConnectorFormModal.vue';
import IntegrationCapabilityCallModal from './components/IntegrationCapabilityCallModal.vue';
import { useIntegrationConnectorAdmin } from './composables/useIntegrationConnectorAdmin';
const { t } = useI18n();
const {
clients, interfaces, bindings, credentials, capabilities,
isLoading, activeEntity, showFormModal, isSaving,
clientForm, interfaceForm, bindingForm, credentialForm,
showCallModal, callCapability, callParamsText, callContextText, callResult, callBusy,
testResultText,
loadAll, openCreateModal, openEditModal, closeFormModal, saveActive,
testConnection, openCallModal, closeCallModal, runCall, deleteClient,
} = useIntegrationConnectorAdmin();
onMounted(() => { void loadAll(); });
type TabKey = 'client' | 'interface' | 'binding' | 'credential' | 'capability';
const tabs: Array<{ key: TabKey; labelKey: string }> = [
{ key: 'client', labelKey: 'admin.integrationConnector.tabs.client' },
{ key: 'interface', labelKey: 'admin.integrationConnector.tabs.interface' },
{ key: 'binding', labelKey: 'admin.integrationConnector.tabs.binding' },
{ key: 'credential', labelKey: 'admin.integrationConnector.tabs.credential' },
{ key: 'capability', labelKey: 'admin.integrationConnector.tabs.capability' },
];
const activeTab = computed<TabKey>(() => (activeEntity.value === 'credential' ? 'credential' : activeEntity.value));
const clientOptions = computed(() => clients.value.map((c) => ({ code: c.code, name: c.name })));
const interfaceOptions = computed(() => interfaces.value.map((i) => ({ code: i.code, name: i.name })));
const capabilityOptions = computed(() => capabilities.value.map((c) => ({ name: c.name })));
function selectTab(key: TabKey) {
// capability tab 只读展示,不进入表单实体;其余映射到可编辑实体。
if (key === 'capability') return;
activeEntity.value = key;
}
</script>
<template>
<section class="admin-table-section animate-fade-in-up">
<div class="admin-table-header admin-table-header--stacked">
<div>
<h2 class="section-title">{{ t('admin.integrationConnector.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.integrationConnector.subtitle') }}</p>
</div>
<button
v-if="activeTab !== 'capability'"
type="button"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
@click="openCreateModal(activeEntity)"
>
<Plus class="w-4 h-4" />
<span>{{ t('admin.integrationConnector.add') }}</span>
</button>
</div>
<div class="flex gap-1 border-b border-default" role="tablist">
<button
v-for="tab in tabs"
:key="tab.key"
type="button"
role="tab"
class="px-4 py-2.5 text-sm font-medium border-b-2 -mb-px transition-colors"
:class="activeTab === tab.key ? 'border-brand-600 text-brand-600' : 'border-transparent text-muted hover:text-secondary'"
:aria-selected="activeTab === tab.key"
@click="selectTab(tab.key)"
>
{{ t(tab.labelKey) }}
</button>
</div>
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<!-- 客户端实例 -->
<div v-if="activeTab === 'client'" class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.code') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.name') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.connectorType') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.environment') }}</th>
<th class="px-6 py-4 text-right text-xs w-40">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="clients.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in clients" :key="row.code">
<td class="px-6 py-4 text-sm font-medium text-primary mono">{{ row.code }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.name }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.connector_type }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.environment }}</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<button type="button" class="p-2 rounded-lg text-muted hover:bg-brand-50 hover:text-brand-600" :title="t('admin.integrationConnector.test')" @click="testConnection(row.code)">
<Plug class="w-4 h-4" />
</button>
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('client', row)">
<Edit class="w-4 h-4" />
</button>
<button type="button" class="p-2 rounded-lg text-muted hover:bg-red-50 hover:text-red-600" :title="t('admin.delete')" @click="deleteClient(row.code)">
<Trash2 class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
<p v-if="testResultText" class="mt-3 rounded-lg bg-surface-soft p-3 text-xs font-mono text-secondary whitespace-pre-wrap break-all">{{ testResultText }}</p>
</div>
<!-- 接口定义 -->
<div v-else-if="activeTab === 'interface'" class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.code') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.name') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.clientInstance') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.status') }}</th>
<th class="px-6 py-4 text-right text-xs w-24">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="interfaces.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in interfaces" :key="row.code">
<td class="px-6 py-4 text-sm font-medium text-primary mono">{{ row.code }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.name }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.client_instance_code }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.status }}</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('interface', row)">
<Edit class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- 绑定 -->
<div v-else-if="activeTab === 'binding'" class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.capability') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.clientInstance') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.interfaceDef') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.status') }}</th>
<th class="px-6 py-4 text-right text-xs w-24">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="bindings.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in bindings" :key="row.id">
<td class="px-6 py-4 text-sm font-medium text-primary">{{ row.capability }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.client_instance_code }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.interface_definition_code }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.status }}</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('binding', row)">
<Edit class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- 凭据引用 -->
<div v-else-if="activeTab === 'credential'" class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.code') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.secretRef') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.secretProvider') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.status') }}</th>
<th class="px-6 py-4 text-right text-xs w-24">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="credentials.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in credentials" :key="row.code">
<td class="px-6 py-4 text-sm font-medium text-primary mono">{{ row.code }}</td>
<td class="px-6 py-4 text-sm text-secondary mono">{{ row.secret_ref }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.secret_provider }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.status }}</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('credential', row)">
<Edit class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- 能力清单 -->
<div v-else class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.name') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.write') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.idempotency') }}</th>
<th class="px-6 py-4 text-right text-xs w-28">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="capabilities.length === 0"><td colspan="4" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in capabilities" :key="row.name">
<td class="px-6 py-4 text-sm font-medium text-primary">{{ row.name }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.write ? 'yes' : 'no' }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.idempotency }}</td>
<td class="px-6 py-4 text-right">
<button type="button" class="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm font-medium text-brand-600 hover:bg-brand-50" @click="openCallModal(row.name)">
<PlayCircle class="w-4 h-4" />
{{ t('admin.integrationConnector.call') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<IntegrationConnectorFormModal
:visible="showFormModal"
:active-entity="activeEntity"
:client-form="clientForm"
:interface-form="interfaceForm"
:binding-form="bindingForm"
:credential-form="credentialForm"
:is-saving="isSaving"
:client-options="clientOptions"
:interface-options="interfaceOptions"
:capability-options="capabilityOptions"
@close="closeFormModal"
@save="saveActive"
/>
<IntegrationCapabilityCallModal
:visible="showCallModal"
:capability="callCapability"
:params-text="callParamsText"
:context-text="callContextText"
:result="callResult"
:busy="callBusy"
@close="closeCallModal"
@run="runCall"
/>
</section>
</template>
@@ -0,0 +1,105 @@
/**
* features/admin/modules/integration-connector/api/integration-connector.api.ts
* 集成连接器管理 API 客户端:客户端实例/接口定义/绑定/凭据引用 CRUD + 能力清单 + 连接测试。
* 依赖:@/shared/api/client(requestJson / BusinessError)、@/shared/utils/auth。
* 逻辑:薄封装后端 /api/integration-connector/* 全部端点;JSON 写请求带 Content-Type。
* 错误码(INTEGRATION.*)由 requestJson 解析到四语言文案。
*/
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import type {
IntegrationBindingRow,
IntegrationCallResultRow,
IntegrationCapabilityRow,
IntegrationClientInstanceRow,
IntegrationCredentialReferenceRow,
IntegrationInterfaceDefinitionRow,
} from '../types/integration-connector.types';
const BASE = '/api/integration-connector';
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
// ---- 能力清单与调用 ----
/** 能力清单(写/幂等/入出参 Schema)。 */
export const listIntegrationCapabilities = () =>
requestJson<IntegrationCapabilityRow[]>(`${BASE}/capabilities`, auth());
/** 手动调用一个已注册能力(入参 + 路由上下文)。 */
export const callIntegrationCapability = (capability: string, payload: { params?: Record<string, unknown>; context?: Record<string, unknown>; operation_id?: string; idempotency_key?: string }) =>
requestJson<IntegrationCallResultRow>(`${BASE}/capabilities/${encodeURIComponent(capability)}`, {
method: 'POST',
...jsonAuth(),
body: JSON.stringify(payload),
});
// ---- 客户端实例 ----
export const listIntegrationClientInstances = () =>
requestJson<IntegrationClientInstanceRow[]>(`${BASE}/client-instances`, auth());
export const createIntegrationClientInstance = (payload: Record<string, unknown>) =>
requestJson<IntegrationClientInstanceRow>(`${BASE}/client-instances`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
});
export const updateIntegrationClientInstance = (code: string, payload: Record<string, unknown>) =>
requestJson<IntegrationClientInstanceRow>(`${BASE}/client-instances/${encodeURIComponent(code)}`, {
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
});
export const deleteIntegrationClientInstance = (code: string) =>
requestJson(`${BASE}/client-instances/${encodeURIComponent(code)}`, { method: 'DELETE', ...auth() });
/** 连接测试(返回底层传输 raw 结果)。 */
export const testIntegrationClientConnection = (code: string) =>
requestJson<Record<string, unknown>>(`${BASE}/client-instances/${encodeURIComponent(code)}/test`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify({}),
});
// ---- 接口定义 ----
export const listIntegrationInterfaceDefinitions = () =>
requestJson<IntegrationInterfaceDefinitionRow[]>(`${BASE}/interface-definitions`, auth());
export const createIntegrationInterfaceDefinition = (payload: Record<string, unknown>) =>
requestJson<IntegrationInterfaceDefinitionRow>(`${BASE}/interface-definitions`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
});
export const updateIntegrationInterfaceDefinition = (code: string, payload: Record<string, unknown>) =>
requestJson<IntegrationInterfaceDefinitionRow>(`${BASE}/interface-definitions/${encodeURIComponent(code)}`, {
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
});
// ---- 绑定 ----
export const listIntegrationBindings = () =>
requestJson<IntegrationBindingRow[]>(`${BASE}/bindings`, auth());
export const createIntegrationBinding = (payload: Record<string, unknown>) =>
requestJson<IntegrationBindingRow>(`${BASE}/bindings`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
});
export const updateIntegrationBinding = (id: number, payload: Record<string, unknown>) =>
requestJson<IntegrationBindingRow>(`${BASE}/bindings/${id}`, {
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
});
// ---- 凭据引用 ----
export const listIntegrationCredentialReferences = () =>
requestJson<IntegrationCredentialReferenceRow[]>(`${BASE}/credential-references`, auth());
export const createIntegrationCredentialReference = (payload: Record<string, unknown>) =>
requestJson<IntegrationCredentialReferenceRow>(`${BASE}/credential-references`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
});
export const updateIntegrationCredentialReference = (code: string, payload: Record<string, unknown>) =>
requestJson<IntegrationCredentialReferenceRow>(`${BASE}/credential-references/${encodeURIComponent(code)}`, {
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
});
@@ -0,0 +1,59 @@
<!--
features/admin/modules/integration-connector/components/IntegrationCapabilityCallModal.vue
用途:手动调用一个已注册能力(输入 params / context JSON),展示调用结果与 trace。
依赖:showCallModal、callParamsText、callContextText、callResult、callBusy。
逻辑:由 IntegrationConnectorPage 打开;emit close/run。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { IntegrationCallResultRow } from '../types/integration-connector.types';
const props = defineProps<{
visible: boolean;
capability: string;
paramsText: string;
contextText: string;
result: IntegrationCallResultRow | null;
busy: boolean;
}>();
const emit = defineEmits<{
close: [];
run: [];
}>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
<div class="admin-modal-panel max-w-2xl max-h-[92vh] scale-100">
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
<h3 class="section-title">{{ t('admin.integrationConnector.callModal.title', { capability }) }}</h3>
<p class="section-desc mt-1">{{ t('admin.integrationConnector.callModal.hint') }}</p>
</div>
<div class="px-5 sm:px-8 py-5 space-y-4 overflow-y-auto">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.callModal.params') }}</label>
<textarea :value="props.paramsText" rows="6" class="input-field text-sm font-mono" spellcheck="false" readonly />
<p class="text-xs text-muted">{{ t('admin.integrationConnector.callModal.paramsHint') }}</p>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.callModal.context') }}</label>
<textarea :value="props.contextText" rows="4" class="input-field text-sm font-mono" spellcheck="false" readonly />
<p class="text-xs text-muted">{{ t('admin.integrationConnector.callModal.contextHint') }}</p>
</div>
<div v-if="result" class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.callModal.result') }}</label>
<pre class="rounded-lg bg-surface-soft p-3 text-xs font-mono text-secondary whitespace-pre-wrap break-all">{{ JSON.stringify(result, null, 2) }}</pre>
</div>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-70" :disabled="busy" @click="emit('run')">
{{ busy ? t('admin.integrationConnector.callModal.running') : t('admin.integrationConnector.callModal.run') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,96 @@
/**
* features/admin/modules/integration-connector/components/IntegrationConnectorFormModal.spec.ts
* 用途:锁定表单按连接器类型动态显示字段——REST 显示超时/HTTP方法/请求路径,
* SOAP 显示 WSDL;关键字段从 JSON 拆出独立输入框,JSON 收进高级配置折叠。
* 依赖:@vue/test-utils、i18n。
* 逻辑:切换 connector_type 后断言对应字段的可见性;高级配置折叠默认收起。
*/
import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import i18n from '@/i18n';
import IntegrationConnectorFormModal from './IntegrationConnectorFormModal.vue';
import {
createEmptyClientInstanceForm,
createEmptyInterfaceDefinitionForm,
createEmptyBindingForm,
createEmptyCredentialReferenceForm,
} from '../types/integration-connector.types';
function mountModal() {
return mount(IntegrationConnectorFormModal, {
props: {
visible: true,
activeEntity: 'client',
clientForm: createEmptyClientInstanceForm(),
interfaceForm: createEmptyInterfaceDefinitionForm(),
bindingForm: createEmptyBindingForm(),
credentialForm: createEmptyCredentialReferenceForm(),
isSaving: false,
clientOptions: [],
interfaceOptions: [],
capabilityOptions: [],
},
global: { plugins: [i18n] },
});
}
describe('IntegrationConnectorFormModal connector-type fields', () => {
it('REST 默认显示接口地址与超时字段', () => {
const wrapper = mountModal();
expect(wrapper.find('[data-testid="client-endpoint"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="client-timeout"]').exists()).toBe(true);
});
it('切换到 SOAP 后连接地址 label 变为 WSDL,超时仍显示;同一 endpoint 字段', async () => {
const wrapper = mountModal();
await wrapper.find('[data-testid="client-connector-type"]').setValue('soap');
await wrapper.vm.$nextTick();
// 连接地址仍是同一 client-endpoint 字段,仅 label 变 WSDL
expect(wrapper.find('[data-testid="client-endpoint"]').exists()).toBe(true);
// 超时在 SOAP 下也显示
expect(wrapper.find('[data-testid="client-timeout"]').exists()).toBe(true);
const labels = wrapper.findAll('label').map((l) => l.text());
expect(labels.some((t) => t.includes('WSDL'))).toBe(true);
});
it('接口定义 REST 显示 HTTP 方法与请求路径', () => {
const wrapper = mount(IntegrationConnectorFormModal, {
props: {
visible: true,
activeEntity: 'interface',
clientForm: createEmptyClientInstanceForm(),
interfaceForm: createEmptyInterfaceDefinitionForm(),
bindingForm: createEmptyBindingForm(),
credentialForm: createEmptyCredentialReferenceForm(),
isSaving: false,
clientOptions: [],
interfaceOptions: [],
capabilityOptions: [],
},
global: { plugins: [i18n] },
});
const labels = wrapper.findAll('label').map((l) => l.text());
expect(labels.some((t) => t.includes('HTTP 方法'))).toBe(true);
expect(labels.some((t) => t.includes('请求路径'))).toBe(true);
});
it('绑定显示来源实例编码独立字段', () => {
const wrapper = mount(IntegrationConnectorFormModal, {
props: {
visible: true,
activeEntity: 'binding',
clientForm: createEmptyClientInstanceForm(),
interfaceForm: createEmptyInterfaceDefinitionForm(),
bindingForm: createEmptyBindingForm(),
credentialForm: createEmptyCredentialReferenceForm(),
isSaving: false,
clientOptions: [],
interfaceOptions: [],
capabilityOptions: [],
},
global: { plugins: [i18n] },
});
const labels = wrapper.findAll('label').map((l) => l.text());
expect(labels.some((t) => t.includes('来源实例编码'))).toBe(true);
});
});
@@ -0,0 +1,277 @@
<!--
features/admin/modules/integration-connector/components/IntegrationConnectorFormModal.vue
用途:集成连接器四实体(客户端实例/接口定义/绑定/凭据引用)创建与编辑弹窗。
依赖:activeEntity 对应的表单 state、useI18n。
逻辑:由 IntegrationConnectorPage 打开;按 activeEntity 渲染对应字段;提交 emit save。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type {
BindingFormState,
ClientInstanceFormState,
CredentialReferenceFormState,
InterfaceDefinitionFormState,
} from '../types/integration-connector.types';
const props = defineProps<{
visible: boolean;
activeEntity: 'client' | 'interface' | 'binding' | 'credential';
clientForm: ClientInstanceFormState;
interfaceForm: InterfaceDefinitionFormState;
bindingForm: BindingFormState;
credentialForm: CredentialReferenceFormState;
isSaving: boolean;
clientOptions: Array<{ code: string; name: string }>;
interfaceOptions: Array<{ code: string; name: string }>;
capabilityOptions: Array<{ name: string }>;
}>();
const emit = defineEmits<{
close: [];
save: [];
}>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
<div class="admin-modal-panel max-w-2xl max-h-[92vh] scale-100">
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
<h3 class="section-title">{{ t(`admin.integrationConnector.tabs.${activeEntity}`) }}</h3>
<p class="section-desc mt-1">{{ t('admin.integrationConnector.formHint') }}</p>
</div>
<div class="px-5 sm:px-8 py-5 space-y-5 overflow-y-auto">
<!-- 客户端实例 -->
<template v-if="activeEntity === 'client'">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.code') }}</label>
<input v-model="clientForm.code" type="text" class="input-field text-sm" :disabled="Boolean(clientForm.id)" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.name') }}</label>
<input v-model="clientForm.name" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.connectorType') }}</label>
<select v-model="clientForm.connector_type" class="input-field text-sm" data-testid="client-connector-type">
<option value="rest">rest</option>
<option value="soap">soap</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.environment') }}</label>
<input v-model="clientForm.environment" type="text" class="input-field text-sm" />
</div>
</div>
<!-- 连接地址:endpoint 合一字段;label 按连接器类型显示(REST=接口地址,SOAP=WSDL 地址) -->
<div class="space-y-1.5">
<label class="label-field">{{ clientForm.connector_type === 'soap' ? t('admin.integrationConnector.fields.wsdl') : t('admin.integrationConnector.fields.endpoint') }}</label>
<input v-model="clientForm.endpoint" type="text" class="input-field text-sm" :placeholder="t(clientForm.connector_type === 'soap' ? 'admin.integrationConnector.placeholders.wsdl' : 'admin.integrationConnector.placeholders.endpoint')" data-testid="client-endpoint" />
</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.timeout') }}</label>
<input v-model="clientForm.timeout_seconds" type="number" class="input-field text-sm" min="0" data-testid="client-timeout" />
</div>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.credentialRef') }}</label>
<input v-model="clientForm.credential_ref_code" type="text" class="input-field text-sm" />
</div>
<details class="rounded-lg border border-slate-200 px-3 py-2">
<summary class="cursor-pointer text-xs font-bold text-secondary">{{ t('admin.integrationConnector.advancedConfig') }}</summary>
<div class="mt-2 space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.configJson') }}</label>
<textarea v-model="clientForm.config_json" rows="6" class="input-field text-sm font-mono" spellcheck="false" />
</div>
</details>
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
<input v-model="clientForm.enabled" type="checkbox" class="w-4 h-4 rounded text-brand-600 border-default" />
{{ t('admin.integrationConnector.fields.enabled') }}
</label>
</template>
<!-- 接口定义 -->
<template v-else-if="activeEntity === 'interface'">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.code') }}</label>
<input v-model="interfaceForm.code" type="text" class="input-field text-sm" :disabled="Boolean(interfaceForm.id)" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.name') }}</label>
<input v-model="interfaceForm.name" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.clientInstance') }}</label>
<select v-model="interfaceForm.client_instance_code" class="input-field text-sm">
<option v-for="opt in clientOptions" :key="opt.code" :value="opt.code">{{ opt.code }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.connectorType') }}</label>
<select v-model="interfaceForm.connector_type" class="input-field text-sm">
<option value="rest">rest</option>
<option value="soap">soap</option>
</select>
</div>
</div>
<div v-if="interfaceForm.connector_type === 'rest'" class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.httpMethod') }}</label>
<select v-model="interfaceForm.http_method" class="input-field text-sm">
<option value="">—</option>
<option value="GET">GET</option>
<option value="POST">POST</option>
<option value="PUT">PUT</option>
<option value="DELETE">DELETE</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.requestPath') }}</label>
<input v-model="interfaceForm.request_path" type="text" class="input-field text-sm font-mono" :placeholder="t('admin.integrationConnector.placeholders.requestPath')" />
</div>
</div>
<details class="rounded-lg border border-slate-200 px-3 py-2">
<summary class="cursor-pointer text-xs font-bold text-secondary">{{ t('admin.integrationConnector.advancedConfig') }}</summary>
<div class="mt-2 grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.requestSpec') }}</label>
<textarea v-model="interfaceForm.request_spec_json" rows="5" class="input-field text-sm font-mono" spellcheck="false" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.inputSchema') }}</label>
<textarea v-model="interfaceForm.input_schema_json" rows="5" class="input-field text-sm font-mono" spellcheck="false" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.responseMapping') }}</label>
<textarea v-model="interfaceForm.response_mapping_json" rows="5" class="input-field text-sm font-mono" spellcheck="false" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.outputSchema') }}</label>
<textarea v-model="interfaceForm.output_schema_json" rows="5" class="input-field text-sm font-mono" spellcheck="false" />
</div>
</div>
</details>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.status') }}</label>
<select v-model="interfaceForm.status" class="input-field text-sm">
<option value="draft">draft</option>
<option value="published">published</option>
<option value="retired">retired</option>
</select>
</div>
<div class="flex items-end pb-1">
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
<input v-model="interfaceForm.enabled" type="checkbox" class="w-4 h-4 rounded text-brand-600 border-default" />
{{ t('admin.integrationConnector.fields.enabled') }}
</label>
</div>
</div>
</template>
<!-- 绑定 -->
<template v-else-if="activeEntity === 'binding'">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.capability') }}</label>
<select v-model="bindingForm.capability" class="input-field text-sm">
<option v-for="cap in capabilityOptions" :key="cap.name" :value="cap.name">{{ cap.name }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.environment') }}</label>
<input v-model="bindingForm.environment" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.clientInstance') }}</label>
<select v-model="bindingForm.client_instance_code" class="input-field text-sm">
<option v-for="opt in clientOptions" :key="opt.code" :value="opt.code">{{ opt.code }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.interfaceDef') }}</label>
<select v-model="bindingForm.interface_definition_code" class="input-field text-sm">
<option v-for="opt in interfaceOptions" :key="opt.code" :value="opt.code">{{ opt.code }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.mappingVersion') }}</label>
<input v-model.number="bindingForm.mapping_version" type="number" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.priority') }}</label>
<input v-model.number="bindingForm.priority" type="number" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.effectiveFrom') }}</label>
<input v-model="bindingForm.effective_from" type="datetime-local" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.effectiveTo') }}</label>
<input v-model="bindingForm.effective_to" type="datetime-local" class="input-field text-sm" />
</div>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.contextSourceCode') }}</label>
<input v-model="bindingForm.context_source_code" type="text" class="input-field text-sm" :placeholder="t('admin.integrationConnector.placeholders.contextSourceCode')" />
</div>
<details class="rounded-lg border border-slate-200 px-3 py-2">
<summary class="cursor-pointer text-xs font-bold text-secondary">{{ t('admin.integrationConnector.advancedConfig') }}</summary>
<div class="mt-2 space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.contextSelector') }}</label>
<textarea v-model="bindingForm.context_selector_json" rows="4" class="input-field text-sm font-mono" spellcheck="false" />
</div>
</details>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.status') }}</label>
<select v-model="bindingForm.status" class="input-field text-sm">
<option value="draft">draft</option>
<option value="published">published</option>
<option value="retired">retired</option>
</select>
</div>
</template>
<!-- 凭据引用 -->
<template v-else>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.code') }}</label>
<input v-model="credentialForm.code" type="text" class="input-field text-sm" :disabled="Boolean(credentialForm.id)" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.secretRef') }}</label>
<input v-model="credentialForm.secret_ref" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.secretProvider') }}</label>
<input v-model="credentialForm.secret_provider" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.credentialType') }}</label>
<input v-model="credentialForm.credential_type" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.status') }}</label>
<select v-model="credentialForm.status" class="input-field text-sm">
<option value="active">active</option>
<option value="rotating">rotating</option>
<option value="retired">retired</option>
</select>
</div>
</div>
</template>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-70" :disabled="isSaving" @click="emit('save')">
{{ isSaving ? t('admin.save') + '...' : t('admin.save') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,148 @@
/**
* features/admin/modules/integration-connector/composables/useIntegrationConnectorAdmin.spec.ts
* 用途:锁定集成连接器管理编排——四实体保存(create/update 分支)、JSON 字段解析校验、
* 必填校验拦截、能力调用与连接测试调用 API。
* 依赖:vi.mock(integration-connector.api)、@vue/test-utils、i18n。
* 逻辑:通过 setup 挂载 harness 组件访问 useIntegrationConnectorAdmin(useI18n 需在 setup 内);
* Mock API 断言 payload 构造与调用;非法 JSON 触发拦截且不调 API。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { defineComponent, h } from 'vue';
import { mount } from '@vue/test-utils';
import i18n from '@/i18n';
import { useIntegrationConnectorAdmin } from './useIntegrationConnectorAdmin';
const api = vi.hoisted(() => ({
listIntegrationClientInstances: vi.fn(),
createIntegrationClientInstance: vi.fn(),
updateIntegrationClientInstance: vi.fn(),
deleteIntegrationClientInstance: vi.fn(),
testIntegrationClientConnection: vi.fn(),
listIntegrationInterfaceDefinitions: vi.fn(),
createIntegrationInterfaceDefinition: vi.fn(),
updateIntegrationInterfaceDefinition: vi.fn(),
listIntegrationBindings: vi.fn(),
createIntegrationBinding: vi.fn(),
updateIntegrationBinding: vi.fn(),
listIntegrationCredentialReferences: vi.fn(),
createIntegrationCredentialReference: vi.fn(),
updateIntegrationCredentialReference: vi.fn(),
listIntegrationCapabilities: vi.fn(),
callIntegrationCapability: vi.fn(),
}));
vi.mock('@/features/admin/modules/integration-connector/api/integration-connector.api', () => api);
function makeHarness() {
let exposed: ReturnType<typeof useIntegrationConnectorAdmin> | null = null;
const Harness = defineComponent({
setup() {
exposed = useIntegrationConnectorAdmin();
return () => h('div');
},
});
mount(Harness, { global: { plugins: [i18n] } });
return exposed!;
}
describe('useIntegrationConnectorAdmin', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('loadAll 拉取五个列表', async () => {
api.listIntegrationClientInstances.mockResolvedValue([]);
api.listIntegrationInterfaceDefinitions.mockResolvedValue([]);
api.listIntegrationBindings.mockResolvedValue([]);
api.listIntegrationCredentialReferences.mockResolvedValue([]);
api.listIntegrationCapabilities.mockResolvedValue([]);
const c = makeHarness();
await c.loadAll();
expect(api.listIntegrationClientInstances).toHaveBeenCalled();
expect(api.listIntegrationCapabilities).toHaveBeenCalled();
});
it('新建客户端实例:关键字段独立列 + config_json 解析为对象并 POST', async () => {
const c = makeHarness();
c.openCreateModal('client');
c.clientForm.value.code = 'ERP-X';
c.clientForm.value.name = 'ERP X';
c.clientForm.value.endpoint = 'https://x.invalid';
c.clientForm.value.timeout_seconds = '90';
c.clientForm.value.config_json = '{"headers":{"X-Tenant":"A"}}';
await c.saveActive();
expect(api.createIntegrationClientInstance).toHaveBeenCalledWith({
code: 'ERP-X', name: 'ERP X', connector_type: 'rest', environment: 'prod',
endpoint: 'https://x.invalid', timeout_seconds: 90,
config_json: { headers: { 'X-Tenant': 'A' } }, credential_ref_code: null, enabled: true,
});
});
it('编辑客户端实例:有 id 走 PUT', async () => {
const c = makeHarness();
c.openEditModal('client', {
id: 1, code: 'ERP-X', name: 'old', connector_type: 'rest', environment: 'prod',
config_json: {}, credential_ref_code: null, enabled: true,
});
c.clientForm.value.name = 'new';
await c.saveActive();
expect(api.updateIntegrationClientInstance).toHaveBeenCalled();
});
it('非法 JSON 字段触发拦截且不调 API', async () => {
const c = makeHarness();
c.openCreateModal('client');
c.clientForm.value.code = 'ERP-X';
c.clientForm.value.name = 'ERP X';
c.clientForm.value.config_json = '{bad json';
await c.saveActive();
expect(api.createIntegrationClientInstance).not.toHaveBeenCalled();
});
it('客户端实例必填:缺 code 不调 API', async () => {
const c = makeHarness();
c.openCreateModal('client');
c.clientForm.value.name = 'ERP X';
await c.saveActive();
expect(api.createIntegrationClientInstance).not.toHaveBeenCalled();
});
it('绑定:必填校验与 POST payload', async () => {
const c = makeHarness();
c.openCreateModal('binding');
c.bindingForm.value.capability = 'in_transit_transfer.query_inventory';
c.bindingForm.value.client_instance_code = 'CLI-A';
c.bindingForm.value.interface_definition_code = 'IF-A';
await c.saveActive();
expect(api.createIntegrationBinding).toHaveBeenCalledWith({
capability: 'in_transit_transfer.query_inventory', context_selector_json: {},
context_source_code: null,
client_instance_code: 'CLI-A', interface_definition_code: 'IF-A',
mapping_version: 1, priority: 0, environment: 'prod',
effective_from: null, effective_to: null, status: 'draft',
});
});
it('凭据引用:创建 payload 不含明文 secret', async () => {
const c = makeHarness();
c.openCreateModal('credential');
c.credentialForm.value.code = 'CRED-A';
c.credentialForm.value.secret_ref = 'IN_TRANSIT_ERP_PASSWORD';
await c.saveActive();
expect(api.createIntegrationCredentialReference).toHaveBeenCalledWith({
code: 'CRED-A', secret_ref: 'IN_TRANSIT_ERP_PASSWORD', secret_provider: 'env',
credential_type: 'password', status: 'active',
});
});
it('连接测试与能力调用走对应 API', async () => {
const c = makeHarness();
api.testIntegrationClientConnection.mockResolvedValue({ ok: true });
api.callIntegrationCapability.mockResolvedValue({ status: 'success', data: { found: true }, error_code: null, error_message: null, document_no: null, trace_id: null });
await c.testConnection('CLI-A');
expect(api.testIntegrationClientConnection).toHaveBeenCalledWith('CLI-A');
c.openCallModal('in_transit_transfer.query_inventory');
await c.runCall();
expect(api.callIntegrationCapability).toHaveBeenCalled();
});
});
@@ -0,0 +1,296 @@
/**
* features/admin/modules/integration-connector/composables/useIntegrationConnectorAdmin.ts
* 集成连接器管理编排:客户端实例/接口定义/绑定/凭据引用四实体列表与增改表单,
* 以及能力清单与手动调用测试。
* 依赖:integration-connector.api、types、useMessage、useI18n。
* 逻辑:各列表独立 loadAll;新增/编辑共用表单弹窗态(form.id 区分);能力测试
* 独立于配置表单(CapabilityCall 弹窗)。保存/删除后刷新对应列表。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '@/shared/composables/useMessage';
import {
callIntegrationCapability,
createIntegrationBinding,
createIntegrationClientInstance,
createIntegrationCredentialReference,
createIntegrationInterfaceDefinition,
deleteIntegrationClientInstance,
listIntegrationBindings,
listIntegrationCapabilities,
listIntegrationClientInstances,
listIntegrationCredentialReferences,
listIntegrationInterfaceDefinitions,
testIntegrationClientConnection,
updateIntegrationBinding,
updateIntegrationClientInstance,
updateIntegrationCredentialReference,
updateIntegrationInterfaceDefinition,
} from '../api/integration-connector.api';
import {
bindingRowToForm,
clientInstanceRowToForm,
createEmptyBindingForm,
createEmptyClientInstanceForm,
createEmptyCredentialReferenceForm,
createEmptyInterfaceDefinitionForm,
credentialReferenceRowToForm,
interfaceDefinitionRowToForm,
type BindingFormState,
type ClientInstanceFormState,
type CredentialReferenceFormState,
type IntegrationBindingRow,
type IntegrationCallResultRow,
type IntegrationCapabilityRow,
type IntegrationClientInstanceRow,
type IntegrationCredentialReferenceRow,
type IntegrationInterfaceDefinitionRow,
type InterfaceDefinitionFormState,
} from '../types/integration-connector.types';
type EditableEntity = 'client' | 'interface' | 'binding' | 'credential';
export function useIntegrationConnectorAdmin() {
const { t } = useI18n();
const msg = useMessage();
// ---- 列表与加载态 ----
const clients = ref<IntegrationClientInstanceRow[]>([]);
const interfaces = ref<IntegrationInterfaceDefinitionRow[]>([]);
const bindings = ref<IntegrationBindingRow[]>([]);
const credentials = ref<IntegrationCredentialReferenceRow[]>([]);
const capabilities = ref<IntegrationCapabilityRow[]>([]);
const isLoading = ref(true);
// ---- 表单弹窗态 ----
const activeEntity = ref<EditableEntity>('client');
const showFormModal = ref(false);
const isSaving = ref(false);
const clientForm = ref<ClientInstanceFormState>(createEmptyClientInstanceForm());
const interfaceForm = ref<InterfaceDefinitionFormState>(createEmptyInterfaceDefinitionForm());
const bindingForm = ref<BindingFormState>(createEmptyBindingForm());
const credentialForm = ref<CredentialReferenceFormState>(createEmptyCredentialReferenceForm());
// ---- 能力调用测试弹窗态 ----
const showCallModal = ref(false);
const callCapability = ref('');
const callParamsText = ref('');
const callContextText = ref('');
const callResult = ref<IntegrationCallResultRow | null>(null);
const callBusy = ref(false);
// ---- 连接测试 ----
const testingClientCode = ref('');
const testResultText = ref('');
const loadClients = async () => { clients.value = await listIntegrationClientInstances(); };
const loadInterfaces = async () => { interfaces.value = await listIntegrationInterfaceDefinitions(); };
const loadBindings = async () => { bindings.value = await listIntegrationBindings(); };
const loadCredentials = async () => { credentials.value = await listIntegrationCredentialReferences(); };
const loadCapabilities = async () => { capabilities.value = await listIntegrationCapabilities(); };
const loadAll = async () => {
isLoading.value = true;
try {
await Promise.all([loadClients(), loadInterfaces(), loadBindings(), loadCredentials(), loadCapabilities()]);
} catch (e) {
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isLoading.value = false;
}
};
const reloadOne = async (entity: EditableEntity) => {
if (entity === 'client') await loadClients();
else if (entity === 'interface') await loadInterfaces();
else if (entity === 'binding') await loadBindings();
else await loadCredentials();
};
// ---- 弹窗打开/关闭 ----
const openCreateModal = (entity: EditableEntity) => {
activeEntity.value = entity;
if (entity === 'client') clientForm.value = createEmptyClientInstanceForm();
else if (entity === 'interface') interfaceForm.value = createEmptyInterfaceDefinitionForm();
else if (entity === 'binding') bindingForm.value = createEmptyBindingForm();
else credentialForm.value = createEmptyCredentialReferenceForm();
showFormModal.value = true;
};
const openEditModal = (entity: EditableEntity, row: IntegrationClientInstanceRow | IntegrationInterfaceDefinitionRow | IntegrationBindingRow | IntegrationCredentialReferenceRow) => {
activeEntity.value = entity;
if (entity === 'client') clientForm.value = clientInstanceRowToForm(row as IntegrationClientInstanceRow);
else if (entity === 'interface') interfaceForm.value = interfaceDefinitionRowToForm(row as IntegrationInterfaceDefinitionRow);
else if (entity === 'binding') bindingForm.value = bindingRowToForm(row as IntegrationBindingRow);
else credentialForm.value = credentialReferenceRowToForm(row as IntegrationCredentialReferenceRow);
showFormModal.value = true;
};
const closeFormModal = () => {
showFormModal.value = false;
clientForm.value = createEmptyClientInstanceForm();
interfaceForm.value = createEmptyInterfaceDefinitionForm();
bindingForm.value = createEmptyBindingForm();
credentialForm.value = createEmptyCredentialReferenceForm();
};
/** 解析 JSON 文本;空串返回 {},非法 JSON 抛错并提示。 */
const parseJsonField = (text: string, fieldLabel: string): Record<string, unknown> => {
const trimmed = String(text || '').trim();
if (!trimmed) return {};
try {
const parsed = JSON.parse(trimmed);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
throw new Error('must be an object');
} catch {
msg.warning(t('admin.integrationConnector.msg.invalidJson', { field: fieldLabel }));
throw new Error('invalid JSON');
}
};
// ---- 保存 ----
const saveActive = async () => {
isSaving.value = true;
try {
if (activeEntity.value === 'client') {
const form = clientForm.value;
if (!form.code.trim() || !form.name.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillClient'));
return;
}
const configJson = parseJsonField(form.config_json, 'config_json');
const payload = {
code: form.code.trim(), name: form.name.trim(), connector_type: form.connector_type,
environment: form.environment,
endpoint: form.endpoint.trim() || null,
timeout_seconds: form.timeout_seconds.trim() ? Number(form.timeout_seconds) : null,
config_json: configJson,
credential_ref_code: form.credential_ref_code.trim() || null, enabled: form.enabled,
};
if (form.id) await updateIntegrationClientInstance(form.code, payload);
else await createIntegrationClientInstance(payload);
} else if (activeEntity.value === 'interface') {
const form = interfaceForm.value;
if (!form.code.trim() || !form.client_instance_code.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillInterface'));
return;
}
const payload = {
code: form.code.trim(), name: form.name.trim() || form.code.trim(),
client_instance_code: form.client_instance_code.trim(), connector_type: form.connector_type,
http_method: form.http_method.trim() || null,
request_path: form.request_path.trim() || null,
request_spec_json: parseJsonField(form.request_spec_json, 'request_spec_json'),
input_schema_json: parseJsonField(form.input_schema_json, 'input_schema_json'),
response_mapping_json: parseJsonField(form.response_mapping_json, 'response_mapping_json'),
output_schema_json: parseJsonField(form.output_schema_json, 'output_schema_json'),
status: form.status, enabled: form.enabled,
};
if (form.id) await updateIntegrationInterfaceDefinition(form.code, payload);
else await createIntegrationInterfaceDefinition(payload);
} else if (activeEntity.value === 'binding') {
const form = bindingForm.value;
if (!form.capability.trim() || !form.client_instance_code.trim() || !form.interface_definition_code.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillBinding'));
return;
}
const payload = {
capability: form.capability.trim(), context_selector_json: parseJsonField(form.context_selector_json, 'context_selector_json'),
context_source_code: form.context_source_code.trim() || null,
client_instance_code: form.client_instance_code.trim(), interface_definition_code: form.interface_definition_code.trim(),
mapping_version: Number(form.mapping_version || 1), priority: Number(form.priority || 0),
environment: form.environment, effective_from: form.effective_from || null, effective_to: form.effective_to || null,
status: form.status,
};
if (form.id) await updateIntegrationBinding(form.id, payload);
else await createIntegrationBinding(payload);
} else {
const form = credentialForm.value;
if (!form.code.trim() || !form.secret_ref.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillCredential'));
return;
}
const payload = {
code: form.code.trim(), secret_ref: form.secret_ref.trim(), secret_provider: form.secret_provider,
credential_type: form.credential_type, status: form.status,
};
if (form.id) await updateIntegrationCredentialReference(form.code, payload);
else await createIntegrationCredentialReference(payload);
}
closeFormModal();
await reloadOne(activeEntity.value);
msg.success(t('admin.integrationConnector.msg.saved'));
} catch (e) {
// parseJsonField 已在内部提示;这里兜底 API 错误。
if (!(e instanceof Error && e.message === 'invalid JSON')) {
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
} finally {
isSaving.value = false;
}
};
// ---- 连接测试 ----
const testConnection = async (code: string) => {
testingClientCode.value = code;
testResultText.value = '';
try {
const result = await testIntegrationClientConnection(code);
testResultText.value = JSON.stringify(result, null, 2);
msg.success(t('admin.integrationConnector.msg.testOk'));
} catch (e) {
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
testingClientCode.value = '';
}
};
// ---- 能力调用测试 ----
const openCallModal = (capability: string) => {
callCapability.value = capability;
callParamsText.value = JSON.stringify({ invoice_no: '', from_warehouse: '', to_warehouse: '', quantity: 0 }, null, 2);
callContextText.value = '{}';
callResult.value = null;
showCallModal.value = true;
};
const closeCallModal = () => {
showCallModal.value = false;
callResult.value = null;
};
const runCall = async () => {
callBusy.value = true;
try {
const params = parseJsonField(callParamsText.value, 'params');
const context = parseJsonField(callContextText.value, 'context');
callResult.value = await callIntegrationCapability(callCapability.value, { params, context });
} catch (e) {
if (!(e instanceof Error && e.message === 'invalid JSON')) {
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
} finally {
callBusy.value = false;
}
};
const deleteClient = async (code: string) => {
try {
await deleteIntegrationClientInstance(code);
await loadClients();
msg.success(t('admin.integrationConnector.msg.deleted'));
} catch (e) {
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
};
return {
clients, interfaces, bindings, credentials, capabilities,
isLoading, activeEntity, showFormModal, isSaving,
clientForm, interfaceForm, bindingForm, credentialForm,
showCallModal, callCapability, callParamsText, callContextText, callResult, callBusy,
testingClientCode, testResultText,
loadAll, openCreateModal, openEditModal, closeFormModal, saveActive,
testConnection, openCallModal, closeCallModal, runCall, deleteClient,
};
}
@@ -0,0 +1,287 @@
/**
* features/admin/modules/integration-connector/types/integration-connector.types.ts
* 集成连接器管理域类型:客户端实例、接口定义、绑定、凭据引用、能力清单、调用结果。
* 依赖:无(纯类型与表单构建函数)。
* 逻辑:与后端 /api/integration-connector/* 序列化契约对齐;JSON 配置字段以 Record 承载
* 具体结构由表单/JSON 编辑器负责,前端不硬编码外部系统差异。
*/
/** 连接器类型:与后端 CONNECTOR_TYPES 对齐。 */
export type IntegrationConnectorType = 'rest' | 'soap';
/** 配置状态:draft 草稿 / published 已发布 / retired 已退役。 */
export type IntegrationConfigStatus = 'draft' | 'published' | 'retired';
/** 凭据状态。 */
export type IntegrationCredentialStatus = 'active' | 'rotating' | 'retired';
/** 能力清单项(后端 capability 注册表)。 */
export interface IntegrationCapabilityRow {
name: string;
write: boolean;
idempotency: string;
input_schema: Record<string, unknown>;
output_schema: Record<string, unknown>;
}
/** 能力调用结果(后端 IntegrationCallResult 序列化)。 */
export interface IntegrationCallResultRow {
status: string;
data: Record<string, unknown> | null;
error_code: string | null;
error_message: string | null;
document_no: string | null;
trace_id: string | null;
}
/** 客户端实例(接口地址/凭据引用/连接配置)。 */
export interface IntegrationClientInstanceRow {
id: number;
code: string;
name: string;
connector_type: IntegrationConnectorType;
environment: string;
endpoint: string | null;
timeout_seconds: number | null;
config_json: Record<string, unknown>;
credential_ref_code: string | null;
enabled: boolean;
}
/** 接口定义(接口模板/入参字段/回传映射/出参 Schema)。 */
export interface IntegrationInterfaceDefinitionRow {
id: number;
code: string;
name: string;
client_instance_code: string;
connector_type: IntegrationConnectorType;
http_method: string | null;
request_path: string | null;
request_spec_json: Record<string, unknown>;
input_schema_json: Record<string, unknown>;
response_mapping_json: Record<string, unknown>;
output_schema_json: Record<string, unknown>;
version: number;
status: IntegrationConfigStatus;
enabled: boolean;
}
/** 绑定(能力 → 客户端 + 接口 + 映射版本)。 */
export interface IntegrationBindingRow {
id: number;
capability: string;
context_selector_json: Record<string, unknown>;
context_source_code: string | null;
client_instance_code: string;
interface_definition_code: string;
mapping_version: number;
priority: number;
environment: string;
effective_from: string | null;
effective_to: string | null;
status: IntegrationConfigStatus;
}
/** 凭据引用(只存 secret_ref,不落明文)。 */
export interface IntegrationCredentialReferenceRow {
id: number;
code: string;
secret_ref: string;
secret_provider: string;
credential_type: string;
version: number;
status: IntegrationCredentialStatus;
last_verified_at: string | null;
}
/** 客户端实例表单。 */
export interface ClientInstanceFormState {
id: number | null;
code: string;
name: string;
connector_type: IntegrationConnectorType;
environment: string;
endpoint: string;
timeout_seconds: string;
config_json: string;
credential_ref_code: string;
enabled: boolean;
}
/** 接口定义表单(JSON 字段以文本承载,提交时解析)。 */
export interface InterfaceDefinitionFormState {
id: number | null;
code: string;
name: string;
client_instance_code: string;
connector_type: IntegrationConnectorType;
http_method: string;
request_path: string;
request_spec_json: string;
input_schema_json: string;
response_mapping_json: string;
output_schema_json: string;
status: IntegrationConfigStatus;
enabled: boolean;
}
/** 绑定表单。 */
export interface BindingFormState {
id: number | null;
capability: string;
context_selector_json: string;
context_source_code: string;
client_instance_code: string;
interface_definition_code: string;
mapping_version: number;
priority: number;
environment: string;
effective_from: string;
effective_to: string;
status: IntegrationConfigStatus;
}
/** 凭据引用表单。 */
export interface CredentialReferenceFormState {
id: number | null;
code: string;
secret_ref: string;
secret_provider: string;
credential_type: string;
status: IntegrationCredentialStatus;
}
const toJsonText = (value: Record<string, unknown> | null | undefined): string => {
if (!value || Object.keys(value).length === 0) return '';
return JSON.stringify(value, null, 2);
};
/** 创建空的客户端实例表单。 */
export function createEmptyClientInstanceForm(): ClientInstanceFormState {
return {
id: null,
code: '',
name: '',
connector_type: 'rest',
environment: 'prod',
endpoint: '',
timeout_seconds: '60',
config_json: '',
credential_ref_code: '',
enabled: true,
};
}
/** 列表行回填为客户端实例编辑表单。 */
export function clientInstanceRowToForm(row: IntegrationClientInstanceRow): ClientInstanceFormState {
return {
id: row.id,
code: row.code,
name: row.name,
connector_type: row.connector_type,
environment: row.environment,
endpoint: row.endpoint ?? '',
timeout_seconds: String(row.timeout_seconds ?? ''),
config_json: toJsonText(row.config_json),
credential_ref_code: row.credential_ref_code ?? '',
enabled: Boolean(row.enabled),
};
}
/** 创建空的接口定义表单。 */
export function createEmptyInterfaceDefinitionForm(): InterfaceDefinitionFormState {
return {
id: null,
code: '',
name: '',
client_instance_code: '',
connector_type: 'rest',
http_method: '',
request_path: '',
request_spec_json: '',
input_schema_json: '',
response_mapping_json: '',
output_schema_json: '',
status: 'draft',
enabled: true,
};
}
/** 列表行回填为接口定义编辑表单。 */
export function interfaceDefinitionRowToForm(row: IntegrationInterfaceDefinitionRow): InterfaceDefinitionFormState {
return {
id: row.id,
code: row.code,
name: row.name,
client_instance_code: row.client_instance_code,
connector_type: row.connector_type,
http_method: row.http_method ?? '',
request_path: row.request_path ?? '',
request_spec_json: toJsonText(row.request_spec_json),
input_schema_json: toJsonText(row.input_schema_json),
response_mapping_json: toJsonText(row.response_mapping_json),
output_schema_json: toJsonText(row.output_schema_json),
status: row.status,
enabled: Boolean(row.enabled),
};
}
/** 创建空的绑定表单。 */
export function createEmptyBindingForm(): BindingFormState {
return {
id: null,
capability: '',
context_selector_json: '',
context_source_code: '',
client_instance_code: '',
interface_definition_code: '',
mapping_version: 1,
priority: 0,
environment: 'prod',
effective_from: '',
effective_to: '',
status: 'draft',
};
}
/** 列表行回填为绑定编辑表单。 */
export function bindingRowToForm(row: IntegrationBindingRow): BindingFormState {
return {
id: row.id,
capability: row.capability,
context_selector_json: toJsonText(row.context_selector_json),
context_source_code: row.context_source_code ?? '',
client_instance_code: row.client_instance_code,
interface_definition_code: row.interface_definition_code,
mapping_version: Number(row.mapping_version || 1),
priority: Number(row.priority || 0),
environment: row.environment,
effective_from: row.effective_from ?? '',
effective_to: row.effective_to ?? '',
status: row.status,
};
}
/** 创建空的凭据引用表单。 */
export function createEmptyCredentialReferenceForm(): CredentialReferenceFormState {
return {
id: null,
code: '',
secret_ref: '',
secret_provider: 'env',
credential_type: 'password',
status: 'active',
};
}
/** 列表行回填为凭据引用编辑表单。 */
export function credentialReferenceRowToForm(row: IntegrationCredentialReferenceRow): CredentialReferenceFormState {
return {
id: row.id,
code: row.code,
secret_ref: row.secret_ref,
secret_provider: row.secret_provider,
credential_type: row.credential_type,
status: row.status,
};
}
@@ -9,6 +9,7 @@ import { ref, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { Plus, Trash2, Edit2, Play, FileText, Image as ImageIcon } from 'lucide-vue-next';
import { listAdminAgents, listAdminAgentGuides, createAdminAgentGuide, updateAdminAgentGuide, deleteAdminAgentGuide, uploadAdminAgentGuideFile } from '@/features/admin/api/admin.api';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
const { t } = useI18n();
@@ -34,6 +35,33 @@ const form = ref({
const isUploading = ref(false);
const uploadError = ref('');
const deleteDialogOpen = ref(false);
const pendingDeleteGuideId = ref<number | null>(null);
const safetyVideoUsages = new Set([
'training_safety_video',
'training_safety_company_video',
'training_safety_department_video',
'training_safety_team_video',
]);
const isVideoUsage = (usage: string) => usage === 'training_video' || safetyVideoUsages.has(usage);
const isPdfUsage = (usage: string) => usage === 'training_exam_pdf' || usage === 'training_safety_pdf';
/**
* 把指南用途编码翻译成管理端可读名称。
* AI 触发时机:平台应用说明列表与弹窗下拉都依赖这层映射,新增资料用途时必须统一从这里出文案,避免表格和表单各自写死分叉。
*/
const getGuideUsageLabel = (usage: string) => {
if (usage === 'training_video') return t('admin.platformApps.trainingVideo');
if (usage === 'training_exam_pdf') return t('admin.platformApps.trainingExamPdf');
if (usage === 'training_safety_company_video') return t('admin.platformApps.trainingSafetyCompanyVideo');
if (usage === 'training_safety_department_video') return t('admin.platformApps.trainingSafetyDepartmentVideo');
if (usage === 'training_safety_team_video') return t('admin.platformApps.trainingSafetyTeamVideo');
if (usage === 'training_safety_video') return t('admin.platformApps.trainingSafetyVideo');
if (usage === 'training_safety_pdf') return t('admin.platformApps.trainingSafetyPdf');
return t('admin.platformApps.generalGuide');
};
/**
* 拉取 Agent 列表并默认选中第一项,再加载其指南。
@@ -131,10 +159,10 @@ const handleFileUpload = async (event: Event) => {
form.value.file_path = res.file_path;
form.value.file_type = res.file_type;
form.value.file_size = res.file_size;
if (form.value.guide_usage === 'training_video' && res.file_type !== 'video') {
if (isVideoUsage(form.value.guide_usage) && res.file_type !== 'video') {
form.value.guide_usage = 'general';
}
if (form.value.guide_usage === 'training_exam_pdf' && res.file_type !== 'pdf') {
if (isPdfUsage(form.value.guide_usage) && res.file_type !== 'pdf') {
form.value.guide_usage = 'general';
}
if (!form.value.file_name) {
@@ -169,17 +197,26 @@ const submitForm = async () => {
}
};
const deleteGuide = (id: number) => {
pendingDeleteGuideId.value = id;
deleteDialogOpen.value = true;
};
/**
* 确认后删除指南。
* @param id - 指南主键
* 确认后删除指南(由 DeleteConfirmDialog 的 @confirm 触发)。
* @param id - 指南主键,取自 pendingDeleteGuideId
*/
const deleteGuide = async (id: number) => {
if (!confirm(t('admin.platformApps.confirmDelete'))) return;
const confirmDeleteGuide = async () => {
const id = pendingDeleteGuideId.value;
if (!id) return;
try {
await deleteAdminAgentGuide(id);
await fetchGuides();
} catch (error) {
console.error('Failed to delete guide:', error);
} finally {
pendingDeleteGuideId.value = null;
deleteDialogOpen.value = false;
}
};
@@ -285,9 +322,7 @@ const getIcon = (type: string) => {
<div class="text-xs text-muted mt-1 truncate max-w-[200px]">{{ guide.remark }}</div>
</td>
<td class="px-6 py-4 text-muted">
<span v-if="guide.guide_usage === 'training_video'">{{ t('admin.platformApps.trainingVideo') }}</span>
<span v-else-if="guide.guide_usage === 'training_exam_pdf'">{{ t('admin.platformApps.trainingExamPdf') }}</span>
<span v-else>{{ t('admin.platformApps.generalGuide') }}</span>
<span>{{ getGuideUsageLabel(guide.guide_usage || 'general') }}</span>
</td>
<td class="px-6 py-4">
<span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-brand-50 text-brand-700 border border-brand-100">
@@ -360,6 +395,11 @@ const getIcon = (type: string) => {
<option value="general">{{ t('admin.platformApps.generalGuide') }}</option>
<option value="training_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingVideo') }}</option>
<option value="training_exam_pdf" :disabled="form.file_type !== 'pdf'">{{ t('admin.platformApps.trainingExamPdf') }}</option>
<option value="training_safety_company_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingSafetyCompanyVideo') }}</option>
<option value="training_safety_department_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingSafetyDepartmentVideo') }}</option>
<option value="training_safety_team_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingSafetyTeamVideo') }}</option>
<option value="training_safety_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingSafetyVideo') }}</option>
<option value="training_safety_pdf" :disabled="form.file_type !== 'pdf'">{{ t('admin.platformApps.trainingSafetyPdf') }}</option>
</select>
<p class="text-xs text-muted">{{ t('admin.platformApps.guideUsageHint') }}</p>
</div>
@@ -391,5 +431,6 @@ const getIcon = (type: string) => {
</div>
</div>
</div>
<DeleteConfirmDialog v-model="deleteDialogOpen" title="{{ t('admin.platformApps.deleteGuide') }}" message="{{ t('admin.platformApps.confirmDelete') }}" confirm-tone="danger" @confirm="confirmDeleteGuide" />
</div>
</template>
@@ -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>
@@ -0,0 +1,83 @@
/**
* features/admin/modules/schedules/components/DynamicTaskParamsForm.spec.ts
* 用途:复现「货代库存 RPA」平台任务参数表单的渲染。
* 背景:排程编辑弹窗选择 shipping-inventory-rpa 后,库存源多选字段不呈现,且弹窗按钮疑似失效。
* 断言:给定带 source_codes(multi_select/options_source=shipping_inventory_sources) 的定义,
* 挂载后应渲染「库存源」标签及动态选项,而不是抛错或渲染为空。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { flushPromises, mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import DynamicTaskParamsForm from './DynamicTaskParamsForm.vue';
vi.mock('@/features/admin/api/schedule.api', () => ({
listAdminPlatformTaskOptions: vi.fn(() =>
Promise.resolve([
{ label: 'DSV 360 / Rooms BK HK', value: 'DSV360', description: 'dbs · fixed · W01' },
{ label: 'Crane Footprint', value: 'CRANE', description: 'crane · inventory_match · -' },
]),
),
}));
const shippingInventoryRpaDefinition = {
task_type: 'shipping-inventory-rpa',
label: '货代库存 RPA',
label_key: 'admin.schedule.form.platformJobShippingInventory',
description: '按计划从配置的库存源抓取库存数据,由 freight_rpa_worker 异步导出。',
description_key: 'admin.schedule.form.shippingInventoryJobHint',
category: 'shipping',
params_schema: [
{
key: 'source_codes',
type: 'multi_select',
label: '库存源',
label_key: 'admin.schedule.form.shippingInventorySources',
required: false,
default: [],
options_source: 'shipping_inventory_sources',
placeholder: '留空则导出全部启用库存源',
placeholder_key: 'admin.schedule.form.shippingInventorySourcesPlaceholder',
help: '选择需要执行的库存源;选项来自库存源配置,留空则全部执行。',
help_key: 'admin.schedule.form.shippingInventorySourcesHelp',
},
],
defaults: { source_codes: [] },
};
function mountForm() {
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
'admin.schedule.form.dynamicParamsAdvancedPlaceholder': '可选:粘贴高级 JSON 对象参数,例如添加 timeout_seconds 等键值对',
'admin.schedule.form.dynamicParamsAdvanced': '高级配置(JSON,可选)',
},
},
});
return mount(DynamicTaskParamsForm, {
props: {
definition: shippingInventoryRpaDefinition as any,
modelValue: { source_codes: [] },
valid: true,
},
global: { plugins: [i18n] },
});
}
describe('DynamicTaskParamsForm (shipping-inventory-rpa)', () => {
beforeEach(() => vi.clearAllMocks());
it('renders the 库存源 label and the two dynamic options', async () => {
const wrapper = mountForm();
await flushPromises();
expect(wrapper.text()).toContain('库存源');
expect(wrapper.text()).toContain('DSV 360 / Rooms BK HK');
expect(wrapper.text()).toContain('Crane Footprint');
expect(wrapper.find('input[type="checkbox"]').exists()).toBe(true);
});
it('does not throw during mount/render given the definition', async () => {
expect(() => mountForm()).not.toThrow();
});
});
@@ -30,6 +30,7 @@ const emit = defineEmits<{
const { t, te } = useI18n();
/** options_source → 选项列表缓存(组件生命周期内共享,避免重复请求) */
const optionsCache = reactive<Record<string, PlatformTaskOption[]>>({});
const optionsLoading = reactive<Record<string, boolean>>({});
@@ -18,8 +18,8 @@ const showCreateModal = useScheduleCreateModalOpen();
<template>
<Teleport to="body">
<div v-if="showCreateModal" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-3xl">
<div class="flex items-center justify-between border-b border-subtle px-8 py-6">
<div class="admin-modal-panel max-h-[92vh] max-w-3xl min-h-0">
<div class="flex shrink-0 items-center justify-between border-b border-subtle px-8 py-6">
<h3 class="text-2xl font-bold tracking-tight text-primary">{{ admin.scheduleEditingId ? $t('admin.schedule.form.editTitle') : $t('admin.schedule.form.createTitle') }}</h3>
<button
class="rounded-full p-2 text-muted transition hover-surface-soft hover:text-secondary"
@@ -28,7 +28,7 @@ const showCreateModal = useScheduleCreateModalOpen();
✕
</button>
</div>
<div class="max-h-[72vh] space-y-5 overflow-y-auto px-8 py-6">
<div class="min-h-0 flex-1 space-y-5 overflow-y-auto px-8 py-6">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div>
<label class="mb-2 block text-sm font-medium text-secondary">{{ $t('admin.schedule.form.name') }}</label>
@@ -300,18 +300,31 @@ const showCreateModal = useScheduleCreateModalOpen();
</template>
</div>
<!-- 平台任务参数区:完全由注册表 params_schema 决定,无任务级 v-if -->
<div
v-if="admin.scheduleCreateForm.schedule_type === 'platform_job' && admin.selectedPlatformTaskDefinition"
class="mt-3"
>
<!-- 平台任务参数区:完全由注册表 params_schema 决定,无任务级 v-if。
外层仅按 schedule_type 判定(同步、必然为真),不依赖异步 definitions;
定义解析完成前显示加载提示,完成后立即渲染 DynamicTaskParamsForm(含库存源)。 -->
<div v-if="admin.scheduleCreateForm.schedule_type === 'platform_job'" class="mt-3">
<DynamicTaskParamsForm
v-if="admin.selectedPlatformTaskDefinition"
:definition="admin.selectedPlatformTaskDefinition"
:model-value="admin.scheduleCreateForm.job_params"
:valid="admin.platformJobParamsValid"
@update:model-value="admin.scheduleCreateForm.job_params = $event"
@update:valid="admin.platformJobParamsValid = $event"
/>
<div v-else-if="admin.platformTaskDefinitionsLoading || admin.platformTaskDefinitionsError" class="space-y-2 rounded-xl border border-blue-200 bg-blue-50/40 px-4 py-3 text-sm text-muted">
<p>{{ admin.platformTaskDefinitionsLoading
? $t('admin.schedule.form.dynamicParamsLoading')
: $t('admin.schedule.form.dynamicParamsLoadFailed') }}</p>
<button
v-if="admin.platformTaskDefinitionsError && !admin.platformTaskDefinitionsLoading"
type="button"
class="btn-secondary btn-sm"
@click="admin.loadPlatformTaskDefinitions"
>
{{ $t('admin.schedule.form.dynamicParamsRetry') }}
</button>
</div>
</div>
<div v-if="admin.scheduleTestResult" class="mt-4 rounded-2xl border border-emerald-200 bg-emerald-50/40 p-4">
@@ -463,7 +476,7 @@ const showCreateModal = useScheduleCreateModalOpen();
</div>
</div>
<div class="admin-modal-footer admin-modal-footer--muted justify-end gap-3 px-8 py-5">
<div class="admin-modal-footer admin-modal-footer--muted relative z-10 pointer-events-auto justify-end gap-3 px-8 py-5">
<button
type="button"
class="btn-secondary"
@@ -0,0 +1,26 @@
/**
* features/admin/modules/schedules/components/dynamicParamsLocale.spec.ts
* 回归防护:vue-i18n 会把 {xxx} 当作命名插值;若 locale 文案里出现裸 {(如示例 JSON),
* 会导致 $t() 在渲染 DynamicTaskParamsForm 时抛错("'multipliers' of null"/编译报错),
* 进而整套参数区无法渲染、弹窗按钮失效。本测试确保四语言该占位文案不含花括号。
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
const LOCALES = ['zh-CN', 'zh-TW', 'en', 'th'];
describe('admin.schedule.form.dynamicParamsAdvancedPlaceholder', () => {
LOCALES.forEach((locale) => {
it(`${locale} must NOT contain message-compiler braces`, () => {
const text = readFileSync(resolve(__dirname, `../../../../../locales/${locale}/admin.json`), 'utf8');
const line = text
.split('\n')
.find((l) => l.includes('"dynamicParamsAdvancedPlaceholder"'));
expect(line, `missing key for ${locale}`).toBeTruthy();
// vue-i18n 编译器会把 { 视为插值起始,示例 JSON 的花括号会导致渲染抛错
expect(line!.includes('{')).toBe(false);
expect(line!.includes('}')).toBe(false);
});
});
});
@@ -18,6 +18,8 @@ export function createScheduleAdminState() {
const platformJobs = ref<PlatformJobOption[]>([]);
/** 平台任务完整契约(含 params_schema),供 DynamicTaskParamsForm 渲染 */
const platformTaskDefinitions = ref<PlatformTaskDefinition[]>([]);
const platformTaskDefinitionsLoading = ref(false);
const platformTaskDefinitionsError = ref(false);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmTitle = ref('');
@@ -118,6 +120,8 @@ export function createScheduleAdminState() {
kbGroups,
platformJobs,
platformTaskDefinitions,
platformTaskDefinitionsLoading,
platformTaskDefinitionsError,
showDeleteConfirmDialog,
deleteConfirmTitle,
deleteConfirmMessage,
@@ -22,6 +22,7 @@ import {
type ScheduleCreateForm,
} from '../../types/schedule-admin.types';
import { buildScheduleConfigPayload } from '../../utils/schedule-form-payload.utils';
import { normalizePlatformJobKey } from '../../utils/schedule-job-key.utils';
import { useScheduleCronDesigner } from '../useScheduleCronDesigner';
import type { ScheduleAdminState } from './schedule-admin.state';
import type { ScheduleAdminLookups } from './useScheduleAdminLookups';
@@ -63,7 +64,10 @@ export function useScheduleAdminForm(
const selectedPlatformTaskDefinition = computed(() => {
const form = scheduleCreateForm.value;
if (form.schedule_type !== 'platform_job' || !form.platform_api_path) return null;
return platformTaskDefinitions.value.find((d) => d.task_type === form.platform_api_path) || null;
// 后端保存时经 normalize_job_key 归一化;历史数据可能存下划线/完整路径/大小写差异,
// 前端比较也归一化,避免严格 === 失配导致参数表单(含库存源)被静默隐藏。
const normalized = normalizePlatformJobKey(form.platform_api_path);
return platformTaskDefinitions.value.find((d) => normalizePlatformJobKey(d.task_type) === normalized) || null;
});
/**
@@ -71,8 +75,9 @@ export function useScheduleAdminForm(
* 核心逻辑:由 modal select @change 触发(不用 watch,防止编辑回填被覆盖)。
*/
const handlePlatformJobChange = (): void => {
const normalized = normalizePlatformJobKey(scheduleCreateForm.value.platform_api_path);
const definition = platformTaskDefinitions.value.find(
(d) => d.task_type === scheduleCreateForm.value.platform_api_path,
(d) => normalizePlatformJobKey(d.task_type) === normalized,
);
scheduleCreateForm.value.job_params = definition && Object.keys(definition.defaults || {}).length
? { ...definition.defaults }
@@ -237,11 +242,13 @@ export function useScheduleAdminForm(
data_source_type: task.schedule_type === 'data_pipeline'
? ((task.data_source_type || 'database') as ScheduleCreateForm['data_source_type'])
: null,
platform_api_path: task.schedule_type === 'platform_job' ? (task.platform_api_path || null) : null,
platform_api_path: task.schedule_type === 'platform_job'
? (normalizePlatformJobKey(task.platform_api_path) || null)
: null,
// 历史 FAQ 任务兼容:无 job_params 时把旧 dify_agent_id 迁移为 app_id
job_params: task.schedule_type === 'platform_job'
? (task.job_params
|| (task.platform_api_path === 'faq-aggregate-hot' && task.dify_agent_id
|| (normalizePlatformJobKey(task.platform_api_path) === 'faq-aggregate-hot' && task.dify_agent_id
? { app_id: task.dify_agent_id }
: null))
: null,
@@ -1,6 +1,9 @@
/**
* features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminList.ts
* 任务列表加载、概览统计、启停/立即执行/删除与视图切换。
* 等待轮询策略:点「立即执行」后每 RUN_NOW_POLL_MS 刷新记录与列表,直到任务离开 running;
* 同一任务仅保留一个轮询(重复点击先清旧定时器)、上一轮未返回时跳过本轮,
* 并设 RUN_NOW_POLL_MAX_MS 上限,防止任务长时间不终态造成页面无限请求。
*/
import { computed } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
@@ -15,6 +18,11 @@ import { useMessage } from '@/shared/composables/useMessage';
import type { ScheduleAdminState } from './schedule-admin.state';
import type { ScheduleAdminRuns } from './useScheduleAdminRuns';
/** 立即执行后的等待轮询间隔 */
const RUN_NOW_POLL_MS = 5_000;
/** 等待轮询总上限:与服务端库存导出超时(默认 900s)对齐,超限后停止自动刷新提示手动查询 */
const RUN_NOW_POLL_MAX_MS = 15 * 60_000;
export function useScheduleAdminList(
state: ScheduleAdminState,
runs: Pick<ScheduleAdminRuns, 'viewScheduleRuns'>,
@@ -30,6 +38,11 @@ export function useScheduleAdminList(
openDeleteConfirm,
} = state;
/** 各任务运行中的单实例等待轮询句柄(重复点「立即执行」复用同一句柄) */
const runNowPollTimers = new Map<number, ReturnType<typeof setInterval>>();
/** 正在执行的等待轮询任务(上一轮未返回时跳过 tick,防请求堆叠) */
const runNowPollsInFlight = new Set<number>();
const scheduleEnabledCount = computed(() => schedules.value.filter((item) => item.enabled).length);
const scheduleDisabledCount = computed(() => schedules.value.filter((item) => !item.enabled).length);
const scheduleRunningCount = computed(() => schedules.value.filter((item) => item.last_status === 'running').length);
@@ -77,17 +90,37 @@ export function useScheduleAdminList(
msg.error(err?.message || t('admin.schedule.msg.runNowFailed'));
return;
}
await runs.viewScheduleRuns(taskId);
await runs.viewScheduleRuns(taskId, true);
await loadSchedules();
// 同一任务只保留一个等待轮询:重复点击先停旧定时器,避免多路 interval 并行放大请求频率
const previousPoll = runNowPollTimers.get(taskId);
if (previousPoll) clearInterval(previousPoll);
let elapsedMs = 0;
const pollInterval = setInterval(async () => {
await runs.viewScheduleRuns(taskId);
await loadSchedules();
const target = schedules.value.find((s: ScheduleTask) => s.id === taskId);
if (target && target.last_status && target.last_status !== 'running') {
clearInterval(pollInterval);
// 上一轮尚未返回时跳过本轮;慢后端下每轮耗时可能超过间隔,跳过可避免请求逐轮堆叠
if (runNowPollsInFlight.has(taskId)) return;
runNowPollsInFlight.add(taskId);
try {
await runs.viewScheduleRuns(taskId, true);
await loadSchedules();
elapsedMs += RUN_NOW_POLL_MS;
const target = schedules.value.find((s: ScheduleTask) => s.id === taskId);
const terminal = !!target?.last_status && target.last_status !== 'running';
const timedOut = elapsedMs >= RUN_NOW_POLL_MAX_MS;
if (terminal || timedOut) {
clearInterval(pollInterval);
runNowPollTimers.delete(taskId);
if (timedOut && !terminal) {
msg.warning(t('admin.schedule.msg.runNowWaitTimeout'));
}
}
} finally {
runNowPollsInFlight.delete(taskId);
}
}, 5000);
}, RUN_NOW_POLL_MS);
runNowPollTimers.set(taskId, pollInterval);
};
const setScheduleEnabled = async (taskId: number, enabled: boolean) => {
@@ -8,7 +8,15 @@ import { getKbGroups } from '@/features/kb/api/kb.api';
import type { ScheduleAdminState } from './schedule-admin.state';
export function useScheduleAdminLookups(state: ScheduleAdminState) {
const { agents, users, kbGroups, platformJobs, platformTaskDefinitions } = state;
const {
agents,
users,
kbGroups,
platformJobs,
platformTaskDefinitions,
platformTaskDefinitionsLoading,
platformTaskDefinitionsError,
} = state;
const loadAgents = async (): Promise<void> => {
try {
@@ -55,11 +63,16 @@ export function useScheduleAdminLookups(state: ScheduleAdminState) {
* 核心逻辑:GET /api/admin/platform-tasks/definitions,供 DynamicTaskParamsForm 按 schema 渲染。
*/
const loadPlatformTaskDefinitions = async (): Promise<void> => {
platformTaskDefinitionsLoading.value = true;
platformTaskDefinitionsError.value = false;
try {
platformTaskDefinitions.value = await listAdminPlatformTaskDefinitions();
} catch (e) {
console.error('Failed to load platform task definitions', e);
platformTaskDefinitions.value = [];
platformTaskDefinitionsError.value = true;
} finally {
platformTaskDefinitionsLoading.value = false;
}
};
@@ -1,8 +1,11 @@
/**
* features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts
* 执行批次列表:筛选、列宽、展开详情、Excel 下载与指标派生。
* 执行批次列表:筛选、列宽、展开详情、Excel 下载、指标派生与 RPA Worker 心跳轮询。
* 轮询策略(历史查询与监控职责分离):执行记录列表是纯历史查询,仅切任务/查询/重置时按需加载;
* RPA Worker 在线状态是监控信号,仅在库存排程工作台模式下每 RPA_WORKER_STATUS_POLL_MS 静默轮询一次,
* 后台标签页暂停、请求未返回时跳过(防堆叠),使「在线/离线」徽标及时反映心跳。
*/
import { computed, watch, type Ref } from 'vue';
import { computed, onBeforeUnmount, watch, type Ref } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
import { listAdminScheduleRuns, adminRunInventoryRawZipUrl, getAdminRpaWorkersStatus } from '@/features/admin/api/schedule.api';
import { useMessage } from '@/shared/composables/useMessage';
@@ -33,6 +36,7 @@ export function useScheduleAdminRuns(
scheduleRunColumnDefs,
resizingScheduleCol,
expandedScheduleRunId,
scheduleViewMode,
} = state;
const syncScheduleRunColumnLabels = () => {
@@ -162,21 +166,63 @@ export function useScheduleAdminRuns(
return latest ? formatDateTime(String(latest)) : '-';
});
const refreshRpaWorkerStatus = async () => {
/**
* 拉取 RPA Worker 心跳状态概览(刷新「在线/离线」徽标与最后心跳时间)。
* @param silent - 静默模式:由后台轮询调用,不翻转 loading,避免徽标每轮闪烁「加载中」
*/
const refreshRpaWorkerStatus = async (silent = false) => {
if (!isInventoryRpaSchedule.value) {
rpaWorkerStatus.value = null;
return;
}
rpaWorkerStatusLoading.value = true;
if (!silent) rpaWorkerStatusLoading.value = true;
try {
rpaWorkerStatus.value = await getAdminRpaWorkersStatus();
} catch {
rpaWorkerStatus.value = null;
} finally {
rpaWorkerStatusLoading.value = false;
if (!silent) rpaWorkerStatusLoading.value = false;
}
};
// ── RPA Worker 心跳轮询(监控信号,仅库存排程) ─────────────────────────
// 心跳由 Worker 每约 20s 上报一次(服务端 TTL 默认 90s),UI 每 10s 刷新即足够;
// 2s 固定轮询只有少量时间点在变化,属于对无变化数据的过度请求。
const RPA_WORKER_STATUS_POLL_MS = 10_000;
/** 是否需要前台轮询心跳:仅工作台模式且当前排程为库存类(该徽标仅在此时可见) */
const shouldPollRpaWorkerStatus = computed(
() => scheduleViewMode.value === 'workbench' && isInventoryRpaSchedule.value && !!selectedScheduleId.value,
);
let rpaStatusPollTimer: ReturnType<typeof setInterval> | null = null;
let rpaStatusPollInFlight = false;
const stopRpaStatusPolling = () => {
if (rpaStatusPollTimer) {
clearInterval(rpaStatusPollTimer);
rpaStatusPollTimer = null;
}
};
const startRpaStatusPolling = () => {
stopRpaStatusPolling();
if (!shouldPollRpaWorkerStatus.value) return;
rpaStatusPollTimer = setInterval(async () => {
// 后台标签页不轮询;上一次请求未返回时跳过本轮,防止请求堆叠与旧响应覆盖
if (document.hidden || rpaStatusPollInFlight) return;
rpaStatusPollInFlight = true;
try {
await refreshRpaWorkerStatus(true);
} finally {
rpaStatusPollInFlight = false;
}
}, RPA_WORKER_STATUS_POLL_MS);
};
watch(shouldPollRpaWorkerStatus, startRpaStatusPolling, { immediate: true });
onBeforeUnmount(stopRpaStatusPolling);
const todayStart = () => {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T00:00:00`;
@@ -192,7 +238,12 @@ export function useScheduleAdminRuns(
scheduleRunStartedBefore.value = todayEnd();
};
const viewScheduleRuns = async (taskId: number) => {
/**
* 加载指定排程的执行记录并顺带刷新 RPA Worker 心跳状态。
* @param taskId - 排程任务 ID
* @param silentRpaStatusRefresh - 静默刷新心跳(用于「立即执行」等待轮询),不翻转 loading 徽标避免闪烁
*/
const viewScheduleRuns = async (taskId: number, silentRpaStatusRefresh = false) => {
selectedScheduleId.value = taskId;
scheduleRunsLoading.value = true;
if (!scheduleRunStartedAfter.value && !scheduleRunStartedBefore.value) {
@@ -208,7 +259,7 @@ export function useScheduleAdminRuns(
params.started_before = new Date(scheduleRunStartedBefore.value).toISOString();
}
selectedScheduleRuns.value = await listAdminScheduleRuns(taskId, params);
await refreshRpaWorkerStatus();
await refreshRpaWorkerStatus(silentRpaStatusRefresh);
} finally {
scheduleRunsLoading.value = false;
}
@@ -243,7 +294,7 @@ export function useScheduleAdminRuns(
const a = document.createElement('a');
a.href = url;
const disposition = res.headers.get('content-disposition');
a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || 'inventory-rpa-raw.zip';
a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || '库存RPA-库存.zip';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
@@ -0,0 +1,35 @@
/**
* features/admin/modules/schedules/utils/schedule-job-key.utils.spec.ts
* 验证 normalizePlatformJobKey 与后端 schedule_contract.normalize_job_key 语义一致,
* 确保 selectedPlatformTaskDefinition 对历史非规范 platform_api_path 仍能命中参数契约。
*/
import { describe, expect, it } from 'vitest';
import { normalizePlatformJobKey } from './schedule-job-key.utils';
describe('normalizePlatformJobKey', () => {
it('保留规范化连字符 key', () => {
expect(normalizePlatformJobKey('shipping-inventory-rpa')).toBe('shipping-inventory-rpa');
});
it('下划线转连字符(历史小写别名)', () => {
expect(normalizePlatformJobKey('shipping_inventory_rpa')).toBe('shipping-inventory-rpa');
});
it('大小写不敏感', () => {
expect(normalizePlatformJobKey('Shipping-Inventory-RPA')).toBe('shipping-inventory-rpa');
});
it('取完整内部路径最后一段', () => {
expect(normalizePlatformJobKey('/api/internal/jobs/shipping-inventory-rpa')).toBe('shipping-inventory-rpa');
});
it('去 query / hash / 首尾斜杠', () => {
expect(normalizePlatformJobKey('/faq-aggregate-hot?x=1#frag')).toBe('faq-aggregate-hot');
});
it('空值与 null 返回空串', () => {
expect(normalizePlatformJobKey('')).toBe('');
expect(normalizePlatformJobKey(null)).toBe('');
expect(normalizePlatformJobKey(undefined)).toBe('');
});
});
@@ -0,0 +1,26 @@
/**
* features/admin/modules/schedules/utils/schedule-job-key.utils.ts
* 平台任务 key 归一化,与后端 schedule_contract.normalize_job_key 保持同一语义。
* 逻辑:小写 → 去 query/hash → 去首尾斜杠 → 取路径最后一段 → 下划线转连字符。
* 用途:openScheduleEditModal 读入 platform_api_path 时归一化,使「平台任务」下拉回显与
* selectedPlatformTaskDefinition 的 task_type 精确匹配不受历史非规范存储值影响。
* 后端在保存时已归一化,历史数据仍可能存下划线(shipping_inventory_rpa)、完整内部路径
* (/api/internal/jobs/shipping-inventory-rpa)或大小写差异;前端此前用严格 === 字符串比较,
* 一旦不匹配即静默隐藏参数表单(含库存源),本工具修复该匹配漏洞。
*/
export function normalizePlatformJobKey(value: string | null | undefined): string {
let raw = String(value || '').trim().toLowerCase();
// 取 query 之前
const queryIdx = raw.indexOf('?');
if (queryIdx >= 0) raw = raw.slice(0, queryIdx);
// 取 hash 之前
const hashIdx = raw.indexOf('#');
if (hashIdx >= 0) raw = raw.slice(0, hashIdx);
// 去首尾斜杠
raw = raw.replace(/^\/+|\/+$/g, '');
// 取最后一段路径
const lastSlash = raw.lastIndexOf('/');
if (lastSlash >= 0) raw = raw.slice(lastSlash + 1);
// 下划线转连字符
return raw.replace(/_/g, '-');
}
@@ -0,0 +1,573 @@
<!--
features/admin/modules/shipping-audit/ShippingAuditCenterPage.vue
用途:管理员货代统一审计中心——按 Conversation/Run/Candidate/Task/Gate/节点分组筛选、详情 Diff、关联链、哈希校验、受控导出。
依赖:shipping-audit.api、shippingAuditDisplay、ShippingAuditEventDetailDrawer、Vue I18n、BusinessError、useMessage。
逻辑:列表不含快照全文;详情抽屉按权限脱敏;导出/校验写服务端访问审计;
事件分组含复核/对话/Process Gate/资格/节点;支持 candidate_no / gate_code;
窄屏用卡片列表;桌面表无横滚,Case/Task 在业务关联列,WF/Item/Run 芯片可复制。
-->
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
exportShippingAuditEvents,
getShippingAuditEvent,
listShippingAuditAssociationChain,
listShippingAuditEvents,
verifyShippingAuditHashChain,
type ShippingAuditEventDetail,
type ShippingAuditEventSummary,
type ShippingAuditFilters,
type ShippingAuditHashVerifyResult,
} from '@/features/admin/api/shipping-audit.api';
import ShippingAuditEventDetailDrawer from './ShippingAuditEventDetailDrawer.vue';
import { shippingAuditBusinessLabel } from './shippingAuditDisplay';
const { t, te } = useI18n();
const msg = useMessage();
const loading = ref(false);
const detailLoading = ref(false);
const exporting = ref(false);
const verifying = ref(false);
const moreOpen = ref(false);
const error = ref('');
const page = ref(1);
const pageSize = 25;
const total = ref(0);
const rows = ref<ShippingAuditEventSummary[]>([]);
const detail = ref<ShippingAuditEventDetail | null>(null);
const chainHint = ref('');
const verifyResult = ref<ShippingAuditHashVerifyResult | null>(null);
const filters = ref<ShippingAuditFilters>({
event_type: '',
event_type_group: '',
actor_type: '',
actor_id: '',
workflow_id: '',
workflow_item_id: '',
run_no: '',
document_id: '',
review_case_no: '',
task_no: '',
candidate_no: '',
gate_code: '',
conversation_id: '',
owner_user_id: '',
profile_id: '',
binding_id: '',
revision_no: '',
segment_id: '',
operation_id: '',
request_id: '',
reason_code: '',
result: '',
created_from: '',
created_to: '',
q: '',
});
/**
* 将 datetime-local 值规范为 ISO 字符串供 API 查询。
*/
function normalizeDateTimeFilter(value?: string): string {
const raw = String(value || '').trim();
if (!raw) return '';
const date = new Date(raw);
if (Number.isNaN(date.getTime())) return raw;
return date.toISOString();
}
/**
* 组装当前筛选 payload。
*/
function buildFilterPayload(): ShippingAuditFilters {
return {
...filters.value,
created_from: normalizeDateTimeFilter(filters.value.created_from),
created_to: normalizeDateTimeFilter(filters.value.created_to),
};
}
const formatTime = (value?: string | null) => (value ? new Date(value).toLocaleString() : '—');
/**
* 列表主区业务关联:仅 Case/Task,与 WF/Item/Run 技术编号严格分离。
*/
function primaryBusinessRefs(row: ShippingAuditEventSummary): string {
const parts = [
row.review_case_no ? `Case ${row.review_case_no}` : '',
row.task_no ? `Task ${row.task_no}` : '',
].filter(Boolean);
return parts.length ? parts.join(' · ') : '—';
}
/**
* 行级技术编号芯片(WF/Item/Run),供桌面业务关联列与窄屏卡片复用。
*/
function techRefChips(row: ShippingAuditEventSummary): Array<{ label: string; value: string }> {
return [
{ label: 'WF', value: row.workflow_id },
{ label: 'Item', value: row.workflow_item_id },
{ label: 'Run', value: row.run_no },
].filter((entry): entry is { label: string; value: string } => Boolean(entry.value));
}
/**
* 业务化标签:与详情抽屉共用 shippingAuditDisplay,保证口径一致。
*/
function businessLabel(kind: 'eventTypes' | 'actions' | 'reasonCodes' | 'actorTypes' | 'results', code?: string | null): string {
return shippingAuditBusinessLabel({ t, te }, kind, code);
}
/**
* 复制技术编号;失败时静默忽略。
*/
async function copyTechId(value?: string | null) {
const text = String(value || '').trim();
if (!text || !navigator?.clipboard?.writeText) return;
try {
await navigator.clipboard.writeText(text);
msg.success(t('admin.shippingAudit.copied'));
} catch {
/* ignore */
}
}
/**
* 统一捕获 API 错误为页面提示 + useMessage。
*/
function reportError(err: unknown, fallbackKey: string) {
if (err instanceof BusinessError) {
error.value = err.message;
msg.error(err.message);
return;
}
error.value = t(fallbackKey);
msg.error(t(fallbackKey));
}
/**
* 加载审计列表;服务端已做管理员鉴权与访问留痕。
*/
async function load() {
loading.value = true;
error.value = '';
try {
const response = await listShippingAuditEvents(page.value, pageSize, buildFilterPayload());
rows.value = response.items;
total.value = response.total;
} catch (err) {
reportError(err, 'admin.shippingAudit.loadFailed');
} finally {
loading.value = false;
}
}
/**
* 应用筛选并回到第一页。
*/
async function applyFilters() {
page.value = 1;
await load();
}
/**
* 打开详情抽屉并加载白名单 Diff。
*/
async function openDetail(eventId: number) {
detailLoading.value = true;
error.value = '';
try {
detail.value = await getShippingAuditEvent(eventId);
} catch (err) {
reportError(err, 'admin.shippingAudit.detailFailed');
} finally {
detailLoading.value = false;
}
}
/**
* 按当前关联种子拉取全链摘要提示。
*/
async function loadAssociationChain() {
error.value = '';
chainHint.value = '';
moreOpen.value = false;
try {
const payload = buildFilterPayload();
const hasSeed = Boolean(
payload.workflow_id || payload.workflow_item_id || payload.run_no
|| payload.document_id || payload.review_case_no || payload.task_no,
);
if (!hasSeed) {
error.value = t('admin.shippingAudit.chainSeedRequired');
return;
}
const chain = await listShippingAuditAssociationChain(payload, 500);
chainHint.value = t('admin.shippingAudit.chainSummary', {
total: chain.total,
truncated: chain.truncated ? t('admin.shippingAudit.chainTruncated') : '',
});
rows.value = chain.items.slice().reverse();
total.value = chain.total;
page.value = 1;
} catch (err) {
reportError(err, 'admin.shippingAudit.chainFailed');
}
}
/**
* 触发哈希链校验。
*/
async function runHashVerify() {
verifying.value = true;
error.value = '';
verifyResult.value = null;
moreOpen.value = false;
try {
const payload = buildFilterPayload();
verifyResult.value = await verifyShippingAuditHashChain({
workflow_id: payload.workflow_id || undefined,
workflow_item_id: payload.workflow_item_id || undefined,
sample_limit: 200,
});
} catch (err) {
reportError(err, 'admin.shippingAudit.verifyFailed');
} finally {
verifying.value = false;
}
}
/**
* 导出当前筛选条件下的 CSV。
*/
async function exportCsv() {
exporting.value = true;
error.value = '';
try {
await exportShippingAuditEvents(buildFilterPayload(), 'csv');
msg.success(t('admin.shippingAudit.exportDone'));
} catch (err) {
reportError(err, 'admin.shippingAudit.exportFailed');
} finally {
exporting.value = false;
}
}
const pageLabel = computed(() => String(page.value));
onMounted(() => {
void load();
});
</script>
<template>
<section class="space-y-5 p-5 md:p-7" data-testid="shipping-audit-center">
<header class="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-start sm:justify-between">
<div class="min-w-0">
<h1 class="section-title">{{ t('admin.shippingAudit.title') }}</h1>
<p class="section-desc mt-1 max-w-3xl">{{ t('admin.shippingAudit.subtitle') }}</p>
</div>
<!-- [STEP] 窄屏主操作:刷新/导出;校验与关联链收入“更多”。 -->
<div class="flex w-full flex-wrap items-center gap-2 sm:w-auto sm:justify-end">
<button type="button" class="btn-secondary btn-sm" :disabled="loading" data-testid="shipping-audit-refresh" @click="load">
{{ t('admin.shippingAudit.refresh') }}
</button>
<button type="button" class="btn-secondary btn-sm" :disabled="exporting" data-testid="shipping-audit-export" @click="exportCsv">
{{ exporting ? t('admin.shippingAudit.exporting') : t('admin.shippingAudit.export') }}
</button>
<div class="relative">
<button
type="button"
class="btn-secondary btn-sm md:hidden"
data-testid="shipping-audit-more"
@click="moreOpen = !moreOpen"
>
{{ t('admin.shippingAudit.moreActions') }}
</button>
<div
class="absolute right-0 z-10 mt-1 w-44 rounded-lg border border-default bg-surface p-1 shadow-md md:static md:mt-0 md:flex md:w-auto md:items-center md:gap-2 md:border-0 md:bg-transparent md:p-0 md:shadow-none"
:class="moreOpen ? 'block' : 'hidden md:flex'"
>
<button type="button" class="btn-secondary btn-sm w-full justify-start md:w-auto" :disabled="verifying" @click="runHashVerify">
{{ verifying ? t('admin.shippingAudit.verifying') : t('admin.shippingAudit.verifyChain') }}
</button>
<button type="button" class="btn-secondary btn-sm w-full justify-start md:w-auto" @click="loadAssociationChain">
{{ t('admin.shippingAudit.loadChain') }}
</button>
</div>
</div>
</div>
</header>
<div class="grid gap-3 rounded-xl border border-default bg-surface p-3 md:grid-cols-3 lg:grid-cols-4">
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.workflowId') }}</span>
<input v-model="filters.workflow_id" class="input-field text-sm" @keyup.enter="applyFilters">
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.workflowItemId') }}</span>
<input v-model="filters.workflow_item_id" class="input-field text-sm" @keyup.enter="applyFilters">
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.runNo') }}</span>
<input v-model="filters.run_no" class="input-field text-sm" @keyup.enter="applyFilters">
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.documentId') }}</span>
<input v-model="filters.document_id" class="input-field text-sm" @keyup.enter="applyFilters">
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.reviewCaseNo') }}</span>
<input v-model="filters.review_case_no" class="input-field text-sm" @keyup.enter="applyFilters">
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.taskNo') }}</span>
<input v-model="filters.task_no" class="input-field text-sm" @keyup.enter="applyFilters">
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.candidateNo') }}</span>
<input
v-model="filters.candidate_no"
class="input-field text-sm"
data-testid="shipping-audit-filter-candidate-no"
@keyup.enter="applyFilters"
>
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.gateCode') }}</span>
<input
v-model="filters.gate_code"
class="input-field text-sm"
data-testid="shipping-audit-filter-gate-code"
@keyup.enter="applyFilters"
>
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.actorType') }}</span>
<select v-model="filters.actor_type" class="select-field text-sm" @change="applyFilters">
<option value="">{{ t('admin.shippingAudit.filters.all') }}</option>
<option value="user">{{ t('admin.shippingAudit.labels.actorTypes.user') }}</option>
<option value="admin">{{ t('admin.shippingAudit.labels.actorTypes.admin') }}</option>
<option value="system">{{ t('admin.shippingAudit.labels.actorTypes.system') }}</option>
<option value="rpa">{{ t('admin.shippingAudit.labels.actorTypes.rpa') }}</option>
</select>
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.actorId') }}</span>
<input v-model="filters.actor_id" class="input-field text-sm" @keyup.enter="applyFilters">
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.eventTypeGroup') }}</span>
<select
v-model="filters.event_type_group"
class="select-field text-sm"
data-testid="shipping-audit-filter-event-type-group"
@change="applyFilters"
>
<option value="">{{ t('admin.shippingAudit.filters.all') }}</option>
<option value="review_workbench">{{ t('admin.shippingAudit.filters.eventTypeGroupReviewWorkbench') }}</option>
<option value="formal_task_edit">{{ t('admin.shippingAudit.filters.eventTypeGroupFormalTaskEdit') }}</option>
<option value="chat_workbench">{{ t('admin.shippingAudit.filters.eventTypeGroupChatWorkbench') }}</option>
<option value="process_gate">{{ t('admin.shippingAudit.filters.eventTypeGroupProcessGate') }}</option>
<option value="candidate_qualification">{{ t('admin.shippingAudit.filters.eventTypeGroupQualification') }}</option>
<option value="workflow_node">{{ t('admin.shippingAudit.filters.eventTypeGroupWorkflowNode') }}</option>
<option value="xfa_visual">{{ t('admin.shippingAudit.filters.eventTypeGroupXfaVisual') }}</option>
<option value="xfa_split">{{ t('admin.shippingAudit.filters.eventTypeGroupXfaSplit') }}</option>
<option value="xfa_unified">{{ t('admin.shippingAudit.filters.eventTypeGroupXfaUnified') }}</option>
</select>
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.profileId') }}</span>
<input
v-model="filters.profile_id"
class="input-field text-sm"
data-testid="shipping-audit-filter-profile-id"
@keyup.enter="applyFilters"
>
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.bindingId') }}</span>
<input
v-model="filters.binding_id"
class="input-field text-sm"
data-testid="shipping-audit-filter-binding-id"
@keyup.enter="applyFilters"
>
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.eventType') }}</span>
<input v-model="filters.event_type" class="input-field text-sm" @keyup.enter="applyFilters">
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.reasonCode') }}</span>
<input v-model="filters.reason_code" class="input-field text-sm" data-testid="shipping-audit-filter-reason-code" @keyup.enter="applyFilters">
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.result') }}</span>
<input v-model="filters.result" class="input-field text-sm" @keyup.enter="applyFilters">
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.createdFrom') }}</span>
<input v-model="filters.created_from" type="datetime-local" class="input-field text-sm" @change="applyFilters">
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.createdTo') }}</span>
<input v-model="filters.created_to" type="datetime-local" class="input-field text-sm" @change="applyFilters">
</label>
<label class="space-y-1 text-xs text-secondary md:col-span-2 lg:col-span-1">
<span>{{ t('admin.shippingAudit.filters.q') }}</span>
<div class="flex gap-2">
<input v-model="filters.q" class="input-field text-sm flex-1" @keyup.enter="applyFilters">
<button type="button" class="btn-secondary btn-sm" @click="applyFilters">{{ t('admin.shippingAudit.apply') }}</button>
</div>
</label>
</div>
<p v-if="chainHint" class="rounded-lg border border-default bg-surface-soft px-3 py-2 text-xs text-secondary">{{ chainHint }}</p>
<p
v-if="verifyResult"
class="rounded-lg border border-default bg-surface-soft px-3 py-2 text-xs text-secondary"
data-testid="shipping-audit-verify-result"
>
{{ t('admin.shippingAudit.verifySummary', {
ok: verifyResult.ok ? t('admin.shippingAudit.verifyOk') : t('admin.shippingAudit.verifyFailedShort'),
checked: verifyResult.checked_chains,
failed: verifyResult.failed_chains,
}) }}
</p>
<p v-if="error" class="rounded-lg border border-rose-200 bg-rose-50 p-3 text-sm text-rose-700">{{ error }}</p>
<!-- 窄屏卡片列表:避免 1360px 表强制横向滚动才能点到 Diff -->
<div class="space-y-3 lg:hidden" data-testid="shipping-audit-card-list">
<p v-if="loading" class="rounded-xl border border-default bg-surface px-3 py-8 text-center text-sm text-muted">
{{ t('admin.shippingAudit.loading') }}
</p>
<p v-else-if="!rows.length" class="rounded-xl border border-default bg-surface px-3 py-8 text-center text-sm text-muted">
{{ t('admin.shippingAudit.empty') }}
</p>
<article
v-for="row in rows"
:key="row.id"
class="rounded-xl border border-default bg-surface p-3"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div class="text-sm font-medium text-secondary">{{ businessLabel('eventTypes', row.event_type) }}</div>
<div class="mt-0.5 text-xs text-muted">{{ businessLabel('actions', row.action) }}</div>
</div>
<button type="button" class="shrink-0 text-sm text-brand-600 hover:underline" @click="openDetail(row.id)">
{{ t('admin.shippingAudit.diff') }}
</button>
</div>
<dl class="mt-2 grid gap-1 text-xs text-secondary">
<div><dt class="inline text-muted">{{ t('admin.shippingAudit.columns.time') }}:</dt><dd class="inline">{{ formatTime(row.created_at) }}</dd></div>
<div><dt class="inline text-muted">{{ t('admin.shippingAudit.columns.actor') }}:</dt><dd class="inline">{{ businessLabel('actorTypes', row.actor_type) }}</dd></div>
<div><dt class="inline text-muted">{{ t('admin.shippingAudit.columns.reasonCode') }}:</dt><dd class="inline font-medium">{{ businessLabel('reasonCodes', row.reason_code) }}</dd></div>
<div><dt class="inline text-muted">{{ t('admin.shippingAudit.columns.result') }}:</dt><dd class="inline">{{ businessLabel('results', row.result) }}</dd></div>
<div v-if="primaryBusinessRefs(row) !== '—'">
<dt class="inline text-muted">{{ t('admin.shippingAudit.columns.businessRefs') }}:</dt>
<dd class="inline">{{ primaryBusinessRefs(row) }}</dd>
</div>
</dl>
<div
v-if="techRefChips(row).length"
class="mt-2 flex flex-wrap items-center gap-1.5"
data-testid="shipping-audit-tech-ref-chips"
>
<span class="text-[10px] text-muted">{{ t('admin.shippingAudit.techRefs') }}</span>
<button
v-for="item in techRefChips(row)"
:key="`${row.id}-m-tech-${item.label}`"
type="button"
class="rounded border border-default px-2 py-1 font-mono text-[11px] text-muted"
:title="item.value"
@click="copyTechId(item.value)"
>
{{ item.label }}
</button>
</div>
</article>
</div>
<!-- 桌面表:table-fixed + 无横滚;技术编号行内次要芯片,无需额外展开 -->
<div class="hidden overflow-x-hidden rounded-xl border border-default bg-surface lg:block" data-testid="shipping-audit-desktop-table">
<table class="w-full table-fixed text-left text-sm">
<thead class="border-b border-default bg-surface-soft text-xs text-muted">
<tr>
<th class="w-[16%] px-3 py-2">{{ t('admin.shippingAudit.columns.time') }}</th>
<th class="w-[20%] px-3 py-2">{{ t('admin.shippingAudit.columns.event') }}</th>
<th class="w-[10%] px-3 py-2">{{ t('admin.shippingAudit.columns.actor') }}</th>
<th class="w-[18%] px-3 py-2">{{ t('admin.shippingAudit.columns.reasonCode') }}</th>
<th class="w-[10%] px-3 py-2">{{ t('admin.shippingAudit.columns.result') }}</th>
<th class="w-[16%] px-3 py-2">{{ t('admin.shippingAudit.columns.businessRefs') }}</th>
<th class="w-[10%] px-3 py-2"></th>
</tr>
</thead>
<tbody>
<tr v-if="loading">
<td colspan="7" class="px-3 py-8 text-center text-muted">{{ t('admin.shippingAudit.loading') }}</td>
</tr>
<tr v-else-if="!rows.length">
<td colspan="7" class="px-3 py-8 text-center text-muted">{{ t('admin.shippingAudit.empty') }}</td>
</tr>
<tr
v-for="row in rows"
:key="row.id"
class="border-b border-default last:border-0"
>
<td class="px-3 py-2 align-top text-xs">{{ formatTime(row.created_at) }}</td>
<td class="px-3 py-2 align-top">
<div class="font-medium break-words">{{ businessLabel('eventTypes', row.event_type) }}</div>
<div class="text-[11px] text-muted break-words">{{ businessLabel('actions', row.action) }}</div>
</td>
<td class="px-3 py-2 align-top text-xs">{{ businessLabel('actorTypes', row.actor_type) }}</td>
<td class="px-3 py-2 align-top text-xs break-words font-medium text-secondary">
{{ businessLabel('reasonCodes', row.reason_code) }}
</td>
<td class="px-3 py-2 align-top">{{ businessLabel('results', row.result) }}</td>
<td class="px-3 py-2 align-top text-[11px] text-secondary break-words">
<div>{{ primaryBusinessRefs(row) }}</div>
<div
v-if="techRefChips(row).length"
class="mt-1 flex flex-wrap gap-1"
data-testid="shipping-audit-tech-ref-chips"
>
<button
v-for="item in techRefChips(row)"
:key="`${row.id}-tech-${item.label}`"
type="button"
class="rounded border border-default bg-surface-soft px-1 py-0.5 font-mono text-[10px] text-muted"
:title="item.value"
@click="copyTechId(item.value)"
>
{{ item.label }}
</button>
</div>
</td>
<td class="px-3 py-2 align-top">
<button type="button" class="text-brand-600 hover:underline" @click="openDetail(row.id)">
{{ t('admin.shippingAudit.diff') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="flex items-center justify-end gap-3 text-sm">
<span class="text-xs text-muted">{{ t('admin.shippingAudit.total', { count: total }) }}</span>
<button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page <= 1 || loading" @click="page -= 1; load()">{{ t('admin.shippingAudit.previous') }}</button>
<span>{{ pageLabel }}</span>
<button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page * pageSize >= total || loading" @click="page += 1; load()">{{ t('admin.shippingAudit.next') }}</button>
</div>
<ShippingAuditEventDetailDrawer
:detail="detail"
:loading="detailLoading"
@close="detail = null"
/>
</section>
</template>
@@ -0,0 +1,149 @@
/**
* features/admin/modules/shipping-audit/ShippingAuditEventDetailDrawer.spec.ts
* 用途:锁定审计详情抽屉脱敏、业务化标签与 Diff 渲染契约。
* 依赖:Vitest、@vue/test-utils、ShippingAuditEventDetailDrawer。
* 逻辑:敏感脱敏文案可见;事件/操作者/结果用业务标签;技术编号不直接平铺主区;Diff 行按 key 渲染。
*/
import { describe, expect, it, vi } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ShippingAuditEventDetailDrawer from './ShippingAuditEventDetailDrawer.vue';
import type { ShippingAuditEventDetail } from '@/features/admin/api/shipping-audit.api';
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => ({
success: vi.fn(),
warning: vi.fn(),
error: vi.fn(),
}),
}));
const messages = {
'zh-CN': {
admin: {
close: '关闭',
shippingAudit: {
detailTitle: '审计详情',
loading: '正在加载...',
sensitiveRedacted: '敏感快照已按权限脱敏',
diff: '前后差异',
before: '变更前',
after: '变更后',
noDiff: '无可展示的白名单差异',
eventHash: '事件哈希',
previousEventHash: '前序哈希',
copied: '已复制编号',
copyId: '复制编号',
techRefsHint: '技术编号默认折叠展示,点击即可复制。',
hashSection: '哈希摘要(排障用)',
beforeHash: '变更前 checksum',
afterHash: '变更后 checksum',
xfaSnapshots: 'XFA 完整快照引用',
xfaSnapshotsHint: '完整密文需敏感读权限按需打开;此处仅展示引用与用途。',
columns: {
event: '事件',
actor: '操作者',
run: 'Run',
task: 'Task',
result: '结果',
reasonCode: '原因',
refs: '关联编号',
},
filters: {
workflowId: 'Workflow',
workflowItemId: 'Workflow Item',
documentId: 'PDF/文档',
reviewCaseNo: 'Case',
operationId: 'operation_id',
requestId: 'request_id',
},
labels: {
eventTypes: {
fallback: '审计事件',
order_review_confirmed: '订单复核已确认',
status_changed: '状态已变更',
},
actions: { fallback: '业务操作' },
reasonCodes: { fallback: '业务原因' },
actorTypes: {
user: '业务用户',
system: '系统',
unknown: '未知操作者',
},
results: { success: '成功', ok: '成功' },
},
},
},
},
};
/**
* 挂载详情抽屉。
*/
function mountDrawer(detail: ShippingAuditEventDetail | null, loading = false) {
const i18n = createI18n({ legacy: false, locale: 'zh-CN', messages });
return mount(ShippingAuditEventDetailDrawer, {
props: { detail, loading },
global: { plugins: [i18n] },
});
}
describe('ShippingAuditEventDetailDrawer', () => {
it('shows sensitive redaction banner when snapshots are trimmed', () => {
const detail: ShippingAuditEventDetail = {
id: 1,
event_type: 'order_review_confirmed',
aggregate_type: 'shipping_order_review_case',
aggregate_id: 'SRC-1',
actor_type: 'user',
has_snapshots: true,
sensitive_redacted: true,
diff: [],
};
const wrapper = mountDrawer(detail);
expect(wrapper.find('[data-testid="shipping-audit-sensitive-redacted"]').exists()).toBe(true);
expect(wrapper.text()).toContain('敏感快照已按权限脱敏');
});
it('uses business labels and does not flatten raw event_type in primary meta', () => {
const detail: ShippingAuditEventDetail = {
id: 3,
event_type: 'order_review_confirmed',
action: 'unknown_action_xyz',
aggregate_type: 'shipping_order_review_case',
aggregate_id: 'SRC-3',
actor_type: 'user',
actor_id: 'u-9',
result: 'success',
run_no: 'SNER-9',
request_id: 'req-9',
has_snapshots: false,
sensitive_redacted: false,
diff: [],
};
const wrapper = mountDrawer(detail);
const text = wrapper.text();
expect(wrapper.get('[data-testid="shipping-audit-detail-event"]').text()).toContain('订单复核已确认');
expect(wrapper.get('[data-testid="shipping-audit-detail-actor"]').text()).toContain('业务用户');
expect(wrapper.get('[data-testid="shipping-audit-detail-result"]').text()).toContain('成功');
expect(text).not.toContain('order_review_confirmed');
expect(wrapper.find('[data-testid="shipping-audit-detail-tech-refs"]').exists()).toBe(true);
});
it('renders whitelist diff rows', () => {
const detail: ShippingAuditEventDetail = {
id: 2,
event_type: 'status_changed',
aggregate_type: 'order_extraction_run',
aggregate_id: 'SNER-1',
actor_type: 'system',
has_snapshots: true,
sensitive_redacted: false,
diff: [{ key: 'status', change: 'changed', before: 'queued', after: 'processing' }],
};
const wrapper = mountDrawer(detail);
expect(wrapper.find('[data-testid="shipping-audit-diff-rows"]').text()).toContain('status');
expect(wrapper.text()).toContain('queued');
expect(wrapper.text()).toContain('processing');
});
});
@@ -0,0 +1,268 @@
<!--
features/admin/modules/shipping-audit/ShippingAuditEventDetailDrawer.vue
用途:审计事件详情抽屉——业务化元数据、敏感脱敏提示、白名单 Diff、XFA 快照引用、哈希摘要。
依赖:shipping-audit.api 类型、shippingAuditDisplay、Vue I18n、useMessage。
逻辑:由 ShippingAuditCenterPage 传入 detail;事件/动作/结果与列表同源业务标签;
展示 before/after checksum 与 XFA snapshot_ref;技术编号以复制芯片展示;
若快照/metadata 含视觉绑定前后摘要则单独渲染;关闭时 emit close;不自行拉接口。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '@/shared/composables/useMessage';
import type { ShippingAuditEventDetail } from '@/features/admin/api/shipping-audit.api';
import { shippingAuditBusinessLabel } from './shippingAuditDisplay';
const props = defineProps<{
detail: ShippingAuditEventDetail | null;
loading?: boolean;
}>();
const emit = defineEmits<{
close: [];
}>();
const { t, te } = useI18n();
const msg = useMessage();
const open = computed(() => Boolean(props.detail || props.loading));
/**
* 与列表页一致的业务化标签。
*/
function label(kind: 'eventTypes' | 'actions' | 'reasonCodes' | 'actorTypes' | 'results', code?: string | null): string {
return shippingAuditBusinessLabel({ t, te }, kind, code);
}
/**
* 复制技术编号。
*/
async function copyTechId(value?: string | null) {
const text = String(value || '').trim();
if (!text || !navigator?.clipboard?.writeText) return;
try {
await navigator.clipboard.writeText(text);
msg.success(t('admin.shippingAudit.copied'));
} catch {
/* ignore */
}
}
/**
* 详情中仅展示有值的关联编号芯片。
*/
const techRefs = computed(() => {
const d = props.detail;
if (!d) return [] as Array<{ label: string; value: string }>;
return [
{ label: t('admin.shippingAudit.filters.workflowId'), value: d.workflow_id },
{ label: t('admin.shippingAudit.filters.workflowItemId'), value: d.workflow_item_id },
{ label: t('admin.shippingAudit.columns.run'), value: d.run_no },
{ label: t('admin.shippingAudit.filters.documentId'), value: d.document_id },
{ label: t('admin.shippingAudit.filters.reviewCaseNo'), value: d.review_case_no },
{ label: t('admin.shippingAudit.columns.task'), value: d.task_no },
{ label: t('admin.shippingAudit.filters.operationId'), value: d.operation_id },
{ label: t('admin.shippingAudit.filters.requestId'), value: d.request_id },
]
.map((item) => ({ label: item.label, value: String(item.value || '').trim() }))
.filter((item) => Boolean(item.value));
});
/**
* 从 before/after 快照或 metadata 提取视觉绑定前后摘要。
*/
const visualBindingDiff = computed(() => {
const d = props.detail as (ShippingAuditEventDetail & {
before_snapshot?: Record<string, unknown> | null;
after_snapshot?: Record<string, unknown> | null;
metadata?: Record<string, unknown>;
}) | null;
if (!d) return null;
const meta = d.metadata && typeof d.metadata === 'object' ? d.metadata : {};
const beforeSnap = d.before_snapshot && typeof d.before_snapshot === 'object' ? d.before_snapshot : {};
const afterSnap = d.after_snapshot && typeof d.after_snapshot === 'object' ? d.after_snapshot : {};
const before =
meta.before_visual_binding
?? beforeSnap.visual_binding
?? beforeSnap.before_visual_binding
?? null;
const after =
meta.after_visual_binding
?? afterSnap.visual_binding
?? afterSnap.after_visual_binding
?? null;
if (before == null && after == null) return null;
return { before, after };
});
/**
* 关闭抽屉。
*/
function onClose() {
emit('close');
}
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-50 flex justify-end bg-overlay"
data-testid="shipping-audit-detail-drawer"
@click.self="onClose"
>
<aside class="h-full w-full max-w-xl overflow-y-auto bg-surface p-6 shadow-2xl">
<div class="flex items-center justify-between">
<h2 class="text-lg font-bold">{{ t('admin.shippingAudit.detailTitle') }}</h2>
<button type="button" class="text-secondary" @click="onClose">{{ t('admin.close') }}</button>
</div>
<p v-if="loading" class="mt-6 text-muted">{{ t('admin.shippingAudit.loading') }}</p>
<template v-else-if="detail">
<p
v-if="detail.sensitive_redacted"
class="mt-4 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800"
data-testid="shipping-audit-sensitive-redacted"
>
{{ t('admin.shippingAudit.sensitiveRedacted') }}
</p>
<dl class="mt-5 grid grid-cols-1 gap-3 text-sm sm:grid-cols-2">
<div>
<dt class="text-xs text-muted">{{ t('admin.shippingAudit.columns.event') }}</dt>
<dd class="mt-0.5 font-medium" data-testid="shipping-audit-detail-event">
{{ label('eventTypes', detail.event_type) }}
</dd>
<dd class="text-xs text-muted">{{ label('actions', detail.action) }}</dd>
</div>
<div>
<dt class="text-xs text-muted">{{ t('admin.shippingAudit.columns.actor') }}</dt>
<dd class="mt-0.5" data-testid="shipping-audit-detail-actor">
{{ label('actorTypes', detail.actor_type) }}
<span v-if="detail.actor_id" class="text-muted"> · {{ t('admin.shippingAudit.copyId') }}</span>
</dd>
<button
v-if="detail.actor_id"
type="button"
class="mt-1 rounded border border-default px-2 py-0.5 font-mono text-[11px] text-muted"
:title="String(detail.actor_id)"
@click="copyTechId(detail.actor_id)"
>
{{ detail.actor_id }}
</button>
</div>
<div>
<dt class="text-xs text-muted">{{ t('admin.shippingAudit.columns.reasonCode') }}</dt>
<dd class="mt-0.5">{{ label('reasonCodes', detail.reason_code) }}</dd>
</div>
<div>
<dt class="text-xs text-muted">{{ t('admin.shippingAudit.columns.result') }}</dt>
<dd class="mt-0.5" data-testid="shipping-audit-detail-result">
{{ label('results', detail.result) }}
</dd>
</div>
</dl>
<section class="mt-5" data-testid="shipping-audit-detail-tech-refs">
<h3 class="text-sm font-semibold">{{ t('admin.shippingAudit.columns.refs') }}</h3>
<p class="mt-1 text-[11px] text-muted">{{ t('admin.shippingAudit.techRefsHint') }}</p>
<div v-if="techRefs.length" class="mt-2 flex flex-wrap gap-2">
<button
v-for="item in techRefs"
:key="`${item.label}-${item.value}`"
type="button"
class="rounded border border-default px-2 py-1 text-[11px] text-secondary"
:title="item.value"
@click="copyTechId(item.value)"
>
<span class="text-muted">{{ item.label }}</span>
· {{ t('admin.shippingAudit.copyId') }}
</button>
</div>
<p v-else class="mt-2 text-xs text-muted">—</p>
</section>
<details class="mt-5 rounded-lg border border-default p-3 text-xs">
<summary class="cursor-pointer font-medium text-secondary">
{{ t('admin.shippingAudit.hashSection') }}
</summary>
<dl class="mt-3 space-y-2">
<div>
<dt class="text-muted">{{ t('admin.shippingAudit.eventHash') }}</dt>
<dd class="break-all font-mono text-[10px]">{{ detail.event_hash || '—' }}</dd>
</div>
<div>
<dt class="text-muted">{{ t('admin.shippingAudit.previousEventHash') }}</dt>
<dd class="break-all font-mono text-[10px]">{{ detail.previous_event_hash || '—' }}</dd>
</div>
<div v-if="detail.before_hash">
<dt class="text-muted">{{ t('admin.shippingAudit.beforeHash') }}</dt>
<dd class="break-all font-mono text-[10px]" data-testid="shipping-audit-before-hash">{{ detail.before_hash }}</dd>
</div>
<div v-if="detail.after_hash">
<dt class="text-muted">{{ t('admin.shippingAudit.afterHash') }}</dt>
<dd class="break-all font-mono text-[10px]" data-testid="shipping-audit-after-hash">{{ detail.after_hash }}</dd>
</div>
</dl>
</details>
<section
v-if="visualBindingDiff"
class="mt-5"
data-testid="shipping-audit-visual-binding-diff"
>
<h3 class="text-sm font-semibold">{{ t('admin.shippingAudit.visualBindingDiff') }}</h3>
<p class="mt-1 text-[11px] text-muted">{{ t('admin.shippingAudit.visualBindingDiffHint') }}</p>
<div class="mt-2 space-y-2 rounded-lg border border-default p-3 text-xs">
<div>
<div class="font-medium text-muted">{{ t('admin.shippingAudit.before') }}</div>
<pre class="mt-1 whitespace-pre-wrap break-all">{{ visualBindingDiff.before == null ? '—' : JSON.stringify(visualBindingDiff.before, null, 2) }}</pre>
</div>
<div>
<div class="font-medium text-muted">{{ t('admin.shippingAudit.after') }}</div>
<pre class="mt-1 whitespace-pre-wrap break-all">{{ visualBindingDiff.after == null ? '—' : JSON.stringify(visualBindingDiff.after, null, 2) }}</pre>
</div>
</div>
</section>
<section
v-if="detail.xfa_snapshot_refs?.length"
class="mt-5"
data-testid="shipping-audit-xfa-snapshots"
>
<h3 class="text-sm font-semibold">{{ t('admin.shippingAudit.xfaSnapshots') }}</h3>
<p class="mt-1 text-[11px] text-muted">{{ t('admin.shippingAudit.xfaSnapshotsHint') }}</p>
<ul class="mt-2 space-y-2">
<li
v-for="ref in detail.xfa_snapshot_refs"
:key="ref.snapshot_ref"
class="rounded-lg border border-default px-3 py-2 text-xs"
>
<div class="font-medium">{{ ref.purpose }}</div>
<button
type="button"
class="mt-1 rounded border border-default px-2 py-0.5 font-mono text-[11px] text-muted"
:title="ref.snapshot_ref"
data-testid="shipping-audit-xfa-snapshot-ref"
@click="copyTechId(ref.snapshot_ref)"
>
{{ t('admin.shippingAudit.copyId') }} · {{ ref.snapshot_ref.slice(0, 12) }}…
</button>
</li>
</ul>
</section>
<h3 class="mt-6 font-semibold">{{ t('admin.shippingAudit.diff') }}</h3>
<div v-if="detail.diff?.length" class="mt-2 space-y-2" data-testid="shipping-audit-diff-rows">
<div
v-for="row in detail.diff"
:key="row.key"
class="rounded-lg border border-default p-3 text-xs"
>
<div class="font-medium">{{ row.key }} · {{ row.change }}</div>
<div class="mt-1 text-muted">{{ t('admin.shippingAudit.before') }}: {{ row.before == null ? '—' : JSON.stringify(row.before) }}</div>
<div class="text-muted">{{ t('admin.shippingAudit.after') }}: {{ row.after == null ? '—' : JSON.stringify(row.after) }}</div>
</div>
</div>
<p v-else class="mt-2 text-sm text-muted">{{ t('admin.shippingAudit.noDiff') }}</p>
</template>
</aside>
</div>
</template>
@@ -0,0 +1,40 @@
/**
* features/admin/modules/shipping-audit/shippingAuditDisplay.ts
* 用途:审计中心列表与详情共用的业务化标签解析。
* 依赖:vue-i18n Translator(te/t)。
* 逻辑:ShippingAuditCenterPage / ShippingAuditEventDetailDrawer 调用;
* 未知码回退通用业务文案,避免主界面直接堆叠内部事件码。
*/
export type ShippingAuditLabelKind =
| 'eventTypes'
| 'actions'
| 'reasonCodes'
| 'actorTypes'
| 'results';
export type ShippingAuditTranslate = {
t: (key: string) => string;
te: (key: string) => boolean;
};
/**
* 将审计事件/动作/原因/操作者/结果码转为业务化文案。
* @param i18n - vue-i18n te/t
* @param kind - 标签分类
* @param code - 原始稳定码
* @returns 业务文案;空码返回 —
*/
export function shippingAuditBusinessLabel(
i18n: ShippingAuditTranslate,
kind: ShippingAuditLabelKind,
code?: string | null,
): string {
const raw = String(code || '').trim();
if (!raw) return '—';
const key = `admin.shippingAudit.labels.${kind}.${raw}`;
if (i18n.te(key)) return i18n.t(key);
if (kind === 'actorTypes') return i18n.t('admin.shippingAudit.labels.actorTypes.unknown');
if (kind === 'results') return raw;
return i18n.t(`admin.shippingAudit.labels.${kind}.fallback`);
}
@@ -0,0 +1,942 @@
/**
* features/admin/modules/shipping-field-assets/ShippingFieldAssetsPage.vue
* 用途:字段资产库主工作台——标准/扩展列表、详情、扩展弃用恢复、影响与审计。
* 依赖:shipping-field-assets.api、BusinessError、useMessage、Vue I18n。
* 逻辑:由 Admin 路由挂载;视觉与订单 Schema 页对齐(页眉、双栏工作台、选中态、主次按钮);
* 采用记录可跳转唯一发货订单 Schema 的历史版本;Schema 采用规则在独立页面编辑;
* 审计优先展示属性级差异摘要,原始 JSON 折叠为技术详情。
*/
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { RouterLink } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
createShippingFieldExtension,
getShippingFieldAsset,
getShippingFieldAssetImpact,
listShippingFieldAssetAudits,
listShippingFieldAssets,
restoreShippingFieldExtension,
retireShippingFieldExtension,
updateShippingFieldExtension,
} from '@/features/admin/api/shipping-field-assets.api';
import type {
CreateShippingFieldExtensionPayload,
ShippingFieldAsset,
ShippingFieldAssetAuditEvent,
ShippingFieldAssetImpact,
} from '@/features/admin/types/shipping-field-assets.types';
const { t } = useI18n();
const message = useMessage();
const loading = ref(false);
const saving = ref(false);
const items = ref<ShippingFieldAsset[]>([]);
const selectedId = ref<string | null>(null);
const q = ref('');
const kindFilter = ref<'system_standard' | 'extension' | ''>('');
const statusFilter = ref<'active' | 'retired' | ''>('');
const impact = ref<ShippingFieldAssetImpact | null>(null);
const audits = ref<ShippingFieldAssetAuditEvent[]>([]);
const selectedDetail = ref<ShippingFieldAsset | null>(null);
const showCreate = ref(false);
const showReasonDialog = ref(false);
const reasonAction = ref<'retire' | 'restore'>('retire');
const reasonText = ref('');
const confirmImpactChecked = ref(false);
const createForm = ref<CreateShippingFieldExtensionPayload>({
field_code: '',
scope: 'header',
value_type: 'string',
display_name: '',
semantic_description: '',
});
const editName = ref('');
const editSemantic = ref('');
const selected = computed(() => selectedDetail.value || items.value.find((item) => item.id === selectedId.value) || null);
const standardItems = computed(() => items.value.filter((item) => item.asset_kind === 'system_standard'));
const extensionItems = computed(() => items.value.filter((item) => item.asset_kind === 'extension'));
/**
* 加载字段资产列表并保持当前选中项。
* 核心逻辑:调用 listShippingFieldAssets;若选中项消失则回退到首项。
*/
async function loadList(): Promise<void> {
loading.value = true;
try {
const data = await listShippingFieldAssets({
q: q.value.trim() || undefined,
asset_kind: kindFilter.value || undefined,
status: statusFilter.value || undefined,
});
items.value = data.items;
if (!selectedId.value || !items.value.some((item) => item.id === selectedId.value)) {
selectedId.value = items.value[0]?.id ?? null;
}
} catch (error) {
message.error(error instanceof BusinessError ? error.message : t('admin.shippingFieldAssets.loadFailed'));
} finally {
loading.value = false;
}
}
/**
* 加载选中资产的影响分析与审计时间线;两者独立失败,互不拖垮。
*/
async function loadDetailSidePanels(fieldId: string): Promise<void> {
impact.value = null;
audits.value = [];
const [impactResult, auditResult] = await Promise.allSettled([
getShippingFieldAssetImpact(fieldId),
listShippingFieldAssetAudits(fieldId),
]);
if (impactResult.status === 'fulfilled') {
impact.value = impactResult.value;
} else {
message.error(
impactResult.reason instanceof BusinessError
? impactResult.reason.message
: t('admin.shippingFieldAssets.impactFailed'),
);
}
if (auditResult.status === 'fulfilled') {
audits.value = auditResult.value.items;
} else {
message.error(
auditResult.reason instanceof BusinessError
? auditResult.reason.message
: t('admin.shippingFieldAssets.auditFailed'),
);
}
}
/**
* 生成管理员可读的存储落点文案。
*/
function storageLabel(item: ShippingFieldAsset): string {
if (item.storage_path) {
if (item.storage_kind === 'typed_column') {
return t('admin.shippingFieldAssets.storageTypedPath', { path: item.storage_path });
}
if (item.storage_kind === 'standard_json') {
return t('admin.shippingFieldAssets.storageStandardJsonPath', { path: item.storage_path });
}
return t('admin.shippingFieldAssets.storageExtensionJsonPath', { path: item.storage_path });
}
if (item.storage_mode === 'typed_column' && item.storage_column) {
return t('admin.shippingFieldAssets.storageTypedPath', { path: item.storage_column });
}
return item.asset_kind === 'system_standard'
? t('admin.shippingFieldAssets.storageStandardJson')
: t('admin.shippingFieldAssets.storageExtensionJson');
}
/**
* 创建扩展字段并刷新列表。
*/
async function submitCreate(): Promise<void> {
saving.value = true;
try {
const created = await createShippingFieldExtension({
...createForm.value,
field_code: createForm.value.field_code.trim().toLowerCase(),
display_name: createForm.value.display_name.trim(),
});
showCreate.value = false;
createForm.value = {
field_code: '',
scope: 'header',
value_type: 'string',
display_name: '',
semantic_description: '',
};
message.success(t('admin.shippingFieldAssets.createSuccess'));
await loadList();
selectedId.value = created.id;
} catch (error) {
message.error(error instanceof BusinessError ? error.message : t('admin.shippingFieldAssets.saveFailed'));
} finally {
saving.value = false;
}
}
/**
* 保存扩展字段显示名与语义说明(带 updated_at 乐观锁)。
*/
async function saveExtensionMeta(): Promise<void> {
if (!selected.value || selected.value.asset_kind !== 'extension') return;
if (!selected.value.updated_at) {
message.error(t('admin.shippingFieldAssets.lockMissing'));
return;
}
saving.value = true;
try {
selectedDetail.value = await updateShippingFieldExtension(selected.value.id, {
display_name: editName.value.trim(),
semantic_description: editSemantic.value.trim() || undefined,
expected_updated_at: selected.value.updated_at,
});
message.success(t('admin.shippingFieldAssets.updateSuccess'));
await loadList();
} catch (error) {
message.error(error instanceof BusinessError ? error.message : t('admin.shippingFieldAssets.saveFailed'));
} finally {
saving.value = false;
}
}
/**
* 打开弃用/恢复原因对话框;弃用前确保已加载影响分析。
*/
async function openReasonDialog(action: 'retire' | 'restore'): Promise<void> {
reasonAction.value = action;
reasonText.value = '';
confirmImpactChecked.value = false;
if (action === 'retire' && selectedId.value) {
if (!impact.value) {
await loadDetailSidePanels(selectedId.value);
}
}
showReasonDialog.value = true;
}
/**
* 提交弃用或恢复;弃用时若有阻断下游必须勾选确认影响。
*/
async function submitReasonAction(): Promise<void> {
if (!selected.value) return;
const reason = reasonText.value.trim();
if (!reason) {
message.error(t('admin.shippingFieldAssets.reasonRequired'));
return;
}
if (reasonAction.value === 'retire') {
const blocked = (impact.value?.blocking_count || 0) > 0;
if (blocked && !confirmImpactChecked.value) {
message.error(t('admin.shippingFieldAssets.retireConfirmRequired'));
return;
}
}
saving.value = true;
try {
if (reasonAction.value === 'retire') {
await retireShippingFieldExtension(selected.value.id, reason, {
confirmImpact: confirmImpactChecked.value || (impact.value?.blocking_count || 0) === 0,
});
message.success(t('admin.shippingFieldAssets.retireSuccess'));
} else {
await restoreShippingFieldExtension(selected.value.id, reason);
message.success(t('admin.shippingFieldAssets.restoreSuccess'));
}
showReasonDialog.value = false;
await loadList();
} catch (error) {
if (
error instanceof BusinessError
&& error.code === 'SHIPPING.FIELD_ASSET_RETIRE_IMPACT_CONFIRM_REQUIRED'
&& error.details
) {
impact.value = error.details as ShippingFieldAssetImpact;
message.error(t('admin.shippingFieldAssets.retireConfirmRequired'));
} else {
message.error(error instanceof BusinessError ? error.message : t('admin.shippingFieldAssets.saveFailed'));
}
} finally {
saving.value = false;
}
}
/**
* 资产显示名:默认名优先,否则 field_code。
*/
function displayLabel(item: ShippingFieldAsset): string {
return item.display_name_default || item.field_code;
}
/**
* 将影响 kind 映射为可读文案。
*/
function blockingLabel(kind: string): string {
const key = `admin.shippingFieldAssets.impactKind.${kind}`;
const translated = t(key);
return translated !== key ? translated : kind;
}
/**
* 将审计事件类型映射为可读文案。
*/
function auditEventLabel(eventType: string): string {
const key = `admin.shippingFieldAssets.auditEvent.${eventType}`;
const translated = t(key);
return translated !== key ? translated : eventType;
}
/**
* 计算审计前后快照的属性级差异行,对象/数组展开为可读业务摘要。
* @param before - 变更前快照
* @param after - 变更后快照
* @returns 差异行(路径 + 格式化前后值)
*/
function snapshotPropertyDiffs(
before: Record<string, unknown> | null | undefined,
after: Record<string, unknown> | null | undefined,
): Array<{ key: string; label: string; before: string; after: string }> {
const left = before && typeof before === 'object' && !Array.isArray(before) ? before : {};
const right = after && typeof after === 'object' && !Array.isArray(after) ? after : {};
return flattenObjectDiffs(left, right);
}
/**
* 将属性路径映射为业务标签;未知路径回退为路径本身。
* @param path - 点分属性路径
*/
function auditPropertyLabel(path: string): string {
const leaf = path.replace(/\[\d+\]/g, '').split('.').filter(Boolean).pop() || path;
const key = `admin.shippingFieldAssets.auditProperty.${leaf}`;
const translated = t(key);
return translated !== key ? translated : path;
}
/**
* 递归展开两个对象的差异;数组与标量在叶节点格式化。
* @param before - 变更前对象
* @param after - 变更后对象
* @param prefix - 当前路径前缀
*/
function flattenObjectDiffs(
before: Record<string, unknown>,
after: Record<string, unknown>,
prefix = '',
): Array<{ key: string; label: string; before: string; after: string }> {
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
const rows: Array<{ key: string; label: string; before: string; after: string }> = [];
for (const key of [...keys].sort()) {
const path = prefix ? `${prefix}.${key}` : key;
const left = before[key];
const right = after[key];
if (JSON.stringify(left) === JSON.stringify(right)) continue;
const bothPlainObjects = isPlainObject(left) && isPlainObject(right);
if (bothPlainObjects) {
rows.push(...flattenObjectDiffs(left as Record<string, unknown>, right as Record<string, unknown>, path));
continue;
}
// 同构对象数组:按索引展开子属性,便于识别批量排序/条目变更。
if (Array.isArray(left) && Array.isArray(right) && left.every(isPlainObject) && right.every(isPlainObject)) {
const max = Math.max(left.length, right.length);
if (left.length !== right.length) {
rows.push({
key: `${path}.length`,
label: t('admin.shippingFieldAssets.auditArrayLength', { path: auditPropertyLabel(path) }),
before: String(left.length),
after: String(right.length),
});
}
for (let index = 0; index < max; index += 1) {
const itemBefore = (left[index] as Record<string, unknown> | undefined) || {};
const itemAfter = (right[index] as Record<string, unknown> | undefined) || {};
if (JSON.stringify(itemBefore) === JSON.stringify(itemAfter)) continue;
rows.push(...flattenObjectDiffs(itemBefore, itemAfter, `${path}[${index}]`));
}
continue;
}
rows.push({
key: path,
label: auditPropertyLabel(path),
before: formatBusinessValue(left),
after: formatBusinessValue(right),
});
}
return rows;
}
/**
* 判断是否为可展开的普通对象(排除数组与 null)。
*/
function isPlainObject(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
/**
* 将审计属性值格式化为业务可读短文案。
* @param value - 任意快照值
*/
function formatBusinessValue(value: unknown): string {
if (value === undefined) return '—';
if (value === null) return t('admin.shippingFieldAssets.auditValueNull');
if (typeof value === 'boolean') {
return value
? t('admin.shippingFieldAssets.auditValueYes')
: t('admin.shippingFieldAssets.auditValueNo');
}
if (typeof value === 'string') return value.trim() ? value : t('admin.shippingFieldAssets.auditValueEmpty');
if (typeof value === 'number') return String(value);
if (Array.isArray(value)) {
if (!value.length) return t('admin.shippingFieldAssets.auditValueEmptyList');
if (value.every((item) => typeof item === 'string' || typeof item === 'number' || typeof item === 'boolean')) {
return value.map((item) => formatBusinessValue(item)).join('、');
}
return t('admin.shippingFieldAssets.auditValueObjectList', { count: value.length });
}
if (isPlainObject(value)) {
const entries = Object.entries(value);
if (!entries.length) return t('admin.shippingFieldAssets.auditValueEmpty');
// 浅对象:列出关键键值,避免整段压缩 JSON。
const preferred = ['field_code', 'display_name', 'display_name_default', 'status', 'scope', 'value_type', 'action', 'reason'];
const ordered = [
...preferred.filter((key) => key in value),
...entries.map(([key]) => key).filter((key) => !preferred.includes(key)),
].slice(0, 6);
return ordered
.map((key) => `${auditPropertyLabel(key)}=${formatBusinessValue(value[key])}`)
.join(' · ');
}
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
/**
* 格式化审计变更摘要为可读短句。
*/
function auditSummaryText(event: ShippingFieldAssetAuditEvent): string {
const summary = event.change_summary || {};
const parts: string[] = [];
if (typeof summary.reason === 'string' && summary.reason.trim()) {
parts.push(t('admin.shippingFieldAssets.auditReason', { reason: summary.reason }));
}
if (typeof summary.action === 'string' && summary.action.trim()) {
parts.push(String(summary.action));
}
if (typeof summary.schema_version === 'number') {
parts.push(t('admin.shippingFieldAssets.auditSchemaVersion', { version: summary.schema_version }));
}
if (typeof summary.field_code === 'string') {
parts.push(String(summary.field_code));
}
if (typeof summary.blocking_count === 'number' && summary.blocking_count > 0) {
parts.push(t('admin.shippingFieldAssets.blockingCount', { count: summary.blocking_count }));
}
return parts.join(' · ') || t('admin.shippingFieldAssets.auditSummaryEmpty');
}
/**
* 列表行治理标签:范围 / 类型 / 采用 / 状态。
*/
function listMeta(item: ShippingFieldAsset): string {
const scope = item.scope === 'header'
? t('admin.shippingFieldAssets.scopeHeader')
: t('admin.shippingFieldAssets.scopeLine');
const adoption = item.adoption_summary?.published
? t('admin.shippingFieldAssets.adoptedPublished', { count: item.adoption_summary.published })
: item.adoption_summary?.draft
? t('admin.shippingFieldAssets.adoptedDraft', { count: item.adoption_summary.draft })
: t('admin.shippingFieldAssets.adoptedNone');
const status = item.status === 'retired'
? t('admin.shippingFieldAssets.statusRetired')
: t('admin.shippingFieldAssets.statusActive');
return `${scope} · ${item.value_type} · ${adoption} · ${status}`;
}
watch(selectedId, async (id) => {
selectedDetail.value = null;
impact.value = null;
audits.value = [];
if (!id) return;
const row = items.value.find((item) => item.id === id);
if (row) {
editName.value = row.display_name_default || '';
editSemantic.value = row.semantic_description || '';
}
try {
selectedDetail.value = await getShippingFieldAsset(id);
editName.value = selectedDetail.value.display_name_default || '';
editSemantic.value = selectedDetail.value.semantic_description || '';
} catch (error) {
message.error(error instanceof BusinessError ? error.message : t('admin.shippingFieldAssets.detailFailed'));
}
void loadDetailSidePanels(id);
});
onMounted(() => {
void loadList();
});
</script>
<template>
<section class="mx-auto max-w-7xl space-y-6 p-6">
<header class="page-header">
<div>
<h1 class="section-title">{{ t('admin.shippingFieldAssets.title') }}</h1>
<p class="section-desc mt-1">{{ t('admin.shippingFieldAssets.subtitle') }}</p>
</div>
<button type="button" class="btn-primary" @click="showCreate = true">
{{ t('admin.shippingFieldAssets.createExtension') }}
</button>
</header>
<div class="toolbar">
<input
v-model="q"
type="search"
class="input-field toolbar-input"
:placeholder="t('admin.shippingFieldAssets.search')"
@keyup.enter="loadList"
>
<select v-model="kindFilter" class="select-field toolbar-select" @change="loadList">
<option value="">{{ t('admin.shippingFieldAssets.kindAll') }}</option>
<option value="system_standard">{{ t('admin.shippingFieldAssets.kindStandard') }}</option>
<option value="extension">{{ t('admin.shippingFieldAssets.kindExtension') }}</option>
</select>
<select v-model="statusFilter" class="select-field toolbar-select" @change="loadList">
<option value="">{{ t('admin.shippingFieldAssets.statusAll') }}</option>
<option value="active">{{ t('admin.shippingFieldAssets.statusActive') }}</option>
<option value="retired">{{ t('admin.shippingFieldAssets.statusRetired') }}</option>
</select>
<button type="button" class="btn-secondary btn-sm" :disabled="loading" @click="loadList">
{{ t('admin.shippingFieldAssets.refresh') }}
</button>
</div>
<div class="assets-workbench">
<aside class="list-panel">
<div class="panel-heading">
<div>
<h2>{{ t('admin.shippingFieldAssets.title') }}</h2>
<p>{{ t('admin.shippingFieldAssets.selectHint') }}</p>
</div>
</div>
<p v-if="loading" class="panel-empty">{{ t('admin.shippingFieldAssets.loading') }}</p>
<div v-else class="field-list">
<section class="field-group">
<div class="field-group-toggle">
<span class="field-group-title">{{ t('admin.shippingFieldAssets.standardGroup', { count: standardItems.length }) }}</span>
</div>
<button
v-for="item in standardItems"
:key="item.id"
type="button"
class="list-item"
:class="{ selected: item.id === selectedId }"
@click="selectedId = item.id"
>
<span class="list-identity">
<strong>{{ displayLabel(item) }}</strong>
<code>{{ item.field_code }}</code>
<small>{{ listMeta(item) }}</small>
</span>
</button>
</section>
<section class="field-group">
<div class="field-group-toggle">
<span class="field-group-title">{{ t('admin.shippingFieldAssets.extensionGroup', { count: extensionItems.length }) }}</span>
</div>
<button
v-for="item in extensionItems"
:key="item.id"
type="button"
class="list-item"
:class="{ selected: item.id === selectedId }"
@click="selectedId = item.id"
>
<span class="list-identity">
<strong>{{ displayLabel(item) }}</strong>
<code>{{ item.field_code }}</code>
<small>{{ listMeta(item) }}</small>
</span>
</button>
</section>
<p v-if="!items.length" class="panel-empty">{{ t('admin.shippingFieldAssets.empty') }}</p>
</div>
</aside>
<section v-if="selected" class="detail-panel">
<div class="detail-heading">
<div class="detail-heading-copy">
<p>{{ selected.asset_kind === 'system_standard' ? t('admin.shippingFieldAssets.kindStandard') : t('admin.shippingFieldAssets.kindExtension') }}</p>
<div class="field-title-line">
<h2>{{ displayLabel(selected) }}</h2>
<code>{{ selected.field_code }}</code>
</div>
</div>
<span v-if="selected.asset_kind === 'system_standard'" class="read-only-badge">
{{ t('admin.shippingFieldAssets.kindStandard') }}
</span>
</div>
<div class="detail-body">
<div class="asset-readonly">
<h3>{{ t('admin.shippingFieldAssets.kind') }}</h3>
<dl class="meta">
<div>
<dt>{{ t('admin.shippingFieldAssets.kind') }}</dt>
<dd>{{ selected.asset_kind === 'system_standard' ? t('admin.shippingFieldAssets.kindStandard') : t('admin.shippingFieldAssets.kindExtension') }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingFieldAssets.storage') }}</dt>
<dd>{{ storageLabel(selected) }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingFieldAssets.scope') }}</dt>
<dd>{{ selected.scope }} / {{ selected.value_type }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingFieldAssets.status') }}</dt>
<dd>{{ selected.status === 'retired' ? t('admin.shippingFieldAssets.statusRetired') : t('admin.shippingFieldAssets.statusActive') }}</dd>
</div>
</dl>
<p v-if="selected.asset_kind === 'system_standard'" class="hint-banner">
{{ t('admin.shippingFieldAssets.standardReadonlyHint') }}
</p>
<p v-if="selected.storage_kind === 'standard_json'" class="hint-banner">
{{ t('admin.shippingFieldAssets.standardJsonHint') }}
</p>
</div>
<div class="section-card">
<h3>{{ t('admin.shippingFieldAssets.adoptionTitle') }}</h3>
<ul v-if="selected.adoptions?.length" class="link-list">
<li v-for="item in selected.adoptions" :key="item.schema_version_id">
<RouterLink
class="adoption-link"
:to="{
path: '/admin/shipping-order-schema',
query: { version: String(item.version) },
}"
>
{{ item.schema_display_name || item.schema_code || 'Schema' }}
V{{ item.version }} ({{ item.status }})
</RouterLink>
</li>
</ul>
<p v-else class="muted">{{ t('admin.shippingFieldAssets.adoptionEmpty') }}</p>
</div>
<template v-if="selected.asset_kind === 'extension'">
<div class="section-card edit-card">
<label>
<span>{{ t('admin.shippingFieldAssets.displayName') }}</span>
<input v-model="editName" class="input-field" type="text">
</label>
<label>
<span>{{ t('admin.shippingFieldAssets.semantic') }}</span>
<textarea v-model="editSemantic" class="input-field" rows="3" />
</label>
<div class="actions">
<button type="button" class="btn-secondary btn-sm" :disabled="saving" @click="saveExtensionMeta">
{{ t('admin.shippingFieldAssets.saveMeta') }}
</button>
<button
v-if="selected.status === 'active'"
type="button"
class="btn-danger btn-sm"
:disabled="saving"
@click="openReasonDialog('retire')"
>
{{ t('admin.shippingFieldAssets.retire') }}
</button>
<button
v-else
type="button"
class="btn-secondary btn-sm"
:disabled="saving"
@click="openReasonDialog('restore')"
>
{{ t('admin.shippingFieldAssets.restore') }}
</button>
</div>
</div>
</template>
<div v-if="impact" class="section-card">
<h3>{{ t('admin.shippingFieldAssets.impactTitle') }}</h3>
<p>{{ t('admin.shippingFieldAssets.blockingCount', { count: impact.blocking_count }) }}</p>
<ul v-if="impact.blocking_items?.length" class="object-list">
<li v-for="item in impact.blocking_items" :key="`${item.kind}-${item.object_id}-${item.reference_path}`">
<strong>{{ blockingLabel(item.kind) }} · {{ item.display_name }}</strong>
<small>
#{{ item.object_id }}
<template v-if="item.version != null"> · v{{ item.version }}</template>
· {{ item.status }}
</small>
<code>{{ item.reference_path }}</code>
</li>
</ul>
<ul v-else-if="impact.blocking_kinds.length" class="plain-list">
<li v-for="kind in impact.blocking_kinds" :key="kind">{{ blockingLabel(kind) }}</li>
</ul>
<p class="muted">
{{ t('admin.shippingFieldAssets.historicalHint', {
runs: impact.historical.observation_count,
versions: impact.historical.immutable_schema_version_count,
}) }}
</p>
</div>
<div class="section-card">
<h3>{{ t('admin.shippingFieldAssets.auditTitle') }}</h3>
<p v-if="!audits.length" class="muted">{{ t('admin.shippingFieldAssets.auditEmpty') }}</p>
<ul v-else class="audit-list">
<li v-for="event in audits" :key="event.id" class="audit-item">
<div class="audit-head">
<strong>{{ auditEventLabel(event.event_type) }}</strong>
<time>{{ event.created_at || '—' }}</time>
</div>
<p class="audit-meta">
{{ t('admin.shippingFieldAssets.auditActor', { name: event.actor_display_name || t('admin.shippingFieldAssets.auditActorUnknown') }) }}
<template v-if="event.request_id"> · {{ t('admin.shippingFieldAssets.auditRequestId', { id: event.request_id }) }}</template>
</p>
<p class="audit-summary">{{ auditSummaryText(event) }}</p>
<ul
v-if="snapshotPropertyDiffs(event.before, event.after).length"
class="audit-diff-list"
>
<li
v-for="diff in snapshotPropertyDiffs(event.before, event.after)"
:key="`${event.id}-${diff.key}`"
>
<strong>{{ diff.label }}</strong>
<span>{{ diff.before }}</span>
<span aria-hidden="true">→</span>
<span>{{ diff.after }}</span>
</li>
</ul>
<details v-if="event.before || event.after" class="audit-snap">
<summary>{{ t('admin.shippingFieldAssets.auditSnapshotRaw') }}</summary>
<pre v-if="event.before">before: {{ JSON.stringify(event.before, null, 2) }}</pre>
<pre v-if="event.after">after: {{ JSON.stringify(event.after, null, 2) }}</pre>
</details>
</li>
</ul>
</div>
</div>
</section>
<section v-else class="detail-panel detail-empty">
<p class="muted">{{ t('admin.shippingFieldAssets.selectHint') }}</p>
</section>
</div>
<div v-if="showCreate" class="impact-overlay" @click.self="showCreate = false">
<div class="impact-dialog">
<header>
<h2>{{ t('admin.shippingFieldAssets.createExtension') }}</h2>
<button type="button" class="btn-ghost btn-sm" @click="showCreate = false">{{ t('admin.shippingFieldAssets.cancel') }}</button>
</header>
<label>
<span>{{ t('admin.shippingFieldAssets.fieldCode') }}</span>
<input v-model="createForm.field_code" class="input-field">
</label>
<label>
<span>{{ t('admin.shippingFieldAssets.displayName') }}</span>
<input v-model="createForm.display_name" class="input-field">
</label>
<label>
<span>{{ t('admin.shippingFieldAssets.scope') }}</span>
<select v-model="createForm.scope" class="select-field">
<option value="header">header</option>
<option value="line">line</option>
</select>
</label>
<label>
<span>{{ t('admin.shippingFieldAssets.valueType') }}</span>
<select v-model="createForm.value_type" class="select-field">
<option value="string">string</option>
<option value="decimal">decimal</option>
<option value="integer">integer</option>
<option value="date">date</option>
<option value="boolean">boolean</option>
<option value="enum">enum</option>
</select>
</label>
<label>
<span>{{ t('admin.shippingFieldAssets.semantic') }}</span>
<textarea v-model="createForm.semantic_description" class="input-field" rows="3" />
</label>
<footer>
<button type="button" class="btn-secondary" @click="showCreate = false">{{ t('admin.shippingFieldAssets.cancel') }}</button>
<button type="button" class="btn-primary" :disabled="saving" @click="submitCreate">{{ t('admin.shippingFieldAssets.confirm') }}</button>
</footer>
</div>
</div>
<div v-if="showReasonDialog" class="impact-overlay" @click.self="showReasonDialog = false">
<div class="impact-dialog">
<header>
<h2>{{ reasonAction === 'retire' ? t('admin.shippingFieldAssets.retire') : t('admin.shippingFieldAssets.restore') }}</h2>
<button type="button" class="btn-ghost btn-sm" @click="showReasonDialog = false">{{ t('admin.shippingFieldAssets.cancel') }}</button>
</header>
<p class="muted">{{ t('admin.shippingFieldAssets.reasonHint') }}</p>
<template v-if="reasonAction === 'retire'">
<div class="impact-summary">
<p>{{ t('admin.shippingFieldAssets.retireImpactSummary', { count: impact?.blocking_count || 0 }) }}</p>
<ul v-if="impact?.blocking_items?.length">
<li v-for="item in impact.blocking_items" :key="`${item.kind}-${item.object_id}`">
{{ blockingLabel(item.kind) }} · {{ item.display_name }} ({{ item.status }})
</li>
</ul>
<label v-if="(impact?.blocking_count || 0) > 0" class="confirm-row">
<input v-model="confirmImpactChecked" type="checkbox">
{{ t('admin.shippingFieldAssets.retireConfirmCheckbox') }}
</label>
</div>
</template>
<textarea v-model="reasonText" class="input-field" rows="4" />
<footer>
<button type="button" class="btn-secondary" @click="showReasonDialog = false">{{ t('admin.shippingFieldAssets.cancel') }}</button>
<button type="button" class="btn-primary" :disabled="saving" @click="submitReasonAction">{{ t('admin.shippingFieldAssets.confirm') }}</button>
</footer>
</div>
</div>
</section>
</template>
<style scoped>
.page-header { display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: space-between; gap: 16px; }
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.toolbar-input, .toolbar-select { min-width: 160px; padding: 7px 9px; font: inherit; font-size: 12px; }
.toolbar-input { min-width: 220px; flex: 1 1 220px; }
.assets-workbench {
display: grid; height: min(700px, calc(100vh - 280px)); min-height: 540px;
grid-template-columns: 320px minmax(0, 1fr); overflow: hidden;
border: 1px solid #dfe7ef; border-radius: 10px; background: #fff;
box-shadow: 0 1px 2px rgb(15 23 42 / 3%);
}
.list-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; }
.panel-heading h2 { margin: 0; color: #1e293b; font-size: 15px; font-weight: 600; }
.panel-heading p, .panel-empty, .muted { margin: 5px 0 0; color: #94a3b8; font-size: 12px; line-height: 1.5; }
.panel-empty { padding: 24px 16px; text-align: center; }
.field-list { min-height: 0; flex: 1 1 auto; overflow-y: auto; overscroll-behavior: contain; padding: 0 8px 12px; }
.field-group { margin-top: 4px; }
.field-group-toggle {
position: sticky; z-index: 2; top: 0; display: flex; width: 100%; align-items: center;
border: 0; border-bottom: 1px solid #edf1f5; background: rgb(251 252 254 / 96%);
padding: 9px 8px 7px; color: #64748b; font: inherit; font-size: 11px; font-weight: 700; text-align: left;
backdrop-filter: blur(5px);
}
.list-item {
display: flex; width: 100%; align-items: center; gap: 8px; margin-top: 2px;
border: 0; border-radius: 7px; background: transparent; padding: 6px 8px; color: #475569;
text-align: left; cursor: pointer;
}
.list-item:hover { background: #f1f6fa; }
.list-item.selected { background: #e8f5fc; color: #0369a1; box-shadow: inset 3px 0 #0ea5e9; }
.list-identity { display: grid; min-width: 0; flex: 1; gap: 2px; }
.list-identity strong { overflow: hidden; color: #334155; font-size: 12.5px; font-weight: 650; text-overflow: ellipsis; white-space: nowrap; }
.list-identity code { overflow: hidden; color: #94a3b8; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 10px; font-weight: 400; text-overflow: ellipsis; white-space: nowrap; }
.list-identity small { color: #64748b; font-size: 10px; line-height: 1.35; }
.list-item.selected .list-identity strong,
.list-item.selected .list-identity code { color: #0369a1; }
.detail-panel { display: flex; min-width: 0; min-height: 0; flex-direction: column; overflow: hidden; background: #fff; }
.detail-empty { place-content: center; padding: 32px; text-align: center; }
.detail-heading {
display: flex; min-height: 92px; flex: 0 0 auto; align-items: center; justify-content: space-between;
gap: 18px; border-bottom: 1px solid #e5ebf1; padding: 16px 24px;
}
.detail-heading-copy { min-width: 0; }
.detail-heading-copy > p { margin: 0 0 4px; color: #94a3b8; font-size: 12px; }
.field-title-line { display: flex; min-width: 0; align-items: baseline; gap: 10px; }
.field-title-line h2 { margin: 0; overflow: hidden; color: #1e293b; font-size: 17px; font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }
.field-title-line code { color: #64748b; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 11px; }
.read-only-badge { border: 1px solid #cbd5e1; border-radius: 999px; background: #f8fafc; padding: 4px 9px; color: #64748b; font-size: 11px; font-weight: 600; }
.detail-body {
display: grid; min-height: 0; flex: 1 1 auto; align-content: start; gap: 18px;
overflow-x: hidden; overflow-y: auto; overscroll-behavior: contain; padding: 22px 24px 30px; scrollbar-gutter: stable;
}
.asset-readonly, .section-card {
border: 1px solid #edf1f5; border-radius: 9px; background: #f8fafc; padding: 16px 18px;
}
.section-card { background: #fcfdff; }
.asset-readonly h3, .section-card h3 {
margin: 0 0 12px; color: #64748b; font-size: 12px; font-weight: 700; letter-spacing: .04em; text-transform: uppercase;
}
.meta { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px 18px; margin: 0; }
.meta dt { color: #64748b; font-size: 12px; }
.meta dd { margin: 5px 0 0; color: #334155; font-size: 13px; }
.hint-banner {
margin: 12px 0 0; border: 1px solid #bae6fd; border-radius: 8px; background: #f0f9ff;
padding: 12px; color: #0369a1; font-size: 12px; line-height: 1.5;
}
.edit-card { display: grid; gap: 14px; }
.edit-card label, .impact-dialog label {
display: grid; gap: 5px; color: #64748b; font-size: 12px;
}
.edit-card .input-field, .impact-dialog .input-field, .impact-dialog .select-field { min-width: 0; padding: 8px 9px; font: inherit; font-size: 13px; }
.actions, .impact-dialog footer { display: flex; flex-wrap: wrap; gap: 8px; }
.impact-dialog footer { justify-content: flex-end; }
.link-list, .plain-list { margin: 0; padding-left: 1.1rem; color: #475569; font-size: 13px; }
.adoption-link { color: #0369a1; text-decoration: underline; text-underline-offset: 2px; }
.adoption-link:hover { color: #0c4a6e; }
.object-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
.object-list li {
display: grid; gap: 2px; border: 1px solid #e2e8f0; border-radius: 8px;
background: #fff; padding: 10px 12px;
}
.object-list small, .object-list code { color: #64748b; font-size: 12px; word-break: break-all; }
.audit-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
.audit-diff-list {
list-style: none;
margin: 6px 0 0;
padding: 0;
display: grid;
gap: 4px;
font-size: 11px;
color: #334155;
}
.audit-diff-list li {
display: grid;
grid-template-columns: minmax(96px, 1.1fr) 1fr auto 1fr;
gap: 6px;
align-items: start;
}
.audit-diff-list strong {
color: #0f766e;
font-size: 11px;
font-weight: 600;
word-break: break-word;
}
.audit-diff-list code { color: #0f766e; font-size: 11px; word-break: break-all; }
.audit-item { border: 1px solid #e2e8f0; border-radius: 8px; background: #fff; padding: 10px 12px; }
.audit-head { display: flex; justify-content: space-between; gap: 12px; align-items: baseline; }
.audit-head time, .audit-meta, .audit-summary { margin: 4px 0 0; color: #64748b; font-size: 12px; }
.audit-snap { margin-top: 6px; color: #475569; font-size: 11px; }
.audit-snap pre {
margin: 6px 0 0; max-height: 10rem; overflow: auto; border-radius: 6px;
background: #f8fafc; padding: 8px; white-space: pre-wrap; word-break: break-word;
}
.impact-overlay {
position: fixed; z-index: 60; inset: 0; display: grid; place-items: center;
background: var(--overlay-soft); padding: 24px;
}
.impact-dialog {
display: grid; width: min(520px, 96vw); max-height: 82vh; gap: 14px; overflow: auto;
border-radius: 12px; background: #fff; padding: 18px; box-shadow: 0 24px 64px rgb(15 23 42 / .24);
}
.impact-dialog header { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.impact-dialog h2, .impact-dialog p { margin: 0; }
.impact-summary {
display: grid; gap: 8px; border: 1px solid #fecaca; border-radius: 8px;
background: #fef2f2; padding: 12px; color: #991b1b; font-size: 13px;
}
.confirm-row { display: flex !important; align-items: flex-start; gap: 8px; color: #334155; font-size: 13px; }
@media (max-width: 900px) {
.assets-workbench { grid-template-columns: 1fr; height: auto; min-height: 0; }
.list-panel { border-right: 0; border-bottom: 1px solid #e5ebf1; max-height: 320px; }
}
</style>
@@ -0,0 +1,118 @@
<!--
features/admin/modules/shipping-field-assets/components/FieldImpactDrawer.vue
用途:展示单字段影响分析(阻断对象明细/警告/历史只读),资产库与 Schema 页共用。
依赖:ShippingFieldAssetImpact DTO、Vue I18n、Vue Router。
逻辑:只读抽屉;列出具体配置对象与引用位置;不含订单正文或证据原文。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import type { ShippingFieldAssetImpact, ShippingFieldImpactItem } from '@/features/admin/types/shipping-field-assets.types';
defineProps<{
modelValue: boolean;
impact: ShippingFieldAssetImpact | null;
loading: boolean;
}>();
defineEmits<{ 'update:modelValue': [value: boolean] }>();
const { t } = useI18n();
const router = useRouter();
/**
* 将后端 blocking kind 映射为管理员可读的下游对象名称。
*/
function blockingLabel(kind: string): string {
const key = `admin.shippingFieldAssets.impactKind.${kind}`;
const translated = t(key);
return translated !== key ? translated : kind;
}
/**
* 打开下游配置处理入口(若提供 admin_path)。
*/
function openAdminPath(item: ShippingFieldImpactItem): void {
if (!item.admin_path) return;
void router.push(item.admin_path);
}
</script>
<template>
<div v-if="modelValue" class="impact-overlay" @click.self="$emit('update:modelValue', false)">
<aside class="impact-drawer" role="dialog" aria-modal="true">
<header>
<h2>{{ t('admin.shippingFieldAssets.impactTitle') }}</h2>
<button type="button" class="btn-ghost btn-sm" @click="$emit('update:modelValue', false)">{{ t('common.close') }}</button>
</header>
<div v-if="loading" class="impact-loading">{{ t('common.loading') }}</div>
<template v-else-if="impact">
<section v-if="impact.blocking_items?.length" class="impact-section blocked">
<h3>{{ t('admin.shippingFieldAssets.impactBlocked') }}</h3>
<p class="muted">{{ t('admin.shippingFieldAssets.blockingCount', { count: impact.blocking_count }) }}</p>
<ul class="object-list">
<li v-for="item in impact.blocking_items" :key="`${item.kind}-${item.object_id}-${item.reference_path}`">
<strong>{{ blockingLabel(item.kind) }} · {{ item.display_name }}</strong>
<small>
#{{ item.object_id }}
<template v-if="item.version != null"> · v{{ item.version }}</template>
· {{ item.status }}
</small>
<code>{{ item.reference_path }}</code>
<button
v-if="item.admin_path"
type="button"
class="link-button"
@click="openAdminPath(item)"
>
{{ t('admin.shippingFieldAssets.impactOpenTarget') }}
</button>
</li>
</ul>
</section>
<section v-else class="impact-section ok">
<p>{{ t('admin.shippingFieldAssets.impactNoBlocking') }}</p>
</section>
<section class="impact-section historical">
<h3>{{ t('admin.shippingFieldAssets.impactHistorical') }}</h3>
<ul>
<li>{{ t('admin.shippingFieldAssets.impactHistoricalVersions', { count: impact.historical.immutable_schema_version_count }) }}</li>
<li>{{ t('admin.shippingFieldAssets.impactHistoricalObservations', { count: impact.historical.observation_count }) }}</li>
<li>{{ t('admin.shippingFieldAssets.impactHistoricalValues', { count: impact.historical.value_count }) }}</li>
</ul>
<ul v-if="impact.historical.immutable_schema_versions?.length" class="object-list compact">
<li
v-for="item in impact.historical.immutable_schema_versions"
:key="item.schema_version_id"
>
{{ item.schema_display_name || item.schema_code || 'Schema' }}
V{{ item.version }} ({{ item.status }})
</li>
</ul>
<small>{{ t('admin.shippingFieldAssets.impactHistoricalHint') }}</small>
</section>
</template>
</aside>
</div>
</template>
<style scoped>
.impact-overlay { position: fixed; z-index: 60; inset: 0; display: flex; justify-content: flex-end; background: rgb(15 23 42 / 38%); }
.impact-drawer { display: grid; width: min(520px, 96vw); height: 100%; grid-template-rows: auto 1fr; gap: 12px; overflow: hidden; background: #fff; padding: 18px; box-shadow: -12px 0 40px rgb(15 23 42 / 18%); }
.impact-drawer header { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.impact-drawer h2, .impact-drawer h3 { margin: 0; color: #1e293b; font-size: 15px; }
.impact-drawer h3 { font-size: 13px; }
.link-button { border: 0; background: transparent; color: #64748b; font: inherit; font-size: 13px; cursor: pointer; }
.link-button { color: #1d4ed8; padding: 0; text-align: left; }
.impact-loading, .muted { color: #64748b; font-size: 13px; }
.impact-section { border: 1px solid #e2e8f0; border-radius: 8px; padding: 12px; overflow-y: auto; }
.impact-section.blocked { border-color: #fecaca; background: #fef2f2; }
.impact-section.ok { border-color: #bbf7d0; background: #f0fdf4; color: #166534; font-size: 13px; }
.impact-section.historical { background: #f8fafc; }
.impact-section ul { margin: 8px 0 0; padding-left: 18px; color: #475569; font-size: 12px; }
.object-list { list-style: none; padding-left: 0 !important; display: grid; gap: 0.75rem; }
.object-list li { display: grid; gap: 0.2rem; border: 1px solid #fecaca; border-radius: 0.5rem; background: #fff; padding: 0.65rem 0.75rem; }
.object-list.compact li { border-color: #e2e8f0; }
.object-list small, .object-list code { color: #64748b; font-size: 11px; word-break: break-all; }
.impact-section small { display: block; margin-top: 8px; color: #94a3b8; font-size: 11px; line-height: 1.4; }
</style>
@@ -0,0 +1,386 @@
<!--
features/admin/modules/shipping-identity-rules/ShippingIdentityRulesPage.vue
用途:维护引用已发布订单上下文字段的客户/送货站点识别定义,并发布不可变规则集。
依赖:规则 API、Vue Composition API、Vue I18n。
逻辑:管理员只能选择服务端提供的已发布识别字段,运行时只消费该字段的已裁决值。
-->
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { ArrowUpRight, Check, CircleDotDashed, CircleHelp, FileCheck2, Layers3, Plus, Send, Tags } from 'lucide-vue-next';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
createShippingIdentityRuleSet,
getShippingIdentityRuleCatalog,
listShippingIdentityRuleSets,
publishShippingIdentityRuleSet,
saveShippingIdentityDefinition,
saveShippingIdentityRuleSet,
} from '@/features/admin/api/shipping-identity-rules.api';
import type { ShippingIdentityDefinition, ShippingIdentityRuleCatalog, ShippingIdentityRuleSet } from '@/features/admin/types/shipping-identity-rules.types';
const { t } = useI18n();
const router = useRouter();
const message = useMessage();
const catalog = ref<ShippingIdentityRuleCatalog | null>(null);
const ruleSets = ref<ShippingIdentityRuleSet[]>([]);
const selectedRuleSet = ref<ShippingIdentityRuleSet | null>(null);
const selectedDefinitionIds = ref<string[]>([]);
const loading = ref(false);
const saving = ref(false);
const form = reactive({
display_name: '', description: '', evidence_label: '', target_type: 'customer', context_field_id: '',
default_weight: 100, max_automation: 'none' as 'none' | 'conditional',
});
const selectedDefinitionCount = computed(() => selectedDefinitionIds.value.length);
const activeDefinitions = computed(() => catalog.value?.definitions.filter((item) => item.status === 'active') || []);
const publishedRuleSet = computed(() => ruleSets.value.find((item) => item.status === 'published') || null);
const selectedAutomation = computed(() => {
return form.max_automation;
});
/** 说明当前来源实际从何处取值和自动化边界,帮助管理员在提交前理解选择结果。 */
const selectedSourceHint = computed(() => {
const field = catalog.value?.context_fields.find((item) => item.field_id === form.context_field_id);
return field ? `${field.display_name} (${field.field_code})` : t('admin.shippingIdentityRules.selectFieldHint');
});
const sourceDisplay = (definition: { context_field?: { field_code: string; display_name?: string } | null }): string => {
return definition.context_field?.display_name || definition.context_field?.field_code || '';
};
watch(selectedRuleSet, (ruleSet) => {
selectedDefinitionIds.value = ruleSet?.definition?.definitions.map((item) => item.id) || [];
}, { immediate: true });
const showError = (error: unknown): void => {
message.error(error instanceof BusinessError ? error.message : t('admin.shippingIdentityRules.operationFailed'));
};
const load = async (): Promise<void> => {
loading.value = true;
try {
const [nextCatalog, nextRuleSets] = await Promise.all([getShippingIdentityRuleCatalog(), listShippingIdentityRuleSets()]);
catalog.value = nextCatalog;
ruleSets.value = nextRuleSets.items;
selectedRuleSet.value = nextRuleSets.items.find((item) => item.status === 'draft') || nextRuleSets.items.find((item) => item.status === 'published') || null;
} catch (error) {
showError(error);
} finally {
loading.value = false;
}
};
/**
* 将定义写接口返回的最新数据合并到本地目录,避免保存后整页重新加载并打断管理员当前操作。
* @param definition - 后端已校验并保存的识别定义。
*/
const upsertDefinition = (definition: ShippingIdentityDefinition): void => {
if (!catalog.value) return;
const index = catalog.value.definitions.findIndex((item) => item.id === definition.id);
if (index === -1) {
catalog.value.definitions = [...catalog.value.definitions, definition];
return;
}
catalog.value.definitions.splice(index, 1, definition);
};
/**
* 用规则集写接口返回的快照更新本地版本列表,保留当前页面的编辑位置和加载状态。
* @param ruleSet - 后端返回的最新规则集版本。
*/
const upsertRuleSet = (ruleSet: ShippingIdentityRuleSet): void => {
const index = ruleSets.value.findIndex((item) => item.id === ruleSet.id);
if (index === -1) {
ruleSets.value = [ruleSet, ...ruleSets.value];
return;
}
ruleSets.value.splice(index, 1, ruleSet);
};
const saveDefinition = async (): Promise<void> => {
saving.value = true;
try {
const saved = await saveShippingIdentityDefinition({ ...form });
upsertDefinition(saved);
Object.assign(form, { display_name: '', description: '', evidence_label: '', max_automation: 'none' });
message.success(t('admin.shippingIdentityRules.definitionSaved'));
} catch (error) {
showError(error);
} finally {
saving.value = false;
}
};
/** 更新已有定义的自动化授权;已发布快照不变,下一次发布规则集时才会生效。 */
const updateDefinitionAutomation = async (
definition: ShippingIdentityDefinition,
maxAutomation: 'none' | 'conditional',
): Promise<void> => {
if (definition.max_automation === maxAutomation) return;
saving.value = true;
try {
const saved = await saveShippingIdentityDefinition({
definition_code: definition.definition_code,
display_name: definition.display_name,
description: definition.description,
evidence_label: definition.evidence_label,
target_type: definition.target_type,
context_field_id: definition.context_field_id,
default_weight: definition.default_weight,
max_automation: maxAutomation,
}, definition.id);
upsertDefinition(saved);
message.success(t('admin.shippingIdentityRules.definitionSaved'));
} catch (error) {
showError(error);
} finally {
saving.value = false;
}
};
const createDraft = async (): Promise<void> => {
saving.value = true;
try {
const draft = await createShippingIdentityRuleSet({
copy_from_rule_set_id: ruleSets.value.find((item) => item.status === 'published')?.id,
});
upsertRuleSet(draft);
selectedRuleSet.value = draft;
} catch (error) {
showError(error);
} finally {
saving.value = false;
}
};
const saveDraft = async (): Promise<void> => {
if (!selectedRuleSet.value || selectedRuleSet.value.status !== 'draft' || !catalog.value) return;
saving.value = true;
try {
const saved = await saveShippingIdentityRuleSet(selectedRuleSet.value.id, {
expected_lock_version: selectedRuleSet.value.lock_version,
definition_ids: selectedDefinitionIds.value,
});
upsertRuleSet(saved);
selectedRuleSet.value = saved;
message.success(t('admin.shippingIdentityRules.ruleSetSaved'));
} catch (error) {
showError(error);
} finally {
saving.value = false;
}
};
const publishDraft = async (): Promise<void> => {
if (!selectedRuleSet.value || selectedRuleSet.value.status !== 'draft' || !selectedDefinitionCount.value) return;
saving.value = true;
try {
// 发布必须先持久化当前勾选,避免投产上一次保存的旧规则快照。
const saved = await saveShippingIdentityRuleSet(selectedRuleSet.value.id, {
expected_lock_version: selectedRuleSet.value.lock_version,
definition_ids: selectedDefinitionIds.value,
});
const published = await publishShippingIdentityRuleSet(saved.id, saved.lock_version);
// 新发布版本会替代旧发布版本;本地同步状态而不重新装载整页。
ruleSets.value = ruleSets.value.map((item) => (
item.status === 'published' && item.id !== published.id ? { ...item, status: 'retired' } : item
));
upsertRuleSet(published);
selectedRuleSet.value = published;
message.success(t('admin.shippingIdentityRules.ruleSetPublished'));
} catch (error) {
showError(error);
} finally {
saving.value = false;
}
};
/** 发布规则集后才可维护证据,跳转保留既有工作台管理员入口。 */
const openCustomerMaster = (): void => {
router.push({ name: 'workspace-shipping-customers' });
};
onMounted(() => { void load(); });
</script>
<template>
<section class="identity-rules-page">
<header class="identity-hero">
<div>
<h1 class="section-title">{{ t('admin.shippingIdentityRules.title') }}</h1>
<p class="section-desc mt-1">{{ t('admin.shippingIdentityRules.subtitle') }}</p>
</div>
<div class="identity-hero__meta">
<div class="identity-hero__status">
<span class="identity-pulse" :class="{ 'identity-pulse--draft': !publishedRuleSet }" />
<span v-if="publishedRuleSet">V{{ publishedRuleSet.version }} · {{ t('admin.shippingIdentityRules.status.published') }}</span>
<span v-else>{{ t('admin.shippingIdentityRules.status.draft') }}</span>
</div>
<button type="button" class="btn-ghost identity-hero__link" @click="openCustomerMaster">
{{ t('admin.shippingIdentityRules.openCustomerMaster') }}<ArrowUpRight class="h-4 w-4" />
</button>
</div>
</header>
<section class="identity-flow" aria-label="workflow">
<div class="identity-flow__rail" />
<div class="identity-flow__step identity-flow__step--active"><span>01</span><div><strong>{{ t('admin.shippingIdentityRules.definitions') }}</strong><small>{{ t('admin.shippingIdentityRules.definitionHint') }}</small></div></div>
<div class="identity-flow__step"><span>02</span><div><strong>{{ t('admin.shippingIdentityRules.ruleSets') }}</strong><small>{{ t('admin.shippingIdentityRules.saveDraft') }}</small></div></div>
<div class="identity-flow__step"><span>03</span><div><strong>{{ t('admin.shippingIdentityRules.openCustomerMaster') }}</strong><small>{{ t('admin.shippingIdentityRules.workflowHint') }}</small></div></div>
</section>
<p v-if="loading" class="identity-loading"><CircleDotDashed class="h-4 w-4 animate-spin" />{{ t('admin.shippingIdentityRules.loading') }}</p>
<div v-else class="identity-workbench">
<section class="identity-panel identity-panel--definitions">
<div class="identity-panel__heading">
<div><p class="identity-panel__eyebrow"><Tags class="h-4 w-4" />{{ t('admin.shippingIdentityRules.definitions') }}</p><h3>{{ activeDefinitions.length }}</h3></div>
<p>{{ t('admin.shippingIdentityRules.definitionHint') }}</p>
</div>
<div v-if="catalog?.definitions.length" class="identity-definition-list">
<article v-for="definition in catalog.definitions" :key="definition.id" class="identity-definition-row">
<div class="identity-definition-row__icon"><Tags class="h-4 w-4" /></div>
<div class="min-w-0"><strong>{{ definition.display_name }}</strong><p>{{ definition.description || sourceDisplay(definition) }}</p></div>
<span class="identity-target">{{ t(`admin.shippingIdentityRules.targets.${definition.target_type}`) }}</span>
<select class="identity-automation identity-automation-select" :class="{ 'identity-automation--enabled': definition.max_automation === 'conditional' }" :value="definition.max_automation" :disabled="saving" @change="updateDefinitionAutomation(definition, ($event.target as HTMLSelectElement).value as 'none' | 'conditional')"><option value="none">{{ t('admin.shippingIdentityRules.automations.none') }}</option><option value="conditional">{{ t('admin.shippingIdentityRules.automations.conditional') }}</option></select>
</article>
</div>
<div v-else class="identity-empty"><Tags class="h-5 w-5" /><span>{{ t('admin.shippingIdentityRules.definitionHint') }}</span></div>
<form class="identity-definition-form" @submit.prevent="saveDefinition">
<div class="identity-form-title"><Plus class="h-4 w-4" /><strong>{{ t('admin.shippingIdentityRules.addDefinition') }}</strong></div>
<p class="identity-form-guide">{{ t('admin.shippingIdentityRules.formGuide') }}</p>
<label><span>{{ t('admin.shippingIdentityRules.displayName') }}</span><input v-model="form.display_name" required class="input-field" :placeholder="t('admin.shippingIdentityRules.displayNamePlaceholder')"></label>
<label><span>{{ t('admin.shippingIdentityRules.selectField') }}</span><select v-model="form.context_field_id" required class="input-field"><option value="">{{ t('admin.shippingIdentityRules.selectField') }}</option><option v-for="field in catalog?.context_fields" :key="field.field_id" :value="field.field_id">{{ field.display_name }}</option></select></label>
<label><span>{{ t('admin.shippingIdentityRules.target') }}</span><select v-model="form.target_type" class="input-field"><option value="customer">{{ t('admin.shippingIdentityRules.targets.customer') }}</option><option value="site">{{ t('admin.shippingIdentityRules.targets.site') }}</option></select></label>
<label><span>{{ t('admin.shippingIdentityRules.evidenceLabel') }}</span><input v-model="form.evidence_label" required class="input-field" :placeholder="t('admin.shippingIdentityRules.evidenceLabelPlaceholder')"></label>
<label><span>{{ t('admin.shippingIdentityRules.description') }}</span><input v-model="form.description" class="input-field" :placeholder="t('admin.shippingIdentityRules.descriptionPlaceholder')"></label>
<label><span class="identity-label-with-tip">{{ t('admin.shippingIdentityRules.automationPolicy') }}<CircleHelp class="identity-label-tip" :title="t('admin.shippingIdentityRules.automationPolicyHint')" :aria-label="t('admin.shippingIdentityRules.automationPolicyHint')" /></span><select v-model="form.max_automation" class="input-field"><option value="none">{{ t('admin.shippingIdentityRules.automations.none') }}</option><option value="conditional">{{ t('admin.shippingIdentityRules.automations.conditional') }}</option></select></label>
<div class="identity-source-help"><strong>{{ t('admin.shippingIdentityRules.selectionResult') }}</strong><span>{{ selectedSourceHint }}</span><small>{{ t(`admin.shippingIdentityRules.automations.${selectedAutomation}`) }}</small></div>
<button type="submit" class="btn-primary identity-definition-form__submit" :disabled="saving || !form.context_field_id"><Plus class="h-4 w-4" />{{ t('admin.shippingIdentityRules.addDefinition') }}</button>
</form>
</section>
<aside class="identity-panel identity-panel--publication">
<div class="identity-publication__header">
<div class="identity-panel__eyebrow"><Layers3 class="h-4 w-4" />{{ t('admin.shippingIdentityRules.ruleSets') }}</div>
<button type="button" class="btn-ghost btn-sm" :disabled="saving" @click="createDraft"><Plus class="h-4 w-4" />{{ t('admin.shippingIdentityRules.createDraft') }}</button>
</div>
<p class="identity-publication__hint">{{ t('admin.shippingIdentityRules.ruleSetHint') }}</p>
<div class="identity-version-list">
<button v-for="item in ruleSets" :key="item.id" type="button" class="identity-version" :class="{ 'identity-version--selected': selectedRuleSet?.id === item.id }" @click="selectedRuleSet = item">
<span>V{{ item.version }}</span><small>{{ t(`admin.shippingIdentityRules.status.${item.status}`) }}</small>
</button>
</div>
<div v-if="selectedRuleSet?.status === 'draft'" class="identity-selection">
<div class="identity-selection__heading"><span>{{ t('admin.shippingIdentityRules.definitions') }}</span><strong>{{ selectedDefinitionCount }}/{{ activeDefinitions.length }}</strong></div>
<label v-for="definition in activeDefinitions" :key="definition.id" class="identity-check-row">
<input v-model="selectedDefinitionIds" type="checkbox" :value="definition.id"><span>{{ definition.display_name }}</span><small>{{ t(`admin.shippingIdentityRules.targets.${definition.target_type}`) }}</small>
</label>
</div>
<div v-else-if="selectedRuleSet" class="identity-published-definitions">
<div class="identity-selection__heading"><span>{{ t('admin.shippingIdentityRules.publishedDefinitions') }}</span><strong>{{ selectedRuleSet.definition?.definitions.length || 0 }}</strong></div>
<div v-if="selectedRuleSet.definition?.definitions.length" class="identity-published-definition-list">
<div v-for="definition in selectedRuleSet.definition.definitions" :key="definition.id" class="identity-published-definition">
<div><strong>{{ definition.display_name }}</strong><small>{{ definition.context_field?.display_name || definition.context_field?.field_code || '-' }}</small></div>
<span class="identity-target">{{ t(`admin.shippingIdentityRules.targets.${definition.target_type}`) }}</span>
<span class="identity-automation" :class="{ 'identity-automation--enabled': definition.max_automation === 'conditional' }">{{ t(`admin.shippingIdentityRules.automations.${definition.max_automation}`) }}</span>
</div>
</div>
<p v-else class="identity-published-empty">{{ t('admin.shippingIdentityRules.publishedDefinitionsEmpty') }}</p>
</div>
<div v-if="selectedRuleSet" class="identity-publication__actions">
<template v-if="selectedRuleSet.status === 'draft'">
<button type="button" class="btn-ghost" :disabled="saving || !selectedDefinitionCount" @click="saveDraft"><FileCheck2 class="h-4 w-4" />{{ t('admin.shippingIdentityRules.saveDraft') }}</button>
<button type="button" class="btn-primary" :disabled="saving || !selectedDefinitionCount" @click="publishDraft"><Send class="h-4 w-4" />{{ t('admin.shippingIdentityRules.publish') }}</button>
</template>
<div v-else class="identity-published"><Check class="h-4 w-4" /><span>{{ t('admin.shippingIdentityRules.status.published') }}</span><code>{{ selectedRuleSet.checksum || '-' }}</code></div>
</div>
</aside>
</div>
</section>
</template>
<style scoped>
.identity-rules-page { max-width: 1380px; margin: 0 auto; display: grid; gap: 1.25rem; color: #183253; }
.identity-hero { display: flex; align-items: end; justify-content: space-between; gap: 2rem; padding: .5rem .25rem .75rem; }
.identity-panel__eyebrow { display: flex; align-items: center; gap: .45rem; color: #475569; font-size: .76rem; font-weight: 800; letter-spacing: .06em; text-transform: uppercase; }
.identity-hero h1 { margin: 0; }
.identity-hero p { max-width: 760px; }
.identity-hero__meta { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; justify-content: flex-end; }
.identity-hero__status { display: inline-flex; align-items: center; gap: .48rem; padding: .5rem .75rem; border: 1px solid #bfe7f8; border-radius: 999px; background: #effaff; color: #087aaa; font-size: .78rem; font-weight: 700; white-space: nowrap; }
.identity-pulse { width: .5rem; height: .5rem; border-radius: 50%; background: #18b17c; box-shadow: 0 0 0 4px #dff8ed; }.identity-pulse--draft { background: #e09b22; box-shadow: 0 0 0 4px #fff2d5; }
.identity-hero__link { display: inline-flex; align-items: center; gap: .35rem; white-space: nowrap; }
.identity-flow { position: relative; display: grid; grid-template-columns: repeat(3, 1fr); gap: .6rem; padding: 1rem; overflow: hidden; border: 1px solid #dce9f2; border-radius: 1rem; background: linear-gradient(105deg, #f4fbff, #fff); }
.identity-flow__rail { position: absolute; top: 1.84rem; left: 12%; right: 12%; height: 1px; background: #cce5f2; }
.identity-flow__step { position: relative; z-index: 1; display: flex; gap: .75rem; align-items: flex-start; min-width: 0; }
.identity-flow__step > span { display: grid; place-items: center; flex: 0 0 1.65rem; height: 1.65rem; border: 1px solid #b9d8e8; border-radius: 50%; background: #fff; color: #6b8298; font-size: .66rem; font-weight: 800; }
.identity-flow__step--active > span { border-color: #0d93cf; background: #0d93cf; color: #fff; box-shadow: 0 0 0 4px #dff4fc; }
.identity-flow strong { display: block; color: #193652; font-size: .82rem; font-weight: 800; }
.identity-flow small { display: -webkit-box; overflow: hidden; margin-top: .15rem; color: #7a8fa6; font-size: .72rem; line-height: 1.45; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
.identity-loading { display: flex; align-items: center; gap: .5rem; padding: 2rem; color: #6f839b; font-size: .9rem; }
.identity-workbench { display: grid; grid-template-columns: minmax(0, 1.45fr) minmax(320px, .8fr); gap: 1.25rem; align-items: start; }
.identity-panel { border: 1px solid #dce8f0; border-radius: 1rem; background: #fff; box-shadow: 0 10px 28px rgba(32, 78, 114, .055); }
.identity-panel--definitions { overflow: hidden; }
.identity-panel__heading { display: flex; align-items: end; justify-content: space-between; gap: 1rem; padding: 1.25rem 1.35rem 1rem; border-bottom: 1px solid #edf3f7; }
.identity-panel__heading h3 { margin: .2rem 0 0; color: #12395a; font-size: 2rem; font-weight: 800; line-height: 1; }
.identity-panel__heading > p { max-width: 28rem; color: #71879e; font-size: .78rem; line-height: 1.55; text-align: right; }
.identity-definition-list { display: grid; }
.identity-definition-row { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; gap: .75rem; align-items: center; padding: .78rem 1.35rem; border-bottom: 1px solid #edf3f7; transition: background .18s ease; }
.identity-definition-row:hover { background: #f7fbfd; }
.identity-definition-row__icon { display: grid; place-items: center; width: 2rem; height: 2rem; border-radius: .6rem; background: #e9f7fd; color: #0b90cc; }
.identity-definition-row strong { color: #1a3856; font-size: .86rem; font-weight: 750; }
.identity-definition-row p { overflow: hidden; margin-top: .18rem; color: #8194a8; font-size: .72rem; text-overflow: ellipsis; white-space: nowrap; }
.identity-target, .identity-automation { padding: .32rem .52rem; border-radius: 999px; background: #f1f5f8; color: #677f98; font-size: .7rem; white-space: nowrap; }
.identity-automation-select { border: 1px solid #dce8ef; cursor: pointer; }
.identity-automation--enabled { background: #e4f8ef; color: #12865c; }
.identity-empty { display: flex; align-items: center; gap: .55rem; min-height: 5.5rem; padding: 1.2rem 1.35rem; color: #7c91a7; font-size: .82rem; }
.identity-definition-form { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .85rem; padding: 1.1rem 1.35rem 1.35rem; background: linear-gradient(135deg, #f7fbfd 0%, #f3f9fc 100%); }
.identity-form-title { grid-column: 1 / -1; display: flex; align-items: center; gap: .42rem; color: #173857; font-size: .85rem; }
.identity-form-guide { grid-column: 1 / -1; margin: -.45rem 0 .1rem; color: #73889e; font-size: .75rem; line-height: 1.55; }
.identity-definition-form label { display: grid; gap: .35rem; color: #667f99; font-size: .72rem; font-weight: 700; }
.identity-label-with-tip { display: inline-flex; align-items: center; gap: .28rem; }
.identity-label-tip { width: .9rem; height: .9rem; color: #7d93a8; cursor: help; }
.identity-label-tip:focus-visible { border-radius: 50%; outline: 2px solid #7cc7eb; outline-offset: 2px; }
.identity-definition-form label small { color: #8295a8; font-size: .67rem; font-weight: 500; line-height: 1.35; }
.identity-definition-form .input-field, .identity-static-field { box-sizing: border-box; min-width: 0; height: 2.75rem; padding: 0 .8rem; border-color: #d9e7ef; background: #fff; font-size: .83rem; line-height: 1.25; }
.identity-definition-form select.input-field { padding-top: 0; padding-bottom: 0; line-height: 2.75rem; }
.identity-static-field { display: flex; align-items: center; padding: 0 .8rem; border: 1px solid #d9e7ef; border-radius: .65rem; color: #5f7893; }
.identity-source-help { display: grid; align-content: center; gap: .12rem; min-height: 2.75rem; padding: .48rem .7rem; border: 1px solid #d6eaf5; border-radius: .65rem; background: #edf8fe; color: #537189; font-size: .69rem; line-height: 1.35; }
.identity-source-help strong { color: #187eae; font-size: .72rem; }.identity-source-help small { color: #2e9068; font-size: .68rem; }
.identity-definition-form__submit { display: inline-flex; align-items: center; justify-content: center; gap: .4rem; align-self: end; min-height: 2.5rem; }
.identity-panel--publication { position: sticky; top: 1rem; padding: 1.25rem; }
.identity-publication__header { display: flex; align-items: center; justify-content: space-between; gap: .75rem; }
.identity-publication__header .btn-ghost, .identity-publication__actions button { display: inline-flex; align-items: center; justify-content: center; gap: .4rem; }
.identity-publication__hint { margin: .75rem 0 1rem; color: #75899f; font-size: .78rem; line-height: 1.6; }
.identity-version-list { display: flex; flex-wrap: wrap; gap: .5rem; padding-bottom: 1rem; border-bottom: 1px solid #e9f0f4; }
.identity-version { display: inline-flex; align-items: center; gap: .35rem; padding: .46rem .6rem; border: 1px solid #dbe7ee; border-radius: .6rem; background: #fff; color: #668099; font-size: .73rem; transition: all .18s ease; }
.identity-version:hover, .identity-version--selected { border-color: #0b91cd; background: #eefaff; color: #087cae; }
.identity-version span { font-weight: 800; }.identity-version small { font-size: .68rem; }
.identity-selection { margin: 1rem 0; }
.identity-published-definitions { margin: 1rem 0; }
.identity-published-definition-list { display: grid; gap: .45rem; }
.identity-published-definition { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; gap: .5rem; align-items: center; padding: .58rem .65rem; border: 1px solid #e5eef3; border-radius: .6rem; background: #fbfdfe; }
.identity-published-definition strong, .identity-published-definition small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.identity-published-definition strong { color: #294660; font-size: .76rem; }
.identity-published-definition small { margin-top: .15rem; color: #8194a8; font-size: .68rem; }
.identity-published-empty { margin: 0; color: #8194a8; font-size: .76rem; }
.identity-selection__heading { display: flex; justify-content: space-between; margin-bottom: .6rem; color: #274563; font-size: .78rem; font-weight: 750; }
.identity-selection__heading strong { color: #0a8bc4; }
.identity-check-row { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: .5rem; padding: .54rem 0; border-bottom: 1px dashed #e2ebf1; color: #37516c; font-size: .78rem; }
.identity-check-row input { accent-color: #0c94ce; }.identity-check-row small { color: #8496a8; font-size: .68rem; }
.identity-publication__actions { display: grid; grid-template-columns: 1fr 1fr; gap: .65rem; padding-top: 1rem; }
.identity-publication__actions .btn-primary, .identity-publication__actions .btn-ghost { min-width: 0; font-size: .79rem; }
.identity-published { grid-column: 1 / -1; display: grid; grid-template-columns: auto auto minmax(0, 1fr); align-items: center; gap: .45rem; padding: .7rem; border-radius: .65rem; background: #eaf9f0; color: #16895e; font-size: .78rem; font-weight: 700; }.identity-published code { overflow: hidden; color: #56826f; font-size: .67rem; text-align: right; text-overflow: ellipsis; white-space: nowrap; }
@media (max-width: 980px) { .identity-workbench { grid-template-columns: 1fr; }.identity-panel--publication { position: static; }.identity-hero { align-items: flex-start; flex-direction: column; gap: .85rem; }.identity-hero__meta { justify-content: flex-start; }.identity-flow__rail { display: none; } }
@media (max-width: 700px) { .identity-rules-page { gap: 1rem; }.identity-flow { grid-template-columns: 1fr; }.identity-definition-form { grid-template-columns: 1fr; }.identity-definition-row { grid-template-columns: auto minmax(0, 1fr); }.identity-target, .identity-automation { justify-self: start; }.identity-panel__heading { align-items: flex-start; flex-direction: column; }.identity-panel__heading > p { text-align: left; }.identity-definition-row__icon { grid-row: span 2; }.identity-publication__actions { grid-template-columns: 1fr; } }
@media (prefers-reduced-motion: reduce) { .identity-definition-row, .identity-version { transition: none; } }
</style>
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,33 @@
/**
* features/admin/modules/shipping-inventory/receiptReportConfigForm.spec.ts
* 用途:覆盖收料报表表单的独立载荷边界。
* 依赖:receiptReportConfigForm、vitest。
* 逻辑:防止收料配置保存时把库存站点路径、库存查询条件或启停状态误发到库存接口。
*/
import { describe, expect, it } from 'vitest';
import { buildReceiptReportConfigPayload } from './receiptReportConfigForm';
describe('receiptReportConfigForm', () => {
it('builds a receipt-only payload without inventory source fields', () => {
// 关键断言:收料路径、条件与仓库必须走独立 API,不能夹带库存 RPA 配置。
const payload = buildReceiptReportConfigPayload({
enabled: true,
report_path_json: { program_group: 'Bison', program_label: 'AWSBI', report_group: 'Inbound', report_name: 'Receipt Detail' },
query_parameters_json: [{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false }],
warehouse_ids_json: ['A', 'B'],
source_code: 'INVENTORY-SHOULD-NOT-LEAK',
snapshot_ttl_seconds: 86400,
inventory_report_path_json: { report_name: 'On Hand' },
});
expect(payload).toEqual({
enabled: true,
report_path_json: { program_group: 'Bison', program_label: 'AWSBI', report_group: 'Inbound', report_name: 'Receipt Detail' },
query_parameters_json: [{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false }],
warehouse_ids_json: ['A', 'B'],
});
expect(payload).not.toHaveProperty('source_code');
expect(payload).not.toHaveProperty('snapshot_ttl_seconds');
});
});
@@ -0,0 +1,28 @@
/**
* features/admin/modules/shipping-inventory/receiptReportConfigForm.ts
* 用途:构建独立收料报表配置的受限保存载荷。
* 依赖:无外部依赖。
* 逻辑:页面仅将收料路径、可选条件和 Warehouse 列表提交到收料配置 API,隔离库存站点字段。
*/
export type ReceiptReportConfigInput = {
enabled: boolean;
report_path_json: Record<string, unknown>;
query_parameters_json: Array<Record<string, unknown>>;
warehouse_ids_json: string[];
};
/**
* 构造独立收料配置保存载荷。
* 核心逻辑:白名单复制可配置业务字段,不允许调用方把库存源、Profile 或启停字段带入收料 API。
* @param input - 抽屉中的收料配置表单状态。
* @returns 仅包含收料配置 API 支持字段的深拷贝载荷。
*/
export function buildReceiptReportConfigPayload(input: ReceiptReportConfigInput): ReceiptReportConfigInput {
return {
enabled: Boolean(input.enabled),
report_path_json: { ...(input.report_path_json || {}) },
query_parameters_json: (input.query_parameters_json || []).map((item) => ({ ...item })),
warehouse_ids_json: [...(input.warehouse_ids_json || [])],
};
}
@@ -0,0 +1,44 @@
/**
* features/admin/modules/shipping-inventory/shippingInventoryReadiness.spec.ts
* 用途:覆盖库存站点上线检查与测试恢复的纯状态映射。
* 依赖:shippingInventoryReadiness、vitest。
* 逻辑:防止页面把已完成项目显示为待办,或持续轮询服务端已结束的测试任务。
*/
import { describe, expect, it } from 'vitest';
import type { ShippingInventoryReadinessCheck } from '@/features/admin/api/admin.api';
import { isConfigurationTestRunning, needsReadinessAction, readinessMarkerKind } from './shippingInventoryReadiness';
import { normaliseInventoryReportPath } from './shippingInventorySourceForm';
const check = (status: ShippingInventoryReadinessCheck['status'], blocking: boolean): ShippingInventoryReadinessCheck => ({
code: 'configuration_test', status, blocking, action: 'run_configuration_test', evidence: {},
});
describe('shippingInventoryReadiness', () => {
it('keeps stale checks actionable and visually distinct from ordinary pending work', () => {
// 关键断言:配置已变更的测试不能被渲染成普通待办,管理员必须重新测试。
expect(readinessMarkerKind('stale')).toBe('attention');
expect(needsReadinessAction(check('stale', true))).toBe(true);
});
it('does not offer duplicate actions for passed or non-blocking checks', () => {
// 关键断言:后端已经通过或依赖前置步骤的项目不应再次分散管理员注意力。
expect(needsReadinessAction(check('passed', false))).toBe(false);
expect(needsReadinessAction(check('pending', false))).toBe(false);
});
it('polls only server-declared running test states', () => {
// 关键断言:完成与失败均是终态,页面不得凭前端时间继续请求详情接口。
expect(isConfigurationTestRunning({ run_no: 'RUN-1', status: 'awaiting_rpa', stage: 'waiting_worker' })).toBe(true);
expect(isConfigurationTestRunning({ run_no: 'RUN-2', status: 'processing', stage: 'analysing_structure' })).toBe(true);
expect(isConfigurationTestRunning({ run_no: 'RUN-3', status: 'completed', stage: 'ready_for_confirmation' })).toBe(false);
expect(isConfigurationTestRunning({ run_no: 'RUN-4', status: 'failed', stage: 'failed' })).toBe(false);
});
it('removes DBS report paths before saving a Crane inventory source', () => {
// 关键断言:Crane 不支持 DBS 四级路径,编辑回填的默认值不得再次提交给后端。
const dbsPath = { program_group: 'Bison', program_label: 'AWSBI', report_group: 'Inventory', report_name: 'On Hand' };
expect(normaliseInventoryReportPath('crane', dbsPath)).toEqual({});
expect(normaliseInventoryReportPath('dbs', dbsPath)).toEqual(dbsPath);
});
});
@@ -0,0 +1,42 @@
/**
* features/admin/modules/shipping-inventory/shippingInventoryReadiness.ts
* 用途:归一库存站点上线检查与配置测试的前端展示状态。
* 依赖:admin.api 中的 Inventory Readiness/Test 类型。
* 逻辑:ShippingInventoryPage 调用本文件决定测试轮询、步骤标记和推荐动作;后端仍是门禁真相源。
*/
import type { ShippingInventoryConfigurationTest, ShippingInventoryReadinessCheck } from '@/features/admin/api/admin.api';
export type ReadinessMarker = 'complete' | 'attention' | 'pending';
/**
* 将后端检查状态归类为无障碍视觉标记。
* 核心逻辑:失败和过期都需要管理员处理;完成与待办分别使用稳定语义。
* @param status - 后端 `checks[]` 返回的稳定状态。
* @returns 供页面选择图形和颜色的有限标记,不参与启用门禁计算。
*/
export function readinessMarkerKind(status: ShippingInventoryReadinessCheck['status']): ReadinessMarker {
if (status === 'passed') return 'complete';
if (status === 'failed' || status === 'stale') return 'attention';
return 'pending';
}
/**
* 判断一个检查项是否应展示其唯一推荐操作。
* 核心逻辑:已通过和仅等待其他前置步骤的检查不提供重复入口。
* @param check - 后端权威检查项。
* @returns 为 true 时页面可展示对应的单一下一步动作。
*/
export function needsReadinessAction(check: ShippingInventoryReadinessCheck): boolean {
return check.status !== 'passed' && check.blocking;
}
/**
* 判断测试运行是否需要继续向服务端轮询。
* 核心逻辑:仅运行态轮询;失败与完成均为终态,防止页面无限请求。
* @param test - 当前恢复或新发起的测试运行。
* @returns 是否继续轮询。
*/
export function isConfigurationTestRunning(test: ShippingInventoryConfigurationTest | null): boolean {
return Boolean(test && ['awaiting_rpa', 'processing'].includes(test.status));
}
@@ -0,0 +1,19 @@
/**
* features/admin/modules/shipping-inventory/shippingInventorySourceForm.ts
* 用途:规范化库存站点表单中仅适用于 DBS 的报表路径字段。
* 依赖:无外部依赖,仅处理库存站点表单的连接器类型和 JSON 路径。
* 逻辑:ShippingInventoryPage 在回填、保存和脏状态比较时调用,避免非 DBS 站点携带 DBS 默认路径。
*/
export type InventoryReportPath = Record<string, unknown>;
/**
* 返回可发送给库存站点接口的报表路径。
* 核心逻辑:DBS 必须保留其四级报表路径;Crane 等非 DBS Driver 不支持该字段,统一发送空对象。
* @param connectorType - 当前库存站点的 Driver 类型。
* @param reportPath - 表单当前保存或回填的路径对象。
* @returns DBS 的路径副本,或非 DBS 的空对象;不会修改原始表单数据。
*/
export function normaliseInventoryReportPath(connectorType: unknown, reportPath: InventoryReportPath | null | undefined): InventoryReportPath {
return String(connectorType || '').trim().toLowerCase() === 'dbs' ? { ...(reportPath || {}) } : {};
}
@@ -0,0 +1,494 @@
<!--
features/admin/modules/shipping-order-document-profiles/OrderProfileBlindTestPage.vue
用途:维护订单模板草稿的独立盲测证据,并完成执行和批准。
依赖:盲测 API、Profile 详情、Vue Router、统一业务错误提示和四语言文案。
逻辑:验证页进入本页;所有模板按统一视觉表候选和字段证据复核;
末端值源差异由服务端 adapter 投影,管理员复核后写入真值,再执行并批准。
-->
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
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,
createOrderProfileTestSuite,
executeOrderProfileTestSuite,
createOrderProfileSample,
getOrderProfileSampleStatus,
listOrderProfileBlindTestAvailableSamples,
listOrderProfileBoundSamples,
previewOrderProfileBlindTestCandidate,
reparseOrderProfileSampleLayout,
removeOrderProfileTestSample,
} from '@/features/admin/api/shipping-order-document-profile.api';
import { uploadFileAsset } from '@/shared/api/file-assets.api';
import type {
OrderProfileBlindTestAvailableSample,
OrderProfileBlindTestCandidate,
OrderProfileTestSuite,
} from '@/features/admin/types/shipping-order-document-profile.types';
const route = useRoute();
const router = useRouter();
const message = useMessage();
const { t } = useI18n();
const profileId = Number(route.params.profileId);
const sessionId = String(route.query.editorSessionId || '').trim() || createRandomUuid();
const suite = ref<OrderProfileTestSuite | null>(null);
const availableSamples = ref<OrderProfileBlindTestAvailableSample[]>([]);
const selectedSampleKey = ref('');
const candidate = ref<OrderProfileBlindTestCandidate | null>(null);
const rowReviews = ref<Array<{ correct: boolean; correction: string }>>([]);
const orderFieldReviews = ref<Record<string, { correct: boolean; value: string }>>({});
const loading = ref(false);
const working = ref(false);
const hasTrainingSample = ref(false);
const availableSamplesLoaded = ref(false);
const availableSamplesLoading = ref(false);
const uploadingSample = ref(false);
const pendingUpload = ref<{ intakeNo: string; filename: string; state: 'materializing' | 'failed'; errorCode?: string | null } | null>(null);
let uploadPollingTimer: number | null = null;
let availableSamplesController: AbortController | null = null;
let availableSamplesTimeout: number | null = null;
/** 当前选择仅以 API 列表中的 document/table 组合为准,避免浏览器提交伪造样本。 */
const selectedSample = computed(() => availableSamples.value.find((item) => `${item.document_id}:${item.table_id}` === selectedSampleKey.value) || null);
/** 用安全表格摘要区分同页多表;内部 table_id 仅作为请求身份,绝不展示给管理员。 */
function sampleLabel(sample: OrderProfileBlindTestAvailableSample): string {
if (sample.table_id === '__document_candidate__') {
return t('admin.shippingOrderProfiles.blindTest.documentCandidateOption', { filename: sample.filename });
}
const header = sample.header_preview.join(' / ');
return t('admin.shippingOrderProfiles.blindTest.sampleOption', {
filename: sample.filename, page: sample.page_no, table: sample.table_index,
rows: sample.row_count, columns: sample.column_count, header,
});
}
/** 盲测执行成功且尚未批准时才允许批准;批准后证据在服务端保持不可变。 */
const canApprove = computed(() => hasTrainingSample.value && suite.value?.status === 'draft' && suite.value.latest_run?.status === 'passed');
/** 将服务端安全失败码转为管理员可定位的摘要;不回显订单正文或人工真值。 */
const failureDetails = computed(() => (suite.value?.latest_run?.failure_codes || []).map((code) => {
const parts = code.split(':');
const sampleId = parts[0] === 'sample' ? Number(parts[1]) : null;
const sample = sampleId == null ? null : suite.value?.samples.find((item) => item.id === sampleId);
const sampleName = sample ? `${sample.filename} · P${sample.page_no}` : t('admin.shippingOrderProfiles.blindTest.unknownSample');
if (parts[2] === 'order_field') {
const fieldCode = parts[3] || '';
const reason = parts[4] || '';
const reasonKey = reason === 'mismatch' ? 'fieldMismatch' : reason === 'needs_review' ? 'fieldNeedsReview' : 'fieldUnavailable';
return { code, message: t(`admin.shippingOrderProfiles.blindTest.failure.${reasonKey}`, { sample: sampleName, field: fieldCode }) };
}
if (parts[2] === 'coordinate_evidence_missing') {
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.coordinateEvidenceMissing', { sample: sampleName }) };
}
if (parts[2] === 'xfa_evidence_missing') {
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.xfaEvidenceMissing', { sample: sampleName }) };
}
if (parts[2] === 'line_count') {
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.rowsMismatch', { sample: sampleName }) };
}
if (parts[2] === 'mismatch') {
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.rowsMismatch', { sample: sampleName }) };
}
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.unknown', { sample: sampleName }) };
}));
/** 读取订单字段复核状态;候选加载完成时会初始化,默认值仅用于渲染过程中的安全兜底。 */
function orderFieldReview(fieldKey: string): { correct: boolean; value: string } {
return orderFieldReviews.value[fieldKey] || { correct: true, value: '' };
}
/** 更新单个订单字段的人工复核状态,保持其他字段复核结果不被输入事件覆盖。 */
function updateOrderFieldReview(fieldKey: string, patch: Partial<{ correct: boolean; value: string }>): void {
orderFieldReviews.value[fieldKey] = { ...orderFieldReview(fieldKey), ...patch };
}
/** 复核与服务端使用同一个 scope:field_code 键,避免同名 Header/Line 字段覆盖。 */
function orderFieldKey(field: { scope: 'header'; field_code: string }): string {
return `${field.scope}:${field.field_code}`;
}
/** 将统一业务错误转换为安全的界面提示,不暴露盲测真值或内部布局数据。 */
function report(error: unknown): void {
const code = error instanceof BusinessError ? error.code : '';
message.error(code ? t(`errors.${code}`, code) : t('admin.orderProfileValidation.failed'));
}
/** 将文件物化失败转成安全提示;版面错误只允许在预览复核阶段出现。 */
function sampleFailureMessage(): string {
return t('admin.shippingOrderProfiles.blindTest.sampleMaterializationFailed');
}
/** 创建或读取当前草稿 checksum 对应的盲测集;候选样本按需加载,避免进入页面时扫描全部历史样本。 */
async function loadSuite(): Promise<void> {
loading.value = true;
try {
const [nextSuite, boundSamples] = await Promise.all([
createOrderProfileTestSuite(profileId),
listOrderProfileBoundSamples(profileId),
]);
suite.value = nextSuite;
hasTrainingSample.value = boundSamples.some((item) => item.sample_role === 'training');
} catch (error) {
report(error);
} finally {
loading.value = false;
}
}
/** 按需读取独立样本摘要;强制刷新会替换旧请求,确保定位刚物化的文档。 */
async function loadAvailableSamples(force = false): Promise<void> {
if (!suite.value || suite.value.status !== 'draft') return;
if (!force && (availableSamplesLoaded.value || availableSamplesLoading.value)) return;
availableSamplesController?.abort();
if (availableSamplesTimeout) window.clearTimeout(availableSamplesTimeout);
const controller = new AbortController();
availableSamplesController = controller;
availableSamplesLoading.value = true;
let timedOut = false;
availableSamplesTimeout = window.setTimeout(() => {
timedOut = true;
controller.abort();
}, 15_000);
try {
availableSamples.value = (await listOrderProfileBlindTestAvailableSamples(suite.value.id, controller.signal)).samples;
availableSamplesLoaded.value = true;
} catch (error) {
if (timedOut) {
message.error(t('admin.shippingOrderProfiles.blindTest.loadIndependentSamplesTimedOut'));
} else if (!controller.signal.aborted) {
report(error);
}
} finally {
if (availableSamplesController === controller) {
availableSamplesController = null;
availableSamplesLoading.value = false;
if (availableSamplesTimeout) window.clearTimeout(availableSamplesTimeout);
availableSamplesTimeout = null;
}
}
}
/** 停止上传样本的后台轮询,避免离开盲测页后继续向已卸载页面写入状态。 */
function stopUploadPolling(): void {
if (uploadPollingTimer) window.clearTimeout(uploadPollingTimer);
uploadPollingTimer = null;
}
/** 文件物化后精确选中同一 Intake 的候选;后台版面预热不参与上传成功判定。 */
async function pollUploadedSample(intakeNo: string): Promise<void> {
try {
const result = await getOrderProfileSampleStatus(intakeNo);
// 与样本列表的可见条件一致:文档物化且 Layout ready 后才进入候选列表。
if (result.parse_status === 'parsed' && result.document_count > 0 && result.layout_status === 'ready') {
await loadAvailableSamples(true);
const selected = availableSamples.value.find((item) => (result.document_ids || []).includes(item.document_id));
if (selected) {
selectedSampleKey.value = `${selected.document_id}:${selected.table_id}`;
pendingUpload.value = null;
message.success(t('admin.shippingOrderProfiles.blindTest.sampleUploaded'));
} else {
pendingUpload.value = null;
message.success(t('admin.shippingOrderProfiles.blindTest.sampleUploaded'));
message.error(t('admin.shippingOrderProfiles.blindTest.noIndependentSamples'));
}
return;
}
if (['failed', 'error'].includes(result.parse_status) || result.layout_status === 'failed') {
await loadAvailableSamples(true);
const selected = availableSamples.value.find((item) => (result.document_ids || []).includes(item.document_id));
if (selected) {
selectedSampleKey.value = `${selected.document_id}:${selected.table_id}`;
pendingUpload.value = null;
message.success(t('admin.shippingOrderProfiles.blindTest.sampleAcceptedForReview'));
} else {
pendingUpload.value = {
intakeNo, filename: pendingUpload.value?.filename || '', state: 'failed', errorCode: result.error_code,
};
}
return;
}
uploadPollingTimer = window.setTimeout(() => void pollUploadedSample(intakeNo), 1500);
} catch {
uploadPollingTimer = window.setTimeout(() => void pollUploadedSample(intakeNo), 2000);
}
}
/** 上传 PDF/EML 到隔离模板样本池;上传后不会自动写入盲测真值。 */
async function uploadIndependentSample(event: Event): Promise<void> {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = '';
if (!file || uploadingSample.value) return;
if (!/\.(pdf|eml)$/i.test(file.name)) {
message.error(t('admin.shippingOrderProfiles.sampleFileTypeInvalid'));
return;
}
stopUploadPolling();
uploadingSample.value = true;
try {
const asset = await uploadFileAsset(file);
const intake = await createOrderProfileSample(asset.asset_no);
pendingUpload.value = { intakeNo: intake.intake_no, filename: file.name, state: 'materializing' };
void pollUploadedSample(intake.intake_no);
} catch (error) {
report(error);
} finally {
uploadingSample.value = false;
}
}
/** 运行选中独立样本并初始化逐行、逐订单字段的人工复核表单。 */
async function previewSample(): Promise<void> {
if (!suite.value || !selectedSample.value) return;
if (selectedSample.value.review_mode === 'preparing') {
message.error(t('admin.shippingOrderProfiles.blindTest.reviewPreparing'));
return;
}
working.value = true;
try {
candidate.value = await previewOrderProfileBlindTestCandidate(suite.value.id, selectedSample.value);
rowReviews.value = candidate.value.rows.map(() => ({ correct: true, correction: '' }));
orderFieldReviews.value = Object.fromEntries(candidate.value.order_fields.map((field) => [
orderFieldKey(field),
{ correct: true, value: field.value == null ? '' : String(field.value) },
]));
} catch (error) {
report(error);
} finally {
working.value = false;
}
}
/** 为缺少坐标证据的样本重新触发布局解析;完成后刷新候选状态再进入复核。 */
async function reprocessSelectedSample(): Promise<void> {
if (!selectedSample.value || selectedSample.value.review_mode !== 'preparing') return;
working.value = true;
try {
await reparseOrderProfileSampleLayout(selectedSample.value.document_id);
message.success(t('admin.shippingOrderProfiles.blindTest.layoutReparseStarted'));
await loadAvailableSamples(true);
} catch (error) {
report(error);
} finally {
working.value = false;
}
}
/** 将错误明细的管理员更正解析为字段对象;正确项由服务端以候选值固化。 */
function reviewedRows(): Array<Record<string, unknown>> | null {
const reviews: Array<Record<string, unknown>> = [];
for (const review of rowReviews.value) {
if (review.correct) {
reviews.push({ correct: true });
continue;
}
try {
const values = JSON.parse(review.correction);
if (!values || typeof values !== 'object' || Array.isArray(values)) throw new Error('invalid');
reviews.push({ correct: false, values });
} catch {
message.error(t('admin.shippingOrderProfiles.blindTest.correctionInvalid'));
return null;
}
}
return reviews;
}
/** 提交全量人工复核,将候选结果或管理员更正转换为服务端受保护的盲测真值。 */
async function confirmReview(): Promise<void> {
if (!suite.value || !candidate.value || !candidate.value.confirmable
|| !candidate.value.layout_version_id || !candidate.value.layout_payload_checksum) return;
const reviews = reviewedRows();
if (!reviews) return;
working.value = true;
try {
suite.value = await confirmOrderProfileBlindTestReviews(suite.value.id, {
document_id: candidate.value.document_id,
table_id: candidate.value.table_id,
layout_version_id: candidate.value.layout_version_id,
layout_payload_checksum: candidate.value.layout_payload_checksum,
row_reviews: reviews,
order_field_reviews: Object.fromEntries(Object.entries(orderFieldReviews.value).map(([fieldKey, review]) => [
fieldKey,
review.correct ? { correct: true } : { correct: false, value: review.value },
])),
});
candidate.value = null;
selectedSampleKey.value = '';
availableSamplesLoaded.value = false;
availableSamples.value = [];
message.success(t('admin.shippingOrderProfiles.blindTest.addedSamples'));
} catch (error) {
if (error instanceof BusinessError && error.code === 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_PREVIEW_STALE') {
candidate.value = null;
selectedSampleKey.value = '';
await loadAvailableSamples(true);
}
report(error);
} finally {
working.value = false;
}
}
/** 删除草稿阶段误加的盲测样本;批准后的套件会由服务端拒绝变更。 */
async function removeSample(sampleId: number): Promise<void> {
if (!suite.value) return;
working.value = true;
try {
suite.value = await removeOrderProfileTestSample(suite.value.id, sampleId);
availableSamplesLoaded.value = false;
availableSamples.value = [];
} catch (error) {
report(error);
} finally {
working.value = false;
}
}
/** 执行当前完整盲测集;失败原因保留在安全摘要并展示给管理员,不能绕过批准。 */
async function executeSuite(): Promise<void> {
if (!suite.value) return;
working.value = true;
try {
suite.value = await executeOrderProfileTestSuite(suite.value.id);
} catch (error) {
report(error);
} finally {
working.value = false;
}
}
/** 批准刚刚通过的当前 checksum 盲测,作为发布门禁所需的质量凭证。 */
async function approveSuite(): Promise<void> {
if (!suite.value || !canApprove.value) return;
working.value = true;
try {
suite.value = await approveOrderProfileTestSuite(suite.value.id);
message.success(t('admin.shippingOrderProfiles.blindTest.approvedHint'));
} catch (error) {
report(error);
} finally {
working.value = false;
}
}
/** 返回验证页保留同一浏览器标签身份,避免在流程切换中误触发租约冲突。 */
function backToValidation(): void {
router.push({ name: 'AdminShippingOrderDocumentProfileValidate', params: route.params, query: { editorSessionId: sessionId } });
}
/** 返回编辑器绑定当前标注样本为训练证据,盲测样本保持与建模样本独立。 */
function goToEditor(): void {
router.push({ name: 'AdminShippingOrderDocumentProfileEdit', params: route.params, query: { editorSessionId: sessionId } });
}
/** 盲测批准后才跳转发布检查;后端仍会再次验证当前草稿 checksum。 */
function goToPublishCheck(): void {
if (suite.value?.status !== 'approved') return;
router.push({ name: 'AdminShippingOrderDocumentProfilePublishCheck', params: route.params, query: { editorSessionId: sessionId } });
}
/** 格式化盲测统一指标百分比。 */
function formatMetricRate(value: number | null | undefined): string {
if (value == null || Number.isNaN(value)) return '—';
return `${Math.round(value * 1000) / 10}%`;
}
onMounted(loadSuite);
onBeforeUnmount(() => {
stopUploadPolling();
availableSamplesController?.abort();
if (availableSamplesTimeout) window.clearTimeout(availableSamplesTimeout);
});
</script>
<template>
<section class="blind-test-page">
<header>
<div>
<h1 class="section-title">{{ t('admin.shippingOrderProfiles.blindTest.title') }}</h1>
<p class="section-desc mt-1">{{ t('admin.shippingOrderProfiles.blindTest.reviewHint') }}</p>
</div>
<div class="actions"><button type="button" class="btn-secondary" @click="backToValidation">{{ t('admin.shippingOrderProfiles.blindTest.backToValidation') }}</button><button v-if="suite?.status === 'approved'" type="button" class="btn-primary" @click="goToPublishCheck">{{ t('admin.shippingOrderProfiles.blindTest.goPublishCheck') }}</button></div>
</header>
<p v-if="loading">{{ t('admin.orderProfileValidation.loading') }}</p>
<template v-else-if="suite">
<section class="card suite-summary"><div><h2>{{ t('admin.shippingOrderProfiles.blindTest.samples', { count: suite.sample_count, required: 1, status: t(`admin.shippingOrderProfiles.versionCenter.testStatus.${suite.status}`) }) }}</h2><p v-if="suite.latest_run">{{ t('admin.shippingOrderProfiles.blindTest.latestResult', { status: suite.latest_run.status, passed: suite.latest_run.passed_sample_count, count: suite.latest_run.sample_count }) }}</p><p v-else>{{ t('admin.shippingOrderProfiles.blindTest.notRun') }}</p></div><span :class="`status ${suite.status}`">{{ t(`admin.shippingOrderProfiles.versionCenter.testStatus.${suite.status}`) }}</span></section>
<section v-if="suite.latest_run?.metrics" class="card metrics-card">
<h2>{{ t('admin.shippingOrderProfiles.blindTest.metricsTitle') }}</h2>
<dl class="metrics">
<div><dt>{{ t('admin.shippingOrderProfiles.blindTest.visualCoverage') }}</dt><dd>{{ formatMetricRate(suite.latest_run.metrics.visual_coverage_rate) }}</dd></div>
<div><dt>{{ t('admin.shippingOrderProfiles.blindTest.evidenceRetention') }}</dt><dd>{{ formatMetricRate(suite.latest_run.metrics.evidence_retention_rate) }}</dd></div>
<div><dt>{{ t('admin.shippingOrderProfiles.blindTest.mirrorConsistency') }}</dt><dd>{{ formatMetricRate(suite.latest_run.metrics.mirror_consistency_rate) }}</dd></div>
<div><dt>{{ t('admin.shippingOrderProfiles.blindTest.keyFieldAccuracy') }}</dt><dd>{{ formatMetricRate(suite.latest_run.metrics.key_field_accuracy_rate) }}</dd></div>
</dl>
</section>
<section v-if="failureDetails.length" class="card failure-details">
<div><h2>{{ t('admin.shippingOrderProfiles.blindTest.failure.title') }}</h2><p>{{ t('admin.shippingOrderProfiles.blindTest.failure.hint') }}</p></div>
<ul><li v-for="failure in failureDetails" :key="failure.code"><span>{{ failure.message }}</span><code>{{ failure.code }}</code></li></ul>
</section>
<section v-if="suite.status === 'draft'" class="card">
<div class="sample-heading"><h2>{{ t('admin.shippingOrderProfiles.blindTest.selectIndependentSample') }}</h2><label class="btn-secondary upload-sample"><input type="file" accept=".pdf,.eml,application/pdf,message/rfc822" :disabled="uploadingSample" @change="uploadIndependentSample"><span>{{ uploadingSample ? t('admin.shippingOrderProfiles.wizard.uploading') : t('admin.shippingOrderProfiles.blindTest.uploadSample') }}</span></label></div>
<p v-if="availableSamplesLoaded && !availableSamples.length">{{ t('admin.shippingOrderProfiles.blindTest.noIndependentSamples') }}</p>
<div class="sample-picker"><button v-if="!availableSamplesLoaded" type="button" class="btn-secondary" :disabled="availableSamplesLoading" @click="() => void loadAvailableSamples()">{{ availableSamplesLoading ? t('admin.shippingOrderProfiles.blindTest.loadingIndependentSamples') : t('admin.shippingOrderProfiles.blindTest.loadIndependentSamples') }}</button><template v-else-if="availableSamples.length"><select v-model="selectedSampleKey" class="select-field"><option value="">{{ t('admin.shippingOrderProfiles.blindTest.selectSamplePlaceholder') }}</option><option v-for="sample in availableSamples" :key="`${sample.document_id}:${sample.table_id}`" :value="`${sample.document_id}:${sample.table_id}`">{{ sampleLabel(sample) }}</option></select><button v-if="selectedSample?.review_mode === 'preparing'" type="button" class="btn-primary" :disabled="working" @click="reprocessSelectedSample">{{ t('admin.shippingOrderProfiles.blindTest.reprocessLayout') }}</button><button v-else type="button" class="btn-primary" :disabled="!selectedSample || working" @click="previewSample">{{ selectedSample?.review_mode === 'diagnostic' ? t('admin.shippingOrderProfiles.blindTest.viewDiagnostic') : t('admin.shippingOrderProfiles.blindTest.previewAndReview') }}</button><button type="button" class="btn-secondary" :disabled="availableSamplesLoading || working" @click="() => void loadAvailableSamples(true)">{{ t('admin.shippingOrderProfiles.blindTest.refreshSamples') }}</button></template></div>
<p v-if="pendingUpload" class="upload-status" :class="{ failed: pendingUpload.state === 'failed' }">{{ pendingUpload.filename }} · {{ pendingUpload.state === 'materializing' ? t('admin.shippingOrderProfiles.blindTest.sampleMaterializing') : sampleFailureMessage() }}</p>
</section>
<section v-if="candidate" class="card candidate-card">
<h2>{{ t('admin.shippingOrderProfiles.blindTest.reviewHint') }}</h2>
<p v-if="!candidate.confirmable" class="training-required">{{ t('admin.shippingOrderProfiles.blindTest.diagnosticOnly') }}</p>
<p
v-if="candidate.reservation_region_status === 'needs_review'"
class="training-required"
>
{{ t('admin.shippingOrderProfiles.blindTest.reservationRegionNeedsReview', {
reasons: (candidate.reservation_region_review_reasons || []).join(', ') || candidate.reservation_region_status,
}) }}
</p>
<p v-if="!candidate.rows.length">{{ t('admin.shippingOrderProfiles.blindTest.candidateRowsEmpty') }}</p>
<article v-for="(row, index) in candidate.rows" :key="index" class="review-item">
<template v-if="rowReviews[index]">
<h3>{{ t('admin.shippingOrderProfiles.blindTest.row', { index: index + 1 }) }}</h3><code>{{ JSON.stringify(row) }}</code>
<label><input v-model="rowReviews[index].correct" type="checkbox">{{ t('admin.shippingOrderProfiles.blindTest.correct') }}</label>
<textarea v-if="!rowReviews[index].correct" v-model="rowReviews[index].correction" class="input-field" :placeholder="t('admin.shippingOrderProfiles.blindTest.expectedRowsPlaceholder')" />
</template>
</article>
<article v-for="field in candidate.order_fields" :key="field.field_id" class="review-item">
<h3>{{ field.field_code }}</h3><code>{{ field.value ?? t('admin.shippingOrderProfiles.emptyCandidateValue') }}</code>
<label><input :checked="orderFieldReview(orderFieldKey(field)).correct" type="checkbox" @change="updateOrderFieldReview(orderFieldKey(field), { correct: ($event.target as HTMLInputElement).checked })">{{ t('admin.shippingOrderProfiles.blindTest.correct') }}</label>
<input v-if="!orderFieldReview(orderFieldKey(field)).correct" class="input-field" :value="orderFieldReview(orderFieldKey(field)).value" :placeholder="t('admin.shippingOrderProfiles.blindTest.correctedValue')" @input="updateOrderFieldReview(orderFieldKey(field), { value: ($event.target as HTMLInputElement).value })">
</article>
<button v-if="candidate.confirmable" type="button" class="btn-primary" :disabled="working || !candidate.rows.length" @click="confirmReview">{{ t('admin.shippingOrderProfiles.blindTest.confirmReview') }}</button>
</section>
<section class="card"><h2>{{ t('admin.shippingOrderProfiles.blindTest.addedSamples') }}</h2><p>{{ t('admin.shippingOrderProfiles.blindTest.addedSamplesHint') }}</p><ul v-if="suite.samples.length"><li v-for="sample in suite.samples" :key="sample.id"><span>{{ sample.filename }} · P{{ sample.page_no }}</span><button v-if="suite.status === 'draft'" type="button" class="btn-secondary btn-sm" :disabled="working" @click="removeSample(sample.id)">{{ t('admin.shippingOrderProfiles.blindTest.removeSample') }}</button></li></ul><p v-else>{{ t('admin.shippingOrderProfiles.blindTest.noIndependentSamples') }}</p></section>
<section class="card execution"><div><h2>{{ t('admin.shippingOrderProfiles.blindTest.execution') }}</h2><p>{{ t('admin.shippingOrderProfiles.blindTest.runHint') }}</p><p v-if="!hasTrainingSample" class="training-required">{{ t('admin.shippingOrderProfiles.blindTest.trainingRequired') }}</p></div><div class="actions"><button v-if="suite.status === 'draft'" type="button" class="btn-secondary" :disabled="working || !suite.sample_count" @click="executeSuite">{{ t('admin.shippingOrderProfiles.blindTest.run') }}</button><button v-if="suite.status === 'draft' && !hasTrainingSample" type="button" class="btn-secondary" :disabled="working" @click="goToEditor">{{ t('admin.shippingOrderProfiles.blindTest.goToEditor') }}</button><button v-if="suite.status === 'draft'" type="button" class="btn-primary" :disabled="working || !canApprove" @click="approveSuite">{{ t('admin.shippingOrderProfiles.blindTest.approve') }}</button></div></section>
</template>
</section>
</template>
<style scoped>
.blind-test-page { padding: 24px; color: var(--text-secondary); }
header, .suite-summary, .execution, .actions, .sample-heading, .sample-picker, li { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
header { align-items: flex-start; margin-bottom: 24px; } h1, h2, h3, p { margin: 0; } h2 { font-size: 16px; } h3 { font-size: 14px; } p:not(.section-desc) { margin-top: 6px; color: var(--text-muted); font-size: 13px; line-height: 1.5; }
.card { display: grid; gap: 14px; margin-top: 14px; border: 1px solid var(--border-default); border-radius: 12px; background: var(--bg-surface); padding: 18px; }
.metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; margin: 0; }
.metrics div { display: grid; gap: 4px; }
.metrics dt { color: var(--text-muted); font-size: 12px; }
.metrics dd { margin: 0; color: var(--text-primary); font-size: 14px; font-weight: 600; }
.status { color: var(--status-warning-fg); font-weight: 700; } .status.approved { color: var(--status-success-fg); } .status.superseded { color: var(--status-error-fg); }
.sample-heading { align-items: center; }.sample-picker { justify-content: flex-start; }.sample-picker .select-field { flex: 1; min-width: 0; } .sample-picker button, .upload-sample { flex: 0 0 auto; white-space: nowrap; } .candidate-card .input-field { padding: 8px; border-radius: 6px; } textarea.input-field { min-height: 72px; font-family: ui-monospace, monospace; }
.upload-sample { position: relative; cursor: pointer; }.upload-sample input { position: absolute; width: 1px; height: 1px; opacity: 0; }.upload-status { margin: 10px 0 0; color: var(--status-info-fg); font-size: .85rem; }.upload-status.failed { color: var(--status-error-fg); }
.candidate-card { grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); } .candidate-card > h2, .candidate-card > p, .candidate-card > button { grid-column: 1 / -1; }
.review-item { display: grid; gap: 8px; border: 1px solid var(--border-default); border-radius: 8px; padding: 12px; } code { overflow-wrap: anywhere; white-space: pre-wrap; color: var(--text-primary); font-size: 12px; } label { display: flex; gap: 6px; align-items: center; }
ul { display: grid; gap: 8px; margin: 0; padding: 0; list-style: none; } li { border-top: 1px solid var(--border-default); padding-top: 8px; }
.failure-details { border-color: var(--status-error-border); background: var(--status-error-bg); }.failure-details h2 { color: var(--status-error-fg); }.failure-details li { display: grid; gap: 4px; color: var(--status-error-fg); }.failure-details code { color: var(--status-error-fg); }
.training-required { color: var(--status-warning-fg) !important; font-weight: 600; }
@media (max-width: 700px) { header, .suite-summary, .execution, .sample-heading, .sample-picker { align-items: stretch; flex-direction: column; } .sample-picker .select-field { min-width: 0; width: 100%; } }
</style>
@@ -0,0 +1,213 @@
<!--
features/admin/modules/shipping-order-document-profiles/OrderProfileCreateWizardPage.vue
用途:以三步向导创建订单文档模板草稿。
依赖:Schema/样本/表格 API、步骤组件和 Vue Router。
逻辑:所有有明细的样本在第三步选择同一视觉主表;XFA datasets/OCR 差异只在编辑器的字段取值映射中配置。
-->
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
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';
import type { ShippingOrderSchemaVersion } from '@/features/admin/types/shipping-order-schema.types';
import OrderProfileIdentityStep from './components/OrderProfileIdentityStep.vue';
import OrderProfileSampleStep from './components/OrderProfileSampleStep.vue';
import OrderProfileModelStartStep from './components/OrderProfileModelStartStep.vue';
type Identity = { displayName: string; schemaId: number };
const { t } = useI18n();
const router = useRouter();
const message = useMessage();
const step = ref(1);
const saving = ref(false);
const schemas = ref<ShippingOrderSchemaVersion[]>([]);
const schemasResolved = ref(false);
const samples = ref<OrderProfileSampleDocument[]>([]);
const tables = ref<Array<{ table_id: string; page_no: number; row_count: number; column_count: number; rows: string[][] }>>([]);
const identity = reactive<Identity>({ displayName: '', schemaId: 0 });
const documentId = ref(0);
const tableId = ref('');
const browserSessionId = createRandomUuid();
let sampleRefreshTimer: ReturnType<typeof setTimeout> | null = null;
const publishedSchemas = computed(() => schemas.value.filter((item) => item.status === 'published'));
const stepThreeLabel = computed(() => t('admin.shippingOrderProfiles.wizard.tableStep'));
const canNext = computed(() => {
if (step.value === 1) return Boolean(identity.displayName.trim() && identity.schemaId);
if (step.value === 2) return Boolean(documentId.value);
return Boolean(tableId.value);
});
const steps = computed(() => [
{ number: 1, label: t('admin.shippingOrderProfiles.wizard.identityStep'), icon: FileText },
{ number: 2, label: t('admin.shippingOrderProfiles.wizard.sampleStep'), icon: Layers3 },
{ number: 3, label: stepThreeLabel.value, icon: Sparkles },
]);
/** 接收首步身份快照;父级单一状态驱动下一步校验,避免子组件对象替换造成状态不同步。 */
function updateIdentity(next: Identity): void {
identity.displayName = next.displayName;
identity.schemaId = next.schemaId;
}
/** 加载可用 Schema 与已解析样本;失败不创建或缓存任何 Profile。 */
async function loadContext(): Promise<void> {
try {
const [state, nextSamples] = await Promise.all([getShippingOrderSchemaState(), listOrderProfileSamples()]);
schemas.value = state.versions || [];
samples.value = nextSamples;
schemasResolved.value = true;
} catch (error) {
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.loadFailed'));
}
}
/** 刷新上传后的样本库;轮询失败静默处理,避免短暂网络异常持续弹出提示。 */
async function refreshSamples(showError = true): Promise<void> {
try { samples.value = await listOrderProfileSamples(); }
catch { if (showError) message.error(t('admin.shippingOrderProfiles.wizard.loadFailed')); }
}
/** 仅在第二步保持已解析文档列表为最新,离开步骤后立即停止。 */
function stopSampleRefresh(): void {
if (sampleRefreshTimer !== null) clearTimeout(sampleRefreshTimer);
sampleRefreshTimer = null;
}
function scheduleSampleRefresh(): void {
stopSampleRefresh();
if (step.value !== 2) return;
void refreshSamples(false).finally(() => {
if (step.value === 2) sampleRefreshTimer = setTimeout(scheduleSampleRefresh, 2000);
});
}
/** 加载选定样本的统一视觉表格;XFA 与普通 PDF 走同一 main_table_id 选择。 */
async function loadTables(id: number): Promise<void> {
try { tables.value = (await getOrderProfileSampleTables(id)).tables; }
catch (error) { message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.tableLoadFailed')); }
}
watch(documentId, async (id) => {
tableId.value = '';
tables.value = [];
if (!id) return;
await loadTables(id);
});
watch(step, (currentStep) => {
if (currentStep === 2) scheduleSampleRefresh();
else stopSampleRefresh();
});
/** 前进仅校验当前步骤;所有模板共享视觉主表选择,单表样本可直接创建。 */
async function next(): Promise<void> {
if (!canNext.value) {
message.error(step.value === 1 && !publishedSchemas.value.length
? t('admin.shippingOrderProfiles.wizard.schemaRequired')
: t('admin.shippingOrderProfiles.wizard.incomplete'));
return;
}
if (step.value === 2) {
if (!tables.value.length) await loadTables(documentId.value);
const onlyTable = tables.value.length === 1 ? tables.value[0] : undefined;
if (onlyTable) {
tableId.value = onlyTable.table_id;
await finish(true);
return;
}
if (!tables.value.length) {
message.error(t('admin.shippingOrderProfiles.wizard.noTable'));
return;
}
}
if (step.value < 3) step.value += 1;
}
/** 单事务完成后进入统一草稿编辑路由;字段取值 source 在编辑器内配置。 */
async function finish(enterEditor: boolean): Promise<void> {
if (!canNext.value) return;
saving.value = true;
try {
const payload = {
display_name: identity.displayName,
schema_version_id: identity.schemaId,
document_id: documentId.value,
main_table_id: tableId.value,
browser_session_id: browserSessionId,
operation_id: createRandomUuid(),
};
const profile = await completeOrderDocumentProfileWizard(payload);
message.success(t('admin.shippingOrderProfiles.created'));
await router.push(enterEditor
? { name: 'AdminShippingOrderDocumentProfileEdit', params: { profileCode: profile.profile_code, profileId: profile.id }, query: { editorSessionId: browserSessionId } }
: { name: 'AdminShippingOrderDocumentProfiles' });
} catch (error) {
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.createFailed'));
} finally { saving.value = false; }
}
onMounted(loadContext);
onBeforeUnmount(stopSampleRefresh);
</script>
<template>
<section class="wizard-page">
<div class="wizard-shell">
<header class="wizard-heading">
<h1 class="section-title">{{ t('admin.shippingOrderProfiles.wizard.title') }}</h1>
<p class="section-desc mt-1">{{ t('admin.shippingOrderProfiles.wizard.description') }}</p>
</header>
<ol class="stepper" :aria-label="t('admin.shippingOrderProfiles.wizard.steps', { step })">
<li v-for="item in steps" :key="item.number" :class="{ active: item.number === step, complete: item.number < step }">
<span class="stepper-icon"><Check v-if="item.number < step" :size="16" /><component :is="item.icon" v-else :size="16" /></span>
<span><small>{{ t('admin.shippingOrderProfiles.wizard.stepLabel', { step: item.number }) }}</small>{{ item.label }}</span>
</li>
</ol>
<main class="wizard-card">
<div class="wizard-card__heading">
<span>{{ t('admin.shippingOrderProfiles.wizard.stepLabel', { step }) }}</span>
<h2>{{ steps[step - 1]?.label || '' }}</h2>
</div>
<OrderProfileIdentityStep
v-if="step === 1"
:model-value="identity"
:schemas="schemas"
:schemas-resolved="schemasResolved"
@update:model-value="updateIdentity"
/>
<OrderProfileSampleStep v-else-if="step === 2" v-model="documentId" :samples="samples" @uploaded="refreshSamples(false)" @refresh="refreshSamples()" />
<OrderProfileModelStartStep v-else v-model="tableId" :tables="tables" />
</main>
<footer class="wizard-actions">
<button type="button" class="btn-secondary" @click="router.push({ name: 'AdminShippingOrderDocumentProfiles' })">{{ t('admin.cancel') }}</button>
<span class="wizard-actions__spacer" />
<button v-if="step > 1" type="button" class="btn-ghost" @click="step -= 1"><ArrowLeft :size="17" />{{ t('admin.shippingOrderProfiles.wizard.previous') }}</button>
<button v-if="step < 3" type="button" class="btn-primary" :disabled="!canNext" @click="next">{{ t('admin.shippingOrderProfiles.wizard.next') }}<ArrowRight :size="17" /></button>
<template v-else>
<button type="button" class="btn-secondary" :disabled="saving || !canNext" @click="finish(false)">{{ t('admin.shippingOrderProfiles.wizard.createDraft') }}</button>
<button type="button" class="btn-primary" :disabled="saving || !canNext" @click="finish(true)">{{ t('admin.shippingOrderProfiles.wizard.createAndEdit') }}<ArrowRight :size="17" /></button>
</template>
</footer>
</div>
</section>
</template>
<style scoped>
.wizard-page { min-height: 100%; padding: 24px; background: #f6f8fc; }
.wizard-shell { width: 100%; }
.wizard-heading { margin-bottom: 28px; }.wizard-heading h1, .wizard-heading p { margin: 0; }
.stepper { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0; margin: 0 0 18px; padding: 0; list-style: none; }.stepper li { display: flex; align-items: center; gap: 10px; color: #94a3b8; font-size: .86rem; font-weight: 650; }.stepper li:not(:last-child)::after { width: 100%; height: 1px; margin-left: 10px; background: #dbe4f0; content: ''; }.stepper li.active { color: #1677d2; }.stepper li.complete { color: #0f8a65; }.stepper-icon { display: inline-grid; flex: 0 0 auto; width: 32px; height: 32px; place-items: center; border: 1px solid currentColor; border-radius: 50%; background: #fff; }.stepper .complete .stepper-icon { color: #fff; border-color: #0f8a65; background: #0f8a65; }.stepper small { display: block; margin-bottom: 1px; color: #94a3b8; font-size: .68rem; font-weight: 700; text-transform: uppercase; }
.wizard-card { min-height: 360px; padding: clamp(24px, 4vw, 44px); border: 1px solid #e1e8f2; border-radius: 12px; background: #fff; box-shadow: 0 8px 24px rgb(15 23 42 / .06); }.wizard-card__heading { margin-bottom: 28px; padding-bottom: 18px; border-bottom: 1px solid #edf1f7; }.wizard-card__heading span { color: #1677d2; font-size: .76rem; font-weight: 750; letter-spacing: .06em; text-transform: uppercase; }.wizard-card__heading h2 { margin: 6px 0 0; color: #1e293b; font-size: 1.25rem; }
.wizard-actions { display: flex; align-items: center; gap: 10px; margin-top: 18px; }.wizard-actions__spacer { flex: 1; }
@media (max-width: 640px) { .wizard-page { padding: 24px 16px; }.stepper { grid-template-columns: 1fr; gap: 10px; }.stepper li:not(:last-child)::after { display: none; }.wizard-card { min-height: 300px; border-radius: 14px; }.wizard-actions { flex-wrap: wrap; }.wizard-actions__spacer { display: none; }.btn-secondary:first-child { margin-right: auto; } }
</style>
@@ -0,0 +1,13 @@
<!--
features/admin/modules/shipping-order-document-profiles/OrderProfileEditorRoutePage.vue
用途:订单文档模板草稿编辑入口;普通 PDF 与 XFA 统一进入 OrderProfileEditorPage。
依赖:OrderProfileEditorPage。
逻辑:不再按 template_mode 分流至 XfaProfileMappingPage;模式差异由统一编辑器内部处理。
-->
<script setup lang="ts">
import OrderProfileEditorPage from './OrderProfileEditorPage.vue';
</script>
<template>
<OrderProfileEditorPage />
</template>
@@ -0,0 +1,340 @@
<!--
features/admin/modules/shipping-order-document-profiles/OrderProfileLibraryPage.vue
用途:按 profile_code 聚合展示订单文档模板族,是创建和继续编辑的唯一首页。
依赖:Profile family API、统一 binding 迁移 scan/dry-run API、Vue Router、Vue I18n。
逻辑:列表只选择下一步路由;展示统一 binding 迁移状态与待补框筛选;支持批量 Dry Run。
-->
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import {
cloneOrderDocumentProfile,
deleteOrderDocumentProfile,
dryRunOrderProfileUnifiedMigration,
listOrderDocumentProfileFamilies,
} from '@/features/admin/api/shipping-order-document-profile.api';
import type { OrderProfileVersionFamilySummary } from '@/features/admin/types/shipping-order-document-profile.types';
const { t } = useI18n();
const router = useRouter();
const message = useMessage();
const loading = ref(false);
const batchDryRunLoading = ref(false);
const query = ref('');
const migrationFilter = ref<'all' | 'needs_migration' | 'pending_visual'>('all');
const families = ref<OrderProfileVersionFamilySummary[]>([]);
const deletingDraft = ref<OrderProfileVersionFamilySummary | null>(null);
const deleteConfirmOpen = computed({
get: () => deletingDraft.value !== null,
set: (visible: boolean) => {
if (!visible) deletingDraft.value = null;
},
});
const filteredFamilies = computed(() => {
const keyword = query.value.trim().toLowerCase();
return families.value.filter((item) => {
const matchesKeyword = !keyword || `${item.profile_code} ${item.display_name}`.toLowerCase().includes(keyword);
if (!matchesKeyword) return false;
if (migrationFilter.value === 'needs_migration') {
return item.unified_binding_status === 'needs_migration' || item.unified_needs_migration === true;
}
if (migrationFilter.value === 'pending_visual') {
return (item.unified_pending_visual_count ?? 0) > 0 || item.unified_binding_status === 'pending_visual';
}
return true;
});
});
const migrationTotals = computed(() => {
const needsMigration = families.value.filter(
(item) => item.unified_binding_status === 'needs_migration' || item.unified_needs_migration,
).length;
const pendingVisual = families.value.filter(
(item) => (item.unified_pending_visual_count ?? 0) > 0 || item.unified_binding_status === 'pending_visual',
).length;
return { needsMigration, pendingVisual, total: families.value.length };
});
/** 仅以服务端返回的不可变 Schema 身份决定复制或迁移,列表页不猜测兼容性。 */
function schemaMigrationRequired(item: OrderProfileVersionFamilySummary): boolean {
return item.published_schema_version_id != null
&& item.current_schema_version_id != null
&& item.published_schema_version_id !== item.current_schema_version_id;
}
/** 加载模板族摘要;列表只显示聚合结果,不能将每个版本扁平为独立模板。 */
async function loadFamilies(): Promise<void> {
loading.value = true;
try {
families.value = await listOrderDocumentProfileFamilies();
} catch (error) {
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.library.loadFailed'));
} finally {
loading.value = false;
}
}
/** 打开当前草稿编辑路由;草稿不存在时由其它操作创建,不在列表页隐式创建。 */
function continueEditing(item: OrderProfileVersionFamilySummary): void {
if (!item.draft_profile_id) return;
router.push({ name: 'AdminShippingOrderDocumentProfileEdit', params: { profileCode: item.profile_code, profileId: item.draft_profile_id } });
}
/** 从已发布版本建立同族下一草稿,然后进入后续编辑路由。 */
async function createNewVersion(item: OrderProfileVersionFamilySummary): Promise<void> {
if (!item.published_profile_id) return;
try {
const draft = await cloneOrderDocumentProfile(item.published_profile_id);
router.push({ name: 'AdminShippingOrderDocumentProfileEdit', params: { profileCode: draft.profile_code, profileId: draft.id } });
} catch (error) {
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.library.createFailed'));
}
}
/** 打开系统内确认框,避免浏览器原生弹窗中断管理员的模板管理流程。 */
function requestDeleteDraft(item: OrderProfileVersionFamilySummary): void {
if (item.draft_profile_id) deletingDraft.value = item;
}
/** 删除已确认的草稿;服务端仍拒绝删除已发布或退役的历史版本。 */
async function confirmDeleteDraft(): Promise<void> {
const item = deletingDraft.value;
if (!item?.draft_profile_id) return;
try {
await deleteOrderDocumentProfile(item.draft_profile_id);
message.success(t('admin.shippingOrderProfiles.deleted'));
await loadFamilies();
} catch (error) {
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.library.loadFailed'));
} finally {
deletingDraft.value = null;
}
}
/** 进入不可变历史详情,不允许在此页面把版本伪装成新草稿。 */
function viewVersion(item: OrderProfileVersionFamilySummary): void {
router.push({ name: 'AdminShippingOrderDocumentProfileVersionDetail', params: { profileCode: item.profile_code, version: item.default_version } });
}
/** 打开已发布版本的 Schema 迁移决策;字段兼容性只能由详情接口安全计算。 */
function openSchemaMigration(item: OrderProfileVersionFamilySummary): void {
if (!item.published_version) return;
router.push({
name: 'AdminShippingOrderDocumentProfileVersionDetail',
params: { profileCode: item.profile_code, version: item.published_version },
query: { migrate: '1' },
});
}
/** 打开版本详情中的统一 binding 迁移 Dry Run 入口。 */
function openUnifiedMigration(item: OrderProfileVersionFamilySummary): void {
const version = item.draft_version ?? item.published_version ?? item.default_version;
router.push({
name: 'AdminShippingOrderDocumentProfileVersionDetail',
params: { profileCode: item.profile_code, version },
query: { unifiedMigration: '1' },
});
}
/** 对需迁移模板族批量 Dry Run(只写审计报告,不改 definition)。 */
async function runBatchUnifiedMigrationDryRun(): Promise<void> {
const targets = families.value.filter(
(item) => item.unified_binding_status === 'needs_migration' || item.unified_needs_migration,
);
if (!targets.length) {
message.info(t('admin.shippingOrderProfiles.unifiedMigration.batchDryRunEmpty'));
return;
}
batchDryRunLoading.value = true;
let failed = 0;
try {
for (const item of targets) {
const profileId = item.draft_profile_id ?? item.published_profile_id ?? item.default_profile_id;
try {
await dryRunOrderProfileUnifiedMigration(profileId);
} catch {
failed += 1;
}
}
await loadFamilies();
if (failed) {
message.warning(t('admin.shippingOrderProfiles.unifiedMigration.batchDryRunPartial', { failed, total: targets.length }));
} else {
message.success(t('admin.shippingOrderProfiles.unifiedMigration.batchDryRunDone', { count: targets.length }));
}
} finally {
batchDryRunLoading.value = false;
}
}
onMounted(loadFamilies);
</script>
<template>
<section class="mx-auto max-w-7xl space-y-6 p-6">
<header class="page-header">
<div>
<h1 class="section-title">{{ t('admin.shippingOrderProfiles.library.title') }}</h1>
<p class="section-desc mt-1">{{ t('admin.shippingOrderProfiles.library.subtitle') }}</p>
</div>
<button class="btn-primary" type="button" @click="router.push({ name: 'AdminShippingOrderDocumentProfileCreate' })">
{{ t('admin.shippingOrderProfiles.library.create') }}
</button>
</header>
<div class="toolbar">
<input v-model="query" class="toolbar-input" :placeholder="t('admin.shippingOrderProfiles.library.search')" type="search">
<select v-model="migrationFilter" class="toolbar-select" data-testid="order-profile-unified-migration-filter">
<option value="all">{{ t('admin.shippingOrderProfiles.unifiedMigration.filterAll') }}</option>
<option value="needs_migration">{{ t('admin.shippingOrderProfiles.unifiedMigration.filterNeedsMigration') }}</option>
<option value="pending_visual">{{ t('admin.shippingOrderProfiles.unifiedMigration.filterPendingVisual') }}</option>
</select>
<button
class="btn-secondary btn-sm"
type="button"
data-testid="order-profile-unified-migration-batch-dry-run"
:disabled="batchDryRunLoading || migrationTotals.needsMigration === 0"
@click="runBatchUnifiedMigrationDryRun"
>
{{
batchDryRunLoading
? t('admin.shippingOrderProfiles.unifiedMigration.batchDryRunRunning')
: t('admin.shippingOrderProfiles.unifiedMigration.batchDryRun', { count: migrationTotals.needsMigration })
}}
</button>
</div>
<p v-if="families.length" class="migration-summary" data-testid="order-profile-unified-migration-summary">
{{
t('admin.shippingOrderProfiles.unifiedMigration.librarySummary', {
total: migrationTotals.total,
needs: migrationTotals.needsMigration,
pending: migrationTotals.pendingVisual,
})
}}
</p>
<section class="library-card" :aria-busy="loading">
<p v-if="loading" class="library-state">{{ t('admin.shippingOrderProfiles.library.loading') }}</p>
<p v-else-if="!filteredFamilies.length" class="library-state">{{ t('admin.shippingOrderProfiles.library.empty') }}</p>
<div v-else class="table-scroll">
<table class="profile-table">
<thead>
<tr>
<th>{{ t('admin.shippingOrderProfiles.name') }}</th>
<th>{{ t('admin.shippingOrderProfiles.code') }}</th>
<th>{{ t('admin.shippingOrderProfiles.library.status') }}</th>
<th>{{ t('admin.shippingOrderProfiles.unifiedMigration.columnTitle') }}</th>
<th class="actions-heading">{{ t('admin.shippingOrderProfiles.library.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="item in filteredFamilies" :key="item.profile_code">
<td class="profile-name">{{ item.display_name }}</td>
<td><code>{{ item.profile_code }}</code></td>
<td>
<span class="status-badge" :class="{ draft: item.draft_profile_id, published: !item.draft_profile_id && item.published_profile_id }">
{{ item.draft_profile_id ? t('admin.shippingOrderProfiles.library.draft') : item.published_profile_id ? t('admin.shippingOrderProfiles.library.published', { version: item.published_version }) : t('admin.shippingOrderProfiles.library.retired') }}
</span>
<small v-if="item.published_profile_id && item.current_schema_version" class="schema-status" :class="{ warning: schemaMigrationRequired(item) }">
{{ schemaMigrationRequired(item)
? t('admin.shippingOrderProfiles.schemaMigration.versionMismatch', { bound: item.published_schema_version, current: item.current_schema_version })
: t('admin.shippingOrderProfiles.schemaMigration.versionMatched', { version: item.current_schema_version }) }}
</small>
</td>
<td>
<span
v-if="item.unified_binding_status"
class="unified-migration-badge"
:class="item.unified_binding_status"
data-testid="order-profile-unified-migration-status"
>
{{ t(`admin.shippingOrderProfiles.unifiedMigration.status.${item.unified_binding_status}`) }}
</span>
<small v-if="(item.unified_pending_visual_count ?? 0) > 0" class="schema-status warning">
{{ t('admin.shippingOrderProfiles.unifiedMigration.pendingVisualShort', { count: item.unified_pending_visual_count }) }}
</small>
</td>
<td class="profile-library__actions">
<!-- flex 必须放在 td 内层,避免破坏 table-cell 盒模型导致行分隔线错位 -->
<div class="profile-library__actions-inner">
<button v-if="item.draft_profile_id" class="btn-ghost btn-sm" type="button" @click="continueEditing(item)">{{ t('admin.shippingOrderProfiles.versionCenter.continueEditing') }}</button>
<button v-if="item.draft_profile_id" class="btn-danger btn-sm" type="button" @click="requestDeleteDraft(item)">{{ t('admin.delete') }}</button>
<button v-else-if="item.published_profile_id && !schemaMigrationRequired(item)" class="btn-secondary btn-sm" type="button" @click="createNewVersion(item)">{{ t('admin.shippingOrderProfiles.newVersion') }}</button>
<button v-if="!item.draft_profile_id && item.published_profile_id && schemaMigrationRequired(item)" class="btn-secondary btn-sm" type="button" @click="openSchemaMigration(item)">{{ t('admin.shippingOrderProfiles.schemaMigration.listAction') }}</button>
<button class="btn-ghost btn-sm" type="button" @click="viewVersion(item)">{{ t('admin.shippingOrderProfiles.versionCenter.viewVersion') }}</button>
<button
v-if="item.unified_binding_status === 'needs_migration' || item.unified_needs_migration"
class="btn-ghost btn-sm"
type="button"
data-testid="order-profile-unified-migration-open"
@click="openUnifiedMigration(item)"
>
{{ t('admin.shippingOrderProfiles.unifiedMigration.open') }}
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</section>
<DeleteConfirmDialog
v-model="deleteConfirmOpen"
:message="t('admin.shippingOrderProfiles.deleteConfirm')"
@confirm="confirmDeleteDraft"
/>
</section>
</template>
<style scoped>
.page-header { display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: space-between; gap: 16px; }
.page-header h1 { margin: 0; }
.page-header p { margin: 0; }
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.toolbar-select {
min-width: 180px; border: 1px solid #d9e2ec; border-radius: 6px; background: #fff;
padding: 7px 9px; color: #334155; font: inherit; font-size: 12px;
}
.migration-summary { margin: 0; color: #64748b; font-size: 12px; }
.unified-migration-badge {
display: inline-flex; border: 1px solid #cbd5e1; border-radius: 999px; background: #f8fafc;
padding: 3px 8px; color: #64748b; font-size: 11px; font-weight: 600; white-space: nowrap;
}
.unified-migration-badge.needs_migration { border-color: #fde68a; background: #fffbeb; color: #b45309; }
.unified-migration-badge.pending_visual { border-color: #fecaca; background: #fef2f2; color: #b91c1c; }
.unified-migration-badge.ready { border-color: #bbf7d0; background: #f0fdf4; color: #15803d; }
.toolbar-input {
min-width: 220px; flex: 1 1 220px; border: 1px solid #d9e2ec; border-radius: 6px; background: #fff;
padding: 7px 9px; color: #334155; font: inherit; font-size: 12px; outline: none;
}
.toolbar-input:focus { border-color: #38bdf8; box-shadow: 0 0 0 2px rgb(56 189 248 / 12%); }
.library-card { overflow: hidden; border: 1px solid #dfe7ef; border-radius: 10px; background: #fff; box-shadow: 0 1px 2px rgb(15 23 42 / 3%); }
.library-state { margin: 0; padding: 48px 24px; color: #94a3b8; font-size: 13px; text-align: center; }
.table-scroll { overflow-x: auto; }
.profile-table { width: 100%; min-width: 720px; border-collapse: collapse; color: #475569; font-size: 13px; }
.profile-table th { background: #f8fafc; color: #64748b; font-size: 12px; font-weight: 600; }
.profile-table th, .profile-table td { padding: 13px 16px; border-bottom: 1px solid #e5ebf1; text-align: left; vertical-align: middle; }
.profile-table tbody tr:last-child td { border-bottom: 0; }
.profile-table tbody tr:hover { background: #fbfdff; }
.profile-name { color: #334155; font-weight: 600; }
.profile-table code { color: #64748b; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 11px; white-space: nowrap; }
.status-badge { display: inline-flex; border: 1px solid #cbd5e1; border-radius: 999px; background: #f8fafc; padding: 3px 8px; color: #64748b; font-size: 11px; font-weight: 600; white-space: nowrap; }
.status-badge.draft { border-color: #bae6fd; background: #f0f9ff; color: #0369a1; }
.status-badge.published { border-color: #bbf7d0; background: #f0fdf4; color: #15803d; }
.schema-status { display: block; margin-top: 5px; color: #64748b; font-size: 11px; white-space: nowrap; }.schema-status.warning { color: #b45309; }
.actions-heading { min-width: 190px; }
.profile-library__actions { vertical-align: middle; }
.profile-library__actions-inner { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; }
@media (max-width: 700px) {
.page-header { flex-direction: column; }
.btn-primary { width: 100%; }
.toolbar-input { min-width: 0; }
}
</style>
@@ -0,0 +1,348 @@
<!--
features/admin/modules/shipping-order-document-profiles/OrderProfilePublishCheckPage.vue
用途:展示版面签名、跨模板唯一性与发布阻断项,并在门禁通过后发布模板。
依赖:发布检查 API、验证运行 API、Vue Router 和统一消息提示。
逻辑:自动选择当前样本试读通过运行;服务端生成签名/重叠验证;阻断项不可绕过,语义差异须逐项确认。
-->
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
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,
createOrderProfilePublishCheck,
listOrderProfileValidationRuns,
} from '@/features/admin/api/shipping-order-document-profile.api';
import type {
OrderProfileOverlapConflictProfile,
OrderProfilePublishCheckReport,
OrderProfileValidationRun,
} from '@/features/admin/types/shipping-order-document-profile.types';
const route = useRoute();
const router = useRouter();
const message = useMessage();
const { t } = useI18n();
const profileId = Number(route.params.profileId);
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() || createRandomUuid();
const leaseToken = ref('');
const validationRun = computed(() => runs.value.find((item) => item.run_type === 'current_sample' && item.status === 'passed') || null);
/** 所有模板共用同一份视觉 layout signature;datasets 身份在其 evidence 中展示。 */
const signatureRun = computed(() => runs.value.find((item) => (
item.run_type === 'layout_signature' && item.status === 'passed'
)) || null);
const signatureStatusDetail = computed(() => report.value?.profile_identity_signature_status || null);
const signatureIdentityDetails = computed(() => signatureStatusDetail.value?.identity_details || null);
const overlapRun = computed(() => runs.value.find((item) => item.run_type === 'cross_template_overlap' && item.status === 'passed') || null);
const publishable = computed(() => report.value?.status === 'valid' && !report.value.blocking_items.length && confirmed.value.length === (report.value.warning_items?.length || 0));
const conflictProfiles = computed<OrderProfileOverlapConflictProfile[]>(() => report.value?.conflict_profiles || report.value?.overlap_summary?.conflict_profiles || []);
const gateStatus = computed<'pass' | 'blocked' | 'pending'>(() => {
if (!report.value) return 'pending';
return report.value.blocking_items.length ? 'blocked' : 'pass';
});
/**
* 统一将 value adapter 的验证指标投影为键值项。
* 核心逻辑:页面只渲染公共指标卡;coordinate adapter 可返回空数组,XFA datasets
* 则提供视觉/镜像/evidence 门禁证据,避免模板类型决定 DOM 结构。
*/
const adapterValidationMetrics = computed<Array<{ label: string; value: number | null }>>(() => {
const summary = validationRun.value?.summary;
if (!summary || typeof summary !== 'object') return [];
const asRate = (value: unknown): number | null => (
typeof value === 'number' && Number.isFinite(value) ? value : null
);
return [
{ label: t('admin.orderProfilePublishCheck.xfaVisualCoverage'), value: asRate(summary.visual_coverage_rate) },
{ label: t('admin.orderProfilePublishCheck.xfaMirrorConsistency'), value: asRate(summary.mirror_consistency_rate) },
{ label: t('admin.orderProfilePublishCheck.xfaEvidenceRetention'), value: asRate(summary.evidence_retention_rate) },
].filter((item) => item.value != null);
});
/** 将 identity adapter 返回的可选证据投影为通用签名指标。 */
const signatureIdentityMetrics = computed<Array<{ label: string; value: string }>>(() => {
const details = signatureIdentityDetails.value;
if (!details) return [];
const metrics: Array<{ label: string; value: string }> = [];
if (typeof details.header_token_coverage === 'number') {
metrics.push({ label: t('admin.orderProfilePublishCheck.signatureHeaderCoverage'), value: formatRate(details.header_token_coverage) });
}
if (details.dataset_structure_fingerprint) {
metrics.push({ label: t('admin.orderProfilePublishCheck.xfaStructureFingerprint'), value: details.dataset_structure_fingerprint });
}
return metrics;
});
/** 显示统一业务错误,避免发布页暴露服务端实现细节。 */
function fail(error: unknown): void {
message.error(error instanceof BusinessError ? error.message : t('admin.orderProfilePublishCheck.failed'));
}
/** 获取租约后才允许创建或消费报告,避免发布页绕过草稿写保护。 */
async function ensureLease(): Promise<boolean> {
if (leaseToken.value) return true;
try {
leaseToken.value = (await acquireOrderDocumentProfileEditLease(profileId, {
browser_session_id: sessionId,
operation_id: createRandomUuid(),
})).lease_token;
return true;
} catch (error) {
fail(error);
return false;
}
}
/** 读取当前草稿仍有效的验证运行;历史 stale 运行不可用于发布。 */
async function loadRuns(): Promise<void> {
try {
runs.value = await listOrderProfileValidationRuns(profileId);
} catch (error) {
fail(error);
}
}
/** 创建发布检查报告;后端继续复核签名、跨模板唯一性、盲测与 Profile 发布前置条件。 */
async function createReport(): Promise<void> {
if (!validationRun.value || !(await ensureLease())) return;
busy.value = true;
try {
report.value = await createOrderProfilePublishCheck(profileId, {
validation_run_id: validationRun.value.id,
matching_signature_run_id: signatureRun.value?.id,
overlap_validation_run_id: overlapRun.value?.id,
browser_session_id: sessionId,
lease_token: leaseToken.value,
operation_id: createRandomUuid(),
});
confirmed.value = [];
await loadRuns();
} catch (error) {
fail(error);
} finally {
busy.value = false;
}
}
/** 逐项确认警告后消费报告并发布;发布成功后进入只读版本详情。 */
async function publish(): Promise<void> {
if (!report.value || !publishable.value || !(await ensureLease())) return;
busy.value = true;
try {
const published = await confirmOrderProfilePublishCheck(profileId, report.value.report_no, {
confirmed_warning_keys: confirmed.value,
browser_session_id: sessionId,
lease_token: leaseToken.value,
operation_id: createRandomUuid(),
});
await router.replace({
name: 'AdminShippingOrderDocumentProfileVersionDetail',
params: { profileCode: published.profile_code, version: String(published.version) },
});
} catch (error) {
fail(error);
} finally {
busy.value = false;
}
}
/** 归一化有限的已知门禁码;未知内容仍保留后端安全摘要。 */
function itemMessage(item: Record<string, unknown>): string {
const key = String(item.key || '');
const map: Record<string, string> = {
current_validation_required: t('admin.orderProfilePublishCheck.currentValidationRequired'),
semantic_diff_review: t('admin.orderProfilePublishCheck.semanticDiffReview'),
signature_required: t('admin.orderProfilePublishCheck.signatureRequired'),
signature_stale: t('admin.orderProfilePublishCheck.signatureStale'),
overlap_validation_required: t('admin.orderProfilePublishCheck.overlapRequired'),
overlap_validation_stale: t('admin.orderProfilePublishCheck.overlapStale'),
overlap_validation_failed: t('admin.orderProfilePublishCheck.overlapFailed'),
self_match_not_unique: t('admin.orderProfilePublishCheck.selfMatchNotUnique'),
self_match_not_unique_blind: t('admin.orderProfilePublishCheck.selfMatchNotUniqueBlind'),
cross_template_false_hit: t('admin.orderProfilePublishCheck.crossTemplateFalseHit'),
cross_template_ambiguous: t('admin.orderProfilePublishCheck.crossTemplateAmbiguous'),
cross_template_parse_failed: t('admin.orderProfilePublishCheck.crossTemplateParseFailed'),
cross_template_coverage_insufficient: t('admin.orderProfilePublishCheck.crossTemplateCoverageInsufficient'),
cross_template_margin_insufficient: t('admin.orderProfilePublishCheck.crossTemplateMarginInsufficient'),
sample_role_pollution: t('admin.orderProfilePublishCheck.sampleRolePollution'),
cross_template_conflict_profiles: t('admin.orderProfilePublishCheck.crossTemplateConflictProfiles'),
xfa_mapping_required: t('admin.orderProfilePublishCheck.xfaFieldMappingsRequired'),
xfa_visual_coverage_insufficient: t('admin.orderProfilePublishCheck.xfaVisualCoverageInsufficient'),
xfa_evidence_retention_insufficient: t('admin.orderProfilePublishCheck.xfaEvidenceRetentionInsufficient'),
xfa_mirror_consistency_insufficient: t('admin.orderProfilePublishCheck.xfaMirrorConsistencyInsufficient'),
};
return map[key] || String(item.message || t('admin.orderProfilePublishCheck.unknownIssue'));
}
/** 格式化百分比指标,供唯一性卡片展示。 */
function formatRate(value: number | null | undefined): string {
if (value == null) return '—';
return `${Math.round(value * 1000) / 10}%`;
}
function backToValidation(): void {
router.push({ name: 'AdminShippingOrderDocumentProfileValidate', params: route.params, query: { editorSessionId: sessionId } });
}
/** 冲突修复必须回到唯一可修改的模板编辑器,避免用户在验证页无路可走。 */
function backToEditor(): void {
router.push({ name: 'AdminShippingOrderDocumentProfileEdit', params: route.params, query: { editorSessionId: sessionId } });
}
function signatureStatus(value: string | undefined): string {
const map: Record<string, string> = {
valid: t('admin.orderProfilePublishCheck.statusValid'),
missing: t('admin.orderProfilePublishCheck.statusMissing'),
stale: t('admin.orderProfilePublishCheck.statusStale'),
};
return map[value || ''] || '—';
}
function conflictReason(value: string): string {
const map: Record<string, string> = {
false_hit: t('admin.orderProfilePublishCheck.crossTemplateFalseHit'),
reverse_false_hit: t('admin.orderProfilePublishCheck.crossTemplateFalseHit'),
ambiguous: t('admin.orderProfilePublishCheck.crossTemplateAmbiguous'),
profile_parse_validation_failed: t('admin.orderProfilePublishCheck.crossTemplateParseFailed'),
profile_evidence_coverage_insufficient: t('admin.orderProfilePublishCheck.crossTemplateCoverageInsufficient'),
profile_margin_insufficient: t('admin.orderProfilePublishCheck.crossTemplateMarginInsufficient'),
};
return map[value] || t('admin.orderProfilePublishCheck.unknownIssue');
}
onMounted(loadRuns);
</script>
<template>
<section class="page">
<header>
<div>
<h1 class="section-title">{{ t('admin.orderProfilePublishCheck.title') }}</h1>
<small class="section-desc mt-1">{{ t('admin.orderProfilePublishCheck.description') }}</small>
</div>
<button type="button" class="btn-secondary" @click="backToValidation">{{ t('admin.orderProfilePublishCheck.back') }}</button>
</header>
<section v-if="!report" class="card">
<h2>{{ t('admin.orderProfilePublishCheck.readyTitle') }}</h2>
<p>{{ validationRun ? t('admin.orderProfilePublishCheck.readyHint') : t('admin.orderProfilePublishCheck.noRun') }}</p>
<button class="btn-primary" :disabled="busy || !validationRun" type="button" @click="createReport">
{{ t('admin.orderProfilePublishCheck.create') }}
</button>
</section>
<template v-else>
<section class="card">
<div class="card-head">
<h2>{{ t('admin.orderProfilePublishCheck.reportTitle') }}</h2>
<button class="btn-secondary" :disabled="busy || !validationRun" type="button" @click="createReport">
{{ t('admin.orderProfilePublishCheck.rerun') }}
</button>
</div>
<p :class="['gate-status', gateStatus]">{{ gateStatus === 'blocked' ? t('admin.orderProfilePublishCheck.blockedHint') : t('admin.orderProfilePublishCheck.reviewHint') }}</p>
</section>
<section class="card">
<h3>{{ t('admin.orderProfilePublishCheck.layoutSignatureTitle') }}</h3>
<dl class="metrics">
<div><dt>{{ t('admin.orderProfilePublishCheck.signatureStatus') }}</dt><dd :class="`status-${signatureStatusDetail?.status || 'unknown'}`">{{ signatureStatus(signatureStatusDetail?.status) }}</dd></div>
<div><dt>{{ t('admin.orderProfilePublishCheck.signatureSampleCount') }}</dt><dd>{{ signatureStatusDetail?.source_sample_count ?? '—' }}</dd></div>
<div v-for="metric in signatureIdentityMetrics" :key="metric.label"><dt>{{ metric.label }}</dt><dd>{{ metric.value }}</dd></div>
<div><dt>{{ t('admin.orderProfilePublishCheck.matcherPolicyVersion') }}</dt><dd>{{ report.matcher_policy_version || signatureStatusDetail?.matcher_policy_version || '—' }}</dd></div>
</dl>
</section>
<section class="card">
<h3>{{ t('admin.orderProfilePublishCheck.uniquenessTitle') }}</h3>
<dl class="metrics">
<div><dt>{{ t('admin.orderProfilePublishCheck.trainingUniqueRate') }}</dt><dd>{{ formatRate(report.overlap_summary?.self_unique_hit_rate_training) }}</dd></div>
<div><dt>{{ t('admin.orderProfilePublishCheck.blindUniqueRate') }}</dt><dd>{{ formatRate(report.overlap_summary?.self_unique_hit_rate_blind) }}</dd></div>
<div><dt>{{ t('admin.orderProfilePublishCheck.falseHitCount') }}</dt><dd>{{ report.overlap_summary?.false_hit_other_count ?? 0 }}</dd></div>
<div><dt>{{ t('admin.orderProfilePublishCheck.reverseFalseHitCount') }}</dt><dd>{{ report.overlap_summary?.reverse_false_hit_count ?? 0 }}</dd></div>
<div><dt>{{ t('admin.orderProfilePublishCheck.ambiguousCount') }}</dt><dd>{{ report.overlap_summary?.ambiguous_count ?? 0 }}</dd></div>
<div><dt>{{ t('admin.orderProfilePublishCheck.minEvidenceCoverage') }}</dt><dd>{{ formatRate(report.overlap_summary?.min_evidence_coverage) }} / ≥ {{ formatRate(report.overlap_summary?.thresholds?.evidence_coverage_minimum) }}</dd></div>
<div><dt>{{ t('admin.orderProfilePublishCheck.minMargin') }}</dt><dd>{{ report.overlap_summary?.min_margin ?? '—' }} / ≥ {{ report.overlap_summary?.thresholds?.minimum_margin ?? '—' }}</dd></div>
<div><dt>{{ t('admin.orderProfilePublishCheck.parseFailedCount') }}</dt><dd>{{ report.overlap_summary?.parse_validation_failed_count ?? 0 }}</dd></div>
</dl>
</section>
<section v-if="adapterValidationMetrics.length" class="card">
<h3>{{ t('admin.orderProfilePublishCheck.xfaUnifiedMetricsTitle') }}</h3>
<dl class="metrics">
<div v-for="metric in adapterValidationMetrics" :key="metric.label"><dt>{{ metric.label }}</dt><dd>{{ formatRate(metric.value) }}</dd></div>
</dl>
</section>
<section v-if="conflictProfiles.length" class="card">
<h3>{{ t('admin.orderProfilePublishCheck.conflictsTitle') }}</h3>
<article v-for="conflict in conflictProfiles" :key="`${conflict.profile_code}-${conflict.version}`" class="conflict-card">
<strong>{{ conflict.profile_code }} v{{ conflict.version }}</strong>
<p class="reasons">{{ conflict.reason_codes.map(conflictReason).join(';') }}</p>
<p>{{ conflict.suggestion }}</p>
<button type="button" class="btn-secondary" @click="backToEditor">{{ t('admin.orderProfilePublishCheck.backToEditor') }}</button>
</article>
</section>
<section class="card">
<h3>{{ t('admin.orderProfilePublishCheck.blocking') }}</h3>
<p v-if="!report.blocking_items.length" class="good">{{ t('admin.orderProfilePublishCheck.noBlocking') }}</p>
<ul v-else>
<li v-for="item in report.blocking_items" :key="String(item.key)">{{ itemMessage(item) }}</li>
</ul>
<h3>{{ t('admin.orderProfilePublishCheck.warnings') }}</h3>
<label v-for="item in report.warning_items" :key="String(item.key)">
<input v-model="confirmed" type="checkbox" :value="String(item.key)">
<span>{{ itemMessage(item) }}</span>
</label>
<p v-if="report.warning_items.length" class="hint">{{ t('admin.orderProfilePublishCheck.confirmHint') }}</p>
<button class="btn-primary" :disabled="busy || !publishable" type="button" @click="publish">
{{ t('admin.orderProfilePublishCheck.confirm') }}
</button>
</section>
</template>
</section>
</template>
<style scoped>
.page { width: 100%; margin: 0; padding: 24px; color: #334155; }
.page header { display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: space-between; gap: 16px; }
.page h1 { margin: 0; }
.page small:not(.section-desc), .card p { color: #64748b; font-size: 13px; line-height: 1.5; }
.page small { display: block; margin-top: 5px; }
.card { margin-top: 20px; border: 1px solid #dfe7ef; border-radius: 10px; background: #fff; padding: 16px; box-shadow: 0 1px 2px rgb(15 23 42 / 3%); }
.card-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.card h2 { margin: 0; color: #1e293b; font-size: 15px; font-weight: 600; }
.card h3 { margin: 0 0 12px; color: #1e293b; font-size: 14px; }
.card label { display: flex; gap: 8px; margin: 10px 0; color: #475569; font-size: 13px; }
.card input { accent-color: #0ea5e9; }
.card .btn-primary { margin-top: 14px; }
.good { color: #15803d; font-size: 13px; }
.gate-status { font-weight: 600; }
.gate-status.blocked { color: #b91c1c; }
.gate-status.pass, .status-valid { color: #15803d; }
.status-missing, .status-stale { color: #b45309; }
.hint { font-size: 13px; }
ul { margin: 8px 0; padding-left: 20px; color: #b91c1c; font-size: 13px; }
.metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin: 0; }
.metrics div { display: grid; gap: 4px; }
.metrics dt { color: #64748b; font-size: 12px; }
.metrics dd { margin: 0; color: #1e293b; font-size: 14px; font-weight: 600; }
.conflict-card { border: 1px solid #fecaca; background: #fff7f7; border-radius: 8px; padding: 12px; margin-top: 10px; }
.conflict-card strong { color: #991b1b; font-size: 13px; }
.conflict-card .reasons { color: #b45309; font-size: 12px; }
@media (max-width: 767px) {
.page { padding: 16px; }
.page header, .card-head { display: grid; }
.page header button, .card-head button { width: 100%; }
}
</style>
@@ -0,0 +1,398 @@
<!--
features/admin/modules/shipping-order-document-profiles/OrderProfileValidationPage.vue
用途:验证当前订单模板草稿,并按“基础验证、盲测、发布检查”顺序引导管理员。
依赖:Profile 验证 API、编辑租约、Vue Router、统一消息提示。
逻辑:一次动作依次执行结构检查和当前样本试读;XFA 从验证摘要展示完整字段级结果;
盲测批准前不解锁发布检查入口。
-->
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
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,
getOrderDocumentProfileDetail,
listOrderProfileBoundSamples,
listOrderProfileValidationRuns,
runOrderProfileCurrentSample,
runOrderProfileInstantCheck,
createOrderProfileTestSuite,
} from '@/features/admin/api/shipping-order-document-profile.api';
import type {
OrderProfileBoundSample,
OrderProfileValidationEvidence,
OrderProfileValidationEvidenceField,
OrderProfileValidationRun,
OrderProfileTestSuite,
ShippingOrderDocumentProfile,
} from '@/features/admin/types/shipping-order-document-profile.types';
const route = useRoute();
const router = useRouter();
const { t, te } = useI18n();
const message = useMessage();
const profileId = Number(route.params.profileId);
const runs = ref<OrderProfileValidationRun[]>([]);
const loading = ref(false);
const executing = ref(false);
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() || createRandomUuid();
const blindTestSuite = ref<OrderProfileTestSuite | null>(null);
const validationEvidence = computed<OrderProfileValidationEvidence | null>(() => {
const raw = sampleRun.value?.summary?.validation_evidence;
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
const value = raw as Record<string, unknown>;
return {
header_fields: Array.isArray(value.header_fields) ? value.header_fields as OrderProfileValidationEvidenceField[] : [],
lines: Array.isArray(value.lines) ? value.lines as OrderProfileValidationEvidence['lines'] : [],
cross_checks: value.cross_checks && typeof value.cross_checks === 'object' && !Array.isArray(value.cross_checks)
? value.cross_checks as Record<string, unknown>
: {},
reservation_region_status: typeof value.reservation_region_status === 'string'
? value.reservation_region_status
: undefined,
reservation_region_review_reasons: Array.isArray(value.reservation_region_review_reasons)
? value.reservation_region_review_reasons.map((item) => String(item))
: undefined,
};
});
const evidenceHeaderFields = computed(() => validationEvidence.value?.header_fields || []);
const evidenceLines = computed(() => validationEvidence.value?.lines || []);
const reservationRegionReviewReasons = computed(
() => validationEvidence.value?.reservation_region_review_reasons || [],
);
const ADAPTER_CROSS_CHECK_KEYS = [
'mirror_status',
'acroform_status',
'line_amount_status',
'total_amount_status',
] as const;
/**
* 从统一字段预览中取标准化值。
*/
function evidenceFieldNormalized(
fields: OrderProfileValidationEvidenceField[],
fieldCode: string,
): string {
const hit = fields.find((item) => item.field_code === fieldCode);
return (hit?.normalized_value ?? '').trim();
}
/**
* 将 adapter 交叉校验状态映射为管理员可读说明(含金额计算过程)。
*/
const adapterCrossCheckEntries = computed(() => {
const checks = validationEvidence.value?.cross_checks;
if (!checks || typeof checks !== 'object' || Array.isArray(checks)) return [];
const map = checks as Record<string, unknown>;
const firstLineFields = evidenceLines.value[0]?.fields || [];
const qty = evidenceFieldNormalized(firstLineFields, 'quantity');
const unitPrice = evidenceFieldNormalized(firstLineFields, 'unit_price');
const amount = evidenceFieldNormalized(firstLineFields, 'amount');
const total = evidenceFieldNormalized(evidenceHeaderFields.value, 'total_amount')
|| evidenceFieldNormalized(evidenceHeaderFields.value, 'order_amount');
const lineSum = evidenceLines.value.reduce((sum, line) => {
const fields = line.fields || [];
const raw = evidenceFieldNormalized(fields, 'amount').replace(/,/g, '');
const n = Number(raw);
return Number.isFinite(n) ? sum + n : sum;
}, 0);
const lineSumText = Number.isFinite(lineSum) && lineSum > 0
? String(Number(lineSum.toFixed(2)))
: amount;
return ADAPTER_CROSS_CHECK_KEYS
.filter((key) => map[key] != null && String(map[key]).trim() !== '')
.map((key) => {
const status = String(map[key] ?? '').trim().toLowerCase();
const label = t(`admin.orderProfileValidation.xfaCheckLabel.${key}`);
const statusLabel = t(
`admin.orderProfileValidation.xfaCheckStatus.${status}`,
status || '-',
);
let detail = '';
if (key === 'line_amount_status' && qty && unitPrice && amount) {
detail = t('admin.orderProfileValidation.xfaAmountFormulaWithoutPriceUnit', {
quantity: qty,
unitPrice,
amount,
});
} else if (key === 'total_amount_status' && total && lineSumText) {
detail = t('admin.orderProfileValidation.xfaTotalFormula', {
total,
lineSum: lineSumText,
});
} else if (key === 'mirror_status' || key === 'acroform_status') {
const hintKey = `admin.orderProfileValidation.xfaCheckHint.${key}.${status}`;
detail = te(hintKey) ? t(hintKey) : '';
}
if (key === 'acroform_status' && Array.isArray(map.acroform_mismatches) && map.acroform_mismatches.length) {
detail = map.acroform_mismatches.map((item) => {
const mismatch = item as Record<string, unknown>;
const row = mismatch.row_index ? ` #${mismatch.row_index}` : '';
return `${String(mismatch.field_code || '-')}${row}: ${String(mismatch.dataset_value ?? '-')} ≠ ${String(mismatch.acroform_value ?? '-')}`;
}).join(';');
}
if (key === 'line_amount_status' && Array.isArray(map.line_amount_failures) && map.line_amount_failures.length) {
detail = map.line_amount_failures.map((item) => {
const failure = item as Record<string, unknown>;
const formula = `${String(failure.quantity ?? '-')} × ${String(failure.unit_price ?? '-')}`;
return `#${String(failure.row_index || '-')}: ${formula} = ${String(failure.expected_amount ?? '?')},amount=${String(failure.amount ?? '-')}`;
}).join(';');
}
return { key, label, statusLabel, detail, status };
});
});
const latestRun = (runType: OrderProfileValidationRun['run_type']) =>
runs.value.find((item) => item.run_type === runType) || null;
const structureRun = computed(() => latestRun('instant_check'));
const sampleRun = computed(() => latestRun('current_sample'));
const canStartBlindTest = computed(() => structureRun.value?.status === 'passed' && sampleRun.value?.status === 'passed');
const canPublish = computed(() => canStartBlindTest.value && blindTestSuite.value?.status === 'approved');
const validationState = computed<'ready' | 'stale' | 'failed' | 'pending'>(() => {
if (canStartBlindTest.value) return 'ready';
if (runs.value.some((item) => item.status === 'stale')) return 'stale';
if (runs.value.some((item) => item.status === 'failed')) return 'failed';
return 'pending';
});
/** 将后端业务错误转换为统一提示,避免验证页泄露服务端内部细节。 */
function report(error: unknown): void {
const code = error instanceof BusinessError ? error.code : '';
message.error(code ? t(`errors.${code}`, code) : t('admin.orderProfileValidation.failed'));
}
/** 读取或建立当前草稿 checksum 的盲测集,使发布入口按已批准状态而非仅样本试读解锁。 */
async function loadBlindTestSuite(): Promise<void> {
if (!canStartBlindTest.value) {
blindTestSuite.value = null;
return;
}
try {
blindTestSuite.value = await createOrderProfileTestSuite(profileId);
} catch (error) {
report(error);
}
}
/** 读取当前草稿对应的不可变验证运行;后端负责将旧 checksum 派生为 stale。 */
async function loadRuns(): Promise<void> {
loading.value = true;
try { runs.value = await listOrderProfileValidationRuns(profileId); } catch (error) { report(error); } finally { loading.value = false; }
}
/** 读取当前草稿和可试读样本;只选建模证据,绝不把盲测样本暴露到页面。 */
async function loadContext(): Promise<void> {
try {
const [detail, samples] = await Promise.all([
getOrderDocumentProfileDetail(profileId), listOrderProfileBoundSamples(profileId),
]);
profile.value = detail;
const selectedSample = samples.find((item) => item.sample_role === 'annotation' || item.sample_role === 'training') || null;
// Validation must use the immutable table identity captured with the sample;
// a legacy mutable binding can point at a table id from a newer layout.
sample.value = selectedSample
? { ...selectedSample, table_id: selectedSample.table_identity_snapshot?.table_id || selectedSample.table_id }
: null;
const schema = await getShippingOrderSchemaVersion(detail.schema_version_id);
fieldNames.value = new Map((schema.definition?.fields || []).map((field) => [field.field_code || '', field.display_name]));
} catch (error) { report(error); }
}
/** Schema 显示名称服务于业务核对;稳定编码仅作为辅助追溯信息保留。 */
function fieldName(fieldCode: string): string { return fieldNames.value.get(fieldCode) || fieldCode; }
/** 为本页获取单写者租约,避免验证或发布检查绕过草稿编辑保护。 */
async function ensureLease(): Promise<boolean> {
if (leaseToken.value) return true;
try {
leaseToken.value = (await acquireOrderDocumentProfileEditLease(profileId, {
browser_session_id: sessionId, operation_id: createRandomUuid(),
})).lease_token;
return true;
} catch (error) { report(error); return false; }
}
/** 依次执行配置结构和当前样本试读;任一步失败均不允许进入发布检查。 */
async function validateCurrentDraft(): Promise<void> {
if (!(await ensureLease())) return;
if (!sample.value?.id) {
message.error(t('admin.orderProfileValidation.noTrainingSample'));
return;
}
executing.value = true;
try {
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();
// Refresh the draft/sample context after validation so the result preview
// uses the same binding and definition that the server just validated.
await loadContext();
await loadBlindTestSuite();
message.success(t('admin.orderProfileValidation.completed'));
} catch (error) { report(error); } finally { executing.value = false; }
}
/** 在基本验证通过后进入独立盲测,避免把建模样本试读误当成发布质量凭证。 */
function goToBlindTest(): void {
if (!canStartBlindTest.value) return;
router.push({ name: 'AdminShippingOrderDocumentProfileBlindTest', params: route.params, query: { editorSessionId: sessionId } });
}
/** 仅在当前草稿的盲测已批准时进入发布检查;后端仍会以 checksum 再次复核门禁。 */
function goToPublishCheck(): void {
if (!canPublish.value) return;
router.push({ name: 'AdminShippingOrderDocumentProfilePublishCheck', params: route.params, query: { editorSessionId: sessionId } });
}
/** 返回同一草稿的编辑路由,保留标签会话身份以复用仍有效的租约。 */
function backToEditor(): void {
router.push({ name: 'AdminShippingOrderDocumentProfileEdit', params: route.params, query: { editorSessionId: sessionId } });
}
onMounted(async () => {
await Promise.all([loadRuns(), loadContext()]);
if (canStartBlindTest.value) {
await loadBlindTestSuite();
}
});
</script>
<template>
<section class="validation-page">
<header>
<div>
<h1 class="section-title">{{ t('admin.orderProfileValidation.title') }}</h1>
<p class="section-desc mt-1">{{ t('admin.orderProfileValidation.description') }}</p>
</div>
<button class="btn-secondary" type="button" @click="backToEditor">{{ t('admin.orderProfileValidation.backToEditor') }}</button>
</header>
<section class="validation-state" :class="`state-${validationState}`">
<div><b>{{ t(`admin.orderProfileValidation.state.${validationState}`) }}</b><p>{{ t(`admin.orderProfileValidation.stateHint.${validationState}`) }}</p></div>
<button v-if="canStartBlindTest" type="button" class="btn-primary" :disabled="!canPublish" @click="goToPublishCheck">{{ t('admin.orderProfileValidation.goPublishCheck') }}</button>
</section>
<section class="validation-card current-draft-validation">
<header>
<div><h2>{{ t('admin.orderProfileValidation.currentDraft') }}</h2><p>{{ t('admin.orderProfileValidation.currentDraftHint') }}</p></div>
<button type="button" class="btn-primary" :disabled="executing" @click="validateCurrentDraft">{{ executing ? t('admin.orderProfileValidation.validating') : t('admin.orderProfileValidation.validateCurrent') }}</button>
</header>
<p v-if="loading">{{ t('admin.orderProfileValidation.loading') }}</p>
<div v-else class="checks" :aria-label="t('admin.orderProfileValidation.currentDraft')">
<article>
<div><h3>{{ t('admin.orderProfileValidation.structureCheck') }}</h3><p>{{ t('admin.orderProfileValidation.structureCheckHint') }}</p></div>
<strong :class="`status ${structureRun?.status || 'pending'}`">{{ t(`admin.orderProfileValidation.runStatus.${structureRun?.status || 'pending'}`) }}</strong>
</article>
<article>
<div><h3>{{ t('admin.orderProfileValidation.sampleCheck') }}</h3><p>{{ t('admin.orderProfileValidation.sampleCheckHint') }}</p></div>
<strong :class="`status ${sampleRun?.status || 'pending'}`">{{ t(`admin.orderProfileValidation.runStatus.${sampleRun?.status || 'pending'}`) }}</strong>
</article>
</div>
</section>
<section v-if="canStartBlindTest" class="blind-test-gate">
<div><h2>{{ t('admin.shippingOrderProfiles.blindTest.gateTitle') }}</h2><p>{{ blindTestSuite?.status === 'approved' ? t('admin.shippingOrderProfiles.blindTest.gateApprovedHint') : t('admin.shippingOrderProfiles.blindTest.gateRequiredHint') }}</p></div>
<div class="gate-actions"><strong :class="`status ${blindTestSuite?.status || 'pending'}`">{{ t(`admin.shippingOrderProfiles.blindTest.status.${blindTestSuite?.status || 'missing'}`) }}</strong><button type="button" class="btn-secondary" @click="goToBlindTest">{{ t('admin.shippingOrderProfiles.blindTest.title') }}</button></div>
</section>
<section v-if="profile && sample" class="results" :aria-label="t('admin.orderProfileValidation.resultsTitle')">
<div class="results-heading"><div><h2>{{ t('admin.orderProfileValidation.resultsTitle') }}</h2><p>{{ t('admin.orderProfileValidation.resultsHint') }}</p></div></div>
<template v-if="validationEvidence">
<dl class="header-results">
<div v-if="adapterCrossCheckEntries.length"><dt>{{ t('admin.orderProfileValidation.xfaCrossCheckStatus') }}</dt><dd>{{ adapterCrossCheckEntries.length }}</dd></div>
</dl>
<dl v-if="adapterCrossCheckEntries.length" class="header-results">
<div
v-for="item in adapterCrossCheckEntries"
:key="item.key"
:class="`field-${item.status === 'matched' || item.status === 'passed' || item.status === 'skipped' ? 'passed' : 'failed'}`"
>
<dt>{{ item.label }}</dt>
<dd>{{ item.statusLabel }}</dd>
<dd v-if="item.detail" class="field-code">{{ item.detail }}</dd>
</div>
</dl>
<h3>{{ t('admin.orderProfileValidation.headerResults') }}</h3>
<dl v-if="evidenceHeaderFields.length" class="header-results">
<div
v-for="field in evidenceHeaderFields"
:key="String(field.field_id || field.field_code)"
:class="`field-${String(field.status || 'missing')}`"
>
<dt>{{ fieldName(String(field.field_code || '')) }}</dt>
<dd class="field-code">{{ field.field_code }}</dd>
<dd>{{ t('admin.orderProfileValidation.read') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</dd>
<dd v-if="field.raw_value && field.raw_value !== field.normalized_value" class="field-code">{{ field.raw_value }}</dd>
<dd v-if="field.issues.length" class="field-issues">{{ field.issues.join(', ') }}</dd>
</div>
</dl>
<p v-else>{{ t('admin.orderProfileValidation.noHeaderResults') }}</p>
<section
v-if="validationEvidence?.reservation_region_status === 'needs_review' || reservationRegionReviewReasons.length"
class="reservation-region-review"
>
<h3>{{ t('admin.orderProfileValidation.reservationRegionTitle') }}</h3>
<p>{{ t('admin.orderProfileValidation.reservationRegionNeedsReview', {
reasons: reservationRegionReviewReasons.join(', ') || validationEvidence?.reservation_region_status || '-',
}) }}</p>
</section>
<h3>{{ t('admin.orderProfileValidation.lineResults') }}</h3>
<div v-if="evidenceLines.length" class="line-results">
<article v-for="line in evidenceLines" :key="String(line.row_index)" class="xfa-line-card">
<h4>#{{ Number(line.row_index) + 1 }}</h4>
<dl class="header-results">
<div
v-for="field in line.fields"
:key="String(field.field_id || field.field_code)"
:class="`field-${String(field.status || 'missing')}`"
>
<dt>{{ fieldName(String(field.field_code || '')) }}</dt>
<dd class="field-code">{{ field.field_code }}</dd>
<dd>{{ t('admin.orderProfileValidation.read') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</dd>
<dd v-if="field.raw_value && field.raw_value !== field.normalized_value" class="field-code">{{ field.raw_value }}</dd>
<dd v-if="field.issues.length" class="field-issues">{{ field.issues.join(', ') }}</dd>
</div>
</dl>
</article>
</div>
<p v-else>{{ t('admin.orderProfileValidation.noLineResults') }}</p>
</template>
<p v-else class="result-error">{{ t('admin.orderProfileValidation.resultsFailed') }}</p>
</section>
</section>
</template>
<style scoped>
.validation-page { width: 100%; margin: 0; padding: 24px; color: #334155; }
header { display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: space-between; gap: 16px; }
h1 { margin: 0; }
header p:not(.section-desc), .validation-card p, .checks p, .validation-state p, .blind-test-gate p { margin: 5px 0 0; color: #64748b; font-size: 13px; line-height: 1.5; }
button:disabled { cursor: not-allowed; opacity: .55; }
.validation-state, .validation-card, .checks article, .blind-test-gate, .results { border: 1px solid #dfe7ef; border-radius: 10px; background: #fff; box-shadow: 0 1px 2px rgb(15 23 42 / 3%); }
.validation-state { display: flex; align-items: center; justify-content: space-between; gap: 20px; margin-top: 20px; padding: 16px; }
.validation-state { border-color: #bae6fd; background: #f0f9ff; }.validation-state b { color: #0369a1; font-size: 14px; }.state-ready { border-color: #bbf7d0; background: #f0fdf4; }.state-ready b { color: #15803d; }.state-stale, .state-failed { border-color: #fecaca; background: #fef2f2; }.state-stale b, .state-failed b { color: #b91c1c; }
.validation-card h2, .checks h3 { margin: 0; color: #1e293b; font-size: 15px; font-weight: 600; }
.current-draft-validation { display: grid; gap: 16px; margin-top: 20px; padding: 16px; }.current-draft-validation > header { align-items: center; }.current-draft-validation > header > div { min-width: 0; }.current-draft-validation > header button { flex: 0 0 auto; }.checks { display: grid; gap: 10px; }.checks article { display: flex; align-items: center; justify-content: space-between; gap: 20px; border-radius: 8px; padding: 15px 16px; }.status { min-width: 72px; text-align: right; font-size: 13px; font-weight: 600; }.passed { color: #15803d; }.failed, .stale { color: #b91c1c; }.pending, .running { color: #64748b; }
.blind-test-gate { display: flex; align-items: center; justify-content: space-between; gap: 20px; margin-top: 20px; padding: 16px; }.blind-test-gate h2 { margin: 0; color: #1e293b; font-size: 15px; font-weight: 600; }.gate-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }.gate-actions .approved { color: #15803d; }.gate-actions .draft, .gate-actions .missing { color: #b45309; }
.results { margin-top: 20px; padding: 16px; }.results-heading { display: flex; align-items: center; justify-content: space-between; gap: 16px; }.results h2, .results h3 { margin: 0; color: #1e293b; }.results h2 { font-size: 15px; }.results h3 { margin-top: 20px; font-size: 14px; }.results-heading p { margin: 5px 0 0; color: #64748b; font-size: 13px; line-height: 1.5; }.header-results { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px; margin: 12px 0 0; }.header-results div { border: 1px solid #e5ebf1; border-radius: 6px; background: #fbfdff; padding: 10px; }.header-results dt { color: #475569; font-size: 13px; font-weight: 600; }.header-results dd { margin: 4px 0 0; overflow-wrap: anywhere; }.header-results .field-code, .line-results th small { color: #94a3b8; font-size: 11px; font-weight: 400; }.line-results { margin-top: 12px; overflow-x: auto; border: 1px solid #e5ebf1; border-radius: 6px; }.line-results table { width: 100%; min-width: 560px; border-collapse: collapse; }.line-results th, .line-results td { padding: 10px 12px; border-bottom: 1px solid #e5ebf1; text-align: left; vertical-align: top; overflow-wrap: anywhere; }.line-results tbody tr:last-child td { border-bottom: 0; }.line-results th { background: #f8fafc; color: #64748b; font-size: 12px; font-weight: 600; }.line-results th span, .line-results th small { display: block; }.deleted-row { color: #94a3b8; text-decoration: line-through; }.result-error { color: #b91c1c; }
.header-results .field-needs_review, .header-results .field-unavailable, .header-results .field-failed, .header-results .field-missing { border-color: #fed7aa; background: #fff7ed; }.header-results .field-issues { color: #b45309; font-size: 11px; }
.header-results .field-passed { border-color: #bbf7d0; background: #f0fdf4; }
.reservation-region-review { margin-top: 16px; padding: 12px; border: 1px solid #fed7aa; border-radius: 8px; background: #fff7ed; }
.reservation-region-review h3 { margin: 0; color: #9a3412; font-size: 14px; }
.reservation-region-review p { margin: 6px 0 0; color: #b45309; font-size: 13px; }
.xfa-line-card { margin-top: 12px; padding: 12px; border: 1px solid #e5ebf1; border-radius: 8px; background: #fbfdff; }.xfa-line-card h4 { margin: 0 0 8px; font-size: 13px; color: #475569; }
@media (max-width: 767px) { .validation-page { padding: 16px; } header, .validation-state, .current-draft-validation > header, .checks article, .blind-test-gate, .results-heading { display: grid; }.validation-state button, .current-draft-validation > header button, .blind-test-gate button, .results-heading button { width: 100%; } }
</style>
@@ -0,0 +1,703 @@
<!--
features/admin/modules/shipping-order-document-profiles/OrderProfileVersionDetailPage.vue
用途:订单模板版本中心详情页,支持刷新恢复与分享。
依赖:版本详情 composable、配置概览组件、版本中心 API、统一迁移 API。
逻辑:当前已接入配置概览、只读样本画布、服务端语义 diff、审计时间线与实际使用;
Schema 迁移弹窗按模态语义提供初始焦点、Tab 陷阱、Escape 关闭与焦点恢复;
统一 binding 迁移提供 Dry Run 状态徽章入口。
-->
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import { BusinessError } from "@/shared/api/client";
import { useMessage } from "@/shared/composables/useMessage";
import {
cloneOrderDocumentProfile,
dryRunOrderProfileUnifiedMigration,
getOrderProfileUnifiedMigrationReport,
migrateOrderDocumentProfileSchema,
} from "@/features/admin/api/shipping-order-document-profile.api";
import { getShippingOrderSchemaState } from "@/features/admin/api/shipping-order-schema.api";
import type { ShippingOrderSchemaVersion } from "@/features/admin/types/shipping-order-schema.types";
import OrderProfileReadOnlyCanvas from "./components/OrderProfileReadOnlyCanvas.vue";
import OrderProfileAuditTimeline from "./components/OrderProfileAuditTimeline.vue";
import OrderProfileVersionDiff from "./components/OrderProfileVersionDiff.vue";
import OrderProfileVersionOverview from "./components/OrderProfileVersionOverview.vue";
import OrderProfileUsageTable from "./components/OrderProfileUsageTable.vue";
import {
useOrderProfileVersionDetail,
type OrderProfileVersionDetailTab,
} from "./composables/useOrderProfileVersionDetail";
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const message = useMessage();
const cloning = ref(false);
const migrating = ref(false);
const unifiedMigrating = ref(false);
const unifiedMigrationReport = ref<{
path_preserve_rate?: number;
field_diff_count?: number;
pending_visual_count?: number;
binding_count?: number;
} | null>(null);
const migrationOpen = ref(false);
const publishedSchema = ref<ShippingOrderSchemaVersion | null>(null);
const migrationResolutions = ref<Record<string, { action: "unbind" } | { replacement_field_id: string }>>({});
const migrationPanelRef = ref<HTMLElement | null>(null);
const migrationCancelRef = ref<HTMLButtonElement | null>(null);
let previouslyFocused: HTMLElement | null = null;
const FOCUSABLE_SELECTOR = [
"a[href]",
"button:not([disabled])",
"textarea:not([disabled])",
"input:not([disabled])",
"select:not([disabled])",
'[tabindex]:not([tabindex="-1"])',
].join(",");
const {
activeTab,
detail,
errorMessage,
loading,
profileCode,
tabOptions,
versions,
} = useOrderProfileVersionDetail();
const canMigrateSchema = computed(() =>
detail.value?.status === "published"
&& publishedSchema.value !== null
&& detail.value.schema_version_id !== publishedSchema.value.id,
);
const breakingChanges = computed(() => detail.value?.schema_compatibility?.breaking_changes || []);
const loadPublishedSchema = async () => {
try {
const state = await getShippingOrderSchemaState();
publishedSchema.value = state.versions.find((item) => item.status === "published") || null;
} catch {
publishedSchema.value = null;
}
};
/** 收集迁移弹窗内可聚焦控件。 */
function migrationFocusableNodes(): HTMLElement[] {
if (!migrationPanelRef.value) return [];
return Array.from(migrationPanelRef.value.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR))
.filter((node) => !node.hasAttribute("disabled") && node.getAttribute("aria-hidden") !== "true");
}
/** 关闭 Schema 迁移弹窗。 */
function closeSchemaMigration(): void {
if (migrating.value) return;
migrationOpen.value = false;
}
/**
* Escape 关闭;Tab 在弹窗内循环,阻止焦点逃逸到背景页。
*/
function onMigrationKeydown(event: KeyboardEvent): void {
if (!migrationOpen.value) return;
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
closeSchemaMigration();
return;
}
if (event.key !== "Tab") return;
const nodes = migrationFocusableNodes();
const first = nodes[0];
const last = nodes[nodes.length - 1];
if (!first || !last) {
event.preventDefault();
return;
}
const active = document.activeElement as HTMLElement | null;
const inside = Boolean(active && migrationPanelRef.value?.contains(active));
if (event.shiftKey) {
if (!inside || active === first) {
event.preventDefault();
last.focus();
}
return;
}
if (!inside || active === last) {
event.preventDefault();
first.focus();
}
}
const openSchemaMigration = () => {
migrationResolutions.value = Object.fromEntries(
breakingChanges.value.map((change) => [change.field_id, { action: "unbind" }]),
);
migrationOpen.value = true;
};
const setMigrationResolution = (fieldId: string, replacementId: string) => {
migrationResolutions.value[fieldId] = replacementId
? { replacement_field_id: replacementId }
: { action: "unbind" };
};
const migrationReplacementId = (fieldId: string): string => {
const resolution = migrationResolutions.value[fieldId];
return resolution && "replacement_field_id" in resolution ? resolution.replacement_field_id : "";
};
const migrationErrorMessage = (error: unknown): string => {
if (!(error instanceof BusinessError)) return t("admin.shippingOrderProfiles.loadFailed");
const reason = String(error.details.reason || "");
if (reason === "duplicate_field_code") {
return t("admin.shippingOrderProfiles.schemaMigration.duplicateSchemaField", {
field: error.details.field_code || "-",
existingScope: error.details.existing_scope || "-",
duplicateScope: error.details.duplicate_scope || "-",
});
}
if (reason === "line_start_field_unbound") {
return t("admin.shippingOrderProfiles.schemaMigration.lineStartRequired", {
field: error.details.line_start_field_code || "-",
});
}
const fieldPath = String(error.details.field_path || "");
return fieldPath
? `${error.message} (${t("admin.shippingOrderProfiles.schemaMigration.invalidPath", { path: fieldPath })})`
: error.message;
};
const migrateSchema = async () => {
if (!detail.value || !publishedSchema.value || migrating.value) return;
migrating.value = true;
try {
const draft = await migrateOrderDocumentProfileSchema(
detail.value.id,
publishedSchema.value.id,
migrationResolutions.value,
);
message.success(t("admin.shippingOrderProfiles.schemaMigration.created"));
migrationOpen.value = false;
void router.push({
name: "AdminShippingOrderDocumentProfiles",
query: { profileCode: draft.profile_code, profileId: String(draft.id) },
});
} catch (error) {
message.error(migrationErrorMessage(error));
} finally {
migrating.value = false;
}
};
onMounted(() => { void loadPublishedSchema(); });
watch(
() => migrationOpen.value,
async (open, wasOpen) => {
if (typeof document === "undefined") return;
if (open && !wasOpen) {
previouslyFocused = document.activeElement instanceof HTMLElement
? document.activeElement
: null;
document.addEventListener("keydown", onMigrationKeydown, true);
await nextTick();
(migrationCancelRef.value || migrationFocusableNodes()[0])?.focus();
return;
}
if (!open && wasOpen) {
document.removeEventListener("keydown", onMigrationKeydown, true);
const restoreTarget = previouslyFocused;
previouslyFocused = null;
await nextTick();
restoreTarget?.focus?.();
}
},
);
onBeforeUnmount(() => {
if (typeof document !== "undefined") {
document.removeEventListener("keydown", onMigrationKeydown, true);
}
});
watch([detail, publishedSchema, () => route.query.migrate], () => {
if (route.query.migrate !== "1" || !canMigrateSchema.value || migrationOpen.value) return;
openSchemaMigration();
void router.replace({ query: { ...route.query, migrate: undefined } });
});
const pageTitle = computed(() => {
if (!detail.value) {
return `${profileCode.value} · v${route.params.version || ""}`;
}
const statusKey =
detail.value.status === "draft"
? "currentDraft"
: detail.value.status === "published"
? "currentPublished"
: "retired";
return `${detail.value.profile_code} · v${detail.value.version} · ${t(
`admin.shippingOrderProfiles.versionCenter.status.${statusKey}`,
)}`;
});
const statusKey = (status: "draft" | "published" | "retired") =>
status === "draft" ? "currentDraft" : status === "published" ? "currentPublished" : "retired";
const openTab = (tab: OrderProfileVersionDetailTab) => {
void router.replace({
query: {
...route.query,
tab,
},
});
};
const openVersion = (profileCodeParam: string, versionParam: number) => {
void router.push({
name: "AdminShippingOrderDocumentProfileVersionDetail",
params: {
profileCode: profileCodeParam,
version: String(versionParam),
},
query: {
tab: activeTab.value,
},
});
};
const goBackToWorkbench = () => {
void router.push({
name: "AdminShippingOrderDocumentProfiles",
query: {
profileCode: profileCode.value || undefined,
},
});
};
const continueEditing = () => {
if (!detail.value) return;
void router.push({
name: "AdminShippingOrderDocumentProfiles",
query: {
profileCode: detail.value.profile_code,
profileId: String(detail.value.id),
},
});
};
const createNewVersion = async () => {
if (!detail.value || cloning.value) return;
cloning.value = true;
try {
const draft = await cloneOrderDocumentProfile(detail.value.id);
message.success(t("admin.shippingOrderProfiles.cloned"));
void router.push({
name: "AdminShippingOrderDocumentProfiles",
query: {
profileCode: draft.profile_code,
profileId: String(draft.id),
},
});
} catch (error) {
message.error(
error instanceof BusinessError ? error.message : t("admin.shippingOrderProfiles.loadFailed"),
);
} finally {
cloning.value = false;
}
};
/**
* 加载最近一次统一 binding 迁移报告(若有)。
*/
async function loadUnifiedMigrationReport(): Promise<void> {
if (!detail.value?.id) {
unifiedMigrationReport.value = null;
return;
}
try {
const payload = await getOrderProfileUnifiedMigrationReport(detail.value.id);
unifiedMigrationReport.value = (payload.report as typeof unifiedMigrationReport.value) || null;
} catch {
unifiedMigrationReport.value = null;
}
}
/**
* Dry Run 统一 binding 迁移并刷新状态徽章。
*/
async function runUnifiedMigrationDryRun(): Promise<void> {
if (!detail.value?.id || unifiedMigrating.value) return;
unifiedMigrating.value = true;
try {
const result = await dryRunOrderProfileUnifiedMigration(detail.value.id);
unifiedMigrationReport.value = result.report;
message.success(t("admin.shippingOrderProfiles.unifiedMigration.dryRunDone"));
} catch (error) {
message.error(
error instanceof BusinessError
? error.message
: t("admin.shippingOrderProfiles.unifiedMigration.dryRunFailed"),
);
} finally {
unifiedMigrating.value = false;
}
}
watch(
() => detail.value?.id,
() => {
void loadUnifiedMigrationReport();
},
{ immediate: true },
);
</script>
<template>
<section class="version-detail-page">
<header class="page-header">
<div class="header-main">
<div class="header-copy">
<p class="header-kicker">{{ t("admin.shippingOrderProfiles.title") }}</p>
<h1 class="section-title">{{ detail?.display_name || profileCode }}</h1>
<p class="header-meta">{{ pageTitle }}</p>
</div>
<div class="header-actions" v-if="detail">
<button type="button" class="btn-secondary" @click="goBackToWorkbench">
{{ t("admin.shippingOrderProfiles.versionCenter.backToWorkbench") }}
</button>
<button
v-if="detail.status === 'draft'"
type="button"
class="btn-primary"
@click="continueEditing"
>
{{ t("admin.shippingOrderProfiles.versionCenter.continueEditing") }}
</button>
<button
v-else
type="button"
class="btn-primary"
:disabled="cloning"
@click="createNewVersion"
>
{{
cloning
? t("admin.shippingOrderProfiles.saving")
: t("admin.shippingOrderProfiles.newVersion")
}}
</button>
<button
v-if="canMigrateSchema"
type="button"
class="btn-primary"
@click="openSchemaMigration"
>
{{ t("admin.shippingOrderProfiles.schemaMigration.action", { version: publishedSchema?.version }) }}
</button>
<button
type="button"
class="btn-ghost"
data-testid="order-profile-unified-migration-dry-run"
:disabled="unifiedMigrating"
@click="runUnifiedMigrationDryRun"
>
{{
unifiedMigrating
? t("admin.shippingOrderProfiles.unifiedMigration.running")
: t("admin.shippingOrderProfiles.unifiedMigration.dryRun")
}}
</button>
<span
v-if="unifiedMigrationReport"
class="unified-migration-badge"
data-testid="order-profile-unified-migration-badge"
>
{{
t("admin.shippingOrderProfiles.unifiedMigration.badge", {
pending: unifiedMigrationReport.pending_visual_count ?? 0,
diff: unifiedMigrationReport.field_diff_count ?? 0,
})
}}
</span>
</div>
</div>
</header>
<div v-if="loading" class="state-card">
{{ t("admin.shippingOrderProfiles.versionCenter.loading") }}
</div>
<div v-else-if="errorMessage" class="state-card error-card">
{{ errorMessage }}
</div>
<template v-else-if="detail">
<nav class="tab-nav" :aria-label="t('admin.shippingOrderProfiles.versionCenter.tabsLabel')">
<button
v-for="tab in tabOptions"
:key="tab.key"
type="button"
class="tab-button"
:class="{ active: activeTab === tab.key }"
@click="openTab(tab.key)"
>
<span>{{ t(`admin.shippingOrderProfiles.versionCenter.tabs.${tab.key}`) }}</span>
<small v-if="tab.count !== undefined && tab.count !== null">{{ tab.count }}</small>
</button>
</nav>
<section class="version-switcher" :aria-label="t('admin.shippingOrderProfiles.versionCenter.familyVersions')">
<div class="version-switcher__label">
<span>{{ t("admin.shippingOrderProfiles.versionCenter.familyVersions") }}</span>
<small>{{ detail.profile_code }}</small>
</div>
<div class="version-switcher__list">
<button
v-for="item in versions"
:key="item.id"
type="button"
class="version-item"
:class="{ active: item.id === detail.id }"
@click="openVersion(item.profile_code, item.version)"
>
<strong>v{{ item.version }}</strong>
<span>{{ t(`admin.shippingOrderProfiles.versionCenter.status.${statusKey(item.status)}`) }}</span>
</button>
</div>
</section>
<div class="detail-panel">
<OrderProfileVersionOverview v-if="activeTab === 'overview'" :detail="detail" />
<OrderProfileReadOnlyCanvas v-else-if="activeTab === 'canvas'" :detail="detail" />
<OrderProfileVersionDiff v-else-if="activeTab === 'diff'" :detail="detail" :versions="versions" />
<OrderProfileAuditTimeline v-else-if="activeTab === 'audit'" :detail="detail" />
<OrderProfileUsageTable v-else-if="activeTab === 'usage'" :detail="detail" />
<section v-else class="state-card">
{{ t("admin.shippingOrderProfiles.loadFailed") }}
</section>
</div>
</template>
<div
v-if="migrationOpen"
class="migration-backdrop"
role="presentation"
data-testid="order-profile-schema-migration-backdrop"
@click.self="closeSchemaMigration"
>
<section
ref="migrationPanelRef"
class="migration-dialog"
role="dialog"
aria-modal="true"
:aria-label="t('admin.shippingOrderProfiles.schemaMigration.title')"
data-testid="order-profile-schema-migration-dialog"
>
<h2>{{ t("admin.shippingOrderProfiles.schemaMigration.title") }}</h2>
<p>{{ t("admin.shippingOrderProfiles.schemaMigration.description", { from: detail?.schema_version, to: publishedSchema?.version }) }}</p>
<p class="migration-note">{{ t("admin.shippingOrderProfiles.schemaMigration.revalidation") }}</p>
<div v-if="breakingChanges.length" class="migration-changes">
<article v-for="change in breakingChanges" :key="change.field_id">
<strong>{{ change.before || change.field_id }}</strong>
<span>{{ t("admin.shippingOrderProfiles.schemaMigration.reason", { reason: change.reason }) }}</span>
<label>
{{ t("admin.shippingOrderProfiles.schemaMigration.resolution") }}
<select
:value="migrationReplacementId(change.field_id)"
@change="setMigrationResolution(change.field_id, ($event.target as HTMLSelectElement).value)"
>
<option value="">{{ t("admin.shippingOrderProfiles.schemaMigration.unbind") }}</option>
<option v-for="candidate in change.replacement_candidates || []" :key="candidate.field_id" :value="candidate.field_id">
{{ candidate.display_name || candidate.field_code || candidate.field_id }}
</option>
</select>
</label>
</article>
</div>
<p v-else class="migration-note">{{ t("admin.shippingOrderProfiles.schemaMigration.noBreakingChanges") }}</p>
<footer>
<button
ref="migrationCancelRef"
type="button"
class="btn-secondary"
:disabled="migrating"
data-testid="order-profile-schema-migration-cancel"
@click="closeSchemaMigration"
>
{{ t("admin.shippingOrderProfiles.schemaMigration.cancel") }}
</button>
<button type="button" class="btn-primary" :disabled="migrating" @click="migrateSchema">
{{ migrating ? t("admin.shippingOrderProfiles.saving") : t("admin.shippingOrderProfiles.schemaMigration.confirm") }}
</button>
</footer>
</section>
</div>
</section>
</template>
<style scoped>
.version-detail-page {
display: grid;
gap: 1.25rem;
}
.page-header,
.state-card,
.version-switcher,
.detail-panel {
border: 1px solid var(--border-default);
border-radius: 1rem;
background: var(--bg-surface);
}
.page-header {
padding: 1.25rem 1.5rem;
}
.header-main {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
}
.header-copy {
min-width: 0;
}
.page-header h1 {
margin: 0;
}
.header-kicker,
.header-meta {
margin: 0;
color: var(--text-muted);
font-size: 0.8125rem;
}
.header-kicker { margin-bottom: 0.25rem; }
.header-meta { margin-top: 0.35rem; overflow-wrap: anywhere; }
.header-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 0.5rem; align-items: center; }
.unified-migration-badge {
display: inline-flex;
align-items: center;
border: 1px solid var(--border-default);
border-radius: 999px;
padding: 0.25rem 0.7rem;
font-size: 0.75rem;
color: var(--text-secondary);
background: var(--bg-muted, transparent);
}
.tab-button,
.version-item {
border: 1px solid var(--border-default);
border-radius: 0.75rem;
background: var(--bg-surface);
color: var(--text-secondary);
cursor: pointer;
font-size: 0.875rem;
}
.tab-nav {
display: flex;
gap: 0.35rem;
overflow-x: auto;
padding-bottom: 0.15rem;
}
.tab-button {
display: inline-flex;
align-items: center;
gap: 0.45rem;
padding: 0.55rem 0.85rem;
}
.tab-button.active {
border-color: #0ea5e9;
background: var(--status-info-bg);
color: var(--status-info-fg);
}
.version-switcher {
display: flex;
align-items: center;
gap: 1rem;
padding: 0.75rem 1rem;
}
.version-switcher__label {
display: grid;
flex: 0 0 auto;
gap: 0.1rem;
font-size: 0.875rem;
font-weight: 600;
color: var(--text-primary);
}
.version-switcher__label small {
max-width: 15rem;
overflow: hidden;
color: var(--text-muted);
font-size: 0.75rem;
font-weight: 400;
text-overflow: ellipsis;
white-space: nowrap;
}
.version-switcher__list {
display: flex;
min-width: 0;
gap: 0.5rem;
overflow-x: auto;
}
.version-item {
display: inline-flex;
flex: 0 0 auto;
align-items: baseline;
gap: 0.35rem;
padding: 0.55rem 0.7rem;
}
.version-item.active {
border-color: #0ea5e9;
background: var(--status-info-bg);
color: var(--status-info-fg);
}
.version-item span {
color: var(--text-muted);
font-size: 0.75rem;
}
.version-item.active span { color: inherit; }
.detail-panel { padding: 1.25rem; }
.error-card {
padding: 1rem;
color: var(--status-error-fg);
}
.migration-backdrop { position: fixed; z-index: 30; inset: 0; display: grid; place-items: center; padding: 1rem; background: rgb(15 23 42 / 45%); }
.migration-dialog { display: grid; width: min(100%, 42rem); max-height: min(44rem, calc(100vh - 2rem)); gap: 1rem; overflow: auto; padding: 1.5rem; border-radius: 1rem; background: var(--bg-surface); box-shadow: 0 20px 40px rgb(15 23 42 / 25%); }
.migration-dialog h2,.migration-dialog p { margin: 0; }.migration-note { color: var(--text-muted); font-size: .875rem; }.migration-changes { display: grid; gap: .75rem; }.migration-changes article { display: grid; gap: .45rem; padding: .85rem; border: 1px solid var(--border-default); border-radius: .75rem; }.migration-changes span { color: var(--text-muted); font-size: .8125rem; }.migration-changes label { display: grid; gap: .3rem; color: var(--text-secondary); font-size: .8125rem; font-weight: 600; }.migration-changes select { min-height: 2.25rem; border: 1px solid var(--border-default); border-radius: .5rem; background: var(--bg-surface); color: var(--text-primary); font: inherit; }.migration-dialog footer { display: flex; justify-content: flex-end; gap: .5rem; }
@media (max-width: 960px) {
.header-main,
.version-switcher {
align-items: flex-start;
flex-direction: column;
}
.header-actions { justify-content: flex-start; }
}
</style>
@@ -0,0 +1,13 @@
<!--
features/admin/modules/shipping-order-document-profiles/ShippingOrderDocumentProfilesPage.vue
用途:订单坐标 Profile 管理路由入口。
依赖:OrderProfileLibraryPage。
逻辑:列表页只承担模板族管理与路由分发;旧工作台不再作为首页创建入口。
-->
<script setup lang="ts">
import OrderProfileLibraryPage from './OrderProfileLibraryPage.vue';
</script>
<template>
<OrderProfileLibraryPage />
</template>
@@ -0,0 +1,162 @@
/**
* features/admin/modules/shipping-order-document-profiles/canvasActions.utils.spec.ts
* 用途:验证共享画布操作 adapter 的能力选择与事件转发。
* 依赖:Vitest、canvasActions.utils。
* 逻辑:编辑页按 Profile capability 选择 adapter;画布事件不再分别编排 XFA 与坐标流程。
*/
import { describe, expect, it, vi } from 'vitest';
import {
filterRegionsAfterRemoval,
resolveSelectedOrderAnchorId,
resolveCanvasActions,
resolveDeskAdapter,
resolveMainTableIdForPageChange,
resolveSharedCanvasDocument,
resolveValueAdapterKey,
shouldKeepUnreadableOrderField,
type OrderProfileCanvasActions,
} from './canvasActions.utils';
describe('filterRegionsAfterRemoval', () => {
it('deletes only the selected ordinary top-level region', () => {
const regions = [
{ id: 'green-1', kind: 'header_field', label: 'A', region: { x0: 0, y0: 0, x1: .1, y1: .1 }, pageNo: 1 },
{ id: 'green-2', kind: 'header_field', label: 'B', region: { x0: 0, y0: .2, x1: .1, y1: .3 }, pageNo: 1 },
] as any;
expect(filterRegionsAfterRemoval(regions, 'green-1')).toEqual([regions[1]]);
});
it('keeps ordinary top-level regions while deleting a document-anchor family', () => {
const regions = [
{ id: 'green-1', kind: 'header_field', label: 'A', region: { x0: 0, y0: 0, x1: .1, y1: .1 }, pageNo: 1 },
{ id: 'anchor-label', kind: 'document_anchor_label', label: 'Label', parentId: 'anchor-1', region: { x0: 0, y0: .2, x1: .1, y1: .3 }, pageNo: 1 },
{ id: 'anchor-value', kind: 'document_anchor_value', label: 'Value', parentId: 'anchor-1', region: { x0: 0, y0: .3, x1: .1, y1: .4 }, pageNo: 1 },
] as any;
expect(filterRegionsAfterRemoval(regions, 'anchor-label', 'anchor-1').map((item) => item.id)).toEqual(['green-1']);
});
});
describe('resolveSelectedOrderAnchorId', () => {
it('only returns an explicitly selected order anchor', () => {
const selectedAnchor = {
id: 'ship_to_anchor', kind: 'order_anchor', label: 'Ship to',
region: { x0: 0, y0: 0, x1: .1, y1: .1 }, pageNo: 1,
} as any;
const selectedValue = {
id: 'ship_to_value', kind: 'order_field', parentId: 'ship_to_anchor',
label: 'Example', region: { x0: 0, y0: .1, x1: .1, y1: .2 }, pageNo: 1,
} as any;
expect(resolveSelectedOrderAnchorId(selectedAnchor)).toBe('ship_to_anchor');
expect(resolveSelectedOrderAnchorId(selectedValue)).toBeNull();
expect(resolveSelectedOrderAnchorId(null)).toBeNull();
});
});
describe('shouldKeepUnreadableOrderField', () => {
it('keeps an XFA value box when visual readback remains unavailable', () => {
// OCR/Widget 回读失败必须可诊断,但不能让管理员已框选的 XFA 值框消失。
expect(shouldKeepUnreadableOrderField('xfa_dataset', 'order_field', false)).toBe(true);
});
it('keeps the ordinary-PDF empty-value guard unchanged', () => {
expect(shouldKeepUnreadableOrderField('coordinate_ocr', 'order_field', false)).toBe(false);
});
});
function actions(): OrderProfileCanvasActions {
return {
create: vi.fn(), select: vi.fn(), dragStart: vi.fn(), dragEnd: vi.fn(), change: vi.fn(),
undo: vi.fn(), redo: vi.fn(), duplicate: vi.fn(), remove: vi.fn(), page: vi.fn(), draw: vi.fn(),
};
}
describe('resolveCanvasActions', () => {
it('selects one capability adapter for the entire shared canvas interaction', () => {
const coordinate = actions();
const xfa = actions();
const active = resolveCanvasActions({
adapterKey: 'xfa_dataset', adapters: { coordinate_ocr: coordinate, xfa_dataset: xfa },
});
active.select('binding-1');
active.undo();
active.page(2);
expect(xfa.select).toHaveBeenCalledWith('binding-1');
expect(xfa.undo).toHaveBeenCalledOnce();
expect(xfa.page).toHaveBeenCalledWith(2);
expect(coordinate.select).not.toHaveBeenCalled();
});
it('selects one desk adapter before shared save and sample lifecycle work begins', () => {
const coordinate = { kind: 'coordinate', save: vi.fn() };
const xfa = { kind: 'xfa', save: vi.fn() };
const active = resolveDeskAdapter({
adapterKey: 'xfa_dataset', adapters: { coordinate_ocr: coordinate, xfa_dataset: xfa },
});
expect(active).toBe(xfa);
});
it('uses one editor-owned preview context without branching on the value adapter', () => {
expect(resolveSharedCanvasDocument({
documentId: 12,
mainTableId: '',
sampleTableId: 'table-1',
})).toEqual({ documentId: 12, tableId: 'table-1' });
expect(resolveSharedCanvasDocument({
documentId: 12,
mainTableId: 'visual-main-table',
sampleTableId: 'table-1',
})).toEqual({ documentId: 12, tableId: 'visual-main-table' });
});
it('keeps the shared save shell independent from XFA confirmation-token naming', async () => {
const saved = vi.fn().mockResolvedValue(true);
const adapter = {
hasUnsavedChanges: true,
skipUnchangedManualSave: true,
canSave: true,
canValidate: false,
exportDefinition: vi.fn(() => ({
template_mode: 'xfa_dataset',
source_contract: {},
header_mappings: [],
line_mapping: { fields: [] },
cross_checks: [],
main_table_id: 'table-1',
bindings: [],
})),
buildPayload: vi.fn(() => ({
definition: { template_mode: 'xfa_dataset' },
splitRuleConfirmationTokens: { path_1: 'token_1' },
})),
applySavedDraft: saved,
};
const payload = adapter.buildPayload();
expect(payload?.splitRuleConfirmationTokens).toEqual({ path_1: 'token_1' });
expect(adapter.exportDefinition()).toMatchObject({ template_mode: 'xfa_dataset' });
expect(adapter.canValidate).toBe(false);
await adapter.applySavedDraft({ id: 1 });
expect(saved).toHaveBeenCalledWith({ id: 1 });
});
it('resolves persisted format only at the adapter boundary', () => {
expect(resolveValueAdapterKey({ template_mode: 'xfa_dataset' } as any)).toBe('xfa_dataset');
expect(resolveValueAdapterKey({ template_mode: 'coordinate' } as any)).toBe('coordinate_ocr');
});
});
describe('resolveMainTableIdForPageChange', () => {
it('keeps the frozen main table when PDF navigation selects another table on the same page', () => {
expect(resolveMainTableIdForPageChange({
frozenMainTableId: 'order-lines-table',
pagePreviewTableId: 'total-amount-table',
})).toBe('order-lines-table');
});
});
@@ -0,0 +1,202 @@
/**
* features/admin/modules/shipping-order-document-profiles/canvasActions.utils.ts
* 用途:为订单模板共享 PDF 画布提供 capability-neutral 的操作接口。
* 依赖:OrderProfileEditorPage 的末端值源 adapter。
* 逻辑:页面按已持久化的模板能力选择一次 adapter;画布组件与工具栏只调用同一组动作。
*/
import type { OrderProfileCanvasRegion, OrderProfileRelativeRegion } from '@/features/admin/types/shipping-order-document-profile.types';
import type { OrderProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
import type { ShippingOrderDocumentProfile } from '@/features/admin/types/shipping-order-document-profile.types';
import type { OrderProfileRecognitionResult } from './orderProfileForm.utils';
/** 共享画布需要的最小动作面;底层可以持有不同 adapter 的持久化载体。 */
export interface OrderProfileCanvasActions {
create(region: OrderProfileRelativeRegion): void | Promise<void>;
select(id: string): void;
dragStart(id: string): void;
dragEnd(): void;
change(id: string, region: OrderProfileRelativeRegion): void;
undo(): void;
redo(): void;
duplicate(): void;
remove(): void;
page(pageNo: number): void;
draw(kind: OrderProfileCanvasRegion['kind']): void;
}
/**
* 计算删除画布区域后的区域集合。
* 普通区域只删除自身及其直接子区域;文档锚点仅在明确传入锚点 ID 时级联删除。
*/
export function filterRegionsAfterRemoval(
regions: OrderProfileCanvasRegion[],
removedId: string,
documentAnchorId: string | null = null,
): OrderProfileCanvasRegion[] {
return regions.filter((item) => (
item.id !== removedId
&& item.parentId !== removedId
&& (documentAnchorId === null || item.parentId !== documentAnchorId)
));
}
/**
* 返回当前明确选中的订单字段标签 ID。
* 核心逻辑:订单字段值框只能继承用户当前选中的标签,绝不回退到页面第一个标签。
* @param selectedRegion - 当前画布选区;非订单字段标签或未选中时返回 null。
* @returns 可作为订单字段父节点的标签 ID,或 null。
*/
export function resolveSelectedOrderAnchorId(
selectedRegion: Pick<OrderProfileCanvasRegion, 'id' | 'kind'> | null,
): string | null {
return selectedRegion?.kind === 'order_anchor' ? selectedRegion.id : null;
}
/**
* 保持模板主表身份与 PDF 页内预览表分离。
* 核心逻辑:翻页是画布导航,不能把同页第一张表(例如合计区)写回已冻结的主表身份。
*/
export function resolveMainTableIdForPageChange(options: {
frozenMainTableId: string;
pagePreviewTableId: string;
}): string {
return options.frozenMainTableId || options.pagePreviewTableId;
}
/**
* 判断 XFA 视觉回读为空时是否应保留用户刚圈选的值框。
* 核心逻辑:空回读是待诊断的视觉证据失败,不得吞掉管理员已经完成的 XFA 位置标注;
* 普通 PDF 仍维持原有的空文本拒绝规则。
*/
export function shouldKeepUnreadableOrderField(
adapterKey: string,
kind: OrderProfileCanvasRegion['kind'] | null,
hasVisualText: boolean,
): boolean {
return hasVisualText || (adapterKey === 'xfa_dataset' && kind === 'order_field');
}
/**
* 共享 Editor 消费的视觉画布状态。
*
* 取值 adapter 可以使用不同的持久化载体,但在
* 进入 Editor 后都必须投影为这一份视觉状态。这样 PDF 预览、工具栏和 DocumentCanvas
* 不再知道模板模式,更不能因此分出第二套交互生命周期。
*/
export interface OrderProfileVisualCanvasAdapter {
actions: OrderProfileCanvasActions;
documentReady: boolean;
preview: { document_id: number; preview_token: string; expires_in_seconds: number } | null;
grant: { page_no: number; preview_token: string } | null;
previewPagePath: string;
regions: OrderProfileCanvasRegion[];
selectedRegionId: string | null;
creationKind: OrderProfileCanvasRegion['kind'] | null;
pageNo: number;
pageCount: number;
saveDisabled: boolean;
autoSuggestDisabled: boolean;
emptyHint: string | null;
loadError: string | null;
undoDisabled: boolean;
redoDisabled: boolean;
duplicateDisabled: boolean;
deleteDisabled: boolean;
setRenderedPageCount(count: number): void;
hasSelection: boolean;
selectedKindLabel: string;
selectedGeometry: string;
activePageHasLines: boolean;
headerRecognitionResults: OrderProfileRecognitionResult[];
lineRecognitionResults: OrderProfileRecognitionResult[];
/** 共同画布状态与动作;错误语义由 adapter 投影,Editor 不再判断模板模式。 */
canvasReadonly: boolean;
warningVisible: boolean;
warningText: string | null;
retryCanvas(): void;
reportCanvasLoadFailed(): void;
applyAutomarkCandidates(candidates: Array<Record<string, unknown>>): boolean;
canRender: boolean;
retryLabel: string;
acceptSuggestion(): void;
rejectSuggestion(): void;
}
/**
* 共享草稿保存 adapter。
*
* Editor 统一负责租约、乐观锁、Revision 保存和失败恢复;adapter 只把当前视觉标注
* 转为其正式值源所需的 definition,并在服务端返回后消费该 adapter 的附加证据。
*/
export interface OrderProfileDraftSaveAdapter {
hasUnsavedChanges: boolean;
skipUnchangedManualSave: boolean;
canSave: boolean;
canValidate: boolean;
exportDefinition(): OrderProfileDefinition | null;
buildPayload(visualDefinition: OrderProfileDefinition): {
definition: OrderProfileDefinition;
splitRuleConfirmationTokens?: Record<string, string>;
allowFormalBindingDeletions?: string[];
} | null;
applySavedDraft(saved: unknown): Promise<boolean>;
}
/**
* 解析 Profile 的末端值源 capability key。
* 编辑器只消费这个 capability,不得直接依据 PDF/XFA 格式分叉流程。
*/
export function resolveValueAdapterKey(profile: ShippingOrderDocumentProfile | null): string {
return profile?.template_mode === 'xfa_dataset' ? 'xfa_dataset' : 'coordinate_ocr';
}
/**
* 返回当前 Profile 的唯一画布动作 adapter。
* 核心逻辑:选择只依据末端值源的 capability key;其后画布事件不再识别文件格式。
* @param options.adapterKey - 已持久化的末端值源 capability key。
* @param options.adapters - 各值源的画布状态 adapter。
* @returns 当前画布应使用的统一动作集合。
*/
export function resolveCanvasActions(options: {
adapterKey: string;
adapters: Record<string, OrderProfileCanvasActions>;
}): OrderProfileCanvasActions {
const adapter = options.adapters[options.adapterKey];
if (!adapter) throw new Error(`Unsupported order-profile value adapter: ${options.adapterKey}`);
return adapter;
}
/**
* 返回共享编辑器壳层当前唯一的值源 desk adapter。
* 核心逻辑:保存、样本上下文和自动标记 Job 由壳层统一编排;adapter 只生成
* payload 或应用取值专属结果,避免这些公共生命周期再次分为 XFA/PDF 两条路径。
*/
export function resolveDeskAdapter<T>(options: {
adapterKey: string;
adapters: Record<string, T>;
}): T {
const adapter = options.adapters[options.adapterKey];
if (!adapter) throw new Error(`Unsupported order-profile value adapter: ${options.adapterKey}`);
return adapter;
}
/**
* 返回唯一由 Editor 消费的 PDF 画布文档上下文。
* 核心逻辑:所有 Profile 先使用共同冻结的 annotation document + main_table_id;
* 历史草稿缺失 main_table_id 时才回退样本 table_id。预览授权、页码和 PDFium/PDF.js 渲染始终
* 由共享 Editor 持有,值源 adapter 不得参与上下文选择。
* @param options.documentId - 共同 annotation 文档身份。
* @param options.mainTableId - definition 中冻结的共同视觉主表。
* @param options.sampleTableId - 历史样本的兼容回退表身份。
* @returns 共享画布唯一使用的文档和表身份。
*/
export function resolveSharedCanvasDocument(options: {
documentId: number;
mainTableId: string;
sampleTableId: string;
}): { documentId: number; tableId: string } {
return {
documentId: options.documentId,
tableId: options.mainTableId || options.sampleTableId,
};
}
@@ -0,0 +1,426 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileAuditTimeline.vue
用途:展示订单模板版本中心的治理审计时间线(含 XFA operation_id / checksum)。
依赖:版本中心审计 API、版本详情 DTO、Vue I18n。
逻辑:使用 before_id 游标分页避免新增事件导致翻页重复;只展示安全 detail 摘要,
以及 XFA 变更前后 definition checksum 与 operation_id;不展示 PDF、正文或盲测真值;
对视觉绑定 / 拆分 / 统一迁移事件渲染分组标签与 visual before/after 摘要。
-->
<script setup lang="ts">
import { computed, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { BusinessError } from "@/shared/api/client";
import { listOrderDocumentProfileAuditEvents } from "@/features/admin/api/shipping-order-document-profile.api";
import type {
OrderProfileAuditEventPage,
ShippingOrderDocumentProfile,
} from "@/features/admin/types/shipping-order-document-profile.types";
const props = defineProps<{ detail: ShippingOrderDocumentProfile }>();
const { t } = useI18n();
const loading = ref(false);
const errorMessage = ref("");
const page = ref<OrderProfileAuditEventPage | null>(null);
const cursorStack = ref<Array<number | null>>([]);
const activeBeforeId = ref<number | null>(null);
const filters = reactive({
eventType: "",
actor: "",
requestIdFilter: "",
createdFrom: "",
createdTo: "",
});
const VISUAL_EVENT_PREFIXES = ["xfa_split_", "order_profile_unified_migration_"];
/**
* 判断是否为统一视觉 / 拆分 / 迁移审计事件。
*/
function isUnifiedVisualOrSplitEvent(eventType: string): boolean {
const value = String(eventType || "");
return VISUAL_EVENT_PREFIXES.some((prefix) => value.startsWith(prefix));
}
/**
* 从 detail 提取视觉 before/after 摘要(若存在)。
*/
function visualPayload(detail: Record<string, unknown> | null | undefined): {
before: unknown;
after: unknown;
} | null {
if (!detail || typeof detail !== "object") return null;
const before = detail.before_visual_binding ?? detail.before;
const after = detail.after_visual_binding ?? detail.after;
if (before == null && after == null) return null;
return { before, after };
}
const formatTime = (value?: string | null) => value ? new Date(value).toLocaleString() : "-";
const formatJson = (value: unknown) => {
try {
return JSON.stringify(value ?? {}, null, 2);
} catch {
return String(value ?? "");
}
};
const hasPrevious = computed(() => cursorStack.value.length > 0);
const hasNext = computed(() => Boolean(page.value?.page.has_more && page.value?.page.next_before_id));
const loadErrorMessage = (error: unknown) => {
if (error instanceof BusinessError && [502, 503, 504].includes(error.status || 0)) {
return t("admin.shippingOrderProfiles.versionCenter.serviceUnavailable");
}
return error instanceof BusinessError
? error.message
: t("admin.shippingOrderProfiles.versionCenter.audit.loadFailed");
};
const load = async () => {
loading.value = true;
errorMessage.value = "";
try {
page.value = await listOrderDocumentProfileAuditEvents(props.detail.id, {
eventType: filters.eventType.trim() || undefined,
actor: filters.actor.trim() || undefined,
requestIdFilter: filters.requestIdFilter.trim() || undefined,
createdFrom: filters.createdFrom || undefined,
createdTo: filters.createdTo || undefined,
beforeId: activeBeforeId.value,
limit: 20,
});
} catch (error) {
page.value = null;
errorMessage.value = loadErrorMessage(error);
} finally {
loading.value = false;
}
};
const applyFilters = async () => {
activeBeforeId.value = null;
cursorStack.value = [];
await load();
};
const resetFilters = async () => {
filters.eventType = "";
filters.actor = "";
filters.requestIdFilter = "";
filters.createdFrom = "";
filters.createdTo = "";
await applyFilters();
};
const loadNext = async () => {
if (!page.value?.page.next_before_id) return;
cursorStack.value.push(activeBeforeId.value);
activeBeforeId.value = page.value.page.next_before_id;
await load();
};
const loadPrevious = async () => {
if (!cursorStack.value.length) return;
activeBeforeId.value = cursorStack.value.pop() ?? null;
await load();
};
watch(
() => props.detail.id,
() => {
activeBeforeId.value = null;
cursorStack.value = [];
void load();
},
{ immediate: true },
);
</script>
<template>
<section class="timeline-panel">
<div class="toolbar">
<div>
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.audit.title") }}</h3>
<p>{{ t("admin.shippingOrderProfiles.versionCenter.audit.subtitle") }}</p>
</div>
<div class="toolbar-actions">
<button type="button" class="btn-ghost btn-sm" :disabled="loading" @click="resetFilters">
{{ t("admin.shippingOrderProfiles.versionCenter.audit.reset") }}
</button>
<button type="button" class="btn-primary btn-sm" :disabled="loading" @click="applyFilters">
{{ t("admin.shippingOrderProfiles.versionCenter.audit.apply") }}
</button>
</div>
</div>
<div class="filters">
<label>
<span>{{ t("admin.shippingOrderProfiles.versionCenter.audit.eventType") }}</span>
<input v-model="filters.eventType" class="input-field" type="text" />
</label>
<label>
<span>{{ t("admin.shippingOrderProfiles.versionCenter.audit.actor") }}</span>
<input v-model="filters.actor" class="input-field" type="text" />
</label>
<label>
<span>{{ t("admin.shippingOrderProfiles.versionCenter.audit.requestId") }}</span>
<input v-model="filters.requestIdFilter" class="input-field" type="text" />
</label>
<label>
<span>{{ t("admin.shippingOrderProfiles.versionCenter.audit.createdFrom") }}</span>
<input v-model="filters.createdFrom" class="input-field" type="date" />
</label>
<label>
<span>{{ t("admin.shippingOrderProfiles.versionCenter.audit.createdTo") }}</span>
<input v-model="filters.createdTo" class="input-field" type="date" />
</label>
</div>
<div v-if="loading" class="state-card">
{{ t("admin.shippingOrderProfiles.versionCenter.audit.loading") }}
</div>
<div v-else-if="errorMessage" class="state-card error-card">
<p>{{ errorMessage }}</p>
<button type="button" class="btn-secondary btn-sm" @click="load">
{{ t("admin.shippingOrderProfiles.versionCenter.retry") }}
</button>
</div>
<div v-else-if="!page?.items.length" class="state-card">
{{ t("admin.shippingOrderProfiles.versionCenter.audit.empty") }}
</div>
<div v-else class="timeline-list">
<article
v-for="item in page.items"
:key="item.id"
class="timeline-item"
>
<header>
<div>
<p class="timeline-type">
{{ item.event_type }}
<span
v-if="isUnifiedVisualOrSplitEvent(item.event_type)"
class="event-tag"
data-testid="order-profile-audit-visual-tag"
>visual/split</span>
</p>
<h4>{{ item.actor.display_name }}</h4>
</div>
<div class="meta">
<span>{{ formatTime(item.created_at) }}</span>
<code v-if="item.request_id">{{ item.request_id }}</code>
<code
v-if="item.operation_id"
data-testid="order-profile-audit-operation-id"
>{{ item.operation_id }}</code>
</div>
</header>
<dl
v-if="item.definition_checksum || item.before_definition_checksum"
class="checksum-row"
data-testid="order-profile-audit-checksums"
>
<div v-if="item.before_definition_checksum">
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.audit.beforeChecksum") }}</dt>
<dd><code>{{ item.before_definition_checksum }}</code></dd>
</div>
<div v-if="item.definition_checksum">
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.audit.afterChecksum") }}</dt>
<dd><code>{{ item.definition_checksum }}</code></dd>
</div>
</dl>
<div
v-if="visualPayload(item.detail as Record<string, unknown>)"
class="visual-diff"
data-testid="order-profile-audit-visual-diff"
>
<p class="visual-diff-title">{{ t("admin.shippingOrderProfiles.versionCenter.audit.visualDiff") }}</p>
<pre>{{ formatJson(visualPayload(item.detail as Record<string, unknown>)) }}</pre>
</div>
<pre>{{ formatJson(item.detail) }}</pre>
</article>
</div>
<div class="pager">
<button type="button" class="btn-ghost btn-sm" :disabled="loading || !hasPrevious" @click="loadPrevious">
{{ t("admin.shippingOrderProfiles.versionCenter.audit.previous") }}
</button>
<button type="button" class="btn-ghost btn-sm" :disabled="loading || !hasNext" @click="loadNext">
{{ t("admin.shippingOrderProfiles.versionCenter.audit.next") }}
</button>
</div>
</section>
</template>
<style scoped>
.timeline-panel,
.toolbar,
.filters,
.timeline-item,
.state-card {
border: 1px solid var(--border-default);
border-radius: 1rem;
background: var(--bg-surface);
}
.timeline-panel {
display: grid;
gap: 0.9rem;
}
.toolbar,
.filters,
.state-card,
.timeline-item {
padding: 0.95rem 1rem;
}
.toolbar {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
}
.toolbar h3,
.timeline-item h4 {
margin: 0;
color: var(--text-primary);
}
.toolbar p {
margin: 0.25rem 0 0;
color: var(--text-muted);
font-size: 0.75rem;
}
.timeline-type {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.4rem;
margin: 0.25rem 0 0;
color: var(--text-muted);
font-size: 0.75rem;
}
.event-tag {
display: inline-flex;
border: 1px solid var(--border-default);
border-radius: 999px;
padding: 0.05rem 0.45rem;
font-size: 0.65rem;
color: var(--text-secondary);
}
.visual-diff {
margin-top: 0.65rem;
padding: 0.65rem 0.75rem;
border: 1px dashed var(--border-default);
border-radius: 0.75rem;
}
.visual-diff-title {
margin: 0 0 0.35rem;
font-size: 0.75rem;
color: var(--text-secondary);
}
.toolbar-actions,
.pager {
display: flex;
gap: 0.6rem;
}
.filters {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 0.75rem;
}
.filters label {
display: grid;
gap: 0.3rem;
color: var(--text-secondary);
font-size: 0.75rem;
}
.filters .input-field {
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
}
.timeline-list {
display: grid;
gap: 0.8rem;
}
.timeline-item header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
}
.checksum-row {
display: grid;
gap: 0.35rem;
margin: 0.5rem 0;
font-size: 0.75rem;
}
.checksum-row dt {
color: var(--text-muted);
}
.checksum-row dd {
margin: 0;
}
.checksum-row code {
font-size: 0.7rem;
word-break: break-all;
}
.meta {
display: grid;
justify-items: end;
gap: 0.25rem;
color: var(--text-muted);
font-size: 0.75rem;
}
.timeline-item pre {
margin: 0.85rem 0 0;
border-radius: 0.75rem;
background: var(--bg-surface-strong);
padding: 0.8rem;
color: var(--text-primary);
font-size: 0.72rem;
line-height: 1.45;
overflow: auto;
white-space: pre-wrap;
}
.error-card {
color: var(--status-error-fg);
}
@media (max-width: 1100px) {
.filters {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 720px) {
.toolbar,
.timeline-item header {
display: grid;
}
.filters {
grid-template-columns: 1fr;
}
}
</style>
@@ -0,0 +1,277 @@
/**
* 用途:验证 XFA 受控原 PDF 预览使用 PDF.js 普通页面外观渲染。
* 依赖:Vitest、Vue Test Utils、OrderProfileDocumentCanvas。
* 逻辑:hybrid XFA 的 getXfa() 可为空;预览必须走 page.render(),保留实际页面外观流。
*/
import { flushPromises, mount } from '@vue/test-utils';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createI18n } from 'vue-i18n';
import OrderProfileDocumentCanvas from './OrderProfileDocumentCanvas.vue';
const { getDocumentMock, getPageMock, renderMock } = vi.hoisted(() => ({
getDocumentMock: vi.fn(),
getPageMock: vi.fn(),
renderMock: vi.fn(),
}));
vi.mock('pdfjs-dist', () => ({
GlobalWorkerOptions: {},
getDocument: (...args: unknown[]) => getDocumentMock(...args),
}));
vi.mock('pdfjs-dist/build/pdf.worker.min.mjs?url', () => ({ default: '/pdf.worker.min.mjs' }));
vi.mock('@/shared/utils/auth', () => ({ getAuthHeaders: () => ({ Authorization: 'Bearer test' }) }));
describe('OrderProfileDocumentCanvas PDF preview', () => {
beforeEach(() => {
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({} as CanvasRenderingContext2D);
renderMock.mockReset();
renderMock.mockReturnValue({ promise: Promise.resolve() });
getPageMock.mockReset();
getPageMock.mockResolvedValue({
getViewport: vi.fn(({ scale }: { scale: number }) => ({ width: 600 * scale, height: 800 * scale })),
render: renderMock,
getXfa: vi.fn(async () => null),
});
getDocumentMock.mockReset();
getDocumentMock.mockReturnValue({ promise: Promise.resolve({ numPages: 2, getPage: getPageMock }) });
vi.stubGlobal('fetch', vi.fn(async () => new Response(new Uint8Array([37, 80, 68, 70]), { status: 200 })));
});
it('renders hybrid XFA through the ordinary page appearance when getXfa is empty', async () => {
const wrapper = mount(OrderProfileDocumentCanvas, {
props: {
profileId: 71,
pdfPreview: { preview_token: 'single-use-token' },
regions: [], pageNo: 1, pageCount: 1,
},
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] },
});
await flushPromises();
await flushPromises();
// 关键断言:hybrid XFA 不依赖 getXfa/XfaLayer,使用页面外观流渲染动态可见值。
expect(getDocumentMock).toHaveBeenCalledWith(expect.objectContaining({ data: expect.any(Uint8Array) }));
expect(getPageMock).toHaveBeenCalledWith(1);
expect(renderMock).toHaveBeenCalledWith(expect.objectContaining({ canvasContext: expect.anything() }));
expect(wrapper.find('canvas.pdf-page').exists()).toBe(true);
expect(wrapper.emitted('pageCount')?.[0]).toEqual([2]);
});
it('keeps XFA suggestion regions on the same scaled coordinate plane as the PDF page', async () => {
const wrapper = mount(OrderProfileDocumentCanvas, {
props: {
profileId: 71,
pdfPreview: { preview_token: 'single-use-token' },
regions: [{
id: 'automark:sugg-1', kind: 'order_field', label: '自动标注', pageNo: 1,
region: { x0: .5, y0: .5, x1: .75, y1: .75 },
}],
pageNo: 1,
pageCount: 1,
},
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] },
});
await flushPromises();
await flushPromises();
await wrapper.findAll('.zoom-control button')[1].trigger('click');
await flushPromises();
await flushPromises();
// PDF.js 的 viewport 已是 125%(750px);覆盖框必须以同一宽度百分比定位,不能二次放大到 937.5px。
expect(wrapper.find('.canvas-stage').attributes('style')).toContain('width: 750px');
expect(wrapper.find('.region').attributes('style')).toContain('left: 50%');
});
it('uses the server-rendered PNG page for an ordinary PDF instead of PDF.js', async () => {
const wrapper = mount(OrderProfileDocumentCanvas, {
props: {
profileId: 71,
grant: { page_no: 1, preview_token: 'page-token' },
previewPagePath: '/api/admin/shipping-notice/order-document-profiles/71/preview-pages',
regions: [], pageNo: 1, pageCount: 1,
},
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] },
});
await flushPromises();
// 普通 PDF 底图由后端 PDFium 输出,避免前端 PDF.js 对特定繁体内嵌字体的渲染差异。
expect(getDocumentMock).not.toHaveBeenCalled();
expect(wrapper.find('img').exists()).toBe(true);
expect(fetch).toHaveBeenCalledWith(
'/api/admin/shipping-notice/order-document-profiles/71/preview-pages/1?preview_token=page-token',
expect.objectContaining({ cache: 'no-store' }),
);
});
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('ignores wheel zoom while a vertical resize drag is active', async () => {
const shortAnchor = {
id: 'order_field_1_1_anchor',
kind: 'order_anchor' as const,
label: 'Number',
pageNo: 1,
region: { x0: .78, y0: .12, x1: .84, y1: .158 },
};
const wrapper = mount(OrderProfileDocumentCanvas, {
props: {
profileId: 8,
grant: { page_no: 1, preview_token: 'page-token' },
previewPagePath: '/api/admin/shipping-notice/order-document-profiles/8/preview-pages',
regions: [shortAnchor],
selectedRegionId: shortAnchor.id,
pageNo: 1,
pageCount: 1,
},
global: {
plugins: [createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
admin: { shippingOrderProfiles: { workbench: { pagePreviewAlt: 'page', resizeHandle: '{direction}' } } },
},
},
})],
},
});
await flushPromises();
const stage = wrapper.find('.canvas-stage').element as HTMLElement;
Object.defineProperty(stage, 'getBoundingClientRect', {
value: () => ({ left: 0, top: 0, width: 1000, height: 1000, right: 1000, bottom: 1000, x: 0, y: 0, toJSON: () => ({}) }),
});
const southEdge = wrapper.find('.resize-edge-s');
southEdge.element.dispatchEvent(new PointerEvent('pointerdown', {
bubbles: true, cancelable: true, clientX: 810, clientY: 158, pointerId: 1,
}));
// 拖高过程中触控板滚轮不得改缩放,否则纵向手势表现为“高度拉不动”。
const beforeZoom = wrapper.find('.zoom-control output').text();
await wrapper.find('.canvas-viewport').trigger('wheel', { deltaY: -120 });
expect(wrapper.find('.zoom-control output').text()).toBe(beforeZoom);
window.dispatchEvent(new PointerEvent('pointermove', { clientX: 810, clientY: 240 }));
window.dispatchEvent(new PointerEvent('pointerup', { clientX: 810, clientY: 240 }));
await flushPromises();
const change = wrapper.emitted('change')?.at(-1);
expect((change?.[1] as { y1: number }).y1).toBeGreaterThan(shortAnchor.region.y1);
expect(wrapper.find('.region').attributes('style')).toContain('bottom:');
});
it('allows shrinking label height below the legacy 0.01 floor', async () => {
const tallAnchor = {
id: 'order_field_1_2_anchor',
kind: 'order_anchor' as const,
label: 'Number',
pageNo: 1,
region: { x0: .70, y0: .035, x1: .85, y1: .055 },
};
const wrapper = mount(OrderProfileDocumentCanvas, {
props: {
profileId: 8,
grant: { page_no: 1, preview_token: 'page-token' },
previewPagePath: '/api/admin/shipping-notice/order-document-profiles/8/preview-pages',
regions: [tallAnchor],
selectedRegionId: tallAnchor.id,
pageNo: 1,
pageCount: 1,
},
global: {
plugins: [createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
admin: { shippingOrderProfiles: { workbench: { pagePreviewAlt: 'page', resizeHandle: '{direction}' } } },
},
},
})],
},
});
await flushPromises();
const stage = wrapper.find('.canvas-stage').element as HTMLElement;
Object.defineProperty(stage, 'getBoundingClientRect', {
value: () => ({ left: 0, top: 0, width: 1000, height: 1000, right: 1000, bottom: 1000, x: 0, y: 0, toJSON: () => ({}) }),
});
// 从下边向上拖,目标高度约 0.006(低于旧下限 0.01,高于新下限 0.002)。
wrapper.find('.resize-edge-s').element.dispatchEvent(new PointerEvent('pointerdown', {
bubbles: true, cancelable: true, clientX: 775, clientY: 55, pointerId: 1,
}));
window.dispatchEvent(new PointerEvent('pointermove', { clientX: 775, clientY: 41 }));
window.dispatchEvent(new PointerEvent('pointerup', { clientX: 775, clientY: 41 }));
await flushPromises();
const next = wrapper.emitted('change')?.at(-1)?.[1] as { y0: number; y1: number };
// 关键断言:单行标签可缩到 <0.01;旧硬编码 .01 会把 y1 卡在 y0+0.01。
expect(next.y1 - next.y0).toBeLessThan(0.01);
expect(next.y1 - next.y0).toBeGreaterThanOrEqual(0.002);
});
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');
const nativeCreateElement = document.createElement.bind(document);
vi.spyOn(document, 'createElement').mockImplementation((tagName: string) => {
const element = nativeCreateElement(tagName) as HTMLCanvasElement;
if (tagName === 'canvas') {
Object.defineProperty(element, 'getContext', { value: vi.fn(() => ({ drawImage })) });
Object.defineProperty(element, 'toDataURL', { value: toDataURL });
}
return element;
});
const wrapper = mount(OrderProfileDocumentCanvas, {
props: { profileId: 71, pdfPreview: { preview_token: 'single-use-token' }, regions: [], pageNo: 1, pageCount: 1 },
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] },
});
await flushPromises();
await flushPromises();
const source = wrapper.find('canvas.pdf-page').element as HTMLCanvasElement;
Object.defineProperties(source, { width: { value: 600 }, height: { value: 800 } });
expect((wrapper.vm as { captureRegion: (region: object) => string | null }).captureRegion({ x0: .1, y0: .2, x1: .4, y1: .5 }))
.toBe('data:image/png;base64,canvas-crop');
// 使用 PDF.js 原始像素而不是 CSS 缩放后的大小,保证回读与用户框选区域一致。
expect(drawImage).toHaveBeenCalledWith(source, 60, 160, 181, 240, 0, 0, 181, 240);
});
});
@@ -0,0 +1,743 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue
用途:展示受控 PDF/XFA flatten 单页预览,并以相对坐标框支持选择、拖动和缩放区域。
依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion、isUnboundOrderFieldCanvasRegion。
逻辑:父级签发单页令牌并提供分页动作;mode=readonly 时只允许查看/缩放/切页,不允许写入任何标注改动;
PNG 预览 token 为一次性消费,组件内按页缓存 blob,翻页回访不再重新拉 token;
未绑定订单字段框强制高亮(region--unbound),并暴露 scrollRegionIntoView 供横幅定位删除;
选中框用 top/right/bottom/left 定位(避免 height% 在内容撑高容器上失效);
拖拽/缩放进行中忽略滚轮缩放,避免触控板纵向手势把高度调整抢走;
绘制模式下仍允许操作当前选中框;整边 resize 热区便于矮标签拉高;
画布区域 aria-label 走四语言 i18n;可选 emptyHint/loadError 区分 XFA page_unavailable 与 PDF 缺样本空态。
-->
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Anchor, ArrowLeft, ArrowRight, Columns3, Copy, Eraser, MessageSquareText, Minus, Plus, Redo2, RotateCcw, Rows3, Save, TableProperties, Tag, TextCursorInput, Trash2, WandSparkles } from 'lucide-vue-next';
import { getAuthHeaders } from '@/shared/utils/auth';
import type { OrderProfileCanvasRegion, OrderProfilePreviewPageGrant } from '@/features/admin/types/shipping-order-document-profile.types';
import { isUnboundOrderFieldCanvasRegion } from '../orderProfileForm.utils';
import type { PDFDocumentProxy } from 'pdfjs-dist';
type PdfJsModule = typeof import('pdfjs-dist');
let pdfjsLoader: Promise<PdfJsModule> | null = null;
/** 动态加载 PDF.js 与 worker;坐标 PDF 与 XFA 在受控管理员画布按需共用。 */
async function loadPdfJs(): Promise<PdfJsModule> {
if (!pdfjsLoader) {
pdfjsLoader = (async () => {
const [pdfjs, workerMod] = await Promise.all([
import('pdfjs-dist'),
import('pdfjs-dist/build/pdf.worker.min.mjs?url'),
]);
pdfjs.GlobalWorkerOptions.workerSrc = workerMod.default;
return pdfjs;
})();
}
return pdfjsLoader;
}
const props = defineProps<{
profileId: number | null;
grant?: OrderProfilePreviewPageGrant | null;
mode?: 'edit' | 'readonly';
previewPagePath?: string | null;
/** 原 PDF 令牌;启用后用 PDF.js 页面外观流渲染,绝不生成可下载 URL。 */
pdfPreview?: { preview_token: string } | null;
regions: OrderProfileCanvasRegion[];
selectedRegionId?: string | null;
creationKind?: OrderProfileCanvasRegion['kind'] | null;
autoSuggestDisabled?: boolean;
suggesting?: boolean;
suggestionProgress?: string;
undoDisabled?: boolean;
redoDisabled?: boolean;
duplicateDisabled?: boolean;
deleteDisabled?: boolean;
pageNo: number;
pageCount: number;
saveDisabled?: boolean;
saving?: boolean;
pendingSuggestionCount?: number;
orderFieldValues?: Record<string, string | null>;
orderFieldValueState?: 'idle' | 'loading' | 'ready' | 'failed';
/** 当前样本坐标重建的首条明细行值,按画布字段区域 ID 索引。 */
lineFieldValues?: Record<string, string | null>;
/** 无图时空态文案;缺省为「选择已绑定的 PDF 样本」。 */
emptyHint?: string | null;
/** 外部注入的页加载错误(如 XFA page_unavailable);优先于空态提示。 */
loadError?: string | null;
}>();
const { t } = useI18n();
const readonlyMode = computed(() => props.mode === 'readonly');
const emit = defineEmits<{
select: [regionId: string];
start: [regionId: string];
end: [];
change: [regionId: string, region: OrderProfileCanvasRegion['region']];
create: [region: OrderProfileCanvasRegion['region']];
draw: [kind: OrderProfileCanvasRegion['kind']];
suggest: [];
undo: [];
redo: [];
duplicate: [];
delete: [];
save: [];
page: [pageNo: number];
pageCount: [count: number];
acceptSuggestion: [];
rejectSuggestion: [];
/** 页图拉取失败(父级可标 page_unavailable)。 */
loadFailed: [];
/** 用户点击重试(父级决定重拉 grant 或 flatten)。 */
retry: [];
}>();
const imageUrl = ref('');
const pdfCanvas = ref<HTMLCanvasElement | null>(null);
const pdfRendered = ref(false);
const pdfPageSize = ref<{ width: number; height: number } | null>(null);
let pdfDocument: PDFDocumentProxy | null = null;
const loading = ref(false);
/** 本组件内 fetch 失败文案;与 props.loadError 合并展示。 */
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';
type DragMode = 'move' | ResizeHandle;
let activeDrag: { id: string; mode: DragMode; startX: number; startY: number; region: OrderProfileCanvasRegion['region'] } | null = null;
let activePan: { startX: number; startY: number; scrollLeft: number; scrollTop: number } | null = null;
let creationStart: { x: number; y: number } | null = null;
const creationRegion = ref<OrderProfileCanvasRegion['region'] | null>(null);
const displayLoadError = computed(() => props.loadError || internalLoadError.value || null);
const emptyStateText = computed(() => (
props.emptyHint || t('admin.shippingOrderProfiles.workbench.selectBoundPdf')
));
/**
* 将内存中的原 PDF 按真实页面外观流绘制到 Canvas。
* 核心逻辑:坐标 PDF 与 hybrid XFA 都用 page.render(),不生成可下载 URL。
*/
const renderPdfPage = async (pdf: PDFDocumentProxy) => {
await nextTick();
const targetPage = Math.min(Math.max(props.pageNo, 1), pdf.numPages);
const page = await pdf.getPage(targetPage);
const canvas = pdfCanvas.value;
const context = canvas?.getContext('2d');
if (!canvas || !context) throw new Error('PDF canvas is unavailable');
const viewport = page.getViewport({ scale: zoom.value });
pdfPageSize.value = { width: viewport.width, height: viewport.height };
canvas.width = Math.ceil(viewport.width);
canvas.height = Math.ceil(viewport.height);
await page.render({ canvas, canvasContext: context, viewport }).promise;
pdfRendered.value = true;
};
/**
* 回收某次会话内全部页图 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 () => {
const generation = ++loadGeneration;
if (cachedProfileId !== props.profileId) {
clearPageImageCache();
cachedProfileId = props.profileId;
}
if (!props.profileId || (!props.grant && !props.pdfPreview)) {
imageUrl.value = '';
pdfRendered.value = false;
internalLoadError.value = null;
return;
}
loading.value = true;
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' },
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
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 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 {
if (generation === loadGeneration) loading.value = false;
}
};
/**
* 用户点击画布重试:清除内部错误并通知父级重新签发页令牌。
*/
const onRetryClick = () => {
internalLoadError.value = null;
clearPageImageCache();
emit('retry');
};
/**
* 画布框最小边长(相对页坐标)。
* 旧值 0.01(页高 1%)对单行标签过粗,例如 Number 框会被卡在高度差 ≥0.01;
* 0.002 仍保证正面积,又能贴紧字形。
*/
const MIN_REGION_SPAN = 0.002;
/**
* 判断缩放手柄是否包含指定轴向。
* 核心逻辑:用显式枚举替代 `includes('n')`,避免手柄命名变更时误匹配。
*/
const resizeAffects = (handle: ResizeHandle, axis: 'n' | 'e' | 's' | 'w'): boolean => {
if (axis === 'n') return handle === 'n' || handle === 'ne' || handle === 'nw';
if (axis === 's') return handle === 's' || handle === 'se' || handle === 'sw';
if (axis === 'e') return handle === 'e' || handle === 'ne' || handle === 'se';
return handle === 'w' || handle === 'nw' || handle === 'sw';
};
/** 将指针移动映射为相对坐标;readonly 模式只保留选中,不允许几何变化。 */
const move = (event: PointerEvent) => {
if (!activeDrag || !canvas.value || readonlyMode.value) return;
const bounds = canvas.value.getBoundingClientRect();
if (bounds.width < 1 || bounds.height < 1) return;
const dx = (event.clientX - activeDrag.startX) / bounds.width;
const dy = (event.clientY - activeDrag.startY) / bounds.height;
if (activeDrag.mode !== 'move') {
const handle = activeDrag.mode;
const prior = activeDrag.region;
const next = {
x0: resizeAffects(handle, 'w') ? Math.max(0, Math.min(prior.x1 - MIN_REGION_SPAN, prior.x0 + dx)) : prior.x0,
y0: resizeAffects(handle, 'n') ? Math.max(0, Math.min(prior.y1 - MIN_REGION_SPAN, prior.y0 + dy)) : prior.y0,
x1: resizeAffects(handle, 'e') ? Math.max(prior.x0 + MIN_REGION_SPAN, Math.min(1, prior.x1 + dx)) : prior.x1,
y1: resizeAffects(handle, 's') ? Math.max(prior.y0 + MIN_REGION_SPAN, Math.min(1, prior.y1 + dy)) : prior.y1,
};
emit('change', activeDrag.id, next);
return;
}
const width = activeDrag.region.x1 - activeDrag.region.x0;
const height = activeDrag.region.y1 - activeDrag.region.y0;
const x0 = Math.max(0, Math.min(1 - width, activeDrag.region.x0 + dx));
const y0 = Math.max(0, Math.min(1 - height, activeDrag.region.y0 + dy));
emit('change', activeDrag.id, { x0, y0, x1: x0 + width, y1: y0 + height });
};
/** 为单次鼠标手势建立一个撤销边界;readonly 模式仅允许选中区域。 */
const beginDrag = (event: PointerEvent, region: OrderProfileCanvasRegion, mode: DragMode) => {
event.preventDefault();
emit('select', region.id);
if (readonlyMode.value || region.isPreview) return;
emit('start', region.id);
activeDrag = { id: region.id, mode, startX: event.clientX, startY: event.clientY, region: { ...region.region } };
window.addEventListener('pointermove', move);
window.addEventListener('pointerup', endMove, { once: true });
window.addEventListener('pointercancel', endMove, { once: true });
};
/** 结束一次区域移动并停止全局事件监听。 */
const endMove = () => {
activeDrag = null;
emit('end');
window.removeEventListener('pointermove', move);
window.removeEventListener('pointercancel', endMove);
};
/** 未处于绘制模式时以左键拖动画布视口,避免依赖横纵滚动条定位放大页面。 */
const beginPan = (event: PointerEvent) => {
if ((props.creationKind && !readonlyMode.value) || !viewport.value || event.button !== 0) return;
event.preventDefault();
activePan = { startX: event.clientX, startY: event.clientY, scrollLeft: viewport.value.scrollLeft, scrollTop: viewport.value.scrollTop };
window.addEventListener('pointermove', pan);
window.addEventListener('pointerup', endPan, { once: true });
};
const pan = (event: PointerEvent) => {
if (!activePan || !viewport.value) return;
viewport.value.scrollLeft = activePan.scrollLeft - (event.clientX - activePan.startX);
viewport.value.scrollTop = activePan.scrollTop - (event.clientY - activePan.startY);
};
const endPan = () => { activePan = null; window.removeEventListener('pointermove', pan); };
/** 在启用绘制模式时,把指针位置转换为受约束的相对区域并交由父级创建。 */
const beginCreation = (event: PointerEvent) => {
if (readonlyMode.value || !props.creationKind || !canvas.value) { beginPan(event); return; }
const bounds = canvas.value.getBoundingClientRect();
const x = Math.max(0, Math.min(1, (event.clientX - bounds.left) / bounds.width));
const y = Math.max(0, Math.min(1, (event.clientY - bounds.top) / bounds.height));
creationStart = { x, y };
creationRegion.value = { x0: x, y0: y, x1: x, y1: y };
window.addEventListener('pointermove', updateCreation);
window.addEventListener('pointerup', endCreation, { once: true });
};
const updateCreation = (event: PointerEvent) => {
if (!creationStart || !canvas.value) return;
const bounds = canvas.value.getBoundingClientRect();
const x = Math.max(0, Math.min(1, (event.clientX - bounds.left) / bounds.width));
const y = Math.max(0, Math.min(1, (event.clientY - bounds.top) / bounds.height));
creationRegion.value = { x0: Math.min(creationStart.x, x), y0: Math.min(creationStart.y, y), x1: Math.max(creationStart.x, x), y1: Math.max(creationStart.y, y) };
};
const endCreation = () => {
const region = creationRegion.value;
if (region && region.x1 - region.x0 >= MIN_REGION_SPAN && region.y1 - region.y0 >= MIN_REGION_SPAN) emit('create', region);
creationStart = null;
creationRegion.value = null;
window.removeEventListener('pointermove', updateCreation);
};
const selected = computed(() => new Set([props.selectedRegionId]));
/** 在画布徽标展示字段身份和实际识别值;编辑态订单字段继续使用工作台即时读取状态。 */
const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
if (readonlyMode.value && !['line', 'exclusion'].includes(region.kind)) {
return `${region.label} · ${region.recognizedValue || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable')}`;
}
if (region.kind !== 'order_field') {
if (region.kind === 'field') {
return `${region.label} · ${props.lineFieldValues?.[region.id] || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable')}`;
}
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'
? t('admin.shippingOrderProfiles.workbench.orderFieldValueReading')
: state === 'failed'
? t('admin.shippingOrderProfiles.workbench.orderFieldValueFailed')
// 新圈选的 XFA 值框先显示同次受控视觉回读;整页 PDFium/OCR 预览完成后再覆盖。
: value || region.suggestedValue || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable');
return `${region.label} · ${suffix}`;
};
/** 以固定步进调整页面倍率;区域采用相对坐标,缩放后仍与图像精确对齐。 */
const adjustZoom = (delta: number) => { zoom.value = Math.max(.5, Math.min(4, Math.round((zoom.value + delta) * 100) / 100)); };
/** 恢复适合工作台宽度的默认倍率,便于快速定位整页。 */
const resetZoom = () => { zoom.value = 1; };
/** 在画布上滚动时缩放页面;拖拽/绘制进行中忽略,避免触控板纵向手势抢走高度调整。 */
const handleWheel = (event: WheelEvent) => {
if (activeDrag || activePan || creationStart) return;
adjustZoom(event.deltaY < 0 ? .1 : -.1);
};
/** 校验页码输入并请求父工作台切页;超出范围时吸附到最近有效页。 */
const goToPage = () => {
const nextPage = Math.max(1, Math.min(props.pageCount || 1, Math.round(Number(pageInput.value) || props.pageNo)));
pageInput.value = nextPage;
if (nextPage !== props.pageNo) emit('page', nextPage);
};
/** 导出当前 PDF.js 画布中框选区域的 PNG;XFA 外观值可能只存在于浏览器渲染结果。 */
const captureRegion = (region: OrderProfileCanvasRegion['region']): string | null => {
const source = pdfCanvas.value;
if (!source || source.width < 1 || source.height < 1) return null;
const x = Math.max(0, Math.floor(region.x0 * source.width));
const y = Math.max(0, Math.floor(region.y0 * source.height));
const width = Math.max(1, Math.ceil((region.x1 - region.x0) * source.width));
const height = Math.max(1, Math.ceil((region.y1 - region.y0) * source.height));
const clippedWidth = Math.min(width, source.width - x);
const clippedHeight = Math.min(height, source.height - y);
if (clippedWidth < 1 || clippedHeight < 1) return null;
const crop = document.createElement('canvas');
crop.width = clippedWidth;
crop.height = clippedHeight;
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,
/**
* 将指定区域滚入画布视口中央,供未绑定框定位删除。
* @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);
});
watch(zoom, async () => {
if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument);
});
onBeforeUnmount(() => {
endMove();
endPan();
endCreation();
clearPageImageCache();
imageUrl.value = '';
});
</script>
<template>
<section
class="canvas-shell"
:aria-label="readonlyMode
? t('admin.shippingOrderProfiles.workbench.readonlyCanvasAriaLabel')
: t('admin.shippingOrderProfiles.workbench.annotationCanvasAriaLabel')"
>
<header v-if="imageUrl || pdfRendered" class="canvas-toolbar">
<div class="toolbar-actions">
<template v-if="!readonlyMode">
<button type="button" :disabled="undoDisabled" :title="t('admin.shippingOrderProfiles.workbench.undo')" @click="emit('undo')"><RotateCcw /></button>
<button type="button" :disabled="redoDisabled" :title="t('admin.shippingOrderProfiles.workbench.redo')" @click="emit('redo')"><Redo2 /></button>
<span class="toolbar-divider" aria-hidden="true" />
<button type="button" :disabled="duplicateDisabled" :title="t('admin.shippingOrderProfiles.workbench.duplicateRegionShortcut')" @click="emit('duplicate')"><Copy /></button>
<button type="button" class="delete-action" :disabled="deleteDisabled" :title="t('admin.shippingOrderProfiles.workbench.deleteRegionShortcut')" @click="emit('delete')"><Trash2 /></button>
<span class="toolbar-divider" aria-hidden="true" />
<button type="button" class="save-action" :disabled="saveDisabled || saving" :title="t('admin.save')" @click="emit('save')"><Save /><span>{{ saving ? t('admin.shippingOrderProfiles.saving') : t('admin.save') }}</span></button>
<template v-if="pendingSuggestionCount">
<span class="toolbar-divider" aria-hidden="true" />
<span class="suggestion-count">{{ pendingSuggestionCount }}</span>
<span class="suggestion-preview-badge">{{ t('admin.shippingOrderProfiles.workbench.suggestionPreviewBadge') }}</span>
</template>
</template>
<span v-else class="readonly-badge">{{ t('admin.shippingOrderProfiles.versionCenter.readonlyCanvasBadge') }}</span>
</div>
<div class="page-control">
<button type="button" :disabled="pageNo <= 1" :title="t('admin.shippingOrderExtractionRuns.previous')" @click="emit('page', pageNo - 1)"><ArrowLeft /></button>
<label><input v-model.number="pageInput" class="input-field" type="number" min="1" :max="pageCount" :aria-label="t('admin.shippingOrderProfiles.workbench.pageNavigation')" @change="goToPage" @keydown.enter.prevent="goToPage" /><span>/ {{ pageCount }}</span></label>
<button type="button" :disabled="pageNo >= pageCount" :title="t('admin.shippingOrderExtractionRuns.next')" @click="emit('page', pageNo + 1)"><ArrowRight /></button>
</div>
<div class="zoom-control">
<button type="button" :disabled="zoom <= .5" :title="t('admin.shippingOrderProfiles.workbench.zoomOut')" @click="adjustZoom(-.25)"><Minus /></button>
<output>{{ zoomPercent }}%</output>
<button type="button" :disabled="zoom >= 4" :title="t('admin.shippingOrderProfiles.workbench.zoomIn')" @click="adjustZoom(.25)"><Plus /></button>
<button type="button" class="fit-action" @click="resetZoom">{{ t('admin.shippingOrderProfiles.workbench.fitPage') }}</button>
</div>
</header>
<div v-if="loading && !pdfPreview" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}</div>
<div v-else-if="displayLoadError" class="canvas-state canvas-state--error" role="alert">
<p>{{ displayLoadError }}</p>
<button type="button" class="canvas-retry" @click="onRetryClick">
{{ t('admin.shippingOrderProfiles.workbench.retryCanvas') }}
</button>
</div>
<div v-else-if="!imageUrl && !pdfRendered && !pdfPreview" class="canvas-state">{{ emptyStateText }}</div>
<div v-else class="canvas-work-area" :class="{ readonly: readonlyMode }">
<aside v-if="!readonlyMode" class="annotation-tools">
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawDocumentMatchAnchorShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawDocumentMatchAnchorShortcut')" :class="{ active: creationKind === 'document_anchor_label' || creationKind === 'document_anchor_value' }" @click="emit('draw', 'document_anchor_label')"><Anchor /></button>
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawOrderAnchorShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawOrderAnchorShortcut')" :class="{ active: creationKind === 'order_anchor' }" @click="emit('draw', 'order_anchor')"><Tag /></button>
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawOrderFieldShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawOrderFieldShortcut')" :class="{ active: creationKind === 'order_field' }" @click="emit('draw', 'order_field')"><TextCursorInput /></button>
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawHeaderShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawHeaderShortcut')" :class="{ active: creationKind === 'header_field' }" @click="emit('draw', 'header_field')"><TableProperties /></button>
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawLineShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawLineShortcut')" :class="{ active: creationKind === 'line' }" @click="emit('draw', 'line')"><Rows3 /></button>
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawFieldShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawFieldShortcut')" :class="{ active: creationKind === 'field' }" @click="emit('draw', 'field')"><Columns3 /></button>
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawExclusionShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawExclusionShortcut')" :class="{ active: creationKind === 'exclusion' }" @click="emit('draw', 'exclusion')"><Eraser /></button>
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawReservationIdRegionShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawReservationIdRegionShortcut')" :class="{ active: creationKind === 'reservation_id_region' }" @click="emit('draw', 'reservation_id_region')"><MessageSquareText /></button>
<button type="button" class="suggest" :aria-label="t('admin.shippingOrderProfiles.workbench.autoSuggestShortcut')" :title="t('admin.shippingOrderProfiles.workbench.autoSuggestShortcut')" :disabled="autoSuggestDisabled || suggesting" @click="emit('suggest')"><WandSparkles /></button>
<p v-if="suggestionProgress" class="suggestion-progress" :class="{ failed: !suggesting }">{{ suggestionProgress }}</p>
</aside>
<div ref="viewport" class="canvas-viewport" :class="{ panning: !creationKind || readonlyMode }" @wheel.prevent="handleWheel">
<div
ref="canvas"
class="canvas-stage"
:class="{ drawing: creationKind && !readonlyMode, 'canvas-stage--xfa': Boolean(pdfPageSize) }"
:style="pdfPageSize
? { width: `${pdfPageSize.width}px`, minWidth: '0', '--canvas-zoom': zoom }
: { '--canvas-zoom': zoom }"
@pointerdown="beginCreation"
>
<img v-if="imageUrl" :src="imageUrl" :alt="t('admin.shippingOrderProfiles.workbench.pagePreviewAlt')" draggable="false" />
<canvas v-else ref="pdfCanvas" class="pdf-page" aria-label="XFA PDF preview" />
<div
v-for="region in regions"
:key="region.id"
role="button"
tabindex="0"
class="region"
: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}%`,
right: `${(1 - region.region.x1) * 100}%`,
bottom: `${(1 - region.region.y1) * 100}%`,
}"
:aria-label="displayRegionLabel(region)"
@pointerdown.stop="beginDrag($event, region, 'move')"
@keydown.enter="emit('select', region.id)"
@keydown.space.prevent="emit('select', region.id)"
>
<span class="region-label" :title="displayRegionLabel(region)" @pointerdown.stop="beginDrag($event, region, 'move')">{{ displayRegionLabel(region) }}</span>
<template v-if="region.kind === 'line' && !readonlyMode && !region.isPreview">
<span v-for="edge in ['n', 'e', 's', 'w']" :key="edge" class="line-hit-edge" :class="`line-hit-${edge}`" @pointerdown.stop="beginDrag($event, region, 'move')" />
</template>
<!-- 整边缩放热区:矮标签框拖上下边时不再落入整体 move。角点手柄叠在热区之上。 -->
<template v-if="!readonlyMode && !region.isPreview && selected.has(region.id)">
<span
v-for="edge in ['n', 'e', 's', 'w'] as ResizeHandle[]"
:key="`edge-${edge}`"
class="resize-edge"
:class="`resize-edge-${edge}`"
:aria-hidden="true"
@pointerdown.stop="beginDrag($event, region, edge)"
/>
</template>
<span
v-if="!readonlyMode && !region.isPreview"
v-for="handle in ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'] as ResizeHandle[]"
:key="handle"
role="button"
tabindex="-1"
class="resize-handle"
:class="`handle-${handle}`"
:aria-label="t('admin.shippingOrderProfiles.workbench.resizeHandle', { direction: handle })"
@pointerdown.stop="beginDrag($event, region, handle)"
/>
</div>
<div
v-if="creationRegion"
class="creation-region"
:style="{
left: `${creationRegion.x0 * 100}%`,
top: `${creationRegion.y0 * 100}%`,
right: `${(1 - creationRegion.x1) * 100}%`,
bottom: `${(1 - creationRegion.y1) * 100}%`,
}"
/>
</div>
</div>
</div>
</section>
</template>
<style scoped>
.canvas-shell { display: flex; height: calc(100vh - 5rem); min-height: 48rem; flex-direction: column; background: #101827; padding: 0 1rem 1rem; overflow: hidden; }
.canvas-toolbar { position: sticky; top: 0; z-index: 4; display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: .75rem; margin: 0 -1rem 1rem; padding: .55rem 1rem; border-bottom: 1px solid #26354b; background: rgb(15 23 42 / .98); color: #cbd5e1; font-size: .75rem; }
.canvas-toolbar > div { display: flex; align-items: center; gap: .35rem; }
.canvas-toolbar button { display: inline-flex; min-width: 2rem; height: 2rem; align-items: center; justify-content: center; gap: .35rem; border: 1px solid #475569; border-radius: .35rem; background: #1e293b; padding: .3rem .5rem; color: #e2e8f0; font-size: .72rem; }
.canvas-toolbar button:hover { border-color: #60a5fa; background: #26364f; }
.canvas-toolbar button:disabled { cursor: not-allowed; opacity: .4; }
.suggestion-count { display: inline-grid; min-width: 1.25rem; height: 1.25rem; place-items: center; border-radius: 999px; background: #f59e0b; color: #172033; font-size: .68rem; font-weight: 800; }
.canvas-toolbar .suggestion-action { border-color: #22c55e; background: #15803d; }
.canvas-toolbar .suggestion-action--reject { border-color: #64748b; background: transparent; }
.canvas-toolbar svg, .annotation-tools svg { width: .95rem; height: .95rem; }
.toolbar-actions { justify-self: start; }
.toolbar-divider { width: 1px; height: 1.25rem; margin: 0 .15rem; background: #475569; }
.toolbar-actions .delete-action:not(:disabled) { color: #fecaca; }
.toolbar-actions .delete-action:not(:disabled):hover { border-color: #f87171; background: #7f1d1d; color: #fff; }
.toolbar-actions .save-action { border-color: #0284c7; background: #0284c7; padding-inline: .65rem; }
.readonly-badge { display: inline-flex; align-items: center; min-height: 2rem; border: 1px solid #475569; border-radius: .35rem; background: #0f172a; padding: 0 .65rem; color: #cbd5e1; }
.page-control { justify-self: center; }
.page-control label { display: flex; height: 2rem; align-items: center; gap: .3rem; border: 1px solid #475569; border-radius: .35rem; background: #0f172a; padding: 0 .45rem; color: #94a3b8; }
.page-control .input-field { width: 3rem; border: 0; background: transparent; color: #f8fafc; font: 700 .76rem/1 ui-monospace, SFMono-Regular, Menlo, monospace; text-align: right; outline: 0; }
.zoom-control { justify-self: end; }
.canvas-toolbar output { min-width: 3.4rem; color: #f8fafc; text-align: center; }
.zoom-control .fit-action { padding-inline: .65rem; }
.canvas-state { display: grid; min-height: 32rem; place-items: center; color: #94a3b8; font-size: .875rem; gap: .75rem; }
.canvas-state--error { color: #fecaca; }
.canvas-retry {
display: inline-flex;
min-height: 2rem;
align-items: center;
justify-content: center;
border: 1px solid #475569;
border-radius: .35rem;
background: #1e293b;
padding: .35rem .75rem;
color: #e2e8f0;
font-size: .78rem;
cursor: pointer;
}
.canvas-retry:hover { border-color: #60a5fa; background: #26364f; }
.canvas-work-area { display: flex; min-height: 0; flex: 1; gap: .6rem; }
.canvas-work-area.readonly { gap: 0; }
.canvas-viewport { position: relative; min-width: 0; flex: 1; overflow: auto; }
.canvas-viewport.panning { cursor: grab; }
.canvas-viewport.panning:active { cursor: grabbing; }
.canvas-stage { position: relative; margin: auto; width: calc(100% * var(--canvas-zoom)); min-width: 42rem; box-shadow: 0 16px 40px rgba(0,0,0,.35); }
.canvas-stage img { display: block; width: 100%; user-select: none; }
.canvas-stage canvas.pdf-page { display: block; background: white; pointer-events: none; user-select: none; }
.canvas-stage.drawing { cursor: crosshair; }
.canvas-stage.drawing .region { pointer-events: none; }
/* 绘制模式下仍可缩放/移动当前选中框,避免点了标签工具后高度完全拉不动。 */
.canvas-stage.drawing .region.selected { pointer-events: auto; }
.creation-region { position: absolute; z-index: 5; box-sizing: border-box; border: 2px dashed #34d399; background: rgb(16 185 129 / .18); pointer-events: none; }
.annotation-tools { display: grid; align-content: start; gap: .3rem; flex: 0 0 2.65rem; padding: .3rem; border: 1px solid rgb(71 85 105 / .9); border-radius: .5rem; background: rgb(15 23 42 / .94); box-shadow: 0 8px 24px rgb(15 23 42 / .3); }
.annotation-tools button { display: grid; min-height: 2rem; place-items: center; border: 1px solid transparent; border-radius: .35rem; background: #1e293b; padding: .35rem; color: #e2e8f0; }
.annotation-tools button:hover, .annotation-tools button.active { border-color: #38bdf8; background: #0c4a6e; color: #f0f9ff; }
.annotation-tools .suggest { border-color: #0ea5e9; background: #0284c7; }
.annotation-tools button:disabled { cursor: not-allowed; opacity: .45; }
.suggestion-progress { margin: .1rem; color: #bae6fd; font-size: .66rem; line-height: 1.35; }
.suggestion-progress.failed { color: #fca5a5; }
.suggestion-preview-badge { color: #fbbf24; font-size: .68rem; }
.region { position: absolute; box-sizing: border-box; z-index: 2; border: 2px solid #38bdf8; background: rgb(14 165 233 / .10); color: #e0f2fe; cursor: move; text-align: left; touch-action: none; }
.region:focus-visible { outline: 3px solid white; outline-offset: 2px; }
.region-label { position: absolute; z-index: 2; top: -1.65rem; left: -2px; max-width: min(18rem, 100%); overflow: hidden; border: 1px solid rgb(255 255 255 / .7); border-radius: .25rem .25rem 0 0; background: #0369a1; padding: .2rem .45rem; color: white; font: 700 .7rem/1.15 ui-monospace, SFMono-Regular, Menlo, monospace; text-overflow: ellipsis; white-space: nowrap; }
/* 整边热区略伸出框外,左右缩进避开角点,保证矮框上下边可拉高。 */
.resize-edge { position: absolute; z-index: 4; touch-action: none; }
.resize-edge-n, .resize-edge-s { left: 8px; right: 8px; height: 14px; cursor: ns-resize; }
.resize-edge-e, .resize-edge-w { top: 8px; bottom: 8px; width: 14px; cursor: ew-resize; }
.resize-edge-n { top: -7px; }
.resize-edge-s { bottom: -7px; }
.resize-edge-e { right: -7px; }
.resize-edge-w { left: -7px; }
.resize-handle { position: absolute; z-index: 5; box-sizing: border-box; width: 12px; height: 12px; border: 2px solid white; border-radius: 2px; background: #0ea5e9; box-shadow: 0 1px 2px rgb(15 23 42 / .55); padding: 0; touch-action: none; cursor: pointer; }
.handle-n, .handle-s { left: 50%; margin-left: -6px; cursor: ns-resize; }
.handle-e, .handle-w { top: 50%; margin-top: -6px; cursor: ew-resize; }
.handle-nw, .handle-se { cursor: nwse-resize; }
.handle-ne, .handle-sw { cursor: nesw-resize; }
.handle-n, .handle-nw, .handle-ne { top: -7px; }
.handle-s, .handle-sw, .handle-se { bottom: -7px; }
.handle-e, .handle-ne, .handle-se { right: -7px; }
.handle-w, .handle-nw, .handle-sw { left: -7px; }
.region-header_field { z-index: 2; border: 1.5px solid #f59e0b; background: rgb(245 158 11 / .08); }
.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); }
.region-document_anchor_label .region-label, .region-document_anchor_label .resize-handle { background: #0369a1; }
.region-document_anchor_value { z-index: 2; border: 1.5px solid #f97316; background: rgb(249 115 22 / .1); }
.region-document_anchor_value .region-label, .region-document_anchor_value .resize-handle { background: #c2410c; }
.region-line { z-index: 0; border-color: #a78bfa; background: rgb(167 139 250 / .1); pointer-events: none; }
.region-line .region-label, .region-line .line-hit-edge, .region-line.selected .resize-handle { pointer-events: auto; }
.region-line .region-label, .region-line .resize-handle { background: #6d28d9; }
.line-hit-edge { position: absolute; z-index: 2; display: block; }
.line-hit-n, .line-hit-s { right: -6px; left: -6px; height: 12px; cursor: move; }
.line-hit-e, .line-hit-w { top: 6px; bottom: 6px; width: 12px; cursor: move; }
.line-hit-n { top: -6px; }
.line-hit-e { right: -6px; }
.line-hit-s { bottom: -6px; }
.line-hit-w { left: -6px; }
.region-exclusion { z-index: 3; border-style: dashed; border-color: #f87171; background: rgb(248 113 113 / .1); }
.region-exclusion .region-label, .region-exclusion .resize-handle { background: #b91c1c; }
.region-reservation_id_region { z-index: 3; border: 2px solid #f43f5e; background: rgb(244 63 94 / .10); }
.region-reservation_id_region .region-label, .region-reservation_id_region .resize-handle { background: #be123c; }
.region-visual--suggested { border-style: dashed; border-color: #f59e0b; background: rgb(245 158 11 / .14); }
.region-visual--suggested .region-label { background: #b45309; }
.region-visual--confirmed { border-color: #22c55e; background: rgb(34 197 94 / .12); }
.region-visual--confirmed .region-label { background: #15803d; }
.region-visual--rejected, .region-visual--needs_review { border-color: #f87171; background: rgb(248 113 113 / .1); }
.region-visual--rejected .region-label, .region-visual--needs_review .region-label { background: #b91c1c; }
.region:not(.selected) .resize-handle { display: none; }
.region.selected { outline: 3px solid white; outline-offset: 2px; }
.region.selected:not(.region-line) { z-index: 4; }
.region-preview { z-index: 5; border-style: dashed; border-width: 2px; border-color: #fbbf24; background: rgb(245 158 11 / .18); color: #fef3c7; cursor: default; pointer-events: auto; }
.region-preview .region-label { background: #a16207; }
@media (max-width: 900px) {
.canvas-shell { height: auto; min-height: 36rem; }
.canvas-toolbar { grid-template-columns: 1fr auto; }
.page-control { grid-column: 1 / -1; grid-row: 2; }
.zoom-control { justify-self: end; }
.canvas-stage { min-width: 32rem; }
.canvas-viewport { max-height: 32rem; }
}
@media (max-width: 640px) {
.canvas-shell { min-height: 24rem; padding-inline: .5rem; }
.canvas-toolbar { margin-inline: -.5rem; padding-inline: .5rem; }
.toolbar-actions .save-action span, .fit-action { display: none; }
.annotation-tools { flex-basis: 2.45rem; }
.annotation-tools button span, .suggestion-progress { display: none; }
}
</style>
@@ -0,0 +1,117 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileFrozenEvidencePanel.vue
用途:展示当前只读样本绑定的冻结证据信息。
依赖:版本详情样本 DTO、i18n。
逻辑:只渲染冻结身份与快照摘要,不泄露正文、对象存储地址或盲测真值。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { OrderProfileBoundSample } from '@/features/admin/types/shipping-order-document-profile.types';
const props = defineProps<{
sample: OrderProfileBoundSample | null;
}>();
const { t } = useI18n();
const frozenStatus = computed(() => (
props.sample?.frozen_evidence_ready
? t('admin.shippingOrderProfiles.versionCenter.frozenEvidence.ready')
: t('admin.shippingOrderProfiles.versionCenter.frozenEvidence.missing')
));
</script>
<template>
<aside class="panel">
<h3>{{ t('admin.shippingOrderProfiles.versionCenter.frozenEvidencePanelTitle') }}</h3>
<p v-if="!sample" class="empty">{{ t('admin.shippingOrderProfiles.versionCenter.selectSampleHint') }}</p>
<dl v-else class="grid">
<div>
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.statusLabel') }}</dt>
<dd>{{ frozenStatus }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.sampleFile') }}</dt>
<dd>{{ sample.source_filename_snapshot || '-' }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.layoutVersionId') }}</dt>
<dd>{{ sample.layout_version_id || '-' }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.evidenceFrozenAt') }}</dt>
<dd>{{ sample.evidence_frozen_at || '-' }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.pageCountPlain') }}</dt>
<dd>{{ sample.page_count_snapshot || '-' }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.parserIdentity') }}</dt>
<dd>{{ sample.parser_name || sample.parser_key || '-' }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.parserVersionTitle') }}</dt>
<dd>{{ sample.parser_version || '-' }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.frozenTableId') }}</dt>
<dd>{{ sample.table_identity_snapshot?.table_id || sample.table_id || '-' }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.frozenPageNo') }}</dt>
<dd>{{ sample.table_identity_snapshot?.page_no || '-' }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.frozenRowCount') }}</dt>
<dd>{{ sample.table_identity_snapshot?.row_count || '-' }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.layoutChecksumTitle') }}</dt>
<dd><code>{{ sample.layout_payload_checksum || '-' }}</code></dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.contentHashTitle') }}</dt>
<dd><code>{{ sample.source_content_hash || '-' }}</code></dd>
</div>
</dl>
</aside>
</template>
<style scoped>
.panel {
border: 1px solid #e2e8f0;
border-radius: 1rem;
background: #fff;
padding: 1rem;
}
.panel h3 {
margin: 0;
color: #0f172a;
}
.empty {
margin: 0.85rem 0 0;
color: #64748b;
}
.grid {
display: grid;
gap: 0.85rem;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
margin: 0.9rem 0 0;
}
.grid dt {
color: #64748b;
font-size: 0.75rem;
}
.grid dd {
margin: 0.3rem 0 0;
color: #0f172a;
word-break: break-word;
}
</style>
@@ -0,0 +1,30 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileIdentityStep.vue
用途:收集模板名称与已发布 Schema。
依赖:Schema DTO、Vue I18n。
逻辑:系统编码由服务端在创建时生成;父级拥有唯一表单状态,避免 v-model 对象替换丢失首步校验状态。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderSchemaVersion } from '@/features/admin/types/shipping-order-schema.types';
type Identity = { displayName: string; schemaId: number };
const props = defineProps<{ modelValue: Identity; schemas: ShippingOrderSchemaVersion[]; schemasResolved: boolean }>();
const emit = defineEmits<{ 'update:modelValue': [value: Identity] }>();
const { t } = useI18n();
const publishedSchemas = computed(() => props.schemas.filter((item) => item.status === 'published'));
/** 每次更新都提交完整快照,确保父级的下一步校验始终读取最新值。 */
function update(key: keyof Identity, value: string | number): void { emit('update:modelValue', { ...props.modelValue, [key]: value }); }
</script>
<template>
<div class="identity-step">
<label class="field"><span>{{ t('admin.shippingOrderProfiles.name') }}<b>*</b></span><input class="input-field" :value="modelValue.displayName" :placeholder="t('admin.shippingOrderProfiles.wizard.namePlaceholder')" @input="update('displayName', ($event.target as HTMLInputElement).value)" /></label>
<div class="system-code"><strong>{{ t('admin.shippingOrderProfiles.code') }}</strong><span>{{ t('admin.shippingOrderProfiles.wizard.systemCodeHint') }}</span></div>
<label class="field"><span>{{ t('admin.shippingOrderProfiles.schema') }}<b>*</b></span><select class="select-field" :value="modelValue.schemaId" @change="update('schemaId', Number(($event.target as HTMLSelectElement).value))"><option :value="0">{{ t('admin.shippingOrderProfiles.wizard.selectSchema') }}</option><option v-for="schema in publishedSchemas" :key="schema.id" :value="schema.id">v{{ schema.version }}</option></select><small v-if="schemasResolved && !publishedSchemas.length" class="field-warning">{{ t('admin.shippingOrderProfiles.wizard.schemaRequired') }}</small></label>
</div>
</template>
<style scoped>
.identity-step { display: grid; gap: 22px; max-width: 560px; }.field { display: grid; gap: 8px; color: var(--text-secondary); font-weight: 700; }.field > span { display: flex; gap: 4px; }.field b { color: var(--status-error-fg); }.field .input-field,.field .select-field { min-height: 44px; box-sizing: border-box; font: inherit; }.field small { color: var(--text-muted); font-size: .8rem; font-weight: 500; }.system-code { display: grid; gap: 4px; padding: 13px 14px; border: 1px solid var(--border-default); border-radius: 9px; color: var(--text-secondary); background: var(--bg-surface-soft); font-size: .86rem; }.system-code strong { color: var(--text-primary); }.field-warning { color: var(--status-warning-fg) !important; }
</style>
@@ -0,0 +1,35 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileIssuePanel.vue
用途:统一呈现工作台保存前的配置问题与局部预览状态。
依赖:无。
逻辑:父页面计算问题码;本组件只呈现可操作的短提示,不保存样本正文或坐标。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
const props = defineProps<{ issues: string[]; previewState: 'idle' | 'updating' | 'ready' | 'failed'; previewError?: string }>();
const { t } = useI18n();
const previewStatusLabel = (state: 'idle' | 'updating' | 'ready' | 'failed') => ({
idle: t('admin.shippingOrderProfiles.workbench.previewIdle'),
updating: t('admin.shippingOrderProfiles.workbench.previewUpdating'),
ready: t('admin.shippingOrderProfiles.workbench.previewReady'),
failed: t('admin.shippingOrderProfiles.workbench.previewFailed'),
}[state]);
</script>
<template>
<aside class="issue-panel">
<div class="issue-title"><span>{{ t('admin.shippingOrderProfiles.workbench.review') }}</span><span :class="`state-${previewState}`">{{ previewStatusLabel(previewState) }}</span></div>
<p v-if="previewState === 'failed' && props.previewError" class="preview-error">{{ props.previewError }}</p>
<p v-if="!issues.length" class="issue-empty">{{ t('admin.shippingOrderProfiles.workbench.noIssues') }}</p>
<ul v-else><li v-for="issue in issues" :key="issue">{{ issue }}</li></ul>
</aside>
</template>
<style scoped>
.issue-panel { border-top: 1px solid #dbe4ef; background: #f8fafc; padding: .75rem 1rem; }
.issue-title { display: flex; align-items: center; justify-content: space-between; color: #334155; font: 700 .72rem/1 ui-monospace, SFMono-Regular, Menlo, monospace; letter-spacing: .08em; text-transform: uppercase; }
.issue-title span:last-child { border-radius: 999px; padding: .25rem .5rem; font-size: .65rem; letter-spacing: normal; text-transform: none; }
.state-idle { background: #e2e8f0; }.state-updating { background: #dbeafe; color: #1d4ed8; }.state-ready { background: #dcfce7; color: #166534; }.state-failed { background: #fee2e2; color: #b91c1c; }
ul { margin: .6rem 0 0; padding-left: 1rem; color: #b45309; font-size: .75rem; line-height: 1.4; }.issue-empty { margin: .5rem 0 0; color: #64748b; font-size: .75rem; }
.preview-error { margin: .55rem 0 0; color: #b91c1c; font-size: .75rem; line-height: 1.4; }
</style>
@@ -0,0 +1,14 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileModelStartStep.vue
用途:在多表样本中选择用于订单明细标注的表格。
依赖:样本表格预览 DTO、Vue I18n。
逻辑:只让用户选定服务端已发现的 table_id;预览限制在容器内横向滚动,避免宽表撑破页面。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
const props = defineProps<{ tables: Array<{ table_id: string; page_no: number; row_count: number; column_count: number; rows: string[][] }>; modelValue: string }>();
const emit = defineEmits<{ 'update:modelValue': [value: string] }>();
const { t } = useI18n();
</script>
<template><div class="wizard-step"><div><label>{{ t('admin.shippingOrderProfiles.wizard.orderLineTable') }}<select class="select-field" :value="modelValue" @change="emit('update:modelValue', ($event.target as HTMLSelectElement).value)"><option value="">{{ t('admin.shippingOrderProfiles.selectTable') }}</option><option v-for="table in tables" :key="table.table_id" :value="table.table_id">{{ t('admin.shippingOrderProfiles.wizard.tableOption', { page: table.page_no, rows: table.row_count, columns: table.column_count }) }}</option></select></label><p class="field-hint">{{ t('admin.shippingOrderProfiles.wizard.orderLineTableHint') }}</p></div><p v-if="!tables.length" class="warning">{{ t('admin.shippingOrderProfiles.wizard.noTable') }}</p><div v-else-if="modelValue" class="table-preview"><table><tbody><tr v-for="row in tables.find((item) => item.table_id === modelValue)?.rows.slice(0, 4) || []" :key="row.join('|')"><td v-for="cell in row" :key="cell">{{ cell }}</td></tr></tbody></table></div></div></template>
<style scoped>.wizard-step{display:grid;min-width:0;gap:1rem}.wizard-step label{display:grid;gap:.35rem;font-weight:600}.wizard-step .select-field{min-width:0}.field-hint{margin:.45rem 0 0;color:var(--text-muted);font-size:.875rem}.warning{color:var(--status-warning-fg)}.table-preview{max-width:100%;overflow-x:auto;border:1px solid var(--border-default);border-radius:.5rem}.table-preview table{width:max-content;min-width:100%;border-collapse:collapse}.table-preview td{max-width:16rem;padding:.55rem;border:1px solid var(--border-default);overflow-wrap:anywhere;vertical-align:top}</style>
@@ -0,0 +1,351 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileReadOnlyCanvas.vue
用途:在版本详情页展示基于冻结样本绑定的只读画布。
依赖:冻结样本预览 API、OrderProfileDocumentCanvas、冻结证据面板。
逻辑:所有模板共用 annotation/training 冻结样本画布;XFA datasets 映射仅作为侧栏证据,
blind_test 继续留在摘要层,不进入样本选择器。
-->
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import {
authorizeOrderProfileFrozenSamplePreviewPages,
getOrderProfileFrozenSampleRegionDiagnostics,
} from '@/features/admin/api/shipping-order-document-profile.api';
import type {
OrderProfileBoundSample,
OrderProfilePreviewPages,
OrderProfileRegionDiagnostic,
ShippingOrderDocumentProfile,
} from '@/features/admin/types/shipping-order-document-profile.types';
import OrderProfileDocumentCanvas from './OrderProfileDocumentCanvas.vue';
import OrderProfileFrozenEvidencePanel from './OrderProfileFrozenEvidencePanel.vue';
import XfaReadOnlyMapping from './XfaReadOnlyMapping.vue';
import { buildOrderProfileReadonlyRegions } from '../orderProfileReadonlyCanvas.utils';
const props = defineProps<{
detail: ShippingOrderDocumentProfile;
}>();
const { t } = useI18n();
const loading = ref(false);
const errorMessage = ref('');
const selectedSampleId = ref<number | null>(null);
const selectedRegionId = ref<string | null>(null);
const previewPages = ref<OrderProfilePreviewPages | null>(null);
const regionDiagnostics = ref(new Map<string, OrderProfileRegionDiagnostic>());
const diagnosticsLoading = ref(false);
const pageNo = ref(1);
const readonlySamples = computed(() =>
(props.detail.sample_summary?.samples || []).filter((sample) => sample.sample_role !== 'blind_test'),
);
const selectedSample = computed<OrderProfileBoundSample | null>(() =>
readonlySamples.value.find((sample) => sample.id === selectedSampleId.value) || null,
);
const readonlyRegions = computed(() => buildOrderProfileReadonlyRegions(props.detail).map((region) => {
const diagnostic = regionDiagnostics.value.get(region.id);
return diagnostic ? {
...region,
recognizedValue: diagnostic.recognized_value,
configuredValue: diagnostic.configured_value,
matchesConfigured: diagnostic.matches_configured,
} : region;
}));
const pageRegions = computed(() => readonlyRegions.value.filter((region) => region.pageNo === pageNo.value));
const selectedRegion = computed(() => pageRegions.value.find((region) => region.id === selectedRegionId.value) || null);
const currentGrant = computed(() =>
previewPages.value?.pages.find((item) => item.page_no === pageNo.value) || null,
);
const previewPagePath = computed(() => (
props.detail.id && selectedSample.value
? `/api/admin/shipping-notice/order-document-profiles/${props.detail.id}/samples/${selectedSample.value.id}/preview-pages`
: null
));
const immutable = computed(() => props.detail.status !== 'draft');
const selectedDiagnostic = computed(() => (
selectedRegion.value ? regionDiagnostics.value.get(selectedRegion.value.id) || null : null
));
const sampleLabel = (sample: OrderProfileBoundSample) => {
const tableLabel = sample.table_identity_snapshot?.table_id || sample.table_id || '-';
return `${sample.source_filename_snapshot || `#${sample.id}`} · ${tableLabel}`;
};
const loadPreview = async (sampleId: number | null) => {
if (!sampleId || !immutable.value) {
previewPages.value = null;
regionDiagnostics.value = new Map();
errorMessage.value = '';
return;
}
loading.value = true;
errorMessage.value = '';
selectedRegionId.value = null;
try {
const payload = await authorizeOrderProfileFrozenSamplePreviewPages(props.detail.id, sampleId);
previewPages.value = payload;
const preferredPage = selectedSample.value?.table_identity_snapshot?.page_no || 1;
pageNo.value = Math.max(1, Math.min(payload.page_count || 1, preferredPage));
} catch (error) {
previewPages.value = null;
errorMessage.value = error instanceof BusinessError
? error.message
: t('admin.shippingOrderProfiles.versionCenter.canvasLoadFailed');
} finally {
loading.value = false;
}
};
/** 读取当前冻结样本页的受控区域识别值,并按 region ID 合并到只读画布。 */
const loadRegionDiagnostics = async (): Promise<void> => {
const sampleId = selectedSampleId.value;
if (!sampleId || !immutable.value) {
regionDiagnostics.value = new Map();
return;
}
diagnosticsLoading.value = true;
try {
const payload = await getOrderProfileFrozenSampleRegionDiagnostics(props.detail.id, sampleId, pageNo.value);
regionDiagnostics.value = new Map(payload.items.map((item) => [item.region_id, item]));
} catch (error) {
regionDiagnostics.value = new Map();
// 区域诊断是增强信息;冻结版面没有 coordinate_evidence 时不能阻断 PDF 主画布。
// 仅保留诊断区域为空,具体字段会回退到“未读取到值”。
if (error instanceof BusinessError && error.code !== 'SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND') {
errorMessage.value = error.message;
}
} finally {
diagnosticsLoading.value = false;
}
};
watch(
() => props.detail.id,
() => {
const firstReady = readonlySamples.value.find((sample) => sample.frozen_evidence_ready) || readonlySamples.value[0] || null;
selectedSampleId.value = firstReady?.id || null;
},
{ immediate: true },
);
watch(selectedSampleId, (value) => {
void loadPreview(value);
}, { immediate: true });
watch([selectedSampleId, pageNo], () => {
void loadRegionDiagnostics();
}, { immediate: true });
</script>
<template>
<section class="readonly-layout">
<div v-if="!immutable" class="state-card">
{{ t('admin.shippingOrderProfiles.versionCenter.draftCanvasHint') }}
</div>
<div v-else-if="!readonlySamples.length" class="state-card">
{{ t('admin.shippingOrderProfiles.versionCenter.noReadableSamples') }}
</div>
<template v-else>
<div class="toolbar">
<label class="field">
<span>{{ t('admin.shippingOrderProfiles.versionCenter.readonlySample') }}</span>
<select v-model.number="selectedSampleId" class="select-field">
<option v-for="sample in readonlySamples" :key="sample.id" :value="sample.id">
{{ sampleLabel(sample) }}
</option>
</select>
</label>
<p v-if="selectedSample && !selectedSample.frozen_evidence_ready" class="warning-text">
{{ t('admin.shippingOrderProfiles.versionCenter.sampleFrozenEvidenceMissing') }}
</p>
</div>
<div v-if="errorMessage" class="state-card error-card">{{ errorMessage }}</div>
<div v-else-if="loading" class="state-card">{{ t('admin.shippingOrderProfiles.versionCenter.loadingCanvas') }}</div>
<div v-else-if="selectedSample && currentGrant" class="canvas-grid">
<OrderProfileDocumentCanvas
:profile-id="detail.id"
:grant="currentGrant"
:mode="'readonly'"
:preview-page-path="previewPagePath"
:regions="pageRegions"
:selected-region-id="selectedRegionId"
:page-no="pageNo"
:page-count="previewPages?.page_count || 1"
@select="selectedRegionId = $event"
@page="pageNo = $event"
/>
<div class="side-panel">
<OrderProfileFrozenEvidencePanel :sample="selectedSample" />
<XfaReadOnlyMapping :detail="detail" />
<section class="panel">
<h3>{{ t('admin.shippingOrderProfiles.versionCenter.regionSummaryTitle') }}</h3>
<p v-if="diagnosticsLoading" class="diagnostic-state">{{ t('admin.shippingOrderProfiles.versionCenter.regionDiagnosticsLoading') }}</p>
<p v-if="!selectedRegion" class="empty">{{ t('admin.shippingOrderProfiles.versionCenter.selectRegionHint') }}</p>
<dl v-else class="grid">
<div>
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.regionLabelTitle') }}</dt>
<dd>{{ selectedRegion.label }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.regionKindTitle') }}</dt>
<dd>{{ selectedRegion.kind }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.regionFieldCodeTitle') }}</dt>
<dd>{{ selectedRegion.fieldCode || '-' }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.regionPageTitle') }}</dt>
<dd>{{ selectedRegion.pageNo }}</dd>
</div>
<div class="wide-row">
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.recognizedValueTitle') }}</dt>
<dd class="diagnostic-value">{{ selectedDiagnostic?.recognized_value || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable') }}</dd>
</div>
<div v-if="selectedDiagnostic?.configured_value != null" class="wide-row">
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.configuredValueTitle') }}</dt>
<dd class="diagnostic-value">{{ selectedDiagnostic.configured_value }}</dd>
</div>
<div v-if="selectedDiagnostic?.matches_configured != null" class="wide-row">
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.matchResultTitle') }}</dt>
<dd :class="selectedDiagnostic.matches_configured ? 'match-ok' : 'match-failed'">
{{ selectedDiagnostic.matches_configured
? t('admin.shippingOrderProfiles.versionCenter.matchResultMatched')
: t('admin.shippingOrderProfiles.versionCenter.matchResultMismatched') }}
</dd>
</div>
</dl>
</section>
</div>
</div>
</template>
</section>
</template>
<style scoped>
.readonly-layout {
display: grid;
gap: 1rem;
}
.toolbar,
.state-card,
.panel {
border: 1px solid #e2e8f0;
border-radius: 1rem;
background: #fff;
padding: 1rem;
}
.toolbar {
display: grid;
gap: 0.75rem;
}
.field {
display: grid;
gap: 0.35rem;
}
.field span {
color: #475569;
font-size: 0.8rem;
}
.field .select-field {
min-height: 2.5rem;
padding: 0 0.75rem;
}
.canvas-grid {
display: grid;
gap: 1rem;
grid-template-columns: minmax(0, 1fr) 320px;
}
.side-panel {
display: grid;
gap: 1rem;
align-content: start;
}
.grid {
display: grid;
gap: 0.75rem;
grid-template-columns: repeat(2, minmax(0, 1fr));
margin: 0.85rem 0 0;
}
.grid dt {
color: #64748b;
font-size: 0.75rem;
}
.grid dd {
margin: 0.25rem 0 0;
color: #0f172a;
word-break: break-word;
}
.wide-row {
grid-column: 1 / -1;
}
.diagnostic-state {
margin: 0.75rem 0 0;
color: #0369a1;
font-size: 0.78rem;
}
.diagnostic-value {
border-left: 3px solid #0ea5e9;
background: #f0f9ff;
padding: 0.65rem 0.75rem;
color: #0f172a;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
line-height: 1.55;
white-space: pre-wrap;
}
.match-ok,
.match-failed {
display: inline-flex;
width: fit-content;
border-radius: 999px;
padding: 0.3rem 0.65rem;
font-weight: 700;
}
.match-ok {
background: #dcfce7;
color: #166534;
}
.match-failed {
background: #fee2e2;
color: #991b1b;
}
.warning-text {
margin: 0;
color: #b45309;
}
.error-card {
color: #b91c1c;
}
.empty {
margin: 0.75rem 0 0;
color: #64748b;
}
@media (max-width: 1180px) {
.canvas-grid {
grid-template-columns: 1fr;
}
}
</style>
@@ -0,0 +1,131 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileSampleStep.vue
用途:上传新模板样本或复用已解析样本,并自动选择上传后解析完成的文档。
依赖:模板样本 Intake 状态 API、文件资产上传 API、Vue I18n。
逻辑:上传后轮询同一 Intake;只有 ready 样本进入父级选择值,避免要求管理员重复选择刚上传的文件。
-->
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import { CheckCircle2, Clock3, UploadCloud } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { uploadFileAsset } from '@/shared/api/file-assets.api';
import { createOrderProfileSample, getOrderProfileSampleStatus } from '@/features/admin/api/shipping-order-document-profile.api';
type Sample = { document_id: number; filename?: string | null; table_count: number; intake_no: string };
const props = defineProps<{ samples: Sample[]; modelValue: number }>();
const emit = defineEmits<{ 'update:modelValue': [value: number]; uploaded: [intakeNo: string]; refresh: []; }>();
const { t } = useI18n();
const message = useMessage();
const uploading = ref(false);
type PendingState = 'uploading' | 'queued' | 'parsing' | 'syncing' | 'failed';
const pendingIntake = ref<{ intakeNo?: string; filename: string; state: PendingState; errorCode?: string | null } | null>(null);
let pollingTimer: number | null = null;
const selectedSample = computed(() => props.samples.find((item) => item.document_id === props.modelValue) || null);
/** 停止当前轮询;离开步骤或开始新上传时都不保留后台计时器。 */
function stopPolling(): void { if (pollingTimer) window.clearTimeout(pollingTimer); pollingTimer = null; }
/** 将模板布局失败码转成管理员可执行的提示,不把内部快照内容暴露到页面。 */
function sampleFailureMessage(errorCode?: string | null): string {
const key = errorCode === 'mineru_cell_coordinates_missing'
? 'sampleLayoutCoordinatesMissing'
: errorCode === 'shipping_document_layout_snapshot_size_exceeded'
? 'sampleLayoutSnapshotTooLarge'
: 'sampleParseFailed';
return t(`admin.shippingOrderProfiles.wizard.${key}`);
}
/** 刷新样本列表后按 Intake 精确定位新文档,防止同名历史文件被误选。 */
function selectUploadedSample(intakeNo: string): boolean {
const sample = props.samples.find((item) => item.intake_no === intakeNo);
if (!sample) return false;
emit('update:modelValue', sample.document_id);
stopPolling();
pendingIntake.value = null;
return true;
}
/** 父级完成样本列表请求后立即选中同一 Intake,避免固定延时与接口响应竞态。 */
watch(() => props.samples, () => {
const intakeNo = pendingIntake.value?.intakeNo;
if (intakeNo && pendingIntake.value?.state === 'syncing' && selectUploadedSample(intakeNo)) {
message.success(t('admin.shippingOrderProfiles.wizard.sampleReady'));
}
}, { deep: false });
/** 查询异步解析状态,完成后请求父级刷新列表并自动选中当前上传的样本。 */
async function pollIntake(intakeNo: string): Promise<void> {
try {
const result = await getOrderProfileSampleStatus(intakeNo);
// 文档记录已落库不等于样本可选;列表接口还要求当前 Layout ready。
// 等待同一状态后再刷新,避免把尚未建好表格的文档误报为已完成。
if (result.parse_status === 'parsed' && result.document_count > 0 && result.layout_status === 'ready') {
pendingIntake.value = { intakeNo, filename: pendingIntake.value?.filename || '', state: 'syncing' };
emit('uploaded', intakeNo);
// 列表可能比状态接口晚一个轮询周期可见,保持轮询直到父级刷新后精确选中。
pollingTimer = window.setTimeout(() => void pollIntake(intakeNo), 1000);
return;
}
if (['failed', 'error'].includes(result.parse_status) || result.layout_status === 'failed') {
pendingIntake.value = {
intakeNo, filename: pendingIntake.value?.filename || '', state: 'failed', errorCode: result.error_code,
};
return;
}
if (pendingIntake.value) pendingIntake.value.state = result.document_count ? 'parsing' : 'queued';
pollingTimer = window.setTimeout(() => void pollIntake(intakeNo), 1500);
} catch {
pollingTimer = window.setTimeout(() => void pollIntake(intakeNo), 2000);
}
}
/** 上传后立即显示解析状态;此处不创建 Profile,解析成功才自动选择样本文档。 */
async function upload(event: Event): Promise<void> {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = '';
if (!file || uploading.value) return;
if (!/\.(pdf|eml)$/i.test(file.name)) { message.error(t('admin.shippingOrderProfiles.sampleFileTypeInvalid')); return; }
stopPolling();
uploading.value = true;
pendingIntake.value = { filename: file.name, state: 'uploading' };
try {
const asset = await uploadFileAsset(file);
const intake = await createOrderProfileSample(asset.asset_no);
pendingIntake.value = { intakeNo: intake.intake_no, filename: file.name, state: 'queued' };
void pollIntake(intake.intake_no);
} catch (error) {
pendingIntake.value = null;
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.uploadFailed'));
} finally { uploading.value = false; }
}
onBeforeUnmount(stopPolling);
</script>
<template>
<div class="sample-step">
<section class="upload-panel">
<div class="upload-panel__icon"><UploadCloud :size="22" /></div>
<div><h3>{{ t('admin.shippingOrderProfiles.wizard.uploadNewSample') }}</h3><p>{{ t('admin.shippingOrderProfiles.wizard.uploadNewSampleHint') }}</p></div>
<label class="upload-action"><input type="file" accept=".pdf,.eml,application/pdf,message/rfc822" :disabled="uploading" @change="upload"><span>{{ uploading ? t('admin.shippingOrderProfiles.wizard.uploading') : t('admin.shippingOrderProfiles.uploadSample') }}</span></label>
</section>
<div v-if="pendingIntake" class="parse-status" :class="{ failed: pendingIntake.state === 'failed' }">
<Clock3 v-if="pendingIntake.state !== 'failed'" :size="19" /><span v-else>!</span>
<div>
<strong>{{ pendingIntake.filename }}</strong>
<p v-if="pendingIntake.state === 'failed'">{{ sampleFailureMessage(pendingIntake.errorCode) }}</p>
<p v-else>{{ t(`admin.shippingOrderProfiles.wizard.sampleStatus.${pendingIntake.state}`) }}</p>
<button v-if="pendingIntake.state !== 'uploading' && pendingIntake.state !== 'failed'" type="button" class="refresh-status" @click="emit('refresh')">{{ t('admin.shippingOrderProfiles.wizard.refreshSamples') }}</button>
</div>
</div>
<div v-if="selectedSample" class="selected-sample"><CheckCircle2 :size="20" /><div><strong>{{ t('admin.shippingOrderProfiles.wizard.sampleSelected') }}</strong><span>{{ selectedSample.filename || selectedSample.intake_no }} · {{ selectedSample.table_count }} {{ t('admin.shippingOrderProfiles.tablesUnit') }}</span></div></div>
<section class="reuse-panel">
<div class="reuse-panel__heading"><h3>{{ t('admin.shippingOrderProfiles.wizard.reuseSample') }}</h3><p>{{ t('admin.shippingOrderProfiles.wizard.reuseSampleHint') }}</p></div>
<label class="field"><span>{{ t('admin.shippingOrderProfiles.selectSample') }}</span><select class="select-field" :value="modelValue" @change="emit('update:modelValue', Number(($event.target as HTMLSelectElement).value))"><option :value="0">{{ t('admin.shippingOrderProfiles.selectSample') }}</option><option v-for="sample in samples" :key="sample.document_id" :value="sample.document_id">{{ sample.filename || sample.intake_no }} · {{ sample.table_count }} {{ t('admin.shippingOrderProfiles.tablesUnit') }}</option></select></label>
</section>
</div>
</template>
<style scoped>
.sample-step { display: grid; gap: 18px; max-width: 640px; }.upload-panel,.reuse-panel,.parse-status,.selected-sample { border: 1px solid var(--border-default); border-radius: 12px; background: var(--bg-surface); }.upload-panel { display: grid; grid-template-columns: auto 1fr auto; gap: 14px; align-items: center; padding: 18px; background: var(--bg-surface-soft); }.upload-panel__icon { display: grid; width: 42px; height: 42px; place-items: center; border-radius: 10px; color: var(--status-info-fg); background: var(--status-info-bg); }.upload-panel h3,.reuse-panel h3,.parse-status p,.selected-sample span { margin: 0; }.upload-panel h3,.reuse-panel h3 { color: var(--text-primary); font-size: 1rem; }.upload-panel p,.reuse-panel p { margin: 5px 0 0; color: var(--text-muted); font-size: .84rem; }.upload-action { display: inline-flex; min-height: 38px; align-items: center; border-radius: 8px; padding: 0 13px; color: #fff; background: #1677d2; font-weight: 700; cursor: pointer; }.upload-action input { position: absolute; width: 1px; height: 1px; overflow: hidden; opacity: 0; }.parse-status,.selected-sample { display: flex; gap: 10px; align-items: center; padding: 13px 15px; color: var(--status-info-fg); background: var(--status-info-bg); }.parse-status strong,.selected-sample strong { display: block; color: var(--text-primary); }.parse-status p,.selected-sample span { display: block; margin-top: 3px; color: var(--text-muted); font-size: .83rem; }.refresh-status { margin-top: 6px; padding: 0; border: 0; color: inherit; background: transparent; font: inherit; font-size: .8rem; font-weight: 700; cursor: pointer; text-decoration: underline; }.parse-status.failed { color: var(--status-error-fg); border-color: var(--status-error-border); background: var(--status-error-bg); }.parse-status.failed > span { display: grid; width: 19px; height: 19px; place-items: center; border-radius: 50%; color: #fff; background: var(--status-error-fg); font-weight: 800; }.selected-sample { color: var(--status-success-fg); border-color: var(--status-success-border); background: var(--status-success-bg); }.reuse-panel { padding: 18px; }.reuse-panel__heading { margin-bottom: 14px; }.field { display: grid; gap: 7px; color: var(--text-secondary); font-size: .88rem; font-weight: 700; }.field .select-field { min-height: 44px; font: inherit; } @media (max-width: 640px) { .upload-panel { grid-template-columns: auto 1fr; }.upload-action { grid-column: 1 / -1; justify-content: center; } }
</style>
@@ -0,0 +1,283 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileUsageTable.vue
用途:展示订单模板版本的实际使用记录,并提供进入只读 Run 审计的入口。
依赖:版本中心 usage API、Vue Router。
逻辑:只读取每个 Unit 最新 RouteDecision 的安全投影;点击行跳转到管理员 Run 诊断页,不在当前页改动任何业务状态。
-->
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { BusinessError } from "@/shared/api/client";
import { listOrderDocumentProfileUsages } from "@/features/admin/api/shipping-order-document-profile.api";
import type {
OrderProfileUsagePage,
OrderProfileUsageRow,
ShippingOrderDocumentProfile,
} from "@/features/admin/types/shipping-order-document-profile.types";
const props = defineProps<{ detail: ShippingOrderDocumentProfile }>();
const { t } = useI18n();
const router = useRouter();
const loading = ref(false);
const errorMessage = ref("");
const page = ref<OrderProfileUsagePage | null>(null);
const cursorStack = ref<Array<number | null>>([]);
const activeBeforeId = ref<number | null>(null);
const hasPrevious = computed(() => cursorStack.value.length > 0);
const hasNext = computed(() => Boolean(page.value?.page.has_more && page.value?.page.next_before_id));
const formatTime = (value?: string | null) => value ? new Date(value).toLocaleString() : "-";
const translateUsageValue = (scope: "runStatuses" | "matchStatuses" | "executionStatuses" | "identityModes", value: string) =>
t(`admin.shippingOrderProfiles.versionCenter.usage.${scope}.${value}`, value);
const loadErrorMessage = (error: unknown) => {
if (error instanceof BusinessError && [502, 503, 504].includes(error.status || 0)) {
return t("admin.shippingOrderProfiles.versionCenter.serviceUnavailable");
}
return error instanceof BusinessError
? error.message
: t("admin.shippingOrderProfiles.versionCenter.usage.loadFailed");
};
const load = async () => {
loading.value = true;
errorMessage.value = "";
try {
page.value = await listOrderDocumentProfileUsages(props.detail.id, {
beforeId: activeBeforeId.value,
limit: 20,
});
} catch (error) {
page.value = null;
errorMessage.value = loadErrorMessage(error);
} finally {
loading.value = false;
}
};
const loadNext = async () => {
if (!page.value?.page.next_before_id) return;
cursorStack.value.push(activeBeforeId.value);
activeBeforeId.value = page.value.page.next_before_id;
await load();
};
const loadPrevious = async () => {
if (!cursorStack.value.length) return;
activeBeforeId.value = cursorStack.value.pop() ?? null;
await load();
};
const openDiagnostic = (item: OrderProfileUsageRow) => {
void router.push({
name: item.diagnostic_entry.route_name,
query: {
runNo: item.diagnostic_entry.run_no,
},
});
};
watch(
() => props.detail.id,
() => {
activeBeforeId.value = null;
cursorStack.value = [];
void load();
},
{ immediate: true },
);
</script>
<template>
<section class="usage-panel">
<div class="toolbar">
<div>
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.usage.title") }}</h3>
<p>{{ t("admin.shippingOrderProfiles.versionCenter.usage.subtitle") }}</p>
</div>
<button type="button" class="ghost-button" :disabled="loading" @click="load">
{{ t("admin.shippingOrderProfiles.versionCenter.usage.refresh") }}
</button>
</div>
<div v-if="loading" class="state-card">
{{ t("admin.shippingOrderProfiles.versionCenter.usage.loading") }}
</div>
<div v-else-if="errorMessage" class="state-card error-card">
<p>{{ errorMessage }}</p>
<button type="button" class="btn-secondary btn-sm" @click="load">
{{ t("admin.shippingOrderProfiles.versionCenter.retry") }}
</button>
</div>
<div v-else-if="!page?.items.length" class="state-card">
{{ t("admin.shippingOrderProfiles.versionCenter.usage.empty") }}
</div>
<div v-else class="table-wrapper">
<table>
<thead>
<tr>
<th>{{ t("admin.shippingOrderProfiles.versionCenter.usage.columns.runNo") }}</th>
<th>{{ t("admin.shippingOrderProfiles.versionCenter.usage.columns.document") }}</th>
<th>{{ t("admin.shippingOrderProfiles.versionCenter.usage.columns.matchStatus") }}</th>
<th>{{ t("admin.shippingOrderProfiles.versionCenter.usage.columns.executionStatus") }}</th>
<th>{{ t("admin.shippingOrderProfiles.versionCenter.usage.columns.identityMode") }}</th>
<th>{{ t("admin.shippingOrderProfiles.versionCenter.usage.columns.autoCreateApproved") }}</th>
<th>{{ t("admin.shippingOrderProfiles.versionCenter.usage.columns.createdAt") }}</th>
<th>{{ t("admin.shippingOrderProfiles.versionCenter.usage.columns.reasonCodes") }}</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="item in page.items" :key="item.route_decision_id">
<td>
<div class="cell-title">{{ item.run_no }}</div>
<small>{{ translateUsageValue("runStatuses", item.run_status) }}</small>
</td>
<td>
<div class="cell-title">{{ item.document_label }}</div>
<small>#{{ item.unit_position + 1 }}</small>
</td>
<td>{{ translateUsageValue("matchStatuses", item.match_status) }}</td>
<td>{{ translateUsageValue("executionStatuses", item.execution_status) }}</td>
<td>{{ translateUsageValue("identityModes", item.identity_match_mode) }}</td>
<td>
{{
item.auto_create_approved == null
? "-"
: t(item.auto_create_approved
? "admin.shippingOrderProfiles.versionCenter.usage.yes"
: "admin.shippingOrderProfiles.versionCenter.usage.no")
}}
</td>
<td>{{ formatTime(item.created_at) }}</td>
<td>
<span v-if="item.reason_codes.length">{{ item.reason_codes.join(", ") }}</span>
<span v-else>-</span>
</td>
<td>
<button type="button" class="link-button" @click="openDiagnostic(item)">
{{ t("admin.shippingOrderProfiles.versionCenter.usage.openDiagnostic") }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="pager">
<button type="button" class="ghost-button" :disabled="loading || !hasPrevious" @click="loadPrevious">
{{ t("admin.shippingOrderProfiles.versionCenter.usage.previous") }}
</button>
<button type="button" class="ghost-button" :disabled="loading || !hasNext" @click="loadNext">
{{ t("admin.shippingOrderProfiles.versionCenter.usage.next") }}
</button>
</div>
</section>
</template>
<style scoped>
.usage-panel,
.toolbar,
.table-wrapper,
.state-card {
border: 1px solid #e2e8f0;
border-radius: 1rem;
background: #fff;
}
.usage-panel {
display: grid;
gap: 0.9rem;
}
.toolbar,
.state-card,
.table-wrapper {
padding: 0.95rem 1rem;
}
.toolbar,
.pager {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 0.8rem;
}
.toolbar h3 {
margin: 0;
color: #0f172a;
}
.toolbar p {
margin: 0.25rem 0 0;
color: #64748b;
font-size: 0.75rem;
}
.ghost-button,
.link-button {
border: 1px solid #cbd5e1;
border-radius: 0.75rem;
background: #fff;
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
}
.link-button {
color: #2563eb;
}
.table-wrapper {
overflow-x: auto;
}
table {
width: 100%;
min-width: 980px;
border-collapse: collapse;
font-size: 0.84rem;
}
thead {
background: #f8fafc;
color: #64748b;
font-size: 0.75rem;
}
th,
td {
padding: 0.75rem;
border-bottom: 1px solid #e2e8f0;
text-align: left;
vertical-align: top;
}
tbody tr:last-child td {
border-bottom: 0;
}
.cell-title {
color: #0f172a;
font-weight: 600;
}
td small {
color: #64748b;
}
.error-card {
color: #b91c1c;
}
@media (max-width: 720px) {
.toolbar,
.pager {
display: grid;
}
}
</style>
@@ -0,0 +1,442 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileVersionDiff.vue
用途:展示订单模板版本中心的服务端语义 diff。
依赖:版本中心 diff API、路由 query、版本摘要列表。
逻辑:始终由服务端计算差异;前端只负责选择对比版本、呈现 summary 和折叠原始 JSON 快照。
-->
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import { BusinessError } from "@/shared/api/client";
import { getOrderDocumentProfileDiff } from "@/features/admin/api/shipping-order-document-profile.api";
import type {
OrderProfileVersionDiff,
OrderProfileVersionDiffChange,
OrderProfileVersionDiffItem,
OrderProfileVersionSummary,
ShippingOrderDocumentProfile,
} from "@/features/admin/types/shipping-order-document-profile.types";
const props = defineProps<{
detail: ShippingOrderDocumentProfile;
versions: OrderProfileVersionSummary[];
}>();
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const loading = ref(false);
const errorMessage = ref("");
const diff = ref<OrderProfileVersionDiff | null>(null);
const explicitAgainstProfileId = computed<number | null>(() => {
const raw = Number(route.query.againstProfileId || 0);
return Number.isFinite(raw) && raw > 0 ? raw : null;
});
const comparableVersions = computed(() =>
props.versions.filter((item) => item.id !== props.detail.id),
);
const changedItems = computed(() =>
(diff.value?.items || []).filter((item) => item.change_type !== "unchanged"),
);
const selectedAgainstProfileId = computed<number | null>(() =>
explicitAgainstProfileId.value ?? diff.value?.compare_profile?.id ?? null,
);
const comparisonTargetLabel = computed(() => {
const target = comparableVersions.value.find((item) => item.id === selectedAgainstProfileId.value)
|| diff.value?.compare_profile
|| null;
if (!target) {
return t("admin.shippingOrderProfiles.versionCenter.diff.initialVersion");
}
return `v${target.version} · ${t(`admin.shippingOrderProfiles.versionCenter.status.${target.status === "draft" ? "currentDraft" : target.status === "published" ? "currentPublished" : "retired"}`)}`;
});
const entityTypeLabel = (item: OrderProfileVersionDiffItem) =>
t(`admin.shippingOrderProfiles.versionCenter.diff.entityType.${item.entity_type}`);
const changeTypeLabel = (value: OrderProfileVersionDiffItem["change_type"]) =>
t(`admin.shippingOrderProfiles.versionCenter.diff.changeType.${value}`);
const changeLabel = (change: OrderProfileVersionDiffChange) => change.key;
const loadErrorMessage = (error: unknown) => {
if (error instanceof BusinessError && [502, 503, 504].includes(error.status || 0)) {
return t("admin.shippingOrderProfiles.versionCenter.serviceUnavailable");
}
return error instanceof BusinessError
? error.message
: t("admin.shippingOrderProfiles.versionCenter.diff.loadFailed");
};
const valueText = (value: unknown) => {
if (value === null || value === undefined || value === "") {
return t("admin.shippingOrderProfiles.versionCenter.diff.empty");
}
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
return String(value);
}
try {
return JSON.stringify(value, null, 2);
} catch {
return String(value);
}
};
const syncAgainstProfileId = (againstProfileId: number | null) => {
const query = { ...route.query };
if (againstProfileId) {
query.againstProfileId = String(againstProfileId);
} else {
delete query.againstProfileId;
}
void router.replace({ query });
};
const handleAgainstChange = (event: Event) => {
const value = Number((event.target as HTMLSelectElement).value || 0);
syncAgainstProfileId(Number.isFinite(value) && value > 0 ? value : null);
};
const load = async () => {
loading.value = true;
errorMessage.value = "";
try {
diff.value = await getOrderDocumentProfileDiff(props.detail.id, explicitAgainstProfileId.value);
} catch (error) {
diff.value = null;
errorMessage.value = loadErrorMessage(error);
} finally {
loading.value = false;
}
};
watch(
() => [props.detail.id, explicitAgainstProfileId.value],
() => {
void load();
},
{ immediate: true },
);
</script>
<template>
<section class="diff-panel">
<div class="toolbar">
<div>
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.diff.title") }}</h3>
<p>{{ t("admin.shippingOrderProfiles.versionCenter.diff.subtitle") }}</p>
</div>
<label class="compare-select">
<span>{{ t("admin.shippingOrderProfiles.versionCenter.diff.compareTarget") }}</span>
<select
class="select-field"
:value="explicitAgainstProfileId || ''"
@change="handleAgainstChange"
>
<option value="">{{ t("admin.shippingOrderProfiles.versionCenter.diff.defaultPrevious") }}</option>
<option
v-for="item in comparableVersions"
:key="item.id"
:value="item.id"
>
v{{ item.version }} · {{ t(`admin.shippingOrderProfiles.versionCenter.status.${item.status === "draft" ? "currentDraft" : item.status === "published" ? "currentPublished" : "retired"}`) }}
</option>
</select>
</label>
</div>
<div v-if="loading" class="state-card">
{{ t("admin.shippingOrderProfiles.versionCenter.diff.loading") }}
</div>
<div v-else-if="errorMessage" class="state-card error-card">
<p>{{ errorMessage }}</p>
<button type="button" class="btn-secondary btn-sm" @click="load">
{{ t("admin.shippingOrderProfiles.versionCenter.retry") }}
</button>
</div>
<template v-else-if="diff">
<div class="summary-bar">
<span class="summary-target">{{ t("admin.shippingOrderProfiles.versionCenter.diff.comparedWith", { target: comparisonTargetLabel }) }}</span>
<span class="summary-pill added">{{ t("admin.shippingOrderProfiles.versionCenter.diff.summary.added", { count: diff.summary.added }) }}</span>
<span class="summary-pill removed">{{ t("admin.shippingOrderProfiles.versionCenter.diff.summary.removed", { count: diff.summary.removed }) }}</span>
<span class="summary-pill modified">{{ t("admin.shippingOrderProfiles.versionCenter.diff.summary.modified", { count: diff.summary.modified }) }}</span>
<span class="summary-pill unchanged">{{ t("admin.shippingOrderProfiles.versionCenter.diff.summary.unchanged", { count: diff.summary.unchanged }) }}</span>
</div>
<div v-if="!changedItems.length" class="state-card">
{{ t("admin.shippingOrderProfiles.versionCenter.diff.noChanges") }}
</div>
<article
v-for="item in changedItems"
:key="`${item.entity_type}:${item.entity_id}:${item.parent_id || ''}`"
class="diff-item"
:class="item.change_type"
>
<header>
<div>
<p>{{ entityTypeLabel(item) }}</p>
<h4>{{ item.label }}</h4>
</div>
<span class="change-type">{{ changeTypeLabel(item.change_type) }}</span>
</header>
<dl v-if="item.changes.length" class="change-list">
<div
v-for="change in item.changes"
:key="change.key"
>
<dt><code>{{ changeLabel(change) }}</code></dt>
<dd>
<template v-if="change.kind === 'set'">
<div class="change-pair"><del>{{ valueText(change.before) }}</del><ins>{{ valueText(change.after) }}</ins></div>
<small v-if="change.added?.length">{{ t("admin.shippingOrderProfiles.versionCenter.diff.addedValues", { values: change.added.join(', ') }) }}</small>
<small v-if="change.removed?.length">{{ t("admin.shippingOrderProfiles.versionCenter.diff.removedValues", { values: change.removed.join(', ') }) }}</small>
<small v-if="change.order_changed">{{ t("admin.shippingOrderProfiles.versionCenter.diff.orderChanged") }}</small>
</template>
<template v-else>
<div class="change-pair"><del>{{ valueText(change.before) }}</del><ins>{{ valueText(change.after) }}</ins></div>
</template>
</dd>
</div>
</dl>
<details class="raw-json">
<summary>{{ t("admin.shippingOrderProfiles.versionCenter.diff.rawJson") }}</summary>
<div class="raw-json-grid">
<section>
<h5>{{ t("admin.shippingOrderProfiles.versionCenter.diff.beforeSnapshot") }}</h5>
<pre>{{ valueText(item.before_snapshot) }}</pre>
</section>
<section>
<h5>{{ t("admin.shippingOrderProfiles.versionCenter.diff.afterSnapshot") }}</h5>
<pre>{{ valueText(item.after_snapshot) }}</pre>
</section>
</div>
</details>
</article>
</template>
</section>
</template>
<style scoped>
.diff-panel,
.toolbar,
.summary-bar,
.diff-item,
.state-card {
border: 1px solid #e2e8f0;
border-radius: 1rem;
background: #fff;
}
.diff-panel {
display: grid;
gap: 0.9rem;
}
.toolbar,
.summary-bar,
.state-card,
.diff-item {
padding: 0.95rem 1rem;
}
.toolbar {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
}
.toolbar h3,
.diff-item h4,
.raw-json h5 {
margin: 0;
color: #0f172a;
}
.toolbar p,
.diff-item header p {
margin: 0 0 0.3rem;
color: #64748b;
font-size: 0.75rem;
}
.compare-select {
display: grid;
gap: 0.35rem;
color: #475569;
font-size: 0.75rem;
}
.compare-select .select-field {
min-width: 220px;
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
}
.summary-bar {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
align-items: center;
}
.summary-target {
margin-right: 0.5rem;
color: #334155;
font-size: 0.875rem;
}
.summary-pill,
.change-type {
border-radius: 999px;
padding: 0.2rem 0.55rem;
font-size: 0.75rem;
}
.summary-pill.added,
.diff-item.added .change-type {
background: #dcfce7;
color: #166534;
}
.summary-pill.removed,
.diff-item.removed .change-type {
background: #fee2e2;
color: #b91c1c;
}
.summary-pill.modified,
.diff-item.modified .change-type {
background: #dbeafe;
color: #1d4ed8;
}
.summary-pill.unchanged,
.diff-item.unchanged .change-type {
background: #e2e8f0;
color: #475569;
}
.diff-item {
border-left-width: 4px;
}
.diff-item.added { border-left-color: #22c55e; }
.diff-item.removed { border-left-color: #ef4444; }
.diff-item.modified { border-left-color: #3b82f6; }
.diff-item header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
}
.change-list {
display: grid;
gap: 0.8rem;
margin: 0.95rem 0 0;
}
.change-list div {
display: grid;
grid-template-columns: minmax(180px, 260px) minmax(0, 1fr);
gap: 0.75rem;
}
.change-list dt {
color: #475569;
font-size: 0.75rem;
}
.change-list dd {
display: grid;
gap: 0.3rem;
margin: 0;
color: #334155;
font-size: 0.82rem;
overflow-wrap: anywhere;
}
.change-pair {
display: grid;
gap: 0.25rem;
}
del {
color: #b91c1c;
text-decoration: line-through;
}
ins {
color: #15803d;
text-decoration: none;
}
.change-list small {
color: #64748b;
}
.raw-json {
margin-top: 0.9rem;
border-top: 1px solid #e2e8f0;
padding-top: 0.9rem;
}
.raw-json summary {
cursor: pointer;
color: #334155;
font-size: 0.8rem;
font-weight: 600;
}
.raw-json-grid {
display: grid;
gap: 0.85rem;
margin-top: 0.75rem;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.raw-json pre {
margin: 0.45rem 0 0;
border-radius: 0.75rem;
background: #0f172a;
padding: 0.75rem;
color: #e2e8f0;
font-size: 0.72rem;
line-height: 1.45;
overflow: auto;
white-space: pre-wrap;
}
.error-card {
color: #b91c1c;
}
@media (max-width: 900px) {
.toolbar,
.diff-item header,
.change-list div,
.raw-json-grid {
grid-template-columns: 1fr;
}
.toolbar,
.diff-item header {
display: grid;
}
.compare-select .select-field {
min-width: 0;
}
}
</style>
@@ -0,0 +1,356 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileVersionOverview.vue
用途:展示模板版本详情的配置概览页签。
依赖:订单模板详情 DTO、i18n。
逻辑:仅渲染结构化摘要与冻结证据状态,不请求 PDF、Layout payload 或盲测真值。
-->
<script setup lang="ts">
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import type { ShippingOrderDocumentProfile } from "@/features/admin/types/shipping-order-document-profile.types";
const props = defineProps<{
detail: ShippingOrderDocumentProfile;
}>();
const { t } = useI18n();
/** 末端值源证据由服务端 adapter 作为可选摘要投影,公共概览不判断模板模式。 */
const valueSourceIdentity = computed(() => props.detail.value_source_identity || null);
const formatDateTime = (value?: string | null) =>
value ? new Date(value).toLocaleString() : "-";
const statusLabel = computed(() => {
if (props.detail.status === "draft") {
return t("admin.shippingOrderProfiles.versionCenter.status.currentDraft");
}
if (props.detail.status === "published") {
return t("admin.shippingOrderProfiles.versionCenter.status.currentPublished");
}
return t("admin.shippingOrderProfiles.versionCenter.status.retired");
});
const statusClass = computed(() => `meta-chip--${props.detail.status}`);
const frozenEvidenceLabel = computed(() => {
const status = props.detail.frozen_evidence?.status || "pending";
return t(`admin.shippingOrderProfiles.versionCenter.frozenEvidence.${status}`);
});
const testStatusLabel = computed(() => {
const status = props.detail.test_summary?.status || "missing";
return t(`admin.shippingOrderProfiles.versionCenter.testStatus.${status}`);
});
</script>
<template>
<section class="overview">
<div class="hero-card">
<div class="hero-row">
<div>
<p class="eyebrow">{{ t("admin.shippingOrderProfiles.versionCenter.eyebrow") }}</p>
<h2>v{{ detail.version }} · {{ statusLabel }}</h2>
<p class="profile-identity">{{ detail.profile_code }}</p>
</div>
<div class="hero-meta">
<span class="meta-chip meta-chip--status" :class="statusClass">{{ statusLabel }}</span>
<span class="meta-chip">
{{ t("admin.shippingOrderProfiles.versionCenter.schemaVersion") }}
{{ detail.schema_summary?.version ?? "-" }}
</span>
<span class="meta-chip">
{{ t("admin.shippingOrderProfiles.versionCenter.sampleCount", { count: detail.sample_summary?.sample_count || 0 }) }}
</span>
</div>
</div>
<p v-if="detail.change_note" class="change-note">{{ detail.change_note }}</p>
</div>
<div class="summary-grid">
<article class="summary-card">
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.definitionStats") }}</h3>
<dl>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.tableRegions") }}</dt>
<dd>{{ detail.definition_stats?.table_region_count || 0 }}</dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.headerLayouts") }}</dt>
<dd>{{ detail.definition_stats?.header_layout_count || 0 }}</dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.lineLayouts") }}</dt>
<dd>{{ detail.definition_stats?.line_layout_count || 0 }}</dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.orderFieldLayouts") }}</dt>
<dd>{{ detail.definition_stats?.order_field_layout_count || 0 }}</dd>
</div>
</dl>
</article>
<article v-if="valueSourceIdentity" class="summary-card">
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.xfaStructureIdentity") }}</h3>
<dl>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.xfaTemplateChecksum") }}</dt>
<dd>{{ valueSourceIdentity.template_packet_checksum || "-" }}</dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.xfaDatasetFingerprint") }}</dt>
<dd>{{ valueSourceIdentity.dataset_structure_fingerprint || "-" }}</dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.xfaAuthoritativeCollection") }}</dt>
<dd>{{ valueSourceIdentity.has_authoritative_collection ? t("common.yes") : t("common.no") }}</dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.mirrorCollections") }}</dt>
<dd>{{ valueSourceIdentity.mirror_collection_count ?? 0 }}</dd>
</div>
</dl>
</article>
<article class="summary-card">
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.frozenEvidenceTitle") }}</h3>
<dl>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.statusLabel") }}</dt>
<dd>{{ frozenEvidenceLabel }}</dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.blindTestSuiteSampleCount") }}</dt>
<dd>{{ detail.frozen_evidence?.sample_count || 0 }}</dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.frozenSampleCount") }}</dt>
<dd>{{ detail.frozen_evidence?.frozen_sample_count || 0 }}</dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.auditReady") }}</dt>
<dd>{{ detail.frozen_evidence?.audit_ready ? t("common.yes") : t("common.no") }}</dd>
</div>
</dl>
</article>
<article class="summary-card">
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.sampleSummaryTitle") }}</h3>
<dl>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.annotationCount") }}</dt>
<dd>{{ detail.sample_summary?.annotation_count || 0 }}</dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.trainingCount") }}</dt>
<dd>{{ detail.sample_summary?.training_count || 0 }}</dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.boundBlindTestCount") }}</dt>
<dd>{{ detail.sample_summary?.blind_test_count || 0 }}</dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.firstSample") }}</dt>
<dd>{{ detail.sample_summary?.samples?.[0]?.source_filename_snapshot || "-" }}</dd>
</div>
</dl>
</article>
<article class="summary-card">
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.testSummaryTitle") }}</h3>
<dl>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.statusLabel") }}</dt>
<dd>{{ testStatusLabel }}</dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.sampleCountPlain") }}</dt>
<dd>{{ detail.test_summary?.sample_count || 0 }}</dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.approvedAt") }}</dt>
<dd>{{ formatDateTime(detail.test_summary?.approved_at) }}</dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.latestRun") }}</dt>
<dd>{{ detail.test_summary?.latest_run?.status || "-" }}</dd>
</div>
</dl>
</article>
</div>
<article class="summary-card source-card">
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.sourceVersionTitle") }}</h3>
<p v-if="detail.source_version">
{{ detail.source_version.profile_code }} · v{{ detail.source_version.version }} ·
{{ detail.source_version.status }}
</p>
<p v-else>{{ t("admin.shippingOrderProfiles.versionCenter.noSourceVersion") }}</p>
</article>
<details class="technical-details">
<summary>{{ t("admin.shippingOrderProfiles.versionCenter.technicalDetails") }}</summary>
<dl class="technical-grid">
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.publishedAt") }}</dt>
<dd>{{ formatDateTime(detail.published_at) }}</dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.retiredAt") }}</dt>
<dd>{{ formatDateTime(detail.retired_at) }}</dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.checksum") }}</dt>
<dd><code>{{ detail.checksum || "-" }}</code></dd>
</div>
<div>
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.schemaChecksum") }}</dt>
<dd><code>{{ detail.schema_summary?.checksum || "-" }}</code></dd>
</div>
</dl>
</details>
</section>
</template>
<style scoped>
.overview {
display: grid;
gap: 1rem;
}
.hero-card,
.summary-card {
border: 1px solid var(--border-default);
border-radius: 0.9rem;
background: var(--bg-surface);
padding: 1rem;
}
.hero-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
}
.eyebrow {
margin: 0 0 0.35rem;
color: var(--text-muted);
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.hero-card h2,
.summary-card h3 {
margin: 0;
color: var(--text-primary);
}
.profile-identity,
.change-note {
margin: 0.65rem 0 0;
color: var(--text-secondary);
}
.profile-identity { font-size: 0.875rem; }
.change-note {
border-left: 3px solid var(--border-default);
padding-left: 0.75rem;
}
.hero-meta {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 0.5rem;
}
.meta-chip {
border-radius: 999px;
background: var(--bg-surface-soft);
color: var(--text-secondary);
padding: 0.35rem 0.65rem;
font-size: 0.75rem;
}
.meta-chip--status {
background: var(--status-success-bg);
color: var(--status-success-fg);
}
.meta-chip--draft {
background: var(--status-warning-bg);
color: var(--status-warning-fg);
}
.meta-chip--retired {
background: var(--status-error-bg);
color: var(--status-error-fg);
}
.summary-card dl {
display: grid;
gap: 0.75rem;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
margin: 1rem 0 0;
}
.summary-card dt {
color: var(--text-muted);
font-size: 0.75rem;
}
.summary-card dd {
margin: 0.25rem 0 0;
color: var(--text-primary);
word-break: break-word;
}
.summary-grid {
display: grid;
gap: 1rem;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
}
.source-card p {
margin: 0.75rem 0 0;
color: var(--text-secondary);
}
.technical-details {
border-top: 1px solid var(--border-subtle);
padding-top: 1rem;
}
.technical-details summary {
cursor: pointer;
color: var(--text-secondary);
font-size: 0.875rem;
font-weight: 600;
}
.technical-grid {
display: grid;
gap: 0.75rem;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
margin: 0.85rem 0 0;
}
.technical-grid dt {
color: var(--text-muted);
font-size: 0.75rem;
}
.technical-grid dd {
margin: 0.25rem 0 0;
color: var(--text-secondary);
overflow-wrap: anywhere;
}
.technical-grid code {
font-size: 0.75rem;
}
</style>
@@ -0,0 +1,105 @@
/**
* features/admin/modules/shipping-order-document-profiles/components/XfaCollectionSelector.spec.ts
* 用途:断言权威集合卡片选择、证据展示与排除原因可见。
* 依赖:Vitest、@vue/test-utils、XfaCollectionSelector。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import XfaCollectionSelector from './XfaCollectionSelector.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
admin: {
shippingOrderProfiles: {
xfaWorkbench: {
collectionsTitle: '集合',
authoritativeCollection: '权威',
selectAuthoritative: '请选择',
mirrorCollections: '镜像',
rowCount: '{count} 行',
collectionEvidenceHint: '证据',
recommendedAuthoritative: '推荐权威',
selectedAuthoritative: '已选权威',
nonEmptyCoverage: '{filled}/{total} {percent}',
excludedCollections: '空集合 {count}',
emptyStructureReason: '空结构',
allCandidatesExcluded: '全部被排除',
collectionReason: {
empty_structure: '空结构',
data_description_structure: '结构描述',
},
},
},
},
},
},
});
describe('XfaCollectionSelector', () => {
it('emits authoritative path when a candidate card is selected', async () => {
const wrapper = mount(XfaCollectionSelector, {
global: { plugins: [i18n] },
props: {
candidates: [
{
path_id: 'a',
collection_path_hash: 'ha',
row_count: 1,
path_label: 'data / ITEMS / DATA',
field_names: ['MATNR', 'MENGE'],
non_empty_field_count: 2,
field_count: 2,
sample_fields: [{ field_name: 'MENGE', display_value: '30', display_policy: 'full' }],
recommended_role: 'authoritative',
},
{
path_id: 'b',
collection_path_hash: 'hb',
row_count: 1,
path_label: 'data / ITEMS1 / DATA',
field_names: ['MATNR', 'MENGE'],
non_empty_field_count: 2,
field_count: 2,
recommended_role: 'mirror',
},
],
authoritativePathId: 'a',
mirrorPathIds: [],
},
});
const radios = wrapper.findAll('input[type="radio"]');
await radios[1].setValue(true);
expect(wrapper.emitted('update:authoritativePathId')?.[0]).toEqual(['b']);
expect(wrapper.text()).toContain('data / ITEMS / DATA');
expect(wrapper.text()).toContain('MATNR');
expect(wrapper.text()).toContain('MENGE');
});
it('shows excluded reasons when no selectable candidates remain', () => {
const wrapper = mount(XfaCollectionSelector, {
global: { plugins: [i18n] },
props: {
candidates: [],
authoritativePathId: '',
mirrorPathIds: [],
excludedCandidates: [
{
path_id: 'desc',
collection_path_hash: 'hd',
row_count: 0,
path_label: 'dataDescription / ITEMS / DATA',
selectable: false,
exclusion_reasons: ['data_description_structure'],
},
],
},
});
expect(wrapper.text()).toContain('全部被排除');
expect(wrapper.text()).toContain('dataDescription / ITEMS / DATA');
expect(wrapper.text()).toContain('结构描述');
});
});
@@ -0,0 +1,198 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/XfaCollectionSelector.vue
用途:权威明细集合与镜像对账集合选择。
依赖:vue-i18n、XfaCollectionCandidate。
逻辑:以候选卡片直接展示完整路径、字段覆盖与样本证据;权威单选强制,镜像多选仅用于对账;
selectable=false 的无效集合禁选;全部候选被排除时仍展示排除原因。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { XfaCollectionCandidate } from '@/features/admin/types/shipping-order-document-profile.types';
import { listMirrorCollectionCandidates } from '../xfaProfileMapping.utils';
const props = defineProps<{
candidates: XfaCollectionCandidate[];
authoritativePathId: string;
mirrorPathIds: string[];
excludedCandidates?: XfaCollectionCandidate[];
}>();
const emit = defineEmits<{
'update:authoritativePathId': [pathId: string];
'update:mirrorPathIds': [pathIds: string[]];
}>();
const { t, te } = useI18n();
const hasSelectable = computed(() => props.candidates.some((item) => item.selectable !== false));
const selectableCandidates = computed(() => props.candidates.filter((item) => item.selectable !== false));
const hasExcludedOnly = computed(() => !hasSelectable.value && Boolean(props.excludedCandidates?.length));
const mirrors = computed(() => listMirrorCollectionCandidates(selectableCandidates.value, props.authoritativePathId));
const selectedAuthoritative = computed(() => selectableCandidates.value.find((item) => item.path_id === props.authoritativePathId));
/** 将非空率转为管理员可读百分比。 */
function percent(value?: number): string {
return `${Math.round(Number(value || 0) * 100)}%`;
}
/**
* 切换镜像集合勾选。
*/
function toggleMirror(pathId: string, checked: boolean): void {
const next = new Set(props.mirrorPathIds);
if (checked) next.add(pathId);
else next.delete(pathId);
emit('update:mirrorPathIds', [...next]);
}
/**
* 将排除/推荐原因码映射为可读文案。
* @param reasons 原因码列表
*/
function reasonLabels(reasons?: string[]): string {
return (reasons || [])
.map((code) => {
const key = `admin.shippingOrderProfiles.xfaWorkbench.collectionReason.${code}`;
return te(key) ? t(key) : code;
})
.join(' · ');
}
</script>
<template>
<section class="xfa-collections" :aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.collectionsTitle')">
<div class="collection-heading">
<strong>{{ t('admin.shippingOrderProfiles.xfaWorkbench.collectionsTitle') }}</strong>
<span>{{ t('admin.shippingOrderProfiles.xfaWorkbench.collectionEvidenceHint') }}</span>
</div>
<p v-if="hasExcludedOnly" class="empty-selectable" role="status">
{{ t('admin.shippingOrderProfiles.xfaWorkbench.allCandidatesExcluded') }}
</p>
<fieldset v-if="hasSelectable" class="auth-cards" :aria-invalid="!authoritativePathId">
<legend>{{ t('admin.shippingOrderProfiles.xfaWorkbench.authoritativeCollection') }}</legend>
<label
v-for="item in selectableCandidates"
:key="item.path_id"
class="candidate-card"
:class="{
selected: authoritativePathId === item.path_id,
recommended: item.recommended_role === 'authoritative',
disabled: item.selectable === false,
}"
>
<input
type="radio"
name="xfa-authoritative-collection"
:value="item.path_id"
:checked="authoritativePathId === item.path_id"
:disabled="item.selectable === false"
@change="emit('update:authoritativePathId', item.path_id)"
/>
<span class="candidate-body">
<span class="candidate-title">
<strong>{{ item.path_label || item.local_name }}</strong>
<span v-if="item.recommended_role === 'authoritative'" class="role-badge">
{{ t('admin.shippingOrderProfiles.xfaWorkbench.recommendedAuthoritative') }}
</span>
<span>{{ t('admin.shippingOrderProfiles.xfaWorkbench.rowCount', { count: item.row_count }) }}</span>
</span>
<small>{{ t('admin.shippingOrderProfiles.xfaWorkbench.nonEmptyCoverage', {
filled: item.non_empty_field_count || 0,
total: item.field_count || 0,
percent: percent(item.non_empty_rate),
}) }}</small>
<span class="fields">{{ (item.field_names || []).slice(0, 8).join(' · ') }}</span>
<span class="samples">
<span v-for="field in item.sample_fields || []" :key="`${item.path_id}-${field.field_name}`">
<b>{{ field.field_name }}</b> {{ field.display_value }}
</span>
</span>
</span>
</label>
</fieldset>
<article v-if="selectedAuthoritative" class="collection-card authoritative">
<header>
<div>
<strong>{{ selectedAuthoritative.path_label || selectedAuthoritative.local_name }}</strong>
<span class="role-badge">{{ t('admin.shippingOrderProfiles.xfaWorkbench.selectedAuthoritative') }}</span>
</div>
<span>{{ t('admin.shippingOrderProfiles.xfaWorkbench.rowCount', { count: selectedAuthoritative.row_count }) }}</span>
</header>
<p>{{ t('admin.shippingOrderProfiles.xfaWorkbench.nonEmptyCoverage', {
filled: selectedAuthoritative.non_empty_field_count || 0,
total: selectedAuthoritative.field_count || 0,
percent: percent(selectedAuthoritative.non_empty_rate),
}) }}</p>
<div class="sample-grid">
<span v-for="field in selectedAuthoritative.sample_fields || []" :key="field.field_name">
<b>{{ field.field_name }}</b> {{ field.display_value }}
</span>
</div>
<small>{{ (selectedAuthoritative.field_names || []).join(' · ') }}</small>
</article>
<fieldset v-if="mirrors.length" class="mirror-fieldset">
<legend>{{ t('admin.shippingOrderProfiles.xfaWorkbench.mirrorCollections') }}</legend>
<label v-for="item in mirrors" :key="item.path_id" class="mirror">
<input
type="checkbox"
:checked="mirrorPathIds.includes(item.path_id)"
@change="toggleMirror(item.path_id, ($event.target as HTMLInputElement).checked)"
/>
<span class="mirror-copy">
<strong>{{ item.path_label || item.local_name }}</strong>
<small>{{ t('admin.shippingOrderProfiles.xfaWorkbench.nonEmptyCoverage', {
filled: item.non_empty_field_count || 0,
total: item.field_count || 0,
percent: percent(item.non_empty_rate),
}) }}</small>
<span>{{ (item.sample_fields || []).map((field) => `${field.field_name} ${field.display_value}`).join(' · ') }}</span>
</span>
</label>
</fieldset>
<details v-if="excludedCandidates?.length" class="excluded" :open="hasExcludedOnly">
<summary>{{ t('admin.shippingOrderProfiles.xfaWorkbench.excludedCollections', { count: excludedCandidates.length }) }}</summary>
<ul>
<li v-for="item in excludedCandidates" :key="item.path_id">
<span>{{ item.path_label || item.local_name }}</span>
<small>{{ reasonLabels(item.exclusion_reasons || item.recommendation_reasons) || t('admin.shippingOrderProfiles.xfaWorkbench.emptyStructureReason') }}</small>
</li>
</ul>
</details>
</section>
</template>
<style scoped>
.xfa-collections { display: grid; grid-template-columns: minmax(280px, 1fr) minmax(320px, 1fr); gap: 12px 16px; align-items: start; width: 100%; }
.collection-heading { grid-column: 1 / -1; display: flex; flex-direction: column; gap: 3px; color: var(--text-primary); }
.collection-heading span { color: var(--text-muted); font-size: .82rem; }
.empty-selectable { grid-column: 1 / -1; margin: 0; padding: 10px 12px; border: 1px solid var(--status-warning-border); border-radius: var(--radius-control); background: var(--status-warning-bg); color: var(--status-warning-fg); }
.auth-cards { grid-column: 1 / -1; display: grid; gap: 10px; margin: 0; padding: 0; border: 0; }
.auth-cards[aria-invalid='true'] .candidate-card { border-color: var(--status-error-border); }
.candidate-card { display: flex; gap: 10px; align-items: flex-start; padding: 12px; border: 1px solid var(--border-default); border-radius: var(--radius-control); background: var(--bg-surface); cursor: pointer; }
.candidate-card.selected, .candidate-card.recommended.selected { border-color: var(--status-info-border); background: var(--status-info-bg); }
.candidate-body { display: flex; min-width: 0; flex: 1; flex-direction: column; gap: 4px; color: var(--text-secondary); }
.candidate-title { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; color: var(--text-primary); }
.role-badge { color: var(--status-info-fg); font-size: .75rem; }
.fields, .samples { color: var(--text-muted); font-size: .78rem; }
.samples { display: flex; flex-wrap: wrap; gap: 6px 12px; }
.samples b { color: var(--text-primary); }
.collection-card, .mirror-fieldset, .excluded { border: 1px solid var(--border-default); border-radius: var(--radius-control); padding: 12px; background: var(--bg-surface); }
.collection-card.authoritative { border-color: var(--status-info-border); background: var(--status-info-bg); }
.collection-card header { display: flex; justify-content: space-between; gap: 12px; color: var(--text-primary); }
.collection-card header div { display: flex; align-items: center; gap: 8px; }
.collection-card p, .collection-card small { color: var(--text-muted); }
.sample-grid { display: flex; flex-wrap: wrap; gap: 6px 12px; margin: 8px 0; color: var(--text-secondary); font-size: .82rem; }
.sample-grid b { color: var(--text-primary); }
.mirror-fieldset { grid-column: 1 / -1; }
.mirror { display: flex; gap: 10px; align-items: flex-start; padding: 8px 0; }
.mirror-copy { display: flex; flex-direction: column; gap: 2px; color: var(--text-secondary); }
.mirror-copy small, .mirror-copy span { color: var(--text-muted); font-size: .78rem; }
.excluded { grid-column: 1 / -1; color: var(--text-secondary); }
.excluded ul { margin: 8px 0 0; padding-left: 18px; }
.excluded li { display: flex; flex-wrap: wrap; gap: 10px; }
.excluded small { color: var(--status-warning-fg); }
@media (max-width: 900px) { .xfa-collections { grid-template-columns: 1fr; } }
</style>
@@ -0,0 +1,197 @@
/**
* features/admin/modules/shipping-order-document-profiles/components/XfaDatasetTree.spec.ts
* 用途:断言 XFA 字段树渲染与 select-path 事件。
* 依赖:Vitest、@vue/test-utils、XfaDatasetTree。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import XfaDatasetTree from './XfaDatasetTree.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
admin: {
shippingOrderProfiles: {
xfaWorkbench: {
treeTitle: '树', searchPaths: '搜索', collectionBadge: '集合', treeEmpty: '空',
},
xfaSplit: { addRule: '新增规则', ruleLabel: '规则 {index}', unnamedRule: '未命名规则', deleteRule: '删除' },
},
},
common: { edit: '编辑' },
},
},
});
describe('XfaDatasetTree', () => {
it('emits select-path when a tree node button is clicked', async () => {
const wrapper = mount(XfaDatasetTree, {
global: { plugins: [i18n] },
props: {
tree: {
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
is_leaf: false,
children: [{
path_id: 'leaf', local_name: 'EBELN', data_path_hash: 'h2', depth: 1, cardinality: 'one',
is_leaf: true, sample_value_display: '4510000227', display_policy: 'full',
}],
},
},
});
const nodes = wrapper.findAll('[role="treeitem"]');
expect(nodes.length).toBeGreaterThan(0);
await nodes[nodes.length - 1].trigger('click');
expect(wrapper.emitted('select-path')?.[0]).toEqual(['leaf', true]);
});
it('exposes tree levels and supports collapse keyboard navigation', async () => {
const wrapper = mount(XfaDatasetTree, {
global: { plugins: [i18n] },
props: {
tree: {
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
is_leaf: false, children: [{
path_id: 'leaf', local_name: 'WAERS', data_path_hash: 'h2', depth: 1, cardinality: 'one',
is_leaf: true, sample_value_display: 'USD', display_policy: 'full',
}],
},
},
});
const root = wrapper.find('[data-xfa-path-id="root"]');
expect(root.attributes('aria-level')).toBe('1');
expect(root.attributes('aria-expanded')).toBe('true');
await root.trigger('keydown', { key: 'ArrowLeft' });
expect(root.attributes('aria-expanded')).toBe('false');
expect(wrapper.text()).not.toContain('USD');
});
it('selects the focused node with Enter and Space', async () => {
const wrapper = mount(XfaDatasetTree, {
global: { plugins: [i18n] },
props: {
tree: {
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
is_leaf: false, children: [{
path_id: 'leaf', local_name: 'WAERS', data_path_hash: 'h2', depth: 1, cardinality: 'one',
is_leaf: true, sample_value_display: 'USD', display_policy: 'full',
}],
},
},
});
const leaf = wrapper.find('[data-xfa-path-id="leaf"]');
await leaf.trigger('keydown', { key: 'Enter' });
await leaf.trigger('keydown', { key: ' ' });
expect(wrapper.emitted('select-path')).toEqual([['leaf', true], ['leaf', true]]);
});
it('emits add-rule when the leaf add button is clicked', async () => {
const wrapper = mount(XfaDatasetTree, {
global: { plugins: [i18n] },
props: {
selectedPathId: 'leaf',
tree: {
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
is_leaf: false, children: [{
path_id: 'leaf', local_name: 'MATNR', data_path_hash: 'h2', depth: 1, cardinality: 'one',
is_leaf: true, sample_value_display: 'TEMP-S', display_policy: 'full',
}],
},
},
});
await wrapper.find('[data-xfa-path-id="leaf"] .add-rule').trigger('click');
expect(wrapper.emitted('add-rule')).toEqual([['leaf']]);
expect(wrapper.emitted('select-path')).toBeUndefined();
});
it('selects a rule row without editing and uses explicit edit and delete controls', async () => {
const wrapper = mount(XfaDatasetTree, {
global: { plugins: [i18n] },
props: {
tree: {
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
is_leaf: false, children: [{
path_id: 'leaf', local_name: 'MATNR', data_path_hash: 'h2', depth: 1, cardinality: 'one',
is_leaf: true, sample_value_display: 'TEMP-S', display_policy: 'full',
}],
},
splitRuleSets: [{
rule_id: 'set-1', rule_version: 1, source_path_id: 'leaf', source_field_code: 'MATNR', strategy: 'pipeline',
rules: [{
rule_id: 'rule-1', order: 1, stages: [{ stage_id: 'stage-1', type: 'select_line', line_index: 1 }],
segment: { segment_id: 'seg-1', segment_code: 'customer_part', display_name: '客户料号', handling: 'evidence_only' },
}],
}],
},
});
await wrapper.find('.xfa-tree__rule-main').trigger('click');
expect(wrapper.emitted('select-rule')).toEqual([['leaf', 'rule-1']]);
expect(wrapper.emitted('edit-rule')).toBeUndefined();
await wrapper.find('.rule-edit').trigger('click');
expect(wrapper.emitted('edit-rule')).toEqual([['leaf', 'rule-1']]);
await wrapper.find('.rule-delete').trigger('click');
expect(wrapper.emitted('delete-rule')).toEqual([['leaf', 'rule-1']]);
});
it('indents rule nodes beyond their deep parent field', () => {
const wrapper = mount(XfaDatasetTree, {
global: { plugins: [i18n] },
props: {
tree: {
path_id: 'root', local_name: 'datasets', data_path_hash: 'h0', depth: 0, cardinality: 'one', is_leaf: false,
children: [{
path_id: 'data', local_name: 'data', data_path_hash: 'h1', depth: 1, cardinality: 'one', is_leaf: false,
children: [{
path_id: 'items', local_name: 'ITEMS', data_path_hash: 'h2', depth: 2, cardinality: 'one', is_leaf: false,
children: [{
path_id: 'leaf', local_name: 'MATNR', data_path_hash: 'h3', depth: 3, cardinality: 'one', is_leaf: true,
}],
}],
}],
},
splitRuleSets: [{
rule_id: 'set-1', rule_version: 1, source_path_id: 'leaf', source_field_code: 'MATNR', strategy: 'pipeline',
rules: [{
rule_id: 'rule-1', order: 1, stages: [{ stage_id: 'stage-1', type: 'select_line', line_index: 1 }],
segment: { segment_id: 'seg-1', segment_code: 'customer_part', display_name: '客户料号', handling: 'evidence_only' },
}],
}],
},
});
const parentPadding = Number.parseFloat(wrapper.find('[data-xfa-path-id="leaf"]').attributes('style').match(/padding-left:\s*([\d.]+)px/)?.[1] || '0');
const ruleIndentValue = Number.parseFloat(wrapper.find('.xfa-tree__rules').attributes('style').match(/--rule-indent:\s*([\d.]+)px/)?.[1] || '0');
expect(ruleIndentValue).toBeGreaterThan(parentPadding);
});
it('hides rule edit controls when readonly is true', async () => {
const wrapper = mount(XfaDatasetTree, {
global: { plugins: [i18n] },
props: {
readonly: true,
selectedPathId: 'leaf',
tree: {
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
is_leaf: false, children: [{
path_id: 'leaf', local_name: 'MATNR', data_path_hash: 'h2', depth: 1, cardinality: 'one',
is_leaf: true, sample_value_display: 'TEMP-S', display_policy: 'full',
}],
},
splitRuleSets: [{
rule_id: 'set-1', rule_version: 1, source_path_id: 'leaf', source_field_code: 'MATNR', strategy: 'pipeline',
rules: [{
rule_id: 'rule-1', order: 1, stages: [{ stage_id: 'stage-1', type: 'select_line', line_index: 1 }],
segment: { segment_id: 'seg-1', segment_code: 'customer_part', display_name: '客户料号', handling: 'evidence_only' },
}],
}],
},
});
expect(wrapper.find('.add-rule').exists()).toBe(false);
expect(wrapper.find('.rule-edit').exists()).toBe(false);
expect(wrapper.find('.rule-delete').exists()).toBe(false);
await wrapper.find('[data-xfa-path-id="leaf"]').trigger('click');
expect(wrapper.emitted('select-path')?.[0]).toEqual(['leaf', true]);
});
});
@@ -0,0 +1,271 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/XfaDatasetTree.vue
用途:XFA 受控数据树;主工作台用于绑定导航,高级诊断抽屉内只读展示。
依赖:vue-i18n、xfaProfileMapping.utils。
逻辑:支持展开折叠、方向键导航与完整样本值展示;readonly 时隐藏增删改规则动作。
-->
<script setup lang="ts">
import { computed, nextTick, ref } from 'vue';
import { ChevronDown, ChevronRight, Pencil } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import type { XfaFieldTreeNode } from '@/features/admin/types/shipping-order-document-profile.types';
import type { XfaSplitRuleSet } from '@/features/admin/types/shipping-order-document-profile.types';
import {
buildXfaPathLabel,
filterXfaTreeNodes,
flattenXfaTreeNodes,
type XfaFlatTreeNode,
} from '../xfaProfileMapping.utils';
const props = defineProps<{
tree: XfaFieldTreeNode | null;
selectedPathId?: string | null;
selectedRuleId?: string | null;
mappedPathIds?: string[];
splitRuleSets?: XfaSplitRuleSet[];
/** 为 true 时隐藏新增/编辑/删除规则操作,仅保留选择与诊断。 */
readonly?: boolean;
}>();
const emit = defineEmits<{
'select-path': [pathId: string, isLeaf: boolean];
'add-rule': [pathId: string];
'select-rule': [pathId: string, ruleId: string];
'edit-rule': [pathId: string, ruleId: string];
'delete-rule': [pathId: string, ruleId: string];
'move-rule': [pathId: string, ruleId: string, direction: -1 | 1];
}>();
const { t } = useI18n();
const query = ref('');
const flat = computed(() => flattenXfaTreeNodes(props.tree || undefined));
const collapsed = ref(new Set<string>());
const focusedPathId = ref('');
const isReadonly = computed(() => Boolean(props.readonly));
const visible = computed(() => {
const filtered = filterXfaTreeNodes(flat.value, query.value);
if (query.value.trim()) return filtered;
return filtered.filter((node) => {
let parent = node.parentPathId;
while (parent) {
if (collapsed.value.has(parent)) return false;
parent = flat.value.find((item) => item.pathId === parent)?.parentPathId;
}
return true;
});
});
const mapped = computed(() => new Set(props.mappedPathIds || []));
const rulesFor = (pathId: string) => props.splitRuleSets?.find((item) => item.source_path_id === pathId)?.rules || [];
/**
* 选择树节点;叶子才用于字段绑定。
* @param pathId 分析 path_id
* @param isLeaf 是否叶子
*/
function onSelect(pathId: string, isLeaf: boolean): void {
focusedPathId.value = pathId;
emit('select-path', pathId, isLeaf);
}
/** 切换非叶子节点展开状态。 */
function toggle(pathId: string): void {
const next = new Set(collapsed.value);
if (next.has(pathId)) next.delete(pathId);
else next.add(pathId);
collapsed.value = next;
}
/**
* 完整可读路径(节点名链路),用于 title / 无障碍标签。
* @param node 扁平树节点
*/
function pathTitle(node: XfaFlatTreeNode): string {
return buildXfaPathLabel(node.pathId, flat.value);
}
/**
* 叶子节点的父路径提示,便于区分同名字段来源。
* @param node 扁平树节点
*/
function parentPathHint(node: XfaFlatTreeNode): string {
const full = buildXfaPathLabel(node.pathId, flat.value);
const parts = full.split('/').filter(Boolean);
if (parts.length <= 1) return '';
return parts.slice(0, -1).join(' / ');
}
/** 使用完整深度缩进,确保任意层级都能辨认父子关系。 */
function nodeIndent(node: XfaFlatTreeNode): string {
return `${8 + node.depth * 14}px`;
}
/** 当前层级导轨位置与完整缩进同步。 */
function nodeGuide(node: XfaFlatTreeNode): string {
return `${8 + Math.max(node.depth - 1, 0) * 14}px`;
}
/**
* 规则作为叶子字段的下一级虚拟节点,缩进必须基于父字段真实深度计算。
* @param node 拆分规则所属的原始叶子节点
* @returns 规则列表左内边距及导轨位置
*/
function ruleIndent(node: XfaFlatTreeNode): Record<string, string> {
const parentIndent = 8 + node.depth * 14;
return {
'--rule-indent': `${parentIndent + 30}px`,
'--rule-guide-offset': `${parentIndent + 18}px`,
};
}
/**
* 实现 WAI-ARIA Tree 方向键、Home/End 与父子导航。
* @param event 键盘事件
* @param pathId 当前节点 path_id
*/
async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
const index = visible.value.findIndex((item) => item.pathId === pathId);
const current = visible.value[index];
if (!current) return;
let target: string | undefined;
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
onSelect(pathId, current.isLeaf);
return;
}
if (event.key === 'ArrowDown') target = visible.value[index + 1]?.pathId;
else if (event.key === 'ArrowUp') target = visible.value[index - 1]?.pathId;
else if (event.key === 'Home') target = visible.value[0]?.pathId;
else if (event.key === 'End') target = visible.value[visible.value.length - 1]?.pathId;
else if (event.key === 'ArrowRight' && !current.isLeaf) {
if (collapsed.value.has(pathId)) toggle(pathId);
else target = visible.value[index + 1]?.parentPathId === pathId ? visible.value[index + 1]?.pathId : undefined;
} else if (event.key === 'ArrowLeft') {
if (!current.isLeaf && !collapsed.value.has(pathId)) toggle(pathId);
else target = current.parentPathId;
} else return;
event.preventDefault();
if (target) {
focusedPathId.value = target;
await nextTick();
document.querySelector<HTMLElement>(`[data-xfa-path-id="${CSS.escape(target)}"]`)?.focus();
}
}
</script>
<template>
<section class="xfa-tree" :aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.treeTitle')">
<label class="xfa-tree__search">
<span class="sr-only">{{ t('admin.shippingOrderProfiles.xfaWorkbench.searchPaths') }}</span>
<input v-model="query" type="search" :placeholder="t('admin.shippingOrderProfiles.xfaWorkbench.searchPaths')" />
</label>
<ul class="xfa-tree__list" role="tree">
<li v-for="(node, index) in visible" :key="node.pathId" role="none">
<div
role="treeitem"
class="xfa-tree__node"
:class="{
selected: selectedPathId === node.pathId,
mapped: mapped.has(node.pathId),
leaf: node.isLeaf,
}"
:style="{ paddingLeft: nodeIndent(node), '--tree-guide-offset': nodeGuide(node) }"
:data-xfa-path-id="node.pathId"
:tabindex="focusedPathId === node.pathId || (!focusedPathId && node === visible[0]) ? 0 : -1"
:aria-level="node.depth + 1"
:aria-setsize="visible.length"
:aria-posinset="index + 1"
:aria-expanded="node.isLeaf ? undefined : !collapsed.has(node.pathId)"
:aria-selected="selectedPathId === node.pathId"
:title="pathTitle(node)"
@click="onSelect(node.pathId, node.isLeaf)"
@focus="focusedPathId = node.pathId"
@keydown="onKeydown($event, node.pathId)"
>
<span v-if="!node.isLeaf" class="toggle" @click.stop="toggle(node.pathId)">
<ChevronRight v-if="collapsed.has(node.pathId)" :size="14" aria-hidden="true" />
<ChevronDown v-else :size="14" aria-hidden="true" />
</span>
<span v-else class="toggle-spacer" />
<span class="name-block">
<span class="name">{{ node.localName }}</span>
<span v-if="node.isLeaf && parentPathHint(node)" class="path-hint">{{ parentPathHint(node) }}</span>
</span>
<span v-if="node.isCollectionCandidate" class="badge">{{ t('admin.shippingOrderProfiles.xfaWorkbench.collectionBadge') }}</span>
<button
v-if="node.isLeaf && !isReadonly"
type="button"
class="add-rule"
:class="{ 'add-rule--active': selectedPathId === node.pathId }"
:title="t('admin.shippingOrderProfiles.xfaSplit.addRule')"
:aria-label="t('admin.shippingOrderProfiles.xfaSplit.addRule')"
@click.stop="emit('add-rule', node.pathId)"
>+</button>
<span v-if="node.sampleValueDisplay" class="sample">
{{ node.sampleValueDisplay }}
</span>
</div>
<ul
v-if="node.isLeaf && rulesFor(node.pathId).length"
class="xfa-tree__rules"
role="group"
:style="ruleIndent(node)"
>
<li
v-for="(rule, ruleIndex) in rulesFor(node.pathId)"
:key="rule.rule_id"
class="xfa-tree__rule"
:class="{ selected: selectedRuleId === rule.rule_id }"
>
<button type="button" class="xfa-tree__rule-main" @click="emit('select-rule', node.pathId, rule.rule_id)">
<span class="rule-glyph">↳</span>
<span class="rule-label">{{ t('admin.shippingOrderProfiles.xfaSplit.ruleLabel', { index: ruleIndex + 1 }) }} · {{ rule.segment.display_name || rule.segment.segment_code || t('admin.shippingOrderProfiles.xfaSplit.unnamedRule') }}</span>
</button>
<button
v-if="!isReadonly"
type="button"
class="rule-edit"
:title="t('common.edit')"
:aria-label="t('common.edit')"
@click.stop="emit('edit-rule', node.pathId, rule.rule_id)"
><Pencil :size="12" aria-hidden="true" /></button>
<button v-if="!isReadonly" type="button" class="rule-delete" :title="t('admin.shippingOrderProfiles.xfaSplit.deleteRule')" @click.stop="emit('delete-rule', node.pathId, rule.rule_id)">×</button>
</li>
</ul>
</li>
</ul>
<p v-if="!visible.length" class="xfa-tree__empty">{{ t('admin.shippingOrderProfiles.xfaWorkbench.treeEmpty') }}</p>
</section>
</template>
<style scoped>
.xfa-tree { display: flex; flex-direction: column; min-height: 0; height: 100%; }
.xfa-tree__search input { width: 100%; padding: 8px 10px; border: 1px solid var(--border-default); border-radius: var(--radius-control); background: var(--bg-surface); color: var(--text-primary); }
.xfa-tree__list { margin: 8px -6px 0 0; padding: 0 6px 0 0; list-style: none; overflow: auto; flex: 1; scrollbar-gutter: stable; }
.xfa-tree__node { position: relative; display: flex; width: 100%; min-width: 0; gap: 5px; align-items: center; min-height: 34px; padding-block: 4px; padding-right: 6px; border: 0; border-radius: var(--radius-control); background: transparent; color: var(--text-secondary); text-align: left; cursor: pointer; }
.xfa-tree__node::before { content: ''; position: absolute; top: 0; bottom: 0; left: max(13px, calc(var(--tree-guide-offset, 0px))); width: 1px; background: var(--border-default); opacity: .65; pointer-events: none; }
.xfa-tree__node[aria-level='1']::before { display: none; }
.xfa-tree__node:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: 1px; }
.xfa-tree__node.selected { background: var(--status-info-bg); color: var(--status-info-fg); }
.xfa-tree__node.mapped .name::after { content: ' ✓'; color: var(--status-success-fg); }
.name-block { display: grid; min-width: 0; flex: 1; gap: 0; }
.xfa-tree__node:not(.leaf) .name { font-weight: 650; }
.xfa-tree__node .name { min-width: 0; overflow: hidden; font-size: .82rem; line-height: 1.2; text-overflow: ellipsis; white-space: nowrap; }
.xfa-tree__node .path-hint { min-width: 0; overflow: hidden; color: var(--text-muted); font-size: .64rem; line-height: 1.2; text-overflow: ellipsis; white-space: nowrap; }
.xfa-tree__node .sample { min-width: 3.2rem; margin-left: auto; max-width: 30%; overflow: hidden; color: var(--text-muted); font-size: .68rem; text-align: right; text-overflow: ellipsis; white-space: nowrap; }
.xfa-tree__node .badge { color: var(--status-warning-fg); font-size: .72rem; font-weight: 700; }
.toggle, .toggle-spacer { display: inline-flex; width: 16px; flex: 0 0 16px; }
.add-rule { display: none; position: relative; z-index: 1; min-width: 24px; min-height: 24px; align-items: center; justify-content: center; margin-left: 2px; border: 1px solid transparent; border-radius: 5px; background: transparent; color: var(--status-info-fg); font-size: 1rem; line-height: 1; cursor: pointer; }
.add-rule--active { display: inline-flex; border-color: var(--status-info-border); background: var(--status-info-bg); }
.xfa-tree__node:hover .add-rule, .xfa-tree__node:focus-within .add-rule { display: inline-flex; }
.xfa-tree__rules { position: relative; margin: 0; padding: 1px 0 5px var(--rule-indent); list-style: none; }
.xfa-tree__rules::before { content: ''; position: absolute; top: 0; bottom: 8px; left: var(--rule-guide-offset); width: 1px; background: var(--border-default); }
.xfa-tree__rule { display: flex; min-width: 0; align-items: center; gap: 3px; border-radius: 4px; }
.xfa-tree__rule.selected { background: var(--status-info-bg); }
.xfa-tree__rule-main { display: flex; min-width: 0; flex: 1; gap: 4px; padding: 3px 2px; border: 0; background: transparent; color: var(--text-muted); text-align: left; font-size: .68rem; cursor: pointer; }
.rule-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.rule-glyph { color: var(--status-info-fg); }
.rule-edit, .rule-delete { display: inline-flex; width: 20px; height: 20px; flex: 0 0 20px; align-items: center; justify-content: center; padding: 0; border: 0; border-radius: 4px; background: transparent; cursor: pointer; }
.rule-edit { color: var(--status-info-fg); }
.rule-delete { color: var(--status-error-fg); font-size: .9rem; }
.rule-edit:hover, .rule-delete:hover { background: var(--bg-page); }
.xfa-tree__empty { color: var(--text-muted); font-size: .85rem; }
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); border: 0; }
</style>
@@ -0,0 +1,89 @@
/**
* features/admin/modules/shipping-order-document-profiles/components/XfaReadOnlyMapping.spec.ts
* 用途:验证 XFA 只读映射组件不依赖 PDF 预览,并能展示结构身份摘要。
* 依赖:@vue/test-utils、vue-i18n、组件本身。
* 逻辑:传入含 xfa_readonly_mapping 的详情 DTO,断言标题与字段映射渲染。
*/
import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import { createI18n } from 'vue-i18n';
import XfaReadOnlyMapping from './XfaReadOnlyMapping.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
admin: {
shippingOrderProfiles: {
xfaReadonly: {
title: 'XFA 只读映射',
noPdfHint: '不显示空白 PDF',
missing: '暂无映射',
identityTitle: '结构身份',
templateChecksum: 'Template',
structureFingerprint: 'Dataset',
authoritativeCollection: '权威集合',
mirrorCollections: '镜像集合',
signatureChecksum: '匹配签名',
headerMaps: 'Header 映射',
lineMaps: 'Line 映射',
},
},
},
},
},
});
describe('XfaReadOnlyMapping', () => {
it('renders the shared adapter-evidence empty state for coordinate profiles', () => {
const wrapper = mount(XfaReadOnlyMapping, {
props: {
detail: {
id: 2, profile_code: 'COORD', display_name: 'COORD', version: 1,
status: 'published', schema_version_id: 1, structure_fingerprint: 'b'.repeat(64),
definition: {}, template_mode: 'coordinate', lock_version: 1,
} as never,
},
global: { plugins: [i18n] },
});
expect(wrapper.text()).toContain('暂无映射');
expect(wrapper.text()).not.toContain('不显示空白 PDF');
});
it('renders structure identity and mappings without requesting PDF', () => {
const wrapper = mount(XfaReadOnlyMapping, {
props: {
detail: {
id: 1,
profile_code: 'XFA',
display_name: 'XFA',
version: 1,
status: 'published',
schema_version_id: 1,
structure_fingerprint: 'a'.repeat(64),
definition: { template_mode: 'xfa_dataset' },
template_mode: 'xfa_dataset',
lock_version: 1,
value_source_readonly_mapping: {
source_contract: {
template_packet_checksum: 'sha256:tpl',
dataset_structure_fingerprint: 'sha256:fp',
authoritative_line_collection_path: '/data/ITEMS/DATA',
mirror_collection_paths: ['/data/ITEMS1/DATA'],
},
header_mappings: [{ mapping_id: 'm1', field_code: 'customer_po_no', path_id: 'p-po' }],
line_mappings: [{ mapping_id: 'm2', field_code: 'material_no', path_id: 'p-mat' }],
matching_signature_checksum: 'sig',
},
} as never,
},
global: { plugins: [i18n] },
});
expect(wrapper.text()).toContain('sha256:tpl');
expect(wrapper.text()).toContain('customer_po_no');
expect(wrapper.text()).toContain('material_no');
expect(wrapper.text()).not.toContain('preview-pages');
});
});
@@ -0,0 +1,99 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/XfaReadOnlyMapping.vue
用途:版本详情页统一值源 adapter 的只读证据面板。
依赖:vue-i18n、Profile readonly mapping DTO。
逻辑:所有模板均挂载该面板;coordinate 没有额外值源证据时展示空态,
XFA 才显示 datasets 结构身份、Header/Line 路径映射与集合策略;不请求 PDF 预览页。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderDocumentProfile } from '@/features/admin/types/shipping-order-document-profile.types';
const props = defineProps<{
detail: ShippingOrderDocumentProfile;
}>();
const { t } = useI18n();
const mapping = computed(() => (props.detail as ShippingOrderDocumentProfile & {
value_source_readonly_mapping?: {
source_contract?: Record<string, unknown>;
header_mappings?: Array<Record<string, unknown>>;
line_mappings?: Array<Record<string, unknown>>;
cross_checks?: Record<string, unknown>;
frozen_samples?: Array<Record<string, unknown>>;
matching_signature_checksum?: string | null;
};
}).value_source_readonly_mapping || null);
const hasValueSourceEvidence = computed(() => Boolean(mapping.value));
const source = computed(() => mapping.value?.source_contract || {});
const headerMaps = computed(() => mapping.value?.header_mappings || []);
const lineMaps = computed(() => mapping.value?.line_mappings || []);
</script>
<template>
<section class="xfa-readonly" :aria-label="t('admin.shippingOrderProfiles.xfaReadonly.title')">
<p v-if="hasValueSourceEvidence" class="hint">{{ t('admin.shippingOrderProfiles.xfaReadonly.noPdfHint') }}</p>
<div v-if="!mapping" class="empty">{{ t('admin.shippingOrderProfiles.xfaReadonly.missing') }}</div>
<template v-else>
<div class="identity">
<h3>{{ t('admin.shippingOrderProfiles.xfaReadonly.identityTitle') }}</h3>
<dl>
<div>
<dt>{{ t('admin.shippingOrderProfiles.xfaReadonly.templateChecksum') }}</dt>
<dd>{{ source.template_packet_checksum || '-' }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.xfaReadonly.structureFingerprint') }}</dt>
<dd>{{ source.dataset_structure_fingerprint || '-' }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.xfaReadonly.authoritativeCollection') }}</dt>
<dd>{{ source.authoritative_line_collection_path || '-' }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.xfaReadonly.mirrorCollections') }}</dt>
<dd>{{ (source.mirror_collection_paths as string[] | undefined)?.join(', ') || '-' }}</dd>
</div>
<div>
<dt>{{ t('admin.shippingOrderProfiles.xfaReadonly.signatureChecksum') }}</dt>
<dd>{{ mapping.matching_signature_checksum || '-' }}</dd>
</div>
</dl>
</div>
<div class="maps">
<div>
<h3>{{ t('admin.shippingOrderProfiles.xfaReadonly.headerMaps') }}</h3>
<ul>
<li v-for="item in headerMaps" :key="String(item.mapping_id)">
{{ item.field_code }} ← {{ item.path_id }}
</li>
</ul>
</div>
<div>
<h3>{{ t('admin.shippingOrderProfiles.xfaReadonly.lineMaps') }}</h3>
<ul>
<li v-for="item in lineMaps" :key="String(item.mapping_id)">
{{ item.field_code }} ← {{ item.path_id }}
</li>
</ul>
</div>
</div>
</template>
</section>
</template>
<style scoped>
.xfa-readonly { border: 1px solid #dfe7ef; border-radius: 10px; background: #fff; padding: 16px; }
.hint { margin: 0 0 12px; color: #64748b; font-size: 13px; }
.identity dl { display: grid; gap: 8px; margin: 8px 0 0; }
.identity dt { color: #64748b; font-size: 12px; }
.identity dd { margin: 2px 0 0; overflow-wrap: anywhere; font-size: 13px; }
.maps { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-top: 16px; }
.maps h3, .identity h3 { margin: 0; font-size: 14px; color: #1e293b; }
.maps ul { margin: 8px 0 0; padding-left: 18px; color: #334155; font-size: 13px; }
.empty { color: #b45309; }
@media (max-width: 767px) { .maps { grid-template-columns: 1fr; } }
</style>
@@ -0,0 +1,676 @@
/**
* features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.spec.ts
* 用途:验证 XfaSplitRulePanel pipeline 规则增删、确认门禁、order 重排与完整值预览。
* 依赖:Vitest、@vue/test-utils、shipping-order-document-profile API mock。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { mount, flushPromises } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import XfaSplitRulePanel from './XfaSplitRulePanel.vue';
import type { OrderXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
const previewMock = vi.fn();
const messageError = vi.fn();
vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
previewOrderProfileSampleXfaSplitRules: (...args: unknown[]) => previewMock(...args),
}));
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => ({ success: vi.fn(), error: messageError }),
}));
const baseDefinition: OrderXfaDatasetProfileDefinition = {
template_mode: 'xfa_dataset',
source_contract: {
template_packet_checksum: 'tpl',
dataset_structure_fingerprint: 'fp',
dataset_root_path: '/data',
authoritative_line_collection_path: '/data/ITEMS/DATA',
mirror_collection_paths: [],
},
header_mappings: [],
line_mapping: { row_path: '/data/ITEMS/DATA', fields: [] },
cross_checks: {
acroform_enabled: false,
mirror_collection_policy: 'ignore',
line_amount_formula: 'disabled',
total_amount_policy: 'disabled',
},
split_rules: [],
};
const xfaSplitMessages = {
title: '拆分',
expand: '展开',
collapse: '收起',
preview: '预览',
confirm: '确认',
addRule: '新增规则',
deleteRule: '删除',
deleteStage: '删除阶段',
moveUp: '上移',
moveDown: '下移',
ruleLabel: '规则 {index}',
stageLabel: '阶段 {index}',
handling: '处理',
mapped: '映射',
evidenceOnly: '证据',
needsReview: '复核',
targetField: '目标',
selectField: '选择',
segmentCode: '编码',
displayName: '名称',
note: '备注',
lineIndex: '行号',
prefix: '前缀',
separators: '分隔符',
caseSensitive: '大小写',
regex: '正则',
captureGroup: '捕获',
find: '查找',
replaceWith: '替换为',
substringStart: '起始',
substringEnd: '结束',
unmatchedPolicy: '未匹配',
noRules: '无规则',
confirmNeedsPreview: '需先预览',
confirmBlockedDiagnostics: '诊断阻断',
confirmDialog: '确认 mapped={mapped} evidence={evidence} diagnostics={diagnostics}',
confirmSuccess: '已确认',
previewTitle: '预览',
previewStatus: '状态 {status}',
previewMapped: '映射',
previewNoMapped: '无',
previewSegments: '段',
previewNoSegments: '无段',
previewValue: '值',
previewRuleStatus: '状态',
diagnostics: '诊断',
ruleSetSettings: '规则集',
normalization: '归一化',
stages: '阶段',
extractionMode: '提取方式',
extractionByLine: '按行号提取',
extractionByLineRange: '连续多行提取',
extractionByLabel: '按标签提取',
extractionByRegex: '按正则提取',
extractionBySubstring: '截取文本',
extractLineNumber: '提取第几行',
extractStartLine: '起始行',
extractEndLine: '结束行',
joinLinesWith: '合并方式',
joinWithNewline: '保留换行',
joinWithSpace: '空格',
joinWithComma: '逗号',
recognizedValue: '识别值',
previewRequired: '预览后显示',
showAdvanced: '高级处理',
hideAdvanced: '收起高级处理',
advancedProcessing: '高级处理',
addAdvancedStep: '添加高级处理',
advancedExtractAfterLabel: '提取标签后内容',
stageType: '类型',
addStage: '添加阶段',
stageTrim: 'trim',
stageRemoveEmptyLines: '去空行',
lineBreaks: '换行',
lineBreaksPlaceholder: '\\n',
stageTypeSplitLines: '拆分行',
stageTypeSelectLine: '选行',
stageTypeSelectLineRange: '连续多行',
stageTypeExtractPrefix: '前缀',
stageTypeRegexCapture: '正则',
stageTypeReplace: '替换',
stageTypeSubstring: '子串',
stageTypeNormalize: '归一化',
validationRequired: '必填',
validationSegmentCode: '蛇形',
validationMappedTarget: '目标必填',
validationPrefixValue: '前缀必填',
validationPrefixSeparators: '分隔符必填',
validationRegexPattern: '正则必填',
validationLineBreaks: '换行必填',
validationLineRangeRequired: '范围必填',
validationLineRangeOrder: '范围错误',
status: { draft: '草稿', confirmed: '已确认', published: '已发布' },
};
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
admin: {
shippingOrderProfiles: {
xfaSplit: xfaSplitMessages,
},
},
},
},
});
function makePipelineRuleSet(overrides: Record<string, unknown> = {}) {
return {
rule_id: 'ruleset-1',
rule_version: 1,
source_path_id: 'path-matnr',
source_field_code: 'MATNR',
strategy: 'pipeline' as const,
normalization: { trim: true, remove_empty_lines: true, line_breaks: ['\r\n', '\r', '\n'] },
rules: [{
rule_id: 'rule-1',
order: 1,
stages: [
{ stage_id: 'stage-1', type: 'split_lines' as const, line_breaks: ['\n'] },
{ stage_id: 'stage-2', type: 'select_line' as const, line_index: 1 },
],
segment: {
segment_id: 'seg-1',
segment_code: 'cpn',
display_name: 'CPN',
handling: 'evidence_only' as const,
},
}],
status: 'draft' as const,
...overrides,
};
}
function mountPanel(overrides: Record<string, unknown> = {}) {
return mount(XfaSplitRulePanel, {
global: { plugins: [i18n] },
props: {
definition: structuredClone(baseDefinition),
selectedPathId: 'path-matnr',
selectedPathLabel: 'MATNR',
selectedFieldCode: 'MATNR',
selectedIsMultiline: true,
documentId: 85,
profileId: 52,
schemaFields: [{
field_id: 'f1',
field_code: 'customer_part_number',
scope: 'line',
enabled: true,
required: true,
value_type: 'string',
}],
canEdit: true,
canPreview: true,
persistedConfirmed: true,
dirtyUnsaved: false,
...overrides,
},
});
}
/**
* 获取父弹窗可调用的组件操作,验证头部按钮迁移后仍保持原有业务行为。
* @param wrapper - 已挂载的拆分规则组件
* @returns 组件通过 defineExpose 暴露的新增、预览与确认方法
*/
function exposedActions(wrapper: ReturnType<typeof mountPanel>) {
return wrapper.vm as unknown as {
addRule: () => void;
runPreview: () => Promise<void>;
confirmRules: () => void;
};
}
describe('XfaSplitRulePanel', () => {
beforeEach(() => {
previewMock.mockReset();
messageError.mockReset();
vi.spyOn(window, 'confirm').mockReturnValue(true);
});
it('adds a rule with default pipeline stages and emits updated split_rules', async () => {
const wrapper = mountPanel();
exposedActions(wrapper).addRule();
const emitted = wrapper.emitted('update:split-rules');
expect(emitted?.length).toBeGreaterThan(0);
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
const ruleSet = last?.find((item) => item.source_path_id === 'path-matnr');
expect(ruleSet?.strategy).toBe('matcher');
expect(ruleSet?.rules?.length).toBe(1);
expect(ruleSet?.rules?.[0]?.matcher?.type).toBe('position');
expect(ruleSet?.rules?.[0]?.stages?.length).toBe(2);
expect(ruleSet?.rules?.[0]?.stages?.[0]?.type).toBe('split_lines');
expect(ruleSet?.rules?.[0]?.stages?.[1]?.type).toBe('select_line');
expect(ruleSet?.rules?.[0]?.order).toBe(1);
expect(ruleSet?.status).toBe('draft');
expect(ruleSet?.requires_confirmation).toBe(true);
});
it('maps a split segment only to an enabled Schema field and clears its target when kept as evidence', async () => {
const wrapper = mountPanel({
definition: { ...baseDefinition, split_rules: [makePipelineRuleSet()] },
schemaFields: [
{
field_id: 'unit-price-id',
field_code: 'unit_price',
display_name: '单价',
scope: 'line',
enabled: true,
required: false,
value_type: 'decimal',
aliases: [],
normalizer_key: 'decimal',
validator_keys: [],
enum_options: [],
evidence_policy: {
required: true,
source_precedence: [],
conflict_policy: 'needs_review',
allow_single_source: true,
},
comparator_key: 'decimal',
},
{
field_id: 'retired-price-unit-id',
field_code: 'price_unit',
display_name: '价格单位',
scope: 'line',
enabled: false,
required: false,
value_type: 'decimal',
aliases: [],
normalizer_key: 'decimal',
validator_keys: [],
enum_options: [],
evidence_policy: {
required: true,
source_precedence: [],
conflict_policy: 'needs_review',
allow_single_source: true,
},
comparator_key: 'decimal',
},
],
});
await wrapper.get('[data-testid="xfa-split-handling"]').setValue('mapped');
let emitted = wrapper.emitted('update:split-rules');
let nextDefinition = {
...baseDefinition,
split_rules: emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules,
};
await wrapper.setProps({ definition: nextDefinition });
const target = wrapper.get('[data-testid="xfa-split-target-field"]');
expect(target.text()).toContain('unit_price');
expect(target.text()).not.toContain('price_unit');
await target.setValue('unit-price-id');
emitted = wrapper.emitted('update:split-rules');
let rule = (emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules)?.[0]?.rules[0];
expect(rule?.segment).toMatchObject({
handling: 'mapped',
target_field_id: 'unit-price-id',
target_field_code: 'unit_price',
});
await wrapper.get('[data-testid="xfa-split-handling"]').setValue('evidence_only');
emitted = wrapper.emitted('update:split-rules');
rule = (emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules)?.[0]?.rules[0];
expect(rule?.segment).toMatchObject({ handling: 'evidence_only' });
expect(rule?.segment.target_field_id).toBeNull();
expect(rule?.segment.target_field_code).toBeNull();
});
it('editing a confirmed rule emits draft with bumped rule_version', async () => {
const wrapper = mountPanel({
definition: {
...baseDefinition,
split_rules: [makePipelineRuleSet({
status: 'confirmed',
requires_confirmation: false,
rule_version: 3,
})],
},
});
const inputs = wrapper.findAll('input');
const segmentCodeInput = inputs.find((input) => {
const label = input.element.closest('label');
return label?.textContent?.includes('编码');
});
expect(segmentCodeInput).toBeTruthy();
await segmentCodeInput!.setValue('cpn_updated');
await segmentCodeInput!.trigger('input');
const emitted = wrapper.emitted('update:split-rules');
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
const ruleSet = last?.[0];
expect(ruleSet?.status).toBe('draft');
expect(ruleSet?.requires_confirmation).toBe(true);
expect(ruleSet?.rule_version).toBe(4);
});
it('blocks confirm when preview has diagnostics', async () => {
previewMock.mockResolvedValue({
preview_token: 'tok-diag',
preview: {
status: 'ok',
mapped_fields: {},
segments: [],
evidence_only_segments: [],
diagnostics: [{ code: 'DUPLICATE', message: 'dup' }],
},
});
const wrapper = mountPanel({
definition: {
...baseDefinition,
split_rules: [makePipelineRuleSet()],
},
});
await exposedActions(wrapper).runPreview();
await flushPromises();
exposedActions(wrapper).confirmRules();
expect(messageError).toHaveBeenCalledWith('诊断阻断');
const confirmed = wrapper.emitted('update:split-rules')?.some((entry) => {
const rules = entry[0] as typeof baseDefinition.split_rules;
return rules?.[0]?.status === 'confirmed';
});
expect(confirmed).toBeFalsy();
});
it('blocks confirm when a mapped segment has no Schema target', async () => {
previewMock.mockResolvedValue({
preview_token: 'tok-mapped-empty',
preview: {
status: 'ok',
mapped_fields: {},
segments: [],
evidence_only_segments: [],
diagnostics: [],
},
});
const wrapper = mountPanel({
definition: {
...baseDefinition,
split_rules: [makePipelineRuleSet({
rules: [{
...makePipelineRuleSet().rules[0],
segment: {
...makePipelineRuleSet().rules[0].segment,
handling: 'mapped',
target_field_id: null,
target_field_code: null,
},
}],
})],
},
});
await exposedActions(wrapper).runPreview();
await flushPromises();
exposedActions(wrapper).confirmRules();
expect(messageError).toHaveBeenCalledWith('目标必填');
expect(wrapper.emitted('confirmed')).toBeUndefined();
});
it('configures consecutive line extraction with range and join mode', async () => {
const wrapper = mountPanel({
definition: { ...baseDefinition, split_rules: [makePipelineRuleSet()] },
});
const extractionSelect = wrapper.findAll('select').find((select) => (
select.element.closest('label')?.textContent?.includes('提取方式')
));
expect(extractionSelect).toBeTruthy();
await extractionSelect!.setValue('select_line_range');
const emitted = wrapper.emitted('update:split-rules');
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
const range = last?.[0]?.rules?.[0]?.stages?.find((stage) => stage.type === 'select_line_range');
expect(range).toMatchObject({ line_start: 1, line_end: 2, join_with: 'newline' });
const rangeWrapper = mountPanel({
definition: { ...baseDefinition, split_rules: last },
});
expect(rangeWrapper.text()).toContain('起始行');
expect(rangeWrapper.text()).toContain('结束行');
expect(rangeWrapper.text()).toContain('合并方式');
});
it('emits the final confirmed rules for parent persistence', async () => {
previewMock.mockResolvedValue({
preview_token: 'tok-preview-1',
preview: {
status: 'ok',
mapped_fields: {},
segments: [{
segment_id: 'seg-1', segment_code: 'cpn', rule_id: 'rule-1',
matcher_type: 'pipeline', normalized_text: 'CPN-001', raw_text: 'CPN-001', status: 'matched',
}],
evidence_only_segments: [],
diagnostics: [],
},
});
const wrapper = mountPanel({
definition: { ...baseDefinition, split_rules: [makePipelineRuleSet()] },
});
await exposedActions(wrapper).runPreview();
await flushPromises();
exposedActions(wrapper).confirmRules();
const confirmed = wrapper.emitted('confirmed');
const rules = confirmed?.[0]?.[0] as typeof baseDefinition.split_rules;
const tokens = confirmed?.[0]?.[1] as Record<string, string>;
expect(rules?.[0]?.status).toBe('confirmed');
expect(rules?.[0]?.requires_confirmation).toBe(false);
expect(rules?.[0]?.source_path_id).toBe('path-matnr');
expect(tokens?.['path-matnr']).toBe('tok-preview-1');
expect(() => JSON.parse(JSON.stringify(rules))).not.toThrow();
});
it('move up/down updates rule order field', async () => {
const wrapper = mountPanel({
definition: {
...baseDefinition,
split_rules: [makePipelineRuleSet({
rules: [
{
rule_id: 'rule-a',
order: 1,
stages: [
{ stage_id: 's1', type: 'split_lines', line_breaks: ['\n'] },
{ stage_id: 's2', type: 'select_line', line_index: 1 },
],
segment: {
segment_id: 'seg-a',
segment_code: 'a',
display_name: 'A',
handling: 'evidence_only',
},
},
{
rule_id: 'rule-b',
order: 2,
stages: [
{ stage_id: 's3', type: 'split_lines', line_breaks: ['\n'] },
{ stage_id: 's4', type: 'select_line', line_index: 2 },
],
segment: {
segment_id: 'seg-b',
segment_code: 'b',
display_name: 'B',
handling: 'evidence_only',
},
},
],
})],
},
});
const moveDownButtons = wrapper.findAll('button').filter((btn) => btn.text() === '下移');
expect(moveDownButtons.length).toBeGreaterThan(0);
await moveDownButtons[0]!.trigger('click');
const emitted = wrapper.emitted('update:split-rules');
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
const rules = last?.[0]?.rules || [];
const ruleA = rules.find((item) => item.rule_id === 'rule-a');
const ruleB = rules.find((item) => item.rule_id === 'rule-b');
expect(ruleA?.order).toBe(2);
expect(ruleB?.order).toBe(1);
});
it('defaults the third rule to extract line three', async () => {
const wrapper = mountPanel({
definition: {
...baseDefinition,
split_rules: [makePipelineRuleSet({
rules: [
makePipelineRuleSet().rules[0],
{ ...makePipelineRuleSet().rules[0], rule_id: 'rule-2', order: 2 },
],
})],
},
});
exposedActions(wrapper).addRule();
const emitted = wrapper.emitted('update:split-rules');
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
const third = last?.[0]?.rules.find((rule) => rule.order === 3);
expect(third?.stages.find((stage) => stage.type === 'select_line')?.line_index).toBe(3);
});
it('keeps line extraction and appends label extraction as advanced processing', async () => {
const wrapper = mountPanel({
definition: { ...baseDefinition, split_rules: [makePipelineRuleSet()] },
});
const advancedButton = wrapper.findAll('button').find((btn) => btn.text().includes('高级处理'));
await advancedButton!.trigger('click');
const addAdvanced = wrapper.find('.xfa-split__add-stage-select');
await addAdvanced.setValue('extract_prefix');
await addAdvanced.trigger('change');
const emitted = wrapper.emitted('update:split-rules');
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
expect(last?.[0]?.rules[0]?.stages.map((stage) => stage.type)).toEqual([
'split_lines', 'select_line', 'extract_prefix',
]);
});
it('keeps advanced processing attached to a position matcher rule', async () => {
const ruleSet = makePipelineRuleSet({
rules: [{
...makePipelineRuleSet().rules[0],
matcher: { type: 'position', line_index: 3 },
}],
});
const wrapper = mountPanel({
definition: { ...baseDefinition, split_rules: [ruleSet] },
});
const advancedButton = wrapper.findAll('button').find((btn) => btn.text().includes('高级处理'));
await advancedButton!.trigger('click');
const addAdvanced = wrapper.find('.xfa-split__add-stage-select');
await addAdvanced.setValue('extract_prefix');
await addAdvanced.trigger('change');
const emitted = wrapper.emitted('update:split-rules');
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
expect(last?.[0]?.rules[0]?.stages.map((stage) => stage.type)).toEqual([
'split_lines', 'select_line', 'extract_prefix',
]);
});
it('adds a rule after mounting when autoAddRule is enabled', () => {
const wrapper = mountPanel({
autoAddRule: true,
definition: { ...baseDefinition, split_rules: [] },
});
const emitted = wrapper.emitted('update:split-rules');
const rules = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
expect(rules?.[0]?.rules).toHaveLength(1);
});
it('previews full values without a reveal permission parameter', async () => {
previewMock.mockResolvedValue({
preview: {
status: 'ok',
mapped_fields: {},
segments: [],
evidence_only_segments: [],
diagnostics: [],
},
});
const wrapper = mountPanel({
definition: {
...baseDefinition,
split_rules: [makePipelineRuleSet({ rules: [] })],
},
});
await exposedActions(wrapper).runPreview();
await flushPromises();
expect(previewMock).toHaveBeenCalledWith(85, expect.not.objectContaining({ reveal: expect.anything() }));
});
it('sends formal matcher post-processors instead of UI-only pipeline fields to preview', async () => {
previewMock.mockResolvedValue({
preview: { status: 'ok', mapped_fields: {}, segments: [], evidence_only_segments: [], diagnostics: [] },
});
const wrapper = mountPanel({
definition: {
...baseDefinition,
split_rules: [makePipelineRuleSet({
strategy: 'pipeline',
rules: [{
...makePipelineRuleSet().rules[0],
order: 3,
matcher: { type: 'position', line_index: 3 },
stages: [
{ stage_id: 'split', type: 'split_lines', line_breaks: ['\\n'] },
{ stage_id: 'line', type: 'select_line', line_index: 3 },
{ stage_id: 'mpn', type: 'extract_prefix', value: 'MPN', separators: [':', ':'] },
],
}],
})],
},
});
await exposedActions(wrapper).runPreview();
await flushPromises();
expect(previewMock).toHaveBeenCalledWith(85, expect.objectContaining({
rule_set: expect.objectContaining({
rules: [expect.objectContaining({
matcher: expect.objectContaining({
type: 'position',
line_index: 3,
post_processors: [{ type: 'prefix', value: 'MPN', separators: [':', ':'], case_sensitive: false }],
}),
})],
}),
}));
const request = previewMock.mock.calls[0]?.[1] as { rule_set: Record<string, unknown> };
expect(request.rule_set).not.toHaveProperty('strategy');
expect(request.rule_set.rules[0]).not.toHaveProperty('order');
expect(request.rule_set.rules[0]).not.toHaveProperty('stages');
});
it('reprojects saved formal post-processors into the advanced editor', async () => {
const wrapper = mountPanel({
definition: {
...baseDefinition,
split_rules: [makePipelineRuleSet({
rules: [{
...makePipelineRuleSet().rules[0],
stages: [],
matcher: {
type: 'position',
line_index: 3,
post_processors: [{ type: 'prefix', value: 'MPN', separators: [':', ':'] }],
},
}],
})],
},
});
const advancedButton = wrapper.findAll('button').find((btn) => btn.text().includes('高级处理'));
await advancedButton!.trigger('click');
expect(wrapper.findAll('input').some((input) => input.element.value === 'MPN')).toBe(true);
});
it('ignores exposed edit actions when canEdit is false', () => {
const wrapper = mountPanel({ canEdit: false });
exposedActions(wrapper).addRule();
exposedActions(wrapper).confirmRules();
expect(wrapper.emitted('update:split-rules')).toBeUndefined();
expect(wrapper.emitted('confirmed')).toBeUndefined();
});
});
@@ -0,0 +1,570 @@
/**
* features/admin/modules/shipping-order-document-profiles/composables/useOrderProfileValueAdapter.spec.ts
* 用途:验证 XFA datasets 末端值源不会吞掉共同画布字段选择。
* 依赖:Vitest、Vue、useOrderProfileValueAdapter、Profile/Schema API mock。
* 逻辑:共同 Editor 可先恢复并选中视觉字段;本测试确保 datasets 异步加载完成后仍创建
* 未绑定值源槽位,供用户选择 path_id,且不影响共同 OCR 样本值展示流程。
*/
import { defineComponent, nextTick, ref } from 'vue';
import { flushPromises, mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { describe, expect, it, vi } from 'vitest';
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => ({ error: vi.fn(), info: vi.fn() }),
}));
vi.mock('@/features/admin/api/shipping-order-schema.api', () => ({
getShippingOrderSchemaState: vi.fn().mockResolvedValue({
versions: [{
id: 7,
definition: { fields: [
{ field_id: 'field-po', field_code: 'customer_po_number', scope: 'header' },
{ field_id: 'field-material', field_code: 'material_number', scope: 'line' },
] },
}],
}),
}));
vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
getOrderDocumentProfileDetail: vi.fn().mockResolvedValue({
id: 9,
lock_version: 1,
display_name: 'XFA sample',
profile_code: 'XFA-TEST',
schema_version_id: 7,
definition: {
template_mode: 'xfa_dataset',
source_contract: {},
header_mappings: [],
line_mapping: { fields: [] },
cross_checks: {},
bindings: [],
split_rules: [],
},
}),
listOrderProfileBoundSamples: vi.fn().mockResolvedValue([{ document_id: 101, sample_role: 'annotation' }]),
getOrderProfileSampleXfaFieldTree: vi.fn().mockResolvedValue({
tree: {
path_id: 'root', local_name: 'data', data_path_hash: 'root-hash', depth: 0,
cardinality: 'one', is_leaf: false, children: [{
path_id: 'header-po', parent_path_id: 'root', local_name: 'HEADER_PO', data_path_hash: 'header-po-hash', depth: 1,
cardinality: 'one', is_leaf: true, children: [],
}, {
path_id: 'items-collection', parent_path_id: 'root', local_name: 'ITEMS', data_path_hash: 'items-hash', depth: 1,
cardinality: 'many', is_leaf: false, children: [{
path_id: 'po-path', parent_path_id: 'items-collection', local_name: 'EBELN', data_path_hash: 'po-hash', depth: 2,
cardinality: 'one', is_leaf: true, children: [],
}],
}],
},
}),
getOrderProfileSampleXfaCollections: vi.fn().mockResolvedValue({ collection_candidates: [], excluded_collection_candidates: [] }),
previewOrderProfileSampleXfaValue: vi.fn().mockResolvedValue({
path_id: 'po-path', display_value: '4510039227', sample_value_masked: '4510******', display_policy: 'full',
}),
previewOrderProfileSampleXfaSplitRules: vi.fn(),
}));
import { useOrderProfileValueAdapter } from './useOrderProfileValueAdapter';
import type { OrderProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
const i18n = createI18n({ legacy: false, locale: 'zh-CN', messages: { 'zh-CN': {} } });
describe('useOrderProfileValueAdapter', () => {
it('restores a shared visual selection made before the datasets definition finishes loading', async () => {
const enabled = ref(false);
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
const Harness = defineComponent({
setup() {
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
// Assertion intent: canvas selection precedes the async datasets tree response.
desk.selectSharedField('customer_po_number', 'order_field_1_1');
return () => null;
},
});
mount(Harness, { global: { plugins: [i18n] } });
await desk?.load();
await flushPromises();
await nextTick();
expect(desk?.selectedBinding.value?.field_layout_id).toBe('order_field_1_1');
expect(desk?.selectedBinding.value?.value_binding.path_id).toBeNull();
expect(desk?.showDatasetsSection.value).toBe(true);
});
it('does not serialize a Schema-bound shared layout as an unbound datasets draft', async () => {
const enabled = ref(false);
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
const Harness = defineComponent({
setup() {
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
return () => null;
},
});
mount(Harness, { global: { plugins: [i18n] } });
await desk?.load();
desk!.authoritativePathId.value = 'root';
const visualDefinition = {
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
table_regions: [],
order_field_layouts: [{
layout_id: 'order_field_1_1', field_id: 'field-po', field_code: 'customer_po_number',
scope: 'header', page_scope: 'exact_page', page_no: 1, anchor: null,
absolute_value_region: null, fallback_value_region: { x0: .1, y0: .1, x1: .2, y1: .2 },
value_mode: 'single_line', stop_anchors: [], normalizer_key: 'trim', required: false,
minimum_evidence_level: 'coordinate',
}],
draft_unbound_order_field_layouts: Array.from({ length: 6 }, () => ({
layout_id: 'order_field_1_1', label: '客户 PO 号', page_scope: 'exact_page', page_no: 1,
anchor: null, absolute_value_region: null,
fallback_value_region: { x0: .1, y0: .1, x1: .2, y1: .2 },
value_mode: 'single_line', stop_anchors: [], minimum_evidence_level: 'coordinate',
})),
} as unknown as OrderProfileDefinition;
const payload = desk?.buildDraftPayload(visualDefinition);
// 关键断言:datasets 尚未选择路径不改变共同 Schema 绑定,也不得制造 unbound 重复项。
expect(payload?.definition.draft_unbound_order_field_layouts).toEqual([]);
expect(payload?.definition.bindings).toEqual([]);
});
it('loads the controlled datasets sample value after selecting a shared field path', async () => {
const enabled = ref(false);
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
const Harness = defineComponent({
setup() {
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
return () => null;
},
});
mount(Harness, { global: { plugins: [i18n] } });
await desk?.load();
desk?.selectSharedField('customer_po_number', 'order_field_1_2');
desk?.updateSelectedDatasetsPath('po-path', true);
await flushPromises();
// 关键断言:datasets 样本值来自受控 value-preview API,而不是树 DTO 的旧缓存。
expect(desk?.selectedSampleValue.value).toBe('4510039227');
});
it('keeps a datasets binding attached to a shared line field when saving', async () => {
const enabled = ref(false);
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
const Harness = defineComponent({
setup() {
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
return () => null;
},
});
mount(Harness, { global: { plugins: [i18n] } });
await desk?.load();
desk!.authoritativePathId.value = 'items-collection';
desk?.selectSharedField('material_number', 'line_1:material_number');
desk?.updateSelectedDatasetsPath('po-path', true);
await flushPromises();
const visualDefinition = {
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
order_field_layouts: [], draft_unbound_order_field_layouts: [],
table_regions: [{
region_id: 'main_lines_page_1', page_scope: 'exact_page', page_no: 1,
region: { x0: .1, y0: .2, x1: .9, y1: .8 }, header_layouts: [],
line_layouts: [{
layout_id: 'line_1', row_offset: 0, role: 'main', region: { x0: .1, y0: .3, x1: .9, y1: .4 },
field_regions: [{
field_id: 'field-material', field_code: 'material_number', scope: 'line',
region: { x0: .2, y0: .3, x1: .4, y1: .4 }, extractor_key: 'direct',
allowed_sources: ['pdf_coordinate'], minimum_evidence_level: 'coordinate',
}], new_line_anchor: null, continuation_conditions: [], required_fields: [], allowed_empty_fields: [],
}], continuation_rule: { allow_cross_page: false, required_anchor_ids: [] },
termination_rules: [], exclusion_regions: [],
}],
} as unknown as OrderProfileDefinition;
const payload = desk?.buildDraftPayload(visualDefinition);
// 关键断言:XFA 只追加 path;共同明细视觉框仍是唯一布局身份,保存不可丢 binding。
expect(payload?.definition.bindings).toEqual(expect.arrayContaining([
expect.objectContaining({ field_layout_id: 'line_1:material_number', value_binding: expect.objectContaining({ path_id: 'po-path' }) }),
]));
});
it('uses the visual field scope when header and line reuse one Schema code', async () => {
const enabled = ref(false);
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
const Harness = defineComponent({
setup() {
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
return () => null;
},
});
mount(Harness, { global: { plugins: [i18n] } });
await desk?.load();
desk!.schemaFields.value = [
{ field_id: 'reservation-header', field_code: 'reservation_id', scope: 'header' },
{ field_id: 'reservation-line', field_code: 'reservation_id', scope: 'line' },
];
desk!.selectSharedField('reservation_id', 'line_1:reservation_id', 'line');
// 关键断言:相同 code 不能让明细画框错误绑定到 Header 字段。
expect(desk!.selectedBinding.value).toMatchObject({
field_id: 'reservation-line', field_code: 'reservation_id', scope: 'line',
});
});
it('keeps a table-header visual field in the line datasets binding scope', async () => {
const enabled = ref(false);
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
const Harness = defineComponent({
setup() {
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
return () => null;
},
});
mount(Harness, { global: { plugins: [i18n] } });
await desk?.load();
desk!.schemaFields.value = [
{ field_id: 'line-material', field_code: 'material_number', scope: 'line' },
];
desk!.selectSharedField('material_number', 'header_1:material_number', 'line');
// 关键断言:表格列头是明细字段的视觉入口,正式 datasets binding 仍必须落到 line scope。
expect(desk!.selectedBinding.value).toMatchObject({
field_id: 'line-material', field_code: 'material_number', scope: 'line',
field_layout_id: 'header_1:material_number',
});
});
it('moves one configured datasets path when its shared visual field is rebound', async () => {
const enabled = ref(false);
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
const Harness = defineComponent({
setup() {
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
return () => null;
},
});
mount(Harness, { global: { plugins: [i18n] } });
await desk?.load();
desk!.schemaFields.value = [
{ field_id: 'line-material', field_code: 'material_number', scope: 'line' },
{ field_id: 'line-internal', field_code: 'part_number', scope: 'line' },
];
desk!.definition.value = {
...desk!.definition.value!,
bindings: [{
binding_id: 'material-binding', field_id: 'line-material', field_code: 'material_number', scope: 'line',
field_layout_id: 'header_1:material_number',
value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: '/data/items/material' },
}],
};
desk!.migrateUniqueSharedFieldBinding(
'material_number', 'header_1:material_number', 'part_number', 'header_1:part_number', 'line',
);
// 关键断言:用户改绑同一视觉列时,唯一正式路径随框迁移,不遗留孤儿旧 identity。
expect(desk!.definition.value?.bindings).toEqual([expect.objectContaining({
field_id: 'line-internal', field_code: 'part_number', scope: 'line',
field_layout_id: 'header_1:part_number',
value_binding: expect.objectContaining({ path_id: 'po-path' }),
})]);
});
it('does not infer a migration when one visual field has multiple formal bindings', async () => {
const enabled = ref(false);
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
const Harness = defineComponent({
setup() {
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
return () => null;
},
});
mount(Harness, { global: { plugins: [i18n] } });
await desk?.load();
desk!.schemaFields.value = [{ field_id: 'line-internal', field_code: 'part_number', scope: 'line' }];
desk!.definition.value = {
...desk!.definition.value!,
bindings: [
{ binding_id: 'first', field_id: 'one', field_code: 'one', scope: 'line', field_layout_id: 'line_1:old', value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: null } },
{ binding_id: 'second', field_id: 'two', field_code: 'two', scope: 'line', field_layout_id: 'line_1:old', value_binding: { type: 'xfa_dataset', path_id: 'header-po', data_path: null } },
],
};
desk!.migrateUniqueSharedFieldBinding('old', 'line_1:old', 'part_number', 'line_1:part_number', 'line');
// 关键断言:多个正式字段共享一个视觉框时保持 fail-closed,不能擅自选一个迁移。
expect(desk!.definition.value?.bindings.map((item) => item.field_layout_id)).toEqual(['line_1:old', 'line_1:old']);
});
it('keeps multiple datasets bindings that intentionally share one visual field layout', async () => {
const enabled = ref(false);
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
const Harness = defineComponent({
setup() {
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
return () => null;
},
});
mount(Harness, { global: { plugins: [i18n] } });
await desk?.load();
desk!.authoritativePathId.value = 'items-collection';
desk!.definition.value = {
...desk!.definition.value!,
bindings: [
{
binding_id: 'customer-part', field_id: 'field-customer-part', field_code: 'customer_part_number', scope: 'line',
field_layout_id: 'line_1:customer_part_number',
value_binding: { type: 'xfa_dataset', path_id: 'customer-path', data_path: '/data/items/MATNR' },
},
{
binding_id: 'internal-part', field_id: 'field-internal-part', field_code: 'part_number', scope: 'line',
field_layout_id: 'line_1:customer_part_number',
value_binding: { type: 'xfa_dataset', path_id: 'internal-path', data_path: '/data/items/MATNR' },
},
],
};
const visualDefinition = {
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
order_field_layouts: [], draft_unbound_order_field_layouts: [],
table_regions: [{
region_id: 'main_lines_page_1', page_scope: 'exact_page', page_no: 1,
region: { x0: .1, y0: .2, x1: .9, y1: .8 }, header_layouts: [],
line_layouts: [{
layout_id: 'line_1', row_offset: 0, role: 'main', region: { x0: .1, y0: .3, x1: .9, y1: .4 },
field_regions: [{
field_id: 'field-customer-part', field_code: 'customer_part_number', scope: 'line',
region: { x0: .2, y0: .3, x1: .4, y1: .4 }, extractor_key: 'direct',
allowed_sources: ['pdf_coordinate'], minimum_evidence_level: 'coordinate',
}], new_line_anchor: null, continuation_conditions: [], required_fields: [], allowed_empty_fields: [],
}], continuation_rule: { allow_cross_page: false, required_anchor_ids: [] },
termination_rules: [], exclusion_regions: [],
}],
} as unknown as OrderProfileDefinition;
const payload = desk!.buildDraftPayload(visualDefinition);
expect(payload?.definition.bindings.map((item) => item.binding_id)).toEqual(['customer-part', 'internal-part']);
});
it('restores a missing formal datasets visual layout from the last saved definition', async () => {
const enabled = ref(false);
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
const Harness = defineComponent({
setup() {
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
return () => null;
},
});
mount(Harness, { global: { plugins: [i18n] } });
await desk?.load();
await desk!.applySavedDraft({
id: 9,
lock_version: 2,
definition: {
...desk!.definition.value!,
order_field_layouts: [{
layout_id: 'xfa_header_currency', field_id: 'field-currency', field_code: 'currency', scope: 'header',
page_scope: 'exact_page', page_no: 1,
anchor_region: { x0: .1, y0: .1, x1: .2, y1: .15 },
fallback_value_region: { x0: .2, y0: .1, x1: .4, y1: .15 },
}],
},
} as unknown as import('@/features/admin/types/shipping-order-document-profile.types').ShippingOrderDocumentProfile);
desk!.authoritativePathId.value = 'root';
desk!.definition.value = {
...desk!.definition.value!,
bindings: [{
binding_id: 'currency-binding', field_id: 'field-currency', field_code: 'currency', scope: 'header',
field_layout_id: 'xfa_header_currency',
value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: '/data/currency' },
}],
};
const visualDefinition = {
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
order_field_layouts: [], draft_unbound_order_field_layouts: [], table_regions: [],
} as unknown as OrderProfileDefinition;
const payload = desk!.buildDraftPayload(visualDefinition);
// 关键断言:正式 datasets binding 的共享框从已保存定义恢复,不再阻断或静默删除。
expect(payload?.definition.order_field_layouts).toEqual(expect.arrayContaining([
expect.objectContaining({ layout_id: 'xfa_header_currency', field_code: 'currency' }),
]));
expect(payload?.definition.bindings).toEqual(expect.arrayContaining([
expect.objectContaining({ binding_id: 'currency-binding', field_layout_id: 'xfa_header_currency' }),
]));
});
it('carries an explicit formal binding deletion through the save payload', async () => {
const enabled = ref(false);
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
const Harness = defineComponent({
setup() {
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
return () => null;
},
});
mount(Harness, { global: { plugins: [i18n] } });
await desk?.load();
desk!.authoritativePathId.value = 'root';
desk!.definition.value = {
...desk!.definition.value!,
bindings: [{
binding_id: 'currency-binding', field_id: 'field-currency', field_code: 'currency', scope: 'header',
field_layout_id: 'xfa_header_currency',
value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: '/data/currency' },
}],
};
desk!.selectSharedField('currency', 'xfa_header_currency');
desk!.deleteSelectedBinding();
const payload = desk!.buildDraftPayload({
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
order_field_layouts: [], draft_unbound_order_field_layouts: [], table_regions: [],
} as unknown as OrderProfileDefinition);
// 关键断言:只有用户明确解除后,保存请求才携带允许删除的正式 binding ID。
expect(payload?.definition.bindings).toEqual([]);
expect(payload?.allow_formal_binding_deletions).toEqual(['currency-binding']);
});
it('restores an empty visual field id from its unique datasets binding when saving', async () => {
const enabled = ref(false);
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
const Harness = defineComponent({
setup() {
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
return () => null;
},
});
mount(Harness, { global: { plugins: [i18n] } });
await desk?.load();
desk!.authoritativePathId.value = 'root';
desk!.definition.value = {
...desk!.definition.value!,
bindings: [{
binding_id: 'line-material', field_id: 'field-material', field_code: 'material_number', scope: 'line',
field_layout_id: 'line_1:material_number', value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: null },
}],
};
const visualDefinition = {
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
order_field_layouts: [], draft_unbound_order_field_layouts: [],
table_regions: [{
region_id: 'main_lines_page_1', page_scope: 'exact_page', page_no: 1,
region: { x0: .1, y0: .2, x1: .9, y1: .8 }, header_layouts: [],
line_layouts: [{
layout_id: 'line_1', row_offset: 0, role: 'main', region: { x0: .1, y0: .3, x1: .9, y1: .4 },
field_regions: [{
field_id: '', field_code: 'material_number', scope: 'line',
region: { x0: .2, y0: .3, x1: .4, y1: .4 }, extractor_key: 'direct',
allowed_sources: ['pdf_coordinate'], minimum_evidence_level: 'coordinate',
}], new_line_anchor: null, continuation_conditions: [], required_fields: [], allowed_empty_fields: [],
}], continuation_rule: { allow_cross_page: false, required_anchor_ids: [] },
termination_rules: [], exclusion_regions: [],
}],
} as unknown as OrderProfileDefinition;
const payload = desk!.buildDraftPayload(visualDefinition);
// 关键断言:已有唯一正式 binding 时,视觉布局必须复用其 Schema ID,避免签名阶段失败。
expect(payload?.definition.table_regions[0]?.line_layouts[0]?.field_regions[0]?.field_id).toBe('field-material');
});
it('keeps a line Schema field bound from an auto-marked table header when saving', async () => {
const enabled = ref(false);
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
const Harness = defineComponent({
setup() {
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
return () => null;
},
});
mount(Harness, { global: { plugins: [i18n] } });
await desk?.load();
desk!.authoritativePathId.value = 'items-collection';
desk!.definition.value = {
...desk!.definition.value!,
bindings: [{
binding_id: 'header-material', field_id: 'field-material', field_code: 'material_number', scope: 'line',
field_layout_id: 'header_1:material_number',
value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: '/data/items/material' },
}],
};
const visualDefinition = {
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
order_field_layouts: [], draft_unbound_order_field_layouts: [],
table_regions: [{
region_id: 'main_lines_page_1', page_scope: 'exact_page', page_no: 1,
region: { x0: .1, y0: .2, x1: .9, y1: .8 },
header_layouts: [{
layout_id: 'header_1', region: { x0: .1, y0: .2, x1: .9, y1: .3 },
field_regions: [{
field_id: '', field_code: 'material_number', scope: 'line',
region: { x0: .2, y0: .2, x1: .4, y1: .3 }, extractor_key: 'direct',
allowed_sources: ['pdf_coordinate'], minimum_evidence_level: 'coordinate',
}],
}],
line_layouts: [], continuation_rule: { allow_cross_page: false, required_anchor_ids: [] },
termination_rules: [], exclusion_regions: [],
}],
} as unknown as OrderProfileDefinition;
const payload = desk!.buildDraftPayload(visualDefinition);
// 关键断言:ITEM/QTY 等视觉表头可绑定 line 字段,二次保存不可将其视为缺失布局。
expect(payload?.definition.table_regions[0]?.header_layouts[0]?.field_regions[0]?.field_id).toBe('field-material');
expect(payload?.definition.bindings).toEqual(expect.arrayContaining([
expect.objectContaining({ field_layout_id: 'header_1:material_number' }),
]));
});
it('marks a Header datasets value chosen for a shared line field as inherited', async () => {
const enabled = ref(false);
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
const Harness = defineComponent({
setup() {
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
return () => null;
},
});
mount(Harness, { global: { plugins: [i18n] } });
await desk?.load();
desk!.authoritativePathId.value = 'items-collection';
desk?.selectSharedField('material_number', 'line_1:material_number');
desk?.updateSelectedDatasetsPath('header-po', true);
await flushPromises();
// 关键断言:Header 叶子仍能绑定 line 字段,但 UI 必须明确展示逐行继承语义。
expect(desk?.lineBindingInheritsHeader.value).toBe(true);
});
});
@@ -0,0 +1,108 @@
/**
* features/admin/modules/shipping-order-document-profiles/composables/useOrderProfileVersionDetail.ts
* 用途:按独立详情路由加载模板版本详情与同族版本导航数据。
* 依赖:vue-router、订单模板版本中心 API。
* 逻辑:只读取结构化详情与版本摘要,不触发 PDF 预览、画布或盲测真值请求。
*/
import { computed, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { BusinessError } from "@/shared/api/client";
import {
getOrderDocumentProfileByFamilyVersion,
listOrderDocumentProfileFamilyVersions,
} from "@/features/admin/api/shipping-order-document-profile.api";
import type {
OrderProfileVersionSummary,
ShippingOrderDocumentProfile,
} from "@/features/admin/types/shipping-order-document-profile.types";
export type OrderProfileVersionDetailTab =
| "overview"
| "canvas"
| "diff"
| "audit"
| "usage";
export interface OrderProfileVersionDetailTabOption {
key: OrderProfileVersionDetailTab;
count?: number | null;
}
const VALID_TABS: OrderProfileVersionDetailTab[] = [
"overview",
"canvas",
"diff",
"audit",
"usage",
];
/**
* 按路由参数读取版本详情,只暴露阶段 3 需要的只读状态。
*/
export const useOrderProfileVersionDetail = () => {
const route = useRoute();
const loading = ref(false);
const detail = ref<ShippingOrderDocumentProfile | null>(null);
const versions = ref<OrderProfileVersionSummary[]>([]);
const errorMessage = ref("");
const profileCode = computed(() =>
String(route.params.profileCode || "").trim(),
);
const version = computed(() => Number(route.params.version || 0));
const activeTab = computed<OrderProfileVersionDetailTab>(() => {
const raw = String(route.query.tab || "overview").trim();
return VALID_TABS.includes(raw as OrderProfileVersionDetailTab)
? (raw as OrderProfileVersionDetailTab)
: "overview";
});
const tabOptions = computed<OrderProfileVersionDetailTabOption[]>(() => [
{ key: "overview" },
{ key: "canvas", count: detail.value?.sample_summary?.sample_count || 0 },
{ key: "diff" },
{ key: "audit" },
{ key: "usage" },
]);
const load = async () => {
if (!profileCode.value || !Number.isFinite(version.value) || version.value <= 0) {
detail.value = null;
versions.value = [];
errorMessage.value = "";
return;
}
loading.value = true;
errorMessage.value = "";
try {
const [detailPayload, versionsPayload] = await Promise.all([
getOrderDocumentProfileByFamilyVersion(profileCode.value, version.value),
listOrderDocumentProfileFamilyVersions(profileCode.value),
]);
detail.value = detailPayload;
versions.value = versionsPayload;
} catch (error) {
detail.value = null;
versions.value = [];
errorMessage.value =
error instanceof BusinessError ? error.message : "Failed to load";
} finally {
loading.value = false;
}
};
watch([profileCode, version], () => {
void load();
}, { immediate: true });
return {
activeTab,
detail,
errorMessage,
loading,
profileCode,
tabOptions,
version,
versions,
};
};
@@ -0,0 +1,636 @@
/**
* features/admin/modules/shipping-order-document-profiles/orderProfileForm.utils.spec.ts
* 用途:验证可视化订单模板表单生成受控规则、明细字段分组,并确保切换样本时配置入口不会消失。
* 依赖:Vitest、orderProfileForm.utils。
* 逻辑:覆盖 direct、复合解析器开关及跨列冲突,避免无效配置进入后端。
*/
import { describe, expect, it } from 'vitest';
import { reactive } from 'vue';
import {
mergeOrderProfileHeaderLabels,
restoreOrderProfileRegionPageNo,
suggestFieldCodeFromHeaders,
shouldShowStandardOrderProfilePreview,
toOrderProfileAnchorId,
buildOrderProfileRecognitionResults,
buildOrderProfileCanvasLineFieldValues,
selectCurrentDatasetsValidationEvidence,
normalizeOrderProfileRelativeRegion,
restoreReservationIdRegion,
groupUniqueOrderProfileLineFields,
restoreFormalBindingFieldCodes,
reconcileAutomarkOrderFieldRegions,
buildAutomarkSuggestedRegions,
normalizeAutomarkFieldCandidates,
preferredAutomarkTableSource,
selectAutomarkReconstruction,
summarizeAutomarkTableCandidates,
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 },
page_scope: 'exact_page' as const,
page_no: 1,
});
const restored = restoreReservationIdRegion(persisted);
// 关键断言:接口列表响应被 Vue 包装为 Proxy 后,重新打开草稿仍须恢复为可编辑的普通坐标对象。
expect(restored).toEqual({
region: { x0: .05, y0: .71, x1: .28, y1: .73 },
page_scope: 'exact_page',
page_no: 1,
});
});
it('keeps an automark suggestion audit identity frozen after the canvas page changes', () => {
const frozenContext = {
documentId: 285,
tableId: 'mineru-table-84a701e5693e0907',
pageNo: 1,
automarkJobId: 7267,
};
const summary = buildAutomarkSuggestionSummary(frozenContext, {
regionCount: 3,
regionKinds: ['line', 'field', 'field'],
evidenceSourceRequired: false,
selectedEvidenceSource: 'pdf_coordinate',
selectedFieldEvidenceSources: {},
});
// 翻页会更新当前画布状态,但接受建议必须仍携带入队时冻结的 Job 身份。
expect(summary).toMatchObject({
document_id: 285,
table_id: 'mineru-table-84a701e5693e0907',
page_no: 1,
automark_job_id: 7267,
});
});
it('preselects native PDF evidence while allowing OCR fallback', () => {
// 关键断言:PDF 只是默认建议;候选列表仍保留 OCR,供人工切换复核。
expect(preferredAutomarkTableSource([
{ source: 'ocr_coordinate' }, { source: 'pdf_coordinate' },
])).toBe('pdf_coordinate');
expect(preferredAutomarkTableSource([{ source: 'ocr_coordinate' }])).toBe('ocr_coordinate');
expect(preferredAutomarkTableSource([])).toBe('');
});
it('keeps datasets-only Schema fields available for XFA visual positioning only', () => {
const datasetsOnly = { enabled: true, allowed_sources: ['xfa_dataset'] };
// 关键断言:XFA 画框是定位证据,不能因没有 pdf_coordinate 正式取值权限而无法选择字段。
expect(isOrderProfileVisualFieldEligible(datasetsOnly, true)).toBe(true);
// 普通 PDF 仍不允许把未授权字段写入 coordinate definition。
expect(isOrderProfileVisualFieldEligible(datasetsOnly, false)).toBe(false);
expect(isOrderProfileVisualFieldEligible({ enabled: false, allowed_sources: ['xfa_dataset'] }, true)).toBe(false);
});
it.each(['line_no', 'customer_po_line_no'])(
'keeps %s available after resolving the main-line fields',
(startFieldCode) => {
const regions = [
{ id: 'main', kind: 'line' as const, label: 'Main', pageNo: 1, region: { x0: .1, y0: .3, x1: .9, y1: .4 } },
{ id: 'start', kind: 'field' as const, label: 'Start', fieldCode: startFieldCode, parentId: 'main', pageNo: 1, region: { x0: .1, y0: .3, x1: .2, y1: .4 } },
{ id: 'part', kind: 'field' as const, label: 'Part', fieldCode: 'part_number', parentId: 'main', pageNo: 1, region: { x0: .2, y0: .3, x1: .5, y1: .4 } },
];
const grouped = groupUniqueOrderProfileLineFields(regions, ['main']);
// 关键断言:起行字段选择和 line_layout 序列化复用同一结果时,字段不会被第一次读取消费。
expect(grouped.fieldsByLayout.get('main')?.map((item) => item.fieldCode)).toEqual([
startFieldCode,
'part_number',
]);
expect(grouped.fieldsByLayout.get('main')?.map((item) => item.fieldCode)).toEqual([
startFieldCode,
'part_number',
]);
expect(grouped.boundRegionIds).toEqual(new Set(['start', 'part']));
},
);
it('keeps directly configurable tables visible despite stale multi-row state', () => {
// 断言上一张表残留的多物理行开关不能隐藏当前可直接配置的表格。
expect(shouldShowStandardOrderProfilePreview(true, true, true)).toBe(true);
expect(shouldShowStandardOrderProfilePreview(false, true, true)).toBe(false);
});
it('merges every physical header row into stable logical column labels', () => {
const labels = mergeOrderProfileHeaderLabels([
['Item', 'Material', 'Vendor Part Number'],
['Item', 'Description', ''],
['IncoTerm', '', 'Manufacturer Part'],
], 2, 3);
// 断言同列跨行文字按顺序合并,并去掉展开 rowspan 产生的重复标签。
expect(labels).toEqual([
'Item / IncoTerm',
'Material / Description',
'Vendor Part Number / Manufacturer Part',
]);
});
it('restores legacy all-page regions to the first page instead of leaking them onto page two', () => {
const base = {
region_id: 'legacy', region: { x0: 0, y0: 0, x1: 1, y1: 1 }, header_layouts: [], line_layouts: [],
continuation_rule: { allow_cross_page: false, required_anchor_ids: [] }, termination_rules: [], exclusion_regions: [],
};
// 断言旧 all_pages 缺失原始页码时采用首篇迁移策略,精确页与续页语义保持不变。
expect(restoreOrderProfileRegionPageNo({ ...base, page_scope: 'all_pages' })).toBe(1);
expect(restoreOrderProfileRegionPageNo({ ...base, page_scope: 'continuation_pages' })).toBe(2);
expect(restoreOrderProfileRegionPageNo({ ...base, page_scope: 'exact_page', page_no: 7 })).toBe(7);
});
it('suggests a cross-page field only when one confirmed header clearly covers the column', () => {
const field = {
id: 'field', kind: 'field' as const, label: 'Field', pageNo: 1,
region: { x0: .6, y0: .4, x1: .8, y1: .45 },
};
const headers = [{
id: 'header-field', kind: 'header_field' as const, label: 'Delivery Date', pageNo: 2,
fieldCode: 'requested_receipt_date', region: { x0: .58, y0: .2, x1: .82, y1: .25 },
}];
// 断言不同页面但同一横向列可形成待确认建议,函数本身不写回字段。
expect(suggestFieldCodeFromHeaders(field, headers)).toBe('requested_receipt_date');
expect(field.fieldCode).toBeUndefined();
});
it('rejects ambiguous cross-page header semantics', () => {
const field = {
id: 'field', kind: 'field' as const, label: 'Field', pageNo: 1,
region: { x0: .6, y0: .4, x1: .8, y1: .45 },
};
const headers = [
{ id: 'a', kind: 'header_field' as const, label: 'A', pageNo: 1, fieldCode: 'part_number', region: { x0: .6, y0: .2, x1: .8, y1: .25 } },
{ id: 'b', kind: 'header_field' as const, label: 'B', pageNo: 2, fieldCode: 'customer_part_number', region: { x0: .6, y0: .2, x1: .8, y1: .25 } },
];
// 断言两个不同字段以相同覆盖率竞争时保持未映射,禁止静默选择。
expect(suggestFieldCodeFromHeaders(field, headers)).toBeNull();
});
it('converts a legacy unbound label into a valid anchor id after schema binding', () => {
// 断言“未绑定字段 -> 选择 Schema 字段”不会把缺失或大写的画布 ID 送入 AnchorRule。
expect(toOrderProfileAnchorId({
id: 'unbound-PURCHASEORDERNO', orderFieldId: 'order_field_1_11', label: 'PURCHASE ORDER NO',
})).toBe('purchaseorderno');
expect(toOrderProfileAnchorId({
id: '', orderFieldId: 'order_field_1_11', label: 'PURCHASE ORDER NO',
})).toBe('order_field_1_11');
expect(toOrderProfileAnchorId({ id: '', orderFieldId: '', label: '' })).toBeNull();
});
it('keeps structured recognition results linked to their annotation regions', () => {
const regions = [
{ id: 'po-value', kind: 'order_field' as const, label: 'PO', fieldCode: 'po_number', pageNo: 1, region: { x0: .1, y0: .1, x1: .2, y1: .2 } },
{ id: 'part-column', kind: 'field' as const, label: 'Part', fieldCode: 'part_number', pageNo: 1, region: { x0: .1, y0: .3, x1: .2, y1: .4 } },
];
const results = buildOrderProfileRecognitionResults(regions, [{
field_id: 'po', field_code: 'po_number', value: 'PO-100', status: 'confirmed', page_no: 1,
}], {
table_id: 'table-1', row_count: 2, column_count: 1, rows: [['part_number'], ['PN-1']],
row_roles: ['header', 'data'], source_row_indices: [[], [1]], status: 'needs_review',
});
// 断言表头和值行都保留可点击的区域 ID,且不恢复原始表格数据结构。
expect(results.header).toMatchObject([{ id: 'po-value', fieldCode: 'po_number', value: 'PO-100', status: 'read' }]);
expect(results.line).toMatchObject([{ id: 'part-column', fieldCode: 'part_number', value: 'PN-1', status: 'read', rowNo: 1 }]);
const deleted = buildOrderProfileRecognitionResults(regions, [], {
table_id: 'table-1', row_count: 2, column_count: 1, rows: [['part_number'], ['PN-DELETED']],
row_roles: ['header', 'deleted'], source_row_indices: [[], [1]], status: 'needs_review',
});
// 删除行仍可定位,且不会被伪装为待复核或可纳入结果的普通明细。
expect(deleted.line).toMatchObject([{ id: 'part-column', value: 'PN-DELETED', status: 'deleted', rowNo: 1 }]);
});
it('does not display a stale auto-suggestion when the current coordinate read has no value', () => {
const results = buildOrderProfileRecognitionResults([{
id: 'address-value', kind: 'order_field' as const, label: 'Address', fieldCode: 'bill_to_address',
suggestedValue: 'n 66 Hou-Kang Street', pageNo: 1, region: { x0: .1, y0: .1, x1: .2, y1: .2 },
}], [], null);
// 坐标框已调整时,旧建议值不能作为当前样本读取结果回显。
expect(results.header).toMatchObject([{ id: 'address-value', value: null, status: 'unavailable' }]);
});
it('displays the current AcroForm widget visual sample value for an XFA header frame', () => {
const results = buildOrderProfileRecognitionResults([{
id: 'po-value', kind: 'order_field' as const, label: 'PO', fieldCode: 'customer_po_number',
pageNo: 1, region: { x0: .4, y0: .1, x1: .8, y1: .2 },
}], [{
field_id: 'po-field', field_code: 'customer_po_number', value: '4510039227',
source: 'acroform_widget', status: 'needs_review', page_no: 1,
issues: ['order_field_acroform_widget_needs_review'],
}], null, 'ready');
// Widget 值来自当前受控视觉回读,必须显示,不得回退为自动标记缓存。
expect(results.header).toMatchObject([{ id: 'po-value', value: '4510039227', status: 'read' }]);
});
it('projects XFA line results only from datasets validation evidence', () => {
const regions = [
{ id: 'part-column', kind: 'field' as const, label: 'Part', fieldCode: 'customer_part_number', pageNo: 1, region: { x0: .1, y0: .3, x1: .2, y1: .4 } },
{ id: 'qty-column', kind: 'field' as const, label: 'Qty', fieldCode: 'quantity', pageNo: 1, region: { x0: .2, y0: .3, x1: .3, y1: .4 } },
];
const results = buildOrderProfileRecognitionResults(regions, [], null, 'ready', {
header_fields: [],
lines: [{ row_index: 0, fields: [
{ field_id: 'part', field_code: 'customer_part_number', raw_value: 'TEMP-S000218922', normalized_value: 'TEMP-S000218922', status: 'passed', issues: [] },
{ field_id: 'qty', field_code: 'quantity', raw_value: '30', normalized_value: '30', status: 'passed', issues: [] },
] }],
cross_checks: {},
});
// XFA 的正式行值只能来自 datasets 验证证据;坐标表头/旧 preview 不得混入。
expect(results.line).toMatchObject([
{ id: 'part-column', fieldCode: 'customer_part_number', value: 'TEMP-S000218922', status: 'read', rowNo: 1 },
{ id: 'qty-column', fieldCode: 'quantity', value: '30', status: 'read', rowNo: 1 },
]);
});
it('selects only the current XFA validation evidence for the active draft checksum', () => {
const evidence = {
header_fields: [], lines: [{ row_index: 0, fields: [] }], cross_checks: {},
};
// 旧草稿或非当前样本 Run 不能回灌至共同工作台,避免显示过期的正式样本值。
expect(selectCurrentDatasetsValidationEvidence([
{ id: 3, run_type: 'current_sample', status: 'passed', definition_checksum: 'old', summary: { validation_evidence: evidence } },
{ id: 2, run_type: 'instant_check', status: 'passed', definition_checksum: 'current', summary: { validation_evidence: evidence } },
{ id: 1, run_type: 'current_sample', status: 'passed', definition_checksum: 'current', summary: { validation_evidence: evidence } },
], 'current')).toEqual(evidence);
});
it('reports reading and failure without reusing a prior suggested value', () => {
const regions = [{
id: 'address-value', kind: 'order_field' as const, label: 'Address', fieldCode: 'bill_to_address',
suggestedValue: 'n 66 Hou-Kang Street', pageNo: 1, region: { x0: .1, y0: .1, x1: .2, y1: .2 },
}];
expect(buildOrderProfileRecognitionResults(regions, [], null, 'loading').header[0].status).toBe('loading');
expect(buildOrderProfileRecognitionResults(regions, [], null, 'failed').header[0]).toMatchObject({
value: null, status: 'failed',
});
});
it('uses an absolute value box when re-serializing a newly annotated order field', () => {
const valueRegion = { x0: .34, y0: .42, x1: .88, y1: .56 };
const definition = {
anchor: { anchor_id: 'bill_to', text: 'BILL TO' },
value_region: null,
absolute_value_region: valueRegion,
fallback_value_region: null,
};
// 新标注不再依赖标签框尺寸,删除旧标签后重画也不会生成 Infinity/NaN 坐标。
expect(definition).toEqual({
anchor: { anchor_id: 'bill_to', text: 'BILL TO' },
value_region: null,
absolute_value_region: valueRegion,
fallback_value_region: null,
});
});
it('clips a legacy or suggested value box to the page before persistence', () => {
// 断言自动建议略超页面边缘时会保留有效可读区域,不能把越界 absolute_value_region 送到后端。
expect(normalizeOrderProfileRelativeRegion({ x0: .74, y0: .18, x1: 1.02, y1: .34 })).toEqual({
x0: .74, y0: .18, x1: 1, y1: .34,
});
// 完全落在页面外或零面积的框没有可解释的读取边界,必须由管理员重画。
expect(normalizeOrderProfileRelativeRegion({ x0: 1.1, y0: .2, x1: 1.2, y1: .3 })).toBeNull();
});
it('keeps header field candidates when visual row reconstruction needs review', () => {
const regions = buildAutomarkSuggestedRegions({
reconstruction: null,
orderFieldCandidates: [{
field_id: 'po', field_code: 'customer_po_number', display_name: 'PO Number',
source: 'ocr_coordinate', status: 'suggested', issue: null,
value_region: { x0: .4, y0: .1, x1: .8, y1: .16 },
}],
pageNo: 1,
unboundColumnLabel: (count) => `Unbound ${count}`,
lineLabel: (count) => `Line ${count}`,
});
// 行证据为空时,只保留可复核的抬头框;不得为了满足旧表格结构虚构明细行。
expect(regions).toMatchObject([{
kind: 'order_field', fieldCode: 'customer_po_number', pageNo: 1,
region: { x0: .4, y0: .1, x1: .8, y1: .16 },
}]);
expect(regions.some((region) => region.kind === 'line' || region.kind === 'field')).toBe(false);
});
it('serializes accepted header fields with header scope', () => {
// 表头候选接受后必须进入 header_layouts;写成 line 会被后端契约拒绝,导致表头刷新后消失。
expect(toOrderProfileHeaderFieldRegion({
fieldCode: 'delivery_date',
region: { x0: .2, y0: .1, x1: .4, y1: .16 },
})).toEqual({
field_id: '', field_code: 'delivery_date', scope: 'header',
region: { x0: .2, y0: .1, x1: .4, y1: .16 },
extractor_key: 'direct', allowed_sources: ['pdf_coordinate'], minimum_evidence_level: 'coordinate',
});
expect(toOrderProfileHeaderFieldRegion({
fieldCode: null,
region: { x0: .2, y0: .1, x1: .4, y1: .16 },
})).toBeNull();
// 视觉表头中的 ITEM/QTY 等列名属于明细 Schema,必须保留 line scope。
expect(toOrderProfileHeaderFieldRegion({
fieldCode: 'qty',
region: { x0: .4, y0: .1, x1: .5, y1: .16 },
}, 'line')?.scope).toBe('line');
// Schema 只允许 datasets 时,视觉框不能丢失,也不能伪造 coordinate 正式绑定;
// 页面定义序列化层会将其放入 draft_unbound_field_regions。
});
it('keeps a cross-scope visual header candidate unbound until an administrator decides', () => {
// 同名字段跨 header/line 时,仅凭视觉列名不足以做业务语义选择。
expect(resolveCoordinateFieldScope('qty', ['customer_po_number'], ['qty'])).toBe('line');
expect(resolveCoordinateFieldScope('customer_po_number', ['customer_po_number'], ['qty'])).toBe('header');
expect(resolveCoordinateFieldScope('reservation_id', ['reservation_id'], ['reservation_id'])).toBeNull();
expect(resolveCoordinateFieldScope('dataset_only', [], [])).toBeNull();
});
it('does not choose a table layout when native and OCR candidates coexist', () => {
const native = {
table_id: 'table-1', subrow_layouts: [{ row_offset: 0, column_boundaries: [0, 1] }],
};
// 两路候选即使暂未计算出冲突,画布也不能按 native 优先投影为已选择的明细框。
expect(selectAutomarkReconstruction(native, [
{ source: 'pdf_coordinate', status: 'needs_review' },
{ source: 'ocr_coordinate', status: 'needs_review' },
], [])).toBeNull();
expect(selectAutomarkReconstruction(native, [
{ source: 'pdf_coordinate', status: 'needs_review' },
], [{ code: 'table_reconstruction_source_conflict' }])).toBeNull();
expect(selectAutomarkReconstruction(native, [
{ source: 'pdf_coordinate', status: 'needs_review' },
], [])).toBe(native);
});
it('uses the explicitly selected Widget table candidate when coordinate reconstruction is absent', () => {
const widget = {
table_id: 'table-1', status: 'needs_review' as const,
subrow_layouts: [{ row_offset: 0, column_boundaries: [0, .5, 1] }],
};
// XFA 外观层可能没有可重建的 native/OCR 文本行;管理员选择唯一 Widget 几何后,
// 共同画布必须使用该结构生成待确认明细框,而不能退化为“无明细行”。
expect(selectAutomarkReconstruction(null, [
{ source: 'acroform_widget_geometry', status: 'needs_review' },
], [], widget)).toBe(widget);
});
it('projects fused Widget geometry and coordinate header text as header fields', () => {
const widget = {
table_id: 'table-1', status: 'needs_review' as const,
subrow_layouts: [{
row_offset: 0, column_boundaries: [0, .25, 1],
suggested_field_codes: [null, null],
}],
header_regions: [{
region: { x0: .1, y0: .15, x1: .9, y1: .2 },
fields: [{
text: 'ITEM', field_code: 'line_no',
region: { x0: .1, y0: .15, x1: .3, y1: .2 },
evidence_sources: ['acroform_widget_geometry', 'pdf_coordinate'],
}],
}],
};
const regions = buildAutomarkSuggestedRegions({
reconstruction: selectAutomarkReconstruction(null, [
{ source: 'acroform_widget_geometry', status: 'needs_review' },
], [], widget),
orderFieldCandidates: [], pageNo: 1,
unboundColumnLabel: (count) => `Unbound ${count}`,
lineLabel: (count) => `Line ${count}`,
});
// Widget 仅提供列几何;融合后的表头文字必须随所选候选进入共同画布。
expect(regions).toContainEqual({
id: 'header_1_1-field-1', kind: 'header_field', parentId: 'header_1_1',
label: 'line_no', fieldCode: 'line_no', pageNo: 1,
region: { x0: .1, y0: .15, x1: .3, y1: .2 },
});
});
it('projects Reservation evidence to the header or its referenced logical line', () => {
const results = buildOrderProfileRecognitionResults([], [], {
table_id: 'table-1', row_count: 3, column_count: 1,
rows: [['part_number'], ['PN-1'], ['PN-2']],
row_roles: ['header', 'data', 'data'], source_row_indices: [[], [1], [2]], status: 'needs_review',
}, 'ready', null, [
{ value: '33008', line_no: null, scope: 'header', raw_text: 'Reservation#33008', status: 'header' },
{ value: '3000098851', line_no: 1, scope: 'line', raw_text: 'Reservation#3000098851 for line#1', status: 'mapped' },
]);
// 无行号值必须显示在订单表头;带行号值只显示在对应的逻辑明细行。
expect(results.header).toContainEqual(expect.objectContaining({
fieldCode: 'reservation_id', value: '33008', status: 'read',
}));
expect(results.line).toContainEqual(expect.objectContaining({
fieldCode: 'reservation_id', value: '3000098851', rowNo: 1, status: 'read',
}));
expect(results.line).not.toContainEqual(expect.objectContaining({
fieldCode: 'reservation_id', rowNo: 2,
}));
});
it('does not project a Widget row that overlaps the fused table header as a line field', () => {
const regions = buildAutomarkSuggestedRegions({
reconstruction: {
table_id: 'table-1', status: 'needs_review',
header_regions: [{
region: { x0: .1, y0: .15, x1: .9, y1: .2 },
fields: [{
text: 'ITEM', field_code: 'line_no',
region: { x0: .1, y0: .15, x1: .3, y1: .2 },
}],
}],
// 动态 XFA 的表头控件带有展示值时,Widget 几何会把它误聚为首条明细行。
subrow_layouts: [{
row_offset: 0, column_boundaries: [0, .25, 1],
region: { x0: .1, y0: .15, x1: .9, y1: .2 },
suggested_field_codes: ['line_no', null],
}],
},
orderFieldCandidates: [], pageNo: 1,
unboundColumnLabel: (count) => `Unbound ${count}`,
lineLabel: (count) => `Line ${count}`,
});
// 表头视觉证据已存在时,同一 y 带不能再成为可保存的明细布局。
expect(regions.filter((region) => region.kind === 'header_field')).toHaveLength(1);
expect(regions.some((region) => region.kind === 'line' || region.kind === 'field')).toBe(false);
});
it('maps reconstructed line values to canvas field region ids', () => {
const values = buildOrderProfileCanvasLineFieldValues([
{ id: 'line_1_1-field-0', kind: 'field', label: 'customer_po_line_no', fieldCode: 'customer_po_line_no', pageNo: 1, parentId: 'line_1_1', region: { x0: .1, y0: .3, x1: .2, y1: .4 } },
{ id: 'line_1_1-field-1', kind: 'field', label: 'qty', fieldCode: 'qty', pageNo: 1, parentId: 'line_1_1', region: { x0: .2, y0: .3, x1: .3, y1: .4 } },
], {
table_id: 'table-1', row_count: 2, column_count: 2,
rows: [['customer_po_line_no', 'qty'], ['10', '3.000']],
row_roles: ['header', 'data'], source_row_indices: [[], [1]], status: 'needs_review',
});
expect(values).toEqual({
'line_1_1-field-0': '10',
'line_1_1-field-1': '3.000',
});
});
it('restores a formal datasets field only for the same automark line and column', () => {
const existing = [{
id: 'line_1_1-field-2', kind: 'field' as const, parentId: 'line_1_1',
fieldCode: 'qty', label: 'qty', pageNo: 1,
region: { x0: .3, y0: .3, x1: .4, y1: .4 },
}];
const suggested = [{
id: 'line_1_1-field-2', kind: 'field' as const, parentId: 'line_1_1',
fieldCode: null, label: 'Unbound 2', pageNo: 1,
region: { x0: .3, y0: .3, x1: .4, y1: .4 },
}, {
id: 'line_1_1-field-3', kind: 'field' as const, parentId: 'line_1_1',
fieldCode: null, label: 'Unbound 3', pageNo: 1,
region: { x0: .4, y0: .3, x1: .5, y1: .4 },
}];
const restored = restoreFormalBindingFieldCodes(existing, suggested, new Set(['line_1_1:qty']));
// 关键断言:同一稳定区域才可恢复字段身份,新增列仍保持待人工绑定。
expect(restored.map((region) => region.fieldCode)).toEqual(['qty', null]);
});
it('reuses an existing formal XFA order-field identity instead of adding a duplicate', () => {
const existing = [{
id: 'order_field_1_7', kind: 'order_field' as const, label: 'PO', pageNo: 1,
orderFieldId: 'order_field_1_7', fieldCode: 'customer_po_number',
region: { x0: .4, y0: .1, x1: .8, y1: .16 },
}];
const suggested = [{
id: 'order_field_1_customer_po_number_1', kind: 'order_field' as const, label: 'PO', pageNo: 1,
orderFieldId: 'order_field_1_customer_po_number_1', fieldCode: 'customer_po_number',
region: { x0: .4, y0: .1, x1: .8, y1: .16 },
}];
const reconciled = reconcileAutomarkOrderFieldRegions(existing, suggested);
// 关键断言:同页、同字段、同视觉框必须继续使用正式 datasets 引用的 layout ID。
expect(reconciled[0]).toMatchObject({ id: 'order_field_1_7', orderFieldId: 'order_field_1_7' });
});
it('does not reuse a formal identity when the same field moved to a different visual box', () => {
const existing = [{
id: 'order_field_1_7', kind: 'order_field' as const, label: 'PO', pageNo: 1,
orderFieldId: 'order_field_1_7', fieldCode: 'customer_po_number',
region: { x0: .4, y0: .1, x1: .8, y1: .16 },
}];
const suggested = [{
id: 'order_field_1_customer_po_number_1', kind: 'order_field' as const, label: 'PO', pageNo: 1,
orderFieldId: 'order_field_1_customer_po_number_1', fieldCode: 'customer_po_number',
region: { x0: .4, y0: .3, x1: .8, y1: .36 },
}];
const reconciled = reconcileAutomarkOrderFieldRegions(existing, suggested);
// 关键断言:视觉位置发生实质变化时保留新候选,避免把正式绑定静默迁移到错误区域。
expect(reconciled[0]?.id).toBe('order_field_1_customer_po_number_1');
});
it('preserves the backend evidence source when projecting automark field candidates', () => {
const candidates = normalizeAutomarkFieldCandidates([{
candidate_kind: 'field_binding',
evidence_sources: ['ocr_coordinate'],
needs_review: true,
binding: {
field_id: 'po', field_code: 'customer_po_number',
visual_binding: { normalized_bbox: { x0: .4, y0: .1, x1: .8, y1: .16 } },
},
}]);
// OCR 视觉候选不能在前端被降级伪装为 native PDF 坐标候选。
expect(candidates).toMatchObject([{
source: 'ocr_coordinate', status: 'suggested',
value_region: { x0: .4, y0: .1, x1: .8, y1: .16 },
issue: 'visual_candidate_needs_review',
}]);
});
it('keeps AcroForm Widget as a visual-only candidate source', () => {
const candidates = normalizeAutomarkFieldCandidates([{
candidate_kind: 'field_binding',
evidence_sources: ['acroform_widget'],
needs_review: true,
binding: {
field_id: 'po', field_code: 'customer_po_number',
visual_binding: { normalized_bbox: { x0: .4, y0: .1, x1: .8, y1: .16 } },
},
}]);
// Widget 只保留为待复核的定位来源;归一化 DTO 中没有也不得生成正式 value_binding。
expect(candidates).toMatchObject([{
source: 'acroform_widget', status: 'suggested',
issue: 'visual_candidate_needs_review',
}]);
});
it('projects an unmatched AcroForm Widget as an unbound visual candidate', () => {
const candidates = normalizeAutomarkFieldCandidates([{
candidate_kind: 'field_binding',
evidence_sources: ['acroform_widget'],
needs_review: true,
binding: {
field_id: '', field_code: '', display_name: 'EBELN',
visual_binding: { normalized_bbox: { x0: .4, y0: .1, x1: .8, y1: .16 } },
},
}]);
// Widget 名称不是业务字段映射;画布只能显示待确认框,不能自动写入 Schema field_code。
expect(candidates).toMatchObject([{
field_code: '', display_name: 'EBELN', source: 'acroform_widget',
issue: 'visual_candidate_needs_review',
}]);
});
it('summarizes every parallel table candidate and marks source conflicts', () => {
// 断言三路视觉候选都可见,摘要只提供结构信息,不替用户选正式值源。
expect(summarizeAutomarkTableCandidates([
{ source: 'pdf_coordinate', reconstruction: { table_id: 't', status: 'needs_review', subrow_layouts: [{ row_offset: 0, column_boundaries: [0, .5, 1] }] } },
{ source: 'ocr_coordinate', reconstruction: { table_id: 't', status: 'needs_review', subrow_layouts: [{ row_offset: 0, column_boundaries: [0, 1] }, { row_offset: 1, column_boundaries: [0, 1] }] } },
{ source: 'opencv_geometry', reconstruction: { table_id: 't', status: 'needs_review', subrow_layouts: [] } },
{ source: 'acroform_widget_geometry', reconstruction: { table_id: 't', status: 'needs_review', subrow_layouts: [{ row_offset: 0, column_boundaries: [0, .25, .75, 1] }] } },
], [{ code: 'table_reconstruction_source_conflict', sources: ['pdf_coordinate', 'opencv_geometry'] }])).toEqual([
{ source: 'pdf_coordinate', rowCount: 1, columnCount: 2, conflictCodes: ['table_reconstruction_source_conflict'], status: 'needs_review' },
{ source: 'ocr_coordinate', rowCount: 2, columnCount: 1, conflictCodes: [], status: 'needs_review' },
{ source: 'opencv_geometry', rowCount: 0, columnCount: 0, conflictCodes: ['table_reconstruction_source_conflict'], status: 'needs_review' },
{ source: 'acroform_widget_geometry', rowCount: 1, columnCount: 3, conflictCodes: [], status: 'needs_review' },
]);
});
});
@@ -0,0 +1,804 @@
/**
* features/admin/modules/shipping-order-document-profiles/orderProfileForm.utils.ts
* 用途:构造可视化订单模板的白名单列规则、明细字段分组,并控制样本表格配置区的安全显示。
* 依赖:订单 Profile DTO。
* 逻辑:页面状态只允许 direct 或已注册复合解析器;同一目标字段跨列只能出现一次;
* 另提供「未绑定订单字段」判定,供画布强制高亮与编辑横幅共用。
*/
import type {
CoordinateReconstructionSuggestion,
CoordinateReconstructionPreview,
OrderFieldLayoutSuggestion,
OrderFieldValuePreview,
OrderProfileCanvasRegion,
OrderProfileFieldRegion,
OrderProfileRelativeRegion,
OrderProfileTableRegion,
OrderProfileValidationEvidence,
OrderProfileValidationRun,
} from '@/features/admin/types/shipping-order-document-profile.types';
export interface OrderProfileLineFieldGroups {
fieldsByLayout: Map<string, OrderProfileCanvasRegion[]>;
boundRegionIds: Set<string>;
}
/**
* 判断 Schema 字段能否出现在共同视觉画布的绑定下拉中。
* 核心逻辑:普通 PDF 的视觉框同时承载 coordinate 正式取值,必须具备该证据授权;
* XFA 的视觉框只承担定位和样本展示,正式值由 datasets binding 另行控制,因此只要字段启用即可。
* @param field - Schema 字段的最小权限信息。
* @param usesExternalValueSource - 是否使用 datasets 等独立正式值源。
* @returns 字段是否可作为当前工作台的视觉绑定目标。
*/
export const isOrderProfileVisualFieldEligible = (
field: { enabled?: boolean; allowed_sources?: string[] },
usesExternalValueSource: boolean,
): boolean => (
field.enabled !== false
&& (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,
* 未绑定框由调用方进入草稿未绑定区,不能猜测业务字段。
* @param item - 已确认的表头画布区域。
* @param scope - Schema 规定的业务字段作用域;视觉表头中的列名通常是 line。
* @returns 可持久化的表头字段区域;没有 fieldCode 时返回 null。
*/
export const toOrderProfileHeaderFieldRegion = (
item: Pick<OrderProfileCanvasRegion, 'fieldCode' | 'region'>,
scope: 'header' | 'line' = 'header',
): OrderProfileFieldRegion | null => {
if (!item.fieldCode) return null;
return {
field_id: '',
field_code: item.fieldCode,
scope,
region: item.region,
extractor_key: 'direct',
allowed_sources: ['pdf_coordinate'],
minimum_evidence_level: 'coordinate',
};
};
/**
* 依据已获坐标证据授权的 Schema 字段解析视觉表头的业务作用域。
* 核心逻辑:同一 field_code 同时存在 header/line 时,视觉文字不足以裁决业务语义;
* 返回 null 使调用方保留未绑定框,等待管理员明确确认。
* @param fieldCode - 自动候选给出的字段代码。
* @param headerFieldCodes - 可使用坐标证据的 Header 字段代码。
* @param lineFieldCodes - 可使用坐标证据的 Line 字段代码。
* @returns 唯一作用域;未授权、未知或跨作用域歧义时返回 null。
*/
export const resolveCoordinateFieldScope = (
fieldCode: string | null | undefined,
headerFieldCodes: Iterable<string | null | undefined>,
lineFieldCodes: Iterable<string | null | undefined>,
): 'header' | 'line' | null => {
if (!fieldCode) return null;
const header = new Set([...headerFieldCodes].filter((code): code is string => Boolean(code)));
const line = new Set([...lineFieldCodes].filter((code): code is string => Boolean(code)));
const inHeader = header.has(fieldCode);
const inLine = line.has(fieldCode);
return inHeader === inLine ? null : inHeader ? 'header' : 'line';
};
/**
* 按物理行顺序收集唯一的明细字段绑定,供起行字段选择和最终定义复用同一份结果。
* 核心逻辑:每个 Schema 字段只归属首个物理行;返回结果可重复读取,不会因预览起行字段而消费绑定。
* @param regions - 当前页面全部画布区域。
* @param layoutIds - 按主行到续行排列的物理行 ID。
* @returns 每个物理行的字段区域,以及已进入正式绑定的区域 ID。
*/
export const groupUniqueOrderProfileLineFields = (
regions: OrderProfileCanvasRegion[],
layoutIds: string[],
): OrderProfileLineFieldGroups => {
const claimedFieldCodes = new Set<string>();
const boundRegionIds = new Set<string>();
const fieldsByLayout = new Map<string, OrderProfileCanvasRegion[]>();
layoutIds.forEach((layoutId) => {
const fields = regions.filter((item) => {
if (item.kind !== 'field' || item.parentId !== layoutId || !item.fieldCode) return false;
if (claimedFieldCodes.has(item.fieldCode)) return false;
claimedFieldCodes.add(item.fieldCode);
boundRegionIds.add(item.id);
return true;
});
fieldsByLayout.set(layoutId, fields);
});
return { fieldsByLayout, boundRegionIds };
};
/**
* 在接受新自动标注前恢复已有 XFA 正式绑定的共同视觉字段身份。
* 核心逻辑:只允许同一行布局、同一自动列序号的候选继承字段码;缺少该严格对应关系时
* 保持未绑定,避免把 datasets 正式路径错误迁移到另一列。
* @param existingRegions - 当前已保存或待保存的画布区域。
* @param suggestedRegions - 当前待接受的自动标注区域。
* @param formalBindingLayoutIds - 已存在正式 datasets binding 的 field_layout_id 集合。
* @returns 仅补回可严格证明身份的候选字段码。
*/
export const restoreFormalBindingFieldCodes = (
existingRegions: OrderProfileCanvasRegion[],
suggestedRegions: OrderProfileCanvasRegion[],
formalBindingLayoutIds: ReadonlySet<string>,
): OrderProfileCanvasRegion[] => {
const fieldCodeByRegionId = new Map<string, string>();
for (const region of existingRegions) {
if (region.kind !== 'field' || !region.parentId || !region.fieldCode) continue;
const layoutId = `${region.parentId}:${region.fieldCode}`;
if (formalBindingLayoutIds.has(layoutId)) fieldCodeByRegionId.set(region.id, region.fieldCode);
}
return suggestedRegions.map((region) => {
if (region.kind !== 'field' || region.fieldCode) return region;
const fieldCode = fieldCodeByRegionId.get(region.id);
return fieldCode ? { ...region, fieldCode } : region;
});
};
/** 自动候选与既有共同订单字段框被视为同一视觉证据的最小 IoU。 */
const AUTOMARK_ORDER_FIELD_IDENTITY_IOU = 0.98;
/**
* 将自动标注的共同订单字段对账到已有画布视觉身份。
* 核心逻辑:datasets binding 以 field_layout_id 引用视觉框。自动候选的临时 ID 不可
* 替代该身份;只有同页、同字段码且几何几乎完全一致时,才继承既有 layout ID。
* @param existingRegions - 当前画布中已保存的区域。
* @param suggestedRegions - 自动标注产生的待接受区域。
* @returns 复用既有 order_field ID 后的候选;坐标变化的候选保持原 ID 供人工复核。
*/
export const reconcileAutomarkOrderFieldRegions = (
existingRegions: OrderProfileCanvasRegion[],
suggestedRegions: OrderProfileCanvasRegion[],
): OrderProfileCanvasRegion[] => {
const usedExistingIds = new Set<string>();
const matchingExistingId = (suggested: OrderProfileCanvasRegion): string | null => {
if (suggested.kind !== 'order_field' || !suggested.fieldCode) return null;
const candidates = existingRegions.filter((existing) => {
if (usedExistingIds.has(existing.id) || existing.kind !== 'order_field') return false;
if (existing.pageNo !== suggested.pageNo || existing.fieldCode !== suggested.fieldCode) return false;
const left = Math.max(existing.region.x0, suggested.region.x0);
const top = Math.max(existing.region.y0, suggested.region.y0);
const right = Math.min(existing.region.x1, suggested.region.x1);
const bottom = Math.min(existing.region.y1, suggested.region.y1);
const intersection = Math.max(0, right - left) * Math.max(0, bottom - top);
const existingArea = Math.max(0, existing.region.x1 - existing.region.x0) * Math.max(0, existing.region.y1 - existing.region.y0);
const suggestedArea = Math.max(0, suggested.region.x1 - suggested.region.x0) * Math.max(0, suggested.region.y1 - suggested.region.y0);
const union = existingArea + suggestedArea - intersection;
return union > 0 && intersection / union >= AUTOMARK_ORDER_FIELD_IDENTITY_IOU;
});
if (candidates.length !== 1) return null;
usedExistingIds.add(candidates[0]!.id);
return candidates[0]!.id;
};
const layoutIds = new Map<string, string>();
suggestedRegions.forEach((region) => {
if (region.kind === 'order_field') {
const existingId = matchingExistingId(region);
if (existingId) layoutIds.set(region.id, existingId);
}
});
return suggestedRegions.map((region) => {
if (region.kind === 'order_field' && layoutIds.has(region.id)) {
const orderFieldId = layoutIds.get(region.id)!;
return { ...region, id: orderFieldId, orderFieldId };
}
if (region.kind === 'order_anchor' && region.orderFieldId && layoutIds.has(region.orderFieldId)) {
const orderFieldId = layoutIds.get(region.orderFieldId)!;
return { ...region, id: `${orderFieldId}_anchor`, orderFieldId };
}
return region;
});
};
/**
* 将画布或历史草稿的区域限制为页面归一化坐标。
* @param region - 可能来自拖拽、自动建议或历史模板的页面区域。
* @returns 可持久化的正面积区域;无法裁剪为有效区域时返回 null。
*/
export const normalizeOrderProfileRelativeRegion = (
region: OrderProfileRelativeRegion,
): OrderProfileRelativeRegion | null => {
const values = [region.x0, region.y0, region.x1, region.y1];
if (values.some((value) => !Number.isFinite(value))) return null;
const x0 = Math.max(0, Math.min(1, region.x0));
const y0 = Math.max(0, Math.min(1, region.y0));
const x1 = Math.max(0, Math.min(1, region.x1));
const y1 = Math.max(0, Math.min(1, region.y1));
return x0 < x1 && y0 < y1 ? { x0, y0, x1, y1 } : null;
};
/**
* 从持久化定义恢复 Reservation ID 专用区域。
* 核心逻辑:Profile 列表被 Vue 包装后内部对象是 Proxy,不能直接传入 structuredClone;
* 此处只读取四个坐标值并构造普通对象,避免草稿重新打开时抛出 DataCloneError。
* @param rawRegion - 接口返回的 Reservation 区域,可为 Vue Proxy 或缺省值。
* @returns 可编辑的普通区域;定义缺失或坐标无效时返回 null。
*/
export const restoreReservationIdRegion = (rawRegion: unknown): {
region: OrderProfileRelativeRegion;
page_scope: 'exact_page';
page_no: number;
} | null => {
if (!rawRegion || typeof rawRegion !== 'object') return null;
const record = rawRegion as { region?: OrderProfileRelativeRegion; page_no?: unknown };
const region = record.region ? normalizeOrderProfileRelativeRegion(record.region) : null;
const pageNo = Number(record.page_no);
if (!region || !Number.isInteger(pageNo) || pageNo < 1) return null;
return { region, page_scope: 'exact_page', page_no: pageNo };
};
/** 自动标注任务启动时冻结的样本身份;候选在跨页浏览期间不得重新读取可变画布状态。 */
export interface AutomarkSuggestionContext {
documentId: number;
tableId: string;
pageNo: number;
automarkJobId: number | string;
}
/**
* 构造待确认自动标注的审计摘要。
* 核心逻辑:Job 已按 document/table/page 冻结证据身份;摘要必须复用同一身份,
* 防止管理员翻页或切换表格后,接受请求被服务端判定为另一份 Job 的候选。
* @param context - 自动标注入队并成功完成后冻结的样本、页面和 Job 身份。
* @param details - 可随管理员选择证据来源而更新的候选描述。
* @returns 后端 suggestion decision 契约所需的完整且稳定摘要。
*/
export const buildAutomarkSuggestionSummary = (
context: AutomarkSuggestionContext,
details: {
regionCount: number;
regionKinds: string[];
evidenceSourceRequired: boolean;
selectedEvidenceSource: string | null;
selectedFieldEvidenceSources: Record<string, string>;
},
): Record<string, unknown> => ({
algorithm_version: 'coordinate-suggest-v1',
kind: 'page_regions',
page_no: context.pageNo,
document_id: context.documentId,
table_id: context.tableId,
automark_job_id: context.automarkJobId,
region_count: details.regionCount,
region_kinds: details.regionKinds,
evidence_source_required: details.evidenceSourceRequired,
selected_evidence_source: details.selectedEvidenceSource,
selected_field_evidence_sources: details.selectedFieldEvidenceSources,
});
/**
* 将统一自动标记结果投影为画布区域。
* 核心逻辑:字段视觉候选与行重建是并行证据;行重建缺失时仍保留抬头字段框供人工复核,
* 但绝不合成 line/field 明细区域。此函数不决定正式取值源。
* @param options.reconstruction - 可选的表格行/列重建诊断。
* @param options.orderFieldCandidates - 共同视觉字段框候选。
* @returns 待确认画布区域,调用方再计算审计摘要和持久化建议。
*/
export const buildAutomarkSuggestedRegions = (options: {
reconstruction: CoordinateReconstructionSuggestion | null | undefined;
orderFieldCandidates: OrderFieldLayoutSuggestion[];
pageNo: number;
unboundColumnLabel: (count: number) => string;
lineLabel: (count: number) => string;
}): OrderProfileCanvasRegion[] => {
const { reconstruction, orderFieldCandidates, pageNo, unboundColumnLabel, lineLabel } = options;
const suggestedRegions: OrderProfileCanvasRegion[] = [];
const headerRegions = (reconstruction?.header_regions || [])
.map((header) => header.region)
.filter((region): region is OrderProfileRelativeRegion => Boolean(region));
for (const [index, header] of (reconstruction?.header_regions || []).entries()) {
const headerId = `header_${pageNo}_${index + 1}`;
for (const [fieldIndex, field] of (header.fields || []).entries()) {
suggestedRegions.push({
id: `${headerId}-field-${fieldIndex + 1}`,
kind: 'header_field', parentId: headerId,
label: field.field_code || field.text || unboundColumnLabel(fieldIndex + 1),
region: field.region, fieldCode: field.field_code || null, pageNo,
});
}
}
for (const [index, candidate] of orderFieldCandidates.entries()) {
if (candidate.scope === 'line') continue;
if (candidate.status !== 'suggested' || !candidate.value_region) continue;
const orderFieldId = `order_field_${pageNo}_${candidate.field_code}_${index + 1}`;
if (candidate.anchor_region && candidate.anchor_text) {
suggestedRegions.push({
id: `${orderFieldId}_anchor`, kind: 'order_anchor', label: candidate.anchor_text,
region: candidate.anchor_region, orderFieldId, pageNo,
});
}
suggestedRegions.push({
id: orderFieldId, kind: 'order_field',
label: candidate.field_code ? candidate.display_name : `${candidate.display_name} · ${unboundColumnLabel(index + 1)}`,
region: candidate.value_region, fieldCode: candidate.field_code || null, orderFieldId,
valueMode: candidate.value_mode, suggestedValue: candidate.suggested_value || null,
evidenceSource: candidate.source, pageNo,
});
}
const layouts = (reconstruction?.subrow_layouts || []).slice().sort(
(left, right) => left.row_offset - right.row_offset,
).filter((layout) => {
const region = layout.region;
if (!region) return true;
return !headerRegions.some((headerRegion) => {
const horizontalOverlap = Math.max(0, Math.min(region.x1, headerRegion.x1) - Math.max(region.x0, headerRegion.x0));
const verticalOverlap = Math.max(0, Math.min(region.y1, headerRegion.y1) - Math.max(region.y0, headerRegion.y0));
const layoutWidth = region.x1 - region.x0;
const headerWidth = headerRegion.x1 - headerRegion.x0;
const layoutHeight = region.y1 - region.y0;
const headerHeight = headerRegion.y1 - headerRegion.y0;
return layoutWidth > 0 && headerWidth > 0 && layoutHeight > 0 && headerHeight > 0
&& horizontalOverlap / Math.min(layoutWidth, headerWidth) >= 0.8
&& verticalOverlap / Math.min(layoutHeight, headerHeight) >= 0.8;
});
});
for (const layout of layouts) {
const lineId = `line_${pageNo}_${layout.row_offset + 1}`;
const region = layout.region || {
x0: 0.04, y0: 0.22 + layout.row_offset * 0.075,
x1: 0.96, y1: 0.285 + layout.row_offset * 0.075,
};
suggestedRegions.push({
id: lineId, kind: 'line', label: lineLabel(layout.row_offset + 1), region, pageNo,
});
layout.column_boundaries.slice(0, -1).forEach((left, index) => {
const right = layout.column_boundaries[index + 1];
if (right === undefined) return;
const fieldCode = layout.row_offset === 0 ? layout.suggested_field_codes[index] || null : null;
suggestedRegions.push({
id: `${lineId}-field-${index + 1}`, kind: 'field', parentId: lineId,
label: fieldCode || unboundColumnLabel(index + 1), fieldCode,
region: {
x0: region.x0 + (region.x1 - region.x0) * left, y0: region.y0,
x1: region.x0 + (region.x1 - region.x0) * right, y1: region.y1,
}, pageNo,
});
});
}
for (const [index, candidate] of orderFieldCandidates.entries()) {
if (candidate.scope !== 'line' || candidate.status !== 'suggested' || !candidate.value_region) continue;
const centerX = (candidate.value_region.x0 + candidate.value_region.x1) / 2;
const centerY = (candidate.value_region.y0 + candidate.value_region.y1) / 2;
const matchingLayouts = layouts.filter((layout) => {
const region = layout.region || {
x0: 0.04, y0: 0.22 + layout.row_offset * 0.075,
x1: 0.96, y1: 0.285 + layout.row_offset * 0.075,
};
return centerX >= region.x0 && centerX <= region.x1 && centerY >= region.y0 && centerY <= region.y1;
});
// 无唯一候选行时不私自挂靠到任一明细行,保留待复核事实。
if (matchingLayouts.length !== 1) continue;
const lineId = `line_${pageNo}_${matchingLayouts[0]!.row_offset + 1}`;
suggestedRegions.push({
id: `${lineId}-widget-${index + 1}`,
kind: 'field', parentId: lineId,
label: candidate.field_code || candidate.display_name || unboundColumnLabel(index + 1),
fieldCode: candidate.field_code || null,
region: candidate.value_region,
evidenceSource: candidate.source,
pageNo,
});
}
return suggestedRegions;
};
/**
* 仅在没有多来源候选或结构冲突时选择行重建结果。
* 核心逻辑:native/OCR 都是候选证据;多来源时禁止沿用后端的优先投影,避免前端静默裁决。
* @param reconstruction - 后端为兼容旧画布返回的单一路径投影
* @param tableReconstructions - 各证据来源的候选摘要
* @param conflicts - 后端检测到的结构冲突
* @returns 可安全用于生成行框的重建结果;存在并行候选或冲突时返回 null
*/
export const selectAutomarkReconstruction = (
reconstruction: CoordinateReconstructionSuggestion | null | undefined,
tableReconstructions: unknown,
conflicts: unknown,
selectedCandidate?: CoordinateReconstructionSuggestion | null,
): CoordinateReconstructionSuggestion | null => {
// 管理员已明确选择(或 UI 已确认唯一)的候选时,应使用该来源本身;特别是
// 动态 XFA 只有 Widget 几何而 coordinate_reconstruction 为 null 的情形。
if (selectedCandidate) return selectedCandidate;
if (!reconstruction) return null;
if (Array.isArray(conflicts) && conflicts.length > 0) return null;
if (Array.isArray(tableReconstructions) && tableReconstructions.length > 1) return null;
return reconstruction;
};
/**
* 为多证据表格候选生成只读摘要,供人工确认区展示。
* 核心逻辑:摘要只反映行/列几何与冲突来源,不显示或选择任何正式 datasets 值。
*/
export const summarizeAutomarkTableCandidates = (
candidates: Array<{ source: string; reconstruction: CoordinateReconstructionSuggestion }>,
conflicts: unknown,
): Array<{ source: string; rowCount: number; columnCount: number; conflictCodes: string[]; status: 'needs_review' }> => {
const conflictItems = Array.isArray(conflicts) ? conflicts.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object')) : [];
return candidates.map((candidate) => {
const layouts = Array.isArray(candidate.reconstruction.subrow_layouts) ? candidate.reconstruction.subrow_layouts : [];
const columnCount = layouts.reduce((max, layout) => {
const boundaries = Array.isArray(layout.column_boundaries) ? layout.column_boundaries.length - 1 : 0;
return Math.max(max, boundaries);
}, 0);
const conflictCodes = conflictItems
.filter((item) => Array.isArray(item.sources) && item.sources.map(String).includes(candidate.source))
.map((item) => String(item.code || 'table_reconstruction_source_conflict'));
return { source: candidate.source, rowCount: layouts.length, columnCount, conflictCodes, status: 'needs_review' };
});
};
/**
* 为多来源自动标注候选提供可审阅的默认来源。
* 原生 PDF 坐标是首选建议,但这只是预选,不绕过人工接受和 Review 门禁;
* 没有原生候选时才使用候选列表中的第一来源。
*/
export const preferredAutomarkTableSource = (
candidates: Array<{ source: string }>,
): string => (
candidates.find((candidate) => candidate.source === 'pdf_coordinate')?.source
|| candidates[0]?.source
|| ''
);
/**
* 将后端统一 field_binding DTO 转为旧页面候选形状,并保留真实证据来源。
* 核心逻辑:只接受视觉 binding;evidence_sources 为空时按不可确认处理,禁止默认宣称 native。
* @param candidates - 自动标记 Job 返回的候选 DTO。
* @param pageNo - 当前画布页码。
* @returns 仅供页面复核的订单字段候选。
*/
export const normalizeAutomarkFieldCandidates = (
candidates: Array<Record<string, unknown>>,
): OrderFieldLayoutSuggestion[] => {
const merged = new Map<string, OrderFieldLayoutSuggestion>();
candidates
.filter((item) => item.candidate_kind === 'field_binding' && item.binding && typeof item.binding === 'object')
.forEach((item) => {
const binding = item.binding as Record<string, unknown>;
const visual = binding.visual_binding && typeof binding.visual_binding === 'object'
? binding.visual_binding as Record<string, unknown> : {};
const sources = Array.isArray(item.evidence_sources)
? item.evidence_sources.map((source) => String(source || '')).filter(Boolean)
: [];
const source = sources[0] === 'ocr_coordinate' || sources[0] === 'acroform_widget'
? sources[0] : 'pdf_coordinate';
const needsReview = item.needs_review === true || !sources.length;
const next = {
field_id: String(binding.field_id || ''),
field_code: String(binding.field_code || ''),
// 未匹配的 XFA/AcroForm Widget 只有技术控件名和几何;它必须作为
// 未绑定视觉候选进入共同画布,不能因 field_code 为空而丢失,也不能猜业务字段。
display_name: String(binding.field_code || binding.display_name || binding.field_id || ''),
scope: binding.scope === 'line' ? 'line' : 'header',
source,
status: 'suggested',
issue: needsReview ? 'visual_candidate_needs_review' : null,
anchor_text: undefined,
anchor_region: undefined,
value_region: visual.normalized_bbox as OrderProfileRelativeRegion | undefined,
} satisfies OrderFieldLayoutSuggestion;
const bbox = next.value_region;
const key = `${next.field_id}|${next.scope}|${JSON.stringify(bbox || {})}`;
const previous = merged.get(key);
if (previous) {
previous.issue = previous.issue || next.issue;
return;
}
merged.set(key, next);
});
return [...merged.values()];
};
/**
* 判断是否显示普通表格预览;可直接创建 Profile 的表格不受上一张表多物理行状态影响。
* @param profileCreationAllowed - 当前表格是否可直接创建 Profile
* @param multiSubrowEnabled - 当前是否启用多物理行坐标重建
* @param coordinateReconstructionAvailable - 当前表格是否具备坐标重建证据
* @returns 为 true 时显示普通表格及字段配置入口
*/
export const shouldShowStandardOrderProfilePreview = (
profileCreationAllowed: boolean,
multiSubrowEnabled: boolean,
coordinateReconstructionAvailable: boolean,
): boolean => (
profileCreationAllowed || !multiSubrowEnabled || !coordinateReconstructionAvailable
);
/**
* 将表头区域内同一逻辑列的多行文字合并为虚拟列头,重复的 rowspan/colspan 文本只保留一次。
* @param rows - 后端展开后的样本表格行
* @param headerRowIndex - 最后一行表头的零基索引
* @param columnCount - 表格逻辑列数
* @returns 与逻辑列一一对应的合并表头文字
*/
export const mergeOrderProfileHeaderLabels = (
rows: string[][], headerRowIndex: number, columnCount: number,
): string[] => Array.from({ length: columnCount }, (_, columnIndex) => {
const labels: string[] = [];
rows.slice(0, Math.max(headerRowIndex + 1, 0)).forEach((row) => {
const label = String(row[columnIndex] || '').replace(/\s+/g, ' ').trim();
if (label && !labels.some((item) => item.toLowerCase() === label.toLowerCase())) labels.push(label);
});
return labels.join(' / ');
});
/**
* 将历史页作用域恢复为单页画布页码;旧 all_pages 缺少原始页号时按首篇样例页迁移。
* @param tableRegion - 已保存的 v2 表格区域
* @returns 当前画布应显示的 1 基页码
*/
export const restoreOrderProfileRegionPageNo = (tableRegion: OrderProfileTableRegion): number => {
if (tableRegion.page_scope === 'exact_page') return tableRegion.page_no || 1;
return tableRegion.page_scope === 'continuation_pages' ? 2 : 1;
};
/**
* 将画布锚点转换为 v2 契约允许的稳定标识。
* @param anchor - 当前订单字段关联的标签区域;历史草稿可能没有可用的区域 ID。
* @returns 可写入 AnchorRule 的 anchor_id;无法确定锚点时返回 null 并由调用方使用固定坐标回退。
*/
export const toOrderProfileAnchorId = (
anchor: Pick<OrderProfileCanvasRegion, 'id' | 'label' | 'orderFieldId'> | null | undefined,
): string | null => {
if (!anchor) return null;
const source = String(anchor.id || anchor.orderFieldId || anchor.label || '')
.trim()
.replace(/^unbound-/i, '');
if (!source) return null;
const normalized = source
.toLocaleLowerCase()
.replace(/[^a-z0-9]+/g, '_')
.replace(/^_+|_+$/g, '');
if (!normalized) return null;
const prefixed = /^[a-z]/.test(normalized) ? normalized : `anchor_${normalized}`;
return prefixed.slice(0, 64);
};
export interface OrderProfileRecognitionResult {
id: string | null;
key: string;
fieldCode: string;
value: string | null;
status: 'read' | 'review' | 'loading' | 'failed' | 'unavailable' | 'deleted';
rowNo?: number;
}
/** Reservation 专用证据区域的后端统一候选;前端只按已给出的 scope 投影展示。 */
export interface ReservationRegionRecognitionCandidate {
value: string;
line_no: number | null;
scope: 'header' | 'line';
raw_text: string;
status: string;
}
/**
* 将坐标重建的首条数据行映射到画布上的明细字段框。
* @param pageRegions - 当前页画布区域。
* @param reconstruction - 坐标重建接口返回的表头与数据行。
* @returns region id 到当前样本明细值的映射;无值或无匹配框时不返回该项。
*/
export const buildOrderProfileCanvasLineFieldValues = (
pageRegions: OrderProfileCanvasRegion[],
reconstruction: CoordinateReconstructionPreview | null,
): Record<string, string> => {
const regionsByCode = new Map(
pageRegions
.filter((item) => item.kind === 'field' && item.fieldCode)
.reduce<[string, string][]>((entries, item) => {
if (!entries.some(([fieldCode]) => fieldCode === item.fieldCode)) {
entries.push([item.fieldCode!, item.id]);
}
return entries;
}, []),
);
if (!reconstruction) return {};
const fieldCodes = reconstruction.rows[0] || [];
const dataIndex = reconstruction.row_roles.findIndex((role, index) => index > 0 && role === 'data');
if (dataIndex < 0) return {};
return Object.fromEntries(
fieldCodes.flatMap((fieldCode, columnIndex) => {
const regionId = regionsByCode.get(fieldCode);
const value = reconstruction.rows[dataIndex]?.[columnIndex] || '';
return regionId && value ? [[regionId, value] as const] : [];
}),
);
};
/**
* 将已有坐标预览和值读取结果变为可反向定位的结构化复核项。
* @param pageRegions - 当前页画布区域;未标注字段不会伪装成可定位项。
* @param fieldValues - 订单表头字段值接口的结果。
* @param reconstruction - 坐标重建接口的明细行结果。
* @returns 表头及明细字段结果,均保留对应画布区域 ID。
*/
export const buildOrderProfileRecognitionResults = (
pageRegions: OrderProfileCanvasRegion[],
fieldValues: OrderFieldValuePreview[],
reconstruction: CoordinateReconstructionPreview | null,
fieldValueState: 'idle' | 'loading' | 'ready' | 'failed' = 'idle',
datasetsEvidence: OrderProfileValidationEvidence | null = null,
reservationCandidates: ReservationRegionRecognitionCandidate[] = [],
): { header: OrderProfileRecognitionResult[]; line: OrderProfileRecognitionResult[] } => {
const valuesByCode = new Map(fieldValues.map((item) => [item.field_code, item]));
const header = pageRegions
.filter((item) => item.kind === 'order_field' && item.fieldCode)
.map((item) => {
const value = valuesByCode.get(item.fieldCode!);
return {
id: item.id,
key: item.id,
fieldCode: item.fieldCode!,
// 实时复核只接受当前坐标读取结果,不能回退显示历史自动建议缓存。
value: value?.value || null,
status: value?.value ? 'read' as const
: fieldValueState === 'loading' ? 'loading' as const
: fieldValueState === 'failed' ? 'failed' as const : 'unavailable' as const,
};
});
const regionsByCode = new Map(
pageRegions
.filter((item) => item.kind === 'field' && item.fieldCode)
.map((item) => [item.fieldCode!, item.id]),
);
// XFA datasets 是正式明细值源;共同视觉坐标只定位和交叉校验,不能把表头或
// OCR 候选伪装成已读取的行值。传入此证据时完全忽略 coordinate reconstruction。
if (datasetsEvidence) {
const line = datasetsEvidence.lines.flatMap((row) => (
row.fields.map((field) => ({
id: regionsByCode.get(field.field_code) || null,
key: `xfa-${row.row_index}-${field.field_code}`,
fieldCode: field.field_code,
value: field.normalized_value || null,
status: field.status === 'passed' && field.normalized_value
? 'read' as const
: 'unavailable' as const,
rowNo: row.row_index + 1,
}))
));
return applyReservationRegionRecognitionResults(
header, line, reservationCandidates, datasetsEvidence.lines.length,
);
}
if (!reconstruction) {
return applyReservationRegionRecognitionResults(header, [], reservationCandidates, 0);
}
const fieldCodes = reconstruction.rows[0] || [];
const line = reconstruction.rows.slice(1).flatMap((row, rowIndex) => {
const sourceIndex = rowIndex + 1;
const role = reconstruction.row_roles[sourceIndex];
if (role !== 'data' && role !== 'deleted') return [];
return fieldCodes.map((fieldCode, columnIndex) => ({
id: regionsByCode.get(fieldCode) || null,
key: `${sourceIndex}-${fieldCode}`,
fieldCode,
value: row[columnIndex] || null,
status: role === 'deleted'
? 'deleted' as const
: row[columnIndex] ? 'read' as const : 'unavailable' as const,
rowNo: rowIndex + 1,
}));
});
return applyReservationRegionRecognitionResults(
header, line, reservationCandidates,
reconstruction.row_roles.filter((role) => role === 'data').length,
);
};
/**
* 将服务端已归属的 Reservation 候选投影到右侧正式结果区。
*
* 这里不解析文本、不猜测行号:无行号候选只进订单表头,带行号候选只进对应
* 逻辑明细行。专用区域没有普通字段框,因此条目不可点击定位到字段框。
*/
const applyReservationRegionRecognitionResults = (
header: OrderProfileRecognitionResult[],
line: OrderProfileRecognitionResult[],
candidates: ReservationRegionRecognitionCandidate[],
logicalLineCount: number,
): { header: OrderProfileRecognitionResult[]; line: OrderProfileRecognitionResult[] } => {
const reservationHeaders = candidates
.filter((item) => item.scope === 'header' && item.value)
.map((item, index) => ({
id: null,
key: `reservation-region-header-${index}-${item.value}`,
fieldCode: 'reservation_id',
value: item.value,
status: 'read' as const,
}));
const reservationLines = candidates.flatMap((item, index) => {
if (
item.scope !== 'line' || item.line_no === null || !item.value
|| item.line_no < 1 || item.line_no > logicalLineCount
) return [];
return [{
id: null,
key: `reservation-region-line-${item.line_no}-${index}-${item.value}`,
fieldCode: 'reservation_id',
value: item.value,
status: 'read' as const,
rowNo: item.line_no,
}];
});
return { header: [...header, ...reservationHeaders], line: [...line, ...reservationLines] };
};
/**
* 选择与当前草稿精确匹配的 XFA 当前样本正式证据。
* 核心逻辑:验证 Run 是不可变的;只消费 current_sample、passed、checksum 相同的
* datasets 证据,旧版本或其他运行类型不能在编辑工作台伪装成当前样本值。
*/
export const selectCurrentDatasetsValidationEvidence = (
runs: OrderProfileValidationRun[],
definitionChecksum: string | null | undefined,
): OrderProfileValidationEvidence | null => {
if (!definitionChecksum) return null;
const run = runs.find((item) => (
item.run_type === 'current_sample'
&& item.status === 'passed'
&& item.definition_checksum === definitionChecksum
));
const evidence = run?.summary?.validation_evidence;
if (!evidence || typeof evidence !== 'object' || Array.isArray(evidence)) return null;
const value = evidence as Partial<OrderProfileValidationEvidence>;
if (!Array.isArray(value.header_fields) || !Array.isArray(value.lines)) return null;
return {
header_fields: value.header_fields,
lines: value.lines,
cross_checks: value.cross_checks && typeof value.cross_checks === 'object' && !Array.isArray(value.cross_checks)
? value.cross_checks : {},
...(typeof value.reservation_region_status === 'string'
? { reservation_region_status: value.reservation_region_status }
: {}),
...(Array.isArray(value.reservation_region_review_reasons)
? { reservation_region_review_reasons: value.reservation_region_review_reasons.map((item) => String(item)) }
: {}),
};
};
/**
* 根据已确认表头的横向覆盖关系建议明细字段;冲突或覆盖不足时拒绝猜测。
* @param fieldRegion - 当前待绑定的明细字段区域
* @param headerRegions - 所有页面上已确认 Schema 字段的表头区域
* @returns 唯一且覆盖至少一半字段宽度的 field_code,否则返回 null
*/
export const suggestFieldCodeFromHeaders = (
fieldRegion: OrderProfileCanvasRegion,
headerRegions: OrderProfileCanvasRegion[],
): string | null => {
const width = fieldRegion.region.x1 - fieldRegion.region.x0;
if (fieldRegion.kind !== 'field' || width <= 0) return null;
const candidates = headerRegions
.filter((item) => item.kind === 'header_field' && item.fieldCode)
.map((item) => ({
fieldCode: item.fieldCode!,
overlap: Math.max(
0,
Math.min(fieldRegion.region.x1, item.region.x1) - Math.max(fieldRegion.region.x0, item.region.x0),
) / width,
}))
.filter((item) => item.overlap >= .5)
.sort((left, right) => right.overlap - left.overlap);
if (!candidates.length) return null;
const best = candidates[0]!;
const competing = candidates.find((item, index) => (
index > 0 && item.fieldCode !== best.fieldCode && Math.abs(item.overlap - best.overlap) < .1
));
return competing ? null : best.fieldCode;
};
@@ -0,0 +1,80 @@
/**
* features/admin/modules/shipping-order-document-profiles/orderProfileReadonlyCanvas.utils.spec.ts
* 用途:验证版本只读画布完整恢复模板定义中的诊断区域。
* 依赖:Vitest、orderProfileReadonlyCanvas.utils。
* 逻辑:已发布版本的必需锚点必须同时显示标签框和值框,且区域 ID 与冻结诊断接口一致;
* 仅含 fallback 的未绑定订单字段框也必须恢复,供签名空白区强制可见。
*/
import { describe, expect, it } from 'vitest';
import type { ShippingOrderDocumentProfile } from '@/features/admin/types/shipping-order-document-profile.types';
import { buildOrderProfileReadonlyRegions } from './orderProfileReadonlyCanvas.utils';
describe('buildOrderProfileReadonlyRegions', () => {
it('restores required anchor label and value regions on the published canvas', () => {
const profile = {
definition: {
document_match: {
required_anchors: [{
anchor_id: 'plant_address',
label: 'PLANT ADDR:',
value: 'No. 88',
value_position: 'right',
page_no: 1,
label_region: { x0: .1, y0: .1, x1: .2, y1: .15 },
value_region: { x0: .2, y0: .1, x1: .5, y1: .2 },
minimum_evidence_level: 'coordinate',
}],
optional_anchors: [],
},
table_regions: [],
order_field_layouts: [],
draft_unbound_order_field_layouts: [],
},
} as unknown as ShippingOrderDocumentProfile;
const regions = buildOrderProfileReadonlyRegions(profile);
// 关键断言:版本画布与后端诊断接口使用同一 region ID,标签和值均不可丢失。
expect(regions).toEqual(expect.arrayContaining([
expect.objectContaining({ id: 'plant_address_label', kind: 'document_anchor_label', configuredValue: 'PLANT ADDR:' }),
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 },
}),
]));
});
});
@@ -0,0 +1,200 @@
/**
* features/admin/modules/shipping-order-document-profiles/orderProfileReadonlyCanvas.utils.ts
* 用途:把模板定义恢复成版本详情只读画布可渲染的区域集合。
* 依赖:订单模板类型、restoreOrderProfileRegionPageNo。
* 逻辑:版本详情只读展示几何和绑定身份,不写回表单或草稿状态。
*/
import type {
OrderProfileCanvasRegion,
ShippingOrderDocumentProfile,
} from '@/features/admin/types/shipping-order-document-profile.types';
import { asVisualProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
import { restoreOrderProfileRegionPageNo } from './orderProfileForm.utils';
const mergeEquivalentOrderAnchors = (items: OrderProfileCanvasRegion[]) => {
const canonicalByKey = new Map<string, string>();
const anchorIds = new Map<string, string>();
const retained: OrderProfileCanvasRegion[] = [];
const anchorKey = (item: OrderProfileCanvasRegion) => [
item.pageNo,
item.label.trim().toLocaleLowerCase(),
item.region.x0,
item.region.y0,
item.region.x1,
item.region.y1,
].join('|');
for (const item of items) {
if (item.kind !== 'order_anchor') {
retained.push(item);
continue;
}
const canonicalId = canonicalByKey.get(anchorKey(item));
if (canonicalId) {
anchorIds.set(item.id, canonicalId);
if (item.orderFieldId) anchorIds.set(`layout:${item.orderFieldId}`, canonicalId);
continue;
}
canonicalByKey.set(anchorKey(item), item.id);
anchorIds.set(item.id, item.id);
if (item.orderFieldId) anchorIds.set(`layout:${item.orderFieldId}`, item.id);
retained.push(item);
}
return retained.map((item) => item.kind === 'order_field'
? {
...item,
parentId: item.parentId
? anchorIds.get(item.parentId) || item.parentId
: item.orderFieldId
? anchorIds.get(`layout:${item.orderFieldId}`) || null
: null,
}
: item);
};
const pageNoOf = (pageScope: 'first_page' | 'all_pages' | 'exact_page', pageNo?: number | null) =>
pageScope === 'exact_page' ? (pageNo || 1) : 1;
/**
* 从版本详情定义恢复只读画布区域;标签统一优先使用 field_code,避免引入可编辑态依赖。
*/
export const buildOrderProfileReadonlyRegions = (
profile: ShippingOrderDocumentProfile,
): OrderProfileCanvasRegion[] => {
const definition = asVisualProfileDefinition(profile.definition);
const restored: OrderProfileCanvasRegion[] = [
...(definition.document_match.required_anchors || []).flatMap<OrderProfileCanvasRegion>((anchor) => {
if (!anchor.label_region || !anchor.value_region || !anchor.page_no) return [];
return [{
id: `${anchor.anchor_id}_label`,
kind: 'document_anchor_label',
label: anchor.label,
configuredValue: anchor.label,
region: anchor.label_region,
parentId: anchor.anchor_id,
pageNo: anchor.page_no,
}, {
id: `${anchor.anchor_id}_value`,
kind: 'document_anchor_value',
label: anchor.value,
configuredValue: anchor.value,
region: anchor.value_region,
parentId: anchor.anchor_id,
pageNo: anchor.page_no,
}];
}),
...(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}`,
kind: 'order_field',
label: item.label,
region: item.fallback_value_region || { x0: .1, y0: .1, x1: .2, y1: .15 },
fieldCode: null,
pageNo,
}];
}
const anchor = item.anchor.region;
return [{
id: `unbound-${item.anchor.anchor_id}`,
kind: 'order_anchor',
label: item.anchor.text,
region: anchor,
orderFieldId: item.layout_id,
pageNo,
}, {
id: `unbound-${item.layout_id}`,
kind: 'order_field',
label: item.label,
region: item.absolute_value_region,
fieldCode: null,
orderFieldId: item.layout_id,
pageNo,
}];
}),
...(definition.order_field_layouts || []).filter((item) => !item.anchor).map((item) => ({
id: item.layout_id,
kind: 'order_field' as const,
label: item.field_code,
region: item.fallback_value_region || { x0: .1, y0: .1, x1: .2, y1: .15 },
fieldCode: item.field_code,
pageNo: pageNoOf(item.page_scope, item.page_no),
})),
...(definition.order_field_layouts || []).flatMap((item) => {
if (!item.anchor?.region || !item.absolute_value_region) return [];
const anchor = item.anchor.region;
return [{
id: item.anchor.anchor_id,
kind: 'order_anchor' as const,
label: item.anchor.text,
region: anchor,
orderFieldId: item.layout_id,
pageNo: pageNoOf(item.page_scope, item.page_no),
}, {
id: item.layout_id,
kind: 'order_field' as const,
label: item.field_code,
region: item.absolute_value_region,
fieldCode: item.field_code,
orderFieldId: item.layout_id,
valueMode: item.value_mode,
stopAnchorText: item.stop_anchors[0]?.text || null,
pageNo: pageNoOf(item.page_scope, item.page_no),
}];
}),
...definition.table_regions.flatMap((table) => {
const regionPageNo = restoreOrderProfileRegionPageNo(table);
const headerLayoutIds = new Set(table.header_layouts.map((item) => item.layout_id));
return [
...table.header_layouts.flatMap((header) =>
header.field_regions.map((item, index) => ({
id: `${header.layout_id}-field-${index}`,
kind: 'header_field' as const,
label: item.field_code,
fieldCode: item.field_code,
region: item.region,
parentId: header.layout_id,
pageNo: regionPageNo,
})),
),
...table.line_layouts.map((item) => ({
id: item.layout_id,
kind: 'line' as const,
label: item.layout_id,
region: item.region,
pageNo: regionPageNo,
})),
...table.line_layouts.flatMap((line) =>
line.field_regions.map((item, index) => ({
id: `${line.layout_id}-field-${index}`,
kind: 'field' as const,
label: item.field_code,
region: item.region,
fieldCode: item.field_code,
parentId: line.layout_id,
pageNo: regionPageNo,
})),
),
...(table.draft_unbound_field_regions || []).map((item) => ({
id: item.region_id,
kind: headerLayoutIds.has(item.parent_layout_id) ? ('header_field' as const) : ('field' as const),
label: item.label,
region: item.region,
fieldCode: null,
parentId: item.parent_layout_id,
pageNo: regionPageNo,
})),
...table.exclusion_regions.map((region, index) => ({
id: `exclusion-${regionPageNo}-${index}`,
kind: 'exclusion' as const,
label: `exclusion ${index + 1}`,
region,
pageNo: regionPageNo,
})),
];
}),
];
return mergeEquivalentOrderAnchors(restored);
};
@@ -0,0 +1,199 @@
/**
* features/admin/modules/shipping-order-document-profiles/xfaProfileMapping.utils.spec.ts
* 用途:验证 XFA 映射工具函数——含 split_rules mapped 目标的 bound field 与覆盖率。
* 依赖:Vitest、xfaProfileMapping.utils。
*/
import { describe, expect, it } from 'vitest';
import {
collectBoundXfaFieldIds,
computeXfaMappingCoverage,
flattenXfaTreeNodes,
hashXfaDataPath,
resolveAuthoritativePathId,
resolveMirrorPathIds,
summarizeXfaMappingBlockers,
} from './xfaProfileMapping.utils';
import type {
OrderXfaDatasetProfileDefinition,
XfaCollectionCandidate,
XfaFieldTreeNode,
} from '@/features/admin/types/shipping-order-document-profile.types';
const baseDefinition: OrderXfaDatasetProfileDefinition = {
template_mode: 'xfa_dataset',
source_contract: {
template_packet_checksum: 'tpl',
dataset_structure_fingerprint: 'fp',
dataset_root_path: '/data',
authoritative_line_collection_path: '/data/ITEMS/DATA',
mirror_collection_paths: [],
},
header_mappings: [],
line_mapping: { row_path: '/data/ITEMS/DATA', fields: [] },
cross_checks: {
acroform_enabled: false,
mirror_collection_policy: 'ignore',
line_amount_formula: 'disabled',
total_amount_policy: 'disabled',
},
split_rules: [{
rule_id: 'matnr-v1',
rule_version: 1,
source_path_id: 'path-matnr',
source_field_code: 'MATNR',
strategy: 'pipeline',
rules: [{
rule_id: 'r1',
order: 1,
stages: [
{ stage_id: 'st1', type: 'split_lines', line_breaks: ['\n'] },
{ stage_id: 'st2', type: 'select_line', line_index: 1 },
],
segment: {
segment_id: 'seg-1',
segment_code: 'cpn',
display_name: 'CPN',
handling: 'mapped',
target_field_id: 'f-cpn',
target_field_code: 'customer_part_number',
},
}],
status: 'confirmed',
source: 'user',
requires_confirmation: false,
}],
};
describe('xfaProfileMapping split utils', () => {
it('collectBoundXfaFieldIds includes split mapped targets', () => {
const ids = collectBoundXfaFieldIds(baseDefinition);
expect(ids.has('f-cpn')).toBe(true);
});
it('computeXfaMappingCoverage does not treat Schema required fields as template blockers', () => {
const coverage = computeXfaMappingCoverage(
[{
field_id: 'f-cpn',
field_code: 'customer_part_number',
scope: 'line',
enabled: true,
required: true,
value_type: 'string',
}],
baseDefinition,
'path-data',
);
expect(coverage.missingRequired).toHaveLength(0);
expect(coverage.requiredTotal).toBe(0);
expect(coverage.requiredMapped).toBe(0);
expect(summarizeXfaMappingBlockers(coverage)).not.toContain('required_fields_unmapped');
});
it('flattenXfaTreeNodes copies line_count to lineCount', () => {
const tree: XfaFieldTreeNode = {
path_id: 'root',
local_name: 'data',
data_path_hash: 'h-root',
depth: 0,
cardinality: 'one',
is_leaf: false,
children: [{
path_id: 'matnr',
local_name: 'MATNR',
data_path_hash: 'h-matnr',
depth: 1,
cardinality: 'one',
is_leaf: true,
line_count: 5,
}],
};
const flat = flattenXfaTreeNodes(tree);
const matnr = flat.find((item) => item.pathId === 'matnr');
expect(matnr?.lineCount).toBe(5);
});
it('selectedIsMultiline uses lineCount greater than one', () => {
const tree: XfaFieldTreeNode = {
path_id: 'single',
local_name: 'FIELD',
data_path_hash: 'h1',
depth: 0,
cardinality: 'one',
is_leaf: true,
line_count: 1,
};
const flat = flattenXfaTreeNodes(tree);
expect((flat[0]?.lineCount || 0) > 1).toBe(false);
const multiline: XfaFieldTreeNode = { ...tree, path_id: 'multi', line_count: 3 };
const flatMulti = flattenXfaTreeNodes(multiline);
expect((flatMulti[0]?.lineCount || 0) > 1).toBe(true);
});
it('restores legacy source contract collection path ids by exact path hash', async () => {
const authoritativePath = '/data/ORDER/ITEMS/DATA';
const mirrorPath = '/data/ORDER/ITEMS_COPY/DATA';
const candidates: XfaCollectionCandidate[] = [{
path_id: 'path-unrelated',
collection_path_hash: await hashXfaDataPath('/data/OTHER/DATA'),
path_label: 'Same display name',
local_name: 'DATA',
field_names: [],
field_count: 0,
non_empty_field_count: 0,
non_empty_rate: 0,
row_count: 0,
selectable: true,
recommended_role: 'candidate',
recommendation_reasons: [],
exclusion_reasons: [],
sibling_collection_path_hashes: [],
}, {
path_id: 'path-authoritative',
collection_path_hash: await hashXfaDataPath(authoritativePath),
path_label: 'Same display name',
local_name: 'DATA',
field_names: [],
field_count: 0,
non_empty_field_count: 0,
non_empty_rate: 0,
row_count: 1,
selectable: true,
recommended_role: 'authoritative',
recommendation_reasons: [],
exclusion_reasons: [],
sibling_collection_path_hashes: [],
}, {
path_id: 'path-mirror',
collection_path_hash: await hashXfaDataPath(mirrorPath),
path_label: 'Same display name',
local_name: 'DATA',
field_names: [],
field_count: 0,
non_empty_field_count: 0,
non_empty_rate: 0,
row_count: 1,
selectable: true,
recommended_role: 'mirror',
recommendation_reasons: [],
exclusion_reasons: [],
sibling_collection_path_hashes: [],
}];
const definition: OrderXfaDatasetProfileDefinition = {
...baseDefinition,
source_contract: {
...baseDefinition.source_contract,
authoritative_line_collection_path: authoritativePath,
mirror_collection_paths: [mirrorPath],
},
};
const authoritativePathId = await resolveAuthoritativePathId(definition, candidates, []);
const mirrorPathIds = await resolveMirrorPathIds(definition, candidates, authoritativePathId);
// 关键断言:历史定义只能以完整路径哈希恢复,不得按同名 DATA 或候选排序猜测。
expect(authoritativePathId).toBe('path-authoritative');
expect(mirrorPathIds).toEqual(['path-mirror']);
});
});
@@ -0,0 +1,476 @@
/**
* features/admin/modules/shipping-order-document-profiles/xfaProfileMapping.utils.ts
* 用途:XFA 映射工作台纯函数——树投影、Schema 过滤、覆盖率、保存 payload 与脏状态检测。
* 依赖:shipping-order-document-profile.types、订单 Schema 字段类型。
* 逻辑:页面与组件只调用本文件;不发网络请求,不持有明文 XML 或 data_path。
*/
import type {
OrderXfaDatasetProfileDefinition,
XfaCollectionCandidate,
XfaFieldMapping,
XfaFieldTreeNode,
XfaMappingCoverageSummary,
} from '@/features/admin/types/shipping-order-document-profile.types';
import type { ShippingOrderFieldConfig } from '@/features/admin/types/shipping-order-schema.types';
export type XfaSchemaFilterMode = 'all' | 'unmapped';
export interface XfaFlatTreeNode {
pathId: string;
localName: string;
depth: number;
isLeaf: boolean;
isHeaderCandidate: boolean;
isCollectionCandidate: boolean;
sampleValueMasked?: string;
sampleValueDisplay?: string;
displayPolicy: 'empty' | 'full' | 'partial' | 'restricted';
canReveal: boolean;
lineCount?: number;
dataPathHash: string;
parentPathId?: string;
}
export interface XfaMappingWorkbenchState {
definition: OrderXfaDatasetProfileDefinition;
authoritativeCollectionPathId: string;
mirrorCollectionPathIds: string[];
}
/**
* 将 XFA 字段树投影为可键盘导航的扁平节点列表。
* 核心逻辑:深度优先展开;仅保留分析记录返回的节点。
* @param tree 字段树根节点
* @returns 扁平节点(含 depth / leaf / collection 标记)
*/
export function flattenXfaTreeNodes(tree: XfaFieldTreeNode | null | undefined): XfaFlatTreeNode[] {
if (!tree || !tree.path_id) return [];
const rows: XfaFlatTreeNode[] = [];
const walk = (node: XfaFieldTreeNode, parentPathId?: string): void => {
rows.push({
pathId: node.path_id,
localName: node.local_name,
depth: node.depth,
isLeaf: Boolean(node.is_leaf),
isHeaderCandidate: Boolean(node.is_header_candidate),
isCollectionCandidate: Boolean(node.is_collection_candidate),
sampleValueMasked: node.sample_value_masked,
sampleValueDisplay: node.sample_value_display || node.sample_value_masked,
displayPolicy: node.display_policy || 'empty',
canReveal: Boolean(node.can_reveal),
lineCount: node.line_count,
dataPathHash: node.data_path_hash,
parentPathId,
});
for (const child of node.children || []) walk(child, node.path_id);
};
walk(tree);
return rows;
}
/**
* 由 path_id 链向上拼接 local_name 展示标签(不含服务端明文路径)。
* @param pathId 目标节点 path_id
* @param nodes 扁平树节点
*/
export function buildXfaPathLabel(pathId: string, nodes: XfaFlatTreeNode[]): string {
const byId = new Map(nodes.map((item) => [item.pathId, item]));
const parts: string[] = [];
let current = byId.get(pathId);
while (current) {
parts.unshift(current.localName);
current = current.parentPathId ? byId.get(current.parentPathId) : undefined;
}
return parts.join('/') || pathId;
}
/**
* 按关键字过滤扁平树(匹配 local_name / path_id / 脱敏样例)。
* @param nodes 扁平节点
* @param query 搜索词
*/
export function filterXfaTreeNodes(nodes: XfaFlatTreeNode[], query: string): XfaFlatTreeNode[] {
const needle = query.trim().toLowerCase();
if (!needle) return nodes;
return nodes.filter((item) => (
item.localName.toLowerCase().includes(needle)
|| item.pathId.toLowerCase().includes(needle)
|| String(item.sampleValueMasked || '').toLowerCase().includes(needle)
));
}
/**
* 判断节点是否位于权威明细集合之下(用于 Header/Line scope 划分)。
* @param pathId 选中叶子 path_id
* @param authoritativePathId 权威集合 path_id
* @param nodes 扁平树
*/
export function isXfaPathUnderCollection(
pathId: string,
authoritativePathId: string,
nodes: XfaFlatTreeNode[],
): boolean {
if (!authoritativePathId || pathId === authoritativePathId) return false;
const byId = new Map(nodes.map((item) => [item.pathId, item]));
let current = byId.get(pathId);
while (current) {
if (current.pathId === authoritativePathId) return true;
current = current.parentPathId ? byId.get(current.parentPathId) : undefined;
}
return false;
}
/**
* 解析选中树节点应绑定的 Schema scope。
* @param pathId 选中 path_id
* @param authoritativePathId 权威集合 path_id
* @param nodes 扁平树
*/
export function resolveXfaNodeScope(
pathId: string,
authoritativePathId: string,
nodes: XfaFlatTreeNode[],
): 'header' | 'line' | null {
const node = nodes.find((item) => item.pathId === pathId);
if (!node?.isLeaf) return null;
return isXfaPathUnderCollection(pathId, authoritativePathId, nodes) ? 'line' : 'header';
}
/**
* 过滤 Schema 字段列表供映射面板展示。
* @param fields 已启用字段
* @param scope 当前节点 scope
* @param filterMode 全部/未映射
* @param definition 当前 definition
* @param boundFieldIds 已绑定 field_id 集合
*/
export function filterXfaSchemaFields(
fields: ShippingOrderFieldConfig[],
scope: 'header' | 'line',
filterMode: XfaSchemaFilterMode,
definition: OrderXfaDatasetProfileDefinition,
): ShippingOrderFieldConfig[] {
const mappings = scope === 'header'
? definition.header_mappings || []
: definition.line_mapping?.fields || [];
const mappedCodes = new Set(mappings.map((item) => item.field_code));
return fields.filter((field) => {
if (field.enabled === false || field.scope !== scope || !field.field_code) return false;
if (filterMode === 'unmapped' && mappedCodes.has(field.field_code)) return false;
return true;
});
}
/**
* 收集全部已绑定 field_id,含 split_rules 中 mapped 目标字段。
*/
export function collectBoundXfaFieldIds(definition: OrderXfaDatasetProfileDefinition): Set<string> {
const ids = new Set<string>();
for (const item of [...(definition.header_mappings || []), ...(definition.line_mapping?.fields || [])]) {
if (item.field_id) ids.add(item.field_id);
}
for (const ruleSet of definition.split_rules || []) {
for (const rule of ruleSet.rules || []) {
if (rule.segment.handling === 'mapped' && rule.segment.target_field_id) {
ids.add(rule.segment.target_field_id);
}
}
}
return ids;
}
/**
* 查找 path_id 对应的映射项。
*/
export function findXfaMappingByPathId(
definition: OrderXfaDatasetProfileDefinition,
pathId: string,
): XfaFieldMapping | null {
const all = [...(definition.header_mappings || []), ...(definition.line_mapping?.fields || [])];
return all.find((item) => item.path_id === pathId) || null;
}
/**
* 查找 field_id 对应的映射项。
*/
export function findXfaMappingByFieldId(
definition: OrderXfaDatasetProfileDefinition,
fieldId: string,
): XfaFieldMapping | null {
const all = [...(definition.header_mappings || []), ...(definition.line_mapping?.fields || [])];
return all.find((item) => item.field_id === fieldId) || null;
}
/**
* 计算 XFA 模板映射的重复绑定与权威集合状态。
* @param schemaFields 已启用 Schema 字段
* @param definition 当前 XFA definition
* @param authoritativePathId 权威集合 path_id(UI 态)
*/
export function computeXfaMappingCoverage(
schemaFields: ShippingOrderFieldConfig[],
definition: OrderXfaDatasetProfileDefinition | null | undefined,
authoritativePathId = '',
): XfaMappingCoverageSummary {
const headers = definition?.header_mappings || [];
const lines = definition?.line_mapping?.fields || [];
const bound = new Map<string, string>();
const duplicateFieldIds: string[] = [];
for (const item of [...headers, ...lines]) {
const key = String(item.field_id || '');
if (!key) continue;
if (bound.has(key)) duplicateFieldIds.push(key);
else bound.set(key, item.field_code);
}
void schemaFields;
const authPath = String(definition?.source_contract?.authoritative_line_collection_path || '').trim();
return {
requiredTotal: 0,
requiredMapped: 0,
missingRequired: [],
duplicateFieldIds: [...new Set(duplicateFieldIds)],
authoritativeMissing: !authoritativePathId && !authPath,
};
}
/**
* 判断集合是否可作为镜像(与权威不同)。
* @param candidates 集合候选
* @param authoritativePathId 权威 path_id
*/
export function listMirrorCollectionCandidates(
candidates: XfaCollectionCandidate[],
authoritativePathId: string,
): XfaCollectionCandidate[] {
return candidates.filter((item) => item.path_id && item.path_id !== authoritativePathId);
}
/**
* 绑定 Schema 字段到选中 path_id,返回新的 definition(不可变)。
* 核心逻辑:同 field_id 覆盖;拒绝跨 scope;保留既有 mapping_id。
*/
export function bindXfaSchemaField(options: {
definition: OrderXfaDatasetProfileDefinition;
scope: 'header' | 'line';
field: ShippingOrderFieldConfig;
pathId: string;
}): OrderXfaDatasetProfileDefinition {
const { definition, scope, field, pathId } = options;
if (field.scope !== scope) {
throw new Error('scope_mismatch');
}
const existing = findXfaMappingByFieldId(definition, field.field_id);
const mapping: XfaFieldMapping = {
mapping_id: existing?.mapping_id || `map-${field.field_id}-${pathId}`.slice(0, 64),
field_id: field.field_id,
field_code: field.field_code || '',
data_path: '',
path_id: pathId,
value_type: field.value_type || 'string',
normalizer_key: field.normalizer_key ?? null,
validator_key: field.validator_keys?.[0] ?? null,
};
if (scope === 'header') {
const others = (definition.header_mappings || []).filter((item) => item.field_id !== field.field_id);
return { ...definition, header_mappings: [...others, mapping] };
}
const others = (definition.line_mapping?.fields || []).filter((item) => item.field_id !== field.field_id);
return {
...definition,
line_mapping: {
row_path: definition.line_mapping?.row_path || definition.source_contract.authoritative_line_collection_path,
fields: [...others, mapping],
},
};
}
/**
* 解除 Schema 字段映射。
*/
export function unbindXfaSchemaField(
definition: OrderXfaDatasetProfileDefinition,
fieldId: string,
): OrderXfaDatasetProfileDefinition {
return {
...definition,
header_mappings: (definition.header_mappings || []).filter((item) => item.field_id !== fieldId),
line_mapping: {
row_path: definition.line_mapping?.row_path || definition.source_contract.authoritative_line_collection_path,
fields: (definition.line_mapping?.fields || []).filter((item) => item.field_id !== fieldId),
},
};
}
/**
* 组装保存请求 definition:附带 path_id 集合选择,data_path 由服务端重写。
* @param state 工作台当前状态
*/
export function buildXfaSaveDefinitionPayload(state: XfaMappingWorkbenchState): Record<string, unknown> {
const { definition, authoritativeCollectionPathId, mirrorCollectionPathIds } = state;
return {
...definition,
template_mode: 'xfa_dataset',
authoritative_collection_path_id: authoritativeCollectionPathId,
mirror_collection_path_ids: mirrorCollectionPathIds,
header_mappings: (definition.header_mappings || []).map((item) => ({
mapping_id: item.mapping_id,
field_id: item.field_id,
field_code: item.field_code,
path_id: item.path_id,
value_type: item.value_type,
normalizer_key: item.normalizer_key,
validator_key: item.validator_key,
})),
line_mapping: {
fields: (definition.line_mapping?.fields || []).map((item) => ({
mapping_id: item.mapping_id,
field_id: item.field_id,
field_code: item.field_code,
path_id: item.path_id,
value_type: item.value_type,
normalizer_key: item.normalizer_key,
validator_key: item.validator_key,
})),
},
split_rules: definition.split_rules || [],
};
}
/**
* 本地校验摘要:权威集合、重复绑定、必填缺口。
*/
export function summarizeXfaMappingBlockers(coverage: XfaMappingCoverageSummary): string[] {
const blockers: string[] = [];
if (coverage.authoritativeMissing) blockers.push('authoritative_collection_required');
if (coverage.duplicateFieldIds.length) blockers.push('duplicate_field_binding');
return blockers;
}
/**
* 截断 checksum 供页眉展示。
*/
export function shortenXfaChecksum(value: string | null | undefined, length = 4): string {
const text = String(value || '').replace(/^sha256:/i, '');
if (!text) return '—';
return text.length <= length * 2 ? text : `${text.slice(0, length)}…`;
}
/**
* 判断工作台状态是否与已保存快照不同(脏状态检测)。
*/
export function isXfaMappingDirty(
saved: XfaMappingWorkbenchState | null | undefined,
current: XfaMappingWorkbenchState,
): boolean {
if (!saved) return true;
return JSON.stringify(buildXfaSaveDefinitionPayload(saved))
!== JSON.stringify(buildXfaSaveDefinitionPayload(current));
}
/**
* 判断两个 definition 是否语义相等(兼容旧调用)。
*/
export function isSameXfaDefinition(
left: OrderXfaDatasetProfileDefinition | null | undefined,
right: OrderXfaDatasetProfileDefinition | null | undefined,
): boolean {
return JSON.stringify(left || null) === JSON.stringify(right || null);
}
/**
* 计算与后端 `hash_data_path` 一致的路径哈希(`sha256:<hex>`)。
* 核心逻辑:对已 trim 的绝对路径做 UTF-8 SHA-256;用于从已保存明文路径反查 path_id。
* @param path 受控 data_path(如 `/data/ITEMS/DATA`)
*/
export async function hashXfaDataPath(path: string): Promise<string> {
const text = String(path || '').trim();
if (!text.startsWith('/')) {
throw new Error('invalid_xfa_data_path');
}
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
const hex = [...new Uint8Array(digest)]
.map((byte) => byte.toString(16).padStart(2, '0'))
.join('');
return `sha256:${hex}`;
}
/**
* 从已保存 definition 与集合候选反查权威集合 path_id。
* 核心逻辑:优先用权威明文路径哈希精确匹配 collection_path_hash / 树节点 dataPathHash;
* 再回退 line 映射祖先集合;最后才用唯一候选。
*/
export async function resolveAuthoritativePathId(
definition: OrderXfaDatasetProfileDefinition,
candidates: XfaCollectionCandidate[],
flatNodes: XfaFlatTreeNode[],
): Promise<string> {
const authPath = String(definition.source_contract?.authoritative_line_collection_path || '').trim();
if (authPath) {
try {
const wanted = await hashXfaDataPath(authPath);
const byCandidate = candidates.find((item) => item.collection_path_hash === wanted && item.path_id);
if (byCandidate?.path_id) return byCandidate.path_id;
const byTree = flatNodes.find(
(item) => item.isCollectionCandidate && item.dataPathHash === wanted && item.pathId,
);
if (byTree?.pathId) return byTree.pathId;
} catch {
// 非法路径时继续走启发式回退。
}
}
const linePathId = (definition.line_mapping?.fields || [])[0]?.path_id;
if (linePathId) {
let current = flatNodes.find((item) => item.pathId === linePathId);
while (current) {
if (current.isCollectionCandidate) return current.pathId;
current = current.parentPathId
? flatNodes.find((item) => item.pathId === current?.parentPathId)
: undefined;
}
}
const collectionNodes = flatNodes.filter((item) => item.isCollectionCandidate);
if (collectionNodes.length === 1 && collectionNodes[0]?.pathId) {
return collectionNodes[0].pathId;
}
if (candidates.length === 1 && candidates[0]?.path_id) {
return candidates[0].path_id;
}
const preferred = collectionNodes.find((item) => item.localName.toUpperCase() === 'DATA');
return preferred?.pathId || '';
}
/**
* 从已保存镜像明文路径精确恢复镜像集合 path_id 列表。
* 核心逻辑:逐条 hash 匹配;排除权威;不按“前 N 个候选”猜测。
*/
export async function resolveMirrorPathIds(
definition: OrderXfaDatasetProfileDefinition,
candidates: XfaCollectionCandidate[],
authoritativePathId: string,
): Promise<string[]> {
const mirrors = (definition.source_contract?.mirror_collection_paths || [])
.map((item) => String(item || '').trim())
.filter(Boolean);
if (!mirrors.length) return [];
const resolved: string[] = [];
for (const path of mirrors) {
try {
const wanted = await hashXfaDataPath(path);
const hit = candidates.find(
(item) => item.collection_path_hash === wanted
&& item.path_id
&& item.path_id !== authoritativePathId,
);
if (hit?.path_id && !resolved.includes(hit.path_id)) {
resolved.push(hit.path_id);
}
} catch {
// skip invalid mirror path
}
}
return resolved;
}
@@ -0,0 +1,425 @@
<!--
features/admin/modules/shipping-order-extraction-runs/ShippingOrderExtractionRunsPage.vue
用途:管理员订单识别运行诊断——健康聚合、积压/取消中筛选、只读详情与活跃 Run 取消。
依赖:admin.api 脱敏诊断/健康/取消 DTO、Vue Composition API、Vue I18n。
逻辑:健康面板 + 列表筛选;详情仍只读;取消走 admin cancel API 且强制填写原因。
-->
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import {
cancelShippingOrderExtractionRun,
getShippingOrderExtractionDiagnosticRun,
getShippingOrderExtractionHealth,
listShippingOrderExtractionDiagnosticRuns,
type ShippingOrderExtractionDiagnosticDetail,
type ShippingOrderExtractionDiagnosticRun,
type ShippingOrderExtractionHealth,
} from '@/features/admin/api/admin.api';
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const loading = ref(false);
const healthLoading = ref(false);
const detailLoading = ref(false);
const cancellingRunNo = ref('');
const pendingCancelRunNo = ref('');
const cancelReason = ref('');
const page = ref(1);
const pageSize = 25;
const total = ref(0);
const status = ref('');
const staleOnly = ref(false);
const cancellationInFlight = ref(false);
const rows = ref<ShippingOrderExtractionDiagnosticRun[]>([]);
const health = ref<ShippingOrderExtractionHealth | null>(null);
const detail = ref<ShippingOrderExtractionDiagnosticDetail | null>(null);
const error = ref('');
const formatTime = (value?: string | null) => value ? new Date(value).toLocaleString() : '-';
const formatDuration = (value?: number | null) => value == null ? '-' : `${(value / 1000).toFixed(value < 10000 ? 1 : 0)} s`;
const translateAutoFreezeReason = (code: string) =>
t(`admin.shippingOrderExtractionRuns.autoFreezeReasonCodes.${code}`, code);
/**
* 判断管理员是否可对 Run 发起取消(活跃且未完成取消)。
*/
const canCancelRun = (row: ShippingOrderExtractionDiagnosticRun) => (
['queued', 'processing'].includes(row.status)
&& !row.cancellation?.completed
&& !row.cancellation?.in_flight
);
/** 展开/收起列表行取消表单。 */
const beginCancelRun = (runNo: string) => {
if (pendingCancelRunNo.value === runNo) {
pendingCancelRunNo.value = '';
cancelReason.value = '';
return;
}
pendingCancelRunNo.value = runNo;
cancelReason.value = '';
};
/**
* 管理员取消 Run;后端强制要求 reason。
*/
const submitCancelRun = async (runNo: string) => {
const reason = String(cancelReason.value || '').trim();
if (!reason || cancellingRunNo.value) return;
cancellingRunNo.value = runNo;
error.value = '';
try {
await cancelShippingOrderExtractionRun(runNo, { reason, reason_code: 'admin_cancelled' });
pendingCancelRunNo.value = '';
cancelReason.value = '';
await refreshAll();
} catch {
error.value = t('admin.shippingOrderExtractionRuns.cancelFailed');
} finally {
cancellingRunNo.value = '';
}
};
/** 加载健康聚合;失败不阻断列表。 */
const loadHealth = async () => {
healthLoading.value = true;
try {
health.value = await getShippingOrderExtractionHealth(24);
} catch {
health.value = null;
} finally {
healthLoading.value = false;
}
};
/** 加载安全摘要;服务端已完成管理员鉴权、审计及敏感字段剔除。 */
const load = async () => {
loading.value = true;
error.value = '';
try {
const response = await listShippingOrderExtractionDiagnosticRuns(
page.value,
pageSize,
status.value,
{
staleOnly: staleOnly.value,
cancellationInFlight: cancellationInFlight.value,
},
);
rows.value = response.items;
total.value = response.total;
} catch {
error.value = t('admin.shippingOrderExtractionRuns.loadFailed');
} finally {
loading.value = false;
}
};
const refreshAll = async () => {
await Promise.all([loadHealth(), load()]);
};
/** 按需打开一条 Run 的脱敏执行尝试和节点生命周期,不预取详情以减少诊断审计噪声。 */
const openDetail = async (runNo: string) => {
detailLoading.value = true;
error.value = '';
try {
detail.value = await getShippingOrderExtractionDiagnosticRun(runNo);
if (route.query.runNo !== runNo) {
void router.replace({ query: { ...route.query, runNo } });
}
} catch {
error.value = t('admin.shippingOrderExtractionRuns.detailFailed');
} finally {
detailLoading.value = false;
}
};
const closeDetail = () => {
detail.value = null;
if (route.query.runNo) {
const nextQuery = { ...route.query };
delete nextQuery.runNo;
void router.replace({ query: nextQuery });
}
};
const applyFilters = async () => {
page.value = 1;
await load();
};
onMounted(() => {
void refreshAll();
const runNo = String(route.query.runNo || '').trim();
if (runNo) void openDetail(runNo);
});
watch(
() => String(route.query.runNo || '').trim(),
(runNo) => {
if (!runNo) {
detail.value = null;
return;
}
if (detail.value?.run.run_no === runNo || detailLoading.value) return;
void openDetail(runNo);
},
);
</script>
<template>
<section class="space-y-5 p-5 md:p-7">
<header class="flex flex-wrap items-start justify-between gap-4">
<div>
<h1 class="section-title">{{ t('admin.shippingOrderExtractionRuns.title') }}</h1>
<p class="section-desc mt-1 max-w-3xl">{{ t('admin.shippingOrderExtractionRuns.subtitle') }}</p>
</div>
<button type="button" class="btn-secondary btn-sm" :disabled="loading || healthLoading" @click="refreshAll">
{{ t('admin.shippingOrderExtractionRuns.refresh') }}
</button>
</header>
<div
class="grid gap-3 rounded-xl border border-default bg-surface p-4 md:grid-cols-4"
data-testid="shipping-order-extraction-health"
>
<div v-if="healthLoading" class="md:col-span-4 text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.loading') }}</div>
<template v-else-if="health">
<div>
<div class="text-xs text-muted">{{ t('admin.shippingOrderExtractionRuns.healthStatus') }}</div>
<div class="mt-1 text-lg font-semibold" :class="health.health_status === 'healthy' ? 'text-emerald-700' : 'text-amber-700'">
{{ t(`admin.shippingOrderExtractionRuns.healthStatuses.${health.health_status}`, health.health_status) }}
</div>
</div>
<div>
<div class="text-xs text-muted">{{ t('admin.shippingOrderExtractionRuns.activeCount') }}</div>
<div class="mt-1 text-lg font-semibold">{{ health.counts.active || 0 }}</div>
</div>
<div>
<div class="text-xs text-muted">{{ t('admin.shippingOrderExtractionRuns.staleCount') }}</div>
<div class="mt-1 text-lg font-semibold">{{ health.counts.stale || 0 }}</div>
</div>
<div>
<div class="text-xs text-muted">{{ t('admin.shippingOrderExtractionRuns.failureRate') }}</div>
<div class="mt-1 text-lg font-semibold">{{ Math.round((health.failure_rate || 0) * 100) }}%</div>
</div>
<div class="md:col-span-4 text-xs text-secondary">
{{ t('admin.shippingOrderExtractionRuns.latencySummary', {
p50: formatDuration(health.latency?.total?.p50_ms),
p95: formatDuration(health.latency?.total?.p95_ms),
max: formatDuration(health.latency?.total?.max_ms),
}) }}
<span v-if="health.stale_run_nos?.length" class="ml-2">
{{ t('admin.shippingOrderExtractionRuns.staleRuns', { runs: health.stale_run_nos.slice(0, 5).join(', ') }) }}
</span>
</div>
</template>
<div v-else class="md:col-span-4 text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.healthUnavailable') }}</div>
</div>
<div class="flex flex-wrap items-center gap-3 rounded-xl border border-default bg-surface p-3">
<label class="flex items-center gap-2 text-sm text-secondary">
{{ t('admin.shippingOrderExtractionRuns.status') }}
<select v-model="status" class="select-field py-1.5" @change="applyFilters">
<option value="">{{ t('admin.shippingOrderExtractionRuns.allStatuses') }}</option>
<option v-for="value in ['queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled']" :key="value" :value="value">
{{ t(`admin.shippingOrderExtractionRuns.statuses.${value}`) }}
</option>
</select>
</label>
<label class="flex items-center gap-2 text-sm text-secondary">
<input v-model="staleOnly" type="checkbox" class="rounded border-default" @change="applyFilters">
{{ t('admin.shippingOrderExtractionRuns.staleOnly') }}
</label>
<label class="flex items-center gap-2 text-sm text-secondary">
<input v-model="cancellationInFlight" type="checkbox" class="rounded border-default" @change="applyFilters">
{{ t('admin.shippingOrderExtractionRuns.cancellationInFlight') }}
</label>
<span class="text-xs text-muted">{{ t('admin.shippingOrderExtractionRuns.total', { count: total }) }}</span>
</div>
<p v-if="error" class="rounded-lg border border-rose-200 bg-rose-50 p-3 text-sm text-rose-700">{{ error }}</p>
<div class="overflow-x-auto rounded-xl border border-default bg-surface">
<table class="min-w-[1040px] w-full text-left text-sm">
<thead class="border-b border-default bg-surface-soft text-xs text-muted"><tr>
<th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.runNo') }}</th>
<th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.status') }}</th>
<th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.stage') }}</th>
<th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.cancellation') }}</th>
<th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.attempts') }}</th>
<th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.createdAt') }}</th>
<th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.totalDuration') }}</th>
<th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.actions') }}</th>
</tr></thead>
<tbody>
<tr v-if="loading"><td colspan="9" class="px-4 py-8 text-center text-muted">{{ t('admin.shippingOrderExtractionRuns.loading') }}</td></tr>
<tr v-else-if="!rows.length"><td colspan="9" class="px-4 py-8 text-center text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</td></tr>
<tr v-for="row in rows" :key="row.run_no" class="border-b border-default last:border-0">
<td class="px-4 py-3 font-mono text-xs">{{ row.run_no }}</td>
<td class="px-4 py-3">{{ t(`admin.shippingOrderExtractionRuns.statuses.${row.status}`) }}</td>
<td class="px-4 py-3">{{ row.current_event_code || '-' }}</td>
<td class="px-4 py-3">
<span v-if="row.cancellation?.in_flight" class="rounded-full bg-amber-100 px-2 py-0.5 text-xs text-amber-800">
{{ t('admin.shippingOrderExtractionRuns.cancellationStates.in_flight') }}
</span>
<span v-else-if="row.cancellation?.completed" class="text-xs text-muted">
{{ t('admin.shippingOrderExtractionRuns.cancellationStates.completed') }}
</span>
<span v-else class="text-xs text-muted">—</span>
</td>
<td class="px-4 py-3">{{ row.attempt_count }}</td>
<td class="px-4 py-3">{{ formatTime(row.created_at) }}</td>
<td class="px-4 py-3">{{ formatDuration(row.durations_ms.total ?? row.durations_ms.elapsed_active) }}</td>
<td class="px-4 py-3">
<div class="flex flex-col gap-2">
<button type="button" class="text-left text-brand-600 hover:underline" @click="openDetail(row.run_no)">{{ t('admin.shippingOrderExtractionRuns.viewDetail') }}</button>
<template v-if="canCancelRun(row)">
<div
v-if="pendingCancelRunNo === row.run_no"
class="min-w-[220px] space-y-1.5 rounded-md border border-rose-200 bg-rose-50/60 p-2 dark:border-rose-900/40 dark:bg-rose-950/20"
>
<label class="block text-[11px] text-secondary">{{ t('chat.shippingOrderExtractionCancel.reasonRequired') }}</label>
<textarea v-model="cancelReason" rows="2" class="input-field w-full py-1 text-xs" />
<div class="flex flex-wrap gap-2">
<button
type="button"
class="text-xs font-medium text-rose-700 hover:underline"
:disabled="cancellingRunNo === row.run_no || !cancelReason.trim()"
@click="submitCancelRun(row.run_no)"
>
{{ cancellingRunNo === row.run_no
? t('chat.shippingOrderExtractionCancel.submitting')
: t('admin.shippingOrderExtractionRuns.cancelRun') }}
</button>
<button
type="button"
class="text-xs text-muted hover:underline"
:disabled="cancellingRunNo === row.run_no"
@click="pendingCancelRunNo = ''; cancelReason = ''"
>
{{ t('admin.cancel') }}
</button>
</div>
</div>
<button
v-else
type="button"
class="text-left text-xs font-medium text-rose-700 hover:underline"
:disabled="Boolean(cancellingRunNo)"
@click="beginCancelRun(row.run_no)"
>
{{ t('admin.shippingOrderExtractionRuns.cancelRun') }}
</button>
</template>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="flex items-center justify-end gap-3 text-sm">
<button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page <= 1 || loading" @click="page -= 1; load()">{{ t('admin.shippingOrderExtractionRuns.previous') }}</button>
<span>{{ page }}</span>
<button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page * pageSize >= total || loading" @click="page += 1; load()">{{ t('admin.shippingOrderExtractionRuns.next') }}</button>
</div>
<div v-if="detail || detailLoading" class="fixed inset-0 z-50 flex justify-end bg-overlay" @click.self="closeDetail">
<aside class="h-full w-full max-w-2xl overflow-y-auto bg-surface p-6 shadow-2xl">
<div class="flex items-center justify-between"><h2 class="text-lg font-bold">{{ t('admin.shippingOrderExtractionRuns.detailTitle') }}</h2><button type="button" class="text-secondary" @click="closeDetail">{{ t('admin.close') }}</button></div>
<p v-if="detailLoading" class="mt-6 text-muted">{{ t('admin.shippingOrderExtractionRuns.loading') }}</p>
<template v-else-if="detail">
<dl class="mt-5 grid grid-cols-2 gap-3 text-sm">
<dt>{{ t('admin.shippingOrderExtractionRuns.runNo') }}</dt><dd class="font-mono text-xs">{{ detail.run.run_no }}</dd>
<dt>{{ t('admin.shippingOrderExtractionRuns.currentEvent') }}</dt><dd class="font-mono text-xs">{{ detail.run.current_event_code || '-' }}</dd>
<dt>{{ t('admin.shippingOrderExtractionRuns.cancellation') }}</dt>
<dd>
<template v-if="detail.run.cancellation?.in_flight">{{ t('admin.shippingOrderExtractionRuns.cancellationStates.in_flight') }}</template>
<template v-else-if="detail.run.cancellation?.completed">{{ t('admin.shippingOrderExtractionRuns.cancellationStates.completed') }}</template>
<template v-else>—</template>
</dd>
<dt>{{ t('admin.shippingOrderExtractionRuns.candidateMaterializedAt') }}</dt><dd>{{ formatTime(detail.run.candidate_materialized_at) }}</dd>
<dt>{{ t('admin.shippingOrderExtractionRuns.errorCode') }}</dt><dd>{{ detail.run.error_code || '-' }}</dd>
<dt>{{ t('admin.shippingOrderExtractionRuns.totalDuration') }}</dt><dd>{{ formatDuration(detail.run.durations_ms.total) }}</dd>
</dl>
<section class="mt-6 rounded-lg border border-default p-4 text-sm">
<div class="font-semibold">{{ t('admin.shippingOrderExtractionRuns.autoFreezePolicy') }}</div>
<dl class="mt-3 grid grid-cols-2 gap-x-3 gap-y-2">
<dt>{{ t('admin.shippingOrderExtractionRuns.autoFreezeEnabled') }}</dt>
<dd>{{ t(detail.run.auto_freeze_policy.enabled ? 'admin.shippingOrderExtractionRuns.yes' : 'admin.shippingOrderExtractionRuns.no') }}</dd>
<dt>{{ t('admin.shippingOrderExtractionRuns.autoFreezeMode') }}</dt>
<dd>{{ t(`admin.shippingOrderExtractionRuns.autoFreezeModes.${detail.run.auto_freeze_policy.mode}`) }}</dd>
<dt>{{ t('admin.shippingOrderExtractionRuns.autoFreezeQualificationStatus') }}</dt>
<dd>{{ detail.run.auto_freeze_policy.qualification_status ? t(`admin.shippingOrderExtractionRuns.autoFreezeQualificationStatuses.${detail.run.auto_freeze_policy.qualification_status}`) : '-' }}</dd>
<dt>{{ t('admin.shippingOrderExtractionRuns.autoFreezeProfile') }}</dt>
<dd>{{ detail.run.auto_freeze_policy.selected_profile_code || '-' }}</dd>
<dt>{{ t('admin.shippingOrderExtractionRuns.autoFreezeCustomerScopeStatus') }}</dt>
<dd>{{ detail.run.auto_freeze_policy.customer_scope_status ? t(`admin.shippingOrderExtractionRuns.autoFreezeCustomerScopeStatuses.${detail.run.auto_freeze_policy.customer_scope_status}`) : '-' }}</dd>
<dt>{{ t('admin.shippingOrderExtractionRuns.autoFreezeBusinessScenarioStatus') }}</dt>
<dd>{{ detail.run.auto_freeze_policy.business_scenario_status ? t(`admin.shippingOrderExtractionRuns.autoFreezeBusinessScenarioStatuses.${detail.run.auto_freeze_policy.business_scenario_status}`) : '-' }}</dd>
<dt>{{ t('admin.shippingOrderExtractionRuns.autoFreezeCustomerConfirmation') }}</dt>
<dd>{{ t(detail.run.auto_freeze_policy.customer_confirmation_required ? 'admin.shippingOrderExtractionRuns.yes' : 'admin.shippingOrderExtractionRuns.no') }}</dd>
</dl>
<div class="mt-3">
<div class="text-xs font-medium text-secondary">{{ t('admin.shippingOrderExtractionRuns.autoFreezeBlockingReasons') }}</div>
<div v-if="detail.run.auto_freeze_policy.blocking_reason_codes.length" class="mt-2 flex flex-wrap gap-2">
<span
v-for="code in detail.run.auto_freeze_policy.blocking_reason_codes"
:key="code"
class="rounded-full border border-default px-2 py-1 text-xs text-secondary"
>
{{ translateAutoFreezeReason(code) }}
</span>
</div>
<div v-else class="mt-2 text-xs text-muted">{{ t('admin.shippingOrderExtractionRuns.autoFreezeNoBlockingReasons') }}</div>
</div>
</section>
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.jobAttempts') }}</h3>
<div class="mt-2 space-y-2">
<div v-for="job in detail.job_attempts" :key="job.job_id" class="rounded-lg border border-default p-3 text-sm">
<b>#{{ job.job_id }}</b> · {{ job.status }} · {{ t('admin.shippingOrderExtractionRuns.attempts') }} {{ job.attempts }}/{{ job.max_attempts }} · {{ formatDuration(job.duration_ms) }}
</div>
<p v-if="!detail.job_attempts.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p>
</div>
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.units') }}</h3>
<div class="mt-2 space-y-2">
<div v-for="unit in detail.units" :key="unit.unit_id" class="rounded-lg border border-default p-3 text-sm">
<b>#{{ unit.position + 1 }} {{ unit.unit_type }}</b> · {{ unit.status }} · {{ t('admin.shippingOrderExtractionRuns.attempts') }} {{ unit.attempt_count }} · {{ formatDuration(unit.duration_ms) }}
<span v-if="unit.error_code" class="ml-2 font-mono text-xs text-danger">{{ unit.error_code }}</span>
<section v-for="routeItem in unit.route_decisions" :key="`${unit.unit_id}:${routeItem.attempt_no}`" class="mt-3 rounded border border-default bg-surface-soft p-3 text-xs">
<h4 class="font-semibold text-primary">{{ t('admin.shippingOrderExtractionRuns.routeDecision') }} #{{ routeItem.attempt_no }}</h4>
<dl class="mt-2 grid grid-cols-2 gap-x-3 gap-y-1">
<dt>{{ t('admin.shippingOrderExtractionRuns.executionMode') }}</dt>
<dd>{{ t(`admin.shippingOrderExtractionRuns.executionModes.${routeItem.execution_mode}`) }}</dd>
<dt>{{ t('admin.shippingOrderExtractionRuns.matchStatus') }}</dt>
<dd>{{ t(`admin.shippingOrderExtractionRuns.matchStatuses.${routeItem.match_status}`) }}</dd>
<dt>{{ t('admin.shippingOrderExtractionRuns.selectedProfile') }}</dt>
<dd>{{ routeItem.selected_profile_code ? `${routeItem.selected_profile_code} V${routeItem.selected_profile_version}` : '-' }}</dd>
<dt>{{ t('admin.shippingOrderExtractionRuns.autoCreateApproved') }}</dt>
<dd>{{ routeItem.auto_create_approved == null ? '-' : t(routeItem.auto_create_approved ? 'admin.shippingOrderExtractionRuns.yes' : 'admin.shippingOrderExtractionRuns.no') }}</dd>
<dt>{{ t('admin.shippingOrderExtractionRuns.fallbackReasons') }}</dt>
<dd>{{ routeItem.fallback_reason_codes.length ? routeItem.fallback_reason_codes.map(code => t(`admin.shippingOrderExtractionRuns.reasonCodes.${code}`)).join(';') : '-' }}</dd>
</dl>
</section>
</div>
<p v-if="!detail.units.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p>
</div>
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.lifecycle') }}</h3>
<div class="mt-2 space-y-2">
<div v-for="event in detail.progress_events" :key="`${event.sequence_no}:${event.event_code}`" class="rounded-lg border border-default p-3 text-sm">
<b>{{ event.event_code }}</b>
<span class="ml-2 text-secondary">{{ event.status || '-' }}</span>
<span class="ml-2 font-mono text-xs text-muted">{{ t(`admin.shippingOrderExtractionRuns.visibilities.${event.visibility}`) }}</span>
<span v-if="event.reason_code" class="ml-2 font-mono text-xs text-muted">{{ event.reason_code }}</span>
<time class="ml-2 text-xs text-muted">{{ formatTime(event.occurred_at) }}</time>
</div>
<p v-if="!detail.progress_events.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p>
</div>
</template>
</aside>
</div>
</section>
</template>
@@ -0,0 +1,109 @@
<!--
features/admin/modules/shipping-order-schema/components/SchemaAuditTimeline.vue
用途:展示订单 Schema 配置的追加式审计时间线。
依赖:ShippingOrderSchemaAuditEvent DTO、Vue I18n。
逻辑:父组件分页读取最小审计摘要;展示字段集合变更与自动建单策略变更,不展示完整快照。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { ShippingOrderSchemaAuditEvent } from '@/features/admin/types/shipping-order-schema.types';
defineProps<{ events: ShippingOrderSchemaAuditEvent[]; total: number; loading: boolean }>();
const emit = defineEmits<{ loadMore: [] }>();
const { t } = useI18n();
/**
* 使用本地时间展示事件发生时刻,缺失时间维持审计可读性。
* @param value - ISO 时间字符串
*/
const formatDate = (value?: string | null): string => value
? new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(new Date(value))
: t('admin.shippingOrderSchema.historyUnknownTime');
/**
* 将事件类型映射为面向业务人员的动作,未知类型保留其原值。
* @param eventType - 审计事件类型码
*/
const eventLabel = (eventType: string): string => {
const key = `admin.shippingOrderSchema.auditEvent.${eventType}`;
const translated = t(key);
return translated === key ? eventType : translated;
};
/**
* 将自动建单 enabled 布尔值映射为「开启/关闭」文案。
* @param enabled - 策略开关
*/
const autoCreationStateLabel = (enabled: boolean): string => (
enabled
? t('admin.shippingOrderSchema.autoCreationOn')
: t('admin.shippingOrderSchema.autoCreationOff')
);
/**
* 只有字段集合确有变化时才显示计数摘要,避免目录事件出现无意义的全零提示。
* @param event - 审计事件
*/
const hasFieldChanges = (event: ShippingOrderSchemaAuditEvent): boolean => [
event.change_summary.added_field_ids,
event.change_summary.removed_field_ids,
event.change_summary.changed_field_ids,
].some((fieldIds) => Array.isArray(fieldIds) && fieldIds.length > 0);
/**
* 判断审计摘要是否包含自动建单策略变更(含 before/after)。
* @param event - 审计事件
*/
const hasAutoCreationChange = (event: ShippingOrderSchemaAuditEvent): boolean => {
if (event.change_summary.auto_creation_policy_changed === true) return true;
const policy = event.change_summary.auto_creation_policy;
return Boolean(policy && typeof policy === 'object');
};
/**
* 生成「自动建单:关闭 → 开启」业务摘要;无法解析时返回空串。
* @param event - 审计事件
*/
const autoCreationSummary = (event: ShippingOrderSchemaAuditEvent): string => {
const raw = event.change_summary.auto_creation_policy;
if (!raw || typeof raw !== 'object') return '';
const policy = raw as { before?: { enabled?: unknown }; after?: { enabled?: unknown } };
const beforeEnabled = policy.before?.enabled === true;
const afterEnabled = policy.after?.enabled === true;
if (beforeEnabled === afterEnabled && event.change_summary.auto_creation_policy_changed !== true) {
return '';
}
return t('admin.shippingOrderSchema.auditAutoCreationSummary', {
before: autoCreationStateLabel(beforeEnabled),
after: autoCreationStateLabel(afterEnabled),
});
};
</script>
<template>
<section class="audit-timeline" :aria-label="t('admin.shippingOrderSchema.auditTitle')">
<div class="audit-heading"><span>{{ t('admin.shippingOrderSchema.auditTitle') }}</span><small>{{ total }}</small></div>
<p v-if="!events.length && !loading" class="audit-empty">{{ t('admin.shippingOrderSchema.auditEmpty') }}</p>
<article v-for="event in events" :key="event.id" class="audit-event">
<strong>{{ eventLabel(event.event_type) }}</strong><span v-if="event.version">V{{ event.version.version }}</span>
<p>{{ formatDate(event.created_at) }} · {{ event.actor?.display_name || t('admin.shippingOrderSchema.historyUnknownActor') }}</p>
<small v-if="hasFieldChanges(event)">{{ t('admin.shippingOrderSchema.auditFieldSummary', { added: (event.change_summary.added_field_ids as string[] | undefined)?.length || 0, removed: (event.change_summary.removed_field_ids as string[] | undefined)?.length || 0, changed: (event.change_summary.changed_field_ids as string[] | undefined)?.length || 0 }) }}</small>
<small v-if="hasAutoCreationChange(event) && autoCreationSummary(event)" class="audit-auto-creation">{{ autoCreationSummary(event) }}</small>
</article>
<button v-if="events.length < total" type="button" :disabled="loading" @click="emit('loadMore')">{{ loading ? t('common.loading') : t('admin.shippingOrderSchema.auditLoadMore') }}</button>
</section>
</template>
<style scoped>
.audit-timeline { margin-top: 22px; border-top: 1px solid #e5ebf1; padding-top: 18px; }
.audit-heading { display: flex; align-items: center; gap: 8px; color: #64748b; font-size: 12px; font-weight: 700; }
.audit-heading small { border-radius: 999px; background: #e0f2fe; padding: 2px 7px; color: #0369a1; }
.audit-event { position: relative; margin: 10px 0 0 6px; border-left: 2px solid #bae6fd; padding: 0 0 10px 13px; }
.audit-event::before { position: absolute; top: 3px; left: -5px; width: 8px; height: 8px; border-radius: 50%; background: #0ea5e9; content: ''; }
.audit-event strong { color: #334155; font-size: 12px; }
.audit-event > span { margin-left: 6px; color: #0369a1; font-size: 11px; }
.audit-event p, .audit-event small { display: block; margin: 4px 0 0; color: #94a3b8; font-size: 11px; }
.audit-auto-creation { color: #0f766e !important; }
.audit-timeline > button { width: 100%; border: 1px dashed #cbd5e1; border-radius: 7px; background: transparent; padding: 8px; color: #0284c7; font: inherit; font-size: 12px; cursor: pointer; }
.audit-empty { color: #94a3b8; font-size: 12px; }
</style>
@@ -0,0 +1,45 @@
<!--
features/admin/modules/shipping-order-schema/components/SchemaExtractionAuditDrawer.vue
用途:以只读方式展示一条订单解析的冻结输入、LLM 输出、裁决和字段证据。
依赖:ShippingOrderExtractionAudit DTO、Vue I18n。
逻辑:复杂运行数据由服务端完整组装;组件使用 JSON 预格式化展示,禁止在审计视图编辑或重放解析。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderExtractionAudit } from '@/features/admin/types/shipping-order-schema.types';
const props = defineProps<{ modelValue: boolean; audit: ShippingOrderExtractionAudit | null; loading: boolean }>();
const emit = defineEmits<{ 'update:modelValue': [visible: boolean] }>();
const { t } = useI18n();
/** 保持审计载荷原样可读,并安全处理缺失或非对象值。 */
const json = (value: unknown): string => JSON.stringify(value ?? null, null, 2);
const documents = computed(() => Array.isArray(props.audit?.input_snapshot.documents) ? props.audit?.input_snapshot.documents : []);
</script>
<template>
<Teleport to="body">
<div v-if="modelValue" class="audit-detail-layer" role="presentation" @click.self="emit('update:modelValue', false)">
<aside class="audit-detail-drawer" role="dialog" aria-modal="true" :aria-label="t('admin.shippingOrderSchema.runtimeAuditTitle')">
<header><div><p>{{ t('admin.shippingOrderSchema.runtimeAuditEyebrow') }}</p><h2>{{ t('admin.shippingOrderSchema.runtimeAuditTitle') }}</h2></div><button type="button" :aria-label="t('common.close')" @click="emit('update:modelValue', false)">×</button></header>
<main v-if="loading" class="audit-detail-empty">{{ t('common.loading') }}</main>
<main v-else-if="audit">
<dl class="audit-meta"><div><dt>{{ t('admin.shippingOrderSchema.runtimeAuditExtraction') }}</dt><dd>#{{ audit.extraction.id }}</dd></div><div><dt>{{ t('admin.shippingOrderSchema.runtimeAuditVersion') }}</dt><dd>V{{ audit.schema_version.version }}</dd></div><div><dt>{{ t('admin.shippingOrderSchema.runtimeAuditStatus') }}</dt><dd>{{ t(`admin.shippingOrderSchema.extractionStatus.${audit.extraction.status}`) }}</dd></div><div><dt>{{ t('admin.shippingOrderSchema.runtimeAuditHash') }}</dt><dd><code>{{ audit.extraction.input_snapshot_hash }}</code></dd></div></dl>
<section><h3>{{ t('admin.shippingOrderSchema.runtimeAuditInput') }}</h3><p v-if="audit.input_snapshot.snapshot_available === false" class="snapshot-unavailable">{{ t('admin.shippingOrderSchema.runtimeAuditInputUnavailable') }}</p><article v-for="document in documents" :key="String(document.id)" class="audit-document"><strong>{{ String(document.filename || document.id) }}</strong><pre>{{ String(document.extracted_text || '') }}</pre></article></section>
<section><h3>{{ t('admin.shippingOrderSchema.runtimeAuditLlm') }}</h3><pre>{{ json(audit.raw_llm_output) }}</pre></section>
<section><h3>{{ t('admin.shippingOrderSchema.runtimeAuditNormalized') }}</h3><pre>{{ json(audit.normalized_result) }}</pre></section>
<section><h3>{{ t('admin.shippingOrderSchema.runtimeAuditValidation') }}</h3><pre>{{ json(audit.validation_result) }}</pre></section>
<section><h3>{{ t('admin.shippingOrderSchema.runtimeAuditDecisions') }} ({{ audit.decisions.length }})</h3><pre>{{ json(audit.decisions) }}</pre></section>
<section><h3>{{ t('admin.shippingOrderSchema.runtimeAuditEvidence') }} ({{ audit.observations.length }})</h3><pre>{{ json(audit.observations) }}</pre></section>
<section><h3>{{ t('admin.shippingOrderSchema.runtimeAuditValues') }} ({{ audit.field_values.length }})</h3><pre>{{ json(audit.field_values) }}</pre></section>
</main>
<main v-else class="audit-detail-empty">{{ t('admin.shippingOrderSchema.runtimeAuditEmpty') }}</main>
</aside>
</div>
</Teleport>
</template>
<style scoped>
.audit-detail-layer { position: fixed; z-index: 90; inset: 0; display: flex; justify-content: flex-end; background: rgb(15 23 42 / 40%); backdrop-filter: blur(2px); }.audit-detail-drawer { display: flex; width: min(900px, 97vw); height: 100%; flex-direction: column; overflow: hidden; background: #f8fafc; box-shadow: -18px 0 48px rgb(15 23 42 / 22%); }.audit-detail-drawer > header { display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid #e2e8f0; background: #fff; padding: 22px 26px; }.audit-detail-drawer header p { margin: 0 0 4px; color: #0284c7; font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }.audit-detail-drawer h2 { margin: 0; color: #1e293b; font-size: 20px; }.audit-detail-drawer > header button { width: 32px; height: 32px; border: 1px solid #dbe5ee; border-radius: 50%; background: #fff; color: #475569; font-size: 22px; line-height: 1; cursor: pointer; }.audit-detail-drawer main { overflow-y: auto; padding: 24px 26px; }.audit-meta { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; margin: 0 0 20px; }.audit-meta div { border: 1px solid #e2e8f0; border-radius: 8px; background: #fff; padding: 10px; }.audit-meta dt { color: #94a3b8; font-size: 10px; }.audit-meta dd { margin: 5px 0 0; color: #334155; font-size: 12px; overflow-wrap: anywhere; }.audit-detail-drawer section { margin-top: 18px; }.audit-detail-drawer h3 { margin: 0 0 8px; color: #64748b; font-size: 12px; }.audit-detail-drawer pre { overflow: auto; max-height: 340px; margin: 0; border: 1px solid #e2e8f0; border-radius: 8px; background: #fff; padding: 12px; color: #334155; font: 11px/1.55 ui-monospace, SFMono-Regular, Consolas, monospace; white-space: pre-wrap; overflow-wrap: anywhere; }.audit-document { margin-top: 8px; border: 1px solid #e2e8f0; border-radius: 8px; background: #fff; padding: 12px; }.audit-document strong { color: #334155; font-size: 12px; }.audit-document pre { max-height: 220px; margin-top: 8px; border: 0; background: #f8fafc; }.snapshot-unavailable { margin: 0; border: 1px solid #fde68a; border-radius: 7px; background: #fffbeb; padding: 9px; color: #a16207; font-size: 12px; }.audit-detail-empty { display: grid; min-height: 240px; place-items: center; color: #94a3b8; font-size: 13px; }@media (max-width: 640px) { .audit-detail-drawer main { padding: 18px; }.audit-meta { grid-template-columns: 1fr; } }
</style>
@@ -0,0 +1,68 @@
<!--
features/admin/modules/shipping-order-schema/components/SchemaVersionDiffDrawer.vue
用途:只读展示两个订单 Schema 版本的服务端语义化字段差异。
依赖:ShippingOrderSchemaVersionDiff DTO、Vue I18n。
逻辑:父组件负责加载差异;本组件只根据后端 field_id 差异结构渲染,绝不自行推断字段是否重命名。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type {
ShippingOrderSchemaFieldChange,
ShippingOrderSchemaFieldDiff,
ShippingOrderSchemaVersionDiff,
} from '@/features/admin/types/shipping-order-schema.types';
const props = defineProps<{ modelValue: boolean; diff: ShippingOrderSchemaVersionDiff | null; loading: boolean }>();
const emit = defineEmits<{ 'update:modelValue': [visible: boolean] }>();
const { t } = useI18n();
/** 隐藏未变化字段,审计人员只聚焦实际配置差异。 */
const changedFields = computed(() => props.diff?.fields.filter((item) => item.change_type !== 'unchanged') || []);
/** 为差异条目提供当前或历史快照中最具识别性的字段名称。 */
const fieldLabel = (field: ShippingOrderSchemaFieldDiff): string =>
field.after?.display_name || field.before?.display_name || field.after?.field_code || field.before?.field_code || field.field_id;
/** 将后端属性键映射为可本地化的审计标签,未知键仍保留原键以防信息丢失。 */
const changeLabel = (change: ShippingOrderSchemaFieldChange): string => {
const key = `admin.shippingOrderSchema.diffField.${change.key}`;
const translated = t(key);
return translated === key ? change.key : translated;
};
/** 标量和集合使用紧凑文本;结构化来源使用稳定 JSON,避免退化为 [object Object]。 */
const valueText = (value: unknown): string => {
if (value === null || value === undefined || value === '') return t('admin.shippingOrderSchema.diffEmpty');
if (Array.isArray(value)) return value.join(', ') || t('admin.shippingOrderSchema.diffEmpty');
if (typeof value === 'object') return JSON.stringify(value, null, 2);
return String(value);
};
</script>
<template>
<Teleport to="body">
<div v-if="modelValue" class="diff-layer" role="presentation" @click.self="emit('update:modelValue', false)">
<aside class="diff-drawer" role="dialog" aria-modal="true" :aria-label="t('admin.shippingOrderSchema.diffTitle')">
<header><div><p>{{ t('admin.shippingOrderSchema.diffEyebrow') }}</p><h2>{{ t('admin.shippingOrderSchema.diffTitle') }}</h2></div><button type="button" :aria-label="t('common.close')" @click="emit('update:modelValue', false)">×</button></header>
<main v-if="loading" class="empty">{{ t('common.loading') }}</main>
<main v-else-if="diff">
<p class="comparison">V{{ diff.base_version.version }} {{ t('admin.shippingOrderSchema.diffComparedWith') }} V{{ diff.compare_version.version }}</p>
<div class="summary"><span v-for="key in ['added', 'removed', 'modified']" :key="key">{{ t(`admin.shippingOrderSchema.diffStatus.${key}`) }} <b>{{ diff.summary[key as 'added' | 'removed' | 'modified'] }}</b></span></div>
<article v-for="field in changedFields" :key="field.field_id" class="diff-field" :class="field.change_type">
<header><div><strong>{{ fieldLabel(field) }}</strong><code>{{ field.after?.field_code || field.before?.field_code }}</code></div><span>{{ t(`admin.shippingOrderSchema.diffStatus.${field.change_type}`) }}</span></header>
<template v-if="field.change_type === 'added'"><p>{{ t('admin.shippingOrderSchema.diffAddedField') }}</p></template>
<template v-else-if="field.change_type === 'removed'"><p>{{ t('admin.shippingOrderSchema.diffRemovedField') }}</p></template>
<dl v-else><div v-for="change in field.changes" :key="change.key"><dt>{{ changeLabel(change) }}</dt><dd><del>{{ valueText(change.before) }}</del><ins>{{ valueText(change.after) }}</ins><small v-if="change.order_changed">{{ t('admin.shippingOrderSchema.diffOrderChanged') }}</small></dd></div></dl>
</article>
<p v-if="!changedFields.length" class="empty">{{ t('admin.shippingOrderSchema.diffNoChanges') }}</p>
</main>
<main v-else class="empty">{{ t('admin.shippingOrderSchema.diffNoChanges') }}</main>
</aside>
</div>
</Teleport>
</template>
<style scoped>
.diff-layer { position: fixed; z-index: 80; inset: 0; display: flex; justify-content: flex-end; background: rgb(15 23 42 / 35%); backdrop-filter: blur(2px); }.diff-drawer { display: flex; width: min(760px, 96vw); height: 100%; flex-direction: column; overflow: hidden; background: #f8fafc; box-shadow: -18px 0 48px rgb(15 23 42 / 18%); }.diff-drawer > header { display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid #e2e8f0; background: #fff; padding: 22px 26px; }.diff-drawer header p { margin: 0 0 4px; color: #0284c7; font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }.diff-drawer h2 { margin: 0; color: #1e293b; font-size: 20px; }.diff-drawer > header button { width: 32px; height: 32px; border: 1px solid #dbe5ee; border-radius: 50%; background: #fff; color: #475569; font-size: 22px; line-height: 1; cursor: pointer; }.diff-drawer main { overflow-y: auto; padding: 24px 26px; }.comparison { margin: 0 0 10px; color: #64748b; font-size: 13px; }.summary { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 18px; }.summary span, .diff-field > header > span { border-radius: 999px; background: #e0f2fe; padding: 3px 7px; color: #0369a1; font-size: 11px; }.summary b { margin-left: 3px; }.diff-field { margin-top: 10px; border: 1px solid #e2e8f0; border-left-width: 3px; border-radius: 8px; background: #fff; padding: 13px; }.diff-field.added { border-left-color: #22c55e; }.diff-field.removed { border-left-color: #ef4444; }.diff-field.modified { border-left-color: #0ea5e9; }.diff-field > header { display: flex; align-items: flex-start; justify-content: space-between; gap: 10px; }.diff-field strong { display: block; color: #1e293b; font-size: 13px; }.diff-field code { color: #64748b; font-size: 11px; }.diff-field > p { margin: 10px 0 0; color: #64748b; font-size: 12px; }.diff-field dl { display: grid; gap: 8px; margin: 12px 0 0; }.diff-field dl div { display: grid; grid-template-columns: 145px minmax(0, 1fr); gap: 8px; }.diff-field dt { color: #64748b; font-size: 11px; }.diff-field dd { display: grid; gap: 4px; margin: 0; color: #475569; font-size: 12px; overflow-wrap: anywhere; }.diff-field del { color: #b91c1c; text-decoration: line-through; }.diff-field ins { color: #15803d; text-decoration: none; }.diff-field small { color: #a16207; font-size: 10px; }.empty { display: grid; min-height: 240px; place-items: center; color: #94a3b8; font-size: 13px; }@media (max-width: 640px) { .diff-drawer main { padding: 18px; }.diff-field dl div { grid-template-columns: 1fr; gap: 3px; } }
</style>
@@ -0,0 +1,166 @@
<!--
features/admin/modules/shipping-order-schema/components/SchemaVersionHistoryDrawer.vue
用途:以时间线和完整只读快照浏览订单 Schema 的草稿、发布及退役版本。
依赖:ShippingOrderSchemaVersion DTO、Vue I18n。
逻辑:父页面加载版本概要和按需详情;本组件仅展示并发出选择/关闭事件,不修改任何版本配置。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import SchemaAuditTimeline from '@/features/admin/modules/shipping-order-schema/components/SchemaAuditTimeline.vue';
import type { ShippingOrderField, ShippingOrderSchemaVersion } from '@/features/admin/types/shipping-order-schema.types';
import type { ShippingOrderSchemaAuditEvent } from '@/features/admin/types/shipping-order-schema.types';
const props = defineProps<{
modelValue: boolean;
versions: ShippingOrderSchemaVersion[];
selectedVersion: ShippingOrderSchemaVersion | null;
loading: boolean;
detailLoading: boolean;
total: number;
auditEvents: ShippingOrderSchemaAuditEvent[];
auditTotal: number;
auditLoading: boolean;
comparisonTarget: ShippingOrderSchemaVersion | null;
copying: boolean;
fieldOrder: ShippingOrderField[];
}>();
const emit = defineEmits<{
'update:modelValue': [visible: boolean];
select: [versionId: number];
loadMore: [];
loadMoreAudit: [];
compare: [versionId: number];
usage: [versionId: number];
copy: [versionId: number];
}>();
const { t } = useI18n();
/** 将时间转为用户本地格式;缺失发布时间时回退创建时间。 */
const formatDate = (value?: string | null): string => {
if (!value) return t('admin.shippingOrderSchema.historyUnknownTime');
return new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(new Date(value));
};
/** 根据版本状态提供一致的时间线标签。 */
const statusLabel = (status: ShippingOrderSchemaVersion['status']): string =>
t(`admin.shippingOrderSchema.historyStatus.${status}`);
/** 历史通用字段直接展示冻结来源键,不依赖当前可能已停用或改名的来源目录。 */
const contextSourceLabel = (field: NonNullable<ShippingOrderSchemaVersion['definition']>['fields'][number]): string =>
field.context_source?.source_key || '-';
/** 快照内容保持不变;展示时按当前字段目录顺序排列,已不存在字段回退冻结 sequence。 */
const fields = computed(() => {
const globalOrder = new Map(props.fieldOrder.map((field) => [field.id, field.display_sequence]));
return [...(props.selectedVersion?.definition?.fields || [])].sort((left, right) => {
const leftOrder = globalOrder.get(left.field_id) ?? 1_000_000 + Number(left.sequence || 0);
const rightOrder = globalOrder.get(right.field_id) ?? 1_000_000 + Number(right.sequence || 0);
return leftOrder - rightOrder;
});
});
/** 关闭抽屉时由父页面同步清除 URL 中的版本查询参数。 */
const close = (): void => emit('update:modelValue', false);
</script>
<template>
<Teleport to="body">
<div v-if="modelValue" class="history-layer" role="presentation" @click.self="close">
<aside class="history-drawer" role="dialog" aria-modal="true" :aria-label="t('admin.shippingOrderSchema.historyTitle')">
<header class="history-header">
<div><p>{{ t('admin.shippingOrderSchema.historyEyebrow') }}</p><h2>{{ t('admin.shippingOrderSchema.historyTitle') }}</h2></div>
<button type="button" class="history-close" :aria-label="t('common.close')" @click="close">×</button>
</header>
<div class="history-content">
<nav class="history-timeline" :aria-label="t('admin.shippingOrderSchema.historyTitle')">
<button
v-for="item in versions"
:key="item.id"
type="button"
class="history-item"
:class="{ selected: selectedVersion?.id === item.id }"
@click="emit('select', item.id)"
>
<span class="history-version">V{{ item.version }}</span>
<span class="history-status" :class="item.status">{{ statusLabel(item.status) }}</span>
<strong>{{ item.change_note || t('admin.shippingOrderSchema.historyNoNote') }}</strong>
<small>{{ formatDate(item.published_at || item.created_at) }}</small>
<small>{{ item.published_by?.display_name || item.created_by?.display_name || t('admin.shippingOrderSchema.historyUnknownActor') }}</small>
</button>
<button v-if="versions.length < total" type="button" class="history-more" :disabled="loading" @click="emit('loadMore')">
{{ loading ? t('common.loading') : t('admin.shippingOrderSchema.historyLoadMore') }}
</button>
</nav>
<section class="history-detail">
<div v-if="detailLoading" class="history-empty">{{ t('common.loading') }}</div>
<template v-else-if="selectedVersion">
<header class="detail-heading">
<div><p>{{ t('admin.shippingOrderSchema.historyViewing') }}</p><h3>V{{ selectedVersion.version }}</h3></div>
<span class="detail-readonly">{{ t('admin.shippingOrderSchema.readOnly') }}</span>
</header>
<dl class="detail-meta">
<div><dt>{{ t('admin.shippingOrderSchema.historyPublishedAt') }}</dt><dd>{{ formatDate(selectedVersion.published_at || selectedVersion.created_at) }}</dd></div>
<div><dt>{{ t('admin.shippingOrderSchema.historyPublisher') }}</dt><dd>{{ selectedVersion.published_by?.display_name || selectedVersion.created_by?.display_name || t('admin.shippingOrderSchema.historyUnknownActor') }}</dd></div>
<div><dt>{{ t('admin.shippingOrderSchema.historyChecksum') }}</dt><dd><code>{{ selectedVersion.checksum || '-' }}</code></dd></div>
<div><dt>{{ t('admin.shippingOrderSchema.changeNote') }}</dt><dd>{{ selectedVersion.change_note || t('admin.shippingOrderSchema.historyNoNote') }}</dd></div>
</dl>
<button v-if="comparisonTarget" type="button" class="compare-button" @click="emit('compare', selectedVersion.id)">
{{ t('admin.shippingOrderSchema.diffWithCurrent', { version: comparisonTarget.version }) }}
</button>
<div class="history-actions">
<button type="button" class="compare-button" @click="emit('usage', selectedVersion.id)">{{ t('admin.shippingOrderSchema.usageOpen') }}</button>
<button v-if="selectedVersion.status !== 'draft'" type="button" class="compare-button" :disabled="copying" @click="emit('copy', selectedVersion.id)">{{ t('admin.shippingOrderSchema.copyToDraft') }}</button>
</div>
<div class="snapshot-heading"><span>{{ t('admin.shippingOrderSchema.historySnapshotFields') }}</span><b>{{ fields.length }}</b></div>
<article v-for="field in fields" :key="field.field_id" class="snapshot-field" :class="{ excluded: field.enabled === false }">
<div class="snapshot-field-title"><strong>{{ field.display_name }}</strong><code>{{ field.field_code }}</code><span v-if="field.enabled === false">{{ t('admin.shippingOrderSchema.historyExcluded') }}</span></div>
<p>{{ field.scope === 'header' ? t('admin.shippingOrderSchema.placementHeader') : t('admin.shippingOrderSchema.placementLine') }} · {{ t(`admin.shippingOrderSchema.fieldType.${field.value_type}`) }}</p>
<dl v-if="field.field_category === 'general_context'"><div><dt>{{ t('admin.shippingOrderSchema.contextSource') }}</dt><dd>{{ contextSourceLabel(field) }}</dd></div><div><dt>{{ t('admin.shippingOrderSchema.deterministicCollection') }}</dt><dd>{{ t('admin.shippingOrderSchema.deterministicCollectionHint') }}</dd></div></dl>
<dl v-else><div><dt>{{ t('admin.shippingOrderSchema.aliases') }}</dt><dd>{{ field.aliases.join(', ') || '-' }}</dd></div><div><dt>{{ t('admin.shippingOrderSchema.extractionInstruction') }}</dt><dd>{{ field.extraction_instruction || '-' }}</dd></div></dl>
</article>
<SchemaAuditTimeline
:events="auditEvents"
:total="auditTotal"
:loading="auditLoading"
@load-more="emit('loadMoreAudit')"
/>
</template>
<div v-else class="history-empty">{{ t('admin.shippingOrderSchema.historySelectVersion') }}</div>
</section>
</div>
</aside>
</div>
</Teleport>
</template>
<style scoped>
.history-layer { position: fixed; z-index: 70; inset: 0; display: flex; justify-content: flex-end; background: rgb(15 23 42 / 30%); backdrop-filter: blur(2px); }
.history-drawer { display: flex; width: min(1060px, 96vw); height: 100%; flex-direction: column; background: #f8fafc; box-shadow: -18px 0 48px rgb(15 23 42 / 18%); }
.history-header { display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid #e2e8f0; background: #fff; padding: 22px 26px; }
.history-header p, .detail-heading p { margin: 0 0 4px; color: #0284c7; font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
.history-header h2, .detail-heading h3 { margin: 0; color: #1e293b; font-size: 20px; }
.history-close { width: 32px; height: 32px; border: 1px solid #dbe5ee; border-radius: 50%; background: #fff; color: #475569; font-size: 22px; line-height: 1; cursor: pointer; }
.history-content { display: grid; min-height: 0; flex: 1; grid-template-columns: 290px minmax(0, 1fr); }
.history-timeline { overflow-y: auto; border-right: 1px solid #e2e8f0; background: #f1f5f9; padding: 14px 10px; }
.history-item { display: grid; width: 100%; gap: 5px; margin-bottom: 6px; border: 1px solid transparent; border-radius: 8px; background: transparent; padding: 12px; color: #475569; font: inherit; text-align: left; cursor: pointer; }
.history-item:hover { background: #fff; }
.history-item.selected { border-color: #bae6fd; background: #fff; box-shadow: inset 3px 0 #0ea5e9; }
.history-version { color: #0f172a; font-size: 16px; font-weight: 700; }
.history-status { width: fit-content; border-radius: 999px; padding: 2px 6px; font-size: 10px; font-weight: 700; }
.history-status.published { background: #dcfce7; color: #15803d; }.history-status.retired { background: #e2e8f0; color: #475569; }.history-status.draft { background: #fef3c7; color: #a16207; }
.history-item strong { overflow: hidden; color: #334155; font-size: 12px; font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }.history-item small { color: #94a3b8; font-size: 11px; }
.history-more { width: 100%; border: 1px dashed #cbd5e1; border-radius: 7px; background: transparent; padding: 8px; color: #0284c7; font: inherit; font-size: 12px; cursor: pointer; }
.history-detail { overflow-y: auto; background: #fff; padding: 26px; }.history-empty { display: grid; min-height: 300px; place-items: center; color: #94a3b8; font-size: 13px; }
.detail-heading { display: flex; align-items: flex-start; justify-content: space-between; }.detail-readonly { border: 1px solid #cbd5e1; border-radius: 999px; background: #f8fafc; padding: 4px 9px; color: #64748b; font-size: 11px; font-weight: 700; }
.detail-meta { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; margin: 22px 0; }.detail-meta div { border: 1px solid #e5ebf1; border-radius: 8px; background: #fbfdff; padding: 10px; }.detail-meta dt, .snapshot-field dt { color: #94a3b8; font-size: 10px; }.detail-meta dd, .snapshot-field dd { margin: 5px 0 0; color: #334155; font-size: 12px; overflow-wrap: anywhere; }.detail-meta code { color: #0369a1; font-size: 10px; }
.snapshot-heading { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; color: #64748b; font-size: 12px; font-weight: 700; }.snapshot-heading b { border-radius: 999px; background: #e0f2fe; padding: 2px 7px; color: #0369a1; }
.compare-button { margin: -8px 0 16px; border: 1px solid #7dd3fc; border-radius: 6px; background: #f0f9ff; padding: 7px 10px; color: #0369a1; font: inherit; font-size: 12px; font-weight: 600; cursor: pointer; }
.history-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: -8px 0 16px; }.history-actions .compare-button { margin: 0; }.compare-button:disabled { cursor: not-allowed; opacity: .55; }
.snapshot-field { margin-top: 8px; border: 1px solid #e5ebf1; border-radius: 8px; padding: 13px; }.snapshot-field.excluded { border-style: dashed; opacity: .68; }.snapshot-field-title { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }.snapshot-field-title strong { color: #1e293b; font-size: 13px; }.snapshot-field-title code { color: #64748b; font-size: 11px; }.snapshot-field-title span { border-radius: 999px; background: #fef3c7; padding: 2px 6px; color: #a16207; font-size: 10px; }.snapshot-field p { margin: 6px 0 10px; color: #94a3b8; font-size: 11px; }.snapshot-field dl { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; margin: 0; }
@media (max-width: 760px) { .history-drawer { width: 100vw; }.history-content { grid-template-columns: 1fr; }.history-timeline { max-height: 38vh; border-right: 0; border-bottom: 1px solid #e2e8f0; }.detail-meta, .snapshot-field dl { grid-template-columns: 1fr; }.history-detail { padding: 18px; } }
</style>
@@ -0,0 +1,46 @@
<!--
features/admin/modules/shipping-order-schema/components/SchemaVersionUsageDrawer.vue
用途:展示一个订单 Schema 版本实际参与解析的使用统计和分页运行记录。
依赖:ShippingOrderSchemaVersionUsage DTO、Vue I18n。
逻辑:父页面负责请求数据和打开单次审计,本组件只展示摘要并发出选择/翻页事件。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { ShippingOrderSchemaVersionUsage } from '@/features/admin/types/shipping-order-schema.types';
defineProps<{ modelValue: boolean; usage: ShippingOrderSchemaVersionUsage | null; loading: boolean }>();
const emit = defineEmits<{ 'update:modelValue': [visible: boolean]; select: [extractionId: number]; loadMore: [] }>();
const { t } = useI18n();
/** 将可选 UTC 时间统一展示为本地阅读格式。 */
const formatDate = (value?: string | null): string => value
? new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(new Date(value))
: t('admin.shippingOrderSchema.historyUnknownTime');
</script>
<template>
<Teleport to="body">
<div v-if="modelValue" class="usage-layer" role="presentation" @click.self="emit('update:modelValue', false)">
<aside class="usage-drawer" role="dialog" aria-modal="true" :aria-label="t('admin.shippingOrderSchema.usageTitle')">
<header><div><p>{{ t('admin.shippingOrderSchema.usageEyebrow') }}</p><h2>{{ t('admin.shippingOrderSchema.usageTitle') }}</h2></div><button type="button" :aria-label="t('common.close')" @click="emit('update:modelValue', false)">×</button></header>
<main v-if="loading" class="usage-empty">{{ t('common.loading') }}</main>
<main v-else-if="usage">
<p class="usage-version">V{{ usage.version.version }}</p>
<dl class="usage-summary"><div><dt>{{ t('admin.shippingOrderSchema.usageTotal') }}</dt><dd>{{ usage.summary.total }}</dd></div><div><dt>{{ t('admin.shippingOrderSchema.usageFirst') }}</dt><dd>{{ formatDate(usage.summary.first_used_at) }}</dd></div><div><dt>{{ t('admin.shippingOrderSchema.usageLast') }}</dt><dd>{{ formatDate(usage.summary.last_used_at) }}</dd></div></dl>
<div class="usage-statuses"><span v-for="(count, status) in usage.summary.status_counts" :key="status">{{ t(`admin.shippingOrderSchema.extractionStatus.${status}`) }} <b>{{ count }}</b></span></div>
<h3>{{ t('admin.shippingOrderSchema.usageRecords') }}</h3>
<p v-if="!usage.items.length" class="usage-empty">{{ t('admin.shippingOrderSchema.usageEmpty') }}</p>
<button v-for="item in usage.items" :key="item.id" type="button" class="usage-record" @click="emit('select', item.id)">
<strong>#{{ item.id }}</strong><span>{{ t(`admin.shippingOrderSchema.extractionStatus.${item.status}`) }}</span><small>{{ formatDate(item.created_at) }} · {{ item.input_snapshot_hash.slice(0, 12) }}</small>
</button>
<button v-if="usage.items.length < usage.total" type="button" class="usage-more" :disabled="loading" @click="emit('loadMore')">{{ t('admin.shippingOrderSchema.usageLoadMore') }}</button>
</main>
<main v-else class="usage-empty">{{ t('admin.shippingOrderSchema.usageEmpty') }}</main>
</aside>
</div>
</Teleport>
</template>
<style scoped>
.usage-layer { position: fixed; z-index: 80; inset: 0; display: flex; justify-content: flex-end; background: rgb(15 23 42 / 35%); backdrop-filter: blur(2px); }.usage-drawer { display: flex; width: min(680px, 96vw); height: 100%; flex-direction: column; overflow: hidden; background: #f8fafc; box-shadow: -18px 0 48px rgb(15 23 42 / 18%); }.usage-drawer > header { display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid #e2e8f0; background: #fff; padding: 22px 26px; }.usage-drawer header p { margin: 0 0 4px; color: #0284c7; font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }.usage-drawer h2 { margin: 0; color: #1e293b; font-size: 20px; }.usage-drawer > header button { width: 32px; height: 32px; border: 1px solid #dbe5ee; border-radius: 50%; background: #fff; color: #475569; font-size: 22px; line-height: 1; cursor: pointer; }.usage-drawer main { overflow-y: auto; padding: 24px 26px; }.usage-version { margin: 0 0 12px; color: #0369a1; font-weight: 700; }.usage-summary { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; margin: 0; }.usage-summary div { border: 1px solid #e2e8f0; border-radius: 8px; background: #fff; padding: 10px; }.usage-summary dt { color: #94a3b8; font-size: 10px; }.usage-summary dd { margin: 5px 0 0; color: #334155; font-size: 12px; overflow-wrap: anywhere; }.usage-statuses { display: flex; flex-wrap: wrap; gap: 7px; margin: 14px 0; }.usage-statuses span { border-radius: 999px; background: #e0f2fe; padding: 3px 7px; color: #0369a1; font-size: 11px; }.usage-drawer h3 { margin: 22px 0 10px; color: #64748b; font-size: 12px; }.usage-record { display: grid; width: 100%; grid-template-columns: 70px 1fr; gap: 5px 10px; margin-top: 7px; border: 1px solid #e2e8f0; border-radius: 8px; background: #fff; padding: 11px; color: #475569; font: inherit; text-align: left; cursor: pointer; }.usage-record:hover { border-color: #7dd3fc; background: #f0f9ff; }.usage-record strong { color: #1e293b; font-size: 12px; }.usage-record span { color: #0369a1; font-size: 12px; }.usage-record small { grid-column: 1 / -1; color: #94a3b8; font-size: 10px; }.usage-empty { display: grid; min-height: 220px; place-items: center; color: #94a3b8; font-size: 13px; }.usage-more { width: 100%; margin-top: 10px; border: 1px dashed #cbd5e1; border-radius: 7px; background: transparent; padding: 8px; color: #0284c7; font: inherit; font-size: 12px; cursor: pointer; }@media (max-width: 640px) { .usage-drawer main { padding: 18px; }.usage-summary { grid-template-columns: 1fr; } }
</style>
@@ -0,0 +1,48 @@
/**
* features/admin/modules/shipping-order-schema/shippingOrderField.utils.spec.ts
* 用途:验证三类订单上下文字段的稳定形态及受控来源文案映射。
* 依赖:Vitest、shippingOrderField.utils。
* 逻辑:阻止通用字段误提交为 Line/LLM/数值字段,并避免页面泄露内部来源键。
*/
import { describe, expect, it } from 'vitest';
import {
contextOptionLabelKey, fieldShapeForCategory, reorderFieldConfigs, reorderFieldIds,
} from './shippingOrderField.utils';
describe('shipping order field category helpers', () => {
it('forces general context fields to deterministic header text', () => {
expect(fieldShapeForCategory('general_context')).toEqual({
scope: 'header', collection_mode: 'deterministic_context', value_type: 'string',
});
});
it('maps order header and line fields to LLM extraction', () => {
expect(fieldShapeForCategory('order_header').scope).toBe('header');
expect(fieldShapeForCategory('order_line')).toMatchObject({ scope: 'line', collection_mode: 'llm_extraction' });
});
it('maps registered From options to localized labels', () => {
expect(contextOptionLabelKey('mail_header', 'from_email')).toContain('mail_header_from_email');
expect(contextOptionLabelKey('json_path', 'selector')).toBeNull();
});
it('reorders fields only inside the selected category slots', () => {
const configs = [
{ field_id: 'context-1' }, { field_id: 'header-1' }, { field_id: 'header-2' }, { field_id: 'line-1' },
] as never[];
const reordered = reorderFieldConfigs(configs, ['header-1', 'header-2'], 'header-2', 'header-1');
expect(reordered.map((item) => item.field_id)).toEqual(['context-1', 'header-2', 'header-1', 'line-1']);
});
it('moves a field after the next row when dragging downward', () => {
expect(reorderFieldIds(['field-1', 'field-2', 'field-3'], 'field-1', 'field-2', 'after'))
.toEqual(['field-2', 'field-1', 'field-3']);
});
it('moves a field before the previous row when dragging upward', () => {
expect(reorderFieldIds(['field-1', 'field-2', 'field-3'], 'field-3', 'field-2', 'before'))
.toEqual(['field-1', 'field-3', 'field-2']);
});
});
@@ -0,0 +1,62 @@
/**
* features/admin/modules/shipping-order-schema/shippingOrderField.utils.ts
* 用途:集中计算订单上下文字段分类对应的稳定身份和受控来源文案键。
* 依赖:shipping-order-schema.types。
* 逻辑:Schema 页面创建字段与展示来源时共享纯函数,避免模板分支产生不一致 payload。
*/
import type { ShippingOrderField, ShippingOrderFieldConfig } from '@/features/admin/types/shipping-order-schema.types';
export type ShippingOrderFieldCategory = ShippingOrderField['field_category'];
export type FieldDropPosition = 'before' | 'after';
/** 将业务分类收敛为后端允许的 scope、collection_mode 和默认 value_type。 */
export const fieldShapeForCategory = (category: ShippingOrderFieldCategory): Pick<
ShippingOrderField,
'scope' | 'collection_mode' | 'value_type'
> => ({
scope: category === 'order_line' ? 'line' : 'header',
collection_mode: category === 'general_context' ? 'deterministic_context' : 'llm_extraction',
value_type: 'string',
});
/** 将首批受控邮件来源转换为四语言键;未知扩展项回退数据库展示名称。 */
export const contextOptionLabelKey = (providerKey: string, optionKey: string): string | null => {
const key = `${providerKey}.${optionKey}`;
return {
'mail_header.from_email': 'admin.shippingOrderSchema.contextOption.mail_header_from_email',
'mail_header.from_domain': 'admin.shippingOrderSchema.contextOption.mail_header_from_domain',
}[key] || null;
};
/** 计算同分类字段的插入顺序;明确区分目标行前后,避免向下拖动相邻字段时顺序不变。 */
export const reorderFieldIds = (
fieldIds: string[],
draggedFieldId: string,
targetFieldId: string,
position: FieldDropPosition = 'before',
): string[] => {
if (draggedFieldId === targetFieldId || !fieldIds.includes(draggedFieldId)) return fieldIds;
const orderedIds = fieldIds.filter((fieldId) => fieldId !== draggedFieldId);
const targetIndex = orderedIds.indexOf(targetFieldId);
if (targetIndex < 0) return fieldIds;
orderedIds.splice(targetIndex + (position === 'after' ? 1 : 0), 0, draggedFieldId);
return orderedIds;
};
/** 按当前数组顺序移动同分类字段;后端保存时会将数组位置固化为 sequence。 */
export const reorderFieldConfigs = <T extends ShippingOrderFieldConfig>(
configs: T[],
fieldIdsInCategory: string[],
draggedFieldId: string,
targetFieldId: string,
position: FieldDropPosition = 'before',
): T[] => {
const orderedIds = reorderFieldIds(fieldIdsInCategory, draggedFieldId, targetFieldId, position);
if (orderedIds === fieldIdsInCategory) return configs;
const categorySet = new Set(fieldIdsInCategory);
const replacements = orderedIds.map((fieldId) => configs.find((item) => item.field_id === fieldId));
let replacementIndex = 0;
return configs.map((item) => (
categorySet.has(item.field_id) ? replacements[replacementIndex++] || item : item
));
};
@@ -0,0 +1,796 @@
<!--
features/admin/modules/shipping-process-gates/ShippingProcessGateDiagnosticsPage.vue
用途:管理员 Process Gate Execution 诊断——列表、Gate 轨道与 Attempt 明细。
依赖:process-gates.api、Vue Router、Vue I18n(admin + workspace.processGate 动作文案)。
逻辑:只读诊断;多维度筛选(status/gate/reason/party/q/时间);小屏卡片列表 + 详情下置;
lg+ 主从布局(左侧 ~38% Execution 紧凑列表 + 分页,右侧 sticky 详情:Gate/findings/attempts);
状态/动作展示业务标签并附技术码;Gate 诊断结构化卡片(findings/blocking/effective_result);
Attempt 展示 snapshot_diff 摘要并可跳转 AdminShippingAudit。
-->
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import {
getAdminProcessExecution,
listAdminProcessExecutions,
listAdminProcessGateAttempts,
type AdminProcessExecutionDetail,
type AdminProcessExecutionListFilters,
type AdminProcessExecutionSummary,
type AdminProcessGateAttemptsPayload,
} from '@/features/shipping-process-gates/api/process-gates.api';
const { t, te } = useI18n();
const router = useRouter();
const loading = ref(false);
const detailLoading = ref(false);
const attemptsLoading = ref(false);
const error = ref('');
const page = ref(1);
const pageSize = 25;
const total = ref(0);
const filters = ref<AdminProcessExecutionListFilters>({
status: '',
gate_code: '',
blocking_reason_code: '',
responsible_party: '',
q: '',
updated_from: '',
updated_to: '',
});
const rows = ref<AdminProcessExecutionSummary[]>([]);
const detail = ref<AdminProcessExecutionDetail | null>(null);
const selectedGateCode = ref('');
const attemptsPayload = ref<AdminProcessGateAttemptsPayload | null>(null);
const EXECUTION_STATUS_OPTIONS = [
'active',
'blocked',
'waiting_external',
'completed',
'failed',
'cancelled',
] as const;
type GateFinding = {
severity?: string;
field_code?: string;
field?: string;
responsible_party?: string;
party?: string;
reason_code?: string;
reason?: string;
code?: string;
finding_code?: string;
message?: string;
details?: Record<string, unknown>;
};
type SnapshotKeyDiff = {
added?: string[];
removed?: string[];
changed?: string[];
};
type SnapshotDiffPayload = {
previous_attempt_no?: number;
input?: SnapshotKeyDiff;
output?: SnapshotKeyDiff;
input_hash_changed?: boolean;
output_hash_changed?: boolean;
};
const EMPTY_FILTERS: AdminProcessExecutionListFilters = {
status: '',
gate_code: '',
blocking_reason_code: '',
responsible_party: '',
q: '',
updated_from: '',
updated_to: '',
};
const formatTime = (value?: string | null) => (value ? new Date(value).toLocaleString() : '—');
/**
* 将 datetime-local 值规范为 ISO 字符串供 API 查询。
*/
function normalizeDateTimeFilter(value?: string): string {
const raw = String(value || '').trim();
if (!raw) return '';
const date = new Date(raw);
if (Number.isNaN(date.getTime())) return raw;
return date.toISOString();
}
/**
* Execution / Gate 状态业务标签;无翻译时回落原始码。
*/
function statusLabel(code?: string | null): string {
const key = String(code || '').trim();
if (!key) return '—';
const i18nKey = `admin.shippingProcessGates.statusLabels.${key}`;
return te(i18nKey) ? t(i18nKey) : key;
}
/**
* 主动作业务标签(复用 workspace 动作文案)+ 技术码,便于运维对照。
*/
function actionLabel(code?: string | null): string {
const key = String(code || '').trim();
if (!key) return '—';
const i18nKey = `workspace.shippingNotice.processGate.actionCodes.${key}`;
const label = te(i18nKey) ? t(i18nKey) : key;
return label === key ? key : `${label} (${key})`;
}
/**
* 组装当前列表筛选 payload,剔除空值并规范化时间。
*/
function buildListFilters(): AdminProcessExecutionListFilters {
const payload: AdminProcessExecutionListFilters = {};
(Object.entries(filters.value) as Array<[keyof AdminProcessExecutionListFilters, string | undefined]>).forEach(
([key, value]) => {
const text = String(value || '').trim();
if (!text) return;
if (key === 'updated_from' || key === 'updated_to') {
payload[key] = normalizeDateTimeFilter(text);
return;
}
payload[key] = text;
},
);
return payload;
}
/** 兼容后端 items / attempts 双字段。 */
const attemptRows = computed(() => {
const payload = attemptsPayload.value;
if (!payload) return [];
const list = payload.items || payload.attempts || [];
return Array.isArray(list) ? list : [];
});
/** 详情中的完整 Gate 列表(含 findings)。 */
const diagnosticGates = computed(() => {
const gates = detail.value?.gates;
return Array.isArray(gates) ? gates : [];
});
const selectedGateDetail = computed(() => {
if (!selectedGateCode.value) return null;
return diagnosticGates.value.find((gate) => String(gate.gate_code) === selectedGateCode.value) || null;
});
const selectedGateFindings = computed(() => normalizeFindings(selectedGateDetail.value?.findings));
const selectedBlockingReasonRows = computed(() => blockingReasonRows(selectedGateDetail.value?.blocking_reason));
const selectedEffectiveResultSummary = computed(() => effectiveResultSummary(selectedGateDetail.value?.effective_result));
const selectedEffectiveResultRemainder = computed(() => (
effectiveResultRemainder(selectedGateDetail.value?.effective_result, selectedEffectiveResultSummary.value)
));
/**
* 将任意 JSON 安全格式化为可展示文本。
*/
function formatJson(value: unknown): string {
if (value == null) return '—';
try {
return JSON.stringify(value, null, 2);
} catch {
return String(value);
}
}
/**
* 将单元格值转为短文本。
*/
function formatCellValue(value: unknown): string {
if (value == null) return '—';
if (typeof value === 'string') return value;
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
/**
* 规范化 Gate findings 数组。
*/
function normalizeFindings(raw: unknown): GateFinding[] {
if (!Array.isArray(raw)) return [];
return raw.filter((item): item is GateFinding => Boolean(item) && typeof item === 'object');
}
/**
* 提取 Finding 展示字段。
*/
function findingField(finding: GateFinding): string {
return String(finding.field_code || finding.field || '').trim() || '—';
}
function findingParty(finding: GateFinding): string {
return String(finding.responsible_party || finding.party || '').trim() || '—';
}
function findingReason(finding: GateFinding): string {
return String(finding.reason_code || finding.reason || finding.code || finding.finding_code || '').trim() || '—';
}
function findingMessage(finding: GateFinding): string {
if (finding.message) return String(finding.message);
const details = finding.details;
if (details && typeof details === 'object' && details.message != null) {
return String(details.message);
}
return '—';
}
/**
* 将 blocking_reason 对象转为 key-value 行。
*/
function blockingReasonRows(raw: unknown): Array<{ key: string; value: string }> {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return [];
return Object.entries(raw as Record<string, unknown>).map(([key, value]) => ({
key,
value: formatCellValue(value),
}));
}
/**
* 从 effective_result 提取摘要 chips(优先常见键 + findings 计数)。
*/
function effectiveResultSummary(raw: unknown): Array<{ key: string; value: string }> {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return [];
const obj = raw as Record<string, unknown>;
const chips: Array<{ key: string; value: string }> = [];
const priorityKeys = ['passed', 'status', 'case', 'outcome', 'summary'];
for (const key of priorityKeys) {
if (Object.prototype.hasOwnProperty.call(obj, key) && obj[key] != null) {
chips.push({ key, value: formatCellValue(obj[key]) });
}
}
if (Array.isArray(obj.findings)) {
chips.push({ key: 'findings', value: String(obj.findings.length) });
}
return chips;
}
/**
* 返回 effective_result 中未出现在摘要 chips 内的剩余 JSON。
*/
function effectiveResultRemainder(
raw: unknown,
summary: Array<{ key: string; value: string }>,
): Record<string, unknown> | null {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
const obj = { ...(raw as Record<string, unknown>) };
const consumed = new Set(summary.map((item) => item.key));
for (const key of consumed) {
delete obj[key];
}
return Object.keys(obj).length ? obj : null;
}
/**
* 格式化 Attempt snapshot_diff 单段(input/output)摘要。
*/
function formatSnapshotDiffSection(scope: 'input' | 'output', diff: SnapshotDiffPayload | null | undefined): string | null {
const section = diff?.[scope];
if (!section) return null;
const added = section.added?.length ?? 0;
const removed = section.removed?.length ?? 0;
const changed = section.changed?.length ?? 0;
if (!added && !removed && !changed) return null;
const scopeLabel = scope === 'input' ? 'input' : 'output';
return t('admin.shippingProcessGates.attemptDiff', {
scope: scopeLabel,
added,
removed,
changed,
});
}
/**
* 合并 Attempt snapshot_diff 的 input/output 摘要行。
*/
function formatAttemptDiffSummary(raw: unknown): string[] {
if (!raw || typeof raw !== 'object') return [];
const diff = raw as SnapshotDiffPayload;
const lines: string[] = [];
const inputLine = formatSnapshotDiffSection('input', diff);
const outputLine = formatSnapshotDiffSection('output', diff);
if (inputLine) lines.push(inputLine);
if (outputLine) lines.push(outputLine);
return lines;
}
/**
* 跳转 Admin 审计中心,预填 Execution 与 process_gate_ 事件前缀。
*/
function openAuditForExecution(executionNo: string) {
void router.push({
name: 'AdminShippingAudit',
query: {
q: executionNo,
event_type: 'process_gate_',
},
});
}
/**
* 加载 Execution 列表。
*/
async function load() {
loading.value = true;
error.value = '';
try {
const response = await listAdminProcessExecutions(page.value, pageSize, buildListFilters());
rows.value = response.items;
total.value = response.total;
} catch {
error.value = t('admin.shippingProcessGates.loadFailed');
} finally {
loading.value = false;
}
}
/**
* 应用筛选并重置到第一页。
*/
function applyFilters() {
page.value = 1;
void load();
}
/**
* 清空筛选并刷新列表。
*/
function resetFilters() {
filters.value = { ...EMPTY_FILTERS };
page.value = 1;
void load();
}
/**
* 打开 Execution 诊断详情。
*/
async function openDetail(executionNo: string) {
detailLoading.value = true;
selectedGateCode.value = '';
attemptsPayload.value = null;
try {
detail.value = await getAdminProcessExecution(executionNo);
const current = detail.value.current_gate?.gate_code
|| detail.value.current_blocking_gate?.gate_code;
if (current) await loadAttempts(String(current));
} catch {
error.value = t('admin.shippingProcessGates.detailFailed');
detail.value = null;
} finally {
detailLoading.value = false;
}
}
/**
* 加载指定 Gate 的 Attempt 列表。
*/
async function loadAttempts(gateCode: string) {
if (!detail.value?.execution_no) return;
selectedGateCode.value = gateCode;
attemptsLoading.value = true;
try {
attemptsPayload.value = await listAdminProcessGateAttempts(detail.value.execution_no, gateCode);
} catch {
attemptsPayload.value = null;
error.value = t('admin.shippingProcessGates.attemptsFailed');
} finally {
attemptsLoading.value = false;
}
}
/**
* 判断 Execution 是否为当前详情选中项,供 lg+ 主从列表行高亮。
*/
function isExecutionSelected(executionNo: string): boolean {
return Boolean(detail.value?.execution_no && detail.value.execution_no === executionNo);
}
/**
* 关闭详情面板。
*/
function closeDetail() {
detail.value = null;
selectedGateCode.value = '';
attemptsPayload.value = null;
}
onMounted(() => {
void load();
});
</script>
<template>
<div class="space-y-6 p-4 sm:p-6">
<header>
<h1 class="text-xl font-bold">{{ t('admin.shippingProcessGates.title') }}</h1>
<p class="mt-1 max-w-3xl text-sm text-muted">{{ t('admin.shippingProcessGates.subtitle') }}</p>
</header>
<section class="rounded-xl border border-default bg-surface p-4">
<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
<label class="text-sm">
<span class="mb-1 block text-xs text-muted">{{ t('admin.shippingProcessGates.status') }}</span>
<select v-model="filters.status" class="w-full rounded border border-default px-2 py-1.5 text-sm">
<option value="">{{ t('admin.shippingProcessGates.allStatuses') }}</option>
<option v-for="code in EXECUTION_STATUS_OPTIONS" :key="code" :value="code">
{{ statusLabel(code) }}
</option>
</select>
</label>
<label class="text-sm">
<span class="mb-1 block text-xs text-muted">{{ t('admin.shippingProcessGates.filterGate') }}</span>
<input
v-model="filters.gate_code"
type="text"
class="w-full rounded border border-default px-2 py-1.5 text-sm font-mono"
:placeholder="t('admin.shippingProcessGates.gateCode')"
/>
</label>
<label class="text-sm">
<span class="mb-1 block text-xs text-muted">{{ t('admin.shippingProcessGates.filterReason') }}</span>
<input
v-model="filters.blocking_reason_code"
type="text"
class="w-full rounded border border-default px-2 py-1.5 text-sm font-mono"
:placeholder="t('admin.shippingProcessGates.blockingReasonCode')"
/>
</label>
<label class="text-sm">
<span class="mb-1 block text-xs text-muted">{{ t('admin.shippingProcessGates.filterParty') }}</span>
<input
v-model="filters.responsible_party"
type="text"
class="w-full rounded border border-default px-2 py-1.5 text-sm"
:placeholder="t('admin.shippingProcessGates.responsibleParty')"
/>
</label>
<label class="text-sm sm:col-span-2 lg:col-span-1">
<span class="mb-1 block text-xs text-muted">{{ t('admin.shippingProcessGates.filterSearch') }}</span>
<input
v-model="filters.q"
type="search"
class="w-full rounded border border-default px-2 py-1.5 text-sm"
:placeholder="t('admin.shippingProcessGates.executionNo')"
/>
</label>
<label class="text-sm">
<span class="mb-1 block text-xs text-muted">{{ t('admin.shippingProcessGates.filterFrom') }}</span>
<input v-model="filters.updated_from" type="datetime-local" class="w-full rounded border border-default px-2 py-1.5 text-sm" />
</label>
<label class="text-sm">
<span class="mb-1 block text-xs text-muted">{{ t('admin.shippingProcessGates.filterTo') }}</span>
<input v-model="filters.updated_to" type="datetime-local" class="w-full rounded border border-default px-2 py-1.5 text-sm" />
</label>
</div>
<div class="mt-3 flex flex-wrap items-center gap-2">
<button type="button" class="rounded border border-default px-3 py-1.5 text-sm" @click="applyFilters">
{{ t('admin.shippingProcessGates.applyFilters') }}
</button>
<button type="button" class="rounded border border-default px-3 py-1.5 text-sm" @click="resetFilters">
{{ t('admin.shippingProcessGates.resetFilters') }}
</button>
<button type="button" class="rounded border border-default px-3 py-1.5 text-sm" @click="load">
{{ t('admin.shippingProcessGates.refresh') }}
</button>
<span class="text-xs text-muted">{{ t('admin.shippingProcessGates.total', { count: total }) }}</span>
</div>
</section>
<p v-if="error" class="text-sm text-rose-600">{{ error }}</p>
<!-- 小屏:卡片列表,避免列标题逐字换行 -->
<div class="space-y-3 lg:hidden" data-testid="shipping-process-gate-cards">
<p v-if="loading" class="rounded-xl border border-default px-4 py-8 text-center text-sm text-muted">
{{ t('admin.shippingProcessGates.loading') }}
</p>
<p v-else-if="!rows.length" class="rounded-xl border border-default px-4 py-8 text-center text-sm text-muted">
{{ t('admin.shippingProcessGates.empty') }}
</p>
<article
v-for="row in rows"
:key="row.execution_no"
class="rounded-xl border border-default bg-surface px-4 py-3 text-sm"
>
<div class="font-mono text-xs break-all">{{ row.execution_no }}</div>
<dl class="mt-2 grid grid-cols-1 gap-1.5 sm:grid-cols-2">
<div>
<dt class="text-xs text-muted">{{ t('admin.shippingProcessGates.status') }}</dt>
<dd>
<span>{{ statusLabel(row.status) }}</span>
<span class="ml-1 font-mono text-[11px] text-muted">{{ row.status }}</span>
</dd>
</div>
<div>
<dt class="text-xs text-muted">{{ t('admin.shippingProcessGates.currentGate') }}</dt>
<dd class="font-mono text-xs break-all">{{ row.current_gate_code || '—' }}</dd>
</div>
<div class="sm:col-span-2">
<dt class="text-xs text-muted">{{ t('admin.shippingProcessGates.nextAction') }}</dt>
<dd class="text-xs">{{ actionLabel(row.primary_next_action_code) }}</dd>
</div>
<div>
<dt class="text-xs text-muted">{{ t('admin.shippingProcessGates.updatedAt') }}</dt>
<dd class="text-xs">{{ formatTime(row.updated_at) }}</dd>
</div>
</dl>
<button
type="button"
class="mt-3 text-sm text-brand-600 hover:underline"
@click="openDetail(row.execution_no)"
>
{{ t('admin.shippingProcessGates.viewDetail') }}
</button>
</article>
</div>
<!-- lg+ 主从:左列表+分页,右 sticky 详情;小屏在网格外卡片列表,网格内仅分页+详情 -->
<div class="grid lg:grid-cols-[minmax(280px,38%)_minmax(0,1fr)] gap-4 items-start">
<div class="space-y-3">
<!-- lg+:紧凑 Execution 行列表 -->
<div class="hidden lg:block space-y-1.5" data-testid="shipping-process-gate-list">
<p v-if="loading" class="rounded-xl border border-default px-4 py-8 text-center text-sm text-muted">
{{ t('admin.shippingProcessGates.loading') }}
</p>
<p v-else-if="!rows.length" class="rounded-xl border border-default px-4 py-8 text-center text-sm text-muted">
{{ t('admin.shippingProcessGates.empty') }}
</p>
<button
v-for="row in rows"
:key="row.execution_no"
type="button"
class="w-full rounded-lg border px-3 py-2.5 text-left text-sm transition-colors"
:class="isExecutionSelected(row.execution_no)
? 'border-brand-500 bg-brand-50/80 ring-1 ring-brand-500/40 dark:bg-brand-950/30'
: 'border-default bg-surface hover:bg-surface-soft'"
@click="openDetail(row.execution_no)"
>
<div class="font-mono text-xs break-all">{{ row.execution_no }}</div>
<div class="mt-1.5 flex flex-wrap items-baseline gap-x-2 gap-y-0.5 text-xs">
<span>{{ statusLabel(row.status) }}</span>
<span class="font-mono text-[11px] text-muted">{{ row.status }}</span>
</div>
<div class="mt-1 truncate font-mono text-[11px] text-muted">
{{ row.current_gate_code || '—' }}
</div>
<div class="mt-1 truncate text-[11px] text-muted">{{ actionLabel(row.primary_next_action_code) }}</div>
<div class="mt-1 text-[11px] text-muted">{{ formatTime(row.updated_at) }}</div>
</button>
</div>
<div class="flex items-center gap-2 text-sm">
<button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page <= 1 || loading" @click="page -= 1; load()">
{{ t('admin.shippingProcessGates.previous') }}
</button>
<span>{{ page }}</span>
<button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page * pageSize >= total || loading" @click="page += 1; load()">
{{ t('admin.shippingProcessGates.next') }}
</button>
</div>
</div>
<aside
v-if="detail"
class="rounded-xl border border-default bg-surface p-4 lg:sticky lg:top-24 lg:max-h-[calc(100vh-8rem)] lg:overflow-y-auto"
data-testid="shipping-process-gate-detail"
>
<div class="mb-4 flex items-center justify-between gap-2">
<h2 class="text-lg font-semibold">{{ t('admin.shippingProcessGates.detailTitle') }}</h2>
<button type="button" class="text-sm text-muted hover:text-primary" @click="closeDetail">{{ t('admin.close') }}</button>
</div>
<p v-if="detailLoading" class="text-sm text-muted">{{ t('admin.shippingProcessGates.loading') }}</p>
<template v-else>
<dl class="grid gap-2 text-sm sm:grid-cols-2">
<div><dt class="text-muted">{{ t('admin.shippingProcessGates.executionNo') }}</dt><dd class="font-mono text-xs break-all">{{ detail.execution_no }}</dd></div>
<div>
<dt class="text-muted">{{ t('admin.shippingProcessGates.status') }}</dt>
<dd>
{{ statusLabel(detail.status) }}
<span class="ml-1 font-mono text-[11px] text-muted">{{ detail.status }}</span>
</dd>
</div>
<div><dt class="text-muted">{{ t('admin.shippingProcessGates.taskNo') }}</dt><dd class="font-mono text-xs">{{ detail.task_no || '—' }}</dd></div>
<div><dt class="text-muted">{{ t('admin.shippingProcessGates.caseNo') }}</dt><dd class="font-mono text-xs">{{ detail.review_case_no || detail.case_no || '—' }}</dd></div>
</dl>
<h3 class="mt-6 text-sm font-semibold">{{ t('admin.shippingProcessGates.gates') }}</h3>
<div class="mt-2 space-y-2 lg:hidden">
<article
v-for="gate in diagnosticGates"
:key="String(gate.gate_code)"
class="rounded-lg border border-default px-3 py-2 text-xs"
:class="{ 'bg-amber-50/60 dark:bg-amber-950/20': selectedGateCode === gate.gate_code }"
>
<div class="font-semibold">#{{ gate.sequence_no }} · {{ gate.gate_code }}</div>
<div class="mt-1">{{ statusLabel(String(gate.status)) }} <span class="font-mono text-muted">{{ gate.status }}</span></div>
<div class="mt-1 font-mono text-muted">{{ gate.blocking_reason_code || '—' }}</div>
<button type="button" class="mt-2 text-brand-600 hover:underline" @click="loadAttempts(String(gate.gate_code))">
{{ t('admin.shippingProcessGates.viewAttempts') }}
</button>
</article>
</div>
<div class="mt-2 hidden overflow-x-auto rounded-lg border border-default lg:block">
<table class="min-w-[640px] w-full text-xs">
<thead class="bg-surface-soft text-left text-muted">
<tr>
<th class="whitespace-nowrap px-3 py-2">#</th>
<th class="whitespace-nowrap px-3 py-2">{{ t('admin.shippingProcessGates.gateCode') }}</th>
<th class="whitespace-nowrap px-3 py-2">{{ t('admin.shippingProcessGates.gateStatus') }}</th>
<th class="whitespace-nowrap px-3 py-2">{{ t('admin.shippingProcessGates.blockingReason') }}</th>
<th class="whitespace-nowrap px-3 py-2">{{ t('admin.shippingProcessGates.actions') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="gate in diagnosticGates"
:key="String(gate.gate_code)"
class="border-t border-default"
:class="{ 'bg-amber-50/60 dark:bg-amber-950/20': selectedGateCode === gate.gate_code }"
>
<td class="whitespace-nowrap px-3 py-2">{{ gate.sequence_no }}</td>
<td class="whitespace-nowrap px-3 py-2 font-mono">{{ gate.gate_code }}</td>
<td class="px-3 py-2">
<div>{{ statusLabel(String(gate.status)) }}</div>
<div class="font-mono text-[11px] text-muted">{{ gate.status }}</div>
</td>
<td class="whitespace-nowrap px-3 py-2 font-mono">{{ gate.blocking_reason_code || '—' }}</td>
<td class="whitespace-nowrap px-3 py-2">
<button type="button" class="text-brand-600 hover:underline" @click="loadAttempts(String(gate.gate_code))">
{{ t('admin.shippingProcessGates.viewAttempts') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
<section v-if="selectedGateDetail" class="mt-4 rounded-lg border border-default px-3 py-3 text-xs">
<h4 class="font-semibold">{{ t('admin.shippingProcessGates.gateDiagnostics') }}</h4>
<p class="mt-1 text-muted">
{{ t('admin.shippingProcessGates.nextAction') }}:
<span>{{ actionLabel(String(selectedGateDetail.next_action_code || '')) }}</span>
</p>
<div class="mt-3">
<div class="font-medium text-muted">{{ t('admin.shippingProcessGates.findingsStructured') }}</div>
<p v-if="!selectedGateFindings.length" class="mt-1 text-muted">{{ t('admin.shippingProcessGates.noFindings') }}</p>
<div v-else class="mt-2 space-y-2">
<article
v-for="(finding, index) in selectedGateFindings"
:key="`${finding.finding_code || finding.reason_code || index}`"
class="rounded border border-default bg-surface-soft px-3 py-2"
>
<div class="flex flex-wrap items-center gap-2">
<span
class="rounded px-1.5 py-0.5 font-mono text-[11px]"
:class="finding.severity === 'blocking'
? 'bg-rose-100 text-rose-800 dark:bg-rose-950 dark:text-rose-200'
: 'bg-slate-100 text-slate-700 dark:bg-slate-900 dark:text-slate-200'"
>
{{ t('admin.shippingProcessGates.severity') }}: {{ finding.severity || '—' }}
</span>
</div>
<dl class="mt-2 grid gap-1 sm:grid-cols-2">
<div>
<dt class="text-muted">{{ t('admin.shippingProcessGates.field') }}</dt>
<dd class="font-mono">{{ findingField(finding) }}</dd>
</div>
<div>
<dt class="text-muted">{{ t('admin.shippingProcessGates.party') }}</dt>
<dd>{{ findingParty(finding) }}</dd>
</div>
<div>
<dt class="text-muted">{{ t('admin.shippingProcessGates.reason') }}</dt>
<dd class="font-mono">{{ findingReason(finding) }}</dd>
</div>
<div class="sm:col-span-2">
<dt class="text-muted">{{ t('admin.shippingProcessGates.message') }}</dt>
<dd class="break-words">{{ findingMessage(finding) }}</dd>
</div>
</dl>
</article>
</div>
</div>
<div class="mt-3">
<div class="font-medium text-muted">{{ t('admin.shippingProcessGates.blockingReasonDetail') }}</div>
<p v-if="!selectedBlockingReasonRows.length" class="mt-1 text-muted">—</p>
<dl v-else class="mt-2 divide-y divide-default rounded border border-default">
<div
v-for="row in selectedBlockingReasonRows"
:key="row.key"
class="grid gap-1 px-3 py-2 sm:grid-cols-[minmax(8rem,30%)_1fr]"
>
<dt class="font-mono text-muted">{{ row.key }}</dt>
<dd class="break-words">{{ row.value }}</dd>
</div>
</dl>
</div>
<div class="mt-3">
<div class="font-medium text-muted">{{ t('admin.shippingProcessGates.effectiveResult') }}</div>
<p v-if="!selectedEffectiveResultSummary.length && !selectedEffectiveResultRemainder" class="mt-1 text-muted">—</p>
<div v-else class="mt-2 space-y-2">
<div v-if="selectedEffectiveResultSummary.length" class="flex flex-wrap gap-2">
<span
v-for="chip in selectedEffectiveResultSummary"
:key="chip.key"
class="rounded-full border border-default bg-surface-soft px-2 py-0.5 font-mono text-[11px]"
>
{{ chip.key }}: {{ chip.value }}
</span>
</div>
<details v-if="selectedEffectiveResultRemainder">
<summary class="cursor-pointer text-brand-600">
{{ Object.keys(selectedEffectiveResultRemainder).join(', ') }}
</summary>
<pre class="mt-2 max-h-48 overflow-auto rounded bg-surface-soft p-2">{{ formatJson(selectedEffectiveResultRemainder) }}</pre>
</details>
</div>
</div>
</section>
<div class="mt-6 flex flex-wrap items-center justify-between gap-2">
<h3 class="text-sm font-semibold">
{{ t('admin.shippingProcessGates.attempts') }}
<span v-if="selectedGateCode" class="font-mono text-xs text-muted">({{ selectedGateCode }})</span>
</h3>
<button
type="button"
class="text-xs text-brand-600 hover:underline"
@click="openAuditForExecution(detail.execution_no)"
>
{{ t('admin.shippingProcessGates.openAudit') }}
</button>
</div>
<p class="text-xs text-muted">{{ t('admin.shippingProcessGates.auditLink') }}</p>
<p v-if="attemptsLoading" class="mt-2 text-sm text-muted">{{ t('admin.shippingProcessGates.loading') }}</p>
<div v-else-if="attemptRows.length" class="mt-2 space-y-2">
<article
v-for="attempt in attemptRows"
:key="String(attempt.id || attempt.attempt_no)"
class="rounded-lg border border-default px-3 py-2 text-xs"
>
<div class="font-mono">#{{ attempt.attempt_no }} · {{ statusLabel(String(attempt.status)) }} <span class="text-muted">({{ attempt.status }})</span></div>
<div v-if="attempt.error_code" class="mt-1 text-rose-700">{{ attempt.error_code }}: {{ attempt.error_summary }}</div>
<div class="mt-1 text-muted">{{ formatTime(attempt.started_at as string) }} → {{ formatTime(attempt.finished_at as string) }}</div>
<div class="mt-1 text-muted">
hash:
in={{ attempt.input_snapshot_hash || '—' }}
/ out={{ attempt.output_snapshot_hash || '—' }}
</div>
<ul v-if="formatAttemptDiffSummary(attempt.snapshot_diff).length" class="mt-2 space-y-0.5 text-muted">
<li v-for="(line, lineIndex) in formatAttemptDiffSummary(attempt.snapshot_diff)" :key="lineIndex">
{{ line }}
</li>
</ul>
<details v-if="attempt.input_snapshot || attempt.output_snapshot" class="mt-2">
<summary class="cursor-pointer text-brand-600">{{ t('admin.shippingProcessGates.viewSnapshots') }}</summary>
<div class="mt-2 grid gap-2 md:grid-cols-2">
<pre class="max-h-48 overflow-auto rounded bg-surface-soft p-2">{{ formatJson(attempt.input_snapshot) }}</pre>
<pre class="max-h-48 overflow-auto rounded bg-surface-soft p-2">{{ formatJson(attempt.output_snapshot) }}</pre>
</div>
</details>
</article>
</div>
<p v-else class="mt-2 text-sm text-muted">{{ t('admin.shippingProcessGates.noAttempts') }}</p>
</template>
</aside>
</div>
</div>
</template>
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,138 @@
<script setup lang="ts">
/**
* features/admin/modules/training-config/components/LeanTargetModal.vue
* 用途:精益周任务"受训对象"选择弹窗,支持按角色、按员工两个维度多选(两个范围取并集生效)。
* 依赖:vue-i18n、lucide 图标与父级培训配置页面传入的目标状态(角色/用户 ID/用户列表)。
* 逻辑:弹窗打开时从 props 快照到本地草稿(取消不污染外部状态);员工支持关键字搜索;
* 确认后 emit save({ roles, userIds }),由父级写回表单并随"保存任务"统一落库。
*/
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Search } from 'lucide-vue-next';
import type { AdminUserRow } from '../../../types/admin.types';
const props = defineProps<{
visible: boolean;
roles: string[];
userIds: number[];
users: AdminUserRow[];
roleOptions: string[];
}>();
const emit = defineEmits<{ close: []; save: [payload: { roles: string[]; userIds: number[] }] }>();
const { t } = useI18n();
const draftRoles = ref<string[]>([]);
const draftUserIds = ref<number[]>([]);
const keyword = ref('');
// [STEP 1] 打开时同步父级当前选择,避免用户在弹窗内取消后残留草稿
watch(() => props.visible, (visible) => {
if (visible) {
draftRoles.value = [...props.roles];
draftUserIds.value = [...props.userIds];
keyword.value = '';
}
});
// [STEP 2] 员工列表按姓名/用户名/部门模糊过滤,便于在大量员工中快速定位
const filteredUsers = computed(() => {
const query = keyword.value.trim().toLowerCase();
if (!query) return props.users;
return props.users.filter((user) => [user.real_name, user.username, user.department]
.some((field) => field && field.toLowerCase().includes(query)));
});
const summaryLabel = computed(() => t('admin.trainingConfig.lean.targetSelectedCount', {
roles: draftRoles.value.length,
users: draftUserIds.value.length,
}));
const toggleRole = (role: string) => {
draftRoles.value = draftRoles.value.includes(role)
? draftRoles.value.filter((item) => item !== role)
: [...draftRoles.value, role];
};
const toggleUser = (userId: number) => {
draftUserIds.value = draftUserIds.value.includes(userId)
? draftUserIds.value.filter((item) => item !== userId)
: [...draftUserIds.value, userId];
};
const handleSave = () => {
emit('save', { roles: [...draftRoles.value], userIds: [...draftUserIds.value] });
};
</script>
<template>
<div v-if="props.visible" class="admin-modal-overlay animate-fade-in items-center" @click.self="emit('close')">
<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.trainingConfig.lean.targetModalTitle') }}</h3>
<p class="mt-1 text-xs text-muted">{{ t('admin.trainingConfig.lean.targetsHint') }}</p>
</div>
<div class="px-5 sm:px-8 py-5 overflow-y-auto">
<div class="grid gap-5 md:grid-cols-2">
<!-- 按角色选择 -->
<div class="space-y-2">
<label class="label-field">{{ t('admin.trainingConfig.lean.targetRoles') }}</label>
<div class="space-y-2 rounded-xl border border-default bg-surface p-3">
<label
v-for="role in props.roleOptions"
:key="role"
class="flex cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm transition hover:bg-surface-soft"
>
<input
type="checkbox"
class="h-4 w-4 rounded border-default text-emerald-600 focus:ring-emerald-500"
:checked="draftRoles.includes(role)"
@change="toggleRole(role)"
/>
<span class="text-primary">{{ role }}</span>
</label>
<p v-if="!props.roleOptions.length" class="px-2 py-3 text-xs text-muted">{{ t('admin.trainingConfig.lean.targetRolesEmpty') }}</p>
</div>
</div>
<!-- 按员工选择 -->
<div class="space-y-2">
<label class="label-field">{{ t('admin.trainingConfig.lean.targetUsers') }}</label>
<div class="relative">
<Search class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted" />
<input
v-model="keyword"
type="text"
class="input-field pl-9 text-sm"
:placeholder="t('admin.trainingConfig.lean.targetSearchPlaceholder')"
/>
</div>
<div class="max-h-64 space-y-1 overflow-y-auto rounded-xl border border-default bg-surface p-2">
<label
v-for="user in filteredUsers"
:key="user.id"
class="flex cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm transition hover:bg-surface-soft"
>
<input
type="checkbox"
class="h-4 w-4 rounded border-default text-emerald-600 focus:ring-emerald-500"
:checked="draftUserIds.includes(user.id)"
@change="toggleUser(user.id)"
/>
<span class="min-w-0 flex-1 truncate text-primary">{{ user.real_name || user.username }}</span>
<span class="shrink-0 text-xs text-muted">{{ user.username }}</span>
</label>
<p v-if="!filteredUsers.length" class="px-2 py-3 text-xs text-muted">{{ t('admin.trainingConfig.lean.targetUsersEmpty') }}</p>
</div>
</div>
</div>
</div>
<div class="admin-modal-footer">
<p class="mr-auto text-xs text-muted">{{ summaryLabel }}</p>
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary" @click="handleSave">
{{ t('admin.trainingConfig.lean.targetConfirm') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,52 @@
<script setup lang="ts">
/**
* features/admin/modules/training-config/components/TrainingTypeFormModal.vue
* 用途:提供培训类型 code 与名称的新增、编辑弹窗。
* 依赖:vue-i18n 与父级培训配置页面的表单状态。
* 逻辑:允许管理员输入符合编码规范的自定义类型 code,并将保存动作交由父级处理。
*/
import { useI18n } from 'vue-i18n';
const props = defineProps<{
visible: boolean;
editing: boolean;
form: { training_type: string; name: string };
isSaving: boolean;
}>();
const emit = defineEmits<{ close: []; save: [] }>();
const { t } = useI18n();
</script>
<template>
<div v-if="props.visible" class="admin-modal-overlay animate-fade-in items-center" @click.self="emit('close')">
<div class="admin-modal-panel max-w-lg 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">{{ props.editing ? t('admin.trainingConfig.editType') : t('admin.trainingConfig.addType') }}</h3>
</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.trainingConfig.fields.type') }}</label>
<input
v-model="props.form.training_type"
type="text"
class="input-field text-sm"
maxlength="50"
pattern="[a-z][a-z0-9_-]*"
:placeholder="t('admin.trainingConfig.placeholders.typeCode')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.trainingConfig.fields.name') }}</label>
<input v-model="props.form.name" type="text" class="input-field text-sm" :placeholder="t('admin.trainingConfig.fields.name')" />
</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="props.isSaving" @click="emit('save')">
{{ props.isSaving ? `${t('admin.save')}...` : props.editing ? t('admin.update') : t('admin.add') }}
</button>
</div>
</div>
</div>
</template>
@@ -218,10 +218,19 @@ onMounted(() => {
>
{{ t('admin.role.' + user.role) }}
</span>
<div v-if="user.feature_permissions?.training_hr_manage" class="mt-2">
<span class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700">
<div v-if="user.feature_permissions?.training_hr_manage || user.feature_permissions?.['contract_payment.access']" class="mt-2 flex flex-wrap gap-1.5">
<span
v-if="user.feature_permissions?.training_hr_manage"
class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700"
>
{{ t('admin.user.fields.trainingHrManage') }}
</span>
<span
v-if="user.feature_permissions?.['contract_payment.access']"
class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700"
>
{{ t('admin.user.fields.contractPaymentAccess') }}
</span>
</div>
</td>
<td class="px-6 py-4 text-right">
@@ -1,6 +1,6 @@
/**
* features/admin/modules/users/components/UserFormModal.vue
* 创建/编辑用户弹窗。
* 创建/编辑用户弹窗,含角色与功能权限勾选(培训 HR、合同付款预警访问)。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
@@ -105,6 +105,17 @@ const { t } = useI18n();
<span class="block text-xs leading-5 text-muted">{{ t('admin.user.fields.trainingHrManageHint') }}</span>
</span>
</label>
<label class="flex items-start gap-3 rounded-xl border border-default bg-white px-4 py-3">
<input
v-model="form.feature_permissions['contract_payment.access']"
type="checkbox"
class="mt-0.5 h-4 w-4 rounded border-default text-brand-600 focus:ring-brand-500"
/>
<span class="space-y-1">
<span class="block text-sm font-medium text-primary">{{ t('admin.user.fields.contractPaymentAccess') }}</span>
<span class="block text-xs leading-5 text-muted">{{ t('admin.user.fields.contractPaymentAccessHint') }}</span>
</span>
</label>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
@@ -205,6 +205,7 @@ export function useUsersAdmin() {
phone_number: user.phone_number || '',
feature_permissions: {
training_hr_manage: Boolean(user.feature_permissions?.training_hr_manage),
'contract_payment.access': Boolean(user.feature_permissions?.['contract_payment.access']),
},
agent_ids: user.agent_ids || [],
};
@@ -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">