feat(shipping-notice): 落地 XFA 拆分、版面签名、统一进度与处理域履约
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
3a9fbac2fc
commit
d2b3d74def
571 files changed
+78064
-24681
No files matched your search
@@ -365,6 +365,7 @@ onMounted(() => {
|
||||
>
|
||||
<option value="">{{ t('admin.shippingAudit.filters.all') }}</option>
|
||||
<option value="review_workbench">{{ t('admin.shippingAudit.filters.eventTypeGroupReviewWorkbench') }}</option>
|
||||
<option value="formal_task_edit">{{ t('admin.shippingAudit.filters.eventTypeGroupFormalTaskEdit') }}</option>
|
||||
<option value="chat_workbench">{{ t('admin.shippingAudit.filters.eventTypeGroupChatWorkbench') }}</option>
|
||||
<option value="process_gate">{{ t('admin.shippingAudit.filters.eventTypeGroupProcessGate') }}</option>
|
||||
<option value="candidate_qualification">{{ t('admin.shippingAudit.filters.eventTypeGroupQualification') }}</option>
|
||||
|
||||
+4
@@ -36,6 +36,10 @@ const messages = {
|
||||
copyId: '复制编号',
|
||||
techRefsHint: '技术编号默认折叠展示,点击即可复制。',
|
||||
hashSection: '哈希摘要(排障用)',
|
||||
beforeHash: '变更前 checksum',
|
||||
afterHash: '变更后 checksum',
|
||||
xfaSnapshots: 'XFA 完整快照引用',
|
||||
xfaSnapshotsHint: '完整密文需敏感读权限按需打开;此处仅展示引用与用途。',
|
||||
columns: {
|
||||
event: '事件',
|
||||
actor: '操作者',
|
||||
|
||||
+38
-2
@@ -1,9 +1,10 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-audit/ShippingAuditEventDetailDrawer.vue
|
||||
用途:审计事件详情抽屉——业务化元数据、敏感脱敏提示、白名单 Diff、哈希摘要。
|
||||
用途:审计事件详情抽屉——业务化元数据、敏感脱敏提示、白名单 Diff、XFA 快照引用、哈希摘要。
|
||||
依赖:shipping-audit.api 类型、shippingAuditDisplay、Vue I18n、useMessage。
|
||||
逻辑:由 ShippingAuditCenterPage 传入 detail;事件/动作/结果与列表同源业务标签;
|
||||
技术编号以复制芯片展示;关闭时 emit close;不自行拉接口。
|
||||
展示 before/after checksum 与 XFA snapshot_ref;技术编号以复制芯片展示;
|
||||
关闭时 emit close;不自行拉接口。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
@@ -164,9 +165,44 @@ function onClose() {
|
||||
<dt class="text-muted">{{ t('admin.shippingAudit.previousEventHash') }}</dt>
|
||||
<dd class="break-all font-mono text-[10px]">{{ detail.previous_event_hash || '—' }}</dd>
|
||||
</div>
|
||||
<div v-if="detail.before_hash">
|
||||
<dt class="text-muted">{{ t('admin.shippingAudit.beforeHash') }}</dt>
|
||||
<dd class="break-all font-mono text-[10px]" data-testid="shipping-audit-before-hash">{{ detail.before_hash }}</dd>
|
||||
</div>
|
||||
<div v-if="detail.after_hash">
|
||||
<dt class="text-muted">{{ t('admin.shippingAudit.afterHash') }}</dt>
|
||||
<dd class="break-all font-mono text-[10px]" data-testid="shipping-audit-after-hash">{{ detail.after_hash }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</details>
|
||||
|
||||
<section
|
||||
v-if="detail.xfa_snapshot_refs?.length"
|
||||
class="mt-5"
|
||||
data-testid="shipping-audit-xfa-snapshots"
|
||||
>
|
||||
<h3 class="text-sm font-semibold">{{ t('admin.shippingAudit.xfaSnapshots') }}</h3>
|
||||
<p class="mt-1 text-[11px] text-muted">{{ t('admin.shippingAudit.xfaSnapshotsHint') }}</p>
|
||||
<ul class="mt-2 space-y-2">
|
||||
<li
|
||||
v-for="ref in detail.xfa_snapshot_refs"
|
||||
:key="ref.snapshot_ref"
|
||||
class="rounded-lg border border-default px-3 py-2 text-xs"
|
||||
>
|
||||
<div class="font-medium">{{ ref.purpose }}</div>
|
||||
<button
|
||||
type="button"
|
||||
class="mt-1 rounded border border-default px-2 py-0.5 font-mono text-[11px] text-muted"
|
||||
:title="ref.snapshot_ref"
|
||||
data-testid="shipping-audit-xfa-snapshot-ref"
|
||||
@click="copyTechId(ref.snapshot_ref)"
|
||||
>
|
||||
{{ t('admin.shippingAudit.copyId') }} · {{ ref.snapshot_ref.slice(0, 12) }}…
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<h3 class="mt-6 font-semibold">{{ t('admin.shippingAudit.diff') }}</h3>
|
||||
<div v-if="detail.diff?.length" class="mt-2 space-y-2" data-testid="shipping-audit-diff-rows">
|
||||
<div
|
||||
|
||||
+80
-32
@@ -1,8 +1,9 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileBlindTestPage.vue
|
||||
用途:维护订单模板草稿的独立盲测证据,并完成执行和批准。
|
||||
依赖:盲测 API、Vue Router、统一业务错误提示和四语言文案。
|
||||
逻辑:验证页进入本页;管理员选择未参与建模的样本、复核候选后写入真值,再执行并批准,最后回到发布检查。
|
||||
依赖:盲测 API、Profile 详情、Vue Router、统一业务错误提示和四语言文案。
|
||||
逻辑:验证页进入本页;coordinate 走表格候选,xfa_dataset 走文档级结构分析候选;
|
||||
管理员复核候选后写入真值,再执行并批准,最后回到发布检查。不回显盲测真值。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
@@ -16,10 +17,10 @@ import {
|
||||
createOrderProfileTestSuite,
|
||||
executeOrderProfileTestSuite,
|
||||
createOrderProfileSample,
|
||||
getOrderDocumentProfileDetail,
|
||||
getOrderProfileSampleStatus,
|
||||
listOrderProfileBlindTestAvailableSamples,
|
||||
listOrderProfileBoundSamples,
|
||||
listOrderProfileSamples,
|
||||
previewOrderProfileBlindTestCandidate,
|
||||
removeOrderProfileTestSample,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
@@ -28,7 +29,9 @@ import type {
|
||||
OrderProfileBlindTestAvailableSample,
|
||||
OrderProfileBlindTestCandidate,
|
||||
OrderProfileTestSuite,
|
||||
OrderProfileTemplateMode,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { isXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
@@ -37,9 +40,12 @@ const { t } = useI18n();
|
||||
const profileId = Number(route.params.profileId);
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
|
||||
const suite = ref<OrderProfileTestSuite | null>(null);
|
||||
const templateMode = ref<OrderProfileTemplateMode>('coordinate');
|
||||
const availableSamples = ref<OrderProfileBlindTestAvailableSample[]>([]);
|
||||
const selectedSampleKey = ref('');
|
||||
const candidate = ref<OrderProfileBlindTestCandidate | null>(null);
|
||||
/** XFA 盲测使用文档级结构证据,不依赖坐标表格。 */
|
||||
const isXfa = computed(() => templateMode.value === 'xfa_dataset');
|
||||
const rowReviews = ref<Array<{ correct: boolean; correction: string }>>([]);
|
||||
const orderFieldReviews = ref<Record<string, { correct: boolean; value: string }>>({});
|
||||
const loading = ref(false);
|
||||
@@ -48,7 +54,7 @@ const hasTrainingSample = ref(false);
|
||||
const availableSamplesLoaded = ref(false);
|
||||
const availableSamplesLoading = ref(false);
|
||||
const uploadingSample = ref(false);
|
||||
const pendingUpload = ref<{ intakeNo: string; filename: string; state: 'parsing' | 'failed'; errorCode?: string | null } | null>(null);
|
||||
const pendingUpload = ref<{ intakeNo: string; filename: string; state: 'materializing' | 'failed'; errorCode?: string | null } | null>(null);
|
||||
let uploadPollingTimer: number | null = null;
|
||||
let availableSamplesController: AbortController | null = null;
|
||||
let availableSamplesTimeout: number | null = null;
|
||||
@@ -57,6 +63,17 @@ let availableSamplesTimeout: number | null = null;
|
||||
const selectedSample = computed(() => availableSamples.value.find((item) => `${item.document_id}:${item.table_id}` === selectedSampleKey.value) || null);
|
||||
/** 用安全表格摘要区分同页多表;内部 table_id 仅作为请求身份,绝不展示给管理员。 */
|
||||
function sampleLabel(sample: OrderProfileBlindTestAvailableSample): string {
|
||||
if (sample.table_id === '__document_candidate__') {
|
||||
return t('admin.shippingOrderProfiles.blindTest.documentCandidateOption', { filename: sample.filename });
|
||||
}
|
||||
if (sample.table_id === 'xfa-authoritative-lines' || isXfa.value) {
|
||||
const identity = sample.header_preview.filter(Boolean).join(' · ');
|
||||
return t('admin.shippingOrderProfiles.blindTest.xfaSampleOption', {
|
||||
filename: sample.filename,
|
||||
rows: sample.row_count,
|
||||
identity: identity || '—',
|
||||
});
|
||||
}
|
||||
const header = sample.header_preview.join(' / ');
|
||||
return t('admin.shippingOrderProfiles.blindTest.sampleOption', {
|
||||
filename: sample.filename, page: sample.page_no, table: sample.table_index,
|
||||
@@ -80,6 +97,12 @@ const failureDetails = computed(() => (suite.value?.latest_run?.failure_codes ||
|
||||
if (parts[2] === 'coordinate_evidence_missing') {
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.coordinateEvidenceMissing', { sample: sampleName }) };
|
||||
}
|
||||
if (parts[2] === 'xfa_evidence_missing') {
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.xfaEvidenceMissing', { sample: sampleName }) };
|
||||
}
|
||||
if (parts[2] === 'line_count') {
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.rowsMismatch', { sample: sampleName }) };
|
||||
}
|
||||
if (parts[2] === 'mismatch') {
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.rowsMismatch', { sample: sampleName }) };
|
||||
}
|
||||
@@ -103,24 +126,24 @@ function report(error: unknown): void {
|
||||
const code = error instanceof BusinessError ? error.code : '';
|
||||
message.error(code ? t(`errors.${code}`, code) : t('admin.orderProfileValidation.failed'));
|
||||
}
|
||||
/** 将模板布局失败码转成盲测页可执行的提示,不向管理员回显内部快照数据。 */
|
||||
function sampleFailureMessage(errorCode?: string | null): string {
|
||||
const key = errorCode === 'mineru_cell_coordinates_missing'
|
||||
? 'sampleLayoutCoordinatesMissing'
|
||||
: errorCode === 'shipping_document_layout_snapshot_size_exceeded'
|
||||
? 'sampleLayoutSnapshotTooLarge'
|
||||
: 'sampleParseFailed';
|
||||
return t(`admin.shippingOrderProfiles.wizard.${key}`);
|
||||
/** 将文件物化失败转成安全提示;版面错误只允许在预览复核阶段出现。 */
|
||||
function sampleFailureMessage(): string {
|
||||
return t('admin.shippingOrderProfiles.blindTest.sampleMaterializationFailed');
|
||||
}
|
||||
|
||||
/** 创建或读取当前草稿 checksum 对应的盲测集;候选样本按需加载,避免进入页面时扫描全部历史样本。 */
|
||||
async function loadSuite(): Promise<void> {
|
||||
loading.value = true;
|
||||
try {
|
||||
const [nextSuite, boundSamples] = await Promise.all([
|
||||
const [nextSuite, boundSamples, profile] = await Promise.all([
|
||||
createOrderProfileTestSuite(profileId),
|
||||
listOrderProfileBoundSamples(profileId),
|
||||
getOrderDocumentProfileDetail(profileId),
|
||||
]);
|
||||
templateMode.value = (
|
||||
profile.template_mode === 'xfa_dataset'
|
||||
|| isXfaDatasetProfileDefinition(profile.definition)
|
||||
) ? 'xfa_dataset' : 'coordinate';
|
||||
suite.value = nextSuite;
|
||||
hasTrainingSample.value = boundSamples.some((item) => item.sample_role === 'training');
|
||||
} catch (error) {
|
||||
@@ -130,9 +153,10 @@ async function loadSuite(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** 按需读取独立样本摘要;上传解析完成时可强制刷新并定位刚上传的文档。 */
|
||||
/** 按需读取独立样本摘要;强制刷新会替换旧请求,确保定位刚物化的文档。 */
|
||||
async function loadAvailableSamples(force = false): Promise<void> {
|
||||
if (!suite.value || suite.value.status !== 'draft' || (!force && availableSamplesLoaded.value) || availableSamplesLoading.value) return;
|
||||
if (!suite.value || suite.value.status !== 'draft') return;
|
||||
if (!force && (availableSamplesLoaded.value || availableSamplesLoading.value)) return;
|
||||
availableSamplesController?.abort();
|
||||
if (availableSamplesTimeout) window.clearTimeout(availableSamplesTimeout);
|
||||
const controller = new AbortController();
|
||||
@@ -156,9 +180,9 @@ async function loadAvailableSamples(force = false): Promise<void> {
|
||||
if (availableSamplesController === controller) {
|
||||
availableSamplesController = null;
|
||||
availableSamplesLoading.value = false;
|
||||
if (availableSamplesTimeout) window.clearTimeout(availableSamplesTimeout);
|
||||
availableSamplesTimeout = null;
|
||||
}
|
||||
if (availableSamplesTimeout) window.clearTimeout(availableSamplesTimeout);
|
||||
availableSamplesTimeout = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,28 +192,36 @@ function stopUploadPolling(): void {
|
||||
uploadPollingTimer = null;
|
||||
}
|
||||
|
||||
/** 上传完成后精确选中同一 Intake 的首个可盲测表格,仍必须经过管理员预览和复核。 */
|
||||
/** 文件物化后精确选中同一 Intake 的候选;后台版面预热不参与上传成功判定。 */
|
||||
async function pollUploadedSample(intakeNo: string): Promise<void> {
|
||||
try {
|
||||
const result = await getOrderProfileSampleStatus(intakeNo);
|
||||
if (result.parse_status === 'parsed' && result.document_count > 0) {
|
||||
const uploaded = (await listOrderProfileSamples()).find((item) => item.intake_no === intakeNo);
|
||||
await loadAvailableSamples(true);
|
||||
const selected = uploaded && availableSamples.value.find((item) => item.document_id === uploaded.document_id);
|
||||
const selected = availableSamples.value.find((item) => (result.document_ids || []).includes(item.document_id));
|
||||
if (selected) {
|
||||
selectedSampleKey.value = `${selected.document_id}:${selected.table_id}`;
|
||||
pendingUpload.value = null;
|
||||
message.success(t('admin.shippingOrderProfiles.wizard.sampleReady'));
|
||||
message.success(t('admin.shippingOrderProfiles.blindTest.sampleUploaded'));
|
||||
} else {
|
||||
pendingUpload.value = { intakeNo, filename: pendingUpload.value?.filename || '', state: 'failed' };
|
||||
pendingUpload.value = null;
|
||||
message.success(t('admin.shippingOrderProfiles.blindTest.sampleUploaded'));
|
||||
message.error(t('admin.shippingOrderProfiles.blindTest.noIndependentSamples'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (['failed', 'error'].includes(result.parse_status)) {
|
||||
pendingUpload.value = {
|
||||
intakeNo, filename: pendingUpload.value?.filename || '', state: 'failed', errorCode: result.error_code,
|
||||
};
|
||||
await loadAvailableSamples(true);
|
||||
const selected = availableSamples.value.find((item) => (result.document_ids || []).includes(item.document_id));
|
||||
if (selected) {
|
||||
selectedSampleKey.value = `${selected.document_id}:${selected.table_id}`;
|
||||
pendingUpload.value = null;
|
||||
message.success(t('admin.shippingOrderProfiles.blindTest.sampleAcceptedForReview'));
|
||||
} else {
|
||||
pendingUpload.value = {
|
||||
intakeNo, filename: pendingUpload.value?.filename || '', state: 'failed', errorCode: result.error_code,
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
uploadPollingTimer = window.setTimeout(() => void pollUploadedSample(intakeNo), 1500);
|
||||
@@ -213,7 +245,7 @@ async function uploadIndependentSample(event: Event): Promise<void> {
|
||||
try {
|
||||
const asset = await uploadFileAsset(file);
|
||||
const intake = await createOrderProfileSample(asset.asset_no);
|
||||
pendingUpload.value = { intakeNo: intake.intake_no, filename: file.name, state: 'parsing' };
|
||||
pendingUpload.value = { intakeNo: intake.intake_no, filename: file.name, state: 'materializing' };
|
||||
void pollUploadedSample(intake.intake_no);
|
||||
} catch (error) {
|
||||
report(error);
|
||||
@@ -225,6 +257,10 @@ async function uploadIndependentSample(event: Event): Promise<void> {
|
||||
/** 运行选中独立样本并初始化逐行、逐订单字段的人工复核表单。 */
|
||||
async function previewSample(): Promise<void> {
|
||||
if (!suite.value || !selectedSample.value) return;
|
||||
if (selectedSample.value.review_mode === 'preparing') {
|
||||
message.error(t('admin.shippingOrderProfiles.blindTest.reviewPreparing'));
|
||||
return;
|
||||
}
|
||||
working.value = true;
|
||||
try {
|
||||
candidate.value = await previewOrderProfileBlindTestCandidate(suite.value.id, selectedSample.value);
|
||||
@@ -262,7 +298,8 @@ function reviewedRows(): Array<Record<string, unknown>> | null {
|
||||
|
||||
/** 提交全量人工复核,将候选结果或管理员更正转换为服务端受保护的盲测真值。 */
|
||||
async function confirmReview(): Promise<void> {
|
||||
if (!suite.value || !candidate.value) return;
|
||||
if (!suite.value || !candidate.value || !candidate.value.confirmable
|
||||
|| !candidate.value.layout_version_id || !candidate.value.layout_payload_checksum) return;
|
||||
const reviews = reviewedRows();
|
||||
if (!reviews) return;
|
||||
working.value = true;
|
||||
@@ -270,6 +307,8 @@ async function confirmReview(): Promise<void> {
|
||||
suite.value = await confirmOrderProfileBlindTestReviews(suite.value.id, {
|
||||
document_id: candidate.value.document_id,
|
||||
table_id: candidate.value.table_id,
|
||||
layout_version_id: candidate.value.layout_version_id,
|
||||
layout_payload_checksum: candidate.value.layout_payload_checksum,
|
||||
row_reviews: reviews,
|
||||
order_field_reviews: Object.fromEntries(Object.entries(orderFieldReviews.value).map(([fieldKey, review]) => [
|
||||
fieldKey,
|
||||
@@ -282,6 +321,11 @@ async function confirmReview(): Promise<void> {
|
||||
availableSamples.value = [];
|
||||
message.success(t('admin.shippingOrderProfiles.blindTest.addedSamples'));
|
||||
} catch (error) {
|
||||
if (error instanceof BusinessError && error.code === 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_PREVIEW_STALE') {
|
||||
candidate.value = null;
|
||||
selectedSampleKey.value = '';
|
||||
await loadAvailableSamples(true);
|
||||
}
|
||||
report(error);
|
||||
} finally {
|
||||
working.value = false;
|
||||
@@ -357,13 +401,16 @@ onBeforeUnmount(() => {
|
||||
<template>
|
||||
<section class="blind-test-page">
|
||||
<header>
|
||||
<div><h1 class="section-title">{{ t('admin.shippingOrderProfiles.blindTest.title') }}</h1><p class="section-desc mt-1">{{ t('admin.shippingOrderProfiles.blindTest.reviewHint') }}</p></div>
|
||||
<div>
|
||||
<h1 class="section-title">{{ t('admin.shippingOrderProfiles.blindTest.title') }}</h1>
|
||||
<p class="section-desc mt-1">{{ isXfa ? t('admin.shippingOrderProfiles.blindTest.xfaReviewHint') : t('admin.shippingOrderProfiles.blindTest.reviewHint') }}</p>
|
||||
</div>
|
||||
<div class="actions"><button type="button" class="btn-secondary" @click="backToValidation">{{ t('admin.shippingOrderProfiles.blindTest.backToValidation') }}</button><button v-if="suite?.status === 'approved'" type="button" class="btn-primary" @click="goToPublishCheck">{{ t('admin.shippingOrderProfiles.blindTest.goPublishCheck') }}</button></div>
|
||||
</header>
|
||||
|
||||
<p v-if="loading">{{ t('admin.orderProfileValidation.loading') }}</p>
|
||||
<template v-else-if="suite">
|
||||
<section class="card suite-summary"><div><h2>{{ t('admin.shippingOrderProfiles.blindTest.samples', { count: suite.sample_count, 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 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="failureDetails.length" class="card failure-details">
|
||||
<div><h2>{{ t('admin.shippingOrderProfiles.blindTest.failure.title') }}</h2><p>{{ t('admin.shippingOrderProfiles.blindTest.failure.hint') }}</p></div>
|
||||
@@ -373,12 +420,13 @@ 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 || working" @click="previewSample">{{ t('admin.shippingOrderProfiles.blindTest.previewAndReview') }}</button></template></div>
|
||||
<p v-if="pendingUpload" class="upload-status" :class="{ failed: pendingUpload.state === 'failed' }">{{ pendingUpload.filename }} · {{ pendingUpload.state === 'parsing' ? t('admin.shippingOrderProfiles.wizard.sampleParsing') : sampleFailureMessage(pendingUpload.errorCode) }}</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>
|
||||
<p v-if="pendingUpload" class="upload-status" :class="{ failed: pendingUpload.state === 'failed' }">{{ pendingUpload.filename }} · {{ pendingUpload.state === 'materializing' ? t('admin.shippingOrderProfiles.blindTest.sampleMaterializing') : sampleFailureMessage() }}</p>
|
||||
</section>
|
||||
|
||||
<section v-if="candidate" class="card candidate-card">
|
||||
<h2>{{ t('admin.shippingOrderProfiles.blindTest.reviewHint') }}</h2>
|
||||
<p v-if="!candidate.confirmable" class="training-required">{{ t('admin.shippingOrderProfiles.blindTest.diagnosticOnly') }}</p>
|
||||
<p v-if="!candidate.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]">
|
||||
@@ -392,7 +440,7 @@ onBeforeUnmount(() => {
|
||||
<label><input :checked="orderFieldReview(orderFieldKey(field)).correct" type="checkbox" @change="updateOrderFieldReview(orderFieldKey(field), { correct: ($event.target as HTMLInputElement).checked })">{{ t('admin.shippingOrderProfiles.blindTest.correct') }}</label>
|
||||
<input v-if="!orderFieldReview(orderFieldKey(field)).correct" class="input-field" :value="orderFieldReview(orderFieldKey(field)).value" :placeholder="t('admin.shippingOrderProfiles.blindTest.correctedValue')" @input="updateOrderFieldReview(orderFieldKey(field), { value: ($event.target as HTMLInputElement).value })">
|
||||
</article>
|
||||
<button type="button" class="btn-primary" :disabled="working || !candidate.rows.length" @click="confirmReview">{{ t('admin.shippingOrderProfiles.blindTest.confirmReview') }}</button>
|
||||
<button v-if="candidate.confirmable" type="button" class="btn-primary" :disabled="working || !candidate.rows.length" @click="confirmReview">{{ t('admin.shippingOrderProfiles.blindTest.confirmReview') }}</button>
|
||||
</section>
|
||||
|
||||
<section class="card"><h2>{{ t('admin.shippingOrderProfiles.blindTest.addedSamples') }}</h2><p>{{ t('admin.shippingOrderProfiles.blindTest.addedSamplesHint') }}</p><ul v-if="suite.samples.length"><li v-for="sample in suite.samples" :key="sample.id"><span>{{ sample.filename }} · P{{ sample.page_no }}</span><button v-if="suite.status === 'draft'" type="button" class="btn-secondary btn-sm" :disabled="working" @click="removeSample(sample.id)">{{ t('admin.shippingOrderProfiles.blindTest.removeSample') }}</button></li></ul><p v-else>{{ t('admin.shippingOrderProfiles.blindTest.noIndependentSamples') }}</p></section>
|
||||
|
||||
+74
-16
@@ -1,8 +1,8 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileCreateWizardPage.vue
|
||||
用途:以三步向导创建订单文档模板草稿。
|
||||
依赖:Schema/样本/表格 API、步骤组件和 Vue Router。
|
||||
逻辑:首步仅收集业务名称和 Schema;最后一步由服务端生成系统编码并原子创建草稿、样本绑定、Revision 与 Lease。
|
||||
用途:以三步向导创建订单文档模板草稿(坐标或 XFA 自动分流)。
|
||||
依赖:Schema/样本/表格/XFA API、步骤组件和 Vue Router。
|
||||
逻辑:样本 xfa_analysis_ready 时第三步改为集合确认;否则保持表格选择;原子创建草稿与 Lease。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
|
||||
@@ -13,10 +13,12 @@ import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { getShippingOrderSchemaState } from '@/features/admin/api/shipping-order-schema.api';
|
||||
import { completeOrderDocumentProfileWizard, getOrderProfileSampleTables, listOrderProfileSamples } from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type { OrderProfileSampleDocument } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { ShippingOrderSchemaVersion } from '@/features/admin/types/shipping-order-schema.types';
|
||||
import OrderProfileIdentityStep from './components/OrderProfileIdentityStep.vue';
|
||||
import OrderProfileSampleStep from './components/OrderProfileSampleStep.vue';
|
||||
import OrderProfileModelStartStep from './components/OrderProfileModelStartStep.vue';
|
||||
import OrderProfileXfaConfirmStep from './components/OrderProfileXfaConfirmStep.vue';
|
||||
|
||||
type Identity = { displayName: string; schemaId: number };
|
||||
|
||||
@@ -27,21 +29,34 @@ const step = ref(1);
|
||||
const saving = ref(false);
|
||||
const schemas = ref<ShippingOrderSchemaVersion[]>([]);
|
||||
const schemasResolved = ref(false);
|
||||
const samples = ref<Array<{ document_id: number; intake_no: string; filename?: string | null; table_count: number }>>([]);
|
||||
const samples = ref<OrderProfileSampleDocument[]>([]);
|
||||
const tables = ref<Array<{ table_id: string; page_no: number; row_count: number; column_count: number; rows: string[][] }>>([]);
|
||||
const identity = reactive<Identity>({ displayName: '', schemaId: 0 });
|
||||
const documentId = ref(0);
|
||||
const tableId = ref('');
|
||||
const authoritativePathId = ref('');
|
||||
const mirrorPathIds = ref<string[]>([]);
|
||||
const browserSessionId = crypto.randomUUID();
|
||||
let sampleRefreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const selectedSample = computed(() => samples.value.find((item) => item.document_id === documentId.value) || null);
|
||||
const isXfaSample = computed(() => Boolean(selectedSample.value?.xfa_analysis_ready));
|
||||
const publishedSchemas = computed(() => schemas.value.filter((item) => item.status === 'published'));
|
||||
const canNext = computed(() => step.value === 1
|
||||
? Boolean(identity.displayName.trim() && identity.schemaId)
|
||||
: step.value === 2 ? Boolean(documentId.value) : Boolean(tableId.value));
|
||||
const stepThreeLabel = computed(() => (
|
||||
isXfaSample.value
|
||||
? t('admin.shippingOrderProfiles.wizard.xfa.stepTitle')
|
||||
: t('admin.shippingOrderProfiles.wizard.tableStep')
|
||||
));
|
||||
const canNext = computed(() => {
|
||||
if (step.value === 1) return Boolean(identity.displayName.trim() && identity.schemaId);
|
||||
if (step.value === 2) return Boolean(documentId.value);
|
||||
if (isXfaSample.value) return Boolean(authoritativePathId.value);
|
||||
return Boolean(tableId.value);
|
||||
});
|
||||
const steps = computed(() => [
|
||||
{ number: 1, label: t('admin.shippingOrderProfiles.wizard.identityStep'), icon: FileText },
|
||||
{ number: 2, label: t('admin.shippingOrderProfiles.wizard.sampleStep'), icon: Layers3 },
|
||||
{ number: 3, label: t('admin.shippingOrderProfiles.wizard.tableStep'), icon: Sparkles },
|
||||
{ number: 3, label: stepThreeLabel.value, icon: Sparkles },
|
||||
]);
|
||||
|
||||
/** 接收首步身份快照;父级单一状态驱动下一步校验,避免子组件对象替换造成状态不同步。 */
|
||||
@@ -49,6 +64,7 @@ function updateIdentity(next: Identity): void {
|
||||
identity.displayName = next.displayName;
|
||||
identity.schemaId = next.schemaId;
|
||||
}
|
||||
|
||||
/** 加载可用 Schema 与已解析样本;失败不创建或缓存任何 Profile。 */
|
||||
async function loadContext(): Promise<void> {
|
||||
try {
|
||||
@@ -60,16 +76,19 @@ async function loadContext(): Promise<void> {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.loadFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
/** 刷新上传后的样本库;轮询失败静默处理,避免短暂网络异常持续弹出提示。 */
|
||||
async function refreshSamples(showError = true): Promise<void> {
|
||||
try { samples.value = await listOrderProfileSamples(); }
|
||||
catch { if (showError) message.error(t('admin.shippingOrderProfiles.wizard.loadFailed')); }
|
||||
}
|
||||
|
||||
/** 仅在第二步保持已解析文档列表为最新,离开步骤后立即停止。 */
|
||||
function stopSampleRefresh(): void {
|
||||
if (sampleRefreshTimer !== null) clearTimeout(sampleRefreshTimer);
|
||||
sampleRefreshTimer = null;
|
||||
}
|
||||
|
||||
function scheduleSampleRefresh(): void {
|
||||
stopSampleRefresh();
|
||||
if (step.value !== 2) return;
|
||||
@@ -77,22 +96,32 @@ function scheduleSampleRefresh(): void {
|
||||
if (step.value === 2) sampleRefreshTimer = setTimeout(scheduleSampleRefresh, 2000);
|
||||
});
|
||||
}
|
||||
/** 加载选定样本的可用表格;单表场景由下一步直接作为订单明细表。 */
|
||||
|
||||
/** 加载选定样本的可用表格;XFA 样本跳过表格加载。 */
|
||||
async function loadTables(id: number): Promise<void> {
|
||||
if (samples.value.find((item) => item.document_id === id)?.xfa_analysis_ready) {
|
||||
tables.value = [];
|
||||
return;
|
||||
}
|
||||
try { tables.value = (await getOrderProfileSampleTables(id)).tables; }
|
||||
catch (error) { message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.tableLoadFailed')); }
|
||||
}
|
||||
|
||||
watch(documentId, async (id) => {
|
||||
tableId.value = '';
|
||||
authoritativePathId.value = '';
|
||||
mirrorPathIds.value = [];
|
||||
tables.value = [];
|
||||
if (!id) return;
|
||||
await loadTables(id);
|
||||
});
|
||||
|
||||
watch(step, (currentStep) => {
|
||||
if (currentStep === 2) scheduleSampleRefresh();
|
||||
else stopSampleRefresh();
|
||||
});
|
||||
/** 前进仅校验当前步骤;单表直接创建,多表才要求管理员确认订单明细表。 */
|
||||
|
||||
/** 前进仅校验当前步骤;XFA 样本进入集合确认,单表坐标样本可直接创建。 */
|
||||
async function next(): Promise<void> {
|
||||
if (!canNext.value) {
|
||||
message.error(step.value === 1 && !publishedSchemas.value.length
|
||||
@@ -101,6 +130,10 @@ async function next(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
if (step.value === 2) {
|
||||
if (isXfaSample.value) {
|
||||
step.value = 3;
|
||||
return;
|
||||
}
|
||||
if (!tables.value.length) await loadTables(documentId.value);
|
||||
const onlyTable = tables.value.length === 1 ? tables.value[0] : undefined;
|
||||
if (onlyTable) {
|
||||
@@ -115,16 +148,31 @@ async function next(): Promise<void> {
|
||||
}
|
||||
if (step.value < 3) step.value += 1;
|
||||
}
|
||||
/** 单事务完成后进入草稿编辑路由;创建草稿和创建并进入标注共享同一审计动作。 */
|
||||
|
||||
/** 单事务完成后进入草稿编辑路由;XFA 与坐标共享同一审计动作入口。 */
|
||||
async function finish(enterEditor: boolean): Promise<void> {
|
||||
if (!canNext.value) return;
|
||||
saving.value = true;
|
||||
try {
|
||||
const profile = await completeOrderDocumentProfileWizard({
|
||||
display_name: identity.displayName,
|
||||
schema_version_id: identity.schemaId, document_id: documentId.value, main_table_id: tableId.value,
|
||||
browser_session_id: browserSessionId, operation_id: crypto.randomUUID(),
|
||||
});
|
||||
const payload = isXfaSample.value
|
||||
? {
|
||||
display_name: identity.displayName,
|
||||
schema_version_id: identity.schemaId,
|
||||
document_id: documentId.value,
|
||||
authoritative_collection_path_id: authoritativePathId.value,
|
||||
mirror_collection_path_ids: mirrorPathIds.value,
|
||||
browser_session_id: browserSessionId,
|
||||
operation_id: crypto.randomUUID(),
|
||||
}
|
||||
: {
|
||||
display_name: identity.displayName,
|
||||
schema_version_id: identity.schemaId,
|
||||
document_id: documentId.value,
|
||||
main_table_id: tableId.value,
|
||||
browser_session_id: browserSessionId,
|
||||
operation_id: crypto.randomUUID(),
|
||||
};
|
||||
const profile = await completeOrderDocumentProfileWizard(payload);
|
||||
message.success(t('admin.shippingOrderProfiles.created'));
|
||||
await router.push(enterEditor
|
||||
? { name: 'AdminShippingOrderDocumentProfileEdit', params: { profileCode: profile.profile_code, profileId: profile.id }, query: { editorSessionId: browserSessionId } }
|
||||
@@ -133,6 +181,7 @@ async function finish(enterEditor: boolean): Promise<void> {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.createFailed'));
|
||||
} finally { saving.value = false; }
|
||||
}
|
||||
|
||||
onMounted(loadContext);
|
||||
onBeforeUnmount(stopSampleRefresh);
|
||||
</script>
|
||||
@@ -165,6 +214,15 @@ onBeforeUnmount(stopSampleRefresh);
|
||||
@update:model-value="updateIdentity"
|
||||
/>
|
||||
<OrderProfileSampleStep v-else-if="step === 2" v-model="documentId" :samples="samples" @uploaded="refreshSamples(false)" @refresh="refreshSamples()" />
|
||||
<OrderProfileXfaConfirmStep
|
||||
v-else-if="isXfaSample"
|
||||
:document-id="documentId"
|
||||
:sample="selectedSample"
|
||||
:authoritative-path-id="authoritativePathId"
|
||||
:mirror-path-ids="mirrorPathIds"
|
||||
@update:authoritative-path-id="authoritativePathId = $event"
|
||||
@update:mirror-path-ids="mirrorPathIds = $event"
|
||||
/>
|
||||
<OrderProfileModelStartStep v-else v-model="tableId" :tables="tables" />
|
||||
</main>
|
||||
|
||||
|
||||
+14
-12
@@ -1,6 +1,6 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue
|
||||
用途:订单坐标 Profile v2 的独立草稿标注编辑页。
|
||||
用途:订单坐标 Profile 的独立草稿标注编辑页。
|
||||
依赖:受控预览 API、Schema API、DocumentCanvas、IssuePanel、shippingOrderField.utils。
|
||||
逻辑:仅编辑由向导创建的草稿;起行锚点默认 customer_po_line_no(内部项次 line_no 亦可绑定);
|
||||
撤销/重做、自动保存和建议决定均受当前标签租约保护。
|
||||
@@ -51,6 +51,7 @@ 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 type {
|
||||
ShippingOrderFieldConfig,
|
||||
ShippingOrderSchemaVersion,
|
||||
@@ -896,7 +897,6 @@ const definition = () => {
|
||||
};
|
||||
});
|
||||
return {
|
||||
contract_version: "order_coordinate_profile.v2" as const,
|
||||
document_match: {
|
||||
document_type: "purchase_order" as const,
|
||||
page_pattern: "one_or_more" as const,
|
||||
@@ -1528,8 +1528,9 @@ const mergeEquivalentOrderAnchors = (items: OrderProfileCanvasRegion[]) => {
|
||||
|
||||
/** 从 v2 定义恢复区域,供草稿重开后继续在画布上编辑。 */
|
||||
const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
const definition = asCoordinateProfileDefinition(profile.definition);
|
||||
for (const key of Object.keys(tableRegionSettings)) delete tableRegionSettings[Number(key)];
|
||||
for (const table of profile.definition.table_regions) {
|
||||
for (const table of definition.table_regions) {
|
||||
const regionPageNo = restoreOrderProfileRegionPageNo(table);
|
||||
tableRegionSettings[regionPageNo] = {
|
||||
rowReconstructionMode: table.row_reconstruction_mode || 'fixed_subrows',
|
||||
@@ -1537,7 +1538,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
};
|
||||
}
|
||||
const restored: OrderProfileCanvasRegion[] = [
|
||||
...(profile.definition.document_match.required_anchors || []).flatMap<OrderProfileCanvasRegion>((anchor) => {
|
||||
...(definition.document_match.required_anchors || []).flatMap<OrderProfileCanvasRegion>((anchor) => {
|
||||
if (!anchor.label_region || !anchor.value_region || !anchor.page_no) return [];
|
||||
return [{
|
||||
id: `${anchor.anchor_id}_label`, kind: 'document_anchor_label', label: anchor.label,
|
||||
@@ -1547,7 +1548,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
region: anchor.value_region, parentId: anchor.anchor_id, pageNo: anchor.page_no,
|
||||
}];
|
||||
}),
|
||||
...(profile.definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
|
||||
...(definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
|
||||
const pageNo = item.page_scope === "exact_page" ? item.page_no || 1 : 1;
|
||||
if (!item.anchor?.region || !item.absolute_value_region) {
|
||||
return [{
|
||||
@@ -1580,7 +1581,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
pageNo,
|
||||
}];
|
||||
}),
|
||||
...(profile.definition.order_field_layouts || []).filter((item) => !item.anchor).map((item) => ({
|
||||
...(definition.order_field_layouts || []).filter((item) => !item.anchor).map((item) => ({
|
||||
id: item.layout_id,
|
||||
kind: "order_field" as const,
|
||||
label: schemaFieldLabel(item.field_code),
|
||||
@@ -1588,7 +1589,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
fieldCode: item.field_code,
|
||||
pageNo: item.page_scope === "exact_page" ? item.page_no || 1 : 1,
|
||||
})),
|
||||
...(profile.definition.order_field_layouts || []).flatMap((item) => {
|
||||
...(definition.order_field_layouts || []).flatMap((item) => {
|
||||
if (!item.anchor?.region || !item.absolute_value_region) return [];
|
||||
const anchor = item.anchor.region;
|
||||
return [{
|
||||
@@ -1612,7 +1613,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
pageNo: item.page_scope === "exact_page" ? item.page_no || 1 : 1,
|
||||
}];
|
||||
}),
|
||||
...profile.definition.table_regions.flatMap((table) => {
|
||||
...definition.table_regions.flatMap((table) => {
|
||||
const regionPageNo = restoreOrderProfileRegionPageNo(table);
|
||||
const headerLayoutIds = new Set(
|
||||
table.header_layouts.map((item) => item.layout_id),
|
||||
@@ -1733,10 +1734,11 @@ const edit = async (profile: ShippingOrderDocumentProfile) => {
|
||||
form.displayName = profile.display_name;
|
||||
form.schemaId = profile.schema_version_id;
|
||||
form.changeNote = profile.change_note || "";
|
||||
documentMatch.requiredAnchors = (profile.definition.document_match.required_anchors || []).map((item) => ({ ...item }));
|
||||
documentMatch.optionalAnchors = (profile.definition.document_match.optional_anchors || []).map((item) => ({ ...item }));
|
||||
documentMatch.minimumScore = profile.definition.document_match.minimum_score;
|
||||
documentMatch.minimumMargin = profile.definition.document_match.minimum_margin;
|
||||
const definition = asCoordinateProfileDefinition(profile.definition);
|
||||
documentMatch.requiredAnchors = (definition.document_match.required_anchors || []).map((item) => ({ ...item }));
|
||||
documentMatch.optionalAnchors = (definition.document_match.optional_anchors || []).map((item) => ({ ...item }));
|
||||
documentMatch.minimumScore = definition.document_match.minimum_score;
|
||||
documentMatch.minimumMargin = definition.document_match.minimum_margin;
|
||||
documentMatchDirty.value = false;
|
||||
regions.value = restoreRegions(profile);
|
||||
history.value = [];
|
||||
|
||||
+28
-10
@@ -1,26 +1,44 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileEditorRoutePage.vue
|
||||
用途:承接草稿编辑深链并挂载独立编辑页。
|
||||
依赖:Vue Router、OrderProfileEditorPage。
|
||||
逻辑:将路径草稿身份传递给独立编辑页;query 仅传递标签会话,不得改变目标草稿。
|
||||
用途:按 template_mode 路由 Coordinate 编辑器或 XFA 映射工作台。
|
||||
依赖:Vue Router、Profile 详情 API、OrderProfileEditorPage、XfaProfileMappingPage。
|
||||
逻辑:加载草稿后鉴别联合;coordinate 保持原编辑器,xfa_dataset 进入映射页。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
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);
|
||||
|
||||
/**
|
||||
* 路由参数由编辑页直接读取;本页只在挂载前准备渲染,避免旧 query 身份适配。
|
||||
* @returns 设置完成后显示编辑页。
|
||||
* 读取草稿 template_mode 后选择编辑器。
|
||||
*/
|
||||
function prepareEditor(): void {
|
||||
ready.value = true;
|
||||
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'));
|
||||
}
|
||||
}
|
||||
|
||||
prepareEditor();
|
||||
onMounted(prepareEditor);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<OrderProfileEditorPage v-if="ready" />
|
||||
<XfaProfileMappingPage v-if="ready && isXfa" />
|
||||
<OrderProfileEditorPage v-else-if="ready" />
|
||||
</template>
|
||||
+272
-24
@@ -1,8 +1,8 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfilePublishCheckPage.vue
|
||||
用途:以当前已验证草稿生成可读的发布检查,并在门禁通过后发布模板。
|
||||
用途:展示版面签名、跨模板唯一性与发布阻断项,并在门禁通过后发布模板。
|
||||
依赖:发布检查 API、验证运行 API、Vue Router 和统一消息提示。
|
||||
逻辑:自动选择当前样本试读的通过运行;阻断项不可绕过,语义差异必须逐项确认。
|
||||
逻辑:自动选择当前样本试读通过运行;服务端生成签名/重叠验证;阻断项不可绕过,语义差异须逐项确认。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
@@ -10,37 +10,264 @@ import { useRoute, useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { acquireOrderDocumentProfileEditLease, confirmOrderProfilePublishCheck, createOrderProfilePublishCheck, listOrderProfileValidationRuns } from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type { OrderProfilePublishCheckReport, OrderProfileValidationRun } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import {
|
||||
acquireOrderDocumentProfileEditLease,
|
||||
confirmOrderProfilePublishCheck,
|
||||
createOrderProfilePublishCheck,
|
||||
listOrderProfileValidationRuns,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type {
|
||||
OrderProfileOverlapConflictProfile,
|
||||
OrderProfilePublishCheckReport,
|
||||
OrderProfileValidationRun,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const message = useMessage();
|
||||
const { t } = useI18n();
|
||||
const profileId = Number(route.params.profileId);
|
||||
const runs = ref<OrderProfileValidationRun[]>([]);
|
||||
const report = ref<OrderProfilePublishCheckReport | null>(null);
|
||||
const confirmed = ref<string[]>([]);
|
||||
const busy = ref(false);
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
|
||||
const leaseToken = ref('');
|
||||
|
||||
const route = useRoute(); const router = useRouter(); const message = useMessage(); const { t } = useI18n();
|
||||
const profileId = Number(route.params.profileId); const runs = ref<OrderProfileValidationRun[]>([]); const report = ref<OrderProfilePublishCheckReport | null>(null); const confirmed = ref<string[]>([]); const busy = ref(false);
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID(); const leaseToken = ref('');
|
||||
const validationRun = computed(() => runs.value.find((item) => item.run_type === 'current_sample' && item.status === 'passed') || null);
|
||||
const publishable = computed(() => report.value?.status === 'valid' && !report.value.blocking_items.length && confirmed.value.length === report.value.warning_items.length);
|
||||
const layoutSignatureRun = computed(() => runs.value.find((item) => item.run_type === 'layout_signature' && item.status === 'passed') || null);
|
||||
const xfaStructureSignatureRun = computed(() => runs.value.find((item) => item.run_type === 'xfa_structure_signature' && item.status === 'passed') || null);
|
||||
const signatureRun = computed(() => xfaStructureSignatureRun.value || layoutSignatureRun.value);
|
||||
const isXfaReport = computed(() => report.value?.template_mode === 'xfa_dataset' || !!report.value?.xfa_structure_signature_status);
|
||||
const overlapRun = computed(() => runs.value.find((item) => item.run_type === 'cross_template_overlap' && item.status === 'passed') || null);
|
||||
const publishable = computed(() => report.value?.status === 'valid' && !report.value.blocking_items.length && confirmed.value.length === (report.value.warning_items?.length || 0));
|
||||
const conflictProfiles = computed<OrderProfileOverlapConflictProfile[]>(() => report.value?.conflict_profiles || report.value?.overlap_summary?.conflict_profiles || []);
|
||||
const gateStatus = computed<'pass' | 'blocked' | 'pending'>(() => {
|
||||
if (!report.value) return 'pending';
|
||||
return report.value.blocking_items.length ? 'blocked' : 'pass';
|
||||
});
|
||||
|
||||
/** 显示统一业务错误,避免发布页暴露服务端实现细节。 */
|
||||
function fail(error: unknown): void { message.error(error instanceof BusinessError ? error.message : t('admin.orderProfilePublishCheck.failed')); }
|
||||
function fail(error: unknown): void {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.orderProfilePublishCheck.failed'));
|
||||
}
|
||||
|
||||
/** 获取租约后才允许创建或消费报告,避免发布页绕过草稿写保护。 */
|
||||
async function ensureLease(): Promise<boolean> { if (leaseToken.value) return true; try { leaseToken.value = (await acquireOrderDocumentProfileEditLease(profileId, { browser_session_id: sessionId, operation_id: crypto.randomUUID() })).lease_token; return true; } catch (error) { fail(error); return false; } }
|
||||
/** 读取当前草稿仍有效的样本试读;历史 stale 运行不可用于发布。 */
|
||||
async function loadRuns(): Promise<void> { try { runs.value = await listOrderProfileValidationRuns(profileId); } catch (error) { fail(error); } }
|
||||
/** 创建发布检查报告;后端继续复核当前验证、盲测与 Profile 发布前置条件。 */
|
||||
async function createReport(): Promise<void> { if (!validationRun.value || !(await ensureLease())) return; busy.value = true; try { report.value = await createOrderProfilePublishCheck(profileId, { validation_run_id: validationRun.value.id, browser_session_id: sessionId, lease_token: leaseToken.value, operation_id: crypto.randomUUID() }); confirmed.value = []; } catch (error) { fail(error); } finally { busy.value = false; } }
|
||||
async function ensureLease(): Promise<boolean> {
|
||||
if (leaseToken.value) return true;
|
||||
try {
|
||||
leaseToken.value = (await acquireOrderDocumentProfileEditLease(profileId, {
|
||||
browser_session_id: sessionId,
|
||||
operation_id: crypto.randomUUID(),
|
||||
})).lease_token;
|
||||
return true;
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 读取当前草稿仍有效的验证运行;历史 stale 运行不可用于发布。 */
|
||||
async function loadRuns(): Promise<void> {
|
||||
try {
|
||||
runs.value = await listOrderProfileValidationRuns(profileId);
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** 创建发布检查报告;后端继续复核签名、跨模板唯一性、盲测与 Profile 发布前置条件。 */
|
||||
async function createReport(): Promise<void> {
|
||||
if (!validationRun.value || !(await ensureLease())) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
report.value = await createOrderProfilePublishCheck(profileId, {
|
||||
validation_run_id: validationRun.value.id,
|
||||
matching_signature_run_id: signatureRun.value?.id,
|
||||
overlap_validation_run_id: overlapRun.value?.id,
|
||||
browser_session_id: sessionId,
|
||||
lease_token: leaseToken.value,
|
||||
operation_id: crypto.randomUUID(),
|
||||
});
|
||||
confirmed.value = [];
|
||||
await loadRuns();
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 逐项确认警告后消费报告并发布;发布成功后进入只读版本详情。 */
|
||||
async function publish(): Promise<void> { if (!report.value || !publishable.value || !(await ensureLease())) return; busy.value = true; try { const published = await confirmOrderProfilePublishCheck(profileId, report.value.report_no, { confirmed_warning_keys: confirmed.value, browser_session_id: sessionId, lease_token: leaseToken.value, operation_id: crypto.randomUUID() }); await router.replace({ name: 'AdminShippingOrderDocumentProfileVersionDetail', params: { profileCode: published.profile_code, version: String(published.version) } }); } catch (error) { fail(error); } finally { busy.value = false; } }
|
||||
async function publish(): Promise<void> {
|
||||
if (!report.value || !publishable.value || !(await ensureLease())) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
const published = await confirmOrderProfilePublishCheck(profileId, report.value.report_no, {
|
||||
confirmed_warning_keys: confirmed.value,
|
||||
browser_session_id: sessionId,
|
||||
lease_token: leaseToken.value,
|
||||
operation_id: crypto.randomUUID(),
|
||||
});
|
||||
await router.replace({
|
||||
name: 'AdminShippingOrderDocumentProfileVersionDetail',
|
||||
params: { profileCode: published.profile_code, version: String(published.version) },
|
||||
});
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 归一化有限的已知门禁码;未知内容仍保留后端安全摘要。 */
|
||||
function itemMessage(item: Record<string, unknown>): string { const key = String(item.key || ''); return key === 'current_validation_required' ? t('admin.orderProfilePublishCheck.currentValidationRequired') : key === 'semantic_diff_review' ? t('admin.orderProfilePublishCheck.semanticDiffReview') : String(item.message || t('admin.orderProfilePublishCheck.unknownIssue')); }
|
||||
function backToValidation(): void { router.push({ name: 'AdminShippingOrderDocumentProfileValidate', params: route.params, query: { editorSessionId: sessionId } }); }
|
||||
function itemMessage(item: Record<string, unknown>): string {
|
||||
const key = String(item.key || '');
|
||||
const map: Record<string, string> = {
|
||||
current_validation_required: t('admin.orderProfilePublishCheck.currentValidationRequired'),
|
||||
semantic_diff_review: t('admin.orderProfilePublishCheck.semanticDiffReview'),
|
||||
signature_required: t('admin.orderProfilePublishCheck.signatureRequired'),
|
||||
signature_stale: t('admin.orderProfilePublishCheck.signatureStale'),
|
||||
overlap_validation_required: t('admin.orderProfilePublishCheck.overlapRequired'),
|
||||
overlap_validation_stale: t('admin.orderProfilePublishCheck.overlapStale'),
|
||||
overlap_validation_failed: t('admin.orderProfilePublishCheck.overlapFailed'),
|
||||
self_match_not_unique: t('admin.orderProfilePublishCheck.selfMatchNotUnique'),
|
||||
self_match_not_unique_blind: t('admin.orderProfilePublishCheck.selfMatchNotUniqueBlind'),
|
||||
cross_template_false_hit: t('admin.orderProfilePublishCheck.crossTemplateFalseHit'),
|
||||
cross_template_ambiguous: t('admin.orderProfilePublishCheck.crossTemplateAmbiguous'),
|
||||
cross_template_parse_failed: t('admin.orderProfilePublishCheck.crossTemplateParseFailed'),
|
||||
cross_template_coverage_insufficient: t('admin.orderProfilePublishCheck.crossTemplateCoverageInsufficient'),
|
||||
cross_template_margin_insufficient: t('admin.orderProfilePublishCheck.crossTemplateMarginInsufficient'),
|
||||
sample_role_pollution: t('admin.orderProfilePublishCheck.sampleRolePollution'),
|
||||
cross_template_conflict_profiles: t('admin.orderProfilePublishCheck.crossTemplateConflictProfiles'),
|
||||
};
|
||||
return map[key] || String(item.message || t('admin.orderProfilePublishCheck.unknownIssue'));
|
||||
}
|
||||
|
||||
/** 格式化百分比指标,供唯一性卡片展示。 */
|
||||
function formatRate(value: number | null | undefined): string {
|
||||
if (value == null) return '—';
|
||||
return `${Math.round(value * 1000) / 10}%`;
|
||||
}
|
||||
|
||||
function backToValidation(): void {
|
||||
router.push({ name: 'AdminShippingOrderDocumentProfileValidate', params: route.params, query: { editorSessionId: sessionId } });
|
||||
}
|
||||
|
||||
/** 冲突修复必须回到唯一可修改的模板编辑器,避免用户在验证页无路可走。 */
|
||||
function backToEditor(): void {
|
||||
router.push({ name: 'AdminShippingOrderDocumentProfileEdit', params: route.params, query: { editorSessionId: sessionId } });
|
||||
}
|
||||
|
||||
function signatureStatus(value: string | undefined): string {
|
||||
const map: Record<string, string> = {
|
||||
valid: t('admin.orderProfilePublishCheck.statusValid'),
|
||||
missing: t('admin.orderProfilePublishCheck.statusMissing'),
|
||||
stale: t('admin.orderProfilePublishCheck.statusStale'),
|
||||
};
|
||||
return map[value || ''] || '—';
|
||||
}
|
||||
|
||||
function conflictReason(value: string): string {
|
||||
const map: Record<string, string> = {
|
||||
false_hit: t('admin.orderProfilePublishCheck.crossTemplateFalseHit'),
|
||||
reverse_false_hit: t('admin.orderProfilePublishCheck.crossTemplateFalseHit'),
|
||||
ambiguous: t('admin.orderProfilePublishCheck.crossTemplateAmbiguous'),
|
||||
profile_parse_validation_failed: t('admin.orderProfilePublishCheck.crossTemplateParseFailed'),
|
||||
profile_evidence_coverage_insufficient: t('admin.orderProfilePublishCheck.crossTemplateCoverageInsufficient'),
|
||||
profile_margin_insufficient: t('admin.orderProfilePublishCheck.crossTemplateMarginInsufficient'),
|
||||
};
|
||||
return map[value] || t('admin.orderProfilePublishCheck.unknownIssue');
|
||||
}
|
||||
|
||||
onMounted(loadRuns);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="page">
|
||||
<header><div><h1 class="section-title">{{ t('admin.orderProfilePublishCheck.title') }}</h1><small class="section-desc mt-1">{{ t('admin.orderProfilePublishCheck.description') }}</small></div><button type="button" class="btn-secondary" @click="backToValidation">{{ t('admin.orderProfilePublishCheck.back') }}</button></header>
|
||||
<section v-if="!report" class="card"><h2>{{ t('admin.orderProfilePublishCheck.readyTitle') }}</h2><p>{{ validationRun ? t('admin.orderProfilePublishCheck.readyHint') : t('admin.orderProfilePublishCheck.noRun') }}</p><button class="btn-primary" :disabled="busy || !validationRun" type="button" @click="createReport">{{ t('admin.orderProfilePublishCheck.create') }}</button></section>
|
||||
<section v-else class="card"><h2>{{ t('admin.orderProfilePublishCheck.reportTitle') }}</h2><p>{{ report.blocking_items.length ? t('admin.orderProfilePublishCheck.blockedHint') : t('admin.orderProfilePublishCheck.reviewHint') }}</p><h3>{{ t('admin.orderProfilePublishCheck.blocking') }}</h3><p v-if="!report.blocking_items.length" class="good">{{ t('admin.orderProfilePublishCheck.noBlocking') }}</p><ul><li v-for="item in report.blocking_items" :key="String(item.key)">{{ itemMessage(item) }}</li></ul><h3>{{ t('admin.orderProfilePublishCheck.warnings') }}</h3><label v-for="item in report.warning_items" :key="String(item.key)"><input v-model="confirmed" type="checkbox" :value="String(item.key)"><span>{{ itemMessage(item) }}</span></label><p v-if="report.warning_items.length" class="hint">{{ t('admin.orderProfilePublishCheck.confirmHint') }}</p><button class="btn-primary" :disabled="busy || !publishable" type="button" @click="publish">{{ t('admin.orderProfilePublishCheck.confirm') }}</button></section>
|
||||
<header>
|
||||
<div>
|
||||
<h1 class="section-title">{{ t('admin.orderProfilePublishCheck.title') }}</h1>
|
||||
<small class="section-desc mt-1">{{ t('admin.orderProfilePublishCheck.description') }}</small>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary" @click="backToValidation">{{ t('admin.orderProfilePublishCheck.back') }}</button>
|
||||
</header>
|
||||
|
||||
<section v-if="!report" class="card">
|
||||
<h2>{{ t('admin.orderProfilePublishCheck.readyTitle') }}</h2>
|
||||
<p>{{ validationRun ? t('admin.orderProfilePublishCheck.readyHint') : t('admin.orderProfilePublishCheck.noRun') }}</p>
|
||||
<button class="btn-primary" :disabled="busy || !validationRun" type="button" @click="createReport">
|
||||
{{ t('admin.orderProfilePublishCheck.create') }}
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<template v-else>
|
||||
<section class="card">
|
||||
<div class="card-head">
|
||||
<h2>{{ t('admin.orderProfilePublishCheck.reportTitle') }}</h2>
|
||||
<button class="btn-secondary" :disabled="busy || !validationRun" type="button" @click="createReport">
|
||||
{{ t('admin.orderProfilePublishCheck.rerun') }}
|
||||
</button>
|
||||
</div>
|
||||
<p :class="['gate-status', gateStatus]">{{ gateStatus === 'blocked' ? t('admin.orderProfilePublishCheck.blockedHint') : t('admin.orderProfilePublishCheck.reviewHint') }}</p>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h3>{{ isXfaReport ? t('admin.orderProfilePublishCheck.xfaStructureSignatureTitle') : t('admin.orderProfilePublishCheck.layoutSignatureTitle') }}</h3>
|
||||
<dl class="metrics">
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.signatureStatus') }}</dt><dd :class="`status-${(isXfaReport ? report.xfa_structure_signature_status : report.layout_signature_status)?.status || 'unknown'}`">{{ signatureStatus((isXfaReport ? report.xfa_structure_signature_status : report.layout_signature_status)?.status) }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.signatureSampleCount') }}</dt><dd>{{ (isXfaReport ? report.xfa_structure_signature_status : report.layout_signature_status)?.source_sample_count ?? '—' }}</dd></div>
|
||||
<div v-if="!isXfaReport"><dt>{{ t('admin.orderProfilePublishCheck.signatureHeaderCoverage') }}</dt><dd>{{ formatRate(report.layout_signature_status?.header_token_coverage) }}</dd></div>
|
||||
<div v-if="isXfaReport"><dt>{{ t('admin.orderProfilePublishCheck.xfaStructureFingerprint') }}</dt><dd>{{ report.xfa_structure_signature_status?.dataset_structure_fingerprint || report.xfa_structure_signature_summary?.dataset_structure_fingerprint || '—' }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.matcherPolicyVersion') }}</dt><dd>{{ report.matcher_policy_version || (isXfaReport ? report.xfa_structure_signature_status : report.layout_signature_status)?.matcher_policy_version || '—' }}</dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h3>{{ t('admin.orderProfilePublishCheck.uniquenessTitle') }}</h3>
|
||||
<dl class="metrics">
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.trainingUniqueRate') }}</dt><dd>{{ formatRate(report.overlap_summary?.self_unique_hit_rate_training) }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.blindUniqueRate') }}</dt><dd>{{ formatRate(report.overlap_summary?.self_unique_hit_rate_blind) }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.falseHitCount') }}</dt><dd>{{ report.overlap_summary?.false_hit_other_count ?? 0 }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.reverseFalseHitCount') }}</dt><dd>{{ report.overlap_summary?.reverse_false_hit_count ?? 0 }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.ambiguousCount') }}</dt><dd>{{ report.overlap_summary?.ambiguous_count ?? 0 }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.minEvidenceCoverage') }}</dt><dd>{{ formatRate(report.overlap_summary?.min_evidence_coverage) }} / ≥ {{ formatRate(report.overlap_summary?.thresholds?.evidence_coverage_minimum) }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.minMargin') }}</dt><dd>{{ report.overlap_summary?.min_margin ?? '—' }} / ≥ {{ report.overlap_summary?.thresholds?.minimum_margin ?? '—' }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.parseFailedCount') }}</dt><dd>{{ report.overlap_summary?.parse_validation_failed_count ?? 0 }}</dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section v-if="conflictProfiles.length" class="card">
|
||||
<h3>{{ t('admin.orderProfilePublishCheck.conflictsTitle') }}</h3>
|
||||
<article v-for="conflict in conflictProfiles" :key="`${conflict.profile_code}-${conflict.version}`" class="conflict-card">
|
||||
<strong>{{ conflict.profile_code }} v{{ conflict.version }}</strong>
|
||||
<p class="reasons">{{ conflict.reason_codes.map(conflictReason).join(';') }}</p>
|
||||
<p>{{ conflict.suggestion }}</p>
|
||||
<button type="button" class="btn-secondary" @click="backToEditor">{{ t('admin.orderProfilePublishCheck.backToEditor') }}</button>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h3>{{ t('admin.orderProfilePublishCheck.blocking') }}</h3>
|
||||
<p v-if="!report.blocking_items.length" class="good">{{ t('admin.orderProfilePublishCheck.noBlocking') }}</p>
|
||||
<ul v-else>
|
||||
<li v-for="item in report.blocking_items" :key="String(item.key)">{{ itemMessage(item) }}</li>
|
||||
</ul>
|
||||
|
||||
<h3>{{ t('admin.orderProfilePublishCheck.warnings') }}</h3>
|
||||
<label v-for="item in report.warning_items" :key="String(item.key)">
|
||||
<input v-model="confirmed" type="checkbox" :value="String(item.key)">
|
||||
<span>{{ itemMessage(item) }}</span>
|
||||
</label>
|
||||
<p v-if="report.warning_items.length" class="hint">{{ t('admin.orderProfilePublishCheck.confirmHint') }}</p>
|
||||
<button class="btn-primary" :disabled="busy || !publishable" type="button" @click="publish">
|
||||
{{ t('admin.orderProfilePublishCheck.confirm') }}
|
||||
</button>
|
||||
</section>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.page { width: 100%; margin: 0; padding: 24px; color: #334155; }
|
||||
.page header { display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: space-between; gap: 16px; }
|
||||
@@ -48,8 +275,29 @@ onMounted(loadRuns);
|
||||
.page small:not(.section-desc), .card p { color: #64748b; font-size: 13px; line-height: 1.5; }
|
||||
.page small { display: block; margin-top: 5px; }
|
||||
.card { margin-top: 20px; border: 1px solid #dfe7ef; border-radius: 10px; background: #fff; padding: 16px; box-shadow: 0 1px 2px rgb(15 23 42 / 3%); }
|
||||
.card h2 { margin: 0; color: #1e293b; font-size: 15px; font-weight: 600; }.card h3 { margin: 20px 0 8px; color: #1e293b; font-size: 14px; }
|
||||
.card label { display: flex; gap: 8px; margin: 10px 0; color: #475569; font-size: 13px; }.card input { accent-color: #0ea5e9; }
|
||||
.card .btn-primary { margin-top: 14px; }.good { color: #15803d; font-size: 13px; }.hint { font-size: 13px; }ul { margin: 8px 0; padding-left: 20px; color: #b91c1c; font-size: 13px; }
|
||||
@media(max-width:767px) { .page { padding: 16px; }.page header { display: grid; }.page header button { width: 100%; } }
|
||||
.card-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.card h2 { margin: 0; color: #1e293b; font-size: 15px; font-weight: 600; }
|
||||
.card h3 { margin: 0 0 12px; color: #1e293b; font-size: 14px; }
|
||||
.card label { display: flex; gap: 8px; margin: 10px 0; color: #475569; font-size: 13px; }
|
||||
.card input { accent-color: #0ea5e9; }
|
||||
.card .btn-primary { margin-top: 14px; }
|
||||
.good { color: #15803d; font-size: 13px; }
|
||||
.gate-status { font-weight: 600; }
|
||||
.gate-status.blocked { color: #b91c1c; }
|
||||
.gate-status.pass, .status-valid { color: #15803d; }
|
||||
.status-missing, .status-stale { color: #b45309; }
|
||||
.hint { font-size: 13px; }
|
||||
ul { margin: 8px 0; padding-left: 20px; color: #b91c1c; font-size: 13px; }
|
||||
.metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin: 0; }
|
||||
.metrics div { display: grid; gap: 4px; }
|
||||
.metrics dt { color: #64748b; font-size: 12px; }
|
||||
.metrics dd { margin: 0; color: #1e293b; font-size: 14px; font-weight: 600; }
|
||||
.conflict-card { border: 1px solid #fecaca; background: #fff7f7; border-radius: 8px; padding: 12px; margin-top: 10px; }
|
||||
.conflict-card strong { color: #991b1b; font-size: 13px; }
|
||||
.conflict-card .reasons { color: #b45309; font-size: 12px; }
|
||||
@media (max-width: 767px) {
|
||||
.page { padding: 16px; }
|
||||
.page header, .card-head { display: grid; }
|
||||
.page header button, .card-head button { width: 100%; }
|
||||
}
|
||||
</style>
|
||||
+194
-21
@@ -2,7 +2,8 @@
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileValidationPage.vue
|
||||
用途:验证当前订单模板草稿,并按“基础验证、盲测、发布检查”顺序引导管理员。
|
||||
依赖:Profile 验证 API、编辑租约、Vue Router、统一消息提示。
|
||||
逻辑:一次动作依次执行结构检查和当前样本试读;盲测批准前不解锁发布检查入口。
|
||||
逻辑:一次动作依次执行结构检查和当前样本试读;XFA 从验证摘要展示脱敏字段级结果;
|
||||
盲测批准前不解锁发布检查入口。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
@@ -30,10 +31,14 @@ import type {
|
||||
OrderProfileTestSuite,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import {
|
||||
asCoordinateProfileDefinition,
|
||||
isXfaDatasetProfileDefinition,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const { t } = useI18n();
|
||||
const { t, te } = useI18n();
|
||||
const message = useMessage();
|
||||
const profileId = Number(route.params.profileId);
|
||||
const runs = ref<OrderProfileValidationRun[]>([]);
|
||||
@@ -49,6 +54,94 @@ const resultFailed = ref(false);
|
||||
const fieldNames = ref(new Map<string, string>());
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
|
||||
const blindTestSuite = ref<OrderProfileTestSuite | null>(null);
|
||||
const isXfa = computed(() => (
|
||||
!!profile.value
|
||||
&& (profile.value.template_mode === 'xfa_dataset' || isXfaDatasetProfileDefinition(profile.value.definition))
|
||||
));
|
||||
const xfaSummary = computed(() => sampleRun.value?.summary || null);
|
||||
const xfaHeaderFields = computed(() => {
|
||||
const rows = xfaSummary.value?.header_fields;
|
||||
return Array.isArray(rows) ? rows as Array<Record<string, unknown>> : [];
|
||||
});
|
||||
const xfaLines = computed(() => {
|
||||
const rows = xfaSummary.value?.lines;
|
||||
return Array.isArray(rows) ? rows as Array<Record<string, unknown>> : [];
|
||||
});
|
||||
const XFA_CROSS_CHECK_KEYS = [
|
||||
'mirror_status',
|
||||
'acroform_status',
|
||||
'line_amount_status',
|
||||
'total_amount_status',
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* 从字段预览中取标准化值。
|
||||
*/
|
||||
function xfaFieldNormalized(
|
||||
fields: Array<Record<string, unknown>>,
|
||||
fieldCode: string,
|
||||
): string {
|
||||
const hit = fields.find((item) => String(item.field_code || '') === fieldCode);
|
||||
return String(hit?.normalized_value ?? '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 将交叉校验技术状态映射为管理员可读说明(含金额计算过程)。
|
||||
*/
|
||||
const xfaCrossCheckEntries = computed(() => {
|
||||
const checks = xfaSummary.value?.cross_checks;
|
||||
if (!checks || typeof checks !== 'object' || Array.isArray(checks)) return [];
|
||||
const map = checks as Record<string, unknown>;
|
||||
const firstLineFields = Array.isArray(xfaLines.value[0]?.fields)
|
||||
? (xfaLines.value[0].fields as Array<Record<string, unknown>>)
|
||||
: [];
|
||||
const qty = xfaFieldNormalized(firstLineFields, 'quantity');
|
||||
const unitPrice = xfaFieldNormalized(firstLineFields, 'unit_price');
|
||||
const priceUnit = xfaFieldNormalized(firstLineFields, 'price_unit') || '1';
|
||||
const amount = xfaFieldNormalized(firstLineFields, 'amount');
|
||||
const total = xfaFieldNormalized(xfaHeaderFields.value, 'total_amount')
|
||||
|| xfaFieldNormalized(xfaHeaderFields.value, 'order_amount');
|
||||
const lineSum = xfaLines.value.reduce((sum, line) => {
|
||||
const fields = Array.isArray(line.fields)
|
||||
? (line.fields as Array<Record<string, unknown>>)
|
||||
: [];
|
||||
const raw = xfaFieldNormalized(fields, 'amount').replace(/,/g, '');
|
||||
const n = Number(raw);
|
||||
return Number.isFinite(n) ? sum + n : sum;
|
||||
}, 0);
|
||||
const lineSumText = Number.isFinite(lineSum) && lineSum > 0
|
||||
? String(Number(lineSum.toFixed(2)))
|
||||
: amount;
|
||||
|
||||
return XFA_CROSS_CHECK_KEYS
|
||||
.filter((key) => map[key] != null && String(map[key]).trim() !== '')
|
||||
.map((key) => {
|
||||
const status = String(map[key] ?? '').trim().toLowerCase();
|
||||
const label = t(`admin.orderProfileValidation.xfaCheckLabel.${key}`);
|
||||
const statusLabel = t(
|
||||
`admin.orderProfileValidation.xfaCheckStatus.${status}`,
|
||||
status || '-',
|
||||
);
|
||||
let detail = '';
|
||||
if (key === 'line_amount_status' && qty && unitPrice && amount) {
|
||||
detail = t('admin.orderProfileValidation.xfaAmountFormula', {
|
||||
quantity: qty,
|
||||
unitPrice,
|
||||
priceUnit,
|
||||
amount,
|
||||
});
|
||||
} else if (key === 'total_amount_status' && total && lineSumText) {
|
||||
detail = t('admin.orderProfileValidation.xfaTotalFormula', {
|
||||
total,
|
||||
lineSum: lineSumText,
|
||||
});
|
||||
} else if (key === 'mirror_status' || key === 'acroform_status') {
|
||||
const hintKey = `admin.orderProfileValidation.xfaCheckHint.${key}.${status}`;
|
||||
detail = te(hintKey) ? t(hintKey) : '';
|
||||
}
|
||||
return { key, label, statusLabel, detail, status };
|
||||
});
|
||||
});
|
||||
|
||||
const latestRun = (runType: OrderProfileValidationRun['run_type']) =>
|
||||
runs.value.find((item) => item.run_type === runType) || null;
|
||||
@@ -95,7 +188,12 @@ async function loadContext(): Promise<void> {
|
||||
getOrderDocumentProfileDetail(profileId), listOrderProfileBoundSamples(profileId),
|
||||
]);
|
||||
profile.value = detail;
|
||||
sample.value = samples.find((item) => item.sample_role === 'annotation' || item.sample_role === 'training') || null;
|
||||
const selectedSample = samples.find((item) => item.sample_role === 'annotation' || item.sample_role === 'training') || null;
|
||||
// Validation must use the immutable table identity captured with the sample;
|
||||
// a legacy mutable binding can point at a table id from a newer layout.
|
||||
sample.value = selectedSample
|
||||
? { ...selectedSample, table_id: selectedSample.table_identity_snapshot?.table_id || selectedSample.table_id }
|
||||
: null;
|
||||
const schema = await getShippingOrderSchemaVersion(detail.schema_version_id);
|
||||
fieldNames.value = new Map((schema.definition?.fields || []).map((field) => [field.field_code || '', field.display_name]));
|
||||
} catch (error) { report(error); }
|
||||
@@ -104,28 +202,44 @@ async function loadContext(): Promise<void> {
|
||||
/** Schema 显示名称服务于业务核对;稳定编码仅作为辅助追溯信息保留。 */
|
||||
function fieldName(fieldCode: string): string { return fieldNames.value.get(fieldCode) || fieldCode; }
|
||||
|
||||
/** 使用本次草稿定义重读全部已绑定表头页和明细;结果只来自实时接口,不回退历史建议文本。 */
|
||||
/** 使用本次草稿定义重读全部已绑定表头页和明细;XFA 从验证摘要读取字段级结果。 */
|
||||
async function loadReadResults(): Promise<void> {
|
||||
if (!profile.value || !sample.value?.table_id) return;
|
||||
if (!profile.value || !sample.value) return;
|
||||
if (isXfa.value) {
|
||||
// XFA 字段级结果来自 current_sample summary,不请求坐标预览。
|
||||
headerValues.value = [];
|
||||
linePreview.value = null;
|
||||
resultFailed.value = false;
|
||||
return;
|
||||
}
|
||||
if (!sample.value.table_id) return;
|
||||
resultLoading.value = true;
|
||||
resultFailed.value = false;
|
||||
try {
|
||||
const pageNos = Array.from(new Set((profile.value.definition.order_field_layouts || []).map((item) => (
|
||||
const definition = asCoordinateProfileDefinition(profile.value.definition);
|
||||
const pageNos = Array.from(new Set((definition.order_field_layouts || []).map((item) => (
|
||||
item.page_scope === 'exact_page' ? (item.page_no || 1) : 1
|
||||
)))).sort((left, right) => left - right);
|
||||
const pageNo = pageNos[0] || sample.value.table_identity_snapshot?.page_no || 1;
|
||||
const [headers, lines] = await Promise.all([
|
||||
previewOrderProfileOrderFieldValues(
|
||||
sample.value.document_id, profile.value.schema_version_id, pageNo, profile.value.definition, pageNos,
|
||||
),
|
||||
previewOrderProfileRegion(profileId, sample.value.document_id, sample.value.table_id, profile.value.definition),
|
||||
]);
|
||||
headerValues.value = headers.fields;
|
||||
linePreview.value = lines;
|
||||
} catch {
|
||||
headerValues.value = [];
|
||||
linePreview.value = null;
|
||||
resultFailed.value = true;
|
||||
let failed = false;
|
||||
try {
|
||||
const headers = await previewOrderProfileOrderFieldValues(
|
||||
sample.value.document_id, profile.value.schema_version_id, pageNo, definition, pageNos,
|
||||
);
|
||||
headerValues.value = headers.fields;
|
||||
} catch {
|
||||
headerValues.value = [];
|
||||
failed = true;
|
||||
}
|
||||
try {
|
||||
linePreview.value = await previewOrderProfileRegion(
|
||||
profileId, sample.value.document_id, sample.value.table_id || '', definition,
|
||||
);
|
||||
} catch {
|
||||
linePreview.value = null;
|
||||
failed = true;
|
||||
}
|
||||
resultFailed.value = failed;
|
||||
} finally { resultLoading.value = false; }
|
||||
}
|
||||
|
||||
@@ -226,8 +340,65 @@ onMounted(async () => {
|
||||
</section>
|
||||
|
||||
<section v-if="profile && sample" class="results" :aria-label="t('admin.orderProfileValidation.resultsTitle')">
|
||||
<div class="results-heading"><div><h2>{{ t('admin.orderProfileValidation.resultsTitle') }}</h2><p>{{ t('admin.orderProfileValidation.resultsHint') }}</p></div><button type="button" class="btn-secondary btn-sm" :disabled="resultLoading" @click="loadReadResults">{{ t('admin.orderProfileValidation.refreshResults') }}</button></div>
|
||||
<p v-if="resultLoading">{{ t('admin.orderProfileValidation.resultsLoading') }}</p>
|
||||
<div class="results-heading"><div><h2>{{ t('admin.orderProfileValidation.resultsTitle') }}</h2><p>{{ isXfa ? t('admin.orderProfileValidation.xfaResultsHint') : t('admin.orderProfileValidation.resultsHint') }}</p></div><button v-if="!isXfa" type="button" class="btn-secondary btn-sm" :disabled="resultLoading" @click="loadReadResults">{{ t('admin.orderProfileValidation.refreshResults') }}</button></div>
|
||||
<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>
|
||||
|
||||
<h3>{{ t('admin.orderProfileValidation.xfaCrossCheckStatus') }}</h3>
|
||||
<dl v-if="xfaCrossCheckEntries.length" class="header-results">
|
||||
<div
|
||||
v-for="item in xfaCrossCheckEntries"
|
||||
:key="item.key"
|
||||
:class="`field-${item.status === 'matched' || item.status === 'passed' || item.status === 'skipped' ? 'passed' : 'failed'}`"
|
||||
>
|
||||
<dt>{{ item.label }}</dt>
|
||||
<dd>{{ item.statusLabel }}</dd>
|
||||
<dd v-if="item.detail" class="field-code">{{ item.detail }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<h3>{{ t('admin.orderProfileValidation.xfaHeaderFields') }}</h3>
|
||||
<dl v-if="xfaHeaderFields.length" class="header-results">
|
||||
<div
|
||||
v-for="field in xfaHeaderFields"
|
||||
:key="String(field.field_id || field.field_code)"
|
||||
:class="`field-${String(field.status || 'missing')}`"
|
||||
>
|
||||
<dt>{{ fieldName(String(field.field_code || '')) }}</dt>
|
||||
<dd class="field-code">{{ field.field_code }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaMaskedRaw') }}:{{ field.masked_raw_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaNormalized') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p v-else>{{ t('admin.orderProfileValidation.xfaNoFieldPreview') }}</p>
|
||||
|
||||
<h3>{{ t('admin.orderProfileValidation.xfaLineFields') }}</h3>
|
||||
<div v-if="xfaLines.length" class="line-results">
|
||||
<article v-for="line in xfaLines" :key="String(line.row_index)" class="xfa-line-card">
|
||||
<h4>#{{ Number(line.row_index) + 1 }}</h4>
|
||||
<dl class="header-results">
|
||||
<div
|
||||
v-for="field in (Array.isArray(line.fields) ? line.fields : [])"
|
||||
:key="String(field.field_id || field.field_code)"
|
||||
:class="`field-${String(field.status || 'missing')}`"
|
||||
>
|
||||
<dt>{{ fieldName(String(field.field_code || '')) }}</dt>
|
||||
<dd class="field-code">{{ field.field_code }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaMaskedRaw') }}:{{ field.masked_raw_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaNormalized') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
</div>
|
||||
<p v-else>{{ t('admin.orderProfileValidation.xfaNoFieldPreview') }}</p>
|
||||
</template>
|
||||
<p v-else-if="resultLoading">{{ t('admin.orderProfileValidation.resultsLoading') }}</p>
|
||||
<p v-else-if="resultFailed" class="result-error">{{ t('admin.orderProfileValidation.resultsFailed') }}</p>
|
||||
<template v-else>
|
||||
<h3>{{ t('admin.orderProfileValidation.headerResults') }}</h3>
|
||||
@@ -254,6 +425,8 @@ button:disabled { cursor: not-allowed; opacity: .55; }
|
||||
.current-draft-validation { display: grid; gap: 16px; margin-top: 20px; padding: 16px; }.current-draft-validation > header { align-items: center; }.current-draft-validation > header > div { min-width: 0; }.current-draft-validation > header button { flex: 0 0 auto; }.checks { display: grid; gap: 10px; }.checks article { display: flex; align-items: center; justify-content: space-between; gap: 20px; border-radius: 8px; padding: 15px 16px; }.status { min-width: 72px; text-align: right; font-size: 13px; font-weight: 600; }.passed { color: #15803d; }.failed, .stale { color: #b91c1c; }.pending, .running { color: #64748b; }
|
||||
.blind-test-gate { display: flex; align-items: center; justify-content: space-between; gap: 20px; margin-top: 20px; padding: 16px; }.blind-test-gate h2 { margin: 0; color: #1e293b; font-size: 15px; font-weight: 600; }.gate-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }.gate-actions .approved { color: #15803d; }.gate-actions .draft, .gate-actions .missing { color: #b45309; }
|
||||
.results { margin-top: 20px; padding: 16px; }.results-heading { display: flex; align-items: center; justify-content: space-between; gap: 16px; }.results h2, .results h3 { margin: 0; color: #1e293b; }.results h2 { font-size: 15px; }.results h3 { margin-top: 20px; font-size: 14px; }.results-heading p { margin: 5px 0 0; color: #64748b; font-size: 13px; line-height: 1.5; }.header-results { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px; margin: 12px 0 0; }.header-results div { border: 1px solid #e5ebf1; border-radius: 6px; background: #fbfdff; padding: 10px; }.header-results dt { color: #475569; font-size: 13px; font-weight: 600; }.header-results dd { margin: 4px 0 0; overflow-wrap: anywhere; }.header-results .field-code, .line-results th small { color: #94a3b8; font-size: 11px; font-weight: 400; }.line-results { margin-top: 12px; overflow-x: auto; border: 1px solid #e5ebf1; border-radius: 6px; }.line-results table { width: 100%; min-width: 560px; border-collapse: collapse; }.line-results th, .line-results td { padding: 10px 12px; border-bottom: 1px solid #e5ebf1; text-align: left; vertical-align: top; overflow-wrap: anywhere; }.line-results tbody tr:last-child td { border-bottom: 0; }.line-results th { background: #f8fafc; color: #64748b; font-size: 12px; font-weight: 600; }.line-results th span, .line-results th small { display: block; }.deleted-row { color: #94a3b8; text-decoration: line-through; }.result-error { color: #b91c1c; }
|
||||
.header-results .field-needs_review, .header-results .field-unavailable { border-color: #fed7aa; background: #fff7ed; }.header-results .field-issues { color: #b45309; font-size: 11px; }
|
||||
.header-results .field-needs_review, .header-results .field-unavailable, .header-results .field-failed, .header-results .field-missing { border-color: #fed7aa; background: #fff7ed; }.header-results .field-issues { color: #b45309; font-size: 11px; }
|
||||
.header-results .field-passed { border-color: #bbf7d0; background: #f0fdf4; }
|
||||
.xfa-line-card { margin-top: 12px; padding: 12px; border: 1px solid #e5ebf1; border-radius: 8px; background: #fbfdff; }.xfa-line-card h4 { margin: 0 0 8px; font-size: 13px; color: #475569; }
|
||||
@media (max-width: 767px) { .validation-page { padding: 16px; } header, .validation-state, .current-draft-validation > header, .checks article, .blind-test-gate, .results-heading { display: grid; }.validation-state button, .current-draft-validation > header button, .blind-test-gate button, .results-heading button { width: 100%; } }
|
||||
</style>
|
||||
+293
@@ -0,0 +1,293 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/XfaProfileMappingPage.spec.ts
|
||||
* 用途:挂载 XFA 映射页并验证四栏布局加载。
|
||||
* 依赖:Vitest、@vue/test-utils、XfaProfileMappingPage。
|
||||
*/
|
||||
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';
|
||||
|
||||
const { saveDraftMock, splitPreviewMock, detailDefinition } = vi.hoisted(() => ({
|
||||
saveDraftMock: vi.fn(),
|
||||
splitPreviewMock: vi.fn(),
|
||||
detailDefinition: { value: null as Record<string, unknown> | null },
|
||||
}));
|
||||
|
||||
const baseDefinition = {
|
||||
template_mode: 'xfa_dataset' as const,
|
||||
source_contract: {
|
||||
template_packet_checksum: 'sha256:tpl',
|
||||
dataset_structure_fingerprint: 'sha256:fp',
|
||||
dataset_root_path: '/data',
|
||||
authoritative_line_collection_path: '/data/ITEMS/DATA',
|
||||
mirror_collection_paths: [],
|
||||
},
|
||||
header_mappings: [],
|
||||
line_mapping: { row_path: '/data/ITEMS/DATA', fields: [] },
|
||||
cross_checks: {
|
||||
acroform_enabled: 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,
|
||||
},
|
||||
split_rules: [],
|
||||
};
|
||||
|
||||
vi.mock('vue-router', () => ({
|
||||
useRoute: () => ({ params: { profileId: '52', profileCode: 'ODP-TEST' }, query: {} }),
|
||||
useRouter: () => ({ push: vi.fn() }),
|
||||
onBeforeRouteLeave: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({ success: vi.fn(), error: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
|
||||
getOrderDocumentProfileDetail: vi.fn(async () => ({
|
||||
id: 52,
|
||||
profile_code: 'ODP-TEST',
|
||||
display_name: 'Fox PO',
|
||||
schema_version_id: 1,
|
||||
lock_version: 1,
|
||||
template_mode: 'xfa_dataset',
|
||||
definition: structuredClone(detailDefinition.value || baseDefinition),
|
||||
})),
|
||||
listOrderProfileBoundSamples: vi.fn(async () => [{ document_id: 85, sample_role: 'annotation' }]),
|
||||
getOrderProfileSampleXfaFieldTree: vi.fn(async () => ({
|
||||
tree: {
|
||||
path_id: 'root-data', local_name: 'data', data_path_hash: 'h0', depth: 0, cardinality: 'one',
|
||||
is_leaf: false, is_collection_candidate: false, children: [
|
||||
{
|
||||
path_id: 'invoiced-to-path', local_name: 'INVOICED_TO', data_path_hash: 'hh', depth: 1, cardinality: 'one',
|
||||
is_leaf: true, sample_value_display: 'Cloud Network', display_policy: 'full',
|
||||
},
|
||||
{
|
||||
path_id: 'items-data', local_name: 'DATA', data_path_hash: 'h', depth: 1, cardinality: 'many',
|
||||
is_leaf: false, is_collection_candidate: true, children: [{
|
||||
path_id: 'material-path', local_name: 'MATNR', data_path_hash: 'h2', depth: 2, cardinality: 'one',
|
||||
is_leaf: true, sample_value_display: 'TEMP-S', display_policy: 'full',
|
||||
}],
|
||||
},
|
||||
],
|
||||
},
|
||||
})),
|
||||
getOrderProfileSampleXfaCollections: vi.fn(async () => ({
|
||||
collection_candidates: [{ path_id: 'items-data', collection_path_hash: 'h', row_count: 1 }],
|
||||
})),
|
||||
acquireOrderDocumentProfileEditLease: vi.fn(async () => ({ lease_token: 'lease', expires_at: new Date().toISOString() })),
|
||||
renewOrderDocumentProfileEditLease: vi.fn(),
|
||||
releaseOrderDocumentProfileEditLease: vi.fn(),
|
||||
saveOrderDocumentProfileDraft: (...args: unknown[]) => saveDraftMock(...args),
|
||||
previewOrderProfileSampleXfaSplitRules: (...args: unknown[]) => splitPreviewMock(...args),
|
||||
previewOrderProfileSampleXfaValue: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-schema.api', () => ({
|
||||
getShippingOrderSchemaState: vi.fn(async () => ({
|
||||
versions: [{
|
||||
id: 1,
|
||||
definition: {
|
||||
fields: [{
|
||||
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',
|
||||
}, {
|
||||
field_id: 'f-bill', field_code: 'bill_to_customer', scope: 'header', display_name: '账款客户', required: false,
|
||||
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',
|
||||
}, {
|
||||
field_id: 'f-line', field_code: 'part_number', scope: 'line', display_name: '料号', required: false,
|
||||
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',
|
||||
}],
|
||||
},
|
||||
}],
|
||||
})),
|
||||
}));
|
||||
|
||||
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: '否' },
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
templateModes: { xfa_dataset: 'XFA' },
|
||||
workbench: {
|
||||
headerReturnToLibrary: '返回',
|
||||
headerSaveDraft: '保存',
|
||||
headerValidate: '验证',
|
||||
headerRecoverLease: '恢复',
|
||||
headerTakeOverLease: '接管',
|
||||
saveStatus: { saved: '已保存', saving: '保存中', failed: '失败', readonly: '只读' },
|
||||
leaveConfirm: '离开?',
|
||||
},
|
||||
xfaWorkbench: {
|
||||
loading: '加载', loadFailed: '失败', saved: '已保存', saveFailed: '失败', scopeMismatch: 'scope',
|
||||
treeTitle: '树', searchPaths: '搜', collectionBadge: '集合', treeEmpty: '空',
|
||||
schemaTitle: 'Schema', selectLeafFirst: '选叶子', unbind: '解除',
|
||||
filter: { all: '全部', unmapped: '未映射', required: '必填' },
|
||||
scope: { header: '表头', line: '明细' },
|
||||
previewTitle: '预览', blockersTitle: '阻断', currentNode: '节点', noneSelected: '无',
|
||||
headerMaps: '表头映射', lineMaps: '明细映射', requiredCoverage: '{mapped}/{total}',
|
||||
maskedSample: '脱敏', noMappings: '无映射', crossChecksTitle: '交叉校验',
|
||||
crossCheck: { acroform: 'AcroForm', mirror: '镜像', lineAmount: '金额', totalAmount: '总额' },
|
||||
previewHint: '验证页', retryLoad: '重试',
|
||||
blocker: {
|
||||
authoritative_collection_required: '权威必选',
|
||||
duplicate_field_binding: '重复',
|
||||
required_fields_unmapped: '必填未映射',
|
||||
},
|
||||
collectionsTitle: '集合', authoritativeCollection: '权威', selectAuthoritative: '选择',
|
||||
mirrorCollections: '镜像', rowCount: '{count} 行',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('XfaProfileMappingPage', () => {
|
||||
beforeEach(() => {
|
||||
saveDraftMock.mockReset();
|
||||
splitPreviewMock.mockReset();
|
||||
detailDefinition.value = null;
|
||||
});
|
||||
|
||||
const mountPage = async () => {
|
||||
const wrapper = mount(XfaProfileMappingPage, { global: { plugins: [i18n] } });
|
||||
for (let i = 0; i < 5; i += 1) {
|
||||
await flushPromises();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
if (wrapper.find('.xfa-workbench__grid').exists()) break;
|
||||
}
|
||||
return wrapper;
|
||||
};
|
||||
|
||||
it('mounts four-column grid after bootstrap', 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('必填');
|
||||
|
||||
await wrapper.find('[data-xfa-path-id="material-path"] .add-rule').trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.find('.xfa-rule-dialog').exists()).toBe(true);
|
||||
});
|
||||
|
||||
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' }],
|
||||
},
|
||||
});
|
||||
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' });
|
||||
});
|
||||
});
|
||||
+748
@@ -0,0 +1,748 @@
|
||||
<!--
|
||||
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>
|
||||
+41
-2
@@ -1,8 +1,9 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileAuditTimeline.vue
|
||||
用途:展示订单模板版本中心的治理审计时间线。
|
||||
用途:展示订单模板版本中心的治理审计时间线(含 XFA operation_id / checksum)。
|
||||
依赖:版本中心审计 API、版本详情 DTO、Vue I18n。
|
||||
逻辑:使用 before_id 游标分页避免新增事件导致翻页重复;只展示安全 detail 摘要,不展示 PDF、正文或盲测真值。
|
||||
逻辑:使用 before_id 游标分页避免新增事件导致翻页重复;只展示安全 detail 摘要,
|
||||
以及 XFA 变更前后 definition checksum 与 operation_id;不展示 PDF、正文或盲测真值。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from "vue";
|
||||
@@ -177,8 +178,26 @@ watch(
|
||||
<div class="meta">
|
||||
<span>{{ formatTime(item.created_at) }}</span>
|
||||
<code v-if="item.request_id">{{ item.request_id }}</code>
|
||||
<code
|
||||
v-if="item.operation_id"
|
||||
data-testid="order-profile-audit-operation-id"
|
||||
>{{ item.operation_id }}</code>
|
||||
</div>
|
||||
</header>
|
||||
<dl
|
||||
v-if="item.definition_checksum || item.before_definition_checksum"
|
||||
class="checksum-row"
|
||||
data-testid="order-profile-audit-checksums"
|
||||
>
|
||||
<div v-if="item.before_definition_checksum">
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.audit.beforeChecksum") }}</dt>
|
||||
<dd><code>{{ item.before_definition_checksum }}</code></dd>
|
||||
</div>
|
||||
<div v-if="item.definition_checksum">
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.audit.afterChecksum") }}</dt>
|
||||
<dd><code>{{ item.definition_checksum }}</code></dd>
|
||||
</div>
|
||||
</dl>
|
||||
<pre>{{ formatJson(item.detail) }}</pre>
|
||||
</article>
|
||||
</div>
|
||||
@@ -273,6 +292,26 @@ watch(
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.checksum-row {
|
||||
display: grid;
|
||||
gap: 0.35rem;
|
||||
margin: 0.5rem 0;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.checksum-row dt {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.checksum-row dd {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.checksum-row code {
|
||||
font-size: 0.7rem;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.meta {
|
||||
display: grid;
|
||||
justify-items: end;
|
||||
|
||||
+13
-4
@@ -20,13 +20,19 @@ import type {
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import OrderProfileDocumentCanvas from './OrderProfileDocumentCanvas.vue';
|
||||
import OrderProfileFrozenEvidencePanel from './OrderProfileFrozenEvidencePanel.vue';
|
||||
import XfaReadOnlyMapping from './XfaReadOnlyMapping.vue';
|
||||
import { buildOrderProfileReadonlyRegions } from '../orderProfileReadonlyCanvas.utils';
|
||||
import { isXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const props = defineProps<{
|
||||
detail: ShippingOrderDocumentProfile;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const isXfa = computed(() => (
|
||||
props.detail.template_mode === 'xfa_dataset'
|
||||
|| isXfaDatasetProfileDefinition(props.detail.definition)
|
||||
));
|
||||
const loading = ref(false);
|
||||
const errorMessage = ref('');
|
||||
const selectedSampleId = ref<number | null>(null);
|
||||
@@ -109,9 +115,11 @@ const loadRegionDiagnostics = async (): Promise<void> => {
|
||||
regionDiagnostics.value = new Map(payload.items.map((item) => [item.region_id, item]));
|
||||
} catch (error) {
|
||||
regionDiagnostics.value = new Map();
|
||||
errorMessage.value = error instanceof BusinessError
|
||||
? error.message
|
||||
: t('admin.shippingOrderProfiles.versionCenter.regionDiagnosticsLoadFailed');
|
||||
// 区域诊断是增强信息;冻结版面没有 coordinate_evidence 时不能阻断 PDF 主画布。
|
||||
// 仅保留诊断区域为空,具体字段会回退到“未读取到值”。
|
||||
if (error instanceof BusinessError && error.code !== 'SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND') {
|
||||
errorMessage.value = error.message;
|
||||
}
|
||||
} finally {
|
||||
diagnosticsLoading.value = false;
|
||||
}
|
||||
@@ -136,7 +144,8 @@ watch([selectedSampleId, pageNo], () => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="readonly-layout">
|
||||
<XfaReadOnlyMapping v-if="isXfa" :detail="detail" />
|
||||
<section v-else class="readonly-layout">
|
||||
<div v-if="!immutable" class="state-card">
|
||||
{{ t('admin.shippingOrderProfiles.versionCenter.draftCanvasHint') }}
|
||||
</div>
|
||||
|
||||
+54
-1
@@ -8,6 +8,7 @@
|
||||
import { computed } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { ShippingOrderDocumentProfile } from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
import { isXfaDatasetProfileDefinition } from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
|
||||
const props = defineProps<{
|
||||
detail: ShippingOrderDocumentProfile;
|
||||
@@ -15,6 +16,15 @@ const props = defineProps<{
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
/** XFA 版本概览展示结构身份与路径映射规模,不展示坐标表区域指标。 */
|
||||
const isXfa = computed(() => (
|
||||
props.detail.template_mode === "xfa_dataset"
|
||||
|| isXfaDatasetProfileDefinition(props.detail.definition)
|
||||
|| props.detail.definition_stats?.template_mode === "xfa_dataset"
|
||||
));
|
||||
|
||||
const xfaIdentity = computed(() => props.detail.xfa_structure_identity || null);
|
||||
|
||||
const formatDateTime = (value?: string | null) =>
|
||||
value ? new Date(value).toLocaleString() : "-";
|
||||
|
||||
@@ -39,6 +49,12 @@ const testStatusLabel = computed(() => {
|
||||
const status = props.detail.test_summary?.status || "missing";
|
||||
return t(`admin.shippingOrderProfiles.versionCenter.testStatus.${status}`);
|
||||
});
|
||||
|
||||
const templateModeLabel = computed(() => (
|
||||
isXfa.value
|
||||
? t("admin.shippingOrderProfiles.versionCenter.templateModeXfa")
|
||||
: t("admin.shippingOrderProfiles.versionCenter.templateModeCoordinate")
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -52,6 +68,7 @@ const testStatusLabel = computed(() => {
|
||||
</div>
|
||||
<div class="hero-meta">
|
||||
<span class="meta-chip meta-chip--status" :class="statusClass">{{ statusLabel }}</span>
|
||||
<span class="meta-chip">{{ templateModeLabel }}</span>
|
||||
<span class="meta-chip">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.schemaVersion") }}
|
||||
{{ detail.schema_summary?.version ?? "-" }}
|
||||
@@ -67,7 +84,21 @@ const testStatusLabel = computed(() => {
|
||||
<div class="summary-grid">
|
||||
<article class="summary-card">
|
||||
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.definitionStats") }}</h3>
|
||||
<dl>
|
||||
<dl v-if="isXfa">
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.headerMappings") }}</dt>
|
||||
<dd>{{ detail.definition_stats?.header_mapping_count || 0 }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.lineMappings") }}</dt>
|
||||
<dd>{{ detail.definition_stats?.line_mapping_count || 0 }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.mirrorCollections") }}</dt>
|
||||
<dd>{{ detail.definition_stats?.mirror_collection_count || 0 }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<dl v-else>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.tableRegions") }}</dt>
|
||||
<dd>{{ detail.definition_stats?.table_region_count || 0 }}</dd>
|
||||
@@ -87,6 +118,28 @@ const testStatusLabel = computed(() => {
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
<article v-if="isXfa && xfaIdentity" class="summary-card">
|
||||
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.xfaStructureIdentity") }}</h3>
|
||||
<dl>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.xfaTemplateChecksum") }}</dt>
|
||||
<dd>{{ xfaIdentity.template_packet_checksum || "-" }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.xfaDatasetFingerprint") }}</dt>
|
||||
<dd>{{ xfaIdentity.dataset_structure_fingerprint || "-" }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.xfaAuthoritativeCollection") }}</dt>
|
||||
<dd>{{ xfaIdentity.has_authoritative_collection ? t("common.yes") : t("common.no") }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.mirrorCollections") }}</dt>
|
||||
<dd>{{ xfaIdentity.mirror_collection_count ?? 0 }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
<article class="summary-card">
|
||||
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.frozenEvidenceTitle") }}</h3>
|
||||
<dl>
|
||||
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileXfaConfirmStep.vue
|
||||
用途:创建向导第三步——XFA 样本结构与明细集合确认(不要求 table_id)。
|
||||
依赖:XFA collections API、XfaCollectionSelector、vue-i18n。
|
||||
逻辑:父级传入 documentId 与 v-model 集合 path_id;watch(immediate) 加载上下文,
|
||||
避免 onMounted 再次触发导致重复请求。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
getOrderProfileSampleXfaCollections,
|
||||
getOrderProfileSampleXfaFieldTree,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type { OrderProfileSampleDocument } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { flattenXfaTreeNodes } from '../xfaProfileMapping.utils';
|
||||
import XfaCollectionSelector from './XfaCollectionSelector.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
documentId: number;
|
||||
sample?: OrderProfileSampleDocument | null;
|
||||
authoritativePathId: string;
|
||||
mirrorPathIds: string[];
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
'update:authoritativePathId': [value: string];
|
||||
'update:mirrorPathIds': [value: string[]];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const message = useMessage();
|
||||
const loading = ref(false);
|
||||
const collections = ref<Awaited<ReturnType<typeof getOrderProfileSampleXfaCollections>> | null>(null);
|
||||
const flatNodes = ref(flattenXfaTreeNodes(null));
|
||||
const excludedCollections = computed(() => collections.value?.excluded_collection_candidates || []);
|
||||
|
||||
const documentKindLabel = computed(() => {
|
||||
const kind = props.sample?.document_kind || collections.value?.document_kind || 'xfa_hybrid';
|
||||
return t(`admin.shippingOrderProfiles.xfa.documentKinds.${kind}`, kind);
|
||||
});
|
||||
|
||||
/**
|
||||
* 加载 XFA 集合候选与字段树(用于展示标签)。
|
||||
* @returns 完成后更新 flatNodes 与 collections。
|
||||
*/
|
||||
async function loadXfaContext(): Promise<void> {
|
||||
if (!props.documentId) return;
|
||||
loading.value = true;
|
||||
try {
|
||||
const [treeResp, collectionResp] = await Promise.all([
|
||||
getOrderProfileSampleXfaFieldTree(props.documentId),
|
||||
getOrderProfileSampleXfaCollections(props.documentId),
|
||||
]);
|
||||
collections.value = collectionResp;
|
||||
flatNodes.value = flattenXfaTreeNodes(treeResp.tree as import('@/features/admin/types/shipping-order-document-profile.types').XfaFieldTreeNode);
|
||||
if (!props.authoritativePathId && collectionResp.collection_candidates.length === 1) {
|
||||
const only = collectionResp.collection_candidates[0];
|
||||
if (only?.path_id) emit('update:authoritativePathId', only.path_id);
|
||||
}
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.xfa.loadFailed'));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.documentId, () => void loadXfaContext(), { immediate: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="xfa-confirm-step">
|
||||
<article v-if="sample" class="xfa-confirm-step__card">
|
||||
<header>
|
||||
<strong>{{ sample.filename || t('admin.shippingOrderProfiles.wizard.sampleSelected') }}</strong>
|
||||
<span class="xfa-confirm-step__badge">{{ documentKindLabel }}</span>
|
||||
</header>
|
||||
<p>{{ t('admin.shippingOrderProfiles.wizard.xfa.intro') }}</p>
|
||||
<ul class="xfa-confirm-step__checks">
|
||||
<li>{{ t('admin.shippingOrderProfiles.wizard.xfa.noBlankPdf') }}</li>
|
||||
<li>{{ t('admin.shippingOrderProfiles.wizard.xfa.scriptNotice') }}</li>
|
||||
</ul>
|
||||
</article>
|
||||
<p v-if="loading" class="xfa-confirm-step__loading">{{ t('admin.shippingOrderProfiles.wizard.xfa.loading') }}</p>
|
||||
<XfaCollectionSelector
|
||||
v-else-if="collections && (collections.collection_candidates?.length || excludedCollections.length)"
|
||||
:candidates="collections.collection_candidates || []"
|
||||
:excluded-candidates="excludedCollections"
|
||||
:authoritative-path-id="authoritativePathId"
|
||||
:mirror-path-ids="mirrorPathIds"
|
||||
@update:authoritative-path-id="emit('update:authoritativePathId', $event)"
|
||||
@update:mirror-path-ids="emit('update:mirrorPathIds', $event)"
|
||||
/>
|
||||
<p v-else-if="!loading" class="xfa-confirm-step__loading">{{ t('admin.shippingOrderProfiles.wizard.xfa.noCollections') }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-confirm-step { display: flex; flex-direction: column; gap: 16px; }
|
||||
.xfa-confirm-step__card { padding: 16px 18px; border: 1px solid var(--border-default); border-radius: var(--radius-control); background: var(--bg-surface-soft); }
|
||||
.xfa-confirm-step__card header { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 8px; }
|
||||
.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); }
|
||||
</style>
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/XfaCollectionSelector.spec.ts
|
||||
* 用途:断言权威集合卡片选择、证据展示与排除原因可见。
|
||||
* 依赖:Vitest、@vue/test-utils、XfaCollectionSelector。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import XfaCollectionSelector from './XfaCollectionSelector.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
xfaWorkbench: {
|
||||
collectionsTitle: '集合',
|
||||
authoritativeCollection: '权威',
|
||||
selectAuthoritative: '请选择',
|
||||
mirrorCollections: '镜像',
|
||||
rowCount: '{count} 行',
|
||||
collectionEvidenceHint: '证据',
|
||||
recommendedAuthoritative: '推荐权威',
|
||||
selectedAuthoritative: '已选权威',
|
||||
nonEmptyCoverage: '{filled}/{total} {percent}',
|
||||
excludedCollections: '空集合 {count}',
|
||||
emptyStructureReason: '空结构',
|
||||
allCandidatesExcluded: '全部被排除',
|
||||
collectionReason: {
|
||||
empty_structure: '空结构',
|
||||
data_description_structure: '结构描述',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('XfaCollectionSelector', () => {
|
||||
it('emits authoritative path when a candidate card is selected', async () => {
|
||||
const wrapper = mount(XfaCollectionSelector, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
candidates: [
|
||||
{
|
||||
path_id: 'a',
|
||||
collection_path_hash: 'ha',
|
||||
row_count: 1,
|
||||
path_label: 'data / ITEMS / DATA',
|
||||
field_names: ['MATNR', 'MENGE'],
|
||||
non_empty_field_count: 2,
|
||||
field_count: 2,
|
||||
sample_fields: [{ field_name: 'MENGE', display_value: '30', display_policy: 'full' }],
|
||||
recommended_role: 'authoritative',
|
||||
},
|
||||
{
|
||||
path_id: 'b',
|
||||
collection_path_hash: 'hb',
|
||||
row_count: 1,
|
||||
path_label: 'data / ITEMS1 / DATA',
|
||||
field_names: ['MATNR', 'MENGE'],
|
||||
non_empty_field_count: 2,
|
||||
field_count: 2,
|
||||
recommended_role: 'mirror',
|
||||
},
|
||||
],
|
||||
authoritativePathId: 'a',
|
||||
mirrorPathIds: [],
|
||||
},
|
||||
});
|
||||
const radios = wrapper.findAll('input[type="radio"]');
|
||||
await radios[1].setValue(true);
|
||||
expect(wrapper.emitted('update:authoritativePathId')?.[0]).toEqual(['b']);
|
||||
expect(wrapper.text()).toContain('data / ITEMS / DATA');
|
||||
expect(wrapper.text()).toContain('MATNR');
|
||||
expect(wrapper.text()).toContain('MENGE');
|
||||
});
|
||||
|
||||
it('shows excluded reasons when no selectable candidates remain', () => {
|
||||
const wrapper = mount(XfaCollectionSelector, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
candidates: [],
|
||||
authoritativePathId: '',
|
||||
mirrorPathIds: [],
|
||||
excludedCandidates: [
|
||||
{
|
||||
path_id: 'desc',
|
||||
collection_path_hash: 'hd',
|
||||
row_count: 0,
|
||||
path_label: 'dataDescription / ITEMS / DATA',
|
||||
selectable: false,
|
||||
exclusion_reasons: ['data_description_structure'],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(wrapper.text()).toContain('全部被排除');
|
||||
expect(wrapper.text()).toContain('dataDescription / ITEMS / DATA');
|
||||
expect(wrapper.text()).toContain('结构描述');
|
||||
});
|
||||
});
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaCollectionSelector.vue
|
||||
用途:权威明细集合与镜像对账集合选择。
|
||||
依赖:vue-i18n、XfaCollectionCandidate。
|
||||
逻辑:以候选卡片直接展示完整路径、字段覆盖与样本证据;权威单选强制,镜像多选仅用于对账;
|
||||
全部候选被排除时仍展示排除原因,禁止只显示“没有集合”。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { XfaCollectionCandidate } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { listMirrorCollectionCandidates } from '../xfaProfileMapping.utils';
|
||||
|
||||
const props = defineProps<{
|
||||
candidates: XfaCollectionCandidate[];
|
||||
authoritativePathId: string;
|
||||
mirrorPathIds: string[];
|
||||
excludedCandidates?: XfaCollectionCandidate[];
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
'update:authoritativePathId': [pathId: string];
|
||||
'update:mirrorPathIds': [pathIds: string[]];
|
||||
}>();
|
||||
const { t, te } = useI18n();
|
||||
const 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 hasExcludedOnly = computed(() => !hasSelectable.value && Boolean(props.excludedCandidates?.length));
|
||||
|
||||
/** 将非空率转为管理员可读百分比。 */
|
||||
function percent(value?: number): string {
|
||||
return `${Math.round(Number(value || 0) * 100)}%`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换镜像集合勾选。
|
||||
*/
|
||||
function toggleMirror(pathId: string, checked: boolean): void {
|
||||
const next = new Set(props.mirrorPathIds);
|
||||
if (checked) next.add(pathId);
|
||||
else next.delete(pathId);
|
||||
emit('update:mirrorPathIds', [...next]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将排除/推荐原因码映射为可读文案。
|
||||
* @param reasons 原因码列表
|
||||
*/
|
||||
function reasonLabels(reasons?: string[]): string {
|
||||
return (reasons || [])
|
||||
.map((code) => {
|
||||
const key = `admin.shippingOrderProfiles.xfaWorkbench.collectionReason.${code}`;
|
||||
return te(key) ? t(key) : code;
|
||||
})
|
||||
.join(' · ');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-collections" :aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.collectionsTitle')">
|
||||
<div class="collection-heading">
|
||||
<strong>{{ t('admin.shippingOrderProfiles.xfaWorkbench.collectionsTitle') }}</strong>
|
||||
<span>{{ t('admin.shippingOrderProfiles.xfaWorkbench.collectionEvidenceHint') }}</span>
|
||||
</div>
|
||||
|
||||
<p v-if="hasExcludedOnly" class="empty-selectable" role="status">
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.allCandidatesExcluded') }}
|
||||
</p>
|
||||
|
||||
<fieldset v-if="hasSelectable" class="auth-cards" :aria-invalid="!authoritativePathId">
|
||||
<legend>{{ t('admin.shippingOrderProfiles.xfaWorkbench.authoritativeCollection') }}</legend>
|
||||
<label
|
||||
v-for="item in candidates"
|
||||
:key="item.path_id"
|
||||
class="candidate-card"
|
||||
:class="{
|
||||
selected: authoritativePathId === item.path_id,
|
||||
recommended: item.recommended_role === 'authoritative',
|
||||
}"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="xfa-authoritative-collection"
|
||||
:value="item.path_id"
|
||||
:checked="authoritativePathId === item.path_id"
|
||||
@change="emit('update:authoritativePathId', item.path_id)"
|
||||
/>
|
||||
<span class="candidate-body">
|
||||
<span class="candidate-title">
|
||||
<strong>{{ item.path_label || item.local_name }}</strong>
|
||||
<span v-if="item.recommended_role === 'authoritative'" class="role-badge">
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.recommendedAuthoritative') }}
|
||||
</span>
|
||||
<span>{{ t('admin.shippingOrderProfiles.xfaWorkbench.rowCount', { count: item.row_count }) }}</span>
|
||||
</span>
|
||||
<small>{{ t('admin.shippingOrderProfiles.xfaWorkbench.nonEmptyCoverage', {
|
||||
filled: item.non_empty_field_count || 0,
|
||||
total: item.field_count || 0,
|
||||
percent: percent(item.non_empty_rate),
|
||||
}) }}</small>
|
||||
<span class="fields">{{ (item.field_names || []).slice(0, 8).join(' · ') }}</span>
|
||||
<span class="samples">
|
||||
<span v-for="field in item.sample_fields || []" :key="`${item.path_id}-${field.field_name}`">
|
||||
<b>{{ field.field_name }}</b> {{ field.display_value }}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
<article v-if="selectedAuthoritative" class="collection-card authoritative">
|
||||
<header>
|
||||
<div>
|
||||
<strong>{{ selectedAuthoritative.path_label || selectedAuthoritative.local_name }}</strong>
|
||||
<span class="role-badge">{{ t('admin.shippingOrderProfiles.xfaWorkbench.selectedAuthoritative') }}</span>
|
||||
</div>
|
||||
<span>{{ t('admin.shippingOrderProfiles.xfaWorkbench.rowCount', { count: selectedAuthoritative.row_count }) }}</span>
|
||||
</header>
|
||||
<p>{{ t('admin.shippingOrderProfiles.xfaWorkbench.nonEmptyCoverage', {
|
||||
filled: selectedAuthoritative.non_empty_field_count || 0,
|
||||
total: selectedAuthoritative.field_count || 0,
|
||||
percent: percent(selectedAuthoritative.non_empty_rate),
|
||||
}) }}</p>
|
||||
<div class="sample-grid">
|
||||
<span v-for="field in selectedAuthoritative.sample_fields || []" :key="field.field_name">
|
||||
<b>{{ field.field_name }}</b> {{ field.display_value }}
|
||||
</span>
|
||||
</div>
|
||||
<small>{{ (selectedAuthoritative.field_names || []).join(' · ') }}</small>
|
||||
</article>
|
||||
|
||||
<fieldset v-if="mirrors.length" class="mirror-fieldset">
|
||||
<legend>{{ t('admin.shippingOrderProfiles.xfaWorkbench.mirrorCollections') }}</legend>
|
||||
<label v-for="item in mirrors" :key="item.path_id" class="mirror">
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="mirrorPathIds.includes(item.path_id)"
|
||||
@change="toggleMirror(item.path_id, ($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
<span class="mirror-copy">
|
||||
<strong>{{ item.path_label || item.local_name }}</strong>
|
||||
<small>{{ t('admin.shippingOrderProfiles.xfaWorkbench.nonEmptyCoverage', {
|
||||
filled: item.non_empty_field_count || 0,
|
||||
total: item.field_count || 0,
|
||||
percent: percent(item.non_empty_rate),
|
||||
}) }}</small>
|
||||
<span>{{ (item.sample_fields || []).map((field) => `${field.field_name} ${field.display_value}`).join(' · ') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
<details v-if="excludedCandidates?.length" class="excluded" :open="hasExcludedOnly">
|
||||
<summary>{{ t('admin.shippingOrderProfiles.xfaWorkbench.excludedCollections', { count: excludedCandidates.length }) }}</summary>
|
||||
<ul>
|
||||
<li v-for="item in excludedCandidates" :key="item.path_id">
|
||||
<span>{{ item.path_label || item.local_name }}</span>
|
||||
<small>{{ reasonLabels(item.exclusion_reasons || item.recommendation_reasons) || t('admin.shippingOrderProfiles.xfaWorkbench.emptyStructureReason') }}</small>
|
||||
</li>
|
||||
</ul>
|
||||
</details>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-collections { display: grid; grid-template-columns: minmax(280px, 1fr) minmax(320px, 1fr); gap: 12px 16px; align-items: start; width: 100%; }
|
||||
.collection-heading { grid-column: 1 / -1; display: flex; flex-direction: column; gap: 3px; color: var(--text-primary); }
|
||||
.collection-heading span { color: var(--text-muted); font-size: .82rem; }
|
||||
.empty-selectable { grid-column: 1 / -1; margin: 0; padding: 10px 12px; border: 1px solid var(--status-warning-border); border-radius: var(--radius-control); background: var(--status-warning-bg); color: var(--status-warning-fg); }
|
||||
.auth-cards { grid-column: 1 / -1; display: grid; gap: 10px; margin: 0; padding: 0; border: 0; }
|
||||
.auth-cards[aria-invalid='true'] .candidate-card { border-color: var(--status-error-border); }
|
||||
.candidate-card { display: flex; gap: 10px; align-items: flex-start; padding: 12px; border: 1px solid var(--border-default); border-radius: var(--radius-control); background: var(--bg-surface); cursor: pointer; }
|
||||
.candidate-card.selected, .candidate-card.recommended.selected { border-color: var(--status-info-border); background: var(--status-info-bg); }
|
||||
.candidate-body { display: flex; min-width: 0; flex: 1; flex-direction: column; gap: 4px; color: var(--text-secondary); }
|
||||
.candidate-title { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; color: var(--text-primary); }
|
||||
.role-badge { color: var(--status-info-fg); font-size: .75rem; }
|
||||
.fields, .samples { color: var(--text-muted); font-size: .78rem; }
|
||||
.samples { display: flex; flex-wrap: wrap; gap: 6px 12px; }
|
||||
.samples b { color: var(--text-primary); }
|
||||
.collection-card, .mirror-fieldset, .excluded { border: 1px solid var(--border-default); border-radius: var(--radius-control); padding: 12px; background: var(--bg-surface); }
|
||||
.collection-card.authoritative { border-color: var(--status-info-border); background: var(--status-info-bg); }
|
||||
.collection-card header { display: flex; justify-content: space-between; gap: 12px; color: var(--text-primary); }
|
||||
.collection-card header div { display: flex; align-items: center; gap: 8px; }
|
||||
.collection-card p, .collection-card small { color: var(--text-muted); }
|
||||
.sample-grid { display: flex; flex-wrap: wrap; gap: 6px 12px; margin: 8px 0; color: var(--text-secondary); font-size: .82rem; }
|
||||
.sample-grid b { color: var(--text-primary); }
|
||||
.mirror-fieldset { grid-column: 1 / -1; }
|
||||
.mirror { display: flex; gap: 10px; align-items: flex-start; padding: 8px 0; }
|
||||
.mirror-copy { display: flex; flex-direction: column; gap: 2px; color: var(--text-secondary); }
|
||||
.mirror-copy small, .mirror-copy span { color: var(--text-muted); font-size: .78rem; }
|
||||
.excluded { grid-column: 1 / -1; color: var(--text-secondary); }
|
||||
.excluded ul { margin: 8px 0 0; padding-left: 18px; }
|
||||
.excluded li { display: flex; flex-wrap: wrap; gap: 10px; }
|
||||
.excluded small { color: var(--status-warning-fg); }
|
||||
@media (max-width: 900px) { .xfa-collections { grid-template-columns: 1fr; } }
|
||||
</style>
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/XfaDatasetTree.spec.ts
|
||||
* 用途:断言 XFA 字段树渲染与 select-path 事件。
|
||||
* 依赖:Vitest、@vue/test-utils、XfaDatasetTree。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import XfaDatasetTree from './XfaDatasetTree.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
xfaWorkbench: {
|
||||
treeTitle: '树', searchPaths: '搜索', collectionBadge: '集合', treeEmpty: '空',
|
||||
revealValue: '查看 {field}',
|
||||
},
|
||||
xfaSplit: { addRule: '新增规则', ruleLabel: '规则 {index}', unnamedRule: '未命名规则', deleteRule: '删除' },
|
||||
},
|
||||
},
|
||||
common: { edit: '编辑' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('XfaDatasetTree', () => {
|
||||
it('emits select-path when a tree node button is clicked', async () => {
|
||||
const wrapper = mount(XfaDatasetTree, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
tree: {
|
||||
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
|
||||
is_leaf: false,
|
||||
children: [{
|
||||
path_id: 'leaf', local_name: 'EBELN', data_path_hash: 'h2', depth: 1, cardinality: 'one',
|
||||
is_leaf: true, sample_value_masked: '451***',
|
||||
}],
|
||||
},
|
||||
},
|
||||
});
|
||||
const nodes = wrapper.findAll('[role="treeitem"]');
|
||||
expect(nodes.length).toBeGreaterThan(0);
|
||||
await nodes[nodes.length - 1].trigger('click');
|
||||
expect(wrapper.emitted('select-path')?.[0]).toEqual(['leaf', true]);
|
||||
});
|
||||
|
||||
it('exposes tree levels and supports collapse keyboard navigation', async () => {
|
||||
const wrapper = mount(XfaDatasetTree, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
tree: {
|
||||
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
|
||||
is_leaf: false, children: [{
|
||||
path_id: 'leaf', local_name: 'WAERS', data_path_hash: 'h2', depth: 1, cardinality: 'one',
|
||||
is_leaf: true, sample_value_display: 'USD', display_policy: 'full',
|
||||
}],
|
||||
},
|
||||
},
|
||||
});
|
||||
const root = wrapper.find('[data-xfa-path-id="root"]');
|
||||
expect(root.attributes('aria-level')).toBe('1');
|
||||
expect(root.attributes('aria-expanded')).toBe('true');
|
||||
await root.trigger('keydown', { key: 'ArrowLeft' });
|
||||
expect(root.attributes('aria-expanded')).toBe('false');
|
||||
expect(wrapper.text()).not.toContain('USD');
|
||||
});
|
||||
|
||||
it('selects the focused node with Enter and Space', async () => {
|
||||
const wrapper = mount(XfaDatasetTree, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
tree: {
|
||||
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
|
||||
is_leaf: false, children: [{
|
||||
path_id: 'leaf', local_name: 'WAERS', data_path_hash: 'h2', depth: 1, cardinality: 'one',
|
||||
is_leaf: true, sample_value_display: 'USD', display_policy: 'full',
|
||||
}],
|
||||
},
|
||||
},
|
||||
});
|
||||
const leaf = wrapper.find('[data-xfa-path-id="leaf"]');
|
||||
await leaf.trigger('keydown', { key: 'Enter' });
|
||||
await leaf.trigger('keydown', { key: ' ' });
|
||||
expect(wrapper.emitted('select-path')).toEqual([['leaf', true], ['leaf', true]]);
|
||||
});
|
||||
|
||||
it('emits add-rule when the leaf add button is clicked', async () => {
|
||||
const wrapper = mount(XfaDatasetTree, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
selectedPathId: 'leaf',
|
||||
tree: {
|
||||
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
|
||||
is_leaf: false, children: [{
|
||||
path_id: 'leaf', local_name: 'MATNR', data_path_hash: 'h2', depth: 1, cardinality: 'one',
|
||||
is_leaf: true, sample_value_display: 'TEMP-S', display_policy: 'full',
|
||||
}],
|
||||
},
|
||||
},
|
||||
});
|
||||
await wrapper.find('[data-xfa-path-id="leaf"] .add-rule').trigger('click');
|
||||
expect(wrapper.emitted('add-rule')).toEqual([['leaf']]);
|
||||
expect(wrapper.emitted('select-path')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('selects a rule row without editing and uses explicit edit and delete controls', async () => {
|
||||
const wrapper = mount(XfaDatasetTree, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
tree: {
|
||||
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
|
||||
is_leaf: false, children: [{
|
||||
path_id: 'leaf', local_name: 'MATNR', data_path_hash: 'h2', depth: 1, cardinality: 'one',
|
||||
is_leaf: true, sample_value_display: 'TEMP-S', display_policy: 'full',
|
||||
}],
|
||||
},
|
||||
splitRuleSets: [{
|
||||
rule_id: 'set-1', rule_version: 1, source_path_id: 'leaf', source_field_code: 'MATNR', strategy: 'pipeline',
|
||||
rules: [{
|
||||
rule_id: 'rule-1', order: 1, stages: [{ stage_id: 'stage-1', type: 'select_line', line_index: 1 }],
|
||||
segment: { segment_id: 'seg-1', segment_code: 'customer_part', display_name: '客户料号', handling: 'evidence_only' },
|
||||
}],
|
||||
}],
|
||||
},
|
||||
});
|
||||
await wrapper.find('.xfa-tree__rule-main').trigger('click');
|
||||
expect(wrapper.emitted('select-rule')).toEqual([['leaf', 'rule-1']]);
|
||||
expect(wrapper.emitted('edit-rule')).toBeUndefined();
|
||||
|
||||
await wrapper.find('.rule-edit').trigger('click');
|
||||
expect(wrapper.emitted('edit-rule')).toEqual([['leaf', 'rule-1']]);
|
||||
await wrapper.find('.rule-delete').trigger('click');
|
||||
expect(wrapper.emitted('delete-rule')).toEqual([['leaf', 'rule-1']]);
|
||||
});
|
||||
|
||||
it('indents rule nodes beyond their deep parent field', () => {
|
||||
const wrapper = mount(XfaDatasetTree, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
tree: {
|
||||
path_id: 'root', local_name: 'datasets', data_path_hash: 'h0', depth: 0, cardinality: 'one', is_leaf: false,
|
||||
children: [{
|
||||
path_id: 'data', local_name: 'data', data_path_hash: 'h1', depth: 1, cardinality: 'one', is_leaf: false,
|
||||
children: [{
|
||||
path_id: 'items', local_name: 'ITEMS', data_path_hash: 'h2', depth: 2, cardinality: 'one', is_leaf: false,
|
||||
children: [{
|
||||
path_id: 'leaf', local_name: 'MATNR', data_path_hash: 'h3', depth: 3, cardinality: 'one', is_leaf: true,
|
||||
}],
|
||||
}],
|
||||
}],
|
||||
},
|
||||
splitRuleSets: [{
|
||||
rule_id: 'set-1', rule_version: 1, source_path_id: 'leaf', source_field_code: 'MATNR', strategy: 'pipeline',
|
||||
rules: [{
|
||||
rule_id: 'rule-1', order: 1, stages: [{ stage_id: 'stage-1', type: 'select_line', line_index: 1 }],
|
||||
segment: { segment_id: 'seg-1', segment_code: 'customer_part', display_name: '客户料号', handling: 'evidence_only' },
|
||||
}],
|
||||
}],
|
||||
},
|
||||
});
|
||||
const parentPadding = Number.parseFloat(wrapper.find('[data-xfa-path-id="leaf"]').attributes('style').match(/padding-left:\s*([\d.]+)px/)?.[1] || '0');
|
||||
const ruleIndentValue = Number.parseFloat(wrapper.find('.xfa-tree__rules').attributes('style').match(/--rule-indent:\s*([\d.]+)px/)?.[1] || '0');
|
||||
expect(ruleIndentValue).toBeGreaterThan(parentPadding);
|
||||
});
|
||||
});
|
||||
+282
@@ -0,0 +1,282 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaDatasetTree.vue
|
||||
用途:XFA 映射工作台左侧受控数据树(仅分析记录节点)。
|
||||
依赖:vue-i18n、xfaProfileMapping.utils。
|
||||
逻辑:支持展开折叠、方向键导航与分级样本展示;叶子展示父路径提示区分同名来源。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref } from 'vue';
|
||||
import { ChevronDown, ChevronRight, Eye, Pencil } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { XfaFieldTreeNode } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { XfaSplitRuleSet } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import {
|
||||
buildXfaPathLabel,
|
||||
filterXfaTreeNodes,
|
||||
flattenXfaTreeNodes,
|
||||
type XfaFlatTreeNode,
|
||||
} from '../xfaProfileMapping.utils';
|
||||
|
||||
const props = defineProps<{
|
||||
tree: XfaFieldTreeNode | null;
|
||||
selectedPathId?: string | null;
|
||||
selectedRuleId?: string | null;
|
||||
mappedPathIds?: string[];
|
||||
revealedValues?: Record<string, string>;
|
||||
revealingPathId?: string;
|
||||
splitRuleSets?: XfaSplitRuleSet[];
|
||||
}>();
|
||||
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];
|
||||
'delete-rule': [pathId: string, ruleId: string];
|
||||
'move-rule': [pathId: string, ruleId: string, direction: -1 | 1];
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const query = ref('');
|
||||
const flat = computed(() => flattenXfaTreeNodes(props.tree || undefined));
|
||||
const collapsed = ref(new Set<string>());
|
||||
const focusedPathId = ref('');
|
||||
const visible = computed(() => {
|
||||
const filtered = filterXfaTreeNodes(flat.value, query.value);
|
||||
if (query.value.trim()) return filtered;
|
||||
return filtered.filter((node) => {
|
||||
let parent = node.parentPathId;
|
||||
while (parent) {
|
||||
if (collapsed.value.has(parent)) return false;
|
||||
parent = flat.value.find((item) => item.pathId === parent)?.parentPathId;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
});
|
||||
const mapped = computed(() => new Set(props.mappedPathIds || []));
|
||||
const rulesFor = (pathId: string) => props.splitRuleSets?.find((item) => item.source_path_id === pathId)?.rules || [];
|
||||
|
||||
/**
|
||||
* 选择树节点;叶子才用于字段绑定。
|
||||
* @param pathId 分析 path_id
|
||||
* @param isLeaf 是否叶子
|
||||
*/
|
||||
function onSelect(pathId: string, isLeaf: boolean): void {
|
||||
focusedPathId.value = pathId;
|
||||
emit('select-path', pathId, isLeaf);
|
||||
}
|
||||
|
||||
/** 切换非叶子节点展开状态。 */
|
||||
function toggle(pathId: string): void {
|
||||
const next = new Set(collapsed.value);
|
||||
if (next.has(pathId)) next.delete(pathId);
|
||||
else next.add(pathId);
|
||||
collapsed.value = next;
|
||||
}
|
||||
|
||||
/**
|
||||
* 完整可读路径(节点名链路),用于 title / 无障碍标签。
|
||||
* @param node 扁平树节点
|
||||
*/
|
||||
function pathTitle(node: XfaFlatTreeNode): string {
|
||||
return buildXfaPathLabel(node.pathId, flat.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 叶子节点的父路径提示,便于区分同名字段来源。
|
||||
* @param node 扁平树节点
|
||||
*/
|
||||
function parentPathHint(node: XfaFlatTreeNode): string {
|
||||
const full = buildXfaPathLabel(node.pathId, flat.value);
|
||||
const parts = full.split('/').filter(Boolean);
|
||||
if (parts.length <= 1) return '';
|
||||
return parts.slice(0, -1).join(' / ');
|
||||
}
|
||||
|
||||
/** 使用完整深度缩进,确保任意层级都能辨认父子关系。 */
|
||||
function nodeIndent(node: XfaFlatTreeNode): string {
|
||||
return `${8 + node.depth * 14}px`;
|
||||
}
|
||||
|
||||
/** 当前层级导轨位置与完整缩进同步。 */
|
||||
function nodeGuide(node: XfaFlatTreeNode): string {
|
||||
return `${8 + Math.max(node.depth - 1, 0) * 14}px`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规则作为叶子字段的下一级虚拟节点,缩进必须基于父字段真实深度计算。
|
||||
* @param node 拆分规则所属的原始叶子节点
|
||||
* @returns 规则列表左内边距及导轨位置
|
||||
*/
|
||||
function ruleIndent(node: XfaFlatTreeNode): Record<string, string> {
|
||||
const parentIndent = 8 + node.depth * 14;
|
||||
return {
|
||||
'--rule-indent': `${parentIndent + 30}px`,
|
||||
'--rule-guide-offset': `${parentIndent + 18}px`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 实现 WAI-ARIA Tree 方向键、Home/End 与父子导航。
|
||||
* @param event 键盘事件
|
||||
* @param pathId 当前节点 path_id
|
||||
*/
|
||||
async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
|
||||
const index = visible.value.findIndex((item) => item.pathId === pathId);
|
||||
const current = visible.value[index];
|
||||
if (!current) return;
|
||||
let target: string | undefined;
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault();
|
||||
onSelect(pathId, current.isLeaf);
|
||||
return;
|
||||
}
|
||||
if (event.key === 'ArrowDown') target = visible.value[index + 1]?.pathId;
|
||||
else if (event.key === 'ArrowUp') target = visible.value[index - 1]?.pathId;
|
||||
else if (event.key === 'Home') target = visible.value[0]?.pathId;
|
||||
else if (event.key === 'End') target = visible.value[visible.value.length - 1]?.pathId;
|
||||
else if (event.key === 'ArrowRight' && !current.isLeaf) {
|
||||
if (collapsed.value.has(pathId)) toggle(pathId);
|
||||
else target = visible.value[index + 1]?.parentPathId === pathId ? visible.value[index + 1]?.pathId : undefined;
|
||||
} else if (event.key === 'ArrowLeft') {
|
||||
if (!current.isLeaf && !collapsed.value.has(pathId)) toggle(pathId);
|
||||
else target = current.parentPathId;
|
||||
} else return;
|
||||
event.preventDefault();
|
||||
if (target) {
|
||||
focusedPathId.value = target;
|
||||
await nextTick();
|
||||
document.querySelector<HTMLElement>(`[data-xfa-path-id="${CSS.escape(target)}"]`)?.focus();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-tree" :aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.treeTitle')">
|
||||
<label class="xfa-tree__search">
|
||||
<span class="sr-only">{{ t('admin.shippingOrderProfiles.xfaWorkbench.searchPaths') }}</span>
|
||||
<input v-model="query" type="search" :placeholder="t('admin.shippingOrderProfiles.xfaWorkbench.searchPaths')" />
|
||||
</label>
|
||||
<ul class="xfa-tree__list" role="tree">
|
||||
<li v-for="(node, index) in visible" :key="node.pathId" role="none">
|
||||
<div
|
||||
role="treeitem"
|
||||
class="xfa-tree__node"
|
||||
:class="{
|
||||
selected: selectedPathId === node.pathId,
|
||||
mapped: mapped.has(node.pathId),
|
||||
leaf: node.isLeaf,
|
||||
}"
|
||||
:style="{ paddingLeft: nodeIndent(node), '--tree-guide-offset': nodeGuide(node) }"
|
||||
:data-xfa-path-id="node.pathId"
|
||||
:tabindex="focusedPathId === node.pathId || (!focusedPathId && node === visible[0]) ? 0 : -1"
|
||||
:aria-level="node.depth + 1"
|
||||
:aria-setsize="visible.length"
|
||||
:aria-posinset="index + 1"
|
||||
:aria-expanded="node.isLeaf ? undefined : !collapsed.has(node.pathId)"
|
||||
:aria-selected="selectedPathId === node.pathId"
|
||||
:title="pathTitle(node)"
|
||||
@click="onSelect(node.pathId, node.isLeaf)"
|
||||
@focus="focusedPathId = node.pathId"
|
||||
@keydown="onKeydown($event, node.pathId)"
|
||||
>
|
||||
<span v-if="!node.isLeaf" class="toggle" @click.stop="toggle(node.pathId)">
|
||||
<ChevronRight v-if="collapsed.has(node.pathId)" :size="14" aria-hidden="true" />
|
||||
<ChevronDown v-else :size="14" aria-hidden="true" />
|
||||
</span>
|
||||
<span v-else class="toggle-spacer" />
|
||||
<span class="name-block">
|
||||
<span class="name">{{ node.localName }}</span>
|
||||
<span v-if="node.isLeaf && parentPathHint(node)" class="path-hint">{{ parentPathHint(node) }}</span>
|
||||
</span>
|
||||
<span v-if="node.isCollectionCandidate" class="badge">{{ t('admin.shippingOrderProfiles.xfaWorkbench.collectionBadge') }}</span>
|
||||
<button
|
||||
v-if="node.isLeaf"
|
||||
type="button"
|
||||
class="add-rule"
|
||||
:class="{ 'add-rule--active': selectedPathId === node.pathId }"
|
||||
:title="t('admin.shippingOrderProfiles.xfaSplit.addRule')"
|
||||
:aria-label="t('admin.shippingOrderProfiles.xfaSplit.addRule')"
|
||||
@click.stop="emit('add-rule', node.pathId)"
|
||||
>+</button>
|
||||
<span v-if="revealedValues?.[node.pathId] || node.sampleValueDisplay" class="sample">
|
||||
{{ revealedValues?.[node.pathId] || 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"
|
||||
class="xfa-tree__rules"
|
||||
role="group"
|
||||
:style="ruleIndent(node)"
|
||||
>
|
||||
<li
|
||||
v-for="(rule, ruleIndex) in rulesFor(node.pathId)"
|
||||
:key="rule.rule_id"
|
||||
class="xfa-tree__rule"
|
||||
:class="{ selected: selectedRuleId === rule.rule_id }"
|
||||
>
|
||||
<button type="button" class="xfa-tree__rule-main" @click="emit('select-rule', node.pathId, rule.rule_id)">
|
||||
<span class="rule-glyph">↳</span>
|
||||
<span class="rule-label">{{ t('admin.shippingOrderProfiles.xfaSplit.ruleLabel', { index: ruleIndex + 1 }) }} · {{ rule.segment.display_name || rule.segment.segment_code || t('admin.shippingOrderProfiles.xfaSplit.unnamedRule') }}</span>
|
||||
</button>
|
||||
<button
|
||||
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>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-if="!visible.length" class="xfa-tree__empty">{{ t('admin.shippingOrderProfiles.xfaWorkbench.treeEmpty') }}</p>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-tree { display: flex; flex-direction: column; min-height: 0; height: 100%; }
|
||||
.xfa-tree__search input { width: 100%; padding: 8px 10px; border: 1px solid var(--border-default); border-radius: var(--radius-control); background: var(--bg-surface); color: var(--text-primary); }
|
||||
.xfa-tree__list { margin: 8px -6px 0 0; padding: 0 6px 0 0; list-style: none; overflow: auto; flex: 1; scrollbar-gutter: stable; }
|
||||
.xfa-tree__node { position: relative; display: flex; width: 100%; min-width: 0; gap: 5px; align-items: center; min-height: 34px; padding-block: 4px; padding-right: 6px; border: 0; border-radius: var(--radius-control); background: transparent; color: var(--text-secondary); text-align: left; cursor: pointer; }
|
||||
.xfa-tree__node::before { content: ''; position: absolute; top: 0; bottom: 0; left: max(13px, calc(var(--tree-guide-offset, 0px))); width: 1px; background: var(--border-default); opacity: .65; pointer-events: none; }
|
||||
.xfa-tree__node[aria-level='1']::before { display: none; }
|
||||
.xfa-tree__node:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: 1px; }
|
||||
.xfa-tree__node.selected { background: var(--status-info-bg); color: var(--status-info-fg); }
|
||||
.xfa-tree__node.mapped .name::after { content: ' ✓'; color: var(--status-success-fg); }
|
||||
.name-block { display: grid; min-width: 0; flex: 1; gap: 0; }
|
||||
.xfa-tree__node:not(.leaf) .name { font-weight: 650; }
|
||||
.xfa-tree__node .name { min-width: 0; overflow: hidden; font-size: .82rem; line-height: 1.2; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.xfa-tree__node .path-hint { min-width: 0; overflow: hidden; color: var(--text-muted); font-size: .64rem; line-height: 1.2; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.xfa-tree__node .sample { min-width: 3.2rem; margin-left: auto; max-width: 30%; overflow: hidden; color: var(--text-muted); font-size: .68rem; text-align: right; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.xfa-tree__node .badge { color: var(--status-warning-fg); font-size: .72rem; font-weight: 700; }
|
||||
.toggle, .toggle-spacer { display: inline-flex; width: 16px; flex: 0 0 16px; }
|
||||
.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; }
|
||||
.xfa-tree__rules { position: relative; margin: 0; padding: 1px 0 5px var(--rule-indent); list-style: none; }
|
||||
.xfa-tree__rules::before { content: ''; position: absolute; top: 0; bottom: 8px; left: var(--rule-guide-offset); width: 1px; background: var(--border-default); }
|
||||
.xfa-tree__rule { display: flex; min-width: 0; align-items: center; gap: 3px; border-radius: 4px; }
|
||||
.xfa-tree__rule.selected { background: var(--status-info-bg); }
|
||||
.xfa-tree__rule-main { display: flex; min-width: 0; flex: 1; gap: 4px; padding: 3px 2px; border: 0; background: transparent; color: var(--text-muted); text-align: left; font-size: .68rem; cursor: pointer; }
|
||||
.rule-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.rule-glyph { color: var(--status-info-fg); }
|
||||
.rule-edit, .rule-delete { display: inline-flex; width: 20px; height: 20px; flex: 0 0 20px; align-items: center; justify-content: center; padding: 0; border: 0; border-radius: 4px; background: transparent; cursor: pointer; }
|
||||
.rule-edit { color: var(--status-info-fg); }
|
||||
.rule-delete { color: var(--status-error-fg); font-size: .9rem; }
|
||||
.rule-edit:hover, .rule-delete:hover { background: var(--bg-page); }
|
||||
.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>
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/XfaReadOnlyMapping.spec.ts
|
||||
* 用途:验证 XFA 只读映射组件不依赖 PDF 预览,并能展示结构身份摘要。
|
||||
* 依赖:@vue/test-utils、vue-i18n、组件本身。
|
||||
* 逻辑:传入含 xfa_readonly_mapping 的详情 DTO,断言标题与字段映射渲染。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import XfaReadOnlyMapping from './XfaReadOnlyMapping.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
xfaReadonly: {
|
||||
title: 'XFA 只读映射',
|
||||
noPdfHint: '不显示空白 PDF',
|
||||
missing: '暂无映射',
|
||||
identityTitle: '结构身份',
|
||||
templateChecksum: 'Template',
|
||||
structureFingerprint: 'Dataset',
|
||||
authoritativeCollection: '权威集合',
|
||||
mirrorCollections: '镜像集合',
|
||||
signatureChecksum: '匹配签名',
|
||||
headerMaps: 'Header 映射',
|
||||
lineMaps: 'Line 映射',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('XfaReadOnlyMapping', () => {
|
||||
it('renders structure identity and mappings without requesting PDF', () => {
|
||||
const wrapper = mount(XfaReadOnlyMapping, {
|
||||
props: {
|
||||
detail: {
|
||||
id: 1,
|
||||
profile_code: 'XFA',
|
||||
display_name: 'XFA',
|
||||
version: 1,
|
||||
status: 'published',
|
||||
schema_version_id: 1,
|
||||
structure_fingerprint: 'a'.repeat(64),
|
||||
definition: { template_mode: 'xfa_dataset' },
|
||||
template_mode: 'xfa_dataset',
|
||||
lock_version: 1,
|
||||
xfa_readonly_mapping: {
|
||||
source_contract: {
|
||||
template_packet_checksum: 'sha256:tpl',
|
||||
dataset_structure_fingerprint: 'sha256:fp',
|
||||
authoritative_line_collection_path: '/data/ITEMS/DATA',
|
||||
mirror_collection_paths: ['/data/ITEMS1/DATA'],
|
||||
},
|
||||
header_mappings: [{ mapping_id: 'm1', field_code: 'customer_po_no', path_id: 'p-po' }],
|
||||
line_mappings: [{ mapping_id: 'm2', field_code: 'material_no', path_id: 'p-mat' }],
|
||||
matching_signature_checksum: 'sig',
|
||||
},
|
||||
} as never,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).toContain('sha256:tpl');
|
||||
expect(wrapper.text()).toContain('customer_po_no');
|
||||
expect(wrapper.text()).toContain('material_no');
|
||||
expect(wrapper.text()).not.toContain('preview-pages');
|
||||
});
|
||||
});
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaReadOnlyMapping.vue
|
||||
用途:版本详情页 XFA 只读映射证据,替代空白 PDF 画布。
|
||||
依赖:vue-i18n、XFA readonly mapping DTO。
|
||||
逻辑:展示结构身份、Header/Line 映射与集合策略;不请求 PDF 预览页。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderDocumentProfile } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const props = defineProps<{
|
||||
detail: ShippingOrderDocumentProfile;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const mapping = computed(() => (props.detail as ShippingOrderDocumentProfile & {
|
||||
xfa_readonly_mapping?: {
|
||||
source_contract?: Record<string, unknown>;
|
||||
header_mappings?: Array<Record<string, unknown>>;
|
||||
line_mappings?: Array<Record<string, unknown>>;
|
||||
cross_checks?: Record<string, unknown>;
|
||||
frozen_samples?: Array<Record<string, unknown>>;
|
||||
matching_signature_checksum?: string | null;
|
||||
};
|
||||
}).xfa_readonly_mapping || null);
|
||||
|
||||
const source = computed(() => mapping.value?.source_contract || {});
|
||||
const headerMaps = computed(() => mapping.value?.header_mappings || []);
|
||||
const lineMaps = computed(() => mapping.value?.line_mappings || []);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-readonly" :aria-label="t('admin.shippingOrderProfiles.xfaReadonly.title')">
|
||||
<p class="hint">{{ t('admin.shippingOrderProfiles.xfaReadonly.noPdfHint') }}</p>
|
||||
<div v-if="!mapping" class="empty">{{ t('admin.shippingOrderProfiles.xfaReadonly.missing') }}</div>
|
||||
<template v-else>
|
||||
<div class="identity">
|
||||
<h3>{{ t('admin.shippingOrderProfiles.xfaReadonly.identityTitle') }}</h3>
|
||||
<dl>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.xfaReadonly.templateChecksum') }}</dt>
|
||||
<dd>{{ source.template_packet_checksum || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.xfaReadonly.structureFingerprint') }}</dt>
|
||||
<dd>{{ source.dataset_structure_fingerprint || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.xfaReadonly.authoritativeCollection') }}</dt>
|
||||
<dd>{{ source.authoritative_line_collection_path || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.xfaReadonly.mirrorCollections') }}</dt>
|
||||
<dd>{{ (source.mirror_collection_paths as string[] | undefined)?.join(', ') || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.xfaReadonly.signatureChecksum') }}</dt>
|
||||
<dd>{{ mapping.matching_signature_checksum || '-' }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
<div class="maps">
|
||||
<div>
|
||||
<h3>{{ t('admin.shippingOrderProfiles.xfaReadonly.headerMaps') }}</h3>
|
||||
<ul>
|
||||
<li v-for="item in headerMaps" :key="String(item.mapping_id)">
|
||||
{{ item.field_code }} ← {{ item.path_id }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<h3>{{ t('admin.shippingOrderProfiles.xfaReadonly.lineMaps') }}</h3>
|
||||
<ul>
|
||||
<li v-for="item in lineMaps" :key="String(item.mapping_id)">
|
||||
{{ item.field_code }} ← {{ item.path_id }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-readonly { border: 1px solid #dfe7ef; border-radius: 10px; background: #fff; padding: 16px; }
|
||||
.hint { margin: 0 0 12px; color: #64748b; font-size: 13px; }
|
||||
.identity dl { display: grid; gap: 8px; margin: 8px 0 0; }
|
||||
.identity dt { color: #64748b; font-size: 12px; }
|
||||
.identity dd { margin: 2px 0 0; overflow-wrap: anywhere; font-size: 13px; }
|
||||
.maps { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-top: 16px; }
|
||||
.maps h3, .identity h3 { margin: 0; font-size: 14px; color: #1e293b; }
|
||||
.maps ul { margin: 8px 0 0; padding-left: 18px; color: #334155; font-size: 13px; }
|
||||
.empty { color: #b45309; }
|
||||
@media (max-width: 767px) { .maps { grid-template-columns: 1fr; } }
|
||||
</style>
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaSchemaMappingPanel.vue
|
||||
用途:中栏 Schema 字段绑定面板(同 scope、类型兼容高亮)。
|
||||
依赖:vue-i18n、订单 Schema 字段。
|
||||
逻辑:点击字段绑定当前选中的原始 path 或拆分规则结果;仅过滤全部/未映射。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { OrderXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { ShippingOrderFieldConfig } from '@/features/admin/types/shipping-order-schema.types';
|
||||
|
||||
const props = defineProps<{
|
||||
schemaFields: ShippingOrderFieldConfig[];
|
||||
definition: OrderXfaDatasetProfileDefinition;
|
||||
selectedPathId?: string | null;
|
||||
selectedPathIsLeaf?: boolean;
|
||||
selectedRuleId?: string | null;
|
||||
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 }>;
|
||||
};
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
'bind-field': [field: ShippingOrderFieldConfig, scope: 'header' | 'line'];
|
||||
'unbind-field': [fieldId: string];
|
||||
'update:filterMode': [mode: 'all' | 'unmapped'];
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const localFilter = ref<'all' | 'unmapped'>(props.filterMode || 'all');
|
||||
|
||||
const boundIds = computed(() => {
|
||||
const ids = new Set<string>();
|
||||
for (const item of props.definition.header_mappings || []) ids.add(item.field_id);
|
||||
for (const item of props.definition.line_mapping?.fields || []) ids.add(item.field_id);
|
||||
for (const ruleSet of props.definition.split_rules || []) {
|
||||
for (const rule of ruleSet.rules || []) {
|
||||
if (rule.segment.handling === 'mapped' && rule.segment.target_field_id) ids.add(rule.segment.target_field_id);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
});
|
||||
|
||||
const mappingByFieldCode = computed(() => new Map(
|
||||
[...(props.mappedFieldPreviews?.header || []), ...(props.mappedFieldPreviews?.line || [])]
|
||||
.map((item) => [item.fieldCode, item]),
|
||||
));
|
||||
|
||||
/** 返回字段当前映射的路径与识别值,用于字段行内直接核对。 */
|
||||
function mappingFor(field: ShippingOrderFieldConfig) {
|
||||
return field.field_code ? mappingByFieldCode.value.get(field.field_code) : undefined;
|
||||
}
|
||||
|
||||
const groups = computed(() => {
|
||||
const mode = localFilter.value;
|
||||
const header: ShippingOrderFieldConfig[] = [];
|
||||
const line: ShippingOrderFieldConfig[] = [];
|
||||
for (const field of props.schemaFields) {
|
||||
if (!field.enabled) continue;
|
||||
const mapped = boundIds.value.has(field.field_id);
|
||||
if (mode === 'unmapped' && mapped) continue;
|
||||
if (field.scope === 'line') line.push(field);
|
||||
else header.push(field);
|
||||
}
|
||||
return { header, line };
|
||||
});
|
||||
|
||||
/**
|
||||
* 绑定当前原始叶子或拆分规则到 Schema 字段。
|
||||
* 拆分规则继承源节点作用域,只允许绑定同作用域字段。
|
||||
*/
|
||||
function bind(field: ShippingOrderFieldConfig): void {
|
||||
if (!props.selectedPathId || !props.selectedPathIsLeaf) return;
|
||||
if (props.selectedRuleId && field.scope !== props.selectedSourceScope) return;
|
||||
emit('bind-field', field, field.scope === 'line' ? 'line' : 'header');
|
||||
}
|
||||
|
||||
/** 将筛选按钮作为普通分段控制切换,避免声明不完整的 Tab 语义。 */
|
||||
function setFilter(mode: 'all' | 'unmapped'): void {
|
||||
localFilter.value = mode;
|
||||
emit('update:filterMode', mode);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-schema" :aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.schemaTitle')">
|
||||
<div class="xfa-schema__filters" role="group" :aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.filterLabel')">
|
||||
<button
|
||||
v-for="mode in (['all', 'unmapped'] as const)"
|
||||
:key="mode"
|
||||
type="button"
|
||||
:aria-pressed="localFilter === mode"
|
||||
:class="{ active: localFilter === mode }"
|
||||
@click="setFilter(mode)"
|
||||
>
|
||||
{{ t(`admin.shippingOrderProfiles.xfaWorkbench.filter.${mode}`) }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="!selectedPathIsLeaf" class="hint" id="xfa-schema-hint">{{ t('admin.shippingOrderProfiles.xfaWorkbench.selectLeafFirst') }}</p>
|
||||
<div v-for="(fields, scope) in { header: groups.header, line: groups.line }" :key="scope" class="group">
|
||||
<h3>{{ t(`admin.shippingOrderProfiles.xfaWorkbench.scope.${scope}`) }}</h3>
|
||||
<ul>
|
||||
<li v-for="field in fields" :key="field.field_id">
|
||||
<button
|
||||
type="button"
|
||||
class="field"
|
||||
:class="{ mapped: boundIds.has(field.field_id), disabled: !selectedPathIsLeaf || Boolean(selectedRuleId && field.scope !== selectedSourceScope) }"
|
||||
:disabled="!selectedPathIsLeaf || Boolean(selectedRuleId && field.scope !== selectedSourceScope)"
|
||||
:aria-describedby="!selectedPathIsLeaf ? 'xfa-schema-hint' : undefined"
|
||||
@click="bind(field)"
|
||||
>
|
||||
<span class="field__identity">
|
||||
<span>{{ field.display_name || field.field_code }}</span>
|
||||
<small>{{ field.field_code }}</small>
|
||||
</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>
|
||||
</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>
|
||||
</button>
|
||||
<button
|
||||
v-if="boundIds.has(field.field_id)"
|
||||
type="button"
|
||||
class="unbind"
|
||||
@click="emit('unbind-field', field.field_id)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.unbind') }}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-schema { display: flex; flex-direction: column; gap: 12px; min-height: 0; height: 100%; overflow: auto; }
|
||||
.xfa-schema__filters { display: flex; gap: 6px; }
|
||||
.xfa-schema__filters button { padding: 6px 10px; border: 1px solid var(--border-default); border-radius: 999px; background: var(--bg-surface); color: var(--text-secondary); }
|
||||
.xfa-schema__filters button.active { border-color: var(--status-info-border); color: var(--status-info-fg); background: var(--status-info-bg); }
|
||||
.hint { margin: 0; color: var(--status-warning-fg); font-size: .85rem; }
|
||||
.group h3 { margin: 0 0 8px; font-size: .9rem; }
|
||||
.group ul { margin: 0 0 14px; padding: 0; list-style: none; }
|
||||
.group li { display: flex; gap: 6px; margin-bottom: 6px; }
|
||||
.field { flex: 1; display: grid; grid-template-columns: minmax(180px, .7fr) minmax(260px, 1.3fr) auto; gap: 12px; align-items: center; min-width: 0; padding: 9px 12px; border: 1px solid var(--border-default); border-radius: var(--radius-control); background: var(--bg-surface); color: var(--text-primary); text-align: left; }
|
||||
.field.mapped { border-color: var(--status-success-border); background: var(--status-success-bg); }
|
||||
.field:focus-visible { outline: 2px solid var(--focus-ring); }
|
||||
.field__identity { display: flex; min-width: 0; align-items: baseline; gap: 8px; }
|
||||
.field__identity > span, .field__identity small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.field small { color: var(--text-muted); }
|
||||
.field__mapping { display: flex; min-width: 0; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.field__path { min-width: 0; overflow: hidden; color: var(--text-secondary); font-size: .76rem; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.field__value { flex: 0 0 auto; max-width: 180px; overflow: hidden; color: var(--status-success-fg); font-size: .76rem; font-weight: 650; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.field__empty { color: var(--text-muted); font-size: .76rem; }
|
||||
.field__check { color: var(--status-success-fg); }
|
||||
.unbind { border: 0; background: transparent; color: var(--status-error-fg); cursor: pointer; }
|
||||
@media (max-width: 1100px) {
|
||||
.field { grid-template-columns: minmax(150px, .8fr) minmax(180px, 1.2fr) auto; }
|
||||
}
|
||||
</style>
|
||||
+476
@@ -0,0 +1,476 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.spec.ts
|
||||
* 用途:验证 XfaSplitRulePanel pipeline 规则增删、确认门禁、order 重排与 reveal 传参。
|
||||
* 依赖:Vitest、@vue/test-utils、shipping-order-document-profile API mock。
|
||||
*/
|
||||
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { mount, flushPromises } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import XfaSplitRulePanel from './XfaSplitRulePanel.vue';
|
||||
import type { OrderXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const previewMock = vi.fn();
|
||||
const messageError = vi.fn();
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
|
||||
previewOrderProfileSampleXfaSplitRules: (...args: unknown[]) => previewMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({ success: vi.fn(), error: messageError }),
|
||||
}));
|
||||
|
||||
const baseDefinition: OrderXfaDatasetProfileDefinition = {
|
||||
template_mode: 'xfa_dataset',
|
||||
source_contract: {
|
||||
template_packet_checksum: 'tpl',
|
||||
dataset_structure_fingerprint: 'fp',
|
||||
dataset_root_path: '/data',
|
||||
authoritative_line_collection_path: '/data/ITEMS/DATA',
|
||||
mirror_collection_paths: [],
|
||||
},
|
||||
header_mappings: [],
|
||||
line_mapping: { row_path: '/data/ITEMS/DATA', fields: [] },
|
||||
cross_checks: {
|
||||
acroform_enabled: false,
|
||||
mirror_collection_policy: 'ignore',
|
||||
line_amount_formula: 'disabled',
|
||||
total_amount_policy: 'disabled',
|
||||
},
|
||||
split_rules: [],
|
||||
};
|
||||
|
||||
const xfaSplitMessages = {
|
||||
title: '拆分',
|
||||
expand: '展开',
|
||||
collapse: '收起',
|
||||
preview: '预览',
|
||||
confirm: '确认',
|
||||
addRule: '新增规则',
|
||||
deleteRule: '删除',
|
||||
deleteStage: '删除阶段',
|
||||
moveUp: '上移',
|
||||
moveDown: '下移',
|
||||
ruleLabel: '规则 {index}',
|
||||
stageLabel: '阶段 {index}',
|
||||
handling: '处理',
|
||||
mapped: '映射',
|
||||
evidenceOnly: '证据',
|
||||
needsReview: '复核',
|
||||
targetField: '目标',
|
||||
selectField: '选择',
|
||||
segmentCode: '编码',
|
||||
displayName: '名称',
|
||||
note: '备注',
|
||||
lineIndex: '行号',
|
||||
prefix: '前缀',
|
||||
separators: '分隔符',
|
||||
caseSensitive: '大小写',
|
||||
regex: '正则',
|
||||
captureGroup: '捕获',
|
||||
find: '查找',
|
||||
replaceWith: '替换为',
|
||||
substringStart: '起始',
|
||||
substringEnd: '结束',
|
||||
unmatchedPolicy: '未匹配',
|
||||
revealFullValues: '完整值',
|
||||
noRules: '无规则',
|
||||
confirmNeedsPreview: '需先预览',
|
||||
confirmBlockedDiagnostics: '诊断阻断',
|
||||
confirmDialog: '确认 mapped={mapped} evidence={evidence} diagnostics={diagnostics}',
|
||||
confirmSuccess: '已确认',
|
||||
previewTitle: '预览',
|
||||
previewStatus: '状态 {status}',
|
||||
previewMapped: '映射',
|
||||
previewNoMapped: '无',
|
||||
previewSegments: '段',
|
||||
previewNoSegments: '无段',
|
||||
previewValue: '值',
|
||||
previewRuleStatus: '状态',
|
||||
diagnostics: '诊断',
|
||||
ruleSetSettings: '规则集',
|
||||
normalization: '归一化',
|
||||
stages: '阶段',
|
||||
extractionMode: '提取方式',
|
||||
extractionByLine: '按行号提取',
|
||||
extractionByLineRange: '连续多行提取',
|
||||
extractionByLabel: '按标签提取',
|
||||
extractionByRegex: '按正则提取',
|
||||
extractionBySubstring: '截取文本',
|
||||
extractLineNumber: '提取第几行',
|
||||
extractStartLine: '起始行',
|
||||
extractEndLine: '结束行',
|
||||
joinLinesWith: '合并方式',
|
||||
joinWithNewline: '保留换行',
|
||||
joinWithSpace: '空格',
|
||||
joinWithComma: '逗号',
|
||||
recognizedValue: '识别值',
|
||||
previewRequired: '预览后显示',
|
||||
showAdvanced: '高级处理',
|
||||
hideAdvanced: '收起高级处理',
|
||||
advancedProcessing: '高级处理',
|
||||
addAdvancedStep: '添加高级处理',
|
||||
advancedExtractAfterLabel: '提取标签后内容',
|
||||
stageType: '类型',
|
||||
addStage: '添加阶段',
|
||||
stageTrim: 'trim',
|
||||
stageRemoveEmptyLines: '去空行',
|
||||
lineBreaks: '换行',
|
||||
lineBreaksPlaceholder: '\\n',
|
||||
stageTypeSplitLines: '拆分行',
|
||||
stageTypeSelectLine: '选行',
|
||||
stageTypeSelectLineRange: '连续多行',
|
||||
stageTypeExtractPrefix: '前缀',
|
||||
stageTypeRegexCapture: '正则',
|
||||
stageTypeReplace: '替换',
|
||||
stageTypeSubstring: '子串',
|
||||
stageTypeNormalize: '归一化',
|
||||
validationRequired: '必填',
|
||||
validationSegmentCode: '蛇形',
|
||||
validationMappedTarget: '目标必填',
|
||||
validationPrefixValue: '前缀必填',
|
||||
validationPrefixSeparators: '分隔符必填',
|
||||
validationRegexPattern: '正则必填',
|
||||
validationLineBreaks: '换行必填',
|
||||
validationLineRangeRequired: '范围必填',
|
||||
validationLineRangeOrder: '范围错误',
|
||||
status: { draft: '草稿', confirmed: '已确认', published: '已发布' },
|
||||
};
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
xfaSplit: xfaSplitMessages,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
function makePipelineRuleSet(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
rule_id: 'ruleset-1',
|
||||
rule_version: 1,
|
||||
source_path_id: 'path-matnr',
|
||||
source_field_code: 'MATNR',
|
||||
strategy: 'pipeline' as const,
|
||||
normalization: { trim: true, remove_empty_lines: true, line_breaks: ['\r\n', '\r', '\n'] },
|
||||
rules: [{
|
||||
rule_id: 'rule-1',
|
||||
order: 1,
|
||||
stages: [
|
||||
{ stage_id: 'stage-1', type: 'split_lines' as const, line_breaks: ['\n'] },
|
||||
{ stage_id: 'stage-2', type: 'select_line' as const, line_index: 1 },
|
||||
],
|
||||
segment: {
|
||||
segment_id: 'seg-1',
|
||||
segment_code: 'cpn',
|
||||
display_name: 'CPN',
|
||||
handling: 'evidence_only' as const,
|
||||
},
|
||||
}],
|
||||
status: 'draft' as const,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function mountPanel(overrides: Record<string, unknown> = {}) {
|
||||
return mount(XfaSplitRulePanel, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
definition: structuredClone(baseDefinition),
|
||||
selectedPathId: 'path-matnr',
|
||||
selectedPathLabel: 'MATNR',
|
||||
selectedFieldCode: 'MATNR',
|
||||
selectedIsMultiline: true,
|
||||
documentId: 85,
|
||||
profileId: 52,
|
||||
schemaFields: [{
|
||||
field_id: 'f1',
|
||||
field_code: 'customer_part_number',
|
||||
scope: 'line',
|
||||
enabled: true,
|
||||
required: true,
|
||||
value_type: 'string',
|
||||
}],
|
||||
canEdit: true,
|
||||
canPreview: true,
|
||||
canRevealSensitive: true,
|
||||
persistedConfirmed: true,
|
||||
dirtyUnsaved: false,
|
||||
...overrides,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取父弹窗可调用的组件操作,验证头部按钮迁移后仍保持原有业务行为。
|
||||
* @param wrapper - 已挂载的拆分规则组件
|
||||
* @returns 组件通过 defineExpose 暴露的新增、预览与确认方法
|
||||
*/
|
||||
function exposedActions(wrapper: ReturnType<typeof mountPanel>) {
|
||||
return wrapper.vm as unknown as {
|
||||
addRule: () => void;
|
||||
runPreview: () => Promise<void>;
|
||||
confirmRules: () => void;
|
||||
};
|
||||
}
|
||||
|
||||
describe('XfaSplitRulePanel', () => {
|
||||
beforeEach(() => {
|
||||
previewMock.mockReset();
|
||||
messageError.mockReset();
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
});
|
||||
|
||||
it('adds a rule with default pipeline stages and emits updated split_rules', async () => {
|
||||
const wrapper = mountPanel();
|
||||
exposedActions(wrapper).addRule();
|
||||
const emitted = wrapper.emitted('update:split-rules');
|
||||
expect(emitted?.length).toBeGreaterThan(0);
|
||||
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
|
||||
const ruleSet = last?.find((item) => item.source_path_id === 'path-matnr');
|
||||
expect(ruleSet?.strategy).toBe('pipeline');
|
||||
expect(ruleSet?.rules?.length).toBe(1);
|
||||
expect(ruleSet?.rules?.[0]?.stages?.length).toBe(2);
|
||||
expect(ruleSet?.rules?.[0]?.stages?.[0]?.type).toBe('split_lines');
|
||||
expect(ruleSet?.rules?.[0]?.stages?.[1]?.type).toBe('select_line');
|
||||
expect(ruleSet?.rules?.[0]?.order).toBe(1);
|
||||
expect(ruleSet?.status).toBe('draft');
|
||||
expect(ruleSet?.requires_confirmation).toBe(true);
|
||||
});
|
||||
|
||||
it('editing a confirmed rule emits draft with bumped rule_version', async () => {
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
split_rules: [makePipelineRuleSet({
|
||||
status: 'confirmed',
|
||||
requires_confirmation: false,
|
||||
rule_version: 3,
|
||||
})],
|
||||
},
|
||||
});
|
||||
const inputs = wrapper.findAll('input');
|
||||
const segmentCodeInput = inputs.find((input) => {
|
||||
const label = input.element.closest('label');
|
||||
return label?.textContent?.includes('编码');
|
||||
});
|
||||
expect(segmentCodeInput).toBeTruthy();
|
||||
await segmentCodeInput!.setValue('cpn_updated');
|
||||
await segmentCodeInput!.trigger('input');
|
||||
const emitted = wrapper.emitted('update:split-rules');
|
||||
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
|
||||
const ruleSet = last?.[0];
|
||||
expect(ruleSet?.status).toBe('draft');
|
||||
expect(ruleSet?.requires_confirmation).toBe(true);
|
||||
expect(ruleSet?.rule_version).toBe(4);
|
||||
});
|
||||
|
||||
it('blocks confirm when preview has diagnostics', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview: {
|
||||
status: 'ok',
|
||||
mapped_fields: {},
|
||||
segments: [],
|
||||
evidence_only_segments: [],
|
||||
diagnostics: [{ code: 'DUPLICATE', message: 'dup' }],
|
||||
},
|
||||
});
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
split_rules: [makePipelineRuleSet()],
|
||||
},
|
||||
});
|
||||
await exposedActions(wrapper).runPreview();
|
||||
await flushPromises();
|
||||
exposedActions(wrapper).confirmRules();
|
||||
expect(messageError).toHaveBeenCalledWith('诊断阻断');
|
||||
const confirmed = wrapper.emitted('update:split-rules')?.some((entry) => {
|
||||
const rules = entry[0] as typeof baseDefinition.split_rules;
|
||||
return rules?.[0]?.status === 'confirmed';
|
||||
});
|
||||
expect(confirmed).toBeFalsy();
|
||||
});
|
||||
|
||||
it('configures consecutive line extraction with range and join mode', async () => {
|
||||
const wrapper = mountPanel({
|
||||
definition: { ...baseDefinition, split_rules: [makePipelineRuleSet()] },
|
||||
});
|
||||
const extractionSelect = wrapper.findAll('select').find((select) => (
|
||||
select.element.closest('label')?.textContent?.includes('提取方式')
|
||||
));
|
||||
expect(extractionSelect).toBeTruthy();
|
||||
await extractionSelect!.setValue('select_line_range');
|
||||
const emitted = wrapper.emitted('update:split-rules');
|
||||
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
|
||||
const range = last?.[0]?.rules?.[0]?.stages?.find((stage) => stage.type === 'select_line_range');
|
||||
expect(range).toMatchObject({ line_start: 1, line_end: 2, join_with: 'newline' });
|
||||
const rangeWrapper = mountPanel({
|
||||
definition: { ...baseDefinition, split_rules: last },
|
||||
});
|
||||
expect(rangeWrapper.text()).toContain('起始行');
|
||||
expect(rangeWrapper.text()).toContain('结束行');
|
||||
expect(rangeWrapper.text()).toContain('合并方式');
|
||||
});
|
||||
|
||||
it('emits the final confirmed rules for parent persistence', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview: {
|
||||
status: 'ok',
|
||||
mapped_fields: {},
|
||||
segments: [{
|
||||
segment_id: 'seg-1', segment_code: 'cpn', rule_id: 'rule-1',
|
||||
matcher_type: 'pipeline', normalized_text: 'CPN-001', raw_text: 'CPN-001', status: 'matched',
|
||||
}],
|
||||
evidence_only_segments: [],
|
||||
diagnostics: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mountPanel({
|
||||
definition: { ...baseDefinition, split_rules: [makePipelineRuleSet()] },
|
||||
});
|
||||
await exposedActions(wrapper).runPreview();
|
||||
await flushPromises();
|
||||
exposedActions(wrapper).confirmRules();
|
||||
|
||||
const confirmed = wrapper.emitted('confirmed');
|
||||
const rules = confirmed?.[0]?.[0] as typeof baseDefinition.split_rules;
|
||||
expect(rules?.[0]?.status).toBe('confirmed');
|
||||
expect(rules?.[0]?.requires_confirmation).toBe(false);
|
||||
expect(rules?.[0]?.source_path_id).toBe('path-matnr');
|
||||
expect(() => JSON.parse(JSON.stringify(rules))).not.toThrow();
|
||||
});
|
||||
|
||||
it('move up/down updates rule order field', async () => {
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
split_rules: [makePipelineRuleSet({
|
||||
rules: [
|
||||
{
|
||||
rule_id: 'rule-a',
|
||||
order: 1,
|
||||
stages: [
|
||||
{ stage_id: 's1', type: 'split_lines', line_breaks: ['\n'] },
|
||||
{ stage_id: 's2', type: 'select_line', line_index: 1 },
|
||||
],
|
||||
segment: {
|
||||
segment_id: 'seg-a',
|
||||
segment_code: 'a',
|
||||
display_name: 'A',
|
||||
handling: 'evidence_only',
|
||||
},
|
||||
},
|
||||
{
|
||||
rule_id: 'rule-b',
|
||||
order: 2,
|
||||
stages: [
|
||||
{ stage_id: 's3', type: 'split_lines', line_breaks: ['\n'] },
|
||||
{ stage_id: 's4', type: 'select_line', line_index: 2 },
|
||||
],
|
||||
segment: {
|
||||
segment_id: 'seg-b',
|
||||
segment_code: 'b',
|
||||
display_name: 'B',
|
||||
handling: 'evidence_only',
|
||||
},
|
||||
},
|
||||
],
|
||||
})],
|
||||
},
|
||||
});
|
||||
const moveDownButtons = wrapper.findAll('button').filter((btn) => btn.text() === '下移');
|
||||
expect(moveDownButtons.length).toBeGreaterThan(0);
|
||||
await moveDownButtons[0]!.trigger('click');
|
||||
const emitted = wrapper.emitted('update:split-rules');
|
||||
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
|
||||
const rules = last?.[0]?.rules || [];
|
||||
const ruleA = rules.find((item) => item.rule_id === 'rule-a');
|
||||
const ruleB = rules.find((item) => item.rule_id === 'rule-b');
|
||||
expect(ruleA?.order).toBe(2);
|
||||
expect(ruleB?.order).toBe(1);
|
||||
});
|
||||
|
||||
it('defaults the third rule to extract line three', async () => {
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
split_rules: [makePipelineRuleSet({
|
||||
rules: [
|
||||
makePipelineRuleSet().rules[0],
|
||||
{ ...makePipelineRuleSet().rules[0], rule_id: 'rule-2', order: 2 },
|
||||
],
|
||||
})],
|
||||
},
|
||||
});
|
||||
exposedActions(wrapper).addRule();
|
||||
const emitted = wrapper.emitted('update:split-rules');
|
||||
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
|
||||
const third = last?.[0]?.rules.find((rule) => rule.order === 3);
|
||||
expect(third?.stages.find((stage) => stage.type === 'select_line')?.line_index).toBe(3);
|
||||
});
|
||||
|
||||
it('keeps line extraction and appends label extraction as advanced processing', async () => {
|
||||
const wrapper = mountPanel({
|
||||
definition: { ...baseDefinition, split_rules: [makePipelineRuleSet()] },
|
||||
});
|
||||
const advancedButton = wrapper.findAll('button').find((btn) => btn.text().includes('高级处理'));
|
||||
await advancedButton!.trigger('click');
|
||||
const addAdvanced = wrapper.find('.xfa-split__add-stage-select');
|
||||
await addAdvanced.setValue('extract_prefix');
|
||||
await addAdvanced.trigger('change');
|
||||
const emitted = wrapper.emitted('update:split-rules');
|
||||
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
|
||||
expect(last?.[0]?.rules[0]?.stages.map((stage) => stage.type)).toEqual([
|
||||
'split_lines', 'select_line', 'extract_prefix',
|
||||
]);
|
||||
});
|
||||
|
||||
it('adds a rule after mounting when autoAddRule is enabled', () => {
|
||||
const wrapper = mountPanel({
|
||||
autoAddRule: true,
|
||||
definition: { ...baseDefinition, split_rules: [] },
|
||||
});
|
||||
const emitted = wrapper.emitted('update:split-rules');
|
||||
const rules = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
|
||||
expect(rules?.[0]?.rules).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('passes reveal:true to preview API when checkbox enabled and canRevealSensitive', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview: {
|
||||
status: 'ok',
|
||||
mapped_fields: {},
|
||||
segments: [],
|
||||
evidence_only_segments: [],
|
||||
diagnostics: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
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 }));
|
||||
});
|
||||
|
||||
it('ignores exposed edit actions when canEdit is false', () => {
|
||||
const wrapper = mountPanel({ canEdit: false });
|
||||
exposedActions(wrapper).addRule();
|
||||
exposedActions(wrapper).confirmRules();
|
||||
expect(wrapper.emitted('update:split-rules')).toBeUndefined();
|
||||
expect(wrapper.emitted('confirmed')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
+1158
File diff suppressed because it is too large.
Load diff
+94
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/XfaStructuredPreview.spec.ts
|
||||
* 用途:断言预览面板展示阻断摘要、脱敏样本与交叉校验策略。
|
||||
* 依赖:Vitest、@vue/test-utils、XfaStructuredPreview。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import XfaStructuredPreview from './XfaStructuredPreview.vue';
|
||||
import type { OrderXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
common: { yes: '是', no: '否' },
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
xfaWorkbench: {
|
||||
previewTitle: '预览', blockersTitle: '阻断', currentNode: '节点', noneSelected: '无',
|
||||
headerMaps: '表头', lineMaps: '明细', requiredCoverage: '必填 {mapped}/{total}',
|
||||
maskedSample: '脱敏样本值', noMappings: '暂无映射',
|
||||
crossChecksTitle: '交叉校验策略',
|
||||
crossCheck: {
|
||||
acroform: 'AcroForm 对账', mirror: '镜像集合',
|
||||
lineAmount: '明细金额公式', totalAmount: '表头总额策略',
|
||||
},
|
||||
previewHint: '请在验证页查看干跑结果',
|
||||
blocker: { required_fields_unmapped: '必填未映射' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const definition: OrderXfaDatasetProfileDefinition = {
|
||||
template_mode: 'xfa_dataset',
|
||||
source_contract: {
|
||||
template_packet_checksum: 'tpl', dataset_structure_fingerprint: 'fp', dataset_root_path: '/data',
|
||||
authoritative_line_collection_path: '/data/ITEMS/DATA', mirror_collection_paths: [],
|
||||
},
|
||||
header_mappings: [{
|
||||
mapping_id: 'm1', field_id: 'f1', field_code: 'customer_po_no',
|
||||
data_path: '', path_id: 'hdr-ebeln', value_type: 'string',
|
||||
}],
|
||||
line_mapping: { row_path: '/data/ITEMS/DATA', fields: [] },
|
||||
cross_checks: {
|
||||
acroform_enabled: true, mirror_collection_policy: 'must_match_when_present',
|
||||
line_amount_formula: 'quantity_times_unit_price', total_amount_policy: 'must_equal_line_sum',
|
||||
},
|
||||
};
|
||||
|
||||
describe('XfaStructuredPreview', () => {
|
||||
it('renders template-local blockers without Schema required coverage', () => {
|
||||
const wrapper = mount(XfaStructuredPreview, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
definition,
|
||||
coverage: {
|
||||
requiredTotal: 0, requiredMapped: 0,
|
||||
missingRequired: [],
|
||||
duplicateFieldIds: [], authoritativeMissing: true,
|
||||
},
|
||||
blockers: ['authoritative_collection_required'],
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[role="alert"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('shows compact mapping summary without internal cross-check details', () => {
|
||||
const wrapper = mount(XfaStructuredPreview, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
definition,
|
||||
coverage: {
|
||||
requiredTotal: 1, requiredMapped: 1,
|
||||
missingRequired: [], duplicateFieldIds: [], authoritativeMissing: false,
|
||||
},
|
||||
mappedFieldPreviews: {
|
||||
header: [{
|
||||
mappingId: 'm1', fieldCode: 'customer_po_no', pathId: 'hdr-ebeln',
|
||||
pathLabel: 'EBELN', maskedValue: '4510***227',
|
||||
}],
|
||||
line: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(wrapper.text()).toContain('customer_po_no');
|
||||
expect(wrapper.text()).not.toContain('交叉校验策略');
|
||||
expect(wrapper.text()).not.toContain('quantity_times_unit_price');
|
||||
});
|
||||
});
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaStructuredPreview.vue
|
||||
用途:右侧阻断摘要与已完成字段映射的紧凑预览。
|
||||
依赖:vue-i18n、覆盖率摘要类型。
|
||||
逻辑:仅展示需要即时处理的阻断项和已完成映射;当前节点由左侧树/中间编辑区表达,交叉校验策略由验证页承担。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type {
|
||||
OrderXfaDatasetProfileDefinition,
|
||||
XfaMappingCoverageSummary,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
export interface XfaMappedFieldPreviewRow {
|
||||
mappingId: string;
|
||||
fieldCode: string;
|
||||
pathId: string;
|
||||
pathLabel: string;
|
||||
maskedValue: string | null;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
definition: OrderXfaDatasetProfileDefinition;
|
||||
coverage: XfaMappingCoverageSummary;
|
||||
mappedFieldPreviews?: {
|
||||
header: XfaMappedFieldPreviewRow[];
|
||||
line: XfaMappedFieldPreviewRow[];
|
||||
};
|
||||
blockers?: string[];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const headerRows = computed(() => props.mappedFieldPreviews?.header?.length
|
||||
? props.mappedFieldPreviews.header
|
||||
: (props.definition.header_mappings || []).map((item) => ({
|
||||
mappingId: item.mapping_id,
|
||||
fieldCode: item.field_code,
|
||||
pathId: item.path_id,
|
||||
pathLabel: item.path_id,
|
||||
maskedValue: null as string | null,
|
||||
})));
|
||||
|
||||
const lineRows = computed(() => props.mappedFieldPreviews?.line?.length
|
||||
? props.mappedFieldPreviews.line
|
||||
: (props.definition.line_mapping?.fields || []).map((item) => ({
|
||||
mappingId: item.mapping_id,
|
||||
fieldCode: item.field_code,
|
||||
pathId: item.path_id,
|
||||
pathLabel: item.path_id,
|
||||
maskedValue: null as string | null,
|
||||
})));
|
||||
const mappingRows = computed(() => [...headerRows.value, ...lineRows.value]);
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-preview" :aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.previewTitle')">
|
||||
<div v-if="blockers?.length" class="blockers" role="alert" tabindex="-1">
|
||||
<h3>{{ t('admin.shippingOrderProfiles.xfaWorkbench.blockersTitle') }}</h3>
|
||||
<ul>
|
||||
<li v-for="code in blockers" :key="code">{{ t(`admin.shippingOrderProfiles.xfaWorkbench.blocker.${code}`) }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="maps">
|
||||
<div class="maps__heading">
|
||||
<h3>{{ t('admin.shippingOrderProfiles.xfaWorkbench.mappingRelations') }}</h3>
|
||||
<span>{{ mappingRows.length }}</span>
|
||||
</div>
|
||||
<ul v-if="mappingRows.length" class="maps__list">
|
||||
<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>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="empty">{{ t('admin.shippingOrderProfiles.xfaWorkbench.noMappings') }}</p>
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-preview { display: flex; flex-direction: column; gap: 10px; min-height: 0; height: 100%; overflow: auto; }
|
||||
.blockers { padding: 10px; border: 1px solid var(--status-error-border); border-radius: var(--radius-control); background: var(--status-error-bg); color: var(--status-error-fg); }
|
||||
.blockers:focus { outline: 2px solid var(--focus-ring); }
|
||||
.maps { min-width: 0; padding: 10px; border: 1px solid var(--border-default); border-radius: var(--radius-control); background: var(--bg-surface); }
|
||||
.maps__heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.maps__heading span { min-width: 1.5rem; border-radius: 999px; background: var(--bg-page); color: var(--text-muted); font-size: .68rem; text-align: center; }
|
||||
.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); }
|
||||
.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); }
|
||||
</style>
|
||||
-36
@@ -7,8 +7,6 @@
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
buildOrderProfileColumnRules,
|
||||
findDuplicateOrderProfileTargets,
|
||||
mergeOrderProfileHeaderLabels,
|
||||
restoreOrderProfileRegionPageNo,
|
||||
suggestFieldCodeFromHeaders,
|
||||
@@ -44,40 +42,6 @@ describe('order profile form rules', () => {
|
||||
},
|
||||
);
|
||||
|
||||
it('builds only registered direct and composite rules', () => {
|
||||
const rules = buildOrderProfileColumnRules([
|
||||
{ extractor_key: 'direct', target: 'qty' },
|
||||
{ extractor_key: 'direct', target: '' },
|
||||
{ extractor_key: 'temp_internal_parts', target: '' },
|
||||
], true);
|
||||
|
||||
// 断言忽略空列,并保持复合解析器的固定双字段输出契约。
|
||||
expect(rules).toEqual([
|
||||
{ column_index: 0, extractor_key: 'direct', target_field_codes: ['qty'] },
|
||||
{
|
||||
column_index: 2,
|
||||
extractor_key: 'temp_internal_parts',
|
||||
target_field_codes: ['customer_part_number', 'part_number'],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('blocks targets repeated by direct or composite mappings', () => {
|
||||
const rules = buildOrderProfileColumnRules([
|
||||
{ extractor_key: 'temp_internal_parts', target: '' },
|
||||
{ extractor_key: 'direct', target: 'part_number' },
|
||||
], true);
|
||||
|
||||
// 断言复合解析器与普通列之间的隐式重复也能在提交前被发现。
|
||||
expect(findDuplicateOrderProfileTargets(rules)).toEqual(['part_number']);
|
||||
});
|
||||
|
||||
it('does not emit an unavailable composite extractor', () => {
|
||||
expect(buildOrderProfileColumnRules([
|
||||
{ extractor_key: 'temp_internal_parts', target: '' },
|
||||
], false)).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps directly configurable tables visible despite stale multi-row state', () => {
|
||||
// 断言上一张表残留的多物理行开关不能隐藏当前可直接配置的表格。
|
||||
expect(shouldShowStandardOrderProfilePreview(true, true, true)).toBe(true);
|
||||
|
||||
-35
@@ -9,16 +9,10 @@ import type {
|
||||
CoordinateReconstructionPreview,
|
||||
OrderFieldValuePreview,
|
||||
OrderProfileCanvasRegion,
|
||||
OrderProfileColumnRule,
|
||||
OrderProfileRelativeRegion,
|
||||
OrderProfileTableRegion,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
export interface OrderProfileColumnSelection {
|
||||
extractor_key: 'direct' | 'temp_internal_parts';
|
||||
target: string;
|
||||
}
|
||||
|
||||
export interface OrderProfileLineFieldGroups {
|
||||
fieldsByLayout: Map<string, OrderProfileCanvasRegion[]>;
|
||||
boundRegionIds: Set<string>;
|
||||
@@ -101,35 +95,6 @@ export const mergeOrderProfileHeaderLabels = (
|
||||
return labels.join(' / ');
|
||||
});
|
||||
|
||||
/** 将逐列选择转换为后端白名单规则;不可用的复合解析器不会进入请求。 */
|
||||
export const buildOrderProfileColumnRules = (
|
||||
selections: OrderProfileColumnSelection[], compositeExtractorAvailable: boolean,
|
||||
): OrderProfileColumnRule[] => {
|
||||
const rules: OrderProfileColumnRule[] = [];
|
||||
selections.forEach((item, columnIndex) => {
|
||||
if (item.extractor_key === 'temp_internal_parts') {
|
||||
if (compositeExtractorAvailable) rules.push({
|
||||
column_index: columnIndex,
|
||||
extractor_key: 'temp_internal_parts',
|
||||
target_field_codes: ['customer_part_number', 'part_number'],
|
||||
});
|
||||
} else if (item.target) {
|
||||
rules.push({
|
||||
column_index: columnIndex,
|
||||
extractor_key: 'direct',
|
||||
target_field_codes: [item.target],
|
||||
});
|
||||
}
|
||||
});
|
||||
return rules;
|
||||
};
|
||||
|
||||
/** 返回跨列重复映射的目标字段,供页面阻止提交并显示明确提示。 */
|
||||
export const findDuplicateOrderProfileTargets = (rules: OrderProfileColumnRule[]): string[] => {
|
||||
const targets = rules.flatMap((item) => item.target_field_codes);
|
||||
return [...new Set(targets.filter((target, index) => targets.indexOf(target) !== index))];
|
||||
};
|
||||
|
||||
/**
|
||||
* 将历史页作用域恢复为单页画布页码;旧 all_pages 缺少原始页号时按首篇样例页迁移。
|
||||
* @param tableRegion - 已保存的 v2 表格区域
|
||||
|
||||
+7
-5
@@ -9,6 +9,7 @@ import type {
|
||||
OrderProfileCanvasRegion,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { asCoordinateProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { restoreOrderProfileRegionPageNo } from './orderProfileForm.utils';
|
||||
|
||||
const mergeEquivalentOrderAnchors = (items: OrderProfileCanvasRegion[]) => {
|
||||
@@ -60,8 +61,9 @@ const pageNoOf = (pageScope: 'first_page' | 'all_pages' | 'exact_page', pageNo?:
|
||||
export const buildOrderProfileReadonlyRegions = (
|
||||
profile: ShippingOrderDocumentProfile,
|
||||
): OrderProfileCanvasRegion[] => {
|
||||
const definition = asCoordinateProfileDefinition(profile.definition);
|
||||
const restored: OrderProfileCanvasRegion[] = [
|
||||
...(profile.definition.document_match.required_anchors || []).flatMap<OrderProfileCanvasRegion>((anchor) => {
|
||||
...(definition.document_match.required_anchors || []).flatMap<OrderProfileCanvasRegion>((anchor) => {
|
||||
if (!anchor.label_region || !anchor.value_region || !anchor.page_no) return [];
|
||||
return [{
|
||||
id: `${anchor.anchor_id}_label`,
|
||||
@@ -81,7 +83,7 @@ export const buildOrderProfileReadonlyRegions = (
|
||||
pageNo: anchor.page_no,
|
||||
}];
|
||||
}),
|
||||
...(profile.definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
|
||||
...(definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
|
||||
const pageNo = pageNoOf(item.page_scope, item.page_no);
|
||||
if (!item.anchor?.region || !item.absolute_value_region) {
|
||||
return [{
|
||||
@@ -111,7 +113,7 @@ export const buildOrderProfileReadonlyRegions = (
|
||||
pageNo,
|
||||
}];
|
||||
}),
|
||||
...(profile.definition.order_field_layouts || []).filter((item) => !item.anchor).map((item) => ({
|
||||
...(definition.order_field_layouts || []).filter((item) => !item.anchor).map((item) => ({
|
||||
id: item.layout_id,
|
||||
kind: 'order_field' as const,
|
||||
label: item.field_code,
|
||||
@@ -119,7 +121,7 @@ export const buildOrderProfileReadonlyRegions = (
|
||||
fieldCode: item.field_code,
|
||||
pageNo: pageNoOf(item.page_scope, item.page_no),
|
||||
})),
|
||||
...(profile.definition.order_field_layouts || []).flatMap((item) => {
|
||||
...(definition.order_field_layouts || []).flatMap((item) => {
|
||||
if (!item.anchor?.region || !item.absolute_value_region) return [];
|
||||
const anchor = item.anchor.region;
|
||||
return [{
|
||||
@@ -141,7 +143,7 @@ export const buildOrderProfileReadonlyRegions = (
|
||||
pageNo: pageNoOf(item.page_scope, item.page_no),
|
||||
}];
|
||||
}),
|
||||
...profile.definition.table_regions.flatMap((table) => {
|
||||
...definition.table_regions.flatMap((table) => {
|
||||
const regionPageNo = restoreOrderProfileRegionPageNo(table);
|
||||
const headerLayoutIds = new Set(table.header_layouts.map((item) => item.layout_id));
|
||||
return [
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/xfaProfileMapping.utils.spec.ts
|
||||
* 用途:验证 XFA 映射工具函数——含 split_rules mapped 目标的 bound field 与覆盖率。
|
||||
* 依赖:Vitest、xfaProfileMapping.utils。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
collectBoundXfaFieldIds,
|
||||
computeXfaMappingCoverage,
|
||||
flattenXfaTreeNodes,
|
||||
summarizeXfaMappingBlockers,
|
||||
} from './xfaProfileMapping.utils';
|
||||
import type { OrderXfaDatasetProfileDefinition, XfaFieldTreeNode } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const baseDefinition: OrderXfaDatasetProfileDefinition = {
|
||||
template_mode: 'xfa_dataset',
|
||||
source_contract: {
|
||||
template_packet_checksum: 'tpl',
|
||||
dataset_structure_fingerprint: 'fp',
|
||||
dataset_root_path: '/data',
|
||||
authoritative_line_collection_path: '/data/ITEMS/DATA',
|
||||
mirror_collection_paths: [],
|
||||
},
|
||||
header_mappings: [],
|
||||
line_mapping: { row_path: '/data/ITEMS/DATA', fields: [] },
|
||||
cross_checks: {
|
||||
acroform_enabled: false,
|
||||
mirror_collection_policy: 'ignore',
|
||||
line_amount_formula: 'disabled',
|
||||
total_amount_policy: 'disabled',
|
||||
},
|
||||
split_rules: [{
|
||||
rule_id: 'matnr-v1',
|
||||
rule_version: 1,
|
||||
source_path_id: 'path-matnr',
|
||||
source_field_code: 'MATNR',
|
||||
strategy: 'pipeline',
|
||||
rules: [{
|
||||
rule_id: 'r1',
|
||||
order: 1,
|
||||
stages: [
|
||||
{ stage_id: 'st1', type: 'split_lines', line_breaks: ['\n'] },
|
||||
{ stage_id: 'st2', type: 'select_line', line_index: 1 },
|
||||
],
|
||||
segment: {
|
||||
segment_id: 'seg-1',
|
||||
segment_code: 'cpn',
|
||||
display_name: 'CPN',
|
||||
handling: 'mapped',
|
||||
target_field_id: 'f-cpn',
|
||||
target_field_code: 'customer_part_number',
|
||||
},
|
||||
}],
|
||||
status: 'confirmed',
|
||||
source: 'user',
|
||||
requires_confirmation: false,
|
||||
}],
|
||||
};
|
||||
|
||||
describe('xfaProfileMapping split utils', () => {
|
||||
it('collectBoundXfaFieldIds includes split mapped targets', () => {
|
||||
const ids = collectBoundXfaFieldIds(baseDefinition);
|
||||
expect(ids.has('f-cpn')).toBe(true);
|
||||
});
|
||||
|
||||
it('computeXfaMappingCoverage does not treat Schema required fields as template blockers', () => {
|
||||
const coverage = computeXfaMappingCoverage(
|
||||
[{
|
||||
field_id: 'f-cpn',
|
||||
field_code: 'customer_part_number',
|
||||
scope: 'line',
|
||||
enabled: true,
|
||||
required: true,
|
||||
value_type: 'string',
|
||||
}],
|
||||
baseDefinition,
|
||||
'path-data',
|
||||
);
|
||||
expect(coverage.missingRequired).toHaveLength(0);
|
||||
expect(coverage.requiredTotal).toBe(0);
|
||||
expect(coverage.requiredMapped).toBe(0);
|
||||
expect(summarizeXfaMappingBlockers(coverage)).not.toContain('required_fields_unmapped');
|
||||
});
|
||||
|
||||
it('flattenXfaTreeNodes copies line_count to lineCount', () => {
|
||||
const tree: XfaFieldTreeNode = {
|
||||
path_id: 'root',
|
||||
local_name: 'data',
|
||||
data_path_hash: 'h-root',
|
||||
depth: 0,
|
||||
cardinality: 'one',
|
||||
is_leaf: false,
|
||||
children: [{
|
||||
path_id: 'matnr',
|
||||
local_name: 'MATNR',
|
||||
data_path_hash: 'h-matnr',
|
||||
depth: 1,
|
||||
cardinality: 'one',
|
||||
is_leaf: true,
|
||||
line_count: 5,
|
||||
}],
|
||||
};
|
||||
const flat = flattenXfaTreeNodes(tree);
|
||||
const matnr = flat.find((item) => item.pathId === 'matnr');
|
||||
expect(matnr?.lineCount).toBe(5);
|
||||
});
|
||||
|
||||
it('selectedIsMultiline uses lineCount greater than one', () => {
|
||||
const tree: XfaFieldTreeNode = {
|
||||
path_id: 'single',
|
||||
local_name: 'FIELD',
|
||||
data_path_hash: 'h1',
|
||||
depth: 0,
|
||||
cardinality: 'one',
|
||||
is_leaf: true,
|
||||
line_count: 1,
|
||||
};
|
||||
const flat = flattenXfaTreeNodes(tree);
|
||||
expect((flat[0]?.lineCount || 0) > 1).toBe(false);
|
||||
|
||||
const multiline: XfaFieldTreeNode = { ...tree, path_id: 'multi', line_count: 3 };
|
||||
const flatMulti = flattenXfaTreeNodes(multiline);
|
||||
expect((flatMulti[0]?.lineCount || 0) > 1).toBe(true);
|
||||
});
|
||||
});
|
||||
+476
@@ -0,0 +1,476 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/xfaProfileMapping.utils.ts
|
||||
* 用途:XFA 映射工作台纯函数——树投影、Schema 过滤、覆盖率、保存 payload 与脏状态检测。
|
||||
* 依赖:shipping-order-document-profile.types、订单 Schema 字段类型。
|
||||
* 逻辑:页面与组件只调用本文件;不发网络请求,不持有明文 XML 或 data_path。
|
||||
*/
|
||||
|
||||
import type {
|
||||
OrderXfaDatasetProfileDefinition,
|
||||
XfaCollectionCandidate,
|
||||
XfaFieldMapping,
|
||||
XfaFieldTreeNode,
|
||||
XfaMappingCoverageSummary,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { ShippingOrderFieldConfig } from '@/features/admin/types/shipping-order-schema.types';
|
||||
|
||||
export type XfaSchemaFilterMode = 'all' | 'unmapped';
|
||||
|
||||
export interface XfaFlatTreeNode {
|
||||
pathId: string;
|
||||
localName: string;
|
||||
depth: number;
|
||||
isLeaf: boolean;
|
||||
isHeaderCandidate: boolean;
|
||||
isCollectionCandidate: boolean;
|
||||
sampleValueMasked?: string;
|
||||
sampleValueDisplay?: string;
|
||||
displayPolicy: 'empty' | 'full' | 'partial' | 'restricted';
|
||||
canReveal: boolean;
|
||||
lineCount?: number;
|
||||
dataPathHash: string;
|
||||
parentPathId?: string;
|
||||
}
|
||||
|
||||
export interface XfaMappingWorkbenchState {
|
||||
definition: OrderXfaDatasetProfileDefinition;
|
||||
authoritativeCollectionPathId: string;
|
||||
mirrorCollectionPathIds: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 XFA 字段树投影为可键盘导航的扁平节点列表。
|
||||
* 核心逻辑:深度优先展开;仅保留分析记录返回的节点。
|
||||
* @param tree 字段树根节点
|
||||
* @returns 扁平节点(含 depth / leaf / collection 标记)
|
||||
*/
|
||||
export function flattenXfaTreeNodes(tree: XfaFieldTreeNode | null | undefined): XfaFlatTreeNode[] {
|
||||
if (!tree || !tree.path_id) return [];
|
||||
const rows: XfaFlatTreeNode[] = [];
|
||||
|
||||
const walk = (node: XfaFieldTreeNode, parentPathId?: string): void => {
|
||||
rows.push({
|
||||
pathId: node.path_id,
|
||||
localName: node.local_name,
|
||||
depth: node.depth,
|
||||
isLeaf: Boolean(node.is_leaf),
|
||||
isHeaderCandidate: Boolean(node.is_header_candidate),
|
||||
isCollectionCandidate: Boolean(node.is_collection_candidate),
|
||||
sampleValueMasked: node.sample_value_masked,
|
||||
sampleValueDisplay: node.sample_value_display || node.sample_value_masked,
|
||||
displayPolicy: node.display_policy || 'empty',
|
||||
canReveal: Boolean(node.can_reveal),
|
||||
lineCount: node.line_count,
|
||||
dataPathHash: node.data_path_hash,
|
||||
parentPathId,
|
||||
});
|
||||
for (const child of node.children || []) walk(child, node.path_id);
|
||||
};
|
||||
walk(tree);
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 由 path_id 链向上拼接 local_name 展示标签(不含服务端明文路径)。
|
||||
* @param pathId 目标节点 path_id
|
||||
* @param nodes 扁平树节点
|
||||
*/
|
||||
export function buildXfaPathLabel(pathId: string, nodes: XfaFlatTreeNode[]): string {
|
||||
const byId = new Map(nodes.map((item) => [item.pathId, item]));
|
||||
const parts: string[] = [];
|
||||
let current = byId.get(pathId);
|
||||
while (current) {
|
||||
parts.unshift(current.localName);
|
||||
current = current.parentPathId ? byId.get(current.parentPathId) : undefined;
|
||||
}
|
||||
return parts.join('/') || pathId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按关键字过滤扁平树(匹配 local_name / path_id / 脱敏样例)。
|
||||
* @param nodes 扁平节点
|
||||
* @param query 搜索词
|
||||
*/
|
||||
export function filterXfaTreeNodes(nodes: XfaFlatTreeNode[], query: string): XfaFlatTreeNode[] {
|
||||
const needle = query.trim().toLowerCase();
|
||||
if (!needle) return nodes;
|
||||
return nodes.filter((item) => (
|
||||
item.localName.toLowerCase().includes(needle)
|
||||
|| item.pathId.toLowerCase().includes(needle)
|
||||
|| String(item.sampleValueMasked || '').toLowerCase().includes(needle)
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断节点是否位于权威明细集合之下(用于 Header/Line scope 划分)。
|
||||
* @param pathId 选中叶子 path_id
|
||||
* @param authoritativePathId 权威集合 path_id
|
||||
* @param nodes 扁平树
|
||||
*/
|
||||
export function isXfaPathUnderCollection(
|
||||
pathId: string,
|
||||
authoritativePathId: string,
|
||||
nodes: XfaFlatTreeNode[],
|
||||
): boolean {
|
||||
if (!authoritativePathId || pathId === authoritativePathId) return false;
|
||||
const byId = new Map(nodes.map((item) => [item.pathId, item]));
|
||||
let current = byId.get(pathId);
|
||||
while (current) {
|
||||
if (current.pathId === authoritativePathId) return true;
|
||||
current = current.parentPathId ? byId.get(current.parentPathId) : undefined;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析选中树节点应绑定的 Schema scope。
|
||||
* @param pathId 选中 path_id
|
||||
* @param authoritativePathId 权威集合 path_id
|
||||
* @param nodes 扁平树
|
||||
*/
|
||||
export function resolveXfaNodeScope(
|
||||
pathId: string,
|
||||
authoritativePathId: string,
|
||||
nodes: XfaFlatTreeNode[],
|
||||
): 'header' | 'line' | null {
|
||||
const node = nodes.find((item) => item.pathId === pathId);
|
||||
if (!node?.isLeaf) return null;
|
||||
return isXfaPathUnderCollection(pathId, authoritativePathId, nodes) ? 'line' : 'header';
|
||||
}
|
||||
|
||||
/**
|
||||
* 过滤 Schema 字段列表供映射面板展示。
|
||||
* @param fields 已启用字段
|
||||
* @param scope 当前节点 scope
|
||||
* @param filterMode 全部/未映射
|
||||
* @param definition 当前 definition
|
||||
* @param boundFieldIds 已绑定 field_id 集合
|
||||
*/
|
||||
export function filterXfaSchemaFields(
|
||||
fields: ShippingOrderFieldConfig[],
|
||||
scope: 'header' | 'line',
|
||||
filterMode: XfaSchemaFilterMode,
|
||||
definition: OrderXfaDatasetProfileDefinition,
|
||||
): ShippingOrderFieldConfig[] {
|
||||
const mappings = scope === 'header'
|
||||
? definition.header_mappings || []
|
||||
: definition.line_mapping?.fields || [];
|
||||
const mappedCodes = new Set(mappings.map((item) => item.field_code));
|
||||
return fields.filter((field) => {
|
||||
if (field.enabled === false || field.scope !== scope || !field.field_code) return false;
|
||||
if (filterMode === 'unmapped' && mappedCodes.has(field.field_code)) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 收集全部已绑定 field_id,含 split_rules 中 mapped 目标字段。
|
||||
*/
|
||||
export function collectBoundXfaFieldIds(definition: OrderXfaDatasetProfileDefinition): Set<string> {
|
||||
const ids = new Set<string>();
|
||||
for (const item of [...(definition.header_mappings || []), ...(definition.line_mapping?.fields || [])]) {
|
||||
if (item.field_id) ids.add(item.field_id);
|
||||
}
|
||||
for (const ruleSet of definition.split_rules || []) {
|
||||
for (const rule of ruleSet.rules || []) {
|
||||
if (rule.segment.handling === 'mapped' && rule.segment.target_field_id) {
|
||||
ids.add(rule.segment.target_field_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找 path_id 对应的映射项。
|
||||
*/
|
||||
export function findXfaMappingByPathId(
|
||||
definition: OrderXfaDatasetProfileDefinition,
|
||||
pathId: string,
|
||||
): XfaFieldMapping | null {
|
||||
const all = [...(definition.header_mappings || []), ...(definition.line_mapping?.fields || [])];
|
||||
return all.find((item) => item.path_id === pathId) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找 field_id 对应的映射项。
|
||||
*/
|
||||
export function findXfaMappingByFieldId(
|
||||
definition: OrderXfaDatasetProfileDefinition,
|
||||
fieldId: string,
|
||||
): XfaFieldMapping | null {
|
||||
const all = [...(definition.header_mappings || []), ...(definition.line_mapping?.fields || [])];
|
||||
return all.find((item) => item.field_id === fieldId) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算 XFA 模板映射的重复绑定与权威集合状态。
|
||||
* @param schemaFields 已启用 Schema 字段
|
||||
* @param definition 当前 XFA definition
|
||||
* @param authoritativePathId 权威集合 path_id(UI 态)
|
||||
*/
|
||||
export function computeXfaMappingCoverage(
|
||||
schemaFields: ShippingOrderFieldConfig[],
|
||||
definition: OrderXfaDatasetProfileDefinition | null | undefined,
|
||||
authoritativePathId = '',
|
||||
): XfaMappingCoverageSummary {
|
||||
const headers = definition?.header_mappings || [];
|
||||
const lines = definition?.line_mapping?.fields || [];
|
||||
const bound = new Map<string, string>();
|
||||
const duplicateFieldIds: string[] = [];
|
||||
for (const item of [...headers, ...lines]) {
|
||||
const key = String(item.field_id || '');
|
||||
if (!key) continue;
|
||||
if (bound.has(key)) duplicateFieldIds.push(key);
|
||||
else bound.set(key, item.field_code);
|
||||
}
|
||||
void schemaFields;
|
||||
const authPath = String(definition?.source_contract?.authoritative_line_collection_path || '').trim();
|
||||
return {
|
||||
requiredTotal: 0,
|
||||
requiredMapped: 0,
|
||||
missingRequired: [],
|
||||
duplicateFieldIds: [...new Set(duplicateFieldIds)],
|
||||
authoritativeMissing: !authoritativePathId && !authPath,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断集合是否可作为镜像(与权威不同)。
|
||||
* @param candidates 集合候选
|
||||
* @param authoritativePathId 权威 path_id
|
||||
*/
|
||||
export function listMirrorCollectionCandidates(
|
||||
candidates: XfaCollectionCandidate[],
|
||||
authoritativePathId: string,
|
||||
): XfaCollectionCandidate[] {
|
||||
return candidates.filter((item) => item.path_id && item.path_id !== authoritativePathId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定 Schema 字段到选中 path_id,返回新的 definition(不可变)。
|
||||
* 核心逻辑:同 field_id 覆盖;拒绝跨 scope;保留既有 mapping_id。
|
||||
*/
|
||||
export function bindXfaSchemaField(options: {
|
||||
definition: OrderXfaDatasetProfileDefinition;
|
||||
scope: 'header' | 'line';
|
||||
field: ShippingOrderFieldConfig;
|
||||
pathId: string;
|
||||
}): OrderXfaDatasetProfileDefinition {
|
||||
const { definition, scope, field, pathId } = options;
|
||||
if (field.scope !== scope) {
|
||||
throw new Error('scope_mismatch');
|
||||
}
|
||||
const existing = findXfaMappingByFieldId(definition, field.field_id);
|
||||
const mapping: XfaFieldMapping = {
|
||||
mapping_id: existing?.mapping_id || `map-${field.field_id}-${pathId}`.slice(0, 64),
|
||||
field_id: field.field_id,
|
||||
field_code: field.field_code || '',
|
||||
data_path: '',
|
||||
path_id: pathId,
|
||||
value_type: field.value_type || 'string',
|
||||
normalizer_key: field.normalizer_key ?? null,
|
||||
validator_key: field.validator_keys?.[0] ?? null,
|
||||
};
|
||||
if (scope === 'header') {
|
||||
const others = (definition.header_mappings || []).filter((item) => item.field_id !== field.field_id);
|
||||
return { ...definition, header_mappings: [...others, mapping] };
|
||||
}
|
||||
const others = (definition.line_mapping?.fields || []).filter((item) => item.field_id !== field.field_id);
|
||||
return {
|
||||
...definition,
|
||||
line_mapping: {
|
||||
row_path: definition.line_mapping?.row_path || definition.source_contract.authoritative_line_collection_path,
|
||||
fields: [...others, mapping],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 解除 Schema 字段映射。
|
||||
*/
|
||||
export function unbindXfaSchemaField(
|
||||
definition: OrderXfaDatasetProfileDefinition,
|
||||
fieldId: string,
|
||||
): OrderXfaDatasetProfileDefinition {
|
||||
return {
|
||||
...definition,
|
||||
header_mappings: (definition.header_mappings || []).filter((item) => item.field_id !== fieldId),
|
||||
line_mapping: {
|
||||
row_path: definition.line_mapping?.row_path || definition.source_contract.authoritative_line_collection_path,
|
||||
fields: (definition.line_mapping?.fields || []).filter((item) => item.field_id !== fieldId),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装保存请求 definition:附带 path_id 集合选择,data_path 由服务端重写。
|
||||
* @param state 工作台当前状态
|
||||
*/
|
||||
export function buildXfaSaveDefinitionPayload(state: XfaMappingWorkbenchState): Record<string, unknown> {
|
||||
const { definition, authoritativeCollectionPathId, mirrorCollectionPathIds } = state;
|
||||
return {
|
||||
...definition,
|
||||
template_mode: 'xfa_dataset',
|
||||
authoritative_collection_path_id: authoritativeCollectionPathId,
|
||||
mirror_collection_path_ids: mirrorCollectionPathIds,
|
||||
header_mappings: (definition.header_mappings || []).map((item) => ({
|
||||
mapping_id: item.mapping_id,
|
||||
field_id: item.field_id,
|
||||
field_code: item.field_code,
|
||||
path_id: item.path_id,
|
||||
value_type: item.value_type,
|
||||
normalizer_key: item.normalizer_key,
|
||||
validator_key: item.validator_key,
|
||||
})),
|
||||
line_mapping: {
|
||||
fields: (definition.line_mapping?.fields || []).map((item) => ({
|
||||
mapping_id: item.mapping_id,
|
||||
field_id: item.field_id,
|
||||
field_code: item.field_code,
|
||||
path_id: item.path_id,
|
||||
value_type: item.value_type,
|
||||
normalizer_key: item.normalizer_key,
|
||||
validator_key: item.validator_key,
|
||||
})),
|
||||
},
|
||||
split_rules: definition.split_rules || [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地校验摘要:权威集合、重复绑定、必填缺口。
|
||||
*/
|
||||
export function summarizeXfaMappingBlockers(coverage: XfaMappingCoverageSummary): string[] {
|
||||
const blockers: string[] = [];
|
||||
if (coverage.authoritativeMissing) blockers.push('authoritative_collection_required');
|
||||
if (coverage.duplicateFieldIds.length) blockers.push('duplicate_field_binding');
|
||||
return blockers;
|
||||
}
|
||||
|
||||
/**
|
||||
* 截断 checksum 供页眉展示。
|
||||
*/
|
||||
export function shortenXfaChecksum(value: string | null | undefined, length = 4): string {
|
||||
const text = String(value || '').replace(/^sha256:/i, '');
|
||||
if (!text) return '—';
|
||||
return text.length <= length * 2 ? text : `${text.slice(0, length)}…`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断工作台状态是否与已保存快照不同(脏状态检测)。
|
||||
*/
|
||||
export function isXfaMappingDirty(
|
||||
saved: XfaMappingWorkbenchState | null | undefined,
|
||||
current: XfaMappingWorkbenchState,
|
||||
): boolean {
|
||||
if (!saved) return true;
|
||||
return JSON.stringify(buildXfaSaveDefinitionPayload(saved))
|
||||
!== JSON.stringify(buildXfaSaveDefinitionPayload(current));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断两个 definition 是否语义相等(兼容旧调用)。
|
||||
*/
|
||||
export function isSameXfaDefinition(
|
||||
left: OrderXfaDatasetProfileDefinition | null | undefined,
|
||||
right: OrderXfaDatasetProfileDefinition | null | undefined,
|
||||
): boolean {
|
||||
return JSON.stringify(left || null) === JSON.stringify(right || null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算与后端 `hash_data_path` 一致的路径哈希(`sha256:<hex>`)。
|
||||
* 核心逻辑:对已 trim 的绝对路径做 UTF-8 SHA-256;用于从已保存明文路径反查 path_id。
|
||||
* @param path 受控 data_path(如 `/data/ITEMS/DATA`)
|
||||
*/
|
||||
export async function hashXfaDataPath(path: string): Promise<string> {
|
||||
const text = String(path || '').trim();
|
||||
if (!text.startsWith('/')) {
|
||||
throw new Error('invalid_xfa_data_path');
|
||||
}
|
||||
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
|
||||
const hex = [...new Uint8Array(digest)]
|
||||
.map((byte) => byte.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
return `sha256:${hex}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从已保存 definition 与集合候选反查权威集合 path_id。
|
||||
* 核心逻辑:优先用权威明文路径哈希精确匹配 collection_path_hash / 树节点 dataPathHash;
|
||||
* 再回退 line 映射祖先集合;最后才用唯一候选。
|
||||
*/
|
||||
export async function resolveAuthoritativePathId(
|
||||
definition: OrderXfaDatasetProfileDefinition,
|
||||
candidates: XfaCollectionCandidate[],
|
||||
flatNodes: XfaFlatTreeNode[],
|
||||
): Promise<string> {
|
||||
const authPath = String(definition.source_contract?.authoritative_line_collection_path || '').trim();
|
||||
if (authPath) {
|
||||
try {
|
||||
const wanted = await hashXfaDataPath(authPath);
|
||||
const byCandidate = candidates.find((item) => item.collection_path_hash === wanted && item.path_id);
|
||||
if (byCandidate?.path_id) return byCandidate.path_id;
|
||||
const byTree = flatNodes.find(
|
||||
(item) => item.isCollectionCandidate && item.dataPathHash === wanted && item.pathId,
|
||||
);
|
||||
if (byTree?.pathId) return byTree.pathId;
|
||||
} catch {
|
||||
// 非法路径时继续走启发式回退。
|
||||
}
|
||||
}
|
||||
|
||||
const linePathId = (definition.line_mapping?.fields || [])[0]?.path_id;
|
||||
if (linePathId) {
|
||||
let current = flatNodes.find((item) => item.pathId === linePathId);
|
||||
while (current) {
|
||||
if (current.isCollectionCandidate) return current.pathId;
|
||||
current = current.parentPathId
|
||||
? flatNodes.find((item) => item.pathId === current?.parentPathId)
|
||||
: undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const collectionNodes = flatNodes.filter((item) => item.isCollectionCandidate);
|
||||
if (collectionNodes.length === 1 && collectionNodes[0]?.pathId) {
|
||||
return collectionNodes[0].pathId;
|
||||
}
|
||||
if (candidates.length === 1 && candidates[0]?.path_id) {
|
||||
return candidates[0].path_id;
|
||||
}
|
||||
const preferred = collectionNodes.find((item) => item.localName.toUpperCase() === 'DATA');
|
||||
return preferred?.pathId || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 从已保存镜像明文路径精确恢复镜像集合 path_id 列表。
|
||||
* 核心逻辑:逐条 hash 匹配;排除权威;不按“前 N 个候选”猜测。
|
||||
*/
|
||||
export async function resolveMirrorPathIds(
|
||||
definition: OrderXfaDatasetProfileDefinition,
|
||||
candidates: XfaCollectionCandidate[],
|
||||
authoritativePathId: string,
|
||||
): Promise<string[]> {
|
||||
const mirrors = (definition.source_contract?.mirror_collection_paths || [])
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean);
|
||||
if (!mirrors.length) return [];
|
||||
const resolved: string[] = [];
|
||||
for (const path of mirrors) {
|
||||
try {
|
||||
const wanted = await hashXfaDataPath(path);
|
||||
const hit = candidates.find(
|
||||
(item) => item.collection_path_hash === wanted
|
||||
&& item.path_id
|
||||
&& item.path_id !== authoritativePathId,
|
||||
);
|
||||
if (hit?.path_id && !resolved.includes(hit.path_id)) {
|
||||
resolved.push(hit.path_id);
|
||||
}
|
||||
} catch {
|
||||
// skip invalid mirror path
|
||||
}
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
Reference in new issue
Block a user