feat(shipping-notice): 落地 XFA 统一视觉拆分确认门禁与处理投影收敛

闭合拆分预览令牌单次消费、样本 checksum 绑定与确认审计;正式提取改为 bindings-only。
同步统一标注工作台交互,并补齐进度投影/任务中心与迁移文档。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-06 10:21:25 +08:00
1 parent d2b3d74def
commit 84a881b554
195 files changed
+20269 -3463

No files matched your search

@@ -55,6 +55,10 @@ const filters = ref<ShippingAuditFilters>({
gate_code: '',
conversation_id: '',
owner_user_id: '',
profile_id: '',
binding_id: '',
revision_no: '',
segment_id: '',
operation_id: '',
request_id: '',
reason_code: '',
@@ -370,8 +374,29 @@ onMounted(() => {
<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">
@@ -4,7 +4,7 @@
依赖:shipping-audit.api 类型、shippingAuditDisplay、Vue I18n、useMessage。
逻辑:由 ShippingAuditCenterPage 传入 detail;事件/动作/结果与列表同源业务标签;
展示 before/after checksum 与 XFA snapshot_ref;技术编号以复制芯片展示;
关闭时 emit close;不自行拉接口。
若快照/metadata 含视觉绑定前后摘要则单独渲染;关闭时 emit close;不自行拉接口。
-->
<script setup lang="ts">
import { computed } from 'vue';
@@ -68,6 +68,33 @@ const techRefs = computed(() => {
.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 };
});
/**
* 关闭抽屉。
*/
@@ -176,6 +203,25 @@ function onClose() {
</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"
@@ -22,6 +22,7 @@ import {
listOrderProfileBlindTestAvailableSamples,
listOrderProfileBoundSamples,
previewOrderProfileBlindTestCandidate,
reparseOrderProfileSampleLayout,
removeOrderProfileTestSample,
} from '@/features/admin/api/shipping-order-document-profile.api';
import { uploadFileAsset } from '@/shared/api/file-assets.api';
@@ -276,6 +277,21 @@ async function previewSample(): Promise<void> {
}
}
/** 为缺少坐标证据的样本重新触发布局解析;完成后刷新候选状态再进入复核。 */
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>> = [];
@@ -390,6 +406,12 @@ function goToPublishCheck(): void {
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();
@@ -412,6 +434,16 @@ onBeforeUnmount(() => {
<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>
@@ -420,7 +452,7 @@ onBeforeUnmount(() => {
<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 type="button" class="btn-primary" :disabled="!selectedSample || selectedSample.review_mode === 'preparing' || working" @click="previewSample">{{ selectedSample?.review_mode === 'preparing' ? t('admin.shippingOrderProfiles.blindTest.reviewPreparing') : selectedSample?.review_mode === 'diagnostic' ? t('admin.shippingOrderProfiles.blindTest.viewDiagnostic') : t('admin.shippingOrderProfiles.blindTest.previewAndReview') }}</button><button type="button" class="btn-secondary" :disabled="availableSamplesLoading" @click="() => void loadAvailableSamples(true)">{{ t('admin.shippingOrderProfiles.blindTest.refreshSamples') }}</button></template></div>
<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>
@@ -455,6 +487,10 @@ onBeforeUnmount(() => {
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); }
@@ -1,9 +1,8 @@
<!--
features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue
用途:订单坐标 Profile 的独立草稿标注编辑页。
依赖:受控预览 API、Schema API、DocumentCanvas、IssuePanel、shippingOrderField.utils。
逻辑:仅编辑由向导创建的草稿;起行锚点默认 customer_po_line_no(内部项次 line_no 亦可绑定);
撤销/重做、自动保存和建议决定均受当前标签租约保护。
用途:订单文档 Profile 统一草稿标注编辑页(普通 PDF 坐标 + XFA 画布)。
依赖:受控预览 API、Schema API、DocumentCanvas、IssuePanel、OrderProfileXfaWorkbench、shippingOrderField.utils。
逻辑:template_mode 只决定 desk/右侧数据源能力;XFA 嵌入统一 bench-header/desk,坐标路径零回归。
-->
<script setup lang="ts">
import {
@@ -26,6 +25,7 @@ import {
acquireOrderDocumentProfileEditLease,
decideOrderDocumentProfileSuggestion,
generateOrderProfileOcrCoordinateEvidence,
getOrderDocumentProfileDetail,
getOrderProfileSampleTables,
listOrderProfileBoundSamples,
listOrderProfileSamples,
@@ -51,12 +51,16 @@ import type {
OrderProfileRowReconstructionMode,
ShippingOrderDocumentProfile,
} from "@/features/admin/types/shipping-order-document-profile.types";
import { asCoordinateProfileDefinition } from "@/features/admin/types/shipping-order-document-profile.types";
import {
asCoordinateProfileDefinition,
isXfaDatasetProfileDefinition,
} from "@/features/admin/types/shipping-order-document-profile.types";
import type {
ShippingOrderFieldConfig,
ShippingOrderSchemaVersion,
} from "@/features/admin/types/shipping-order-schema.types";
import OrderProfileDocumentCanvas from "./components/OrderProfileDocumentCanvas.vue";
import OrderProfileXfaWorkbench from "./OrderProfileXfaWorkbench.vue";
import {
restoreOrderProfileRegionPageNo,
suggestFieldCodeFromHeaders,
@@ -70,6 +74,38 @@ const { t } = useI18n();
const message = useMessage();
const route = useRoute();
const router = useRouter();
/** XFA 草稿走统一编辑器外壳;探测失败 fail-closed,禁止静默进入坐标编辑器。 */
const editorMode = ref<'detecting' | 'coordinate' | 'xfa' | 'error'>('detecting');
const editorModeError = ref<string | null>(null);
const isXfaTemplate = computed(() => editorMode.value === 'xfa');
const xfaWorkbenchRef = ref<InstanceType<typeof OrderProfileXfaWorkbench> | null>(null);
const xfaDirty = ref(false);
const xfaValidateBlocked = ref(false);
/**
* 根据草稿 template_mode / definition 选择统一编辑器分支。
* 核心逻辑:仅读取详情鉴别联合;请求失败时阻断并展示重试,不回退到坐标工作台。
*/
async function detectEditorMode(): Promise<void> {
editorMode.value = 'detecting';
editorModeError.value = null;
try {
const profileId = Number(route.params.profileId);
if (!Number.isFinite(profileId) || profileId <= 0) {
editorMode.value = 'error';
editorModeError.value = 'invalid_profile';
return;
}
const profile = await getOrderDocumentProfileDetail(profileId);
editorMode.value = (
isXfaDatasetProfileDefinition(profile.definition)
|| profile.template_mode === 'xfa_dataset'
) ? 'xfa' : 'coordinate';
} catch {
editorMode.value = 'error';
editorModeError.value = 'load_failed';
}
}
const profiles = ref<ShippingOrderDocumentProfile[]>([]);
const samples = ref<
Array<{
@@ -254,6 +290,7 @@ const selectedRegionKindLabel = computed(() => {
order_anchor: 'orderAnchor', order_field: 'orderField', header_field: 'header',
header: 'header', line: 'line', field: 'field', exclusion: 'exclusion',
document_anchor_label: 'documentMatchAnchorLabel', document_anchor_value: 'documentMatchAnchorValue',
xfa_visual: 'orderField',
};
const translationKey = translationKeys[kind];
return t(`admin.shippingOrderProfiles.workbench.${translationKey}`);
@@ -315,7 +352,11 @@ const selectedFieldHeaderSuggestion = computed(() => {
)
: null;
});
const dirty = computed(() => history.value.length > 0 || documentMatchDirty.value);
const dirty = computed(() => (
isXfaTemplate.value
? xfaDirty.value
: history.value.length > 0 || documentMatchDirty.value
));
/** 当前标注样本可同时作为训练证据;盲测样本仍由独立工作台维护。 */
const currentSampleIsTraining = computed(() => boundSamples.value.some(
(item) => item.sample_role === 'training' && item.document_id === form.documentId && item.table_id === form.tableId,
@@ -1013,6 +1054,25 @@ const definition = () => {
* @returns 保存完成后的最新草稿状态。
*/
const save = async (automatic = false) => {
if (isXfaTemplate.value) {
if (saving.value) return;
if (!automatic && !xfaDirty.value) return;
saving.value = true;
saveState.value = 'saving';
try {
const ok = await xfaWorkbenchRef.value?.saveDraft() ?? false;
if (ok) {
saveState.value = 'saved';
xfaDirty.value = false;
if (!automatic) message.success(t('admin.shippingOrderProfiles.xfaWorkbench.saved'));
} else if (saveState.value === 'saving') {
saveState.value = 'failed';
}
} finally {
saving.value = false;
}
return;
}
if (issues.value.length || saving.value) return;
saving.value = true;
saveState.value = 'saving';
@@ -1724,8 +1784,29 @@ const stopLeaseRenewal = (): void => {
const renewLeaseOnVisibility = (): void => {
if (document.visibilityState === 'visible') void renewEditLease();
};
/** 打开路由指定草稿并恢复冻结的标注上下文。 */
/** 打开路由指定草稿并恢复冻结的标注上下文;XFA 仅恢复元数据与租约,desk 由 XfaWorkbench 加载。 */
const edit = async (profile: ShippingOrderDocumentProfile) => {
const isXfa = isXfaDatasetProfileDefinition(profile.definition)
|| profile.template_mode === 'xfa_dataset';
if (isXfa) {
active.value = profile;
form.profileCode = profile.profile_code;
form.displayName = profile.display_name;
form.schemaId = profile.schema_version_id;
form.changeNote = profile.change_note || '';
xfaDirty.value = false;
try {
await acquireEditLease(profile.id);
saveState.value = 'saved';
} catch (error) {
if (error instanceof BusinessError && error.code === 'SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_CONFLICT') {
saveState.value = 'readonly';
} else {
throw error;
}
}
return;
}
// Suppress document/table watchers until both restored canvas regions and the
// bound sample are ready; otherwise an old preview request can win the race.
restoringProfile = true;
@@ -1899,6 +1980,7 @@ const beforeUnload = (event: BeforeUnloadEvent) => {
const updateCompactEditor = () => { compactEditor.value = window.innerWidth < 768; };
/** 处理不与输入控件冲突的工作台快捷键,让标注、缩放和草稿操作无需离开画布。 */
const handleShortcut = (event: KeyboardEvent) => {
if (isXfaTemplate.value) return;
const target = event.target as HTMLElement | null;
if (target?.matches('input, textarea, select, [contenteditable="true"]'))
return;
@@ -1969,7 +2051,18 @@ const resolveLeave = (allowed: boolean) => {
resolveRouteLeave?.(allowed);
resolveRouteLeave = null;
};
const onXfaSaveStateChange = (state: 'saved' | 'saving' | 'failed' | 'readonly') => {
saveState.value = state;
};
const onXfaProfileSaved = (payload: { lockVersion: number }) => {
if (!active.value) return;
active.value = { ...active.value, lock_version: payload.lockVersion };
profiles.value = profiles.value.map((item) => (
item.id === active.value?.id ? { ...item, lock_version: payload.lockVersion } : item
));
};
onMounted(async () => {
await detectEditorMode();
window.addEventListener("beforeunload", beforeUnload);
window.addEventListener("keydown", handleShortcut);
window.addEventListener("resize", updateCompactEditor);
@@ -2004,24 +2097,34 @@ onBeforeUnmount(() => {
</script>
<template>
<section class="workbench editor-workbench">
<p v-if="editorMode === 'detecting'" class="loading">{{ t('admin.shippingOrderProfiles.xfaWorkbench.loading') }}</p>
<section v-else-if="editorMode === 'error'" class="editor-mode-error" role="alert">
<p>{{ t('admin.shippingOrderProfiles.xfaWorkbench.modeDetectFailed') }}</p>
<button type="button" class="btn-primary" @click="() => void detectEditorMode()">
{{ t('admin.shippingOrderProfiles.xfaWorkbench.retryLoad') }}
</button>
</section>
<section v-else class="workbench editor-workbench">
<header class="bench-header">
<div class="editor-title">
<div>
<h1 class="section-title">{{ `${form.displayName || t("admin.shippingOrderProfiles.title")} · ${t("admin.shippingOrderProfiles.updateDraft")}` }}</h1>
<p>{{ form.profileCode }}</p>
<p>
{{ form.profileCode }}
<span v-if="isXfaTemplate" class="template-mode-badge">{{ t('admin.shippingOrderProfiles.templateModes.xfa_dataset') }}</span>
</p>
</div>
</div>
<div class="header-actions">
<output class="save-status" :class="`save-status--${saveState}`">{{ t(`admin.shippingOrderProfiles.workbench.saveStatus.${saveState}`) }}</output>
<div v-if="saveState === 'readonly'" class="header-actions__lease">
<button type="button" class="btn-secondary" @click="downloadLocalDraft">{{ t('admin.shippingOrderProfiles.workbench.headerExport') }}</button>
<button v-if="!isXfaTemplate" type="button" class="btn-secondary" @click="downloadLocalDraft">{{ t('admin.shippingOrderProfiles.workbench.headerExport') }}</button>
<button type="button" class="btn-secondary" @click="() => void recoverEditLease()">{{ t('admin.shippingOrderProfiles.workbench.headerRecoverLease') }}</button>
<button type="button" class="btn-secondary" @click="() => void recoverEditLease(true)">{{ t('admin.shippingOrderProfiles.workbench.headerTakeOverLease') }}</button>
</div>
<output v-if="active && currentSampleIsTraining" class="training-sample-status">{{ t('admin.shippingOrderProfiles.workbench.headerTrainingSample') }}</output>
<output v-if="active && currentSampleIsTraining && !isXfaTemplate" class="training-sample-status">{{ t('admin.shippingOrderProfiles.workbench.headerTrainingSample') }}</output>
<button
v-else-if="active"
v-else-if="active && !isXfaTemplate"
type="button"
class="btn-secondary"
:disabled="!form.documentId || !form.tableId || saveState === 'readonly'"
@@ -2031,7 +2134,9 @@ onBeforeUnmount(() => {
<button
v-if="active"
type="button"
:disabled="issues.length > 0 || saving || saveState === 'readonly'"
:disabled="isXfaTemplate
? (!xfaDirty || saving || saveState === 'readonly')
: (issues.length > 0 || saving || saveState === 'readonly')"
class="btn-primary"
@click="() => void save()"
>{{ saving ? t("admin.shippingOrderProfiles.saving") : t("admin.shippingOrderProfiles.workbench.headerSaveDraft") }}</button>
@@ -2039,13 +2144,28 @@ onBeforeUnmount(() => {
v-if="active"
type="button"
class="btn-secondary"
:disabled="isXfaTemplate && (xfaDirty || xfaValidateBlocked)"
@click="validateProfile(active)"
>{{ t('admin.shippingOrderProfiles.workbench.headerValidate') }}</button>
<button type="button" class="btn-secondary" @click="router.push({ name: 'AdminShippingOrderDocumentProfiles' })">{{ t('admin.shippingOrderProfiles.workbench.headerReturnToLibrary') }}</button>
</div>
</div>
</header>
<div class="desk editor-desk">
<div class="desk editor-desk" :class="{ 'editor-desk--xfa': isXfaTemplate }">
<OrderProfileXfaWorkbench
v-if="isXfaTemplate && active"
ref="xfaWorkbenchRef"
:profile-id="active.id"
:lease-token="editLeaseToken || ''"
:save-state="saveState"
:editor-session-id="editorSessionId"
@dirty-change="xfaDirty = $event"
@save-state-change="onXfaSaveStateChange"
@save-request="() => void save()"
@profile-saved="onXfaProfileSaved"
@validate-blocked-change="xfaValidateBlocked = $event"
/>
<template v-else-if="!isXfaTemplate">
<main>
<div v-if="canvasUnavailable" class="canvas-warning">
<span>{{
@@ -2333,6 +2453,7 @@ onBeforeUnmount(() => {
</section>
</aside>
</template>
</div>
<DeleteConfirmDialog v-model="leaveConfirmOpen" :message="t('admin.shippingOrderProfiles.workbench.leaveConfirm')" confirm-tone="primary" @update:model-value="(visible: boolean) => { if (!visible) resolveLeave(false); }" @confirm="() => resolveLeave(true)" @cancel="() => resolveLeave(false)" />
</section>
@@ -2361,6 +2482,23 @@ onBeforeUnmount(() => {
color: #64748b;
font-size: 0.82rem;
}
.template-mode-badge {
margin-left: 0.5rem;
color: #0369a1;
font-weight: 700;
}
.editor-desk--xfa {
display: flex;
flex-direction: column;
min-height: calc(100dvh - 120px);
height: calc(100dvh - 120px);
overflow: hidden;
}
.editor-desk--xfa :deep(.xfa-workbench) {
flex: 1 1 auto;
min-height: 0;
height: 100%;
}
.schema-warning,
.schema-hint {
display: block;
@@ -2727,6 +2865,10 @@ onBeforeUnmount(() => {
.save-status--saving { background: #dbeafe; color: #1d4ed8; }.save-status--failed,.save-status--readonly { background: #fee2e2; color: #b91c1c; }.save-status--saved { background: #dcfce7; color: #166534; }
.training-sample-status { background: #dcfce7; color: #166534; }
.editor-workbench { padding: 0; background: #0f172a; }
.editor-mode-error {
display: flex; flex-direction: column; gap: 12px; align-items: flex-start;
margin: 24px; padding: 20px; border: 1px solid #fecaca; border-radius: 0.75rem; background: #fef2f2; color: #991b1b;
}
.editor-workbench .bench-header { max-width: none; padding: .7rem 1rem; color: #e2e8f0; }
.editor-workbench .bench-header p { color: #94a3b8; }
.editor-title { min-width: 0; }
@@ -1,44 +1,13 @@
<!--
features/admin/modules/shipping-order-document-profiles/OrderProfileEditorRoutePage.vue
用途:按 template_mode 路由 Coordinate 编辑器或 XFA 映射工作台。
依赖:Vue Router、Profile 详情 API、OrderProfileEditorPage、XfaProfileMappingPage。
逻辑:加载草稿后鉴别联合;coordinate 保持原编辑器,xfa_dataset 进入映射页。
用途:订单文档模板草稿编辑入口;普通 PDF 与 XFA 统一进入 OrderProfileEditorPage。
依赖:OrderProfileEditorPage。
逻辑:不再按 template_mode 分流至 XfaProfileMappingPage;模式差异由统一编辑器内部处理。
-->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { getOrderDocumentProfileDetail } from '@/features/admin/api/shipping-order-document-profile.api';
import { isXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
import OrderProfileEditorPage from './OrderProfileEditorPage.vue';
import XfaProfileMappingPage from './XfaProfileMappingPage.vue';
const { t } = useI18n();
const route = useRoute();
const message = useMessage();
const ready = ref(false);
const isXfa = ref(false);
/**
* 读取草稿 template_mode 后选择编辑器。
*/
async function prepareEditor(): Promise<void> {
try {
const profileId = Number(route.params.profileId);
const profile = await getOrderDocumentProfileDetail(profileId);
isXfa.value = isXfaDatasetProfileDefinition(profile.definition) || profile.template_mode === 'xfa_dataset';
ready.value = true;
} catch (error) {
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.xfaWorkbench.loadFailed'));
}
}
onMounted(prepareEditor);
</script>
<template>
<XfaProfileMappingPage v-if="ready && isXfa" />
<OrderProfileEditorPage v-else-if="ready" />
<OrderProfileEditorPage />
</template>
@@ -1,8 +1,8 @@
<!--
features/admin/modules/shipping-order-document-profiles/OrderProfileLibraryPage.vue
用途:按 profile_code 聚合展示订单文档模板族,是创建和继续编辑的唯一首页。
依赖:Profile family API、Vue Router、Vue I18n。
逻辑:列表只选择下一步路由;草稿可继续编辑或删除,已发布版本创建新草稿,历史版本进入只读版本中心。
依赖: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';
@@ -11,14 +11,21 @@ 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, listOrderDocumentProfileFamilies } from '@/features/admin/api/shipping-order-document-profile.api';
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({
@@ -30,8 +37,27 @@ const deleteConfirmOpen = computed({
const filteredFamilies = computed(() => {
const keyword = query.value.trim().toLowerCase();
if (!keyword) return families.value;
return families.value.filter((item) => `${item.profile_code} ${item.display_name}`.toLowerCase().includes(keyword));
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 身份决定复制或迁移,列表页不猜测兼容性。 */
@@ -105,6 +131,47 @@ function openSchemaMigration(item: OrderProfileVersionFamilySummary): void {
});
}
/** 打开版本详情中的统一 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>
@@ -122,8 +189,36 @@ onMounted(loadFamilies);
<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>
@@ -134,6 +229,7 @@ onMounted(loadFamilies);
<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>
@@ -151,12 +247,34 @@ onMounted(loadFamilies);
: 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">
<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>
</td>
</tr>
</tbody>
@@ -176,6 +294,18 @@ onMounted(loadFamilies);
.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;
@@ -47,6 +47,30 @@ const gateStatus = computed<'pass' | 'blocked' | 'pending'>(() => {
return report.value.blocking_items.length ? 'blocked' : 'pass';
});
/** XFA 统一验证指标:来自 current_sample 运行 summary(阶段 5–6)。 */
const xfaValidationMetrics = computed<{
visual: number | null;
mirror: number | null;
evidence: number | null;
} | null>(() => {
if (!isXfaReport.value) return null;
const summary = validationRun.value?.summary;
if (!summary || typeof summary !== 'object') return null;
const asRate = (value: unknown): number | null => (
typeof value === 'number' && Number.isFinite(value) ? value : null
);
const visual = asRate(summary.visual_coverage_rate);
const mirror = asRate(summary.mirror_consistency_rate);
const evidence = asRate(summary.evidence_retention_rate);
if (visual == null && mirror == null && evidence == null) return null;
return { visual, mirror, evidence };
});
/** 安全格式化 XFA 指标,避免 template 对 Record 字段推断为 unknown。 */
function formatXfaMetric(value: number | null | undefined): string {
return formatRate(value);
}
/** 显示统一业务错误,避免发布页暴露服务端实现细节。 */
function fail(error: unknown): void {
message.error(error instanceof BusinessError ? error.message : t('admin.orderProfilePublishCheck.failed'));
@@ -140,6 +164,11 @@ function itemMessage(item: Record<string, unknown>): string {
cross_template_margin_insufficient: t('admin.orderProfilePublishCheck.crossTemplateMarginInsufficient'),
sample_role_pollution: t('admin.orderProfilePublishCheck.sampleRolePollution'),
cross_template_conflict_profiles: t('admin.orderProfilePublishCheck.crossTemplateConflictProfiles'),
xfa_visual_bindings_required: t('admin.orderProfilePublishCheck.xfaVisualBindingsRequired'),
xfa_visual_binding_incomplete: t('admin.orderProfilePublishCheck.xfaVisualBindingIncomplete'),
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'));
}
@@ -237,6 +266,15 @@ onMounted(loadRuns);
</dl>
</section>
<section v-if="xfaValidationMetrics" class="card">
<h3>{{ t('admin.orderProfilePublishCheck.xfaUnifiedMetricsTitle') }}</h3>
<dl class="metrics">
<div><dt>{{ t('admin.orderProfilePublishCheck.xfaVisualCoverage') }}</dt><dd>{{ formatXfaMetric(xfaValidationMetrics.visual) }}</dd></div>
<div><dt>{{ t('admin.orderProfilePublishCheck.xfaMirrorConsistency') }}</dt><dd>{{ formatXfaMetric(xfaValidationMetrics.mirror) }}</dd></div>
<div><dt>{{ t('admin.orderProfilePublishCheck.xfaEvidenceRetention') }}</dt><dd>{{ formatXfaMetric(xfaValidationMetrics.evidence) }}</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">
@@ -2,7 +2,7 @@
features/admin/modules/shipping-order-document-profiles/OrderProfileValidationPage.vue
用途:验证当前订单模板草稿,并按“基础验证、盲测、发布检查”顺序引导管理员。
依赖:Profile 验证 API、编辑租约、Vue Router、统一消息提示。
逻辑:一次动作依次执行结构检查和当前样本试读;XFA 从验证摘要展示脱敏字段级结果;
逻辑:一次动作依次执行结构检查和当前样本试读;XFA 从验证摘要展示完整字段级结果;
盲测批准前不解锁发布检查入口。
-->
<script setup lang="ts">
@@ -139,6 +139,19 @@ const xfaCrossCheckEntries = computed(() => {
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>;
return `#${String(failure.row_index || '-')}: ${String(failure.quantity ?? '-')} × ${String(failure.unit_price ?? '-')} ÷ ${String(failure.price_unit ?? '1')} = ${String(failure.expected_amount ?? '?')},amount=${String(failure.amount ?? '-')}`;
}).join(';');
}
return { key, label, statusLabel, detail, status };
});
});
@@ -344,8 +357,6 @@ onMounted(async () => {
<template v-if="isXfa">
<dl class="header-results">
<div><dt>{{ t('admin.orderProfileValidation.xfaTemplateMode') }}</dt><dd>XFA</dd></div>
<div><dt>{{ t('admin.orderProfileValidation.xfaRequiredMissing') }}</dt><dd>{{ xfaSummary?.header_required_missing_count ?? '-' }}</dd></div>
<div><dt>{{ t('admin.orderProfileValidation.xfaAutoCreateMissing') }}</dt><dd>{{ xfaSummary?.auto_create_key_missing_count ?? '-' }}</dd></div>
<div><dt>{{ t('admin.orderProfileValidation.xfaLineRows') }}</dt><dd>{{ xfaSummary?.line_row_count ?? '-' }}</dd></div>
<div><dt>{{ t('admin.orderProfileValidation.xfaCrossChecks') }}</dt><dd>{{ Array.isArray(xfaSummary?.cross_check_failures) && xfaSummary.cross_check_failures.length ? xfaSummary.cross_check_failures.join(', ') : t('admin.orderProfileValidation.xfaCrossChecksPassed') }}</dd></div>
</dl>
@@ -372,7 +383,7 @@ onMounted(async () => {
>
<dt>{{ fieldName(String(field.field_code || '')) }}</dt>
<dd class="field-code">{{ field.field_code }}</dd>
<dd>{{ t('admin.orderProfileValidation.xfaMaskedRaw') }}:{{ field.masked_raw_value || t('admin.orderProfileValidation.noValue') }}</dd>
<dd>{{ t('admin.orderProfileValidation.xfaRawValue') }}:{{ field.raw_value || t('admin.orderProfileValidation.noValue') }}</dd>
<dd>{{ t('admin.orderProfileValidation.xfaNormalized') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</dd>
</div>
</dl>
@@ -390,7 +401,7 @@ onMounted(async () => {
>
<dt>{{ fieldName(String(field.field_code || '')) }}</dt>
<dd class="field-code">{{ field.field_code }}</dd>
<dd>{{ t('admin.orderProfileValidation.xfaMaskedRaw') }}:{{ field.masked_raw_value || t('admin.orderProfileValidation.noValue') }}</dd>
<dd>{{ t('admin.orderProfileValidation.xfaRawValue') }}:{{ field.raw_value || t('admin.orderProfileValidation.noValue') }}</dd>
<dd>{{ t('admin.orderProfileValidation.xfaNormalized') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</dd>
</div>
</dl>
@@ -1,9 +1,10 @@
<!--
features/admin/modules/shipping-order-document-profiles/OrderProfileVersionDetailPage.vue
用途:订单模板版本中心详情页,支持刷新恢复与分享。
依赖:版本详情 composable、配置概览组件、版本中心 API。
依赖:版本详情 composable、配置概览组件、版本中心 API、统一迁移 API。
逻辑:当前已接入配置概览、只读样本画布、服务端语义 diff、审计时间线与实际使用;
Schema 迁移弹窗按模态语义提供初始焦点、Tab 陷阱、Escape 关闭与焦点恢复。
Schema 迁移弹窗按模态语义提供初始焦点、Tab 陷阱、Escape 关闭与焦点恢复;
统一 binding 迁移提供 Dry Run 状态徽章入口。
-->
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
@@ -13,6 +14,8 @@ 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";
@@ -33,6 +36,13 @@ 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 }>>({});
@@ -302,6 +312,51 @@ const createNewVersion = async () => {
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>
@@ -346,6 +401,31 @@ const createNewVersion = async () => {
>
{{ 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>
@@ -503,7 +583,18 @@ const createNewVersion = async () => {
.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; }
.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 {
@@ -1,13 +1,12 @@
/**
* features/admin/modules/shipping-order-document-profiles/XfaProfileMappingPage.spec.ts
* 用途:挂载 XFA 映射页并验证四栏布局加载。
* 依赖:Vitest、@vue/test-utils、XfaProfileMappingPage。
* features/admin/modules/shipping-order-document-profiles/OrderProfileXfaWorkbench.spec.ts
* 用途:挂载统一编辑器 desk 内 XFA 片段并验证布局与诊断抽屉(无独立 Header)。
* 依赖:Vitest、@vue/test-utils、OrderProfileXfaWorkbench。
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { mount, flushPromises } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import XfaProfileMappingPage from './XfaProfileMappingPage.vue';
import XfaSplitRulePanel from './components/XfaSplitRulePanel.vue';
import OrderProfileXfaWorkbench from './OrderProfileXfaWorkbench.vue';
const { saveDraftMock, splitPreviewMock, detailDefinition } = vi.hoisted(() => ({
saveDraftMock: vi.fn(),
@@ -15,6 +14,13 @@ const { saveDraftMock, splitPreviewMock, detailDefinition } = vi.hoisted(() => (
detailDefinition: { value: null as Record<string, unknown> | null },
}));
const defaultProps = {
profileId: 52,
leaseToken: 'lease',
saveState: 'saved' as const,
editorSessionId: 'editor-session',
};
const baseDefinition = {
template_mode: 'xfa_dataset' as const,
source_contract: {
@@ -38,7 +44,6 @@ const baseDefinition = {
vi.mock('vue-router', () => ({
useRoute: () => ({ params: { profileId: '52', profileCode: 'ODP-TEST' }, query: {} }),
useRouter: () => ({ push: vi.fn() }),
onBeforeRouteLeave: vi.fn(),
}));
vi.mock('@/shared/composables/useMessage', () => ({
@@ -77,6 +82,13 @@ vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
getOrderProfileSampleXfaCollections: vi.fn(async () => ({
collection_candidates: [{ path_id: 'items-data', collection_path_hash: 'h', row_count: 1 }],
})),
authorizeOrderProfilePreviewPages: vi.fn(async () => ({
document_id: 85,
page_count: 1,
pages: [{ page_no: 1, preview_token: 'token' }],
expires_in_seconds: 60,
})),
suggestOrderProfileXfaUnifiedMapping: vi.fn(),
acquireOrderDocumentProfileEditLease: vi.fn(async () => ({ lease_token: 'lease', expires_at: new Date().toISOString() })),
renewOrderDocumentProfileEditLease: vi.fn(),
releaseOrderDocumentProfileEditLease: vi.fn(),
@@ -111,33 +123,13 @@ vi.mock('@/features/admin/api/shipping-order-schema.api', () => ({
})),
}));
vi.mock('@/features/auth/stores/auth.store', () => ({
useAuthStore: () => ({
user: {
feature_permissions: {
'shipping_notice.xfa_split_rule_edit': true,
'shipping_notice.xfa_split_rule_preview': true,
'shipping_notice.audit_sensitive_read': true,
},
},
}),
}));
vi.mock('pinia', async () => {
const actual = await vi.importActual<typeof import('pinia')>('pinia');
return {
...actual,
storeToRefs: (store: { user: unknown }) => ({ user: { value: store.user } }),
};
});
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
fallbackLocale: 'zh-CN',
messages: {
'zh-CN': {
common: { yes: '是', no: '否' },
common: { yes: '是', no: '否', close: '关闭' },
admin: {
shippingOrderProfiles: {
templateModes: { xfa_dataset: 'XFA' },
@@ -149,6 +141,23 @@ const i18n = createI18n({
headerTakeOverLease: '接管',
saveStatus: { saved: '已保存', saving: '保存中', failed: '失败', readonly: '只读' },
leaveConfirm: '离开?',
annotationCanvasAriaLabel: '画布',
loadingPage: '加载',
selectBoundPdf: '选择 PDF',
zoomIn: '+', zoomOut: '-', fitPage: '适合',
pageNavigation: '页',
},
xfaUnified: {
drawFieldBox: '画框',
suggesting: '分析中',
openDiagnostics: '高级诊断',
diagnosticsDrawerTitle: '诊断',
diagnosticsSummary: '{mapped}/{total}',
candidatePanelTitle: '候选',
acceptCandidate: '采用',
confirmVisual: '确认',
rejectVisual: '驳回',
visualStatus: { suggested: '建议', confirmed: '已确认', rejected: '已驳回', needs_review: '待复核' },
},
xfaWorkbench: {
loading: '加载', loadFailed: '失败', saved: '已保存', saveFailed: '失败', scopeMismatch: 'scope',
@@ -169,125 +178,80 @@ const i18n = createI18n({
collectionsTitle: '集合', authoritativeCollection: '权威', selectAuthoritative: '选择',
mirrorCollections: '镜像', rowCount: '{count} 行',
},
xfaUnified: {
drawFieldBox: '画字段框', suggesting: '匹配中', suggestFailed: '建议失败',
candidatePanelTitle: '候选', acceptCandidate: '采用',
confirmVisual: '确认', rejectVisual: '驳回',
confirmSuccess: '确认成功', confirmFailed: '确认失败',
rejectSuccess: '驳回成功', rejectFailed: '驳回失败',
diagnosticsSummary: '{mapped}/{total}', openDiagnostics: '高级诊断',
diagnosticsDrawerTitle: '诊断',
visualStatus: { suggested: '建议', confirmed: '已确认', rejected: '已驳回', needs_review: '待复核' },
},
xfaSplit: {
title: '拆分', addRule: '新增', deleteConfirm: '删除?', deleteRule: '删', ruleLabel: '规则 {index}', unnamedRule: '未命名',
},
},
},
},
},
});
describe('XfaProfileMappingPage', () => {
describe('OrderProfileXfaWorkbench', () => {
beforeEach(() => {
saveDraftMock.mockReset();
splitPreviewMock.mockReset();
detailDefinition.value = null;
vi.stubGlobal('fetch', vi.fn(async () => ({
ok: true,
blob: async () => new Blob([new Uint8Array([137, 80, 78, 71])], { type: 'image/png' }),
})));
vi.stubGlobal('URL', {
...URL,
createObjectURL: vi.fn(() => 'blob:mock-page'),
revokeObjectURL: vi.fn(),
});
});
const mountPage = async () => {
const wrapper = mount(XfaProfileMappingPage, { global: { plugins: [i18n] } });
for (let i = 0; i < 5; i += 1) {
const wrapper = mount(OrderProfileXfaWorkbench, {
props: defaultProps,
global: { plugins: [i18n] },
});
for (let i = 0; i < 20; i += 1) {
await flushPromises();
await new Promise((resolve) => setTimeout(resolve, 0));
if (wrapper.find('.xfa-workbench__grid').exists()) break;
if (wrapper.find('.xfa-workbench__desk').exists()) break;
}
return wrapper;
};
it('mounts four-column grid after bootstrap', async () => {
it('mounts canvas-first desk after bootstrap without standalone header', async () => {
const wrapper = await mountPage();
expect(wrapper.find('.xfa-workbench__grid').exists()).toBe(true);
expect(wrapper.find('.xfa-tree').exists()).toBe(true);
expect(wrapper.find('.xfa-schema__filters').text()).not.toContain('必填');
expect(wrapper.find('.xfa-workbench__desk').exists()).toBe(true);
expect(wrapper.find('.xfa-workbench__header').exists()).toBe(false);
expect(wrapper.find('.xfa-workbench__canvas').exists()).toBe(true);
expect(wrapper.find('.canvas-shell').exists()).toBe(true);
expect(wrapper.find('.xfa-tree').exists()).toBe(false);
await wrapper.find('[data-xfa-path-id="material-path"] .add-rule').trigger('click');
await wrapper.find('.xfa-workbench__diagnostics-trigger button').trigger('click');
await flushPromises();
expect(wrapper.find('.xfa-rule-dialog').exists()).toBe(true);
expect(wrapper.find('.diagnostics-drawer').exists()).toBe(true);
expect(wrapper.find('.diagnostics-drawer .xfa-tree').exists()).toBe(true);
expect(wrapper.find('.diagnostics-drawer .add-rule').exists()).toBe(false);
}, 15000);
it('opens readonly diagnostics drawer from panel footer', async () => {
const wrapper = await mountPage();
expect(wrapper.find('.xfa-workbench__panel').exists()).toBe(true);
await wrapper.find('.xfa-workbench__diagnostics-trigger button').trigger('click');
await flushPromises();
expect(wrapper.find('.diagnostics-drawer').exists()).toBe(true);
expect(wrapper.find('.diagnostics-drawer .add-rule').exists()).toBe(false);
});
it('persists confirmed rules and renders them below the source tree node', async () => {
saveDraftMock.mockResolvedValueOnce({
id: 52, profile_code: 'ODP-TEST', display_name: 'Fox PO', schema_version_id: 1, lock_version: 2,
template_mode: 'xfa_dataset',
definition: {
...structuredClone(baseDefinition),
split_rules: [{
rule_id: 'ruleset-1', rule_version: 1, source_path_id: 'material-path', source_field_code: 'MATNR',
strategy: 'pipeline', status: 'confirmed', requires_confirmation: false, source: 'user',
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: 'mapped', target_field_id: 'f1', target_field_code: 'customer_po_no' },
}],
}],
},
});
splitPreviewMock.mockResolvedValueOnce({
preview: {
segments: [{ rule_id: 'rule-1', normalized_text: 'TEMP••922', raw_text: 'TEMP-922' }],
},
});
it('emits dirty-change when local definition diverges from saved snapshot', async () => {
const wrapper = await mountPage();
await wrapper.find('[data-xfa-path-id="material-path"] .add-rule').trigger('click');
await flushPromises();
const rules = [{
rule_id: 'ruleset-1', rule_version: 1, source_path_id: 'material-path', source_field_code: 'MATNR',
strategy: 'pipeline' as const, status: 'confirmed' as const, requires_confirmation: false, source: 'user' as const,
rules: [{
rule_id: 'rule-1', order: 1,
stages: [{ stage_id: 'stage-1', type: 'select_line' as const, line_index: 1 }],
segment: { segment_id: 'seg-1', segment_code: 'customer_part', display_name: '客户料号', handling: 'mapped' as const, target_field_id: 'f1', target_field_code: 'customer_po_no' },
}],
}];
wrapper.findComponent(XfaSplitRulePanel).vm.$emit('confirmed', rules);
await flushPromises();
expect(saveDraftMock).toHaveBeenCalledWith(52, expect.objectContaining({
definition: expect.objectContaining({ split_rules: rules }),
}));
expect(wrapper.find('[data-xfa-path-id="material-path"] + .xfa-tree__rules').text()).toContain('客户料号');
expect(wrapper.find('.xfa-schema').text()).toContain('TEMP••922');
expect(wrapper.findAll('.field__value').map((item) => item.text())).not.toContain('TEMP-S');
expect(wrapper.find('.xfa-rule-dialog').exists()).toBe(false);
});
it('keeps the rule dialog open when confirmed rules fail to save', async () => {
saveDraftMock.mockRejectedValueOnce(new Error('save failed'));
const wrapper = await mountPage();
await wrapper.find('[data-xfa-path-id="material-path"] .add-rule').trigger('click');
await flushPromises();
const rules = [{
rule_id: 'ruleset-1', rule_version: 1, source_path_id: 'material-path', source_field_code: 'MATNR',
strategy: 'pipeline' as const, status: 'confirmed' as const, requires_confirmation: false,
rules: [],
}];
wrapper.findComponent(XfaSplitRulePanel).vm.$emit('confirmed', rules);
await flushPromises();
expect(wrapper.find('.xfa-rule-dialog').exists()).toBe(true);
});
it('allows a header source split rule to map a header field only', async () => {
detailDefinition.value = {
...structuredClone(baseDefinition),
split_rules: [{
rule_id: 'header-rules', rule_version: 1, source_path_id: 'invoiced-to-path', source_field_code: 'INVOICED_TO',
strategy: 'pipeline', status: 'confirmed', requires_confirmation: false, source: 'user',
rules: [{
rule_id: 'bill-rule', order: 1,
stages: [{ stage_id: 'stage-1', type: 'select_line', line_index: 1 }],
segment: { segment_id: 'seg-bill', segment_code: 'bill_customer', display_name: '账款客户', handling: 'evidence_only' },
}],
}],
};
const wrapper = await mountPage();
await wrapper.find('[data-xfa-path-id="invoiced-to-path"] + .xfa-tree__rules .xfa-tree__rule-main').trigger('click');
await flushPromises();
const billButton = wrapper.findAll('button.field').find((item) => item.text().includes('bill_to_customer'));
const lineButton = wrapper.findAll('button.field').find((item) => item.text().includes('part_number'));
expect(billButton?.attributes('disabled')).toBeUndefined();
expect(lineButton?.attributes('disabled')).toBeDefined();
await billButton?.trigger('click');
expect((wrapper.vm as unknown as { definition: typeof baseDefinition }).definition.split_rules?.[0].rules[0].segment)
.toMatchObject({ handling: 'mapped', target_field_id: 'f-bill', target_field_code: 'bill_to_customer' });
expect(wrapper.emitted('dirty-change')?.[0]).toEqual([false]);
});
});
@@ -1,748 +0,0 @@
<!--
features/admin/modules/shipping-order-document-profiles/XfaProfileMappingPage.vue
用途:XFA 四栏映射工作台(数据树 / 拆分规则 / Schema / 预览),复用 Lease/Revision/operation_id。
依赖:Profile/XFA API、Schema API、Xfa* 组件、xfaProfileMapping.utils。
逻辑:加载草稿与样本树;权威集合必选后可保存;租约 409 进入只读;脏状态离开确认。
-->
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { getShippingOrderSchemaState } from '@/features/admin/api/shipping-order-schema.api';
import {
acquireOrderDocumentProfileEditLease,
getOrderDocumentProfileDetail,
getOrderProfileSampleXfaCollections,
getOrderProfileSampleXfaFieldTree,
previewOrderProfileSampleXfaSplitRules,
previewOrderProfileSampleXfaValue,
listOrderProfileBoundSamples,
releaseOrderDocumentProfileEditLease,
renewOrderDocumentProfileEditLease,
saveOrderDocumentProfileDraft,
} from '@/features/admin/api/shipping-order-document-profile.api';
import type {
OrderXfaDatasetProfileDefinition,
XfaCollectionCandidate,
XfaFieldTreeNode,
} from '@/features/admin/types/shipping-order-document-profile.types';
import { isXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
import type { ShippingOrderFieldConfig } from '@/features/admin/types/shipping-order-schema.types';
import XfaDatasetTree from './components/XfaDatasetTree.vue';
import XfaSchemaMappingPanel from './components/XfaSchemaMappingPanel.vue';
import XfaSplitRulePanel from './components/XfaSplitRulePanel.vue';
import {
bindXfaSchemaField,
buildXfaPathLabel,
computeXfaMappingCoverage,
flattenXfaTreeNodes,
isSameXfaDefinition,
resolveAuthoritativePathId,
resolveMirrorPathIds,
resolveXfaNodeScope,
summarizeXfaMappingBlockers,
unbindXfaSchemaField,
} from './xfaProfileMapping.utils';
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const message = useMessage();
const profileId = computed(() => Number(route.params.profileId));
const editorSessionId = String(route.query.editorSessionId || crypto.randomUUID());
const loading = ref(true);
const loadError = ref(false);
const saving = ref(false);
const saveState = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
const editLeaseToken = ref('');
const lockVersion = ref(0);
const schemaFields = ref<ShippingOrderFieldConfig[]>([]);
const definition = ref<OrderXfaDatasetProfileDefinition | null>(null);
const savedSnapshot = ref<OrderXfaDatasetProfileDefinition | null>(null);
const tree = ref<XfaFieldTreeNode | null>(null);
const collections = ref<XfaCollectionCandidate[]>([]);
const excludedCollections = ref<XfaCollectionCandidate[]>([]);
const annotationDocumentId = ref(0);
const selectedPathId = ref<string | null>(null);
const selectedPathIsLeaf = ref(false);
const selectedRuleId = ref<string | null>(null);
const splitRuleDialogOpen = ref(false);
const splitRuleDialogAutoAdd = ref(false);
const splitRulePanel = ref<{ addRule: () => void; runPreview: () => void; confirmRules: () => void } | null>(null);
const dialogDefinition = ref<OrderXfaDatasetProfileDefinition | null>(null);
const revealedValues = ref<Record<string, string>>({});
const splitRulePreviewValues = ref<Record<string, string>>({});
const revealingPathId = ref('');
const revealTimers = new Map<string, ReturnType<typeof setTimeout>>();
const authoritativePathId = ref('');
const mirrorPathIds = ref<string[]>([]);
const displayName = ref('');
const profileCode = ref('');
const schemaVersionId = ref(0);
let renewTimer: ReturnType<typeof setInterval> | null = null;
const flatNodes = computed(() => flattenXfaTreeNodes(tree.value));
const selectedPathLabel = computed(() => (
selectedPathId.value ? buildXfaPathLabel(selectedPathId.value, flatNodes.value) : ''
));
const selectedFieldCode = computed(() => {
if (!selectedPathId.value) return '';
return flatNodes.value.find((item) => item.pathId === selectedPathId.value)?.localName || '';
});
const selectedIsMultiline = computed(() => {
if (!selectedPathId.value) return false;
const node = flatNodes.value.find((item) => item.pathId === selectedPathId.value);
return (node?.lineCount || 0) > 1;
});
const selectedSourceScope = computed(() => (
selectedPathId.value
? resolveXfaNodeScope(selectedPathId.value, authoritativePathId.value, flatNodes.value)
: null
));
const canEditSplitRules = computed(() => saveState.value !== 'readonly');
const canPreviewSplitRules = computed(() => true);
const canRevealSensitiveSplit = computed(() => true);
const splitRulePersistedConfirmed = computed(() => {
const pathId = selectedPathId.value;
if (!pathId || !definition.value || !savedSnapshot.value) return true;
const current = (definition.value.split_rules || []).find((item) => item.source_path_id === pathId);
if (!current || current.status !== 'confirmed') return true;
const saved = (savedSnapshot.value.split_rules || []).find((item) => item.source_path_id === pathId);
return !!saved && JSON.stringify(current) === JSON.stringify(saved);
});
const mappedFieldPreviews = computed(() => {
if (!definition.value) return { header: [], line: [] };
const byPath = new Map(flatNodes.value.map((item) => [item.pathId, item]));
const mapItems = (items: Array<{ mapping_id: string; field_code: string; path_id: string }>) =>
items.map((item) => ({
mappingId: item.mapping_id,
fieldCode: item.field_code,
pathId: item.path_id,
pathLabel: byPath.get(item.path_id)
? buildXfaPathLabel(item.path_id, flatNodes.value)
: item.path_id,
maskedValue: revealedValues.value[item.path_id] || byPath.get(item.path_id)?.sampleValueDisplay || null,
}));
const splitItems = (definition.value.split_rules || []).flatMap((ruleSet) =>
[...ruleSet.rules]
.sort((a, b) => a.order - b.order)
.filter((rule) => rule.segment.handling === 'mapped' && rule.segment.target_field_code)
.map((rule, index) => ({
mappingId: rule.segment.segment_id,
fieldCode: String(rule.segment.target_field_code),
pathId: ruleSet.source_path_id,
pathLabel: `${buildXfaPathLabel(ruleSet.source_path_id, flatNodes.value)} / ${t('admin.shippingOrderProfiles.xfaSplit.ruleLabel', { index: index + 1 })} · ${rule.segment.display_name || rule.segment.segment_code}`,
maskedValue: splitRulePreviewValues.value[rule.rule_id] || null,
})),
);
const splitItemsByScope = splitItems.reduce((groups, item) => {
const scope = resolveXfaNodeScope(item.pathId, authoritativePathId.value, flatNodes.value);
if (scope) groups[scope].push(item);
return groups;
}, { header: [] as typeof splitItems, line: [] as typeof splitItems });
return {
header: [...mapItems(definition.value.header_mappings || []), ...splitItemsByScope.header],
line: [...mapItems(definition.value.line_mapping?.fields || []), ...splitItemsByScope.line],
};
});
const dirty = computed(() => !isSameXfaDefinition(definition.value, savedSnapshot.value)
|| Boolean(authoritativePathId.value && definition.value
&& authoritativePathId.value !== savedAuthoritativePathId.value)
|| JSON.stringify([...mirrorPathIds.value].sort()) !== JSON.stringify([...savedMirrorPathIds.value].sort()));
const savedAuthoritativePathId = ref('');
const savedMirrorPathIds = ref<string[]>([]);
/**
* 将 XFA JSON 契约数据复制为不含 Vue Proxy 的普通对象。
* 核心逻辑:定义和规则契约只包含可序列化字段;JSON 快照可安全跨越组件事件与保存 payload。
* @param value 当前响应式或普通 JSON 契约数据
* @returns 可独立编辑和持久化的纯对象副本
*/
function cloneXfaData<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T;
}
const coverage = computed(() => computeXfaMappingCoverage(
schemaFields.value,
definition.value || undefined,
authoritativePathId.value,
));
const blockers = computed(() => summarizeXfaMappingBlockers(coverage.value));
const mappedPathIds = computed(() => {
if (!definition.value) return [];
return [
...definition.value.header_mappings.map((item) => item.path_id),
...definition.value.line_mapping.fields.map((item) => item.path_id),
];
});
const splitRuleSets = computed(() => definition.value?.split_rules || []);
const dialogHasRules = computed(() => Boolean(
selectedPathId.value
&& dialogDefinition.value?.split_rules?.find((item) => item.source_path_id === selectedPathId.value)?.rules.length,
));
/**
* 获取或恢复编辑租约。
*/
async function acquireLease(confirmTakeover = false): Promise<void> {
try {
const lease = await acquireOrderDocumentProfileEditLease(profileId.value, {
browser_session_id: editorSessionId,
operation_id: crypto.randomUUID(),
confirm_takeover: confirmTakeover,
});
editLeaseToken.value = lease.lease_token;
saveState.value = 'saved';
} catch (error) {
if (error instanceof BusinessError && String(error.code || '').includes('LEASE')) {
saveState.value = 'readonly';
return;
}
throw error;
}
}
/**
* 从已保存 definition 恢复权威/镜像集合选择(按路径哈希精确匹配)。
*/
async function restoreCollectionSelection(def: OrderXfaDatasetProfileDefinition): Promise<void> {
const flat = flattenXfaTreeNodes(tree.value);
const restoredAuth = await resolveAuthoritativePathId(def, collections.value, flat);
authoritativePathId.value = restoredAuth;
savedAuthoritativePathId.value = restoredAuth;
const restoredMirrors = await resolveMirrorPathIds(def, collections.value, restoredAuth);
mirrorPathIds.value = restoredMirrors;
savedMirrorPathIds.value = [...restoredMirrors];
}
/**
* 加载 Profile、Schema、XFA 树与集合,并恢复已保存权威/镜像选择。
*/
async function load(): Promise<void> {
loading.value = true;
loadError.value = false;
try {
const [profile, schemaState, samples] = await Promise.all([
getOrderDocumentProfileDetail(profileId.value),
getShippingOrderSchemaState(),
listOrderProfileBoundSamples(profileId.value),
]);
if (!isXfaDatasetProfileDefinition(profile.definition)) {
throw new Error('not_xfa');
}
definition.value = structuredClone(profile.definition);
savedSnapshot.value = structuredClone(profile.definition);
lockVersion.value = profile.lock_version;
displayName.value = profile.display_name;
profileCode.value = profile.profile_code;
schemaVersionId.value = profile.schema_version_id;
const schema = (schemaState.versions || []).find((item) => item.id === profile.schema_version_id);
schemaFields.value = (schema?.definition?.fields || []) as ShippingOrderFieldConfig[];
const annotation = samples.find((item) => item.sample_role === 'annotation') || samples[0];
annotationDocumentId.value = annotation?.document_id || 0;
if (!annotationDocumentId.value) throw new Error('missing_sample');
const [treeRes, collRes] = await Promise.all([
getOrderProfileSampleXfaFieldTree(annotationDocumentId.value),
getOrderProfileSampleXfaCollections(annotationDocumentId.value),
]);
tree.value = (treeRes.tree && 'path_id' in treeRes.tree) ? treeRes.tree as XfaFieldTreeNode : null;
collections.value = collRes.collection_candidates || [];
excludedCollections.value = collRes.excluded_collection_candidates || [];
await restoreCollectionSelection(profile.definition);
await refreshSplitRulePreviews(profile.definition.split_rules || []);
await acquireLease(false);
startRenewal();
} catch (error) {
loadError.value = true;
definition.value = null;
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.xfaWorkbench.loadFailed'));
} finally {
loading.value = false;
}
}
/**
* 执行各字段拆分规则并按 rule_id 缓存脱敏结果。
* 核心逻辑:规则预览失败时保持空值,禁止回退到源字段整段内容造成错误映射认知。
* @param ruleSets 当前已保存或待展示的规则集合
*/
async function refreshSplitRulePreviews(
ruleSets: import('@/features/admin/types/shipping-order-document-profile.types').XfaSplitRuleSet[],
): Promise<void> {
if (!annotationDocumentId.value) {
splitRulePreviewValues.value = {};
return;
}
const next: Record<string, string> = {};
await Promise.allSettled(ruleSets.map(async (ruleSet) => {
if (!ruleSet.rules?.length) return;
const response = await previewOrderProfileSampleXfaSplitRules(annotationDocumentId.value, {
path_id: ruleSet.source_path_id,
rule_set: ruleSet as unknown as Record<string, unknown>,
profile_id: profileId.value,
reveal: false,
});
for (const segment of response.preview?.segments || []) {
const value = String(segment.normalized_text || segment.raw_text || '').trim();
if (segment.rule_id && value) next[segment.rule_id] = value;
}
}));
splitRulePreviewValues.value = next;
}
/**
* 绑定选中叶子或规则结果到同作用域 Schema 字段。
* 规则继承源节点作用域,避免 Header 源规则被错误限制为明细字段。
*/
function onBindField(field: ShippingOrderFieldConfig, scope: 'header' | 'line'): void {
if (!definition.value || !selectedPathId.value) return;
if (selectedRuleId.value) {
if (!selectedSourceScope.value || scope !== selectedSourceScope.value) {
message.error(t('admin.shippingOrderProfiles.xfaWorkbench.scopeMismatch'));
return;
}
const selectedId = selectedRuleId.value;
const nextDefinition = unbindXfaSchemaField(definition.value, field.field_id);
definition.value = {
...nextDefinition,
split_rules: (nextDefinition.split_rules || []).map((ruleSet) => ({
...ruleSet,
rules: ruleSet.rules.map((rule) => {
const segment = rule.segment;
if (rule.rule_id === selectedId) {
return {
...rule,
segment: {
...segment,
handling: 'mapped',
target_field_id: field.field_id,
target_field_code: field.field_code,
},
};
}
if (segment.target_field_id === field.field_id) {
return {
...rule,
segment: { ...segment, handling: 'evidence_only', target_field_id: null, target_field_code: null },
};
}
return rule;
}),
})),
};
return;
}
const current = [
...(definition.value.header_mappings || []),
...(definition.value.line_mapping?.fields || []),
].find((item) => item.field_id === field.field_id);
if (current && current.path_id !== selectedPathId.value) {
const oldLabel = buildXfaPathLabel(current.path_id, flatNodes.value) || current.path_id;
const newLabel = buildXfaPathLabel(selectedPathId.value, flatNodes.value) || selectedPathId.value;
if (!window.confirm(t('admin.shippingOrderProfiles.xfaWorkbench.replaceConfirm', { old: oldLabel, next: newLabel }))) return;
}
try {
const definitionWithoutSplitTarget = {
...definition.value,
split_rules: (definition.value.split_rules || []).map((ruleSet) => ({
...ruleSet,
rules: ruleSet.rules.map((rule) => rule.segment.target_field_id === field.field_id
? { ...rule, segment: { ...rule.segment, handling: 'evidence_only' as const, target_field_id: null, target_field_code: null } }
: rule),
})),
};
definition.value = bindXfaSchemaField({
definition: definitionWithoutSplitTarget,
scope,
field,
pathId: selectedPathId.value,
});
} catch {
message.error(t('admin.shippingOrderProfiles.xfaWorkbench.scopeMismatch'));
}
}
/**
* 按管理员敏感读权限临时查看当前字段完整值。
* 核心逻辑:只保存在当前页面内存;后端对每次读取写入敏感审计与加密快照。
*/
async function revealSelectedValue(): Promise<void> {
if (!selectedPathId.value || !annotationDocumentId.value) return;
const pathId = selectedPathId.value;
revealingPathId.value = pathId;
try {
const result = await previewOrderProfileSampleXfaValue(annotationDocumentId.value, pathId, true);
const previousTimer = revealTimers.get(pathId);
if (previousTimer) clearTimeout(previousTimer);
revealedValues.value = { ...revealedValues.value, [pathId]: result.display_value };
revealTimers.set(pathId, setTimeout(() => {
const next = { ...revealedValues.value };
delete next[pathId];
revealedValues.value = next;
revealTimers.delete(pathId);
}, 60_000));
} catch (error) {
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.xfaWorkbench.revealFailed'));
} finally {
revealingPathId.value = '';
}
}
/**
* 解除字段映射。
*/
function onUnbindField(fieldId: string): void {
if (!definition.value) return;
const next = unbindXfaSchemaField(definition.value, fieldId);
definition.value = {
...next,
split_rules: (next.split_rules || []).map((ruleSet) => ({
...ruleSet,
rules: ruleSet.rules.map((rule) => rule.segment.target_field_id === fieldId
? { ...rule, segment: { ...rule.segment, handling: 'evidence_only', target_field_id: null, target_field_code: null } }
: rule),
})),
};
}
/**
* 保存映射:要求权威集合;Lease/lock_version/operation_id 复用坐标治理。
*/
async function save(): Promise<boolean> {
if (!definition.value || saveState.value === 'readonly') return false;
if (!authoritativePathId.value) {
message.error(t('admin.shippingOrderProfiles.xfaWorkbench.blocker.authoritative_collection_required'));
return false;
}
saving.value = true;
saveState.value = 'saving';
try {
const payloadDefinition: OrderXfaDatasetProfileDefinition & Record<string, unknown> = {
...definition.value,
authoritative_collection_path_id: authoritativePathId.value,
mirror_collection_path_ids: mirrorPathIds.value,
};
const saved = await saveOrderDocumentProfileDraft(profileId.value, {
profile_code: profileCode.value,
display_name: displayName.value,
schema_version_id: schemaVersionId.value,
expected_lock_version: lockVersion.value,
definition: payloadDefinition as OrderXfaDatasetProfileDefinition,
browser_session_id: editorSessionId,
lease_token: editLeaseToken.value,
operation_id: crypto.randomUUID(),
});
if (!isXfaDatasetProfileDefinition(saved.definition)) throw new Error('bad_mode');
definition.value = structuredClone(saved.definition);
savedSnapshot.value = structuredClone(saved.definition);
lockVersion.value = saved.lock_version;
await restoreCollectionSelection(saved.definition);
await refreshSplitRulePreviews(saved.definition.split_rules || []);
saveState.value = 'saved';
message.success(t('admin.shippingOrderProfiles.xfaWorkbench.saved'));
return true;
} catch (error) {
if (error instanceof BusinessError && (
String(error.code || '').includes('LEASE')
|| String(error.code || '').includes('VERSION_CONFLICT')
)) {
saveState.value = 'readonly';
message.error(error.message);
return false;
}
saveState.value = 'failed';
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.xfaWorkbench.saveFailed'));
return false;
} finally {
saving.value = false;
}
}
function startRenewal(): void {
stopRenewal();
renewTimer = setInterval(async () => {
if (!editLeaseToken.value || saveState.value === 'readonly') return;
try {
await renewOrderDocumentProfileEditLease(profileId.value, {
browser_session_id: editorSessionId,
lease_token: editLeaseToken.value,
operation_id: crypto.randomUUID(),
});
} catch (error) {
if (error instanceof BusinessError && String(error.code || '').includes('LEASE')) {
saveState.value = 'readonly';
}
}
}, 90_000);
}
function stopRenewal(): void {
if (renewTimer) clearInterval(renewTimer);
renewTimer = null;
}
onBeforeRouteLeave(async () => {
if (!dirty.value) return true;
return window.confirm(t('admin.shippingOrderProfiles.workbench.leaveConfirm'));
});
/**
* 更新 definition.split_rules 并标记脏状态。
*/
function onSplitRulesUpdate(rules: import('@/features/admin/types/shipping-order-document-profile.types').XfaSplitRuleSet[]): void {
if (!definition.value) return;
definition.value = { ...definition.value, split_rules: rules };
}
/**
* 弹窗内只更新临时 definition;关闭弹窗不会污染页面草稿。
*/
function onDialogSplitRulesUpdate(
rules: import('@/features/admin/types/shipping-order-document-profile.types').XfaSplitRuleSet[],
): void {
if (!dialogDefinition.value) return;
dialogDefinition.value = { ...dialogDefinition.value, split_rules: rules };
}
/**
* 放弃本次弹窗编辑,恢复到打开弹窗前的页面状态。
*/
function closeSplitRuleDialog(): void {
dialogDefinition.value = null;
splitRuleDialogAutoAdd.value = false;
splitRuleDialogOpen.value = false;
}
/**
* 确认拆分规则后立即刷新树并保存整个 XFA 定义。
* 核心逻辑:使用子组件传回的最终规则消除事件时序差异;保存成功才关闭弹窗,失败保留编辑现场。
* @param rules 已标记为 confirmed 的完整拆分规则数组
*/
async function commitDialogSplitRules(
rules: import('@/features/admin/types/shipping-order-document-profile.types').XfaSplitRuleSet[],
): Promise<void> {
if (!dialogDefinition.value) return;
const confirmedDefinition = {
...cloneXfaData(dialogDefinition.value),
split_rules: cloneXfaData(rules),
};
dialogDefinition.value = confirmedDefinition;
definition.value = structuredClone(confirmedDefinition);
const saved = await save();
if (saved) closeSplitRuleDialog();
}
function openSplitRuleDialog(autoAdd = false): void {
if (!definition.value) return;
dialogDefinition.value = cloneXfaData(definition.value);
splitRuleDialogAutoAdd.value = autoAdd;
splitRuleDialogOpen.value = true;
}
function addRuleForPath(pathId: string): void {
selectedPathId.value = pathId;
selectedPathIsLeaf.value = true;
selectedRuleId.value = null;
openSplitRuleDialog(true);
}
/** 选择规则作为 Schema 映射来源,不打开编辑弹窗。 */
function selectRule(pathId: string, ruleId: string): void {
selectedPathId.value = pathId;
selectedPathIsLeaf.value = true;
selectedRuleId.value = ruleId;
}
/** 仅由规则行编辑图标打开维护弹窗。 */
function editRule(pathId: string, ruleId: string): void {
selectRule(pathId, ruleId);
openSplitRuleDialog();
}
function deleteRule(pathId: string, ruleId: string): void {
const current = definition.value?.split_rules?.find((item) => item.source_path_id === pathId);
if (!current || !window.confirm(t('admin.shippingOrderProfiles.xfaSplit.deleteConfirm'))) return;
onSplitRulesUpdate((definition.value?.split_rules || []).map((item) => item.source_path_id === pathId
? { ...item, rules: item.rules.filter((rule) => rule.rule_id !== ruleId).map((rule, index) => ({ ...rule, order: index + 1 })) }
: item));
}
watch(authoritativePathId, (pathId) => {
if (!definition.value || !pathId) return;
// 本地标记权威已选;真正路径由后端按 path_id 重写。
mirrorPathIds.value = mirrorPathIds.value.filter((item) => item !== pathId);
});
onMounted(load);
onBeforeUnmount(async () => {
revealTimers.forEach((timer) => clearTimeout(timer));
revealTimers.clear();
stopRenewal();
if (editLeaseToken.value) {
try {
await releaseOrderDocumentProfileEditLease(profileId.value, {
browser_session_id: editorSessionId,
lease_token: editLeaseToken.value,
operation_id: crypto.randomUUID(),
});
} catch { /* ignore release errors on unload */ }
}
});
</script>
<template>
<section class="xfa-workbench" v-if="!loading && definition">
<header class="xfa-workbench__header">
<div>
<button type="button" class="link" @click="router.push({ name: 'AdminShippingOrderDocumentProfiles' })">
← {{ t('admin.shippingOrderProfiles.workbench.headerReturnToLibrary') }}
</button>
<h1>{{ displayName }} · {{ profileCode }}</h1>
<p>
<span class="mode">{{ t('admin.shippingOrderProfiles.templateModes.xfa_dataset') }}</span>
<span>{{ t(`admin.shippingOrderProfiles.workbench.saveStatus.${saveState}`) }}</span>
</p>
</div>
<div class="actions">
<button v-if="saveState === 'readonly'" type="button" class="btn-secondary" @click="acquireLease(false)">
{{ t('admin.shippingOrderProfiles.workbench.headerRecoverLease') }}
</button>
<button v-if="saveState === 'readonly'" type="button" class="btn-secondary" @click="acquireLease(true)">
{{ t('admin.shippingOrderProfiles.workbench.headerTakeOverLease') }}
</button>
<button type="button" class="btn-secondary" :disabled="saving || !dirty" @click="save()">
{{ t('admin.shippingOrderProfiles.workbench.headerSaveDraft') }}
</button>
<button
type="button"
class="btn-primary"
:disabled="dirty || blockers.includes('authoritative_collection_required')"
@click="router.push({ name: 'AdminShippingOrderDocumentProfileValidate', params: { profileCode, profileId } })"
>
{{ t('admin.shippingOrderProfiles.workbench.headerValidate') }}
</button>
</div>
</header>
<div class="xfa-workbench__grid">
<XfaDatasetTree
:tree="tree"
:selected-path-id="selectedPathId"
:selected-rule-id="selectedRuleId"
:mapped-path-ids="mappedPathIds"
:revealed-values="revealedValues"
:revealing-path-id="revealingPathId"
:split-rule-sets="splitRuleSets"
@select-path="(pathId, isLeaf) => { selectedPathId = pathId; selectedPathIsLeaf = isLeaf; selectedRuleId = null; }"
@reveal-path="(pathId) => { selectedPathId = pathId; void revealSelectedValue(); }"
@add-rule="addRuleForPath"
@select-rule="selectRule"
@edit-rule="editRule"
@delete-rule="deleteRule"
/>
<div class="xfa-workbench__mapping-column">
<XfaSchemaMappingPanel
:schema-fields="schemaFields"
:definition="definition"
:mapped-field-previews="mappedFieldPreviews"
:selected-path-id="selectedPathId"
:selected-path-is-leaf="selectedPathIsLeaf"
:selected-rule-id="selectedRuleId"
:selected-source-scope="selectedSourceScope"
@bind-field="onBindField"
@unbind-field="onUnbindField"
/>
</div>
</div>
<div v-if="splitRuleDialogOpen" class="xfa-rule-dialog" role="dialog" aria-modal="true">
<div class="xfa-rule-dialog__backdrop" @click="closeSplitRuleDialog" />
<section class="xfa-rule-dialog__panel">
<header class="xfa-rule-dialog__header">
<div><strong>{{ t('admin.shippingOrderProfiles.xfaSplit.title') }}</strong><p>{{ selectedPathLabel }}</p></div>
<div class="xfa-rule-dialog__actions">
<button type="button" class="btn-secondary" :disabled="saveState === 'readonly'" @click="splitRulePanel?.addRule()">
{{ t('admin.shippingOrderProfiles.xfaSplit.addRule') }}
</button>
<button type="button" class="btn-secondary" :disabled="!dialogHasRules" @click="splitRulePanel?.runPreview()">
{{ t('admin.shippingOrderProfiles.xfaSplit.preview') }}
</button>
<button type="button" class="btn-primary" :disabled="saveState === 'readonly' || !dialogHasRules" @click="splitRulePanel?.confirmRules()">
{{ t('admin.shippingOrderProfiles.xfaSplit.confirm') }}
</button>
<button type="button" class="xfa-rule-dialog__close" :aria-label="t('common.close')" @click="closeSplitRuleDialog">×</button>
</div>
</header>
<XfaSplitRulePanel
ref="splitRulePanel"
:definition="dialogDefinition || definition"
:selected-path-id="selectedPathIsLeaf ? selectedPathId : null"
:selected-path-label="selectedPathLabel"
:selected-field-code="selectedFieldCode"
:selected-is-multiline="selectedIsMultiline"
:document-id="annotationDocumentId"
:profile-id="profileId"
:readonly="saveState === 'readonly'"
:can-edit="canEditSplitRules"
:can-preview="canPreviewSplitRules"
:can-reveal-sensitive="canRevealSensitiveSplit"
:dirty-unsaved="false"
:persisted-confirmed="splitRulePersistedConfirmed"
:auto-add-rule="splitRuleDialogAutoAdd"
@update:split-rules="onDialogSplitRulesUpdate"
@confirmed="commitDialogSplitRules"
/>
</section>
</div>
</section>
<p v-else-if="loading" class="loading">{{ t('admin.shippingOrderProfiles.xfaWorkbench.loading') }}</p>
<section v-else-if="loadError" class="xfa-workbench__error" role="alert">
<p>{{ t('admin.shippingOrderProfiles.xfaWorkbench.loadFailed') }}</p>
<button type="button" class="btn-primary" @click="load()">
{{ t('admin.shippingOrderProfiles.xfaWorkbench.retryLoad') }}
</button>
</section>
</template>
<style scoped>
.xfa-workbench { display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 12px; height: calc(100dvh - 24px); min-height: 0; padding: 12px 16px; overflow: hidden; background: var(--bg-page); }
.xfa-workbench__header { display: flex; justify-content: space-between; gap: 16px; align-items: start; padding: 12px 16px; border: 1px solid var(--border-default); border-radius: var(--radius-surface); background: var(--bg-surface); color: var(--text-primary); }
.xfa-workbench__header h1 { margin: 4px 0; font-size: 1.15rem; }
.xfa-workbench__header p { display: flex; gap: 12px; margin: 0; color: var(--text-muted); }
.mode { color: var(--status-info-fg); font-weight: 700; }
.actions { display: flex; flex-wrap: wrap; gap: 8px; }
.xfa-workbench__grid { display: grid; grid-template-columns: 360px minmax(0, 1fr); gap: 12px; min-height: 0; min-width: 0; width: 100%; overflow: hidden; }
.xfa-workbench__grid > * { min-width: 0; max-width: 100%; overflow: hidden; padding: 12px; border: 1px solid var(--border-default); border-radius: var(--radius-surface); background: var(--bg-surface); min-height: 0; }
.xfa-workbench__grid > .xfa-workbench__mapping-column { display: grid; grid-template-rows: minmax(0, 1fr); gap: 10px; padding: 0; border: 0; background: transparent; }
.xfa-workbench__mapping-column > * { min-width: 0; min-height: 0; overflow: auto; padding: 12px; border: 1px solid var(--border-default); border-radius: var(--radius-surface); background: var(--bg-surface); }
.xfa-workbench__split-column > .xfa-split { height: 100%; overflow: auto; }
.xfa-collections-inline { padding: 8px 12px !important; }
.xfa-collections-inline summary { cursor: pointer; color: var(--text-secondary); font-size: .78rem; font-weight: 700; }
.xfa-rule-dialog { position: fixed; z-index: 50; inset: 0; display: grid; place-items: center; padding: 24px; }
.xfa-rule-dialog__backdrop { position: absolute; inset: 0; background: rgb(15 23 42 / .42); }
.xfa-rule-dialog__panel { position: relative; display: flex; width: min(860px, 94vw); max-height: min(820px, 90vh); flex-direction: column; overflow: hidden; border: 1px solid var(--border-default); border-radius: var(--radius-surface); background: var(--bg-surface); box-shadow: 0 24px 70px rgb(15 23 42 / .24); }
.xfa-rule-dialog__header { display: flex; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--border-default); }
.xfa-rule-dialog__header p { margin: 3px 0 0; color: var(--text-muted); font-size: .76rem; }
.xfa-rule-dialog__actions { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 8px; }
.xfa-rule-dialog__actions button { min-height: 34px; }
.xfa-rule-dialog__close { display: inline-grid; width: 34px; padding: 0; place-items: center; border: 0; border-radius: var(--radius-control); background: transparent; color: var(--text-muted); cursor: pointer; font-size: 1.15rem; }
.xfa-rule-dialog__close:hover { background: var(--bg-page); color: var(--text-primary); }
.xfa-rule-dialog__panel > .xfa-split { min-height: 0; overflow: auto; padding: 14px 16px 18px; }
.link { border: 0; background: transparent; color: var(--status-info-fg); cursor: pointer; }
.loading { padding: 24px; }
.xfa-workbench__error {
display: flex; flex-direction: column; gap: 12px; align-items: flex-start;
margin: 24px; padding: 20px; border: 1px solid var(--status-error-border); border-radius: var(--radius-surface); background: var(--status-error-bg); color: var(--status-error-fg);
}
@media (max-width: 1400px) {
.xfa-workbench__grid { grid-template-columns: 240px minmax(420px, 1fr); }
.xfa-workbench__grid > :last-child { grid-column: 1 / -1; max-height: 36vh; }
}
@media (max-width: 1100px) {
.xfa-workbench__grid { grid-template-columns: 1fr; }
}
</style>
@@ -3,7 +3,8 @@
用途:展示订单模板版本中心的治理审计时间线(含 XFA operation_id / checksum)。
依赖:版本中心审计 API、版本详情 DTO、Vue I18n。
逻辑:使用 before_id 游标分页避免新增事件导致翻页重复;只展示安全 detail 摘要,
以及 XFA 变更前后 definition checksum 与 operation_id;不展示 PDF、正文或盲测真值。
以及 XFA 变更前后 definition checksum 与 operation_id;不展示 PDF、正文或盲测真值;
对视觉绑定 / 拆分 / 统一迁移事件渲染分组标签与 visual before/after 摘要。
-->
<script setup lang="ts">
import { computed, reactive, ref, watch } from "vue";
@@ -31,6 +32,30 @@ const filters = reactive({
createdTo: "",
});
const VISUAL_EVENT_PREFIXES = ["xfa_visual_binding_", "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 {
@@ -172,7 +197,14 @@ watch(
>
<header>
<div>
<p class="timeline-type">{{ item.event_type }}</p>
<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">
@@ -198,6 +230,14 @@ watch(
<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>
@@ -249,13 +289,44 @@ watch(
color: var(--text-primary);
}
.toolbar p,
.timeline-type {
.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;
@@ -34,9 +34,12 @@ const props = defineProps<{
pendingSuggestionCount?: number;
orderFieldValues?: Record<string, string | null>;
orderFieldValueState?: 'idle' | 'loading' | 'ready' | 'failed';
/** full=坐标全工具;xfa_visual=仅 XFA 画框。 */
annotationToolSet?: 'full' | 'xfa_visual';
}>();
const { t } = useI18n();
const readonlyMode = computed(() => props.mode === 'readonly');
const xfaVisualTools = computed(() => props.annotationToolSet === 'xfa_visual');
const emit = defineEmits<{
select: [regionId: string];
start: [regionId: string];
@@ -177,7 +180,13 @@ 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') return region.label;
if (region.kind !== 'order_field') {
if (region.kind === 'xfa_visual' && region.visualBindingStatus) {
const statusKey = `admin.shippingOrderProfiles.xfaUnified.visualStatus.${region.visualBindingStatus}`;
return `${region.label} · ${t(statusKey)}`;
}
return region.label;
}
const state = props.orderFieldValueState || 'idle';
const value = region.fieldCode ? props.orderFieldValues?.[region.fieldCode] : null;
const suffix = state === 'loading'
@@ -247,6 +256,10 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
<div v-else-if="!imageUrl" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.selectBoundPdf') }}</div>
<div v-else class="canvas-work-area" :class="{ readonly: readonlyMode }">
<aside v-if="!readonlyMode" class="annotation-tools">
<template v-if="xfaVisualTools">
<button type="button" :aria-label="t('admin.shippingOrderProfiles.xfaUnified.drawFieldBox')" :title="t('admin.shippingOrderProfiles.xfaUnified.drawFieldBox')" :class="{ active: creationKind === 'xfa_visual' }" @click="emit('draw', 'xfa_visual')"><TextCursorInput /></button>
</template>
<template v-else>
<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>
@@ -255,19 +268,21 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
<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" class="suggest" :aria-label="t('admin.shippingOrderProfiles.workbench.autoSuggestShortcut')" :title="t('admin.shippingOrderProfiles.workbench.autoSuggestShortcut')" :disabled="autoSuggestDisabled || suggesting" @click="emit('suggest')"><WandSparkles /></button>
</template>
<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 }" :style="{ '--canvas-zoom': zoom }" @pointerdown="beginCreation">
<img :src="imageUrl" alt="Controlled document page preview" draggable="false" />
<img :src="imageUrl" :alt="t('admin.shippingOrderProfiles.workbench.pagePreviewAlt')" draggable="false" />
<div
v-for="region in regions"
:key="region.id"
role="button"
tabindex="0"
class="region"
:class="[`region-${region.kind}`, { selected: selected.has(region.id) }]"
:class="[`region-${region.kind}`, { selected: selected.has(region.id) }, region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '']"
:style="{ left: `${region.region.x0 * 100}%`, top: `${region.region.y0 * 100}%`, width: `${(region.region.x1 - region.region.x0) * 100}%`, height: `${(region.region.y1 - region.region.y0) * 100}%` }"
:aria-label="displayRegionLabel(region)"
@pointerdown.stop="beginDrag($event, region, 'move')"
@keydown.enter="emit('select', region.id)"
@keydown.space.prevent="emit('select', region.id)"
@@ -359,6 +374,14 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
.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-xfa_visual { z-index: 2; border: 1.5px solid #38bdf8; background: rgb(14 165 233 / .12); }
.region-xfa_visual .region-label, .region-xfa_visual .resize-handle { background: #0369a1; }
.region-visual--suggested { 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; }
@@ -36,6 +36,19 @@ const collections = ref<Awaited<ReturnType<typeof getOrderProfileSampleXfaCollec
const flatNodes = ref(flattenXfaTreeNodes(null));
const excludedCollections = computed(() => collections.value?.excluded_collection_candidates || []);
/** 创建草稿前的阻断摘要(权威集合必选等)。 */
const createBlockers = computed(() => {
const items: string[] = [];
const selectable = (collections.value?.collection_candidates || []).filter((item) => item.selectable !== false);
if (!props.authoritativePathId && selectable.length) {
items.push(t('admin.shippingOrderProfiles.xfaWorkbench.blocker.authoritative_collection_required'));
}
if (!selectable.length && !props.authoritativePathId) {
items.push(t('admin.shippingOrderProfiles.xfaWorkbench.allCandidatesExcluded'));
}
return items;
});
const documentKindLabel = computed(() => {
const kind = props.sample?.document_kind || collections.value?.document_kind || 'xfa_hybrid';
return t(`admin.shippingOrderProfiles.xfa.documentKinds.${kind}`, kind);
@@ -83,6 +96,12 @@ watch(() => props.documentId, () => void loadXfaContext(), { immediate: true });
</ul>
</article>
<p v-if="loading" class="xfa-confirm-step__loading">{{ t('admin.shippingOrderProfiles.wizard.xfa.loading') }}</p>
<aside v-else-if="createBlockers.length" class="xfa-confirm-step__blockers" role="status">
<strong>{{ t('admin.shippingOrderProfiles.xfaUnified.createBlockersTitle') }}</strong>
<ul>
<li v-for="(item, index) in createBlockers" :key="index">{{ item }}</li>
</ul>
</aside>
<XfaCollectionSelector
v-else-if="collections && (collections.collection_candidates?.length || excludedCollections.length)"
:candidates="collections.collection_candidates || []"
@@ -103,4 +122,6 @@ watch(() => props.documentId, () => void loadXfaContext(), { immediate: true });
.xfa-confirm-step__badge { padding: 2px 8px; border-radius: 999px; background: var(--status-info-bg); color: var(--status-info-fg); font-size: .72rem; font-weight: 700; }
.xfa-confirm-step__checks { margin: 8px 0 0; padding-left: 18px; color: var(--text-secondary); font-size: .86rem; }
.xfa-confirm-step__loading { margin: 0; color: var(--text-muted); }
.xfa-confirm-step__blockers { padding: 12px 14px; border: 1px solid var(--status-warning-border); border-radius: var(--radius-control); background: var(--status-warning-bg); color: var(--status-warning-fg); font-size: .84rem; }
.xfa-confirm-step__blockers ul { margin: 6px 0 0; padding-left: 18px; }
</style>
@@ -3,7 +3,7 @@
用途:权威明细集合与镜像对账集合选择。
依赖:vue-i18n、XfaCollectionCandidate。
逻辑:以候选卡片直接展示完整路径、字段覆盖与样本证据;权威单选强制,镜像多选仅用于对账;
全部候选被排除时仍展示排除原因,禁止只显示“没有集合”。
selectable=false 的无效集合禁选;全部候选被排除时仍展示排除原因。
-->
<script setup lang="ts">
import { computed } from 'vue';
@@ -22,10 +22,11 @@ const emit = defineEmits<{
'update:mirrorPathIds': [pathIds: string[]];
}>();
const { t, te } = useI18n();
const mirrors = computed(() => listMirrorCollectionCandidates(props.candidates, props.authoritativePathId));
const selectedAuthoritative = computed(() => props.candidates.find((item) => item.path_id === props.authoritativePathId));
const hasSelectable = computed(() => props.candidates.length > 0);
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 {
@@ -70,12 +71,13 @@ function reasonLabels(reasons?: string[]): string {
<fieldset v-if="hasSelectable" class="auth-cards" :aria-invalid="!authoritativePathId">
<legend>{{ t('admin.shippingOrderProfiles.xfaWorkbench.authoritativeCollection') }}</legend>
<label
v-for="item in candidates"
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
@@ -83,6 +85,7 @@ function reasonLabels(reasons?: string[]): string {
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">
@@ -17,7 +17,6 @@ const i18n = createI18n({
shippingOrderProfiles: {
xfaWorkbench: {
treeTitle: '树', searchPaths: '搜索', collectionBadge: '集合', treeEmpty: '空',
revealValue: '查看 {field}',
},
xfaSplit: { addRule: '新增规则', ruleLabel: '规则 {index}', unnamedRule: '未命名规则', deleteRule: '删除' },
},
@@ -37,7 +36,7 @@ describe('XfaDatasetTree', () => {
is_leaf: false,
children: [{
path_id: 'leaf', local_name: 'EBELN', data_path_hash: 'h2', depth: 1, cardinality: 'one',
is_leaf: true, sample_value_masked: '451***',
is_leaf: true, sample_value_display: '4510000227', display_policy: 'full',
}],
},
},
@@ -166,4 +165,33 @@ describe('XfaDatasetTree', () => {
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]);
});
});
@@ -1,12 +1,12 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/XfaDatasetTree.vue
用途:XFA 映射工作台左侧受控数据树(仅分析记录节点)。
用途:XFA 受控数据树;主工作台用于绑定导航,高级诊断抽屉内只读展示。
依赖:vue-i18n、xfaProfileMapping.utils。
逻辑:支持展开折叠、方向键导航与分级样本展示;叶子展示父路径提示区分同名来源。
逻辑:支持展开折叠、方向键导航与完整样本值展示;readonly 时隐藏增删改规则动作。
-->
<script setup lang="ts">
import { computed, nextTick, ref } from 'vue';
import { ChevronDown, ChevronRight, Eye, Pencil } from 'lucide-vue-next';
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';
@@ -22,13 +22,12 @@ const props = defineProps<{
selectedPathId?: string | null;
selectedRuleId?: string | null;
mappedPathIds?: string[];
revealedValues?: Record<string, string>;
revealingPathId?: string;
splitRuleSets?: XfaSplitRuleSet[];
/** 为 true 时隐藏新增/编辑/删除规则操作,仅保留选择与诊断。 */
readonly?: boolean;
}>();
const emit = defineEmits<{
'select-path': [pathId: string, isLeaf: boolean];
'reveal-path': [pathId: string];
'add-rule': [pathId: string];
'select-rule': [pathId: string, ruleId: string];
'edit-rule': [pathId: string, ruleId: string];
@@ -40,6 +39,7 @@ 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;
@@ -190,7 +190,7 @@ async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
</span>
<span v-if="node.isCollectionCandidate" class="badge">{{ t('admin.shippingOrderProfiles.xfaWorkbench.collectionBadge') }}</span>
<button
v-if="node.isLeaf"
v-if="node.isLeaf && !isReadonly"
type="button"
class="add-rule"
:class="{ 'add-rule--active': selectedPathId === node.pathId }"
@@ -198,19 +198,9 @@ async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
:aria-label="t('admin.shippingOrderProfiles.xfaSplit.addRule')"
@click.stop="emit('add-rule', node.pathId)"
>+</button>
<span v-if="revealedValues?.[node.pathId] || node.sampleValueDisplay" class="sample">
{{ revealedValues?.[node.pathId] || node.sampleValueDisplay }}
<span v-if="node.sampleValueDisplay" class="sample">
{{ node.sampleValueDisplay }}
</span>
<button
v-if="node.isLeaf && node.canReveal && !revealedValues?.[node.pathId]"
type="button"
class="reveal"
:disabled="revealingPathId === node.pathId"
:aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.revealValue', { field: pathTitle(node) })"
@click.stop="emit('reveal-path', node.pathId)"
>
<Eye :size="14" aria-hidden="true" />
</button>
</div>
<ul
v-if="node.isLeaf && rulesFor(node.pathId).length"
@@ -229,13 +219,14 @@ async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
<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 type="button" class="rule-delete" :title="t('admin.shippingOrderProfiles.xfaSplit.deleteRule')" @click.stop="emit('delete-rule', node.pathId, rule.rule_id)">×</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>
@@ -261,7 +252,6 @@ async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
.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; }
.reveal { display: inline-flex; padding: 3px; border: 0; border-radius: 6px; background: transparent; color: var(--status-info-fg); cursor: pointer; }
.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; }
@@ -276,7 +266,6 @@ async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
.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); }
.reveal:focus-visible { outline: 2px solid var(--focus-ring); }
.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,70 @@
/**
* features/admin/modules/shipping-order-document-profiles/components/XfaSchemaMappingPanel.spec.ts
* 用途:验证 XFA Schema 映射面板渲染与 bind-field 事件。
* 依赖:Vitest、@vue/test-utils、XfaSchemaMappingPanel。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import XfaSchemaMappingPanel from './XfaSchemaMappingPanel.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
admin: {
shippingOrderProfiles: {
xfaWorkbench: {
schemaTitle: 'Schema',
filter: { all: '全部', unmapped: '未映射' },
scope: { header: '表头', line: '明细' },
selectLeafFirst: '选叶子',
unbind: '解除',
requiredCoverage: '{mapped}/{total}',
currentNode: '节点',
noneSelected: '无',
},
},
},
},
},
});
const definition = {
template_mode: 'xfa_dataset' as const,
source_contract: {
template_packet_checksum: 'a', dataset_structure_fingerprint: 'b', dataset_root_path: '/data',
authoritative_line_collection_path: '/data/ITEMS', mirror_collection_paths: [],
},
header_mappings: [],
line_mapping: { row_path: '/data/ITEMS', fields: [] },
cross_checks: {
acroform_enabled: true,
mirror_collection_policy: 'must_match_when_present' as const,
line_amount_formula: 'quantity_times_unit_price' as const,
total_amount_policy: 'must_equal_line_sum' as const,
},
};
describe('XfaSchemaMappingPanel', () => {
it('emits bind-field when a schema field is clicked with leaf selected', async () => {
const wrapper = mount(XfaSchemaMappingPanel, {
global: { plugins: [i18n] },
props: {
schemaFields: [{
field_id: 'f1', field_code: 'customer_po_no', scope: 'header', display_name: 'PO', required: true,
enabled: true, aliases: [], normalizer_key: 'trim', validator_keys: [], enum_options: [],
evidence_policy: { required: false, source_precedence: [], conflict_policy: 'fail', allow_single_source: true },
comparator_key: 'exact',
}],
definition,
selectedPathId: 'leaf-path',
selectedPathIsLeaf: true,
selectedSourceScope: 'header',
},
});
await wrapper.find('button.field').trigger('click');
expect(wrapper.emitted('bind-field')?.[0]?.[0]).toMatchObject({ field_code: 'customer_po_no' });
});
});
@@ -19,8 +19,8 @@ const props = defineProps<{
selectedSourceScope?: 'header' | 'line' | null;
filterMode?: 'all' | 'unmapped';
mappedFieldPreviews?: {
header: Array<{ fieldCode: string; pathLabel: string; maskedValue: string | null }>;
line: Array<{ fieldCode: string; pathLabel: string; maskedValue: string | null }>;
header: Array<{ fieldCode: string; pathLabel: string; value: string | null }>;
line: Array<{ fieldCode: string; pathLabel: string; value: string | null }>;
};
}>();
const emit = defineEmits<{
@@ -117,7 +117,7 @@ function setFilter(mode: 'all' | 'unmapped'): void {
</span>
<span v-if="mappingFor(field)" class="field__mapping">
<span class="field__path">← {{ mappingFor(field)?.pathLabel }}</span>
<strong v-if="mappingFor(field)?.maskedValue" class="field__value">{{ mappingFor(field)?.maskedValue }}</strong>
<strong v-if="mappingFor(field)?.value" class="field__value">{{ mappingFor(field)?.value }}</strong>
</span>
<span v-else class="field__empty">{{ t('admin.shippingOrderProfiles.xfaWorkbench.unmappedValue') }}</span>
<strong v-if="boundIds.has(field.field_id)" class="field__check">✓</strong>
@@ -1,6 +1,6 @@
/**
* features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.spec.ts
* 用途:验证 XfaSplitRulePanel pipeline 规则增删、确认门禁、order 重排与 reveal 传参。
* 用途:验证 XfaSplitRulePanel pipeline 规则增删、确认门禁、order 重排与完整值预览。
* 依赖:Vitest、@vue/test-utils、shipping-order-document-profile API mock。
*/
@@ -74,7 +74,6 @@ const xfaSplitMessages = {
substringStart: '起始',
substringEnd: '结束',
unmatchedPolicy: '未匹配',
revealFullValues: '完整值',
noRules: '无规则',
confirmNeedsPreview: '需先预览',
confirmBlockedDiagnostics: '诊断阻断',
@@ -200,7 +199,6 @@ function mountPanel(overrides: Record<string, unknown> = {}) {
}],
canEdit: true,
canPreview: true,
canRevealSensitive: true,
persistedConfirmed: true,
dirtyUnsaved: false,
...overrides,
@@ -235,8 +233,9 @@ describe('XfaSplitRulePanel', () => {
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('pipeline');
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');
@@ -274,6 +273,7 @@ describe('XfaSplitRulePanel', () => {
it('blocks confirm when preview has diagnostics', async () => {
previewMock.mockResolvedValue({
preview_token: 'tok-diag',
preview: {
status: 'ok',
mapped_fields: {},
@@ -322,6 +322,7 @@ describe('XfaSplitRulePanel', () => {
it('emits the final confirmed rules for parent persistence', async () => {
previewMock.mockResolvedValue({
preview_token: 'tok-preview-1',
preview: {
status: 'ok',
mapped_fields: {},
@@ -342,9 +343,11 @@ describe('XfaSplitRulePanel', () => {
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();
});
@@ -443,7 +446,7 @@ describe('XfaSplitRulePanel', () => {
expect(rules?.[0]?.rules).toHaveLength(1);
});
it('passes reveal:true to preview API when checkbox enabled and canRevealSensitive', async () => {
it('previews full values without a reveal permission parameter', async () => {
previewMock.mockResolvedValue({
preview: {
status: 'ok',
@@ -459,11 +462,9 @@ describe('XfaSplitRulePanel', () => {
split_rules: [makePipelineRuleSet({ rules: [] })],
},
});
const revealCheckbox = wrapper.find('.xfa-split__reveal input[type="checkbox"]');
await revealCheckbox.setValue(true);
await exposedActions(wrapper).runPreview();
await flushPromises();
expect(previewMock).toHaveBeenCalledWith(85, expect.objectContaining({ reveal: true }));
expect(previewMock).toHaveBeenCalledWith(85, expect.not.objectContaining({ reveal: expect.anything() }));
});
it('ignores exposed edit actions when canEdit is false', () => {
@@ -1,9 +1,9 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue
用途:XFA 多行字段拆分规则工作台——多阶段 pipeline 编辑、预览、确认与 segment 映射。
依赖:shipping-order-document-profile API、vue-i18n、Schema 字段列表、权限 props。
逻辑:编辑 definition.split_rules(strategy=pipeline);确认前须预览当前 rule_set 哈希;
编辑规则/阶段/归一化/策略均回退 draft 并失效预览;reveal 仅在有 audit_sensitive_read 时传递。
用途:XFA 字段拆分规则编辑——matcher 优先(prefix/regex/position),兼容历史 stages[] 投影。
依赖:shipping-order-document-profile API、vue-i18n、Schema 字段列表。
逻辑:编辑 definition.split_rules;新增/改提取方式同步写入 matcher;stages 保留供 UI 与兼容预览;
确认前须预览当前 rule_set 哈希;预览直接返回完整识别值。
-->
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
@@ -15,6 +15,7 @@ import {
} from '@/features/admin/api/shipping-order-document-profile.api';
import type {
OrderXfaDatasetProfileDefinition,
XfaSplitMatcher,
XfaSplitNormalization,
XfaSplitPreviewResult,
XfaSplitRule,
@@ -24,10 +25,11 @@ import type {
XfaSplitStageType,
} from '@/features/admin/types/shipping-order-document-profile.types';
/** updateRule 局部补丁:segment/stages 允许浅合并字段 */
type XfaSplitRulePatch = Omit<Partial<XfaSplitRule>, 'segment' | 'stages'> & {
/** updateRule 局部补丁:segment/stages/matcher 允许浅合并字段 */
type XfaSplitRulePatch = Omit<Partial<XfaSplitRule>, 'segment' | 'stages' | 'matcher'> & {
segment?: Partial<XfaSplitSegment>;
stages?: XfaSplitStage[];
matcher?: XfaSplitMatcher;
};
type XfaSplitStagePatch = Partial<XfaSplitStage>;
@@ -44,7 +46,6 @@ const props = defineProps<{
readonly?: boolean;
canEdit?: boolean;
canPreview?: boolean;
canRevealSensitive?: boolean;
dirtyUnsaved?: boolean;
persistedConfirmed?: boolean;
autoAddRule?: boolean;
@@ -52,7 +53,8 @@ const props = defineProps<{
const emit = defineEmits<{
'update:split-rules': [rules: XfaSplitRuleSet[]];
confirmed: [rules: XfaSplitRuleSet[]];
/** 确认时附带 path_id → preview_token,供父级保存时提交服务端校验 */
confirmed: [rules: XfaSplitRuleSet[], confirmationTokens: Record<string, string>];
}>();
const { t } = useI18n();
@@ -60,7 +62,8 @@ const message = useMessage();
const loading = ref(false);
const preview = ref<XfaSplitPreviewResult | null>(null);
const previewRuleSetHash = ref<string | null>(null);
const revealFullValues = ref(false);
/** 最近一次成功预览签发的确认令牌 */
const previewConfirmationToken = ref<string | null>(null);
const collapsedRules = ref(new Set<string>());
const advancedRules = ref(new Set<string>());
@@ -75,7 +78,7 @@ const activeRuleSet = computed(() => {
const sortedRules = computed(() => {
if (!activeRuleSet.value) return [];
return [...activeRuleSet.value.rules].sort((a, b) => a.order - b.order);
return [...activeRuleSet.value.rules].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
});
const showUnsavedConfirmBanner = computed(() => (
@@ -128,7 +131,7 @@ function markRuleSetDirty(ruleSet: XfaSplitRuleSet): XfaSplitRuleSet {
*/
function normalizeRuleOrders(rules: XfaSplitRule[]): XfaSplitRule[] {
return [...rules]
.sort((a, b) => a.order - b.order)
.sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
.map((rule, index) => ({ ...rule, order: index + 1 }));
}
@@ -183,6 +186,32 @@ function createDefaultPipelineStages(lineIndex = 1): XfaSplitStage[] {
];
}
/**
* 由提取模式与阶段参数生成正式 matcher(prefix > regex > position)。
*/
function matcherFromExtraction(mode: ExtractionMode, stage: Partial<XfaSplitStage>, order: number): XfaSplitMatcher {
if (mode === 'extract_prefix') {
return {
type: 'prefix',
value: String(stage.value || ''),
separators: (stage.separators && stage.separators.length) ? stage.separators : [':', ':'],
case_sensitive: Boolean(stage.case_sensitive),
};
}
if (mode === 'regex_capture') {
return {
type: 'regex',
pattern: String(stage.pattern || ''),
capture_group: stage.capture_group ?? 1,
case_sensitive: Boolean(stage.case_sensitive),
};
}
return {
type: 'position',
line_index: Number(stage.line_index || stage.line_start || order || 1),
};
}
/**
* 确保存在可编辑的规则集;无则创建 Draft 空壳(strategy=pipeline)。
*/
@@ -219,6 +248,7 @@ function ensureRuleSet(): XfaSplitRuleSet {
function invalidatePreview(): void {
preview.value = null;
previewRuleSetHash.value = null;
previewConfirmationToken.value = null;
}
/**
@@ -231,21 +261,20 @@ function applyRuleSetChange(updater: (ruleSet: XfaSplitRuleSet) => XfaSplitRuleS
}
/**
* 预览当前规则集执行结果;reveal 仅在有敏感读权限时传给后端。
* 预览当前规则集执行结果;返回脱敏预览与确认令牌(完整值需 reveal)。
*/
async function runPreview(): Promise<void> {
if (!props.selectedPathId || !activeRuleSet.value || props.canPreview === false) return;
loading.value = true;
try {
const reveal = revealFullValues.value && Boolean(props.canRevealSensitive);
const result = await previewOrderProfileSampleXfaSplitRules(props.documentId, {
path_id: props.selectedPathId,
rule_set: activeRuleSet.value as unknown as Record<string, unknown>,
profile_id: props.profileId,
reveal,
});
preview.value = result.preview;
previewRuleSetHash.value = hashRuleSet(activeRuleSet.value);
previewConfirmationToken.value = String(result.preview_token || '') || null;
} catch (error) {
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.xfaSplit.previewFailed'));
} finally {
@@ -255,12 +284,12 @@ async function runPreview(): Promise<void> {
/**
* 管理员确认规则:须已预览当前 rule_set;诊断或 needs_review 时阻断。
* 核心逻辑:确认事件携带完整规则数组,由父页面立即刷新树并完成持久化,避免依赖异步 props 回写。
* 核心逻辑:确认事件携带完整规则数组与 preview_token,由父页面保存时交服务端校验。
*/
function confirmRules(): void {
if (!activeRuleSet.value || isReadonly.value) return;
const currentHash = hashRuleSet(activeRuleSet.value);
if (!preview.value || previewRuleSetHash.value !== currentHash) {
if (!preview.value || previewRuleSetHash.value !== currentHash || !previewConfirmationToken.value) {
message.error(t('admin.shippingOrderProfiles.xfaSplit.confirmNeedsPreview'));
return;
}
@@ -289,20 +318,24 @@ function confirmRules(): void {
),
confirmedRuleSet,
];
const tokens = { [confirmedRuleSet.source_path_id]: previewConfirmationToken.value };
emit('update:split-rules', confirmedRules);
emit('confirmed', confirmedRules);
emit('confirmed', confirmedRules, tokens);
}
/**
* 新增一条拆分规则(segment + 默认 pipeline stages)。
* 新增一条拆分规则(matcher 优先,并投影兼容 stages[])。
*/
function addRule(): void {
if (isReadonly.value || !props.selectedPathId) return;
const ruleSet = ensureRuleSet();
const order = (ruleSet.rules?.length || 0) + 1;
const stages = createDefaultPipelineStages(order);
const nextRule: XfaSplitRule = {
rule_id: newClientId('rule'),
order: (ruleSet.rules?.length || 0) + 1,
stages: createDefaultPipelineStages((ruleSet.rules?.length || 0) + 1),
order,
matcher: matcherFromExtraction('select_line', stages[1] || {}, order),
stages,
segment: {
segment_id: newClientId('seg'),
segment_code: '',
@@ -313,6 +346,7 @@ function addRule(): void {
};
upsertRuleSet(markRuleSetDirty({
...ruleSet,
strategy: 'matcher',
rules: normalizeRuleOrders([...(ruleSet.rules || []), nextRule]),
}));
collapsedRules.value = new Set([...collapsedRules.value].filter((id) => id !== nextRule.rule_id));
@@ -352,40 +386,75 @@ function toggleAdvanced(ruleId: string): void {
advancedRules.value = next;
}
/** 返回规则的业务提取步骤;兼容历史 pipeline。 */
/** 返回规则的业务提取步骤;优先由 matcher 合成,兼容历史 pipeline stages。 */
function extractionStage(rule: XfaSplitRule): XfaSplitStage {
return rule.stages.find((stage) => (
if (rule.matcher?.type === 'prefix') {
return {
...createDefaultStage('extract_prefix'),
value: rule.matcher.value,
separators: rule.matcher.separators,
case_sensitive: rule.matcher.case_sensitive,
};
}
if (rule.matcher?.type === 'regex') {
return {
...createDefaultStage('regex_capture'),
pattern: rule.matcher.pattern,
capture_group: rule.matcher.capture_group,
case_sensitive: rule.matcher.case_sensitive,
};
}
if (rule.matcher?.type === 'position') {
return {
...createDefaultStage('select_line'),
line_index: rule.matcher.line_index ?? rule.order ?? 1,
};
}
const stages = rule.stages || [];
return stages.find((stage) => (
stage.type === 'select_line'
|| stage.type === 'select_line_range'
|| stage.type === 'extract_prefix'
|| stage.type === 'regex_capture'
|| stage.type === 'substring'
)) || { ...createDefaultStage('select_line'), line_index: rule.order };
)) || { ...createDefaultStage('select_line'), line_index: rule.order ?? 1 };
}
function extractionMode(rule: XfaSplitRule): ExtractionMode {
const stages = rule.stages || [];
// 连续行/截取仍靠 stages 驱动 UI;正式 matcher 用 position 近似。
if (stages.some((stage) => stage.type === 'select_line_range')) return 'select_line_range';
if (stages.some((stage) => stage.type === 'substring')) return 'substring';
if (rule.matcher?.type === 'prefix') return 'extract_prefix';
if (rule.matcher?.type === 'regex') return 'regex_capture';
if (rule.matcher?.type === 'position') return 'select_line';
return extractionStage(rule).type as ExtractionMode;
}
/** 返回主提取之后顺序执行的高级处理步骤。 */
function advancedStages(rule: XfaSplitRule): XfaSplitStage[] {
const stages = rule.stages || [];
const primary = extractionStage(rule);
const primaryIndex = rule.stages.findIndex((stage) => stage.stage_id === primary.stage_id);
const primaryIndex = stages.findIndex((stage) => stage.stage_id === primary.stage_id);
if (primaryIndex < 0) return [];
return rule.stages.slice(primaryIndex + 1);
return stages.slice(primaryIndex + 1);
}
/** 更换提取方式,同时保留公共拆分步骤和额外高级处理。 */
/** 更换提取方式,同时同步正式 matcher 与兼容 stages。 */
function changeExtractionMode(rule: XfaSplitRule, mode: ExtractionMode): void {
const split = rule.stages.find((stage) => stage.type === 'split_lines') || createDefaultStage('split_lines');
const stages = rule.stages || [];
const split = stages.find((stage) => stage.type === 'split_lines') || createDefaultStage('split_lines');
const advanced = advancedStages(rule);
const extraction = createDefaultStage(mode);
if (mode === 'select_line') extraction.line_index = rule.order;
if (mode === 'select_line') extraction.line_index = rule.order ?? 1;
if (mode === 'select_line_range') {
extraction.line_start = rule.order;
extraction.line_end = rule.order + 1;
extraction.line_start = rule.order ?? 1;
extraction.line_end = (rule.order ?? 1) + 1;
}
updateRule(rule.rule_id, { stages: [split, extraction, ...advanced] });
updateRule(rule.rule_id, {
stages: [split, extraction, ...advanced],
matcher: matcherFromExtraction(mode, extraction, rule.order ?? 1),
});
}
/** 在主提取之后追加高级处理步骤。 */
@@ -394,10 +463,17 @@ function addAdvancedStage(ruleId: string, type: XfaSplitStageType): void {
addStage(ruleId, type);
}
/** 更新当前规则的业务提取步骤参数。 */
/** 更新当前规则的业务提取步骤参数,并同步 matcher。 */
function updateExtraction(rule: XfaSplitRule, patch: XfaSplitStagePatch): void {
const current = extractionStage(rule);
updateStage(rule.rule_id, current.stage_id, patch);
const nextStage = { ...current, ...patch };
const mode = extractionMode(rule);
updateRule(rule.rule_id, {
stages: (rule.stages || []).map((stage) => (
stage.stage_id === current.stage_id ? nextStage : stage
)),
matcher: matcherFromExtraction(mode, nextStage, rule.order ?? 1),
});
}
/** 返回当前规则在最近一次预览中的识别结果。 */
@@ -444,6 +520,7 @@ function updateRule(ruleId: string, patch: XfaSplitRulePatch): void {
...patch,
segment: patch.segment ? { ...rule.segment, ...patch.segment } : rule.segment,
stages: patch.stages ?? rule.stages,
matcher: patch.matcher ?? rule.matcher,
};
}),
}));
@@ -490,7 +567,7 @@ function deleteStage(ruleId: string, stageId: string): void {
function moveStage(ruleId: string, stageId: string, direction: -1 | 1): void {
const rule = activeRuleSet.value?.rules.find((item) => item.rule_id === ruleId);
if (!rule) return;
const stages = [...rule.stages];
const stages = [...(rule.stages || [])];
const index = stages.findIndex((item) => item.stage_id === stageId);
const target = index + direction;
if (index < 0 || target < 0 || target >= stages.length) return;
@@ -509,7 +586,7 @@ function updateStage(ruleId: string, stageId: string, patch: XfaSplitStagePatch)
const rule = activeRuleSet.value?.rules.find((item) => item.rule_id === ruleId);
if (!rule) return;
updateRule(ruleId, {
stages: rule.stages.map((stage) => (
stages: (rule.stages || []).map((stage) => (
stage.stage_id === stageId ? { ...stage, ...patch } : stage
)),
});
@@ -619,7 +696,6 @@ function stageTypeLabel(type: XfaSplitStageType): string {
watch(() => props.selectedPathId, () => {
invalidatePreview();
revealFullValues.value = false;
});
defineExpose({ addRule, runPreview, confirmRules });
@@ -701,11 +777,6 @@ watch(activeRuleSet, (current, previous) => {
· v{{ activeRuleSet.rule_version }}
</p>
<label v-if="canRevealSensitive" class="xfa-split__reveal">
<input v-model="revealFullValues" type="checkbox" :disabled="canPreview === false" />
{{ t('admin.shippingOrderProfiles.xfaSplit.revealPreviewValues') }}
</label>
<div v-if="preview" class="xfa-split__preview">
<h4>{{ t('admin.shippingOrderProfiles.xfaSplit.previewTitle') }}</h4>
<p>{{ t('admin.shippingOrderProfiles.xfaSplit.previewStatus', { status: preview.status }) }}</p>
@@ -824,7 +895,7 @@ watch(activeRuleSet, (current, previous) => {
type="number"
min="1"
:disabled="isReadonly"
:value="extractionStage(rule).line_index ?? rule.order"
:value="extractionStage(rule).line_index ?? (rule.order ?? 1)"
@input="updateExtraction(rule, { line_index: Number(($event.target as HTMLInputElement).value) || 1 })"
/>
</label>
@@ -836,7 +907,7 @@ watch(activeRuleSet, (current, previous) => {
type="number"
min="1"
:disabled="isReadonly"
:value="extractionStage(rule).line_start ?? rule.order"
:value="extractionStage(rule).line_start ?? (rule.order ?? 1)"
@input="updateExtraction(rule, { line_start: Number(($event.target as HTMLInputElement).value) || 1 })"
/>
</label>
@@ -846,7 +917,7 @@ watch(activeRuleSet, (current, previous) => {
type="number"
min="1"
:disabled="isReadonly"
:value="extractionStage(rule).line_end ?? rule.order + 1"
:value="extractionStage(rule).line_end ?? (rule.order ?? 1) + 1"
@input="updateExtraction(rule, { line_end: Number(($event.target as HTMLInputElement).value) || 1 })"
/>
</label>
@@ -943,7 +1014,7 @@ watch(activeRuleSet, (current, previous) => {
<button
type="button"
class="danger"
:disabled="isReadonly || rule.stages.length <= 1"
:disabled="isReadonly || (rule.stages || []).length <= 1"
@click="deleteStage(rule.rule_id, stage.stage_id)"
>
{{ t('admin.shippingOrderProfiles.xfaSplit.deleteStage') }}
@@ -81,7 +81,7 @@ describe('XfaStructuredPreview', () => {
mappedFieldPreviews: {
header: [{
mappingId: 'm1', fieldCode: 'customer_po_no', pathId: 'hdr-ebeln',
pathLabel: 'EBELN', maskedValue: '4510***227',
pathLabel: 'EBELN', value: '4510000227',
}],
line: [],
},
@@ -17,7 +17,7 @@ export interface XfaMappedFieldPreviewRow {
fieldCode: string;
pathId: string;
pathLabel: string;
maskedValue: string | null;
value: string | null;
}
const props = defineProps<{
@@ -39,7 +39,7 @@ const headerRows = computed(() => props.mappedFieldPreviews?.header?.length
fieldCode: item.field_code,
pathId: item.path_id,
pathLabel: item.path_id,
maskedValue: null as string | null,
value: null as string | null,
})));
const lineRows = computed(() => props.mappedFieldPreviews?.line?.length
@@ -49,7 +49,7 @@ const lineRows = computed(() => props.mappedFieldPreviews?.line?.length
fieldCode: item.field_code,
pathId: item.path_id,
pathLabel: item.path_id,
maskedValue: null as string | null,
value: null as string | null,
})));
const mappingRows = computed(() => [...headerRows.value, ...lineRows.value]);
@@ -73,7 +73,7 @@ const mappingRows = computed(() => [...headerRows.value, ...lineRows.value]);
<li v-for="item in mappingRows" :key="item.mappingId">
<strong>{{ item.fieldCode }}</strong>
← {{ item.pathLabel }}
<span v-if="item.maskedValue" class="masked">({{ item.maskedValue }})</span>
<span v-if="item.value" class="value">({{ item.value }})</span>
</li>
</ul>
<p v-else class="empty">{{ t('admin.shippingOrderProfiles.xfaWorkbench.noMappings') }}</p>
@@ -93,7 +93,7 @@ const mappingRows = computed(() => [...headerRows.value, ...lineRows.value]);
.maps__heading--line { margin-top: 12px; }
.maps__list { display: grid; gap: 4px; margin: 0; padding: 0; list-style: none; }
.maps li { min-width: 0; overflow: hidden; color: var(--text-secondary); font-size: .75rem; line-height: 1.35; text-overflow: ellipsis; white-space: nowrap; }
.masked { color: var(--status-success-fg); }
.value { color: var(--status-success-fg); }
.empty { margin: 4px 0 0; color: var(--text-muted); font-size: .78rem; }
h3 { margin: 0 0 8px; font-size: .9rem; }
p { margin: 0; color: var(--text-secondary); }