feat(shipping-notice): 完善 XFA 模板映射与订单审核流程
- 统一 XFA 数据集、字段拆分、校验及运行时解析 - 完善订单模板管理、发布检查与迁移状态 - 优化订单审核草稿、预约回退及 STP 投影缓存 - 更新前端模板编辑器、映射组件与多语言错误文案 - 补充后端与前端测试,并更新本地集成启动配置
This commit is contained in:
1 parent
43a30a7489
commit
4ec436d44c
67 files changed
+5411
-528
No files matched your search
@@ -234,12 +234,17 @@ export const suggestOrderProfileOrderFields = (
|
||||
|
||||
/** 按当前未保存的工作台定义重读订单单头字段值;传入多页时由后端统一处理跨页冲突。 */
|
||||
export const previewOrderProfileOrderFieldValues = (
|
||||
documentId: number, schemaVersionId: number, pageNo: number, definition: ShippingOrderDocumentProfile['definition'],
|
||||
documentId: number,
|
||||
schemaVersionId: number,
|
||||
pageNo: number,
|
||||
definition: ShippingOrderDocumentProfile['definition'],
|
||||
pageNos?: number[],
|
||||
signal?: AbortSignal,
|
||||
) => requestJson<OrderFieldValuePreviewResponse>(
|
||||
'/api/admin/shipping-notice/order-document-profile-samples/order-field-values-preview', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ document_id: documentId, schema_version_id: schemaVersionId, page_no: pageNo, page_nos: pageNos, definition }),
|
||||
signal,
|
||||
...jsonAuth(),
|
||||
},
|
||||
);
|
||||
@@ -267,12 +272,17 @@ export const completeOrderDocumentProfileWizard = (payload: {
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 读取样本文档 XFA 字段树(脱敏值,不含明文路径)。 */
|
||||
export const getOrderProfileSampleXfaFieldTree = (documentId: number) =>
|
||||
requestJson<import('../types/shipping-order-document-profile.types').XfaFieldTreeResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/value-adapter/field-tree`,
|
||||
/** 读取样本文档 XFA 字段树;reveal=true 时需敏感读权限并返回完整样本展示值。 */
|
||||
export const getOrderProfileSampleXfaFieldTree = (
|
||||
documentId: number,
|
||||
options?: { reveal?: boolean },
|
||||
) => {
|
||||
const qs = options?.reveal ? '?reveal=true' : '';
|
||||
return requestJson<import('../types/shipping-order-document-profile.types').XfaFieldTreeResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/value-adapter/field-tree${qs}`,
|
||||
auth(),
|
||||
);
|
||||
};
|
||||
|
||||
/** 读取 XFA 明细集合候选。 */
|
||||
export const getOrderProfileSampleXfaCollections = (documentId: number) =>
|
||||
|
||||
+134
-3
@@ -3,7 +3,9 @@
|
||||
用途:维护订单模板草稿的独立盲测证据,并完成执行和批准。
|
||||
依赖:盲测 API、Profile 详情、Vue Router、统一业务错误提示和四语言文案。
|
||||
逻辑:验证页进入本页;所有模板按统一视觉表候选和字段证据复核;
|
||||
末端值源差异由服务端 adapter 投影,管理员复核后写入真值,再执行并批准。
|
||||
末端值源差异由服务端 adapter 投影,管理员复核后写入真值,再执行并批准;
|
||||
XFA 以 datasets 为正式值:OCR 对照与视觉/镜像指标仅 soft 诊断,不硬拦;
|
||||
业务错误优先用扁平 errors key 翻译,并附带服务端 message 便于定位。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
@@ -94,8 +96,101 @@ const failureDetails = computed(() => (suite.value?.latest_run?.failure_codes ||
|
||||
if (parts[2] === 'mismatch') {
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.rowsMismatch', { sample: sampleName }) };
|
||||
}
|
||||
if (parts[2] === 'extraction' && parts[3] === 'ocr_datasets_mismatch') {
|
||||
// 历史 Run 可能仍带此硬失败码;现已改为 soft_diagnostics,文案标明「对照诊断」语义。
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.ocrDatasetsMismatchLegacy', { sample: sampleName }) };
|
||||
}
|
||||
if (
|
||||
parts[2] === 'visual_coverage_insufficient'
|
||||
|| parts[2] === 'mirror_consistency_insufficient'
|
||||
|| parts[2] === 'evidence_retention_insufficient'
|
||||
) {
|
||||
// 历史 Run:XFA 视觉/镜像/留痕曾硬拦;现以 datasets 真值为准,请重新执行。
|
||||
return {
|
||||
code,
|
||||
message: t('admin.shippingOrderProfiles.blindTest.failure.visualMetricLegacy', {
|
||||
sample: sampleName,
|
||||
metric: parts[2],
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (parts[2] === 'extraction') {
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.extractionFailed', { sample: sampleName, reason: parts.slice(3).join(':') || 'failed' }) };
|
||||
}
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.unknown', { sample: sampleName }) };
|
||||
}));
|
||||
|
||||
/**
|
||||
* 执行后的 soft 诊断:OCR↔datasets 与 XFA 视觉/镜像/留痕不足,不阻断批准门禁。
|
||||
*/
|
||||
const softDiagnosticDetails = computed(() => {
|
||||
const diagnostics = suite.value?.latest_run?.soft_diagnostics || [];
|
||||
return diagnostics.flatMap((item) => {
|
||||
const sample = suite.value?.samples.find((entry) => entry.id === item.sample_id);
|
||||
const sampleName = sample
|
||||
? `${sample.filename} · P${sample.page_no}`
|
||||
: t('admin.shippingOrderProfiles.blindTest.unknownSample');
|
||||
if (item.code === 'visual_coverage_soft' || item.code === 'mirror_consistency_soft' || item.code === 'evidence_retention_soft') {
|
||||
const ratePct = item.rate == null ? '—' : `${(Number(item.rate) * 100).toFixed(1)}%`;
|
||||
return [{
|
||||
key: `soft-${item.sample_id}-${item.code}`,
|
||||
message: t('admin.shippingOrderProfiles.blindTest.softDiagnostic.visualMetricSoft', {
|
||||
sample: sampleName,
|
||||
metric: t(`admin.shippingOrderProfiles.blindTest.softDiagnostic.metric.${item.code}`),
|
||||
rate: ratePct,
|
||||
}),
|
||||
}];
|
||||
}
|
||||
const fields = item.fields || [];
|
||||
if (!fields.length) {
|
||||
return [{
|
||||
key: `soft-${item.sample_id}-empty`,
|
||||
message: t('admin.shippingOrderProfiles.blindTest.softDiagnostic.ocrDatasetsMismatch', {
|
||||
sample: sampleName,
|
||||
fields: t('admin.shippingOrderProfiles.blindTest.softDiagnostic.fieldsUnknown'),
|
||||
count: item.mismatch_count || 0,
|
||||
}),
|
||||
}];
|
||||
}
|
||||
return fields.map((field, index) => {
|
||||
const code = String(field.field_code || '').trim() || t('admin.shippingOrderProfiles.blindTest.softDiagnostic.fieldsUnknown');
|
||||
const label = field.scope === 'line' && field.row_index != null
|
||||
? `${code}#${Number(field.row_index) + 1}`
|
||||
: code;
|
||||
return {
|
||||
key: `soft-${item.sample_id}-${code}-${index}`,
|
||||
message: t('admin.shippingOrderProfiles.blindTest.softDiagnostic.ocrDatasetsFieldDiff', {
|
||||
sample: sampleName,
|
||||
field: label,
|
||||
ocr: String(field.ocr_value || '').trim() || t('admin.shippingOrderProfiles.blindTest.softDiagnostic.emptyValue'),
|
||||
datasets: String(field.datasets_value || '').trim() || t('admin.shippingOrderProfiles.blindTest.softDiagnostic.emptyValue'),
|
||||
}),
|
||||
};
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 预览复核时列出当前样本 OCR 与 datasets 未对齐项(含两侧截断值)。
|
||||
*/
|
||||
const candidateOcrMismatchLines = computed(() => {
|
||||
const check = candidate.value?.ocr_datasets_cross_check;
|
||||
if (!check || check.status !== 'mismatched') return [];
|
||||
return (check.mismatches || [])
|
||||
.map((item) => {
|
||||
const code = String(item.field_code || '').trim();
|
||||
if (!code) return null;
|
||||
const label = item.scope === 'line' && item.row_index != null
|
||||
? `${code}#${Number(item.row_index) + 1}`
|
||||
: code;
|
||||
return t('admin.shippingOrderProfiles.blindTest.softDiagnostic.ocrDatasetsFieldDiffInline', {
|
||||
field: label,
|
||||
ocr: String(item.ocr_value || '').trim() || t('admin.shippingOrderProfiles.blindTest.softDiagnostic.emptyValue'),
|
||||
datasets: String(item.datasets_value || '').trim() || t('admin.shippingOrderProfiles.blindTest.softDiagnostic.emptyValue'),
|
||||
});
|
||||
})
|
||||
.filter((item): item is string => Boolean(item));
|
||||
});
|
||||
/** 读取订单字段复核状态;候选加载完成时会初始化,默认值仅用于渲染过程中的安全兜底。 */
|
||||
function orderFieldReview(fieldKey: string): { correct: boolean; value: string } {
|
||||
return orderFieldReviews.value[fieldKey] || { correct: true, value: '' };
|
||||
@@ -111,8 +206,21 @@ function orderFieldKey(field: { scope: 'header'; field_code: string }): string {
|
||||
|
||||
/** 将统一业务错误转换为安全的界面提示,不暴露盲测真值或内部布局数据。 */
|
||||
function report(error: unknown): void {
|
||||
const code = error instanceof BusinessError ? error.code : '';
|
||||
message.error(code ? t(`errors.${code}`, code) : t('admin.orderProfileValidation.failed'));
|
||||
if (!(error instanceof BusinessError)) {
|
||||
message.error(t('admin.orderProfileValidation.failed'));
|
||||
return;
|
||||
}
|
||||
// 点号 code 在 i18n 里常被当成嵌套路径;优先扁平 key,再回退原文 code。
|
||||
const flatKey = `errors.${error.code.replace(/\./g, '_')}`;
|
||||
const dottedKey = `errors.${error.code}`;
|
||||
const translated = t(flatKey);
|
||||
const label = translated !== flatKey
|
||||
? translated
|
||||
: (t(dottedKey) !== dottedKey ? t(dottedKey) : error.code);
|
||||
const detail = typeof error.message === 'string' && error.message && error.message !== error.code
|
||||
? error.message
|
||||
: '';
|
||||
message.error(detail ? `${label}(${detail})` : label);
|
||||
}
|
||||
/** 将文件物化失败转成安全提示;版面错误只允许在预览复核阶段出现。 */
|
||||
function sampleFailureMessage(): string {
|
||||
@@ -432,6 +540,16 @@ onBeforeUnmount(() => {
|
||||
<ul><li v-for="failure in failureDetails" :key="failure.code"><span>{{ failure.message }}</span><code>{{ failure.code }}</code></li></ul>
|
||||
</section>
|
||||
|
||||
<section v-if="softDiagnosticDetails.length" class="card soft-diagnostics">
|
||||
<div>
|
||||
<h2>{{ t('admin.shippingOrderProfiles.blindTest.softDiagnostic.title') }}</h2>
|
||||
<p>{{ t('admin.shippingOrderProfiles.blindTest.softDiagnostic.hint') }}</p>
|
||||
</div>
|
||||
<ul>
|
||||
<li v-for="item in softDiagnosticDetails" :key="item.key">{{ item.message }}</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section v-if="suite.status === 'draft'" class="card">
|
||||
<div class="sample-heading"><h2>{{ t('admin.shippingOrderProfiles.blindTest.selectIndependentSample') }}</h2><label class="btn-secondary upload-sample"><input type="file" accept=".pdf,.eml,application/pdf,message/rfc822" :disabled="uploadingSample" @change="uploadIndependentSample"><span>{{ uploadingSample ? t('admin.shippingOrderProfiles.wizard.uploading') : t('admin.shippingOrderProfiles.blindTest.uploadSample') }}</span></label></div>
|
||||
<p v-if="availableSamplesLoaded && !availableSamples.length">{{ t('admin.shippingOrderProfiles.blindTest.noIndependentSamples') }}</p>
|
||||
@@ -450,6 +568,14 @@ onBeforeUnmount(() => {
|
||||
reasons: (candidate.reservation_region_review_reasons || []).join(', ') || candidate.reservation_region_status,
|
||||
}) }}
|
||||
</p>
|
||||
<p v-if="candidateOcrMismatchLines.length" class="ocr-diagnostic">
|
||||
{{ t('admin.shippingOrderProfiles.blindTest.softDiagnostic.previewOcrMismatchIntro', {
|
||||
count: candidateOcrMismatchLines.length,
|
||||
}) }}
|
||||
</p>
|
||||
<ul v-if="candidateOcrMismatchLines.length" class="ocr-diagnostic-list">
|
||||
<li v-for="(line, index) in candidateOcrMismatchLines" :key="`ocr-diff-${index}`">{{ line }}</li>
|
||||
</ul>
|
||||
<p v-if="!candidate.rows.length">{{ t('admin.shippingOrderProfiles.blindTest.candidateRowsEmpty') }}</p>
|
||||
<article v-for="(row, index) in candidate.rows" :key="index" class="review-item">
|
||||
<template v-if="rowReviews[index]">
|
||||
@@ -489,6 +615,11 @@ header { align-items: flex-start; margin-bottom: 24px; } h1, h2, h3, p { margin:
|
||||
.review-item { display: grid; gap: 8px; border: 1px solid var(--border-default); border-radius: 8px; padding: 12px; } code { overflow-wrap: anywhere; white-space: pre-wrap; color: var(--text-primary); font-size: 12px; } label { display: flex; gap: 6px; align-items: center; }
|
||||
ul { display: grid; gap: 8px; margin: 0; padding: 0; list-style: none; } li { border-top: 1px solid var(--border-default); padding-top: 8px; }
|
||||
.failure-details { border-color: var(--status-error-border); background: var(--status-error-bg); }.failure-details h2 { color: var(--status-error-fg); }.failure-details li { display: grid; gap: 4px; color: var(--status-error-fg); }.failure-details code { color: var(--status-error-fg); }
|
||||
.soft-diagnostics { border-color: var(--status-warning-border, #f59e0b); background: var(--status-warning-bg, #fffbeb); }
|
||||
.soft-diagnostics h2, .soft-diagnostics li, .ocr-diagnostic { color: var(--status-warning-fg) !important; }
|
||||
.ocr-diagnostic { font-weight: 600; grid-column: 1 / -1; }
|
||||
.ocr-diagnostic-list { grid-column: 1 / -1; margin: 0; padding-left: 1.2rem; color: var(--status-warning-fg); }
|
||||
.ocr-diagnostic-list li { margin: 4px 0; }
|
||||
.training-required { color: var(--status-warning-fg) !important; font-weight: 600; }
|
||||
@media (max-width: 700px) { header, .suite-summary, .execution, .sample-heading, .sample-picker { align-items: stretch; flex-direction: column; } .sample-picker .select-field { min-width: 0; width: 100%; } }
|
||||
</style>
|
||||
+364
-119
@@ -6,7 +6,15 @@
|
||||
逻辑:PDF 与 XFA 共用同一 desk DOM(main + aside.config + OrderProfileDocumentCanvas);
|
||||
XFA 仅在属性区插入读取方式/数据源/拆分/样本显示增量;OCR 建议进入普通建议区;
|
||||
未绑定订单字段框通过横幅 + 画布高亮强制展示,避免空白底图漏看导致发布失败;
|
||||
选中已有标注时退出绘制模式,避免 drawing 态吞掉缩放导致标签高度无法调整。
|
||||
选中已有标注时退出绘制模式,避免 drawing 态吞掉缩放导致标签高度无法调整;
|
||||
datasets 字段选型使用弹窗(复用 xfa-rule-dialog),避免窄侧栏内联树;
|
||||
数据源按钮有 path 时展示 selectedPathLabel,否则占位「选择数据源」;
|
||||
datasets 树「+」经 @add-rule → addSplitRuleFromTree 打开拆分弹窗;
|
||||
规则行点击即应用到当前 Schema 字段(@select-rule),铅笔才打开编辑(@edit-rule);
|
||||
删除视觉框/紫标签时同步移除 datasets binding(含级联删掉的绿框),避免重标新 ID 后保存报 formal_binding_visual_missing;
|
||||
识别结果区:OCR 表头保留,datasets header_fields/lines 作正式值增量;保存后刷新 validation runs;
|
||||
整页 order-field OCR 可中止+超时,自动保存前取消,避免占满连接池卡在「保存中」;
|
||||
保存飞行中若又选了 datasets path,applySavedDraft 后 restoreConcurrentEdits,禁止冲掉未入库绑定。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
@@ -162,6 +170,14 @@ const selectedVisualSampleValue = ref<string | null>(null);
|
||||
const selectedVisualSampleState = ref<'idle' | 'loading' | 'ready' | 'failed'>('idle');
|
||||
const visualSampleCache = new Map<string, { text: string | null; source: typeof selectedVisualSampleSource.value }>();
|
||||
const VISUAL_SAMPLE_TIMEOUT_MS = 10000;
|
||||
/** 整页 order-field OCR 预览超时;超时必须中止,否则会占满连接池拖死自动保存。 */
|
||||
const ORDER_FIELD_VALUE_TIMEOUT_MS = 12000;
|
||||
/** 连续标注时整页 OCR 防抖;须长于 autosave(800ms),避免每次画框都并发打满 preview。 */
|
||||
const ORDER_FIELD_VALUE_DEBOUNCE_MS = 1600;
|
||||
/** 自动保存成功后延迟再刷 OCR;编辑中会取消,避免保存后立刻再堵连接。 */
|
||||
const ORDER_FIELD_VALUE_POST_AUTOSAVE_DELAY_MS = 2500;
|
||||
/** region-text 附带的裁剪图 data URL 上限;超限则省略,避免大包体拖垮本地 worker / 阻塞草稿保存。 */
|
||||
const VISUAL_SAMPLE_RENDERED_IMAGE_MAX_CHARS = 1_400_000;
|
||||
/** 当前选区视觉样本的实际证据来源;仅供管理员交叉复核,不能替代 datasets 正式值。 */
|
||||
const selectedVisualSampleSource = ref<'pdf_coordinate' | 'ocr_coordinate' | 'acroform_widget' | 'xfa_rendered_ocr' | null>(null);
|
||||
const previewError = ref("");
|
||||
@@ -200,6 +216,17 @@ const documentCanvas = ref<{
|
||||
captureRegion: (region: OrderProfileRelativeRegion) => string | null;
|
||||
scrollRegionIntoView?: (regionId: string) => void;
|
||||
} | null>(null);
|
||||
/**
|
||||
* 导出画布裁剪图供 region-text 兜底 OCR;超限或 XFA datasets 模式返回 null。
|
||||
* XFA 正式值只认 datasets;视觉回读优先坐标/OCR 证据,避免大图 OCR 占满 worker 拖死保存。
|
||||
* @param region - 相对页宽高的框选区域
|
||||
*/
|
||||
const captureRegionForRegionText = (region: OrderProfileRelativeRegion): string | null => {
|
||||
if (hasValueSourceMapping.value) return null;
|
||||
const captured = documentCanvas.value?.captureRegion(region) || null;
|
||||
if (!captured || captured.length > VISUAL_SAMPLE_RENDERED_IMAGE_MAX_CHARS) return null;
|
||||
return captured;
|
||||
};
|
||||
const previewState = ref<"idle" | "updating" | "ready" | "failed">("idle");
|
||||
const canvasUnavailable = ref(false);
|
||||
const saving = ref(false);
|
||||
@@ -252,6 +279,7 @@ const valueAdapterDesk = reactive(useOrderProfileValueAdapter({
|
||||
onProfileSaved: onXfaProfileSaved,
|
||||
onValidateBlockedChange: (blocked) => { xfaValidateBlocked.value = blocked; },
|
||||
onSaveRequest: () => save(),
|
||||
onRequestAutosave: () => { scheduleAutosave(); },
|
||||
}));
|
||||
/** 共享 Editor 唯一持有 PDF 预览、翻页与渲染所需的 annotation 上下文。 */
|
||||
const deskAnnotationContext = computed(() => ({
|
||||
@@ -277,6 +305,13 @@ function assignXfaSplitDialogPanel(el: unknown): void {
|
||||
valueAdapterDesk.splitRuleDialogPanel = (el as HTMLElement | null) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定 datasets 字段选择弹窗 DOM,供焦点陷阱使用。
|
||||
*/
|
||||
function assignXfaDatasetsPickerPanel(el: unknown): void {
|
||||
valueAdapterDesk.datasetsPickerPanel = (el as HTMLElement | null) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定拆分规则面板实例,供 Header 动作调用。
|
||||
*/
|
||||
@@ -321,14 +356,17 @@ function onDeskCanvasSelect(id: string): void {
|
||||
canvasActions.value.select(id);
|
||||
const region = regions.value.find((item) => item.id === id);
|
||||
if (hasValueSourceMapping.value && region && ['order_field', 'header_field', 'field'].includes(region.kind)) {
|
||||
// 明细字段的共同布局 ID 由行布局 + field_code 稳定生成;不能另造 XFA 专属框。
|
||||
// 明细/表头字段以画布 region.id 为 field_layout_id,避免同 field_code 多框共用一个 binding。
|
||||
const fieldLayoutId = ['header_field', 'field'].includes(region.kind)
|
||||
? `${region.parentId || ''}:${region.fieldCode || ''}`.replace(/^:|:$/g, '')
|
||||
? region.id
|
||||
: (region.orderFieldId || region.id);
|
||||
valueAdapterDesk.selectSharedField(
|
||||
region.fieldCode,
|
||||
fieldLayoutId,
|
||||
['header_field', 'field'].includes(region.kind) ? 'line' : 'header',
|
||||
['header_field', 'field'].includes(region.kind)
|
||||
? `${region.parentId || ''}:${region.fieldCode || ''}`.replace(/^:|:$/g, '') || null
|
||||
: null,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -415,6 +453,8 @@ let previewTimer: number | null = null;
|
||||
/** 预览请求代次;旧的异步响应不得覆盖较新的 Profile 定义或样本选择。 */
|
||||
let previewRequest = 0;
|
||||
let orderFieldValueTimer: number | null = null;
|
||||
let orderFieldValuePostSaveTimer: number | null = null;
|
||||
let orderFieldValueAbortController: AbortController | null = null;
|
||||
let pendingGestureId: string | null = null;
|
||||
let activeGestureId: string | null = null;
|
||||
let activeGestureMoved = false;
|
||||
@@ -736,9 +776,20 @@ const deskAutoSuggestDisabled = computed(() => (
|
||||
const deskPageNo = computed(() => visualCanvas.value.pageNo);
|
||||
const deskPageCount = computed(() => visualCanvas.value.pageCount);
|
||||
const deskSaveDisabled = computed(() => visualCanvas.value.saveDisabled);
|
||||
const deskOrderFieldValues = computed(() => (
|
||||
orderFieldValues.value
|
||||
));
|
||||
const deskOrderFieldValues = computed(() => {
|
||||
const base: Record<string, string | null> = { ...orderFieldValues.value };
|
||||
// XFA:OCR 为空时用当前样本 header_fields 增量补齐画布标签,与右侧识别结果同源。
|
||||
const evidence = hasValueSourceMapping.value
|
||||
? selectCurrentDatasetsValidationEvidence(validationRuns.value, active.value?.structure_fingerprint)
|
||||
: null;
|
||||
for (const field of evidence?.header_fields || []) {
|
||||
const code = String(field.field_code || '').trim();
|
||||
const value = field.normalized_value;
|
||||
if (!code || value == null || value === '') continue;
|
||||
if (!base[code]) base[code] = value;
|
||||
}
|
||||
return base;
|
||||
});
|
||||
const deskOrderFieldValueState = computed(() => (
|
||||
orderFieldValueState.value
|
||||
));
|
||||
@@ -815,12 +866,15 @@ const selectedRegion = computed(
|
||||
watch(selectedRegion, (region) => {
|
||||
if (!hasValueSourceMapping.value || !region || !['order_field', 'header_field', 'field'].includes(region.kind)) return;
|
||||
const fieldLayoutId = ['header_field', 'field'].includes(region.kind)
|
||||
? `${region.parentId || ''}:${region.fieldCode || ''}`.replace(/^:|:$/g, '')
|
||||
? region.id
|
||||
: (region.orderFieldId || region.id);
|
||||
valueAdapterDesk.selectSharedField(
|
||||
region.fieldCode,
|
||||
fieldLayoutId,
|
||||
['header_field', 'field'].includes(region.kind) ? 'line' : 'header',
|
||||
['header_field', 'field'].includes(region.kind)
|
||||
? `${region.parentId || ''}:${region.fieldCode || ''}`.replace(/^:|:$/g, '') || null
|
||||
: null,
|
||||
);
|
||||
}, { immediate: true });
|
||||
/** 当前样本值只能来自本次按画布坐标回读的结果,禁止回退到旧的自动建议缓存。 */
|
||||
@@ -1144,8 +1198,9 @@ const beginFieldBindingEdit = () => {
|
||||
const isLine = ['header_field', 'field'].includes(target.kind);
|
||||
pendingFieldBinding = {
|
||||
fieldCode: target.fieldCode || null,
|
||||
// 明细框身份跟 region.id 走;Schema 改绑时 layout 不变,只迁 field_code。
|
||||
fieldLayoutId: isLine
|
||||
? `${target.parentId || ''}:${target.fieldCode || ''}`.replace(/^:|:$/g, '')
|
||||
? target.id
|
||||
: (target.orderFieldId || target.id),
|
||||
scope: isLine ? 'line' : 'header',
|
||||
};
|
||||
@@ -1169,15 +1224,17 @@ const finishFieldBindingEdit = () => {
|
||||
const target = selectedRegion.value;
|
||||
const previousBinding = pendingFieldBinding;
|
||||
pendingFieldBinding = null;
|
||||
if (target?.kind === 'order_field' && target.fieldCode) {
|
||||
target.label = schemaFieldLabel(target.fieldCode);
|
||||
if (target && ['order_field', 'header_field', 'field'].includes(target.kind) && target.fieldCode) {
|
||||
// 明细框标签原先不会随 Schema 下拉同步,导致画布仍显示旧 field_code。
|
||||
target.label = target.kind === 'order_field'
|
||||
? schemaFieldLabel(target.fieldCode)
|
||||
: target.fieldCode;
|
||||
}
|
||||
finishFormEdit();
|
||||
if (hasValueSourceMapping.value && target && ['order_field', 'header_field', 'field'].includes(target.kind)) {
|
||||
const fieldLayoutId = ['header_field', 'field'].includes(target.kind)
|
||||
? `${target.parentId || ''}:${target.fieldCode || ''}`.replace(/^:|:$/g, '')
|
||||
: (target.orderFieldId || target.id);
|
||||
const scope = ['header_field', 'field'].includes(target.kind) ? 'line' : 'header';
|
||||
const isLine = ['header_field', 'field'].includes(target.kind);
|
||||
const fieldLayoutId = isLine ? target.id : (target.orderFieldId || target.id);
|
||||
const scope = isLine ? 'line' : 'header';
|
||||
if (previousBinding) {
|
||||
valueAdapterDesk.migrateUniqueSharedFieldBinding(
|
||||
previousBinding.fieldCode,
|
||||
@@ -1191,6 +1248,9 @@ const finishFieldBindingEdit = () => {
|
||||
target.fieldCode,
|
||||
fieldLayoutId,
|
||||
scope,
|
||||
isLine
|
||||
? `${target.parentId || ''}:${target.fieldCode || ''}`.replace(/^:|:$/g, '') || null
|
||||
: null,
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -1332,7 +1392,7 @@ const readDocumentAnchorText = async (region: OrderProfileRelativeRegion): Promi
|
||||
try {
|
||||
const result = await readOrderProfilePreviewPageRegionText(
|
||||
active.value.id, form.documentId, pageNo.value, region, undefined, undefined,
|
||||
documentCanvas.value?.captureRegion(region),
|
||||
captureRegionForRegionText(region),
|
||||
);
|
||||
return result.text.trim() || null;
|
||||
} catch (error) {
|
||||
@@ -1484,24 +1544,45 @@ const duplicateSelected = () => {
|
||||
selectedId.value = copied.id;
|
||||
schedulePreview();
|
||||
};
|
||||
/** 删除当前选中区域并记录在撤销历史中。 */
|
||||
/**
|
||||
* 删除当前选中区域并记录在撤销历史中。
|
||||
* 核心逻辑:删紫标签会级联去掉依赖绿框;XFA 正式 binding 必须按 layout 身份一并清掉,
|
||||
* 否则重标得到新 order_field_* ID 后,旧 field_layout_id 仍占 path,保存报缺框。
|
||||
*/
|
||||
const removeSelected = () => {
|
||||
if (!selectedRegion.value) return;
|
||||
checkpoint();
|
||||
const removedId = selectedRegion.value.id;
|
||||
const removedKind = selectedRegion.value.kind;
|
||||
const removedLayoutId = selectedRegion.value.orderFieldId || selectedRegion.value.id;
|
||||
const documentAnchorId = ['document_anchor_label', 'document_anchor_value'].includes(selectedRegion.value.kind)
|
||||
? selectedRegion.value.parentId
|
||||
: null;
|
||||
// Removing a shared label removes dependent value boxes; removing one value box
|
||||
// preserves the label and any sibling customer/address field.
|
||||
const beforeIds = new Set(regions.value.map((item) => item.id));
|
||||
regions.value = filterRegionsAfterRemoval(regions.value, removedId, documentAnchorId || null);
|
||||
const removedLayoutIds = [...beforeIds]
|
||||
.filter((id) => !regions.value.some((item) => item.id === id))
|
||||
.flatMap((id) => {
|
||||
// 已删除区域的 layout 身份:order_field 优先 orderFieldId,明细框用 region.id。
|
||||
if (id === removedId) return [removedLayoutId, id];
|
||||
return [id];
|
||||
});
|
||||
// order_anchor 不在旧白名单内时,绿框已删但 binding 残留 → formal_binding_visual_missing。
|
||||
if (hasValueSourceMapping.value && ['order_field', 'order_anchor', 'header_field', 'field'].includes(removedKind)) {
|
||||
valueAdapterDesk.removeBindingsForVisualLayouts(removedLayoutIds);
|
||||
}
|
||||
if (documentAnchorId) {
|
||||
documentMatch.requiredAnchors = documentMatch.requiredAnchors.filter((item) => item.anchor_id !== documentAnchorId);
|
||||
documentMatch.optionalAnchors = documentMatch.optionalAnchors.filter((item) => item.anchor_id !== documentAnchorId);
|
||||
documentMatchDirty.value = true;
|
||||
}
|
||||
selectedId.value = null;
|
||||
markLocalChange();
|
||||
scheduleAutosave();
|
||||
schedulePreview();
|
||||
scheduleOrderFieldSuggestionValues();
|
||||
};
|
||||
/** 标记一次画布手势,只有实际产生几何变化时才创建撤销检查点。 */
|
||||
const beginRegionGesture = (id: string) => {
|
||||
@@ -1619,6 +1700,8 @@ const definition = () => {
|
||||
field_code: item.fieldCode!,
|
||||
scope: "line" as const,
|
||||
region: item.region,
|
||||
// 持久化画布框 ID,供 XFA binding.field_layout_id 精确引用。
|
||||
region_id: item.id,
|
||||
extractor_key: "direct",
|
||||
allowed_sources: ["pdf_coordinate"],
|
||||
minimum_evidence_level: "coordinate",
|
||||
@@ -1854,97 +1937,153 @@ const definition = () => {
|
||||
/**
|
||||
* 保存当前草稿或执行 800ms 自动保存。
|
||||
* 核心逻辑:自动保存复用同一租约与乐观锁契约;失败只保留本地状态并有限次重试,绝不重载画布。
|
||||
* 保存前中止 region-text 与整页 order-field OCR(真正 abort HTTP),草稿写入成功后立即释放 saving;
|
||||
* 自动保存后延迟再刷 OCR,避免连接池被 OCR 占满导致「保存中」卡住。
|
||||
* @param automatic - 为 true 时不弹成功提示,连续编辑会合并为一次 Revision。
|
||||
* @returns 保存完成后的最新草稿状态。
|
||||
* @returns 保存是否成功。
|
||||
*/
|
||||
const save = async (automatic = false) => {
|
||||
const adapter = draftSaveAdapter.value;
|
||||
if (saving.value || !adapter.canSave) return false;
|
||||
if (!automatic && adapter.skipUnchangedManualSave && !adapter.hasUnsavedChanges) return true;
|
||||
// 保存进行中又选了数据源时,不能丢请求:重新排队,等当前 PUT 结束后再写 path。
|
||||
if (saving.value) {
|
||||
if (automatic) scheduleAutosave();
|
||||
return false;
|
||||
}
|
||||
if (!adapter.canSave) return false;
|
||||
if (!automatic && adapter.skipUnchangedManualSave && !adapter.hasUnsavedChanges) {
|
||||
message.info(t('admin.shippingOrderProfiles.workbench.noUnsavedChanges'));
|
||||
return true;
|
||||
}
|
||||
// [STEP 1] 让出后端与浏览器连接池:取消进行中的视觉回读 / 整页 OCR,避免草稿 PUT 被卡住。
|
||||
selectedVisualSampleAbortController?.abort();
|
||||
selectedVisualSampleAbortController = null;
|
||||
orderFieldValueAbortController?.abort();
|
||||
orderFieldValueAbortController = null;
|
||||
if (orderFieldValueTimer) {
|
||||
window.clearTimeout(orderFieldValueTimer);
|
||||
orderFieldValueTimer = null;
|
||||
}
|
||||
if (orderFieldValuePostSaveTimer) {
|
||||
window.clearTimeout(orderFieldValuePostSaveTimer);
|
||||
orderFieldValuePostSaveTimer = null;
|
||||
}
|
||||
++selectedVisualSampleRequest;
|
||||
++orderFieldValueRequest;
|
||||
++previewRequest;
|
||||
saving.value = true;
|
||||
saveState.value = 'saving';
|
||||
const savingChangeVersion = localChangeVersion;
|
||||
const xfaEpochAtStart = hasValueSourceMapping.value ? valueAdapterDesk.editEpoch.value : 0;
|
||||
let saveSucceeded = false;
|
||||
let shouldRescheduleAutosave = false;
|
||||
try {
|
||||
const existingProfile = active.value;
|
||||
const adapterPayload = adapter.buildPayload(definition());
|
||||
if (!adapterPayload) {
|
||||
saveState.value = 'failed';
|
||||
return false;
|
||||
} else {
|
||||
const payload = {
|
||||
profile_code: form.profileCode.toUpperCase(),
|
||||
display_name: form.displayName,
|
||||
schema_version_id: form.schemaId,
|
||||
definition: adapterPayload.definition,
|
||||
sample_document_id: form.documentId,
|
||||
// sample_table_id 与 definition.main_table_id 是同一份冻结身份;当前页预览表不能参与保存。
|
||||
sample_table_id: resolveMainTableIdForPageChange({
|
||||
frozenMainTableId: mainTableId.value,
|
||||
pagePreviewTableId: form.tableId,
|
||||
}),
|
||||
change_note: form.changeNote,
|
||||
};
|
||||
if (!existingProfile) throw new Error('A draft must be created by the wizard before editing.');
|
||||
const savedProfile = await saveOrderDocumentProfileDraft(existingProfile.id, {
|
||||
...payload,
|
||||
expected_lock_version: existingProfile.lock_version,
|
||||
browser_session_id: editorSessionId,
|
||||
lease_token: editLeaseToken.value || '',
|
||||
operation_id: createRandomUuid(),
|
||||
...(adapterPayload.splitRuleConfirmationTokens
|
||||
? { split_rule_confirmation_tokens: adapterPayload.splitRuleConfirmationTokens }
|
||||
: {}),
|
||||
...(adapterPayload.allowFormalBindingDeletions?.length
|
||||
? { allow_formal_binding_deletions: adapterPayload.allowFormalBindingDeletions }
|
||||
: {}),
|
||||
});
|
||||
active.value = savedProfile;
|
||||
// [STEP] PUT 成功即解锁「保存中」;applySavedDraft 不得继续占住保存态。
|
||||
// 若保存飞行中用户又选了数据源,先抓本地快照,避免随后被服务端旧草稿冲掉。
|
||||
const concurrentXfaEdit = hasValueSourceMapping.value
|
||||
&& valueAdapterDesk.editEpoch.value !== xfaEpochAtStart
|
||||
? valueAdapterDesk.captureConcurrentEditState()
|
||||
: null;
|
||||
saving.value = false;
|
||||
saveState.value = 'saved';
|
||||
autosaveFailures = 0;
|
||||
const applied = await adapter.applySavedDraft(savedProfile);
|
||||
if (!applied) {
|
||||
saveState.value = 'failed';
|
||||
} else {
|
||||
if (concurrentXfaEdit) {
|
||||
// 飞行中改的 path/bindings/拆分写回本地,保持 dirty,立刻再排一次 autosave。
|
||||
valueAdapterDesk.restoreConcurrentEdits(concurrentXfaEdit);
|
||||
shouldRescheduleAutosave = true;
|
||||
}
|
||||
if (localChangeVersion === savingChangeVersion) {
|
||||
history.value = [];
|
||||
future.value = [];
|
||||
documentMatchDirty.value = false;
|
||||
reservationIdRegionDirty.value = false;
|
||||
}
|
||||
if (!automatic) message.success(t("admin.shippingOrderProfiles.updated"));
|
||||
profiles.value = profiles.value.map((item) => item.id === savedProfile.id ? savedProfile : item);
|
||||
saveSucceeded = true;
|
||||
shouldRescheduleAutosave = shouldRescheduleAutosave
|
||||
|| localChangeVersion !== savingChangeVersion;
|
||||
}
|
||||
}
|
||||
const payload = {
|
||||
profile_code: form.profileCode.toUpperCase(),
|
||||
display_name: form.displayName,
|
||||
schema_version_id: form.schemaId,
|
||||
definition: adapterPayload.definition,
|
||||
sample_document_id: form.documentId,
|
||||
// sample_table_id 与 definition.main_table_id 是同一份冻结身份;当前页预览表不能参与保存。
|
||||
sample_table_id: resolveMainTableIdForPageChange({
|
||||
frozenMainTableId: mainTableId.value,
|
||||
pagePreviewTableId: form.tableId,
|
||||
}),
|
||||
change_note: form.changeNote,
|
||||
};
|
||||
if (!existingProfile) throw new Error('A draft must be created by the wizard before editing.');
|
||||
const savedProfile = await saveOrderDocumentProfileDraft(existingProfile.id, {
|
||||
...payload,
|
||||
expected_lock_version: existingProfile.lock_version,
|
||||
browser_session_id: editorSessionId,
|
||||
lease_token: editLeaseToken.value || '',
|
||||
operation_id: createRandomUuid(),
|
||||
...(adapterPayload.splitRuleConfirmationTokens
|
||||
? { split_rule_confirmation_tokens: adapterPayload.splitRuleConfirmationTokens }
|
||||
: {}),
|
||||
...(adapterPayload.allowFormalBindingDeletions?.length
|
||||
? { allow_formal_binding_deletions: adapterPayload.allowFormalBindingDeletions }
|
||||
: {}),
|
||||
});
|
||||
active.value = savedProfile;
|
||||
const applied = await adapter.applySavedDraft(savedProfile);
|
||||
if (!applied) {
|
||||
saveState.value = 'failed';
|
||||
return false;
|
||||
}
|
||||
if (localChangeVersion === savingChangeVersion) {
|
||||
history.value = [];
|
||||
future.value = [];
|
||||
documentMatchDirty.value = false;
|
||||
reservationIdRegionDirty.value = false;
|
||||
}
|
||||
saveState.value = 'saved';
|
||||
autosaveFailures = 0;
|
||||
if (!automatic) message.success(t("admin.shippingOrderProfiles.updated"));
|
||||
profiles.value = profiles.value.map((item) => item.id === savedProfile.id ? savedProfile : item);
|
||||
// 保存主表后后端会冻结当前 Layout 身份;立即同步门禁,避免管理员必须重开编辑页。
|
||||
await refreshAutomarkSampleReadiness();
|
||||
await refreshOrderFieldSuggestionValues();
|
||||
if (localChangeVersion !== savingChangeVersion) scheduleAutosave();
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof BusinessError && ['SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED', 'SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_CONFLICT'].includes(error.code)) {
|
||||
saveState.value = 'readonly';
|
||||
return false;
|
||||
}
|
||||
saveState.value = 'failed';
|
||||
autosaveFailures += 1;
|
||||
if (error instanceof BusinessError && error.code === 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID' && error.details.field_path) {
|
||||
message.error(t('admin.shippingOrderProfiles.workbench.invalidDefinitionPath', { path: error.details.field_path }));
|
||||
} else {
|
||||
fail(error);
|
||||
saveState.value = 'failed';
|
||||
autosaveFailures += 1;
|
||||
if (error instanceof BusinessError && error.code === 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID' && error.details.field_path) {
|
||||
message.error(t('admin.shippingOrderProfiles.workbench.invalidDefinitionPath', { path: error.details.field_path }));
|
||||
} else {
|
||||
fail(error);
|
||||
}
|
||||
// A definition validation error cannot recover without an administrator edit.
|
||||
// Retrying it only produces repeated toast notifications for the same canvas state.
|
||||
const retryable = !(error instanceof BusinessError && [
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
|
||||
].includes(error.code));
|
||||
if (automatic && retryable && autosaveFailures < 3 && navigator.onLine) {
|
||||
if (retryTimer) window.clearTimeout(retryTimer);
|
||||
retryTimer = window.setTimeout(() => void save(true), 1500 * autosaveFailures);
|
||||
}
|
||||
}
|
||||
// A definition validation error cannot recover without an administrator edit.
|
||||
// Retrying it only produces repeated toast notifications for the same canvas state.
|
||||
const retryable = !(error instanceof BusinessError && [
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
|
||||
].includes(error.code));
|
||||
if (automatic && retryable && autosaveFailures < 3 && navigator.onLine) {
|
||||
if (retryTimer) window.clearTimeout(retryTimer);
|
||||
retryTimer = window.setTimeout(() => void save(true), 1500 * autosaveFailures);
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
// [STEP 2] 草稿已落库并解锁按钮后再刷门禁/预览;失败不影响已保存状态。
|
||||
if (saveSucceeded) {
|
||||
void refreshAutomarkSampleReadiness();
|
||||
// 自动保存后绝不立刻打整页 OCR:标注连点时会把连接池堵死,UI 一直停在「保存中」。
|
||||
if (automatic) {
|
||||
scheduleDeferredOrderFieldSuggestionValues();
|
||||
} else {
|
||||
void refreshOrderFieldSuggestionValues();
|
||||
}
|
||||
// XFA 正式明细/表头预览绑定 definition checksum;保存后刷新 Run 列表,避免仍指向旧证据。
|
||||
if (hasValueSourceMapping.value && active.value?.id) {
|
||||
void listOrderProfileValidationRuns(active.value.id)
|
||||
.then((runs) => { validationRuns.value = runs; })
|
||||
.catch(() => { /* 列表失败不阻断已保存草稿 */ });
|
||||
}
|
||||
if (shouldRescheduleAutosave) scheduleAutosave();
|
||||
}
|
||||
return saveSucceeded;
|
||||
};
|
||||
/** 创建只含主行区域的最小草稿并自动绑定样本,之后才允许打开受控页面画布标注。 */
|
||||
/** 以启用的 Schema 字段规则和冻结坐标生成待复核标记,绝不自动发布模板。 */
|
||||
@@ -2284,35 +2423,105 @@ const clearOrderFieldValuePreview = (state: 'idle' | 'loading' | 'failed') => {
|
||||
orderFieldValueError.value = '';
|
||||
};
|
||||
/**
|
||||
* 根据当前共同画布定义读取订单字段;过期请求不得覆盖更新后的值框结果。
|
||||
* 根据当前共同画布定义读取订单字段;过期/已中止请求不得覆盖更新后的值框结果。
|
||||
* 核心逻辑:XFA 也必须先复用这份 PDFium/OCR 视觉证据;datasets 只在右侧增量显示正式值。
|
||||
* 本地已存在重复 Schema 绑定时跳过请求,避免进入编辑页即打满 400 / 拖垮续租。
|
||||
* 必须支持 AbortSignal:整页 OCR 可达数十秒,不中止会占满连接池拖死自动保存 PUT。
|
||||
*/
|
||||
const refreshOrderFieldSuggestionValues = async () => {
|
||||
orderFieldValueAbortController?.abort();
|
||||
orderFieldValueAbortController = null;
|
||||
const request = ++orderFieldValueRequest;
|
||||
if (!form.documentId || !form.schemaId || !pageRegions.value.some((item) => item.kind === "order_field")) {
|
||||
clearOrderFieldValuePreview('idle');
|
||||
return;
|
||||
}
|
||||
const orderFieldCodes = regions.value
|
||||
.filter((item) => item.kind === 'order_field' && item.fieldCode)
|
||||
.map((item) => item.fieldCode!);
|
||||
const duplicateCodes = [...new Set(orderFieldCodes.filter((code, index) => orderFieldCodes.indexOf(code) !== index))];
|
||||
if (duplicateCodes.length) {
|
||||
clearOrderFieldValuePreview('failed');
|
||||
orderFieldValueError.value = t('admin.shippingOrderProfiles.workbench.orderFieldDuplicatePreview', {
|
||||
fields: duplicateCodes.join(', '),
|
||||
});
|
||||
return;
|
||||
}
|
||||
clearOrderFieldValuePreview('loading');
|
||||
const abortController = new AbortController();
|
||||
orderFieldValueAbortController = abortController;
|
||||
let timeoutId: number | null = null;
|
||||
try {
|
||||
const result = await previewOrderProfileOrderFieldValues(
|
||||
form.documentId,
|
||||
form.schemaId,
|
||||
pageNo.value,
|
||||
definition(),
|
||||
);
|
||||
const result = await Promise.race([
|
||||
previewOrderProfileOrderFieldValues(
|
||||
form.documentId,
|
||||
form.schemaId,
|
||||
pageNo.value,
|
||||
definition(),
|
||||
undefined,
|
||||
abortController.signal,
|
||||
),
|
||||
new Promise<never>((_, reject) => {
|
||||
timeoutId = window.setTimeout(() => {
|
||||
abortController.abort();
|
||||
reject(new DOMException('order_field_value_timeout', 'AbortError'));
|
||||
}, ORDER_FIELD_VALUE_TIMEOUT_MS);
|
||||
}),
|
||||
]);
|
||||
if (request !== orderFieldValueRequest) return;
|
||||
orderFieldValuePreviews.value = result.fields;
|
||||
orderFieldValueState.value = 'ready';
|
||||
} catch (error) {
|
||||
if (error instanceof DOMException && error.name === 'AbortError') {
|
||||
// 被保存/重调度/超时中止时勿卡在「读取中」,否则标注间隙 UI 一直像在读。
|
||||
if (request === orderFieldValueRequest && orderFieldValueState.value === 'loading') {
|
||||
orderFieldValueState.value = 'idle';
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (request === orderFieldValueRequest) {
|
||||
clearOrderFieldValuePreview('failed');
|
||||
orderFieldValueError.value = error instanceof BusinessError
|
||||
? error.message
|
||||
: t('admin.shippingOrderProfiles.workbench.orderFieldValueFailed');
|
||||
}
|
||||
} finally {
|
||||
if (timeoutId !== null) window.clearTimeout(timeoutId);
|
||||
if (orderFieldValueAbortController === abortController) {
|
||||
orderFieldValueAbortController = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
/**
|
||||
* 订单字段框或读取方式变化后延迟回读整页字符证据。
|
||||
* 核心逻辑:先中止旧 HTTP(不仅是丢弃结果),并拉长防抖,避免连点标注时并发打满 OCR。
|
||||
*/
|
||||
const scheduleOrderFieldSuggestionValues = () => {
|
||||
if (orderFieldValueTimer) window.clearTimeout(orderFieldValueTimer);
|
||||
if (orderFieldValuePostSaveTimer) {
|
||||
window.clearTimeout(orderFieldValuePostSaveTimer);
|
||||
orderFieldValuePostSaveTimer = null;
|
||||
}
|
||||
// [STEP] 几何刚变化:中止进行中的整页 OCR,腾出连接给即将到来的自动保存。
|
||||
// 防抖期间保留旧预览,真正发请求时再切 loading,避免连点标注一直「读取中」。
|
||||
orderFieldValueAbortController?.abort();
|
||||
orderFieldValueAbortController = null;
|
||||
++orderFieldValueRequest;
|
||||
orderFieldValueTimer = window.setTimeout(() => {
|
||||
void refreshOrderFieldSuggestionValues();
|
||||
}, ORDER_FIELD_VALUE_DEBOUNCE_MS);
|
||||
};
|
||||
/**
|
||||
* 自动保存成功后延迟刷新整页 OCR;若期间又有标注则取消,优先保证保存通道畅通。
|
||||
*/
|
||||
const scheduleDeferredOrderFieldSuggestionValues = () => {
|
||||
if (orderFieldValuePostSaveTimer) window.clearTimeout(orderFieldValuePostSaveTimer);
|
||||
orderFieldValuePostSaveTimer = window.setTimeout(() => {
|
||||
orderFieldValuePostSaveTimer = null;
|
||||
if (saving.value || dirty.value) return;
|
||||
void refreshOrderFieldSuggestionValues();
|
||||
}, ORDER_FIELD_VALUE_POST_AUTOSAVE_DELAY_MS);
|
||||
};
|
||||
/**
|
||||
* 读取当前选中非单头框的视觉样本值。
|
||||
*
|
||||
@@ -2354,7 +2563,7 @@ const refreshSelectedVisualSampleValue = async () => {
|
||||
active.value.id, form.documentId, region.pageNo, region.region,
|
||||
abortController.signal,
|
||||
undefined,
|
||||
documentCanvas.value?.captureRegion(region.region),
|
||||
captureRegionForRegionText(region.region),
|
||||
),
|
||||
new Promise<never>((_, reject) => {
|
||||
timeoutId = window.setTimeout(() => {
|
||||
@@ -2395,16 +2604,6 @@ watch(
|
||||
() => { void refreshSelectedVisualSampleValue(); },
|
||||
{ immediate: true },
|
||||
);
|
||||
/** 订单字段框或读取方式变化后延迟回读整页字符证据,避免地址字段停留在旧的空候选。 */
|
||||
const scheduleOrderFieldSuggestionValues = () => {
|
||||
if (orderFieldValueTimer) window.clearTimeout(orderFieldValueTimer);
|
||||
// 几何刚变化即进入读取中,任何旧结果均不再可见。
|
||||
++orderFieldValueRequest;
|
||||
clearOrderFieldValuePreview('loading');
|
||||
orderFieldValueTimer = window.setTimeout(() => {
|
||||
void refreshOrderFieldSuggestionValues();
|
||||
}, 400);
|
||||
};
|
||||
/** 在后台刷新区域预览,保留原有坐标/OCR 准备行为;结果不再占用标注画布下方空间。 */
|
||||
const schedulePreview = () => {
|
||||
if (previewTimer) window.clearTimeout(previewTimer);
|
||||
@@ -2767,7 +2966,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
return [
|
||||
...table.header_layouts.flatMap((header) =>
|
||||
header.field_regions.map((item, index) => ({
|
||||
id: `${header.layout_id}-field-${index}`,
|
||||
id: item.region_id || `${header.layout_id}-field-${index}`,
|
||||
kind: "header_field" as const,
|
||||
label: item.field_code,
|
||||
// Keep the binding as well as its visible label. Without fieldCode, a
|
||||
@@ -2788,7 +2987,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
})),
|
||||
...table.line_layouts.flatMap((line) =>
|
||||
line.field_regions.map((item, index) => ({
|
||||
id: `${line.layout_id}-field-${index}`,
|
||||
id: item.region_id || `${line.layout_id}-field-${index}`,
|
||||
kind: "field" as const,
|
||||
label: item.field_code,
|
||||
region: item.region,
|
||||
@@ -3180,9 +3379,14 @@ onMounted(async () => {
|
||||
onBeforeUnmount(() => {
|
||||
++previewRequest;
|
||||
++selectedVisualSampleRequest;
|
||||
++orderFieldValueRequest;
|
||||
selectedVisualSampleAbortController?.abort();
|
||||
selectedVisualSampleAbortController = null;
|
||||
orderFieldValueAbortController?.abort();
|
||||
orderFieldValueAbortController = null;
|
||||
if (previewTimer) window.clearTimeout(previewTimer);
|
||||
if (orderFieldValueTimer) window.clearTimeout(orderFieldValueTimer);
|
||||
if (orderFieldValuePostSaveTimer) window.clearTimeout(orderFieldValuePostSaveTimer);
|
||||
if (autosaveTimer) window.clearTimeout(autosaveTimer);
|
||||
if (retryTimer) window.clearTimeout(retryTimer);
|
||||
stopLeaseRenewal();
|
||||
@@ -3630,21 +3834,12 @@ onBeforeUnmount(() => {
|
||||
type="button"
|
||||
class="btn-secondary"
|
||||
:disabled="xfaConfigReadonly || valueAdapterDesk.loading || !valueAdapterDesk.tree"
|
||||
@click="valueAdapterDesk.datasetsPickerOpen = !valueAdapterDesk.datasetsPickerOpen"
|
||||
:title="valueAdapterDesk.selectedPathLabel || t('admin.shippingOrderProfiles.xfaDesk.pickDatasetsPath')"
|
||||
@click="valueAdapterDesk.openDatasetsPicker()"
|
||||
>
|
||||
{{ valueAdapterDesk.selectedPathLabel || t('admin.shippingOrderProfiles.xfaDesk.pickDatasetsPath') }}
|
||||
</button>
|
||||
</label>
|
||||
<div v-if="valueAdapterDesk.datasetsPickerOpen" class="xfa-datasets-popover xfa-incremental-popover">
|
||||
<XfaDatasetTree
|
||||
:tree="valueAdapterDesk.tree"
|
||||
:selected-path-id="valueAdapterDesk.selectedPathId"
|
||||
:selected-rule-id="valueAdapterDesk.selectedRuleId"
|
||||
:mapped-path-ids="valueAdapterDesk.mappedPathIds"
|
||||
:split-rule-sets="valueAdapterDesk.splitRuleSets"
|
||||
@select-path="(pathId, isLeaf) => valueAdapterDesk.updateSelectedDatasetsPath(pathId, isLeaf)"
|
||||
/>
|
||||
</div>
|
||||
<section class="sample-value-card">
|
||||
<span>{{ t('admin.shippingOrderProfiles.xfaDesk.datasetsSampleValue') }}</span>
|
||||
<strong :class="{ empty: !valueAdapterDesk.selectedSampleValue }">
|
||||
@@ -3670,6 +3865,7 @@ onBeforeUnmount(() => {
|
||||
{{ t('admin.shippingOrderProfiles.xfaSplit.editRules') }}
|
||||
</button>
|
||||
</label>
|
||||
<p class="xfa-header-inheritance-hint">{{ t('admin.shippingOrderProfiles.xfaSplit.splitVisualReuseHint') }}</p>
|
||||
<section class="xfa-datasource-summary">
|
||||
<strong>{{ t('admin.shippingOrderProfiles.xfaDesk.datasourceSummary') }}</strong>
|
||||
<p>{{ t('admin.shippingOrderProfiles.xfaWorkbench.collectionMeta', {
|
||||
@@ -3709,7 +3905,7 @@ onBeforeUnmount(() => {
|
||||
@click="selectDeskRecognitionRegion(item.id)"
|
||||
>
|
||||
<span :title="schemaFieldLabel(item.fieldCode)">{{ schemaFieldLabel(item.fieldCode) }}</span>
|
||||
<strong :class="{ empty: !item.value }" :title="item.value || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable')">{{ item.value || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable') }}</strong>
|
||||
<strong :class="{ empty: !item.value }" :title="item.value || (item.status === 'loading' ? t('admin.shippingOrderProfiles.workbench.orderFieldValueReading') : t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable'))">{{ item.value || (item.status === 'loading' ? t('admin.shippingOrderProfiles.workbench.orderFieldValueReading') : t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable')) }}</strong>
|
||||
<small :class="`evidence-status--${item.status}`">{{ t(`admin.shippingOrderProfiles.workbench.evidenceStatus.${item.status}`) }}</small>
|
||||
</button>
|
||||
<p v-if="!deskHeaderRecognitionResults.length" class="recognition-empty">{{ t('admin.shippingOrderProfiles.workbench.noRecognitionResults') }}</p>
|
||||
@@ -3742,6 +3938,40 @@ onBeforeUnmount(() => {
|
||||
</section>
|
||||
</aside>
|
||||
|
||||
<div
|
||||
v-if="hasValueSourceMapping && valueAdapterDesk.datasetsPickerOpen"
|
||||
class="xfa-rule-dialog"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="t('admin.shippingOrderProfiles.xfaDesk.pickDatasetsPathTitle')"
|
||||
@keydown.esc.stop.prevent="valueAdapterDesk.closeDatasetsPicker()"
|
||||
>
|
||||
<div class="xfa-rule-dialog__backdrop" @click="valueAdapterDesk.closeDatasetsPicker()" />
|
||||
<section :ref="assignXfaDatasetsPickerPanel" class="xfa-rule-dialog__panel xfa-datasets-picker-panel">
|
||||
<header class="xfa-rule-dialog__header">
|
||||
<div>
|
||||
<strong>{{ t('admin.shippingOrderProfiles.xfaDesk.pickDatasetsPathTitle') }}</strong>
|
||||
<p>{{ t('admin.shippingOrderProfiles.xfaDesk.pickDatasetsPathHint') }}</p>
|
||||
</div>
|
||||
<button type="button" class="xfa-rule-dialog__close" :aria-label="t('common.close')" @click="valueAdapterDesk.closeDatasetsPicker()">×</button>
|
||||
</header>
|
||||
<div class="xfa-datasets-picker-body">
|
||||
<XfaDatasetTree
|
||||
expand-samples
|
||||
:tree="valueAdapterDesk.tree"
|
||||
:selected-path-id="valueAdapterDesk.selectedPathId"
|
||||
:selected-rule-id="valueAdapterDesk.selectedRuleId"
|
||||
:mapped-path-ids="valueAdapterDesk.mappedPathIds"
|
||||
:split-rule-sets="valueAdapterDesk.splitRuleSets"
|
||||
@select-path="(pathId, isLeaf) => valueAdapterDesk.updateSelectedDatasetsPath(pathId, isLeaf)"
|
||||
@add-rule="valueAdapterDesk.addSplitRuleFromTree"
|
||||
@edit-rule="valueAdapterDesk.editSplitRuleFromTree"
|
||||
@select-rule="valueAdapterDesk.selectSplitRuleFromTree"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="hasValueSourceMapping && valueAdapterDesk.splitRuleDialogOpen"
|
||||
class="xfa-rule-dialog"
|
||||
@@ -3929,6 +4159,21 @@ onBeforeUnmount(() => {
|
||||
background: #fff;
|
||||
padding: 8px;
|
||||
}
|
||||
.xfa-datasets-picker-panel {
|
||||
width: min(920px, 96vw);
|
||||
max-height: min(860px, 92vh);
|
||||
}
|
||||
.xfa-datasets-picker-body {
|
||||
display: flex;
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
padding: 12px 16px 16px;
|
||||
}
|
||||
.xfa-datasets-picker-body :deep(.xfa-tree) {
|
||||
min-height: 420px;
|
||||
}
|
||||
.binding-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
@@ -4277,7 +4522,7 @@ onBeforeUnmount(() => {
|
||||
padding: 0.65rem;
|
||||
}
|
||||
.sample-value-card span { color: #0369a1; font-size: 0.72rem; font-weight: 700; }
|
||||
.sample-value-card strong { color: #0c4a6e; font: 700 0.82rem/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; overflow-wrap: anywhere; }
|
||||
.sample-value-card strong { color: #0c4a6e; font: 700 0.82rem/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; overflow-wrap: anywhere; white-space: pre-wrap; }
|
||||
.sample-value-card strong.empty { color: #64748b; font-family: inherit; font-weight: 500; }
|
||||
.sample-value-card__source { color: #64748b; font-size: 0.72rem; }
|
||||
.xfa-header-inheritance-hint { margin: 0; color: #9a3412; font-size: .76rem; line-height: 1.45; }
|
||||
|
||||
+17
-1
@@ -2,7 +2,8 @@
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfilePublishCheckPage.vue
|
||||
用途:展示版面签名、跨模板唯一性与发布阻断项,并在门禁通过后发布模板。
|
||||
依赖:发布检查 API、验证运行 API、Vue Router 和统一消息提示。
|
||||
逻辑:自动选择当前样本试读通过运行;服务端生成签名/重叠验证;阻断项不可绕过,语义差异须逐项确认。
|
||||
逻辑:自动选择当前样本试读通过运行;服务端生成签名/重叠验证;阻断项不可绕过,语义差异须逐项确认;
|
||||
XFA path 覆盖不全时展示 missing_fields 的 scope.field_code,避免同名 header/line 误判。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
@@ -158,6 +159,21 @@ async function publish(): Promise<void> {
|
||||
/** 归一化有限的已知门禁码;未知内容仍保留后端安全摘要。 */
|
||||
function itemMessage(item: Record<string, unknown>): string {
|
||||
const key = String(item.key || '');
|
||||
if (key === 'xfa_required_path_coverage_incomplete') {
|
||||
const missing = Array.isArray(item.missing_fields) ? item.missing_fields : [];
|
||||
const labels = missing
|
||||
.map((entry) => {
|
||||
if (!entry || typeof entry !== 'object') return '';
|
||||
const scope = String((entry as { scope?: string }).scope || '').trim();
|
||||
const code = String((entry as { field_code?: string }).field_code || '').trim();
|
||||
if (!code) return '';
|
||||
return scope ? `${scope}.${code}` : code;
|
||||
})
|
||||
.filter(Boolean);
|
||||
return t('admin.orderProfilePublishCheck.xfaRequiredPathCoverageIncomplete', {
|
||||
fields: labels.join(', ') || t('admin.orderProfilePublishCheck.xfaRequiredPathFieldsUnknown'),
|
||||
});
|
||||
}
|
||||
const map: Record<string, string> = {
|
||||
current_validation_required: t('admin.orderProfilePublishCheck.currentValidationRequired'),
|
||||
semantic_diff_review: t('admin.orderProfilePublishCheck.semanticDiffReview'),
|
||||
|
||||
+12
-8
@@ -8,7 +8,8 @@
|
||||
选中框用 top/right/bottom/left 定位(避免 height% 在内容撑高容器上失效);
|
||||
拖拽/缩放进行中忽略滚轮缩放,避免触控板纵向手势把高度调整抢走;
|
||||
绘制模式下仍允许操作当前选中框;整边 resize 热区便于矮标签拉高;
|
||||
画布区域 aria-label 走四语言 i18n;可选 emptyHint/loadError 区分 XFA page_unavailable 与 PDF 缺样本空态。
|
||||
画布区域 aria-label 走四语言 i18n;可选 emptyHint/loadError 区分 XFA page_unavailable 与 PDF 缺样本空态;
|
||||
订单字段标签在已有正式/OCR 值时优先展示,loading 仅在尚无值时显示「读取中」。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
@@ -352,7 +353,7 @@ const endCreation = () => {
|
||||
};
|
||||
|
||||
const selected = computed(() => new Set([props.selectedRegionId]));
|
||||
/** 在画布徽标展示字段身份和实际识别值;编辑态订单字段继续使用工作台即时读取状态。 */
|
||||
/** 在画布徽标展示字段身份和实际识别值;已有值优先于 loading 状态文案。 */
|
||||
const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
|
||||
if (readonlyMode.value && !['line', 'exclusion'].includes(region.kind)) {
|
||||
return `${region.label} · ${region.recognizedValue || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable')}`;
|
||||
@@ -369,12 +370,15 @@ const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
|
||||
}
|
||||
const state = props.orderFieldValueState || 'idle';
|
||||
const value = region.fieldCode ? props.orderFieldValues?.[region.fieldCode] : null;
|
||||
const suffix = state === 'loading'
|
||||
? t('admin.shippingOrderProfiles.workbench.orderFieldValueReading')
|
||||
: state === 'failed'
|
||||
? t('admin.shippingOrderProfiles.workbench.orderFieldValueFailed')
|
||||
// 新圈选的 XFA 值框先显示同次受控视觉回读;整页 PDFium/OCR 预览完成后再覆盖。
|
||||
: value || region.suggestedValue || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable');
|
||||
// 已有正式/OCR 值时优先展示;loading 仅在尚无值时显示「读取中」,避免与「未读取到值」叠字。
|
||||
const suffix = value
|
||||
? value
|
||||
: state === 'loading'
|
||||
? t('admin.shippingOrderProfiles.workbench.orderFieldValueReading')
|
||||
: state === 'failed'
|
||||
? t('admin.shippingOrderProfiles.workbench.orderFieldValueFailed')
|
||||
// 新圈选的 XFA 值框先显示同次受控视觉回读;整页 PDFium/OCR 预览完成后再覆盖。
|
||||
: region.suggestedValue || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable');
|
||||
return `${region.label} · ${suffix}`;
|
||||
};
|
||||
/** 以固定步进调整页面倍率;区域采用相对坐标,缩放后仍与图像精确对齐。 */
|
||||
|
||||
+20
@@ -194,4 +194,24 @@ describe('XfaDatasetTree', () => {
|
||||
await wrapper.find('[data-xfa-path-id="leaf"]').trigger('click');
|
||||
expect(wrapper.emitted('select-path')?.[0]).toEqual(['leaf', true]);
|
||||
});
|
||||
|
||||
it('expands sample display in picker mode without truncating the class layout', () => {
|
||||
const wrapper = mount(XfaDatasetTree, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
expandSamples: true,
|
||||
tree: {
|
||||
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
|
||||
is_leaf: false,
|
||||
children: [{
|
||||
path_id: 'leaf', local_name: 'NAME1', data_path_hash: 'h2', depth: 1, cardinality: 'one',
|
||||
is_leaf: true, sample_value_display: 'Cloud Network Technology Kft.', display_policy: 'full',
|
||||
}],
|
||||
},
|
||||
},
|
||||
});
|
||||
// 断言意图:弹窗选型模式启用 expandSamples,完整样本可出现在节点上。
|
||||
expect(wrapper.find('.xfa-tree').classes()).toContain('xfa-tree--expand-samples');
|
||||
expect(wrapper.find('.sample').text()).toBe('Cloud Network Technology Kft.');
|
||||
});
|
||||
});
|
||||
+23
-4
@@ -2,7 +2,8 @@
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaDatasetTree.vue
|
||||
用途:XFA 受控数据树;主工作台用于绑定导航,高级诊断抽屉内只读展示。
|
||||
依赖:vue-i18n、xfaProfileMapping.utils。
|
||||
逻辑:支持展开折叠、方向键导航与完整样本值展示;readonly 时隐藏增删改规则动作。
|
||||
逻辑:支持展开折叠、方向键导航与完整样本值展示;readonly 时隐藏增删改规则动作;
|
||||
expandSamples 用于弹窗选型场景,放宽样本列宽度并允许换行。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref } from 'vue';
|
||||
@@ -25,6 +26,8 @@ const props = defineProps<{
|
||||
splitRuleSets?: XfaSplitRuleSet[];
|
||||
/** 为 true 时隐藏新增/编辑/删除规则操作,仅保留选择与诊断。 */
|
||||
readonly?: boolean;
|
||||
/** 弹窗选型时放宽样本列展示,避免窄侧栏截断。 */
|
||||
expandSamples?: boolean;
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
'select-path': [pathId: string, isLeaf: boolean];
|
||||
@@ -40,6 +43,7 @@ const flat = computed(() => flattenXfaTreeNodes(props.tree || undefined));
|
||||
const collapsed = ref(new Set<string>());
|
||||
const focusedPathId = ref('');
|
||||
const isReadonly = computed(() => Boolean(props.readonly));
|
||||
const expandSamples = computed(() => Boolean(props.expandSamples));
|
||||
const visible = computed(() => {
|
||||
const filtered = filterXfaTreeNodes(flat.value, query.value);
|
||||
if (query.value.trim()) return filtered;
|
||||
@@ -78,7 +82,9 @@ function toggle(pathId: string): void {
|
||||
* @param node 扁平树节点
|
||||
*/
|
||||
function pathTitle(node: XfaFlatTreeNode): string {
|
||||
return buildXfaPathLabel(node.pathId, flat.value);
|
||||
const path = buildXfaPathLabel(node.pathId, flat.value);
|
||||
const sample = String(node.sampleValueDisplay || '').trim();
|
||||
return sample ? `${path} · ${sample}` : path;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -151,7 +157,11 @@ async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-tree" :aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.treeTitle')">
|
||||
<section
|
||||
class="xfa-tree"
|
||||
:class="{ 'xfa-tree--expand-samples': expandSamples }"
|
||||
:aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.treeTitle')"
|
||||
>
|
||||
<label class="xfa-tree__search">
|
||||
<span class="sr-only">{{ t('admin.shippingOrderProfiles.xfaWorkbench.searchPaths') }}</span>
|
||||
<input v-model="query" type="search" :placeholder="t('admin.shippingOrderProfiles.xfaWorkbench.searchPaths')" />
|
||||
@@ -198,7 +208,7 @@ 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="node.sampleValueDisplay" class="sample">
|
||||
<span v-if="node.sampleValueDisplay" class="sample" :title="node.sampleValueDisplay">
|
||||
{{ node.sampleValueDisplay }}
|
||||
</span>
|
||||
</div>
|
||||
@@ -250,6 +260,15 @@ async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
|
||||
.xfa-tree__node .name { min-width: 0; overflow: hidden; font-size: .82rem; line-height: 1.2; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.xfa-tree__node .path-hint { min-width: 0; overflow: hidden; color: var(--text-muted); font-size: .64rem; line-height: 1.2; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.xfa-tree__node .sample { min-width: 3.2rem; margin-left: auto; max-width: 30%; overflow: hidden; color: var(--text-muted); font-size: .68rem; text-align: right; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.xfa-tree--expand-samples .xfa-tree__node { align-items: flex-start; }
|
||||
.xfa-tree--expand-samples .xfa-tree__node .sample {
|
||||
max-width: 48%;
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
word-break: break-word;
|
||||
line-height: 1.25;
|
||||
text-align: left;
|
||||
}
|
||||
.xfa-tree__node .badge { color: var(--status-warning-fg); font-size: .72rem; font-weight: 700; }
|
||||
.toggle, .toggle-spacer { display: inline-flex; width: 16px; flex: 0 0 16px; }
|
||||
.add-rule { display: none; position: relative; z-index: 1; min-width: 24px; min-height: 24px; align-items: center; justify-content: center; margin-left: 2px; border: 1px solid transparent; border-radius: 5px; background: transparent; color: var(--status-info-fg); font-size: 1rem; line-height: 1; cursor: pointer; }
|
||||
|
||||
+132
-3
@@ -2,6 +2,7 @@
|
||||
* features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.spec.ts
|
||||
* 用途:验证 XfaSplitRulePanel pipeline 规则增删、确认门禁、order 重排与完整值预览。
|
||||
* 依赖:Vitest、@vue/test-utils、shipping-order-document-profile API mock。
|
||||
* 逻辑:确认门禁须忽略 line_match_candidates 等 informational 诊断,仅阻断真实冲突。
|
||||
*/
|
||||
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
@@ -87,6 +88,7 @@ const xfaSplitMessages = {
|
||||
previewNoSegments: '无段',
|
||||
previewValue: '值',
|
||||
previewRuleStatus: '状态',
|
||||
fullValuesRevealed: '当前预览为完整值',
|
||||
diagnostics: '诊断',
|
||||
ruleSetSettings: '规则集',
|
||||
normalization: '归一化',
|
||||
@@ -374,6 +376,56 @@ describe('XfaSplitRulePanel', () => {
|
||||
expect(confirmed).toBeFalsy();
|
||||
});
|
||||
|
||||
it('allows confirm when only informational line_match_candidates diagnostics exist', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview_token: 'tok-info-diag',
|
||||
preview: {
|
||||
status: 'parsed',
|
||||
mapped_fields: {},
|
||||
segments: [
|
||||
{
|
||||
segment_id: 'seg-1',
|
||||
segment_code: 'customer_part_number',
|
||||
rule_id: 'rule-1',
|
||||
matcher_type: 'position',
|
||||
normalized_text: 'CPN',
|
||||
raw_text: 'CPN',
|
||||
status: 'parsed',
|
||||
line_no: 1,
|
||||
},
|
||||
{
|
||||
segment_id: 'unmatched-2',
|
||||
segment_code: 'unmatched_line_2',
|
||||
rule_id: 'unmatched',
|
||||
matcher_type: 'unmatched',
|
||||
normalized_text: 'noise',
|
||||
raw_text: 'noise',
|
||||
status: 'parsed',
|
||||
line_no: 2,
|
||||
},
|
||||
],
|
||||
evidence_only_segments: [],
|
||||
diagnostics: [
|
||||
{ code: 'line_match_candidates', message: 'All matcher hits for line recorded', line_no: 1 },
|
||||
{ code: 'line_match_candidates', message: 'All matcher hits for line recorded', line_no: 2 },
|
||||
],
|
||||
},
|
||||
});
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
split_rules: [makePipelineRuleSet()],
|
||||
},
|
||||
});
|
||||
await exposedActions(wrapper).runPreview();
|
||||
await flushPromises();
|
||||
expect(wrapper.text()).not.toContain('line_match_candidates');
|
||||
exposedActions(wrapper).confirmRules();
|
||||
expect(messageError).not.toHaveBeenCalledWith('诊断阻断');
|
||||
const confirmed = wrapper.emitted('confirmed');
|
||||
expect(confirmed?.[0]?.[1]).toMatchObject({ 'path-matnr': 'tok-info-diag' });
|
||||
});
|
||||
|
||||
it('blocks confirm when a mapped segment has no Schema target', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview_token: 'tok-mapped-empty',
|
||||
@@ -422,6 +474,13 @@ describe('XfaSplitRulePanel', () => {
|
||||
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
|
||||
const range = last?.[0]?.rules?.[0]?.stages?.find((stage) => stage.type === 'select_line_range');
|
||||
expect(range).toMatchObject({ line_start: 1, line_end: 2, join_with: 'newline' });
|
||||
// 断言意图:正式 matcher 须带 line_end/join_with,不能只投影成单行 line_index。
|
||||
expect(last?.[0]?.rules?.[0]?.matcher).toMatchObject({
|
||||
type: 'position',
|
||||
line_index: 1,
|
||||
line_end: 2,
|
||||
join_with: 'newline',
|
||||
});
|
||||
const rangeWrapper = mountPanel({
|
||||
definition: { ...baseDefinition, split_rules: last },
|
||||
});
|
||||
@@ -430,6 +489,63 @@ describe('XfaSplitRulePanel', () => {
|
||||
expect(rangeWrapper.text()).toContain('合并方式');
|
||||
});
|
||||
|
||||
it('previews consecutive line extraction with line_end and join_with in formal payload', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview_token: 'tok-range',
|
||||
preview: {
|
||||
status: 'ok',
|
||||
mapped_fields: {},
|
||||
segments: [{
|
||||
segment_id: 'seg-addr',
|
||||
segment_code: 'bill_to_address',
|
||||
rule_id: 'rule-1',
|
||||
matcher_type: 'position',
|
||||
line_no: 2,
|
||||
line_end_no: 4,
|
||||
normalized_text: 'Bánki Donát u. 1.\n2900 Komárom\nHungary',
|
||||
raw_text: 'Bánki Donát u. 1.\n2900 Komárom\nHungary',
|
||||
status: 'parsed',
|
||||
}],
|
||||
evidence_only_segments: [],
|
||||
diagnostics: [],
|
||||
full_values_revealed: true,
|
||||
},
|
||||
});
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
split_rules: [makePipelineRuleSet({
|
||||
rules: [{
|
||||
...makePipelineRuleSet().rules[0],
|
||||
matcher: { type: 'position', line_index: 2, line_end: 4, join_with: 'newline' },
|
||||
stages: [
|
||||
{ stage_id: 'split', type: 'split_lines', line_breaks: ['\\n'] },
|
||||
{ stage_id: 'range', type: 'select_line_range', line_start: 2, line_end: 4, join_with: 'newline' },
|
||||
],
|
||||
}],
|
||||
})],
|
||||
},
|
||||
});
|
||||
await exposedActions(wrapper).runPreview();
|
||||
await flushPromises();
|
||||
expect(previewMock).toHaveBeenCalledWith(85, expect.objectContaining({
|
||||
reveal: true,
|
||||
rule_set: expect.objectContaining({
|
||||
rules: [expect.objectContaining({
|
||||
matcher: expect.objectContaining({
|
||||
type: 'position',
|
||||
line_index: 2,
|
||||
line_end: 4,
|
||||
join_with: 'newline',
|
||||
}),
|
||||
})],
|
||||
}),
|
||||
}));
|
||||
expect(wrapper.text()).toContain('Bánki Donát u. 1.');
|
||||
expect(wrapper.text()).toContain('2900 Komárom');
|
||||
expect(wrapper.text()).toContain('Hungary');
|
||||
});
|
||||
|
||||
it('emits the final confirmed rules for parent persistence', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview_token: 'tok-preview-1',
|
||||
@@ -578,15 +694,25 @@ describe('XfaSplitRulePanel', () => {
|
||||
expect(rules?.[0]?.rules).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('previews full values without a reveal permission parameter', async () => {
|
||||
it('previews split rules with reveal so mapped values are not masked', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview: {
|
||||
status: 'ok',
|
||||
mapped_fields: {},
|
||||
segments: [],
|
||||
segments: [
|
||||
{
|
||||
segment_id: 's1',
|
||||
segment_code: 'bill_to_customer',
|
||||
normalized_text: 'Cloud Network Technology Kft.',
|
||||
raw_text: 'Cloud Network Technology Kft.',
|
||||
status: 'parsed',
|
||||
},
|
||||
],
|
||||
evidence_only_segments: [],
|
||||
diagnostics: [],
|
||||
full_values_revealed: true,
|
||||
},
|
||||
preview_token: 'tok-full',
|
||||
});
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
@@ -596,7 +722,10 @@ describe('XfaSplitRulePanel', () => {
|
||||
});
|
||||
await exposedActions(wrapper).runPreview();
|
||||
await flushPromises();
|
||||
expect(previewMock).toHaveBeenCalledWith(85, expect.not.objectContaining({ reveal: expect.anything() }));
|
||||
// 断言意图:文档模板拆分预览与侧栏同源,必须带 reveal 以免分段值被遮蔽。
|
||||
expect(previewMock).toHaveBeenCalledWith(85, expect.objectContaining({ reveal: true }));
|
||||
expect(wrapper.text()).toContain('Cloud Network Technology Kft.');
|
||||
expect(wrapper.text()).not.toContain('Clou***');
|
||||
});
|
||||
|
||||
it('sends formal matcher post-processors instead of UI-only pipeline fields to preview', async () => {
|
||||
|
||||
+87
-16
@@ -3,7 +3,10 @@
|
||||
用途:XFA 字段拆分规则编辑——matcher 优先(prefix/regex/position),兼容历史 stages[] 投影。
|
||||
依赖:shipping-order-document-profile API、vue-i18n、Schema 字段列表。
|
||||
逻辑:编辑 definition.split_rules;新增/改提取方式同步写入 matcher;stages 仅保留编辑态;
|
||||
预览和确认统一投影为正式 matcher DTO,确认前须校验同一正式 DTO 哈希。
|
||||
预览和确认统一投影为正式 matcher DTO,确认前须校验同一正式 DTO 哈希;
|
||||
连续多行提取投影为 position.line_end + join_with,引擎合并多行文本;
|
||||
预览优先 reveal 完整分段值(与映射台侧栏/数据源弹窗一致),权限不足再回退脱敏;
|
||||
确认门禁仅阻断真正影响取值可信度的诊断(与后端 informational 白名单对齐)。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
@@ -36,6 +39,15 @@ type XfaSplitRulePatch = Omit<Partial<XfaSplitRule>, 'segment' | 'stages' | 'mat
|
||||
|
||||
type XfaSplitStagePatch = Partial<XfaSplitStage>;
|
||||
type ExtractionMode = 'select_line' | 'select_line_range' | 'extract_prefix' | 'regex_capture' | 'substring';
|
||||
type XfaSplitPreviewDiagnostic = XfaSplitPreviewResult['diagnostics'][number];
|
||||
|
||||
/**
|
||||
* 与后端 xfa_profile_extraction._SPLIT_INFORMATIONAL_DIAGNOSTIC_CODES 对齐。
|
||||
* line_match_candidates 仅记录命中审计,不表示歧义;未配置规则的行在 evidence_only 下也不应阻断确认。
|
||||
*/
|
||||
const SPLIT_INFORMATIONAL_DIAGNOSTIC_CODES = new Set([
|
||||
'line_match_candidates',
|
||||
]);
|
||||
|
||||
const props = defineProps<{
|
||||
definition: OrderXfaDatasetProfileDefinition;
|
||||
@@ -75,6 +87,23 @@ const SEGMENT_CODE_RE = /^[a-z][a-z0-9_]{1,63}$/;
|
||||
|
||||
const isReadonly = computed(() => props.readonly || props.canEdit === false);
|
||||
|
||||
/**
|
||||
* 判断诊断码是否会阻断确认(排除仅审计用的 informational 码)。
|
||||
* @param code - 预览诊断 code
|
||||
* @returns true 表示须阻断确认
|
||||
*/
|
||||
function isBlockingSplitDiagnostic(code: string | null | undefined): boolean {
|
||||
if (!code) return true;
|
||||
return !SPLIT_INFORMATIONAL_DIAGNOSTIC_CODES.has(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* 预览中真正影响确认/取值可信度的诊断列表(过滤 line_match_candidates 等审计项)。
|
||||
*/
|
||||
const blockingDiagnostics = computed((): XfaSplitPreviewDiagnostic[] => (
|
||||
(preview.value?.diagnostics || []).filter((item) => isBlockingSplitDiagnostic(item.code))
|
||||
));
|
||||
|
||||
/** 可被拆分段正式写入的字段;Schema 外字段只能作为 evidence 保留。 */
|
||||
const splitTargetFields = computed(() => (props.schemaFields || []).filter((field) => (
|
||||
field.enabled !== false && Boolean(field.field_id && field.field_code)
|
||||
@@ -228,6 +257,7 @@ function createDefaultPipelineStages(lineIndex = 1): XfaSplitStage[] {
|
||||
|
||||
/**
|
||||
* 由提取模式与阶段参数生成正式 matcher(prefix > regex > position)。
|
||||
* 连续多行写入 position.line_end + join_with,供引擎合并多行文本。
|
||||
*/
|
||||
function matcherFromExtraction(mode: ExtractionMode, stage: Partial<XfaSplitStage>, order: number): XfaSplitMatcher {
|
||||
if (mode === 'extract_prefix') {
|
||||
@@ -246,6 +276,16 @@ function matcherFromExtraction(mode: ExtractionMode, stage: Partial<XfaSplitStag
|
||||
case_sensitive: Boolean(stage.case_sensitive),
|
||||
};
|
||||
}
|
||||
if (mode === 'select_line_range') {
|
||||
const lineStart = Number(stage.line_start || order || 1);
|
||||
const lineEnd = Number(stage.line_end || lineStart);
|
||||
return {
|
||||
type: 'position',
|
||||
line_index: lineStart,
|
||||
line_end: Math.max(lineEnd, lineStart),
|
||||
join_with: (stage.join_with || 'newline') as 'newline' | 'space' | 'comma',
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: 'position',
|
||||
line_index: Number(stage.line_index || stage.line_start || order || 1),
|
||||
@@ -301,18 +341,33 @@ 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 formalRuleSet = toFormalRuleSet(activeRuleSet.value);
|
||||
const result = await previewOrderProfileSampleXfaSplitRules(props.documentId, {
|
||||
const payload = {
|
||||
path_id: props.selectedPathId,
|
||||
rule_set: formalRuleSet || {},
|
||||
profile_id: props.profileId,
|
||||
});
|
||||
};
|
||||
let result;
|
||||
try {
|
||||
// [STEP 1] 映射台配置场景优先完整值,避免 Clou***ft 类遮蔽干扰规则校验。
|
||||
result = await previewOrderProfileSampleXfaSplitRules(props.documentId, {
|
||||
...payload,
|
||||
reveal: true,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof BusinessError && error.code === 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_VALUE_FORBIDDEN') {
|
||||
result = await previewOrderProfileSampleXfaSplitRules(props.documentId, payload);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
preview.value = result.preview;
|
||||
previewRuleSetHash.value = hashRuleSet(activeRuleSet.value);
|
||||
previewConfirmationToken.value = String(result.preview_token || '') || null;
|
||||
@@ -324,8 +379,9 @@ async function runPreview(): Promise<void> {
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员确认规则:须已预览当前 rule_set;诊断或 needs_review 时阻断。
|
||||
* 核心逻辑:确认事件携带完整规则数组与 preview_token,由父页面保存时交服务端校验。
|
||||
* 管理员确认规则:须已预览当前 rule_set;阻断性诊断或 needs_review 时阻断。
|
||||
* 核心逻辑:确认事件携带完整规则数组与 preview_token,由父页面保存时交服务端校验;
|
||||
* line_match_candidates 与未匹配行(evidence_only)不视为阻断。
|
||||
*/
|
||||
function confirmRules(): void {
|
||||
if (!activeRuleSet.value || isReadonly.value) return;
|
||||
@@ -341,13 +397,13 @@ function confirmRules(): void {
|
||||
message.error(t('admin.shippingOrderProfiles.xfaSplit.confirmNeedsPreview'));
|
||||
return;
|
||||
}
|
||||
if (preview.value.status === 'needs_review' || (preview.value.diagnostics || []).length > 0) {
|
||||
if (preview.value.status === 'needs_review' || blockingDiagnostics.value.length > 0) {
|
||||
message.error(t('admin.shippingOrderProfiles.xfaSplit.confirmBlockedDiagnostics'));
|
||||
return;
|
||||
}
|
||||
const ruleCount = activeRuleSet.value.rules.length;
|
||||
const segmentCount = (preview.value.segments || []).length;
|
||||
const diagCount = (preview.value.diagnostics || []).length;
|
||||
const diagCount = blockingDiagnostics.value.length;
|
||||
const summary = t('admin.shippingOrderProfiles.xfaSplit.confirmDialog', {
|
||||
rules: ruleCount,
|
||||
segments: segmentCount,
|
||||
@@ -464,9 +520,19 @@ function extractionStage(rule: XfaSplitRule): XfaSplitStage {
|
||||
};
|
||||
}
|
||||
if (rule.matcher?.type === 'position') {
|
||||
const lineStart = rule.matcher.line_index ?? rule.order ?? 1;
|
||||
const lineEnd = rule.matcher.line_end ?? lineStart;
|
||||
if (Number(lineEnd) > Number(lineStart)) {
|
||||
return {
|
||||
...createDefaultStage('select_line_range'),
|
||||
line_start: lineStart,
|
||||
line_end: lineEnd,
|
||||
join_with: rule.matcher.join_with || 'newline',
|
||||
};
|
||||
}
|
||||
return {
|
||||
...createDefaultStage('select_line'),
|
||||
line_index: rule.matcher.line_index ?? rule.order ?? 1,
|
||||
line_index: lineStart,
|
||||
};
|
||||
}
|
||||
return { ...createDefaultStage('select_line'), line_index: rule.order ?? 1 };
|
||||
@@ -474,12 +540,16 @@ function extractionStage(rule: XfaSplitRule): XfaSplitStage {
|
||||
|
||||
function extractionMode(rule: XfaSplitRule): ExtractionMode {
|
||||
const stages = rule.stages || [];
|
||||
// 连续行/截取仍靠 stages 驱动 UI;正式 matcher 用 position 近似。
|
||||
// 连续行/截取仍可靠 stages 驱动 UI;正式 matcher 也可用 line_end 表达连续多行。
|
||||
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';
|
||||
if (rule.matcher?.type === 'position') {
|
||||
const start = Number(rule.matcher.line_index || 0);
|
||||
const end = Number(rule.matcher.line_end || start);
|
||||
return end > start ? 'select_line_range' : 'select_line';
|
||||
}
|
||||
return extractionStage(rule).type as ExtractionMode;
|
||||
}
|
||||
|
||||
@@ -907,9 +977,9 @@ watch(activeRuleSet, (current, previous) => {
|
||||
</table>
|
||||
<p v-else class="hint">{{ t('admin.shippingOrderProfiles.xfaSplit.previewNoSegments') }}</p>
|
||||
|
||||
<h5 v-if="preview.diagnostics?.length">{{ t('admin.shippingOrderProfiles.xfaSplit.diagnostics') }}</h5>
|
||||
<ul v-if="preview.diagnostics?.length" class="xfa-split__diagnostics">
|
||||
<li v-for="(diag, idx) in preview.diagnostics" :key="`${diag.code}-${idx}`">
|
||||
<h5 v-if="blockingDiagnostics.length">{{ t('admin.shippingOrderProfiles.xfaSplit.diagnostics') }}</h5>
|
||||
<ul v-if="blockingDiagnostics.length" class="xfa-split__diagnostics">
|
||||
<li v-for="(diag, idx) in blockingDiagnostics" :key="`${diag.code}-${idx}`">
|
||||
<strong>{{ diag.code }}</strong>: {{ diag.message }}
|
||||
<small v-if="diag.line_no">L{{ diag.line_no }}</small>
|
||||
</li>
|
||||
@@ -1333,8 +1403,8 @@ watch(activeRuleSet, (current, previous) => {
|
||||
.xfa-split__rule-title .rule-chevron { width: 12px; color: var(--status-info-fg); font-size: 1rem; }
|
||||
.xfa-split__rule-detail { display: grid; gap: 6px; }
|
||||
.xfa-split__extraction { display: grid; grid-template-columns: minmax(180px, 1fr) minmax(160px, .7fr); gap: 8px 12px; padding: 10px; border: 1px solid var(--status-info-border); border-radius: 6px; background: var(--status-info-bg); }
|
||||
.xfa-split__inline-preview { grid-column: 1 / -1; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding-top: 7px; border-top: 1px solid var(--status-info-border); color: var(--text-muted); font-size: .75rem; }
|
||||
.xfa-split__inline-preview strong { max-width: 70%; overflow: hidden; color: var(--status-success-fg); text-overflow: ellipsis; white-space: nowrap; }
|
||||
.xfa-split__inline-preview { grid-column: 1 / -1; display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding-top: 7px; border-top: 1px solid var(--status-info-border); color: var(--text-muted); font-size: .75rem; }
|
||||
.xfa-split__inline-preview strong { max-width: 70%; overflow: hidden; color: var(--status-success-fg); white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.xfa-split__advanced-toggle { justify-self: start; padding: 3px 0; border: 0; background: transparent; color: var(--status-info-fg); cursor: pointer; font-size: .75rem; }
|
||||
.xfa-split__rule-actions { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
.xfa-split__rule-actions button { padding: 2px 6px; font-size: 0.72rem; border: 1px solid var(--border-default); border-radius: 4px; background: var(--bg-page); cursor: pointer; }
|
||||
@@ -1349,6 +1419,7 @@ watch(activeRuleSet, (current, previous) => {
|
||||
.xfa-split__preview h4, .xfa-split__preview h5 { margin: 8px 0 4px; font-size: 0.85rem; }
|
||||
.xfa-split__table { width: 100%; border-collapse: collapse; font-size: 0.75rem; }
|
||||
.xfa-split__table th, .xfa-split__table td { border: 1px solid var(--border-default); padding: 4px 6px; text-align: left; vertical-align: top; }
|
||||
.xfa-split__table td:nth-child(4) { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.xfa-split__diagnostics li { font-size: 0.8rem; color: var(--status-warning-fg); }
|
||||
.xfa-split__hint-error { color: var(--status-error-fg); font-size: 0.72rem; }
|
||||
.xfa-split__invalid { border-color: var(--status-error-border); }
|
||||
|
||||
+1100
-5
File diff suppressed because it is too large.
Load diff
+932
-106
File diff suppressed because it is too large.
Load diff
+35
-1
@@ -2,7 +2,8 @@
|
||||
* features/admin/modules/shipping-order-document-profiles/orderProfileForm.utils.spec.ts
|
||||
* 用途:验证可视化订单模板表单生成受控规则、明细字段分组,并确保切换样本时配置入口不会消失。
|
||||
* 依赖:Vitest、orderProfileForm.utils。
|
||||
* 逻辑:覆盖 direct、复合解析器开关及跨列冲突,避免无效配置进入后端。
|
||||
* 逻辑:覆盖 direct、复合解析器开关及跨列冲突,避免无效配置进入后端;
|
||||
* XFA 识别结果在 OCR 空值时用 datasets header_fields 增量补齐。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
@@ -269,6 +270,37 @@ describe('order profile form rules', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('overlays XFA datasets header_fields when OCR header values are empty', () => {
|
||||
const regions = [
|
||||
{ id: 'date-box', kind: 'order_field' as const, label: 'Date', fieldCode: 'order_date', pageNo: 1, region: { x0: .4, y0: .1, x1: .6, y1: .15 } },
|
||||
{ id: 'currency-box', kind: 'order_field' as const, label: 'Currency', fieldCode: 'currency', pageNo: 1, region: { x0: .6, y0: .1, x1: .7, y1: .15 } },
|
||||
{ id: 'po-box', kind: 'order_field' as const, label: 'PO', fieldCode: 'customer_po_number', pageNo: 1, region: { x0: .1, y0: .1, x1: .3, y1: .15 } },
|
||||
];
|
||||
|
||||
const results = buildOrderProfileRecognitionResults(
|
||||
regions,
|
||||
[{ field_id: 'po', field_code: 'customer_po_number', value: '4510039227', source: 'ocr_coordinate', status: 'confirmed', page_no: 1, issues: [] }],
|
||||
null,
|
||||
'loading',
|
||||
{
|
||||
header_fields: [
|
||||
{ field_id: 'date', field_code: 'order_date', raw_value: '2024-05-20', normalized_value: '2024-05-20', status: 'passed', issues: [] },
|
||||
{ field_id: 'currency', field_code: 'currency', raw_value: 'USD', normalized_value: 'USD', status: 'passed', issues: [] },
|
||||
{ field_id: 'po', field_code: 'customer_po_number', raw_value: 'DATASET-PO', normalized_value: 'DATASET-PO', status: 'passed', issues: [] },
|
||||
],
|
||||
lines: [],
|
||||
cross_checks: {},
|
||||
},
|
||||
);
|
||||
|
||||
// datasets 只增量补齐 OCR 空值;已有 OCR 值(PO)不得被 datasets 覆盖。
|
||||
expect(results.header).toMatchObject([
|
||||
{ id: 'date-box', fieldCode: 'order_date', value: '2024-05-20', status: 'read' },
|
||||
{ id: 'currency-box', fieldCode: 'currency', value: 'USD', status: 'read' },
|
||||
{ id: 'po-box', fieldCode: 'customer_po_number', value: '4510039227', status: 'read' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('selects only the current XFA validation evidence for the active draft checksum', () => {
|
||||
const evidence = {
|
||||
header_fields: [], lines: [{ row_index: 0, fields: [] }], cross_checks: {},
|
||||
@@ -345,11 +377,13 @@ describe('order profile form rules', () => {
|
||||
it('serializes accepted header fields with header scope', () => {
|
||||
// 表头候选接受后必须进入 header_layouts;写成 line 会被后端契约拒绝,导致表头刷新后消失。
|
||||
expect(toOrderProfileHeaderFieldRegion({
|
||||
id: 'header_field_1_1',
|
||||
fieldCode: 'delivery_date',
|
||||
region: { x0: .2, y0: .1, x1: .4, y1: .16 },
|
||||
})).toEqual({
|
||||
field_id: '', field_code: 'delivery_date', scope: 'header',
|
||||
region: { x0: .2, y0: .1, x1: .4, y1: .16 },
|
||||
region_id: 'header_field_1_1',
|
||||
extractor_key: 'direct', allowed_sources: ['pdf_coordinate'], minimum_evidence_level: 'coordinate',
|
||||
});
|
||||
expect(toOrderProfileHeaderFieldRegion({
|
||||
|
||||
+33
-5
@@ -3,7 +3,8 @@
|
||||
* 用途:构造可视化订单模板的白名单列规则、明细字段分组,并控制样本表格配置区的安全显示。
|
||||
* 依赖:订单 Profile DTO。
|
||||
* 逻辑:页面状态只允许 direct 或已注册复合解析器;同一目标字段跨列只能出现一次;
|
||||
* 另提供「未绑定订单字段」判定,供画布强制高亮与编辑横幅共用。
|
||||
* 另提供「未绑定订单字段」判定,供画布强制高亮与编辑横幅共用;
|
||||
* 表头/明细 field_regions 可带 region_id,供 XFA binding 按画布框精确定位。
|
||||
*/
|
||||
|
||||
import type {
|
||||
@@ -60,7 +61,7 @@ export const isUnboundOrderFieldCanvasRegion = (
|
||||
* @returns 可持久化的表头字段区域;没有 fieldCode 时返回 null。
|
||||
*/
|
||||
export const toOrderProfileHeaderFieldRegion = (
|
||||
item: Pick<OrderProfileCanvasRegion, 'fieldCode' | 'region'>,
|
||||
item: Pick<OrderProfileCanvasRegion, 'id' | 'fieldCode' | 'region'>,
|
||||
scope: 'header' | 'line' = 'header',
|
||||
): OrderProfileFieldRegion | null => {
|
||||
if (!item.fieldCode) return null;
|
||||
@@ -69,6 +70,7 @@ export const toOrderProfileHeaderFieldRegion = (
|
||||
field_code: item.fieldCode,
|
||||
scope,
|
||||
region: item.region,
|
||||
region_id: item.id || null,
|
||||
extractor_key: 'direct',
|
||||
allowed_sources: ['pdf_coordinate'],
|
||||
minimum_evidence_level: 'coordinate',
|
||||
@@ -141,8 +143,14 @@ export const restoreFormalBindingFieldCodes = (
|
||||
const fieldCodeByRegionId = new Map<string, string>();
|
||||
for (const region of existingRegions) {
|
||||
if (region.kind !== 'field' || !region.parentId || !region.fieldCode) continue;
|
||||
const layoutId = `${region.parentId}:${region.fieldCode}`;
|
||||
if (formalBindingLayoutIds.has(layoutId)) fieldCodeByRegionId.set(region.id, region.fieldCode);
|
||||
// 新身份:region.id;旧身份:parent:fieldCode。任一命中正式 binding 即可恢复。
|
||||
const legacyLayoutId = `${region.parentId}:${region.fieldCode}`;
|
||||
if (
|
||||
formalBindingLayoutIds.has(region.id)
|
||||
|| formalBindingLayoutIds.has(legacyLayoutId)
|
||||
) {
|
||||
fieldCodeByRegionId.set(region.id, region.fieldCode);
|
||||
}
|
||||
}
|
||||
return suggestedRegions.map((region) => {
|
||||
if (region.kind !== 'field' || region.fieldCode) return region;
|
||||
@@ -623,9 +631,14 @@ export const buildOrderProfileCanvasLineFieldValues = (
|
||||
|
||||
/**
|
||||
* 将已有坐标预览和值读取结果变为可反向定位的结构化复核项。
|
||||
* 核心逻辑:OCR/PDFium 表头结果始终保留;若传入 datasets 当前样本证据,则用
|
||||
* header_fields 增量补齐 OCR 为空的表头(订单日期/币种等),明细仅消费 datasets.lines。
|
||||
* @param pageRegions - 当前页画布区域;未标注字段不会伪装成可定位项。
|
||||
* @param fieldValues - 订单表头字段值接口的结果。
|
||||
* @param reconstruction - 坐标重建接口的明细行结果。
|
||||
* @param fieldValueState - 表头 OCR 读取状态。
|
||||
* @param datasetsEvidence - XFA 当前样本正式证据;有则忽略 coordinate reconstruction。
|
||||
* @param reservationCandidates - Reservation 专区候选。
|
||||
* @returns 表头及明细字段结果,均保留对应画布区域 ID。
|
||||
*/
|
||||
export const buildOrderProfileRecognitionResults = (
|
||||
@@ -660,6 +673,21 @@ export const buildOrderProfileRecognitionResults = (
|
||||
// XFA datasets 是正式明细值源;共同视觉坐标只定位和交叉校验,不能把表头或
|
||||
// OCR 候选伪装成已读取的行值。传入此证据时完全忽略 coordinate reconstruction。
|
||||
if (datasetsEvidence) {
|
||||
// [STEP] OCR 为空时用 datasets header_fields 增量补齐,避免 XFA 外观页表头永久「未读取到值」。
|
||||
const formalHeaderByCode = new Map(
|
||||
datasetsEvidence.header_fields.map((field) => [field.field_code, field]),
|
||||
);
|
||||
const mergedHeader = header.map((item) => {
|
||||
if (item.value) return item;
|
||||
const formal = formalHeaderByCode.get(item.fieldCode);
|
||||
const formalValue = formal?.normalized_value || null;
|
||||
if (!formalValue) return item;
|
||||
return {
|
||||
...item,
|
||||
value: formalValue,
|
||||
status: 'read' as const,
|
||||
};
|
||||
});
|
||||
const line = datasetsEvidence.lines.flatMap((row) => (
|
||||
row.fields.map((field) => ({
|
||||
id: regionsByCode.get(field.field_code) || null,
|
||||
@@ -673,7 +701,7 @@ export const buildOrderProfileRecognitionResults = (
|
||||
}))
|
||||
));
|
||||
return applyReservationRegionRecognitionResults(
|
||||
header, line, reservationCandidates, datasetsEvidence.lines.length,
|
||||
mergedHeader, line, reservationCandidates, datasetsEvidence.lines.length,
|
||||
);
|
||||
}
|
||||
if (!reconstruction) {
|
||||
|
||||
+16
@@ -113,6 +113,22 @@ describe('xfaProfileMapping split utils', () => {
|
||||
expect(matnr?.lineCount).toBe(5);
|
||||
});
|
||||
|
||||
it('flattenXfaTreeNodes does not fall back to masked sample asterisks', () => {
|
||||
const tree: XfaFieldTreeNode = {
|
||||
path_id: 'netpr',
|
||||
local_name: 'NETPR',
|
||||
data_path_hash: 'h-netpr',
|
||||
depth: 0,
|
||||
cardinality: 'one',
|
||||
is_leaf: true,
|
||||
sample_value_masked: '***',
|
||||
};
|
||||
const flat = flattenXfaTreeNodes(tree);
|
||||
// 断言意图:与选择数据源弹窗一致,缺 display 时保持空,不展示 ***。
|
||||
expect(flat[0]?.sampleValueDisplay).toBe('');
|
||||
expect(flat[0]?.sampleValueMasked).toBe('***');
|
||||
});
|
||||
|
||||
it('selectedIsMultiline uses lineCount greater than one', () => {
|
||||
const tree: XfaFieldTreeNode = {
|
||||
path_id: 'single',
|
||||
|
||||
+5
-3
@@ -2,7 +2,8 @@
|
||||
* features/admin/modules/shipping-order-document-profiles/xfaProfileMapping.utils.ts
|
||||
* 用途:XFA 映射工作台纯函数——树投影、Schema 过滤、覆盖率、保存 payload 与脏状态检测。
|
||||
* 依赖:shipping-order-document-profile.types、订单 Schema 字段类型。
|
||||
* 逻辑:页面与组件只调用本文件;不发网络请求,不持有明文 XML 或 data_path。
|
||||
* 逻辑:页面与组件只调用本文件;不发网络请求,不持有明文 XML 或 data_path;
|
||||
* 扁平树样本展示只用 sample_value_display,与选择数据源弹窗一致,禁止回退脱敏 ***。
|
||||
*/
|
||||
|
||||
import type {
|
||||
@@ -40,7 +41,7 @@ export interface XfaMappingWorkbenchState {
|
||||
|
||||
/**
|
||||
* 将 XFA 字段树投影为可键盘导航的扁平节点列表。
|
||||
* 核心逻辑:深度优先展开;仅保留分析记录返回的节点。
|
||||
* 核心逻辑:深度优先展开;样本展示仅取 sample_value_display(与弹窗一致),不回退脱敏。
|
||||
* @param tree 字段树根节点
|
||||
* @returns 扁平节点(含 depth / leaf / collection 标记)
|
||||
*/
|
||||
@@ -57,7 +58,8 @@ export function flattenXfaTreeNodes(tree: XfaFieldTreeNode | null | undefined):
|
||||
isHeaderCandidate: Boolean(node.is_header_candidate),
|
||||
isCollectionCandidate: Boolean(node.is_collection_candidate),
|
||||
sampleValueMasked: node.sample_value_masked,
|
||||
sampleValueDisplay: node.sample_value_display || node.sample_value_masked,
|
||||
// 映射台/弹窗样本与侧栏同源:只用受控 sample_value_display,禁止回退脱敏 ***。
|
||||
sampleValueDisplay: node.sample_value_display || '',
|
||||
displayPolicy: node.display_policy || 'empty',
|
||||
canReveal: Boolean(node.can_reveal),
|
||||
lineCount: node.line_count,
|
||||
|
||||
@@ -69,7 +69,18 @@ export interface OrderProfileCoordinateModel {
|
||||
max_translate_x?: number;
|
||||
max_translate_y?: number;
|
||||
}
|
||||
export interface OrderProfileFieldRegion { field_id: string; field_code: string; scope: 'header' | 'line'; region: OrderProfileRelativeRegion; extractor_key: OrderProfileExtractorKey; allowed_sources: OrderProfileAllowedSource[]; minimum_evidence_level: OrderProfileEvidenceLevel; target_fields?: Array<{ field_id: string; field_code: string; scope: 'header' | 'line' }>; }
|
||||
export interface OrderProfileFieldRegion {
|
||||
field_id: string;
|
||||
field_code: string;
|
||||
scope: 'header' | 'line';
|
||||
region: OrderProfileRelativeRegion;
|
||||
/** 画布框稳定身份;XFA binding.field_layout_id 优先引用,避免同 field_code 多框撞绑。 */
|
||||
region_id?: string | null;
|
||||
extractor_key: OrderProfileExtractorKey;
|
||||
allowed_sources: OrderProfileAllowedSource[];
|
||||
minimum_evidence_level: OrderProfileEvidenceLevel;
|
||||
target_fields?: Array<{ field_id: string; field_code: string; scope: 'header' | 'line' }>;
|
||||
}
|
||||
export interface OrderProfileOrderFieldLayout { layout_id: string; field_id: string; field_code: string; scope: 'header'; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; normalizer_key?: string | null; required: boolean; minimum_evidence_level: OrderProfileEvidenceLevel; }
|
||||
export interface OrderProfileDraftUnboundOrderFieldLayout { layout_id: string; label: string; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; minimum_evidence_level: OrderProfileEvidenceLevel; }
|
||||
export interface OrderProfileHeaderLayout { layout_id: string; region: OrderProfileRelativeRegion; field_regions: OrderProfileFieldRegion[]; }
|
||||
@@ -251,10 +262,14 @@ export interface XfaSplitSegment {
|
||||
note?: string | null;
|
||||
}
|
||||
|
||||
/** 单行匹配器:优先级固定 prefix > regex > position > unmatched。 */
|
||||
/** 匹配器:优先级固定 prefix > regex > position > unmatched;position 可连续多行。 */
|
||||
export interface XfaSplitMatcher {
|
||||
type: XfaSplitMatcherType;
|
||||
line_index?: number | null;
|
||||
/** position 连续多行结束行(含);缺省等于 line_index。 */
|
||||
line_end?: number | null;
|
||||
/** 连续多行合并方式;仅 line_end > line_index 时有效。 */
|
||||
join_with?: 'newline' | 'space' | 'comma' | null;
|
||||
value?: string | null;
|
||||
separators?: string[];
|
||||
case_sensitive?: boolean;
|
||||
@@ -927,6 +942,20 @@ export interface OrderProfileTestSuite {
|
||||
evidence_retention_rate?: number;
|
||||
key_field_accuracy_rate?: number;
|
||||
} | null;
|
||||
/** OCR↔datasets / XFA 视觉指标 soft 诊断;含两侧截断值或 rate,便于标明差异。 */
|
||||
soft_diagnostics?: Array<{
|
||||
sample_id: number;
|
||||
code: string;
|
||||
mismatch_count: number;
|
||||
rate?: number;
|
||||
fields: Array<{
|
||||
scope: string;
|
||||
field_code: string;
|
||||
row_index?: number | null;
|
||||
ocr_value?: string;
|
||||
datasets_value?: string;
|
||||
}>;
|
||||
}>;
|
||||
} | null;
|
||||
}
|
||||
|
||||
@@ -962,6 +991,19 @@ export interface OrderProfileBlindTestCandidate {
|
||||
order_fields: Array<{ field_id: string; field_code: string; scope: 'header'; value: unknown; status: 'confirmed' | 'needs_review' | 'unavailable'; page_no: number | null; issues: string[] }>;
|
||||
reservation_region_status?: string;
|
||||
reservation_region_review_reasons?: string[];
|
||||
/** XFA:OCR 与 datasets 同名字段对照;mismatched 仅为诊断,不否决复核。 */
|
||||
ocr_datasets_cross_check?: {
|
||||
status: 'matched' | 'mismatched' | 'unavailable';
|
||||
compared_field_count?: number;
|
||||
mismatch_count?: number;
|
||||
mismatches?: Array<{
|
||||
scope?: string;
|
||||
field_code?: string;
|
||||
row_index?: number | null;
|
||||
ocr_value?: string;
|
||||
datasets_value?: string;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
/** 工作台的本地几何状态;保存前转为 v2 相对区域定义。 */
|
||||
|
||||
Reference in new issue
Block a user