!11 feat(shipping-notice): 实现滚动履约功能,优化发货通知流程与代码清理

Merge pull request !11 from 曹惠鹏/hugo-shipping-notice
This commit is contained in:
sophie authored and Gitee committed 2026-08-26 00:25:10 +00:00
commit 2ff9fdafe4
402 files changed
+23045 -20484

No files matched your search

@@ -1,420 +0,0 @@
<!--
features/admin/modules/shipping-legacy-stp-jobs/ShippingLegacyStpJobsPage.vue
用途:Phase 5-1 —— 管理员「历史 STP Job(928/929 回放)」运维面板。
依赖:shipping-legacy-stp-jobs.api、Vue Router、Vue I18n、workspace.shippingNotice.actions 键。
逻辑:
[STEP 1] 左侧 ~38%:分页列表(筛选 q/case_no/error_code/blocking_reason/status/created_from/to)
按创建时间倒序;
[STEP 2] 右侧 sticky:详情 —— Job 摘要、回链 Review Case(case 非空时跳转工作台 Case 详情)、
replay_plan(推荐 user_action)、
「一键回放 Reconcile And Progress」按钮直接走
POST /api/workspace/shipping-notice/order-review-cases/<case_no>/reconcile-and-progress
带 legacy_job_id + replay_mode。
全部只读 + 一个写操作(回放按钮),写操作必须管理员;非管理员会被后端 422。
-->
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import {
DEFAULT_LEGACY_STP_JOB_FILTERS,
LEGACY_STP_JOB_STATUS_OPTIONS,
getAdminLegacyStpJob,
listAdminLegacyStpJobs,
type LegacyStpJobDetailPayload,
type LegacyStpJobListFilters,
type LegacyStpJobRow,
} from '@/features/admin/api/shipping-legacy-stp-jobs.api';
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import { useMessage } from '@/shared/composables/useMessage';
const { t, te } = useI18n();
const router = useRouter();
const message = useMessage();
const loading = ref(false);
const detailLoading = ref(false);
const replaying = ref(false);
const error = ref('');
const page = ref(1);
const pageSize = ref(25);
const total = ref(0);
const filters = ref<LegacyStpJobListFilters>({ ...DEFAULT_LEGACY_STP_JOB_FILTERS });
const rows = ref<LegacyStpJobRow[]>([]);
const selectedJobId = ref<number | null>(null);
const detail = ref<LegacyStpJobDetailPayload | null>(null);
const replayUserAction = ref<'auto' | 'reuse_existing' | 'create_revision' | 'force_create' | 'adjudicate'>('create_revision');
const replayLastResult = ref<{ ok: boolean; outcome?: string | null; message?: string | null } | null>(null);
const formatTime = (value?: string | null) => (value ? new Date(value).toLocaleString() : '—');
function jsonFormat(value: unknown): string {
if (value == null) return '—';
try { return JSON.stringify(value, null, 2); } catch { return String(value); }
}
type CodeLabelNs = 'admin.legacyStpJobs.statusLabels' | 'admin.legacyStpJobs.reasonCodes' | 'workspace.shippingNotice.processGate.actionCodes';
function codeLabel(code?: string | null, ns: CodeLabelNs = 'admin.legacyStpJobs.statusLabels'): string {
const key = String(code || '').trim();
if (!key) return '—';
const i18nKey = `${ns}.${key}`;
return te(i18nKey) ? t(i18nKey) : key;
}
function actionLabel(code?: string | null): string { return codeLabel(code, 'workspace.shippingNotice.processGate.actionCodes'); }
function resetFilters() {
filters.value = { ...DEFAULT_LEGACY_STP_JOB_FILTERS };
page.value = 1;
selectedJobId.value = null;
detail.value = null;
}
async function loadList() {
loading.value = true;
error.value = '';
try {
const payload = await listAdminLegacyStpJobs(page.value, pageSize.value, filters.value);
const items = (payload as any).items ?? [];
rows.value = Array.isArray(items) ? items : [];
total.value = Number((payload as any).pagination?.total ?? 0);
} catch (exc: any) {
error.value = exc?.message || String(exc);
rows.value = [];
total.value = 0;
} finally {
loading.value = false;
}
}
async function loadDetail(jobId: number) {
detailLoading.value = true;
detail.value = null;
replayLastResult.value = null;
replayUserAction.value = 'create_revision';
try {
detail.value = await getAdminLegacyStpJob(jobId);
const plan = detail.value.replay_plan;
if (plan?.recommended_user_action === 'force_create') {
replayUserAction.value = 'force_create';
} else if (plan?.recommended_user_action === 'create_revision') {
replayUserAction.value = 'create_revision';
}
} catch (exc: any) {
message.error(exc?.message || String(exc));
} finally {
detailLoading.value = false;
}
}
function onRowClick(row: LegacyStpJobRow) {
selectedJobId.value = Number(row.job_id);
loadDetail(Number(row.job_id)).catch(() => {});
}
function openCaseInWorkspace(caseNo: string) {
router.push({
name: 'WorkspaceShippingNotice',
query: { case_no: caseNo, focus: 'review_case' },
});
}
/**
* 【回放按钮】严格只走 /workspace/shipping-notice/order-review-cases/<case_no>/reconcile-and-progress,
* 携带 operation_id / legacy_job_id / replay_mode / user_action 四参数。
* 禁止任何绕过该 API 的直接 SQL/Job.status 修改。
*/
async function replaySelected() {
if (!detail.value || !detail.value.job.case_no) {
message.error(t('admin.legacyStpJobs.replayError_noCaseNo'));
return;
}
const caseNo = String(detail.value.job.case_no).trim();
const legacyJobId = Number(detail.value.job.job_id);
const replayMode = Boolean(detail.value.replay_plan?.needs_replay_mode);
const action = replayUserAction.value;
const operationId = crypto.randomUUID
? crypto.randomUUID()
: String(Date.now()) + '-' + Math.random().toString(36).slice(2);
const url = `/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/reconcile-and-progress`;
const headers = { 'Content-Type': 'application/json', ...getAuthHeaders() };
const body = JSON.stringify({
operation_id: operationId,
user_action: action,
legacy_job_id: legacyJobId,
replay_mode: replayMode || action === 'force_create',
});
replaying.value = true;
replayLastResult.value = null;
try {
const resp = await requestJson<any>(url, { method: 'POST', headers, body });
const outcome = (resp as any)?.data?.outcome ?? null;
const ok = !!(resp as any)?.success && String(outcome || '') !== 'ERROR';
replayLastResult.value = {
ok,
outcome: outcome,
message: (resp as any)?.data?.message ?? null,
};
if (ok) {
message.success(t('admin.legacyStpJobs.replaySuccess', { outcome: String(outcome || '') }));
} else {
message.error(t('admin.legacyStpJobs.replayRejected', { outcome: String(outcome || '') }));
}
} catch (exc: any) {
const err = exc?.message || String(exc);
replayLastResult.value = { ok: false, outcome: 'ERROR', message: err };
message.error(err);
} finally {
replaying.value = false;
}
}
onMounted(loadList);
watch([page, pageSize], loadList);
</script>
<template>
<div class="flex flex-col h-full gap-4 lg:gap-6 p-4 lg:p-6">
<div class="flex items-center justify-between flex-wrap gap-3">
<div>
<h2 class="text-xl font-semibold">{{ t('admin.legacyStpJobs.pageTitle') }}</h2>
<p class="text-sm text-gray-600">{{ t('admin.legacyStpJobs.pageSubtitle') }}</p>
</div>
<div class="flex items-center gap-2">
<button
class="px-3 py-1.5 text-sm rounded border border-gray-300 hover:bg-gray-50"
type="button"
@click="resetFilters"
>
{{ t('common.reset') }}
</button>
<button
class="px-3 py-1.5 text-sm rounded bg-indigo-600 text-white hover:bg-indigo-700"
type="button"
@click="loadList"
:disabled="loading"
>
{{ t('common.refresh') }}
</button>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-5 gap-3">
<input
v-model="filters.q"
class="px-3 py-2 border rounded text-sm"
:placeholder="t('admin.legacyStpJobs.filterQ')"
@keyup.enter="page = 1, loadList()"
/>
<input
v-model="filters.case_no"
class="px-3 py-2 border rounded text-sm"
:placeholder="t('admin.legacyStpJobs.filterCaseNo')"
@keyup.enter="page = 1, loadList()"
/>
<input
v-model="filters.error_code"
class="px-3 py-2 border rounded text-sm"
:placeholder="t('admin.legacyStpJobs.filterErrorCode')"
@keyup.enter="page = 1, loadList()"
/>
<select
v-model="filters.status"
class="px-3 py-2 border rounded text-sm"
@change="page = 1, loadList()"
>
<option value="">{{ t('admin.legacyStpJobs.statusAll') }}</option>
<option v-for="s in LEGACY_STP_JOB_STATUS_OPTIONS" :key="s" :value="s">{{ codeLabel(s) }}</option>
</select>
<input
v-model="filters.created_from"
type="datetime-local"
class="px-3 py-2 border rounded text-sm"
@change="page = 1, loadList()"
/>
</div>
<div class="grid grid-cols-1 lg:grid-cols-[minmax(0,38%)_1fr] gap-4 lg:gap-6 min-h-0 flex-1">
<!-- 左侧列表 -->
<section class="flex flex-col min-h-0 border rounded bg-white/60">
<div class="flex items-center justify-between px-4 py-2 border-b">
<span class="text-sm font-medium">{{ t('admin.legacyStpJobs.listTitle', { count: total }) }}</span>
<span v-if="loading" class="text-xs text-gray-500">{{ t('common.loading') }}</span>
</div>
<div v-if="error" class="p-3 text-sm text-red-700 bg-red-50 border-b">{{ error }}</div>
<div class="overflow-auto min-h-0 max-h-[72vh] divide-y">
<div
v-for="row in rows"
:key="row.job_id"
class="px-4 py-3 cursor-pointer hover:bg-indigo-50/60"
:class="selectedJobId === row.job_id ? 'bg-indigo-50 ring-2 ring-inset ring-indigo-300' : ''"
@click="onRowClick(row)"
>
<div class="flex items-center justify-between gap-3">
<div class="min-w-0">
<div class="flex items-center gap-2 text-sm">
<span class="font-mono text-xs bg-gray-100 px-2 py-0.5 rounded">#{{ row.job_id }}</span>
<span
class="text-xs px-2 py-0.5 rounded"
:class="row.status === 'failed' ? 'bg-red-100 text-red-700' : 'bg-gray-200 text-gray-700'"
>{{ codeLabel(row.status) }}</span>
<span class="truncate text-xs text-gray-500">{{ row.case_no || row.business_ref || '—' }}</span>
</div>
<div class="mt-1.5 text-sm">
<span class="text-gray-700">{{ codeLabel(row.blocking_reason || row.error_code || '', 'admin.legacyStpJobs.reasonCodes') }}</span>
<span class="mx-2 text-gray-300">·</span>
<span class="text-xs text-gray-500">{{ row.attempts }}/{{ row.max_attempts }}</span>
</div>
</div>
<div class="text-right text-xs text-gray-500 leading-5 shrink-0">
<div>{{ formatTime(row.created_at) }}</div>
<div v-if="row.finished_at">→ {{ formatTime(row.finished_at) }}</div>
</div>
</div>
</div>
<div v-if="!rows.length && !loading" class="p-8 text-center text-sm text-gray-500">
{{ t('admin.legacyStpJobs.empty') }}
</div>
</div>
<div class="flex items-center justify-between px-4 py-2 border-t text-sm">
<span class="text-gray-500">{{ t('common.pageOf', { page, total: Math.max(1, Math.ceil(total / pageSize)) }) }}</span>
<div class="flex items-center gap-1">
<button
class="px-2 py-1 rounded border disabled:opacity-50"
:disabled="page <= 1"
type="button"
@click="page -= 1"
>{{ t('common.prev') }}</button>
<button
class="px-2 py-1 rounded border disabled:opacity-50"
:disabled="page * pageSize >= total"
type="button"
@click="page += 1"
>{{ t('common.next') }}</button>
</div>
</div>
</section>
<!-- 右侧详情 -->
<section class="flex flex-col min-h-0 border rounded bg-white/60">
<div class="flex items-center justify-between px-4 py-2 border-b">
<span class="text-sm font-medium">{{ t('admin.legacyStpJobs.detailTitle') }}</span>
<span v-if="detailLoading" class="text-xs text-gray-500">{{ t('common.loading') }}</span>
</div>
<div v-if="!detail && !detailLoading" class="p-8 text-center text-sm text-gray-500">
{{ t('admin.legacyStpJobs.detailEmpty') }}
</div>
<div v-else-if="detail" class="overflow-auto min-h-0 max-h-[72vh] px-5 py-4 space-y-5">
<!-- 摘要行 -->
<div class="grid grid-cols-1 md:grid-cols-3 gap-3 text-sm">
<div class="border rounded p-3">
<div class="text-xs text-gray-500 mb-1">{{ t('admin.legacyStpJobs.job') }}</div>
<div class="font-mono">#{{ detail.job.job_id }} · {{ codeLabel(detail.job.status) }}</div>
<div class="mt-1 text-xs text-gray-500">attempts: {{ detail.job.attempts }}/{{ detail.job.max_attempts }}</div>
</div>
<div class="border rounded p-3">
<div class="text-xs text-gray-500 mb-1">{{ t('admin.legacyStpJobs.reviewCase') }}</div>
<button
v-if="detail.job.case_no"
class="text-indigo-600 hover:underline font-mono"
type="button"
@click="openCaseInWorkspace(detail.job.case_no!)"
>{{ detail.job.case_no }}</button>
<span v-else class="text-gray-400">—</span>
<div class="mt-1 text-xs text-gray-500 truncate">{{ detail.job.business_ref || '—' }}</div>
</div>
<div class="border rounded p-3">
<div class="text-xs text-gray-500 mb-1">{{ t('admin.legacyStpJobs.blocking') }}</div>
<div class="font-medium">{{ codeLabel(detail.job.blocking_reason || detail.job.error_code || '', 'admin.legacyStpJobs.reasonCodes') }}</div>
<div class="mt-1 text-xs text-gray-500 truncate">{{ detail.job.message || detail.job.error_message || '—' }}</div>
</div>
</div>
<!-- 回链 Case:若存在则展示 8 字段 -->
<div v-if="detail.case" class="border rounded p-4">
<div class="text-sm font-medium mb-2">{{ t('admin.legacyStpJobs.linkedCase') }}</div>
<dl class="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
<div><dt class="text-xs text-gray-500">case_id</dt><dd class="font-mono">{{ detail.case.case_id }}</dd></div>
<div><dt class="text-xs text-gray-500">{{ t('admin.legacyStpJobs.caseStatus') }}</dt><dd>{{ detail.case.status }}</dd></div>
<div><dt class="text-xs text-gray-500">candidate_id</dt><dd class="font-mono">{{ detail.case.candidate_id ?? '—' }}</dd></div>
<div><dt class="text-xs text-gray-500">confirmed_task_id</dt><dd class="font-mono">{{ detail.case.confirmed_task_id ?? '—' }}</dd></div>
<div><dt class="text-xs text-gray-500">document_id</dt><dd class="font-mono">{{ detail.case.document_id ?? '—' }}</dd></div>
<div><dt class="text-xs text-gray-500">owner_user_id</dt><dd class="font-mono">{{ detail.case.owner_user_id ?? '—' }}</dd></div>
<div><dt class="text-xs text-gray-500">{{ t('common.createdAt') }}</dt><dd>{{ formatTime(detail.case.created_at) }}</dd></div>
<div><dt class="text-xs text-gray-500">{{ t('common.updatedAt') }}</dt><dd>{{ formatTime(detail.case.updated_at) }}</dd></div>
</dl>
</div>
<!-- 回放计划:推荐动作 + 回放按钮 -->
<div class="border rounded p-4 bg-amber-50/60">
<div class="text-sm font-medium mb-2">{{ t('admin.legacyStpJobs.replayPlan') }}</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 items-center">
<div class="text-sm space-y-1">
<div>
<span class="text-gray-500 mr-2">{{ t('admin.legacyStpJobs.recommendedAction') }}:</span>
<span class="px-2 py-0.5 rounded bg-white border text-sm">
{{ actionLabel(detail.replay_plan.recommended_user_action) }}
</span>
</div>
<div>
<span class="text-gray-500 mr-2">{{ t('admin.legacyStpJobs.needsReplayMode') }}:</span>
<span :class="detail.replay_plan.needs_replay_mode ? 'text-amber-700 font-medium' : 'text-gray-500'">
{{ detail.replay_plan.needs_replay_mode ? t('common.yes') : t('common.no') }}
</span>
</div>
<div v-if="detail.replay_plan.reconcile_and_progress_endpoint" class="font-mono text-xs text-gray-500 break-all">
POST {{ detail.replay_plan.reconcile_and_progress_endpoint }}
</div>
</div>
<div class="flex flex-col gap-2 md:items-end">
<label class="flex items-center gap-2 text-sm md:justify-end">
<span class="text-gray-600 w-32">{{ t('admin.legacyStpJobs.userAction') }}</span>
<select v-model="replayUserAction" class="px-3 py-1.5 border rounded text-sm">
<option value="auto">{{ actionLabel('auto') }}</option>
<option value="reuse_existing">{{ actionLabel('reuse_existing') }}</option>
<option value="create_revision">{{ actionLabel('create_revision') }}</option>
<option value="force_create">{{ actionLabel('force_create') }}</option>
<option value="adjudicate">{{ actionLabel('adjudicate') }}</option>
</select>
</label>
<button
class="px-4 py-2 rounded bg-indigo-600 text-white hover:bg-indigo-700 disabled:opacity-60 max-w-xs"
type="button"
:disabled="replaying || !detail.job.case_no"
@click="replaySelected"
>
{{ replaying ? t('common.loading') : t('admin.legacyStpJobs.replayButton') }}
</button>
</div>
</div>
<div v-if="replayLastResult" class="mt-3 text-sm border-t pt-3">
<div class="flex items-center gap-2">
<span
class="text-xs px-2 py-0.5 rounded"
:class="replayLastResult.ok ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'"
>
{{ replayLastResult.ok ? t('common.ok') : t('common.error') }}
</span>
<span class="font-mono text-xs bg-white border rounded px-2 py-0.5">{{ replayLastResult.outcome ?? '—' }}</span>
</div>
<div v-if="replayLastResult.message" class="mt-1.5 text-xs text-gray-600 whitespace-pre-wrap break-all">
{{ replayLastResult.message }}
</div>
</div>
</div>
<!-- 原始 JSON:payload / result(masked) -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="border rounded p-3">
<div class="text-xs text-gray-500 mb-1">{{ t('admin.legacyStpJobs.payloadJson') }}</div>
<pre class="text-xs whitespace-pre-wrap break-all bg-gray-50 p-2 rounded max-h-64 overflow-auto">{{ jsonFormat(detail.job.payload_json_masked) }}</pre>
</div>
<div class="border rounded p-3">
<div class="text-xs text-gray-500 mb-1">{{ t('admin.legacyStpJobs.resultJson') }}</div>
<pre class="text-xs whitespace-pre-wrap break-all bg-gray-50 p-2 rounded max-h-64 overflow-auto">{{ jsonFormat(detail.job.result_json_masked) }}</pre>
</div>
</div>
</div>
</section>
</div>
</div>
</template>
@@ -178,7 +178,8 @@ function stopUploadPolling(): void {
async function pollUploadedSample(intakeNo: string): Promise<void> {
try {
const result = await getOrderProfileSampleStatus(intakeNo);
if (result.parse_status === 'parsed' && result.document_count > 0) {
// 与样本列表的可见条件一致:文档物化且 Layout ready 后才进入候选列表。
if (result.parse_status === 'parsed' && result.document_count > 0 && result.layout_status === 'ready') {
await loadAvailableSamples(true);
const selected = availableSamples.value.find((item) => (result.document_ids || []).includes(item.document_id));
if (selected) {
@@ -192,7 +193,7 @@ async function pollUploadedSample(intakeNo: string): Promise<void> {
}
return;
}
if (['failed', 'error'].includes(result.parse_status)) {
if (['failed', 'error'].includes(result.parse_status) || result.layout_status === 'failed') {
await loadAvailableSamples(true);
const selected = availableSamples.value.find((item) => (result.document_ids || []).includes(item.document_id));
if (selected) {
@@ -6,13 +6,66 @@
*/
import { describe, expect, it, vi } from 'vitest';
import {
filterRegionsAfterRemoval,
resolveSelectedOrderAnchorId,
resolveCanvasActions,
resolveDeskAdapter,
resolveMainTableIdForPageChange,
resolveSharedCanvasDocument,
resolveValueAdapterKey,
shouldKeepUnreadableOrderField,
type OrderProfileCanvasActions,
} from './canvasActions.utils';
describe('filterRegionsAfterRemoval', () => {
it('deletes only the selected ordinary top-level region', () => {
const regions = [
{ id: 'green-1', kind: 'header_field', label: 'A', region: { x0: 0, y0: 0, x1: .1, y1: .1 }, pageNo: 1 },
{ id: 'green-2', kind: 'header_field', label: 'B', region: { x0: 0, y0: .2, x1: .1, y1: .3 }, pageNo: 1 },
] as any;
expect(filterRegionsAfterRemoval(regions, 'green-1')).toEqual([regions[1]]);
});
it('keeps ordinary top-level regions while deleting a document-anchor family', () => {
const regions = [
{ id: 'green-1', kind: 'header_field', label: 'A', region: { x0: 0, y0: 0, x1: .1, y1: .1 }, pageNo: 1 },
{ id: 'anchor-label', kind: 'document_anchor_label', label: 'Label', parentId: 'anchor-1', region: { x0: 0, y0: .2, x1: .1, y1: .3 }, pageNo: 1 },
{ id: 'anchor-value', kind: 'document_anchor_value', label: 'Value', parentId: 'anchor-1', region: { x0: 0, y0: .3, x1: .1, y1: .4 }, pageNo: 1 },
] as any;
expect(filterRegionsAfterRemoval(regions, 'anchor-label', 'anchor-1').map((item) => item.id)).toEqual(['green-1']);
});
});
describe('resolveSelectedOrderAnchorId', () => {
it('only returns an explicitly selected order anchor', () => {
const selectedAnchor = {
id: 'ship_to_anchor', kind: 'order_anchor', label: 'Ship to',
region: { x0: 0, y0: 0, x1: .1, y1: .1 }, pageNo: 1,
} as any;
const selectedValue = {
id: 'ship_to_value', kind: 'order_field', parentId: 'ship_to_anchor',
label: 'Example', region: { x0: 0, y0: .1, x1: .1, y1: .2 }, pageNo: 1,
} as any;
expect(resolveSelectedOrderAnchorId(selectedAnchor)).toBe('ship_to_anchor');
expect(resolveSelectedOrderAnchorId(selectedValue)).toBeNull();
expect(resolveSelectedOrderAnchorId(null)).toBeNull();
});
});
describe('shouldKeepUnreadableOrderField', () => {
it('keeps an XFA value box when visual readback remains unavailable', () => {
// OCR/Widget 回读失败必须可诊断,但不能让管理员已框选的 XFA 值框消失。
expect(shouldKeepUnreadableOrderField('xfa_dataset', 'order_field', false)).toBe(true);
});
it('keeps the ordinary-PDF empty-value guard unchanged', () => {
expect(shouldKeepUnreadableOrderField('coordinate_ocr', 'order_field', false)).toBe(false);
});
});
function actions(): OrderProfileCanvasActions {
return {
create: vi.fn(), select: vi.fn(), dragStart: vi.fn(), dragEnd: vi.fn(), change: vi.fn(),
@@ -98,3 +151,12 @@ describe('resolveCanvasActions', () => {
expect(resolveValueAdapterKey({ template_mode: 'coordinate' } as any)).toBe('coordinate_ocr');
});
});
describe('resolveMainTableIdForPageChange', () => {
it('keeps the frozen main table when PDF navigation selects another table on the same page', () => {
expect(resolveMainTableIdForPageChange({
frozenMainTableId: 'order-lines-table',
pagePreviewTableId: 'total-amount-table',
})).toBe('order-lines-table');
});
});
@@ -24,6 +24,58 @@ export interface OrderProfileCanvasActions {
draw(kind: OrderProfileCanvasRegion['kind']): void;
}
/**
* 计算删除画布区域后的区域集合。
* 普通区域只删除自身及其直接子区域;文档锚点仅在明确传入锚点 ID 时级联删除。
*/
export function filterRegionsAfterRemoval(
regions: OrderProfileCanvasRegion[],
removedId: string,
documentAnchorId: string | null = null,
): OrderProfileCanvasRegion[] {
return regions.filter((item) => (
item.id !== removedId
&& item.parentId !== removedId
&& (documentAnchorId === null || item.parentId !== documentAnchorId)
));
}
/**
* 返回当前明确选中的订单字段标签 ID。
* 核心逻辑:订单字段值框只能继承用户当前选中的标签,绝不回退到页面第一个标签。
* @param selectedRegion - 当前画布选区;非订单字段标签或未选中时返回 null。
* @returns 可作为订单字段父节点的标签 ID,或 null。
*/
export function resolveSelectedOrderAnchorId(
selectedRegion: Pick<OrderProfileCanvasRegion, 'id' | 'kind'> | null,
): string | null {
return selectedRegion?.kind === 'order_anchor' ? selectedRegion.id : null;
}
/**
* 保持模板主表身份与 PDF 页内预览表分离。
* 核心逻辑:翻页是画布导航,不能把同页第一张表(例如合计区)写回已冻结的主表身份。
*/
export function resolveMainTableIdForPageChange(options: {
frozenMainTableId: string;
pagePreviewTableId: string;
}): string {
return options.frozenMainTableId || options.pagePreviewTableId;
}
/**
* 判断 XFA 视觉回读为空时是否应保留用户刚圈选的值框。
* 核心逻辑:空回读是待诊断的视觉证据失败,不得吞掉管理员已经完成的 XFA 位置标注;
* 普通 PDF 仍维持原有的空文本拒绝规则。
*/
export function shouldKeepUnreadableOrderField(
adapterKey: string,
kind: OrderProfileCanvasRegion['kind'] | null,
hasVisualText: boolean,
): boolean {
return hasVisualText || (adapterKey === 'xfa_dataset' && kind === 'order_field');
}
/**
* 共享 Editor 消费的视觉画布状态。
*
@@ -35,6 +87,7 @@ export interface OrderProfileVisualCanvasAdapter {
actions: OrderProfileCanvasActions;
documentReady: boolean;
preview: { document_id: number; preview_token: string; expires_in_seconds: number } | null;
grant: { page_no: number; preview_token: string } | null;
previewPagePath: string;
regions: OrderProfileCanvasRegion[];
selectedRegionId: string | null;
@@ -130,7 +183,7 @@ export function resolveDeskAdapter<T>(options: {
/**
* 返回唯一由 Editor 消费的 PDF 画布文档上下文。
* 核心逻辑:所有 Profile 先使用共同冻结的 annotation document + main_table_id;
* 历史草稿缺失 main_table_id 时才回退样本 table_id。预览授权、页码和 PDF.js 渲染始终
* 历史草稿缺失 main_table_id 时才回退样本 table_id。预览授权、页码和 PDFium/PDF.js 渲染始终
* 由共享 Editor 持有,值源 adapter 不得参与上下文选择。
* @param options.documentId - 共同 annotation 文档身份。
* @param options.mainTableId - definition 中冻结的共同视觉主表。
@@ -82,4 +82,52 @@ describe('OrderProfileDocumentCanvas PDF preview', () => {
expect(wrapper.find('.canvas-stage').attributes('style')).toContain('width: 750px');
expect(wrapper.find('.region').attributes('style')).toContain('left: 50%');
});
it('uses the server-rendered PNG page for an ordinary PDF instead of PDF.js', async () => {
const wrapper = mount(OrderProfileDocumentCanvas, {
props: {
profileId: 71,
grant: { page_no: 1, preview_token: 'page-token' },
previewPagePath: '/api/admin/shipping-notice/order-document-profiles/71/preview-pages',
regions: [], pageNo: 1, pageCount: 1,
},
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] },
});
await flushPromises();
// 普通 PDF 底图由后端 PDFium 输出,避免前端 PDF.js 对特定繁体内嵌字体的渲染差异。
expect(getDocumentMock).not.toHaveBeenCalled();
expect(wrapper.find('img').exists()).toBe(true);
expect(fetch).toHaveBeenCalledWith(
'/api/admin/shipping-notice/order-document-profiles/71/preview-pages/1?preview_token=page-token',
expect.objectContaining({ cache: 'no-store' }),
);
});
it('captures the selected XFA appearance from the unscaled PDF.js canvas', async () => {
const drawImage = vi.fn();
const toDataURL = vi.fn(() => 'data:image/png;base64,canvas-crop');
const nativeCreateElement = document.createElement.bind(document);
vi.spyOn(document, 'createElement').mockImplementation((tagName: string) => {
const element = nativeCreateElement(tagName) as HTMLCanvasElement;
if (tagName === 'canvas') {
Object.defineProperty(element, 'getContext', { value: vi.fn(() => ({ drawImage })) });
Object.defineProperty(element, 'toDataURL', { value: toDataURL });
}
return element;
});
const wrapper = mount(OrderProfileDocumentCanvas, {
props: { profileId: 71, pdfPreview: { preview_token: 'single-use-token' }, regions: [], pageNo: 1, pageCount: 1 },
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] },
});
await flushPromises();
await flushPromises();
const source = wrapper.find('canvas.pdf-page').element as HTMLCanvasElement;
Object.defineProperties(source, { width: { value: 600 }, height: { value: 800 } });
expect((wrapper.vm as { captureRegion: (region: object) => string | null }).captureRegion({ x0: .1, y0: .2, x1: .4, y1: .5 }))
.toBe('data:image/png;base64,canvas-crop');
// 使用 PDF.js 原始像素而不是 CSS 缩放后的大小,保证回读与用户框选区域一致。
expect(drawImage).toHaveBeenCalledWith(source, 60, 160, 181, 240, 0, 0, 181, 240);
});
});
@@ -8,7 +8,7 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Anchor, ArrowLeft, ArrowRight, Columns3, Copy, Eraser, Minus, Plus, Redo2, RotateCcw, Rows3, Save, TableProperties, Tag, TextCursorInput, Trash2, WandSparkles } from 'lucide-vue-next';
import { Anchor, ArrowLeft, ArrowRight, Columns3, Copy, Eraser, MessageSquareText, Minus, Plus, Redo2, RotateCcw, Rows3, Save, TableProperties, Tag, TextCursorInput, Trash2, WandSparkles } from 'lucide-vue-next';
import { getAuthHeaders } from '@/shared/utils/auth';
import type { OrderProfileCanvasRegion, OrderProfilePreviewPageGrant } from '@/features/admin/types/shipping-order-document-profile.types';
import type { PDFDocumentProxy } from 'pdfjs-dist';
@@ -55,6 +55,8 @@ const props = defineProps<{
pendingSuggestionCount?: number;
orderFieldValues?: Record<string, string | null>;
orderFieldValueState?: 'idle' | 'loading' | 'ready' | 'failed';
/** 当前样本坐标重建的首条明细行值,按画布字段区域 ID 索引。 */
lineFieldValues?: Record<string, string | null>;
/** 无图时空态文案;缺省为「选择已绑定的 PDF 样本」。 */
emptyHint?: string | null;
/** 外部注入的页加载错误(如 XFA page_unavailable);优先于空态提示。 */
@@ -215,7 +217,7 @@ const move = (event: PointerEvent) => {
const beginDrag = (event: PointerEvent, region: OrderProfileCanvasRegion, mode: DragMode) => {
event.preventDefault();
emit('select', region.id);
if (readonlyMode.value) return;
if (readonlyMode.value || region.isPreview) return;
emit('start', region.id);
activeDrag = { id: region.id, mode, startX: event.clientX, startY: event.clientY, region: { ...region.region } };
window.addEventListener('pointermove', move);
@@ -275,6 +277,9 @@ const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
return `${region.label} · ${region.recognizedValue || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable')}`;
}
if (region.kind !== 'order_field') {
if (region.kind === 'field') {
return `${region.label} · ${props.lineFieldValues?.[region.id] || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable')}`;
}
return region.label;
}
const state = props.orderFieldValueState || 'idle';
@@ -283,7 +288,8 @@ const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
? t('admin.shippingOrderProfiles.workbench.orderFieldValueReading')
: state === 'failed'
? t('admin.shippingOrderProfiles.workbench.orderFieldValueFailed')
: value || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable');
// 新圈选的 XFA 值框先显示同次受控视觉回读;整页 PDFium/OCR 预览完成后再覆盖。
: value || region.suggestedValue || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable');
return `${region.label} · ${suffix}`;
};
/** 以固定步进调整页面倍率;区域采用相对坐标,缩放后仍与图像精确对齐。 */
@@ -298,7 +304,24 @@ const goToPage = () => {
pageInput.value = nextPage;
if (nextPage !== props.pageNo) emit('page', nextPage);
};
defineExpose({ zoomIn: () => adjustZoom(.25), zoomOut: () => adjustZoom(-.25), resetZoom });
/** 导出当前 PDF.js 画布中框选区域的 PNG;XFA 外观值可能只存在于浏览器渲染结果。 */
const captureRegion = (region: OrderProfileCanvasRegion['region']): string | null => {
const source = pdfCanvas.value;
if (!source || source.width < 1 || source.height < 1) return null;
const x = Math.max(0, Math.floor(region.x0 * source.width));
const y = Math.max(0, Math.floor(region.y0 * source.height));
const width = Math.max(1, Math.ceil((region.x1 - region.x0) * source.width));
const height = Math.max(1, Math.ceil((region.y1 - region.y0) * source.height));
const clippedWidth = Math.min(width, source.width - x);
const clippedHeight = Math.min(height, source.height - y);
if (clippedWidth < 1 || clippedHeight < 1) return null;
const crop = document.createElement('canvas');
crop.width = clippedWidth;
crop.height = clippedHeight;
crop.getContext('2d')?.drawImage(source, x, y, clippedWidth, clippedHeight, 0, 0, clippedWidth, clippedHeight);
return crop.toDataURL('image/png');
};
defineExpose({ zoomIn: () => adjustZoom(.25), zoomOut: () => adjustZoom(-.25), resetZoom, captureRegion });
watch(() => [props.grant?.preview_token, props.pdfPreview?.preview_token], () => { void loadPage(); }, { immediate: true });
watch(() => props.pageNo, async (value) => {
pageInput.value = value;
@@ -330,8 +353,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
<template v-if="pendingSuggestionCount">
<span class="toolbar-divider" aria-hidden="true" />
<span class="suggestion-count">{{ pendingSuggestionCount }}</span>
<button type="button" class="suggestion-action" @click="emit('acceptSuggestion')">{{ t('admin.shippingOrderProfiles.workbench.acceptSuggestion') }}</button>
<button type="button" class="suggestion-action suggestion-action--reject" @click="emit('rejectSuggestion')">{{ t('admin.shippingOrderProfiles.workbench.rejectSuggestion') }}</button>
<span class="suggestion-preview-badge">{{ t('admin.shippingOrderProfiles.workbench.suggestionPreviewBadge') }}</span>
</template>
</template>
<span v-else class="readonly-badge">{{ t('admin.shippingOrderProfiles.versionCenter.readonlyCanvasBadge') }}</span>
@@ -365,6 +387,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawLineShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawLineShortcut')" :class="{ active: creationKind === 'line' }" @click="emit('draw', 'line')"><Rows3 /></button>
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawFieldShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawFieldShortcut')" :class="{ active: creationKind === 'field' }" @click="emit('draw', 'field')"><Columns3 /></button>
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawExclusionShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawExclusionShortcut')" :class="{ active: creationKind === 'exclusion' }" @click="emit('draw', 'exclusion')"><Eraser /></button>
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawReservationIdRegionShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawReservationIdRegionShortcut')" :class="{ active: creationKind === 'reservation_id_region' }" @click="emit('draw', 'reservation_id_region')"><MessageSquareText /></button>
<button type="button" class="suggest" :aria-label="t('admin.shippingOrderProfiles.workbench.autoSuggestShortcut')" :title="t('admin.shippingOrderProfiles.workbench.autoSuggestShortcut')" :disabled="autoSuggestDisabled || suggesting" @click="emit('suggest')"><WandSparkles /></button>
<p v-if="suggestionProgress" class="suggestion-progress" :class="{ failed: !suggesting }">{{ suggestionProgress }}</p>
</aside>
@@ -386,7 +409,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
role="button"
tabindex="0"
class="region"
:class="[`region-${region.kind}`, { selected: selected.has(region.id) }, region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '']"
:class="[`region-${region.kind}`, { selected: selected.has(region.id), 'region-preview': region.isPreview }, region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '']"
:style="{ left: `${region.region.x0 * 100}%`, top: `${region.region.y0 * 100}%`, width: `${(region.region.x1 - region.region.x0) * 100}%`, height: `${(region.region.y1 - region.region.y0) * 100}%` }"
:aria-label="displayRegionLabel(region)"
@pointerdown.stop="beginDrag($event, region, 'move')"
@@ -394,10 +417,10 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
@keydown.space.prevent="emit('select', region.id)"
>
<span class="region-label" :title="displayRegionLabel(region)" @pointerdown.stop="beginDrag($event, region, 'move')">{{ displayRegionLabel(region) }}</span>
<template v-if="region.kind === 'line' && !readonlyMode">
<template v-if="region.kind === 'line' && !readonlyMode && !region.isPreview">
<span v-for="edge in ['n', 'e', 's', 'w']" :key="edge" class="line-hit-edge" :class="`line-hit-${edge}`" @pointerdown.stop="beginDrag($event, region, 'move')" />
</template>
<button v-if="!readonlyMode" v-for="handle in ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'] as ResizeHandle[]" :key="handle" type="button" class="resize-handle" :class="`handle-${handle}`" :aria-label="t('admin.shippingOrderProfiles.workbench.resizeHandle', { direction: handle })" @pointerdown.stop="beginDrag($event, region, handle)" />
<button v-if="!readonlyMode && !region.isPreview" v-for="handle in ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'] as ResizeHandle[]" :key="handle" type="button" class="resize-handle" :class="`handle-${handle}`" :aria-label="t('admin.shippingOrderProfiles.workbench.resizeHandle', { direction: handle })" @pointerdown.stop="beginDrag($event, region, handle)" />
</div>
<div v-if="creationRegion" class="creation-region" :style="{ left: `${creationRegion.x0 * 100}%`, top: `${creationRegion.y0 * 100}%`, width: `${(creationRegion.x1 - creationRegion.x0) * 100}%`, height: `${(creationRegion.y1 - creationRegion.y0) * 100}%` }" />
</div>
@@ -462,6 +485,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
.annotation-tools button:disabled { cursor: not-allowed; opacity: .45; }
.suggestion-progress { margin: .1rem; color: #bae6fd; font-size: .66rem; line-height: 1.35; }
.suggestion-progress.failed { color: #fca5a5; }
.suggestion-preview-badge { color: #fbbf24; font-size: .68rem; }
.region { position: absolute; box-sizing: border-box; z-index: 2; border: 2px solid #38bdf8; background: rgb(14 165 233 / .10); color: #e0f2fe; cursor: move; text-align: left; touch-action: none; }
.region:focus-visible { outline: 3px solid white; outline-offset: 2px; }
.region-label { position: absolute; top: -1.65rem; left: -2px; max-width: min(18rem, 100%); overflow: hidden; border: 1px solid rgb(255 255 255 / .7); border-radius: .25rem .25rem 0 0; background: #0369a1; padding: .2rem .45rem; color: white; font: 700 .7rem/1.15 ui-monospace, SFMono-Regular, Menlo, monospace; text-overflow: ellipsis; white-space: nowrap; }
@@ -496,6 +520,8 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
.line-hit-w { left: -6px; }
.region-exclusion { z-index: 3; border-style: dashed; border-color: #f87171; background: rgb(248 113 113 / .1); }
.region-exclusion .region-label, .region-exclusion .resize-handle { background: #b91c1c; }
.region-reservation_id_region { z-index: 3; border: 2px solid #f43f5e; background: rgb(244 63 94 / .10); }
.region-reservation_id_region .region-label, .region-reservation_id_region .resize-handle { background: #be123c; }
.region-visual--suggested { border-style: dashed; border-color: #f59e0b; background: rgb(245 158 11 / .14); }
.region-visual--suggested .region-label { background: #b45309; }
.region-visual--confirmed { border-color: #22c55e; background: rgb(34 197 94 / .12); }
@@ -505,6 +531,8 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
.region:not(.selected) .resize-handle { display: none; }
.region.selected { outline: 3px solid white; outline-offset: 2px; }
.region.selected:not(.region-line) { z-index: 4; }
.region-preview { z-index: 5; border-style: dashed; border-width: 2px; border-color: #fbbf24; background: rgb(245 158 11 / .18); color: #fef3c7; cursor: default; pointer-events: auto; }
.region-preview .region-label { background: #a16207; }
.canvas-stage.drawing .region { pointer-events: none; }
@media (max-width: 900px) {
.canvas-shell { height: auto; min-height: 36rem; }
@@ -55,14 +55,16 @@ watch(() => props.samples, () => {
async function pollIntake(intakeNo: string): Promise<void> {
try {
const result = await getOrderProfileSampleStatus(intakeNo);
if (result.parse_status === 'parsed' && result.document_count > 0) {
// 文档记录已落库不等于样本可选;列表接口还要求当前 Layout ready。
// 等待同一状态后再刷新,避免把尚未建好表格的文档误报为已完成。
if (result.parse_status === 'parsed' && result.document_count > 0 && result.layout_status === 'ready') {
pendingIntake.value = { intakeNo, filename: pendingIntake.value?.filename || '', state: 'syncing' };
emit('uploaded', intakeNo);
// 列表可能比状态接口晚一个轮询周期可见,保持轮询直到父级刷新后精确选中。
pollingTimer = window.setTimeout(() => void pollIntake(intakeNo), 1000);
return;
}
if (['failed', 'error'].includes(result.parse_status)) {
if (['failed', 'error'].includes(result.parse_status) || result.layout_status === 'failed') {
pendingIntake.value = {
intakeNo, filename: pendingIntake.value?.filename || '', state: 'failed', errorCode: result.error_code,
};
@@ -1,280 +0,0 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/VcMergePreviewTable.vue
用途:三来源候选合并预览表。严格后端决定 UI,只按后端返回的 resolution/decision_status 着色,
绝不 if/else 推导合并结果。
依赖:shipping-order-document-profile.vc.types.ts Section E(VCMergedObservationCandidate);
所有着色规则由 resolutionClass 查表映射,禁止前端自行推导业务状态。
逻辑:只读展示,无 emit。空态显示「暂无预览数据,请点击预览按钮」。
-->
<script setup lang="ts">
import type { VCMergedObservationCandidate } from '@/features/admin/types/shipping-order-document-profile.vc.types';
defineProps<{
candidates: VCMergedObservationCandidate[];
loading?: boolean;
}>();
function sourceColorClass(source: string): string {
if (source === 'header_region') return 'vc-map__src-header';
if (source === 'table_column') return 'vc-map__src-table';
if (source === 'vendor_comments') return 'vc-map__src-vc';
return '';
}
function resolutionClass(resolution: string, decisionStatus: string): string {
const key = `${resolution}|${decisionStatus}`;
const classMap: Record<string, string> = {
'needs_review|pending': 'bg-red-50 text-red-700 border-red-200',
'needs_review|needs_review': 'bg-red-50 text-red-700 border-red-200',
'same_value_merged|accepted': 'bg-emerald-50 text-emerald-700 border-emerald-200',
'single_source_direct|accepted': 'bg-green-50 text-green-700 border-green-200',
'fill_missing|accepted': 'bg-sky-50 text-sky-700 border-sky-200',
'annotation_only_dropped|accepted': 'bg-gray-50 text-gray-500 line-through',
'annotation_only_dropped|missing': 'bg-gray-50 text-gray-500 line-through',
'invalid_line_reference|blocked': 'bg-gray-50 text-gray-500 line-through',
'no_value|missing': 'bg-gray-50 text-gray-500 line-through',
};
return classMap[key] ?? '';
}
function resolutionBadge(resolution: string): string {
const labelMap: Record<string, string> = {
same_value_merged: '同值合并',
fill_missing: '补空',
needs_review: '需复核',
no_value: '无值',
single_source_direct: '单源直达',
annotation_only_dropped: '仅备注(丢弃)',
};
return labelMap[resolution] ?? resolution;
}
function conflictGroupKey(cand: VCMergedObservationCandidate): string {
return `[${cand.target_scope}] ${cand.target_field_code} #${cand.effective_line_no ?? 'H'}`;
}
</script>
<template>
<div class="vc-merge-preview">
<div v-if="candidates.length === 0" class="vc-merge-preview__empty">
<p v-if="loading">预览加载中…</p>
<p v-else>暂无预览数据,请点击预览按钮</p>
</div>
<div v-else class="vc-merge-preview__body">
<div
v-for="(cand, i) in candidates"
:key="i"
class="vc-merge-preview__row"
:class="resolutionClass(cand.resolution, cand.decision_status)"
>
<div class="vc-merge-preview__row-main">
<div class="vc-merge-preview__key">
<strong>{{ conflictGroupKey(cand) }}</strong>
</div>
<div class="vc-merge-preview__badge">
<span class="vc-merge-preview__resolution" :class="`vc-merge-preview__resolution--${cand.resolution}`">
{{ resolutionBadge(cand.resolution) }}
</span>
<span class="vc-merge-preview__status">
{{ cand.decision_status }}
</span>
</div>
<div class="vc-merge-preview__accepted">
<template v-if="cand.decision_status === 'needs_review' || cand.resolution === 'needs_review'">
<span class="vc-merge-preview__needs-review">
⚠ 需人工复核
</span>
</template>
<template v-else>
<span v-if="cand.accepted_value !== null && cand.accepted_value !== undefined">
accepted_value:<code>{{ cand.accepted_value }}</code>
</span>
<span v-else class="vc-merge-preview__muted">
accepted_value:—
</span>
</template>
</div>
</div>
<div class="vc-merge-preview__conflicts">
<div class="vc-merge-preview__conflicts-title">
来源快照 ({{ cand.source_observations.length }})
</div>
<ul class="vc-map__src-list">
<li
v-for="(obs, j) in cand.source_observations"
:key="j"
:class="sourceColorClass(obs.source)"
>
<span class="vc-map__src-tag">{{ obs.source }}</span>
<code>{{ obs.normalized_value }}</code>
<small v-if="obs.format_valid === false" class="vc-map__format-invalid">
(format: {{ obs.format_reason_code }})
</small>
</li>
</ul>
<div v-if="cand.conflicts && cand.conflicts.length > 0" class="vc-merge-preview__conflicts-detail">
<details>
<summary>冲突详情 ({{ cand.conflicts.length }})</summary>
<pre>{{ JSON.stringify(cand.conflicts, null, 2) }}</pre>
</details>
</div>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.vc-merge-preview {
display: flex;
flex-direction: column;
gap: 8px;
}
.vc-merge-preview__empty {
padding: 20px 10px;
text-align: center;
color: var(--text-muted);
font-size: 0.82rem;
border: 1px dashed var(--border-default);
border-radius: 6px;
}
.vc-merge-preview__body {
display: flex;
flex-direction: column;
gap: 8px;
}
.vc-merge-preview__row {
border: 1px solid var(--border-default);
border-radius: 8px;
padding: 10px;
display: flex;
flex-direction: column;
gap: 8px;
background: var(--bg-primary);
}
.vc-merge-preview__row-main {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
flex-wrap: wrap;
}
.vc-merge-preview__key {
font-size: 0.85rem;
}
.vc-merge-preview__badge {
display: flex;
align-items: center;
gap: 6px;
}
.vc-merge-preview__resolution {
display: inline-block;
padding: 2px 8px;
border-radius: 10px;
font-size: 0.72rem;
font-weight: 600;
border: 1px solid;
}
.vc-merge-preview__resolution--same_value_merged {
background: rgba(16, 185, 129, 0.1);
border-color: rgba(16, 185, 129, 0.3);
color: #047857;
}
.vc-merge-preview__resolution--single_source_direct {
background: rgba(34, 197, 94, 0.1);
border-color: rgba(34, 197, 94, 0.3);
color: #15803d;
}
.vc-merge-preview__resolution--fill_missing {
background: rgba(14, 165, 233, 0.1);
border-color: rgba(14, 165, 233, 0.3);
color: #0369a1;
}
.vc-merge-preview__resolution--needs_review {
background: rgba(239, 68, 68, 0.1);
border-color: rgba(239, 68, 68, 0.3);
color: #b91c1c;
}
.vc-merge-preview__resolution--annotation_only_dropped,
.vc-merge-preview__resolution--no_value {
background: rgba(107, 114, 128, 0.1);
border-color: rgba(107, 114, 128, 0.3);
color: #4b5563;
}
.vc-merge-preview__status {
font-size: 0.72rem;
color: var(--text-muted);
}
.vc-merge-preview__accepted {
font-size: 0.82rem;
}
.vc-merge-preview__needs-review {
color: #b91c1c;
font-weight: 600;
}
.vc-merge-preview__muted {
color: var(--text-muted);
}
.vc-merge-preview__conflicts {
padding-top: 6px;
border-top: 1px dashed var(--border-default);
display: flex;
flex-direction: column;
gap: 6px;
}
.vc-merge-preview__conflicts-title {
font-size: 0.78rem;
font-weight: 600;
color: var(--text-secondary);
}
.vc-map__src-list {
list-style: none;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
gap: 4px;
}
.vc-map__src-tag {
display: inline-block;
padding: 1px 6px;
border-radius: 10px;
font-size: 0.7rem;
margin-right: 4px;
color: white;
}
.vc-map__src-header .vc-map__src-tag { background: #3b82f6; }
.vc-map__src-table .vc-map__src-tag { background: #10b981; }
.vc-map__src-vc .vc-map__src-tag { background: #f59e0b; }
.vc-map__format-invalid {
color: var(--text-danger);
margin-left: 4px;
}
code {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
background: var(--bg-elevated);
padding: 1px 4px;
border-radius: 3px;
font-size: 0.78rem;
}
.vc-merge-preview__conflicts-detail {
margin-top: 4px;
}
.vc-merge-preview__conflicts-detail summary {
cursor: pointer;
font-size: 0.75rem;
color: var(--text-muted);
}
.vc-merge-preview__conflicts-detail pre {
margin: 6px 0 0 0;
padding: 6px;
border: 1px solid var(--border-default);
border-radius: 4px;
background: var(--bg-elevated);
font-size: 0.72rem;
max-height: 160px;
overflow: auto;
}
</style>
@@ -1,431 +0,0 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/VcNamedRegionBox.vue
用途:Vendor Comments 命名区域圈选框——薄封装 OrderProfileDocumentCanvas,维护 dedicated regions。
依赖:shipping-order-document-profile.vc.types.ts Section A/H、OrderProfileDocumentCanvas。
逻辑:不做任何 save,所有写操作走 emit 父级;region/page_scope/selection_mode 四元组变更触发
VCProfileDraftTrigger(reasons: named_region_*),仅负责前端门禁,真实判定在后端。
-->
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import OrderProfileDocumentCanvas from './OrderProfileDocumentCanvas.vue';
import type {
OrderProfileCanvasRegion,
OrderProfilePreviewPageGrant,
OrderProfileRelativeRegion,
} from '@/features/admin/types/shipping-order-document-profile.types';
import type {
VCNamedRegion,
VCNamedRegionPageScope,
VCNamedRegionSelectionMode,
VCProfileDraftTrigger,
} from '@/features/admin/types/shipping-order-document-profile.vc.types';
type VCNamedRegionCreatePartial = {
label: string;
page_scope: VCNamedRegionPageScope;
selection_mode: VCNamedRegionSelectionMode;
region: OrderProfileRelativeRegion;
};
const props = withDefaults(defineProps<{
profileId: number | null;
grant?: OrderProfilePreviewPageGrant | null;
pageNo: number;
pageCount: number;
previewPagePath?: string | null;
namedRegions: Record<string, VCNamedRegion>;
selectedRegionId: string | null;
regionOptions?: {
page_scope_options?: { value: string; label: string }[];
};
readonly?: boolean;
}>(), {
regionOptions: () => ({}),
readonly: false,
});
const emit = defineEmits<{
'update:namedRegions': [regions: Record<string, VCNamedRegion>];
select: [regionId: string];
create: [partial: VCNamedRegionCreatePartial];
change: [regionId: string, patch: Partial<VCNamedRegion>];
delete: [regionId: string];
draftRequired: [trigger: VCProfileDraftTrigger];
}>();
const defaultPageScopeOptions = computed(() => {
if (props.regionOptions?.page_scope_options?.length) {
return props.regionOptions.page_scope_options;
}
return [
{ value: 'first_page', label: '首页' },
{ value: 'last_page', label: '末页' },
{ value: 'exact_page', label: '指定页' },
];
});
const selectionModeOptions: { value: VCNamedRegionSelectionMode; label: string }[] = [
{ value: 'fixed_region', label: '固定区域 (box)' },
{ value: 'auto_take_last_qualified', label: '取末段合格 (paragraph)' },
];
const selectedOrderRegionId = computed(() => {
return props.selectedRegionId ? `vc:${props.selectedRegionId}` : null;
});
const canvasRegions = computed<OrderProfileCanvasRegion[]>(() => {
const regions: OrderProfileCanvasRegion[] = [];
Object.values(props.namedRegions || {}).forEach((nr) => {
let pageNo = props.pageNo;
if (nr.page_scope === 'exact_page' && nr.page_no) {
pageNo = nr.page_no;
}
regions.push({
id: `vc:${nr.region_id}`,
kind: 'order_field',
label: nr.label,
region: { ...nr.region },
pageNo,
});
});
return regions;
});
const priorSnapshot = ref<string>('');
function snapshotRegions(): string {
const entries = Object.entries(props.namedRegions || {})
.sort(([a], [b]) => a.localeCompare(b))
.map(([id, r]) => `${id}|${r.label}|${r.page_scope}|${r.selection_mode}|${JSON.stringify(r.region)}`);
return entries.join('||');
}
watch(() => snapshotRegions(), (next, prev) => {
if (!prev || !next || next === prev) return;
const prevMap = props.namedRegions || {};
const reasons: VCProfileDraftTrigger['reasons'] = [];
const prevIds = new Set(Object.keys(prevMap));
const nextIds = new Set(Object.keys(prevMap));
prevIds.forEach((id) => {
if (!nextIds.has(id)) {
reasons.push({ kind: 'named_region_removed', region_id: id });
}
});
nextIds.forEach((id) => {
if (!prevIds.has(id)) {
reasons.push({ kind: 'named_region_added', region_id: id });
}
});
nextIds.forEach((id) => {
if (!prevIds.has(id)) return;
const prev = prevMap[id];
const nextR = prevMap[id];
if (!prev || !nextR) return;
if (prev.page_scope !== nextR.page_scope) {
reasons.push({ kind: 'named_region_scope', region_id: id });
}
const prevGeo = `${prev.region.x0},${prev.region.y0},${prev.region.x1},${prev.region.y1}`;
const nextGeo = `${nextR.region.x0},${nextR.region.y0},${nextR.region.x1},${nextR.region.y1}`;
if (prevGeo !== nextGeo) {
reasons.push({ kind: 'named_region_geometry', region_id: id });
}
});
if (reasons.length > 0) {
emit('draftRequired', {
named_regions_changed: true,
field_source_mappings_changed: false,
requires_draft_reset: true,
reasons,
});
}
}, { flush: 'post' });
priorSnapshot.value = snapshotRegions();
function onCanvasSelect(regionId: string): void {
if (!regionId.startsWith('vc:')) return;
emit('select', regionId.slice(3));
}
function onCanvasCreate(region: OrderProfileCanvasRegion['region']): void {
const count = Object.keys(props.namedRegions || {}).length;
emit('create', {
label: `Vendor Comments ${count + 1}`,
page_scope: 'first_page',
selection_mode: 'fixed_region',
region,
});
}
function onCanvasChange(regionId: string, region: OrderProfileCanvasRegion['region']): void {
if (!regionId.startsWith('vc:')) return;
const id = regionId.slice(3);
emit('change', id, { region });
}
function updateLabel(regionId: string, label: string): void {
emit('change', regionId, { label });
}
function updatePageScope(regionId: string, pageScope: VCNamedRegionPageScope): void {
emit('change', regionId, { page_scope: pageScope });
}
function updateSelectionMode(regionId: string, mode: VCNamedRegionSelectionMode): void {
emit('change', regionId, { selection_mode: mode });
}
function updatePageNo(regionId: string, pageNo: number | null): void {
emit('change', regionId, { page_no: pageNo });
}
function addRegion(): void {
const count = Object.keys(props.namedRegions || {}).length;
emit('create', {
label: `Vendor Comments ${count + 1}`,
page_scope: 'first_page',
selection_mode: 'fixed_region',
region: { x0: 0.1, y0: 0.1, x1: 0.9, y1: 0.15 },
});
}
const orderedRegions = computed(() => {
return Object.values(props.namedRegions || {}).sort((a, b) => (
a.label.localeCompare(b.label)
));
});
</script>
<template>
<div class="vc-named-region-box">
<div class="vc-named-region-box__toolbar">
<button
type="button"
:disabled="readonly"
class="vc-named-region-box__add-btn"
@click="addRegion"
>
新增 Vendor Comments 区域
</button>
</div>
<div class="vc-named-region-box__body">
<aside class="vc-named-region-box__sidebar">
<ul v-if="orderedRegions.length" class="vc-named-region-box__list">
<li
v-for="nr in orderedRegions"
:key="nr.region_id"
class="vc-named-region-box__item"
:class="{ 'is-selected': selectedRegionId === nr.region_id }"
@click="emit('select', nr.region_id)"
>
<div class="vc-named-region-box__item-header">
<input
class="vc-named-region-box__label-input"
:disabled="readonly"
:value="nr.label"
@input="updateLabel(nr.region_id, ($event.target as HTMLInputElement).value)"
@click.stop
/>
<button
type="button"
class="vc-named-region-box__delete-btn"
:disabled="readonly"
@click.stop="emit('delete', nr.region_id)"
>
×
</button>
</div>
<div class="vc-named-region-box__item-fields">
<label>
页范围
<select
:disabled="readonly"
:value="nr.page_scope"
@change.stop="updatePageScope(nr.region_id, ($event.target as HTMLSelectElement).value as VCNamedRegionPageScope)"
>
<option
v-for="opt in defaultPageScopeOptions"
:key="opt.value"
:value="opt.value"
>
{{ opt.label }}
</option>
</select>
</label>
<label v-if="nr.page_scope === 'exact_page'">
页码
<input
type="number"
min="1"
:max="pageCount || undefined"
:disabled="readonly"
:value="nr.page_no ?? ''"
@input.stop="updatePageNo(nr.region_id, ($event.target as HTMLInputElement).value === '' ? null : Number(($event.target as HTMLInputElement).value))"
/>
</label>
<label>
选择模式
<select
:disabled="readonly"
:value="nr.selection_mode"
@change.stop="updateSelectionMode(nr.region_id, ($event.target as HTMLSelectElement).value as VCNamedRegionSelectionMode)"
>
<option
v-for="opt in selectionModeOptions"
:key="opt.value"
:value="opt.value"
>
{{ opt.label }}
</option>
</select>
</label>
</div>
</li>
</ul>
<p v-else class="vc-named-region-box__empty">
暂无命名区域,点击上方按钮新增或在画布上拖动圈选。
</p>
</aside>
<div class="vc-named-region-box__canvas">
<OrderProfileDocumentCanvas
:profile-id="profileId"
:grant="grant"
:preview-page-path="previewPagePath"
:mode="readonly ? 'readonly' : 'edit'"
:regions="canvasRegions"
:selected-region-id="selectedOrderRegionId"
:creation-kind="readonly ? null : 'order_field'"
:page-no="pageNo"
:page-count="pageCount"
@select="onCanvasSelect"
@create="onCanvasCreate"
@change="onCanvasChange"
/>
</div>
</div>
</div>
</template>
<style scoped>
.vc-named-region-box {
display: flex;
flex-direction: column;
gap: 8px;
min-height: 0;
height: 100%;
}
.vc-named-region-box__toolbar {
display: flex;
align-items: center;
gap: 8px;
}
.vc-named-region-box__add-btn {
padding: 6px 12px;
border: 1px solid var(--border-default);
border-radius: 6px;
background: var(--bg-primary);
cursor: pointer;
font-size: 0.85rem;
}
.vc-named-region-box__add-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.vc-named-region-box__body {
display: grid;
grid-template-columns: 280px 1fr;
gap: 8px;
min-height: 0;
flex: 1;
}
.vc-named-region-box__sidebar {
display: flex;
flex-direction: column;
gap: 6px;
overflow: auto;
border: 1px solid var(--border-default);
border-radius: 6px;
padding: 8px;
background: var(--bg-elevated);
}
.vc-named-region-box__list {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 8px;
}
.vc-named-region-box__item {
border: 1px solid var(--border-default);
border-radius: 6px;
padding: 8px;
cursor: pointer;
background: var(--bg-primary);
}
.vc-named-region-box__item.is-selected {
border-color: var(--accent-primary);
box-shadow: 0 0 0 1px var(--accent-primary);
}
.vc-named-region-box__item-header {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 6px;
}
.vc-named-region-box__label-input {
flex: 1;
padding: 4px 6px;
border: 1px solid var(--border-default);
border-radius: 4px;
font-size: 0.85rem;
min-width: 0;
}
.vc-named-region-box__delete-btn {
width: 24px;
height: 24px;
border: 1px solid var(--border-default);
border-radius: 4px;
background: var(--bg-primary);
cursor: pointer;
color: var(--text-danger);
}
.vc-named-region-box__delete-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.vc-named-region-box__item-fields {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 0.78rem;
}
.vc-named-region-box__item-fields label {
display: grid;
grid-template-columns: 56px 1fr;
align-items: center;
gap: 6px;
}
.vc-named-region-box__item-fields select,
.vc-named-region-box__item-fields input {
padding: 3px 6px;
border: 1px solid var(--border-default);
border-radius: 4px;
font-size: 0.78rem;
min-width: 0;
}
.vc-named-region-box__empty {
margin: 0;
color: var(--text-muted);
font-size: 0.8rem;
text-align: center;
padding: 16px 8px;
}
.vc-named-region-box__canvas {
min-height: 0;
border: 1px solid var(--border-default);
border-radius: 6px;
overflow: hidden;
background: var(--bg-primary);
}
</style>
@@ -1,544 +0,0 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingPanel.vue
用途:薄编排主面板——只做顶层三开关 + 引入 VcSourceMappingSection * 3 + VcSplitRuleEditor
(抽屉/modal)+ VcMergePreviewTable。
依赖:shipping-order-document-profile.vc.types.ts Section B/C/D/E/H/I;
子组件:VcSourceMappingSection、VcSplitRuleEditor、VcMergePreviewTable。
逻辑:emit update:definition 写回完整 patch;field_source_mappings 任何改动 + split_rules
改动触发 VCProfileDraftTrigger(聚合所有子 trigger)。
Props / Emits 保留原来的契约,确保父级零修改可切换。
-->
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import type {
VCMergedObservationCandidate,
VCProfileDefinitionExtensions,
VCProfileDraftTrigger,
VCProfileFieldSourceMapping,
VCSplitRuleSet,
} from '@/features/admin/types/shipping-order-document-profile.vc.types';
import VcSourceMappingSection from './VcSourceMappingSection.vue';
import VcSplitRuleEditor from './VcSplitRuleEditor.vue';
import VcMergePreviewTable from './VcMergePreviewTable.vue';
type VCProfileFieldSourceMappingPatch = Partial<VCProfileFieldSourceMapping>;
const props = withDefaults(defineProps<{
definition: VCProfileDefinitionExtensions;
selectedFieldCode: string;
targetScopes?: Array<'header' | 'line'>;
readonly?: boolean;
documentId: number;
profileId: number;
dirtyUnsaved?: boolean;
persistedConfirmed?: boolean;
canPreview?: boolean;
}>(), {
selectedFieldCode: 'reservation_id',
targetScopes: () => ['header', 'line'],
readonly: false,
dirtyUnsaved: false,
persistedConfirmed: false,
canPreview: true,
});
const emit = defineEmits<{
'update:definition': [patch: VCProfileDefinitionExtensions];
draftRequired: [trigger: VCProfileDraftTrigger];
'vc:split-panel-confirmed': [
rules: VCSplitRuleSet[],
confirmationTokens: Record<string, string>,
fieldCode: string,
];
}>();
function newClientId(): string {
return `map-${crypto.randomUUID().replace(/-/g, '')}`;
}
const DEFAULT_FORMAT_POLICY = {
mode: 'inherit_global' as const,
pattern: null,
max_capture_groups: 1,
timeout_ms: 500,
case_sensitive: false,
};
const EMPTY_MAPPING_BASE = (fieldCode: string, targetScope: 'header' | 'line'): VCProfileFieldSourceMapping => ({
mapping_id: newClientId(),
target_scope: targetScope,
target_field_code: fieldCode,
target_field_id: '',
header_source_enabled: false,
header_source_ref: null,
header_normalizer_key: null,
table_source_enabled: false,
table_column_code: null,
vendor_comments_enabled: false,
vendor_comments_region_ref: null,
vendor_comments_split_rule_set: null,
relation_policy: 'bind_target_line',
missing_relation_policy: 'default_all_lines',
line_reference_basis: 'classified_logical_line_no',
fill_missing_from_other_sources: true,
format_policy: { ...DEFAULT_FORMAT_POLICY },
});
const activeMappings = computed(() => {
const list = props.definition?.field_source_mappings || [];
return list.filter((m) => m.target_field_code === props.selectedFieldCode);
});
const headerMapping = computed(() => activeMappings.value.find((m) => m.target_scope === 'header') || null);
const lineMapping = computed(() => activeMappings.value.find((m) => m.target_scope === 'line') || null);
const scopeOptions = computed(() => (
props.targetScopes.map((s) => ({
value: s,
label: s === 'header' ? 'Header (订单头)' : 'Line (明细行)',
}))
));
const splitEditorVisible = ref(false);
const splitEditorScope = ref<'header' | 'line'>('line');
const splitEditorRuleSet = computed<VCSplitRuleSet | null>(() => {
const mapping = splitEditorScope.value === 'header' ? headerMapping.value : lineMapping.value;
return mapping?.vendor_comments_split_rule_set ?? null;
});
const mergeLoading = ref(false);
const mergePreviewResults = ref<VCMergedObservationCandidate[]>([]);
function cloneDefinitionForWrite(): VCProfileDefinitionExtensions {
return {
named_regions: props.definition?.named_regions ? { ...props.definition.named_regions } : null,
field_source_mappings: props.definition?.field_source_mappings
? props.definition.field_source_mappings.map((m) => ({ ...m }))
: [],
};
}
function ensureMapping(scope: 'header' | 'line'): VCProfileFieldSourceMapping {
const existing = scope === 'header' ? headerMapping.value : lineMapping.value;
if (existing) return existing;
const fresh = EMPTY_MAPPING_BASE(props.selectedFieldCode, scope);
const patch = cloneDefinitionForWrite();
patch.field_source_mappings = [...(patch.field_source_mappings || []), fresh];
emit('update:definition', patch);
emitDraftTriggerAggregated({
reasons: [{ kind: 'field_source_mapping_added', mapping_id: fresh.mapping_id }],
changed: true,
});
return fresh;
}
function updateMapping(mappingId: string, patchFields: VCProfileFieldSourceMappingPatch): void {
const patch = cloneDefinitionForWrite();
const list = patch.field_source_mappings || [];
const idx = list.findIndex((m) => m.mapping_id === mappingId);
if (idx < 0) return;
const current = list[idx];
if (!current) return;
const before = JSON.stringify(current);
list[idx] = { ...current, ...patchFields };
patch.field_source_mappings = list;
emit('update:definition', patch);
const after = JSON.stringify(list[idx]);
if (before === after) return;
const beforeObj = JSON.parse(before) as VCProfileFieldSourceMapping;
const afterObj = JSON.parse(after) as VCProfileFieldSourceMapping;
const reasons: VCProfileDraftTrigger['reasons'] = [];
if (
beforeObj.format_policy?.mode !== afterObj.format_policy?.mode
|| beforeObj.format_policy?.pattern !== afterObj.format_policy?.pattern
|| beforeObj.format_policy?.max_capture_groups !== afterObj.format_policy?.max_capture_groups
) {
reasons.push({
kind: 'field_source_mapping_format_policy_changed',
mapping_id: mappingId,
});
}
const enabledKeys = [
'header_source_enabled',
'table_source_enabled',
'vendor_comments_enabled',
] as const;
let hasEnabledChange = false;
for (const k of enabledKeys) {
if (beforeObj[k] !== afterObj[k]) {
hasEnabledChange = true;
break;
}
}
if (hasEnabledChange) {
reasons.push({
kind: 'field_source_mapping_format_policy_changed',
mapping_id: mappingId,
});
}
if (
beforeObj.vendor_comments_region_ref !== afterObj.vendor_comments_region_ref
|| beforeObj.table_column_code !== afterObj.table_column_code
) {
reasons.push({
kind: 'field_source_mapping_format_policy_changed',
mapping_id: mappingId,
});
}
if (reasons.length === 0) {
reasons.push({
kind: 'field_source_mapping_format_policy_changed',
mapping_id: mappingId,
});
}
emitDraftTriggerAggregated({ reasons, changed: true });
}
function emitDraftTriggerAggregated(opts: {
reasons: VCProfileDraftTrigger['reasons'];
changed: boolean;
}): void {
emit('draftRequired', {
named_regions_changed: false,
field_source_mappings_changed: opts.changed,
requires_draft_reset: true,
reasons: opts.reasons,
});
}
function handleSectionMappingUpdate(
scope: 'header' | 'line',
updatedMapping: VCProfileFieldSourceMapping,
): void {
const patch = cloneDefinitionForWrite();
const list = patch.field_source_mappings || [];
const idx = list.findIndex((m) => m.mapping_id === updatedMapping.mapping_id);
if (idx < 0) {
ensureMapping(scope);
return;
}
const before = JSON.stringify(list[idx]);
list[idx] = { ...updatedMapping };
patch.field_source_mappings = list;
emit('update:definition', patch);
const after = JSON.stringify(list[idx]);
if (before === after) return;
const beforeObj = JSON.parse(before) as VCProfileFieldSourceMapping;
const afterObj = JSON.parse(after) as VCProfileFieldSourceMapping;
const reasons: VCProfileDraftTrigger['reasons'] = [];
if (
beforeObj.format_policy?.mode !== afterObj.format_policy?.mode
|| beforeObj.format_policy?.pattern !== afterObj.format_policy?.pattern
|| beforeObj.format_policy?.max_capture_groups !== afterObj.format_policy?.max_capture_groups
) {
reasons.push({
kind: 'field_source_mapping_format_policy_changed',
mapping_id: updatedMapping.mapping_id,
});
}
const enabledKeys = [
'header_source_enabled',
'table_source_enabled',
'vendor_comments_enabled',
] as const;
for (const k of enabledKeys) {
if (beforeObj[k] !== afterObj[k]) {
reasons.push({
kind: 'field_source_mapping_format_policy_changed',
mapping_id: updatedMapping.mapping_id,
});
break;
}
}
if (
beforeObj.vendor_comments_region_ref !== afterObj.vendor_comments_region_ref
|| beforeObj.table_column_code !== afterObj.table_column_code
) {
reasons.push({
kind: 'field_source_mapping_format_policy_changed',
mapping_id: updatedMapping.mapping_id,
});
}
if (reasons.length === 0) {
reasons.push({
kind: 'field_source_mapping_format_policy_changed',
mapping_id: updatedMapping.mapping_id,
});
}
emitDraftTriggerAggregated({ reasons, changed: true });
}
function openSplitEditor(scope: 'header' | 'line'): void {
ensureMapping(scope);
splitEditorScope.value = scope;
splitEditorVisible.value = true;
}
function handleSplitRuleSetUpdate(updated: VCSplitRuleSet): void {
const scope = splitEditorScope.value;
const mapping = scope === 'header' ? headerMapping.value : lineMapping.value;
if (!mapping) return;
updateMapping(mapping.mapping_id, { vendor_comments_split_rule_set: updated });
}
function handleSplitEditorConfirmed(ruleSet: VCSplitRuleSet, previewToken: string): void {
emit('vc:split-panel-confirmed',
[ruleSet],
{ [ruleSet.rule_set_id]: previewToken },
props.selectedFieldCode,
);
splitEditorVisible.value = false;
}
function handleSplitEditorDraftRequired(trigger: VCProfileDraftTrigger): void {
emit('draftRequired', {
...trigger,
reasons: trigger.reasons.map((r) => ({ ...r })),
});
}
async function runMergePreview(): Promise<void> {
if (props.canPreview === false) return;
mergeLoading.value = true;
try {
// TODO: 后端 API stub,后续接入实际 endpoint
// 预期:POST /admin/shipping/document-profiles/{profileId}/documents/{documentId}/preview-merge
// 请求体:{ field_code: selectedFieldCode, definition }
// 响应:VCMergedObservationCandidate[]
mergePreviewResults.value = [];
} finally {
mergeLoading.value = false;
}
}
watch(splitEditorVisible, (v) => {
if (!v) {
// 关闭编辑器时无需特殊处理,ruleSet 已通过 update:ruleSet 实时同步
}
});
</script>
<template>
<section class="vc-source-mapping">
<header class="vc-map__header">
<h3 class="vc-map__title">字段来源映射 · {{ selectedFieldCode }}</h3>
<div class="vc-map__scope-tabs">
<span
v-for="s in scopeOptions"
:key="s.value"
class="vc-map__scope-tab"
:class="{ active: (s.value === 'header' ? headerMapping : lineMapping) != null }"
>
{{ s.label }}
</span>
</div>
</header>
<div class="vc-map__scopes">
<div
v-for="scope in scopeOptions"
:key="scope.value"
class="vc-map__scope-panel"
>
<div class="vc-map__scope-header">
<strong>{{ scope.label }}</strong>
<small v-if="!(scope.value === 'header' ? headerMapping : lineMapping)">
(未启用——开启任一来源将自动创建)
</small>
</div>
<div class="vc-map__source-groups">
<VcSourceMappingSection
kind="header_region"
:mapping="scope.value === 'header' ? headerMapping : lineMapping"
:definition="definition"
:readonly="readonly"
:mapping-id="(scope.value === 'header' ? headerMapping : lineMapping)?.mapping_id || 'pending'"
@update:mapping="(m) => handleSectionMappingUpdate(scope.value, m)"
/>
<VcSourceMappingSection
kind="table_column"
:mapping="scope.value === 'header' ? headerMapping : lineMapping"
:definition="definition"
:readonly="readonly"
:mapping-id="(scope.value === 'header' ? headerMapping : lineMapping)?.mapping_id || 'pending'"
@update:mapping="(m) => handleSectionMappingUpdate(scope.value, m)"
/>
<VcSourceMappingSection
kind="vendor_comments"
:mapping="scope.value === 'header' ? headerMapping : lineMapping"
:definition="definition"
:readonly="readonly"
:show-split-rules="true"
:mapping-id="(scope.value === 'header' ? headerMapping : lineMapping)?.mapping_id || 'pending'"
@update:mapping="(m) => handleSectionMappingUpdate(scope.value, m)"
@split-editor-open="openSplitEditor(scope.value)"
/>
</div>
</div>
</div>
<div v-if="splitEditorVisible" class="vc-map__split-editor-wrapper">
<VcSplitRuleEditor
:rule-set="splitEditorRuleSet"
:selected-field-code="selectedFieldCode"
:document-id="documentId"
:profile-id="profileId"
:readonly="readonly"
:dirty-unsaved="dirtyUnsaved"
:persisted-confirmed="persistedConfirmed"
:visible="splitEditorVisible"
@update:rule-set="handleSplitRuleSetUpdate"
@confirmed="handleSplitEditorConfirmed"
@draft-required="handleSplitEditorDraftRequired"
/>
<div class="vc-map__split-editor-close">
<button type="button" @click="splitEditorVisible = false">
关闭编辑器
</button>
</div>
</div>
<div class="vc-map__merge-preview">
<div class="vc-map__merge-toolbar">
<h4>合并预览(后端决定 UI,禁止前端 if/else 推导)</h4>
<button
type="button"
:disabled="!canPreview || mergeLoading"
@click="runMergePreview"
>
{{ mergeLoading ? '预览中…' : '拉取合并裁决 (stub)' }}
</button>
</div>
<VcMergePreviewTable
:candidates="mergePreviewResults"
:loading="mergeLoading"
/>
</div>
</section>
</template>
<style scoped>
.vc-source-mapping {
display: flex;
flex-direction: column;
gap: 10px;
min-height: 0;
overflow: auto;
}
.vc-map__header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.vc-map__title {
margin: 0;
font-size: 1rem;
font-weight: 600;
}
.vc-map__scope-tabs {
display: flex;
gap: 6px;
}
.vc-map__scope-tab {
padding: 4px 10px;
border-radius: 12px;
border: 1px solid var(--border-default);
font-size: 0.78rem;
background: var(--bg-elevated);
}
.vc-map__scope-tab.active {
border-color: var(--accent-primary);
color: var(--accent-primary);
}
.vc-map__scopes {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(480px, 1fr));
gap: 10px;
}
.vc-map__scope-panel {
border: 1px solid var(--border-default);
border-radius: 8px;
padding: 10px;
background: var(--bg-primary);
display: flex;
flex-direction: column;
gap: 8px;
}
.vc-map__scope-header {
display: flex;
align-items: center;
gap: 6px;
}
.vc-map__scope-header small {
color: var(--text-muted);
}
.vc-map__source-groups {
display: flex;
flex-direction: column;
gap: 8px;
}
.vc-map__split-editor-wrapper {
display: flex;
flex-direction: column;
gap: 6px;
padding: 10px;
border: 2px solid var(--accent-primary);
border-radius: 8px;
background: var(--bg-elevated);
}
.vc-map__split-editor-close {
display: flex;
justify-content: flex-end;
}
.vc-map__split-editor-close button {
padding: 4px 12px;
border: 1px solid var(--border-default);
border-radius: 4px;
background: var(--bg-primary);
cursor: pointer;
font-size: 0.8rem;
}
.vc-map__merge-preview {
border: 1px solid var(--border-default);
border-radius: 8px;
padding: 10px;
display: flex;
flex-direction: column;
gap: 8px;
}
.vc-map__merge-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.vc-map__merge-toolbar h4 {
margin: 0;
font-size: 0.9rem;
}
.vc-map__merge-toolbar button {
padding: 6px 12px;
border: 1px solid var(--border-default);
border-radius: 6px;
background: var(--bg-primary);
cursor: pointer;
}
.vc-map__merge-toolbar button:disabled { opacity: 0.6; cursor: not-allowed; }
</style>
@@ -1,393 +0,0 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingSection.vue
用途:三来源通用配置区(Header/Table/Vendor Comments 每来源的开关+target_scope+relation_policy+missing_relation+format_policy),
不包含拆分规则编辑器(Vendor Comments 区的拆分规则编辑按钮仅触发 emit)。
依赖:shipping-order-document-profile.vc.types.ts Section B/D/I;
由 VcSourceMappingPanel.vue 薄编排主面板统一编排事件。
逻辑:任何字段变化通过 update:mapping 发射完整 mapping 对象;
Vendor Comments 点击「编辑拆分规则」时触发 split-editor-open。
-->
<script setup lang="ts">
import { computed } from 'vue';
import type {
VCLineReferenceBasis,
VCMissingRelationPolicy,
VCProfileDefinitionExtensions,
VCProfileFieldSourceMapping,
VCRelationPolicy,
VCReservationFormatPolicy,
} from '@/features/admin/types/shipping-order-document-profile.vc.types';
const props = withDefaults(defineProps<{
kind: 'header_region' | 'table_column' | 'vendor_comments';
mapping: VCProfileFieldSourceMapping | null;
definition: VCProfileDefinitionExtensions;
readonly?: boolean;
showSplitRules?: boolean;
mappingId: string;
}>(), {
readonly: false,
showSplitRules: false,
});
const emit = defineEmits<{
'update:mapping': [mapping: VCProfileFieldSourceMapping];
'split-editor-open': [];
}>();
const enabledKey = computed<'header_source_enabled' | 'table_source_enabled' | 'vendor_comments_enabled'>(() => {
if (props.kind === 'header_region') return 'header_source_enabled';
if (props.kind === 'table_column') return 'table_source_enabled';
return 'vendor_comments_enabled';
});
const isEnabled = computed(() => props.mapping?.[enabledKey.value] ?? false);
function emitPatch(patch: Partial<VCProfileFieldSourceMapping>): void {
if (!props.mapping) return;
emit('update:mapping', { ...props.mapping, ...patch });
}
function toggleEnabled(enabled: boolean): void {
emitPatch({ [enabledKey.value]: enabled } as Partial<VCProfileFieldSourceMapping>);
}
const namedRegionOptions = computed(() => {
const map = props.definition?.named_regions || {};
return Object.values(map).map((nr) => ({
value: nr.region_id,
label: nr.label,
}));
});
const scopeOptions = [
{ value: 'header' as const, label: 'Header (订单头)' },
{ value: 'line' as const, label: 'Line (明细行)' },
];
const relationPolicyOptions: { value: VCRelationPolicy; label: string }[] = [
{ value: 'bind_target_line', label: '绑定目标行 (bind_target_line)' },
{ value: 'annotation_only', label: '仅备注 (annotation_only)' },
{ value: 'no_relation', label: '无关联 (no_relation)' },
];
const missingRelationPolicyOptions: { value: VCMissingRelationPolicy; label: string }[] = [
{ value: 'default_all_lines', label: '默认所有行 (default_all_lines)' },
{ value: 'default_header_only', label: '默认仅 Header (default_header_only)' },
{ value: 'fallback_single_line_when_no_reference', label: '无参考回退单行 (fallback_single_line_when_no_reference)' },
];
const lineReferenceBasisOptions: { value: VCLineReferenceBasis; label: string }[] = [
{ value: 'explicit_line_column', label: '显式行列号 (explicit)' },
{ value: 'profile_business_line_no', label: '业务行号 (profile_business_line_no)' },
{ value: 'classified_logical_line_no', label: '分类逻辑行号 (classified_logical_line_no)' },
];
const kindLabel = computed(() => {
if (props.kind === 'header_region') return 'Header 来源';
if (props.kind === 'table_column') return 'Table 来源';
return 'Vendor Comments 来源';
});
const sourceClass = computed(() => {
if (props.kind === 'header_region') return 'vc-map__source--header';
if (props.kind === 'table_column') return 'vc-map__source--table';
return 'vc-map__source--vc';
});
function updateFormatPolicy(policy: Partial<VCReservationFormatPolicy>): void {
if (!props.mapping) return;
const next: VCReservationFormatPolicy = {
...props.mapping.format_policy,
...policy,
};
emitPatch({ format_policy: next });
}
const targetScopeDisabled = computed(() => {
if (props.kind === 'table_column' || props.kind === 'vendor_comments') return true;
return false;
});
const showLineReferenceBasis = computed(() => {
return props.kind === 'table_column' || props.kind === 'vendor_comments';
});
</script>
<template>
<fieldset class="vc-map__source" :class="sourceClass">
<legend>
<label class="vc-map__toggle-label">
<input
type="checkbox"
:disabled="readonly"
:checked="isEnabled"
@change="toggleEnabled(($event.target as HTMLInputElement).checked)"
/>
{{ kindLabel }}
</label>
</legend>
<template v-if="isEnabled && mapping">
<template v-if="kind === 'header_region'">
<label>
Header 引用键
<input
:disabled="readonly"
:value="mapping.header_source_ref ?? ''"
placeholder="header_ref / 留空走自动检测"
@input="emitPatch({ header_source_ref: ($event.target as HTMLInputElement).value || null })"
/>
</label>
</template>
<template v-else-if="kind === 'table_column'">
<label>
列 column_code
<input
:disabled="readonly"
:value="mapping.table_column_code ?? ''"
placeholder="例如:reservation_id"
@input="emitPatch({ table_column_code: ($event.target as HTMLInputElement).value || null })"
/>
</label>
</template>
<template v-else-if="kind === 'vendor_comments'">
<label>
命名区域
<select
:disabled="readonly"
:value="mapping.vendor_comments_region_ref ?? ''"
@change="emitPatch({ vendor_comments_region_ref: ($event.target as HTMLSelectElement).value || null })"
>
<option value="">— 请选择命名区域 —</option>
<option v-for="opt in namedRegionOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
</select>
</label>
<div v-if="showSplitRules" class="vc-map__split-open-row">
<button
type="button"
:disabled="readonly"
class="vc-map__split-open-btn"
@click="emit('split-editor-open')"
>
编辑拆分规则…
</button>
<span v-if="mapping.vendor_comments_split_rule_set" class="vc-map__split-status-inline">
规则集:v{{ mapping.vendor_comments_split_rule_set.rule_version }}
· {{ mapping.vendor_comments_split_rule_set.status || 'draft' }}
</span>
<span v-else class="vc-map__split-status-inline vc-map__split-status--muted">
尚未配置规则集
</span>
</div>
</template>
<label>
目标作用域
<select
:disabled="readonly || targetScopeDisabled"
:value="targetScopeDisabled ? 'line' : mapping.target_scope"
@change="emitPatch({ target_scope: ($event.target as HTMLSelectElement).value as 'header' | 'line' })"
>
<option v-for="opt in scopeOptions" :key="opt.value" :value="opt.value">
{{ opt.label }}{{ targetScopeDisabled && opt.value === 'line' ? ' (默认)' : '' }}
</option>
</select>
</label>
<label>
关联策略
<select
:disabled="readonly"
:value="mapping.relation_policy"
@change="emitPatch({ relation_policy: ($event.target as HTMLSelectElement).value as VCRelationPolicy })"
>
<option v-for="opt in relationPolicyOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
</select>
</label>
<template v-if="showLineReferenceBasis">
<label>
行参考基准
<select
:disabled="readonly"
:value="mapping.line_reference_basis"
@change="emitPatch({ line_reference_basis: ($event.target as HTMLSelectElement).value as VCLineReferenceBasis })"
>
<option v-for="opt in lineReferenceBasisOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
</select>
</label>
</template>
<label>
缺关联策略
<select
:disabled="readonly"
:value="mapping.missing_relation_policy"
@change="emitPatch({ missing_relation_policy: ($event.target as HTMLSelectElement).value as VCMissingRelationPolicy })"
>
<option v-for="opt in missingRelationPolicyOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
</select>
</label>
<label class="vc-map__checkbox">
<input
type="checkbox"
:disabled="readonly"
:checked="mapping.fill_missing_from_other_sources ?? true"
@change="emitPatch({ fill_missing_from_other_sources: ($event.target as HTMLInputElement).checked })"
/>
fill_missing_from_other_sources(从其他来源补空)
</label>
<div class="vc-map__format-block">
<div class="vc-map__format-title">格式策略</div>
<div class="vc-map__format-radios">
<label class="vc-map__radio">
<input
type="radio"
:disabled="readonly"
:name="`format-mode-${kind}-${mappingId}`"
value="inherit_global"
:checked="mapping.format_policy.mode === 'inherit_global'"
@change="updateFormatPolicy({ mode: 'inherit_global' })"
/>
inherit_global(使用 Profile 全局设置)
</label>
<label class="vc-map__radio">
<input
type="radio"
:disabled="readonly"
:name="`format-mode-${kind}-${mappingId}`"
value="numeric_5_or_10"
:checked="mapping.format_policy.mode === 'numeric_5_or_10'"
@change="updateFormatPolicy({ mode: 'numeric_5_or_10' })"
/>
numeric_5_or_10(单号 5 或 10 位数字)
</label>
<label class="vc-map__radio">
<input
type="radio"
:disabled="readonly"
:name="`format-mode-${kind}-${mappingId}`"
value="custom_safe_regex"
:checked="mapping.format_policy.mode === 'custom_safe_regex'"
@change="updateFormatPolicy({ mode: 'custom_safe_regex' })"
/>
custom_safe_regex(自定义安全正则)
</label>
</div>
<template v-if="mapping.format_policy.mode === 'custom_safe_regex'">
<label>
pattern
<input
:disabled="readonly"
:value="mapping.format_policy.pattern ?? ''"
placeholder="例如:^[A-Z]?\d{5,10}$"
@input="updateFormatPolicy({ pattern: ($event.target as HTMLInputElement).value || null })"
/>
</label>
<label>
max_capture_groups
<input
type="number"
min="0"
:disabled="readonly"
:value="mapping.format_policy.max_capture_groups ?? 1"
@input="updateFormatPolicy({ max_capture_groups: Number(($event.target as HTMLInputElement).value) || 0 })"
/>
</label>
</template>
</div>
</template>
</fieldset>
</template>
<style scoped>
.vc-map__source {
border: 1px solid var(--border-default);
border-radius: 6px;
padding: 8px 10px;
margin: 0;
display: grid;
gap: 6px;
}
.vc-map__source--header { border-left: 4px solid #3b82f6; }
.vc-map__source--table { border-left: 4px solid #10b981; }
.vc-map__source--vc { border-left: 4px solid #f59e0b; }
.vc-map__source legend {
font-size: 0.82rem;
font-weight: 600;
padding: 0 4px;
}
.vc-map__toggle-label {
display: inline-flex;
align-items: center;
gap: 6px;
cursor: pointer;
font-weight: 600;
}
.vc-map__source label {
display: grid;
grid-template-columns: 110px 1fr;
align-items: center;
gap: 6px;
font-size: 0.8rem;
}
.vc-map__checkbox {
grid-template-columns: auto 1fr !important;
align-items: center;
}
.vc-map__radio {
grid-template-columns: auto 1fr !important;
align-items: center;
}
.vc-map__format-block {
grid-column: 1 / -1;
display: grid;
gap: 4px;
padding: 6px;
border: 1px dashed var(--border-default);
border-radius: 6px;
background: var(--bg-elevated);
}
.vc-map__format-title {
font-size: 0.8rem;
font-weight: 600;
color: var(--text-secondary);
}
.vc-map__format-radios {
display: flex;
flex-direction: column;
gap: 4px;
}
.vc-map__source select,
.vc-map__source input {
padding: 4px 6px;
border: 1px solid var(--border-default);
border-radius: 4px;
font-size: 0.8rem;
min-width: 0;
}
.vc-map__split-open-row {
grid-column: 1 / -1;
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.vc-map__split-open-btn {
padding: 4px 12px;
border: 1px solid var(--border-default);
border-radius: 4px;
background: var(--bg-primary);
cursor: pointer;
font-size: 0.8rem;
}
.vc-map__split-open-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.vc-map__split-status-inline {
font-size: 0.75rem;
color: var(--text-primary);
}
.vc-map__split-status--muted {
color: var(--text-muted);
}
</style>
@@ -1,921 +0,0 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/VcSplitRuleEditor.vue
用途:VC 专用拆分规则编辑器(只处理 Section C VCSplit* 类型,不引入任何 XfaSplit*)。
复用 XfaSplitRulePanel 的 addRule/matcherFromExtraction/preview/dirty banner 交互模式,
但所有类型、常量、stages 全部本地化,类型只用 vc.types.ts Section C。
依赖:shipping-order-document-profile.vc.types.ts Section C/J;
preview API 为本地 stub,标注后续接入 endpoint。
逻辑:split_rules 变化时 emit draftRequired,reason=split_rule_changed;
确认前必须先预览(needs_preview → diagnostics → confirm dialog → emit confirmed)。
-->
<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import type {
VCProfileDraftTrigger,
VCSplitEnginePreviewResult,
VCSplitMatcher,
VCSplitNormalization,
VCSplitRule,
VCSplitRuleSet,
VCSplitSegment,
} from '@/features/admin/types/shipping-order-document-profile.vc.types';
type ExtractionMode = 'select_line' | 'select_line_range' | 'extract_prefix' | 'regex_capture' | 'substring';
type VCSplitStageType =
| 'split_lines'
| 'select_line'
| 'select_line_range'
| 'extract_prefix'
| 'regex_capture'
| 'replace'
| 'substring'
| 'normalize';
interface VCSplitStage {
stage_id: string;
type: VCSplitStageType;
trim?: boolean;
remove_empty_lines?: boolean;
line_breaks?: string[];
line_index?: number;
line_start?: number;
line_end?: number;
join_with?: 'newline' | 'space' | 'comma';
value?: string;
separators?: string[];
case_sensitive?: boolean;
pattern?: string;
capture_group?: number;
find?: string;
replace_with?: string;
start?: number;
end?: number | null;
}
interface VCSplitRulePatch {
order?: number;
matcher?: VCSplitMatcher | null;
segment?: Partial<VCSplitSegment>;
}
const props = withDefaults(defineProps<{
ruleSet: VCSplitRuleSet | null;
selectedFieldCode: string;
documentId: number;
profileId: number;
readonly?: boolean;
dirtyUnsaved?: boolean;
persistedConfirmed?: boolean;
visible: boolean;
}>(), {
selectedFieldCode: 'reservation_id',
readonly: false,
dirtyUnsaved: false,
persistedConfirmed: false,
visible: false,
});
const emit = defineEmits<{
'update:ruleSet': [ruleSet: VCSplitRuleSet];
confirmed: [ruleSet: VCSplitRuleSet, previewToken: string];
draftRequired: [trigger: VCProfileDraftTrigger];
}>();
const message = useMessage();
function newClientId(prefix: 'rs' | 'rule' | 'seg' | 'stage'): string {
return `${prefix}-${crypto.randomUUID().replace(/-/g, '')}`;
}
const splitLoading = ref(false);
const splitPreview = ref<VCSplitEnginePreviewResult | null>(null);
const splitPreviewRuleSetHash = ref<string | null>(null);
const splitPreviewConfirmationToken = ref<string | null>(null);
const splitCollapsedRules = ref(new Set<string>());
const splitAdvancedRules = ref(new Set<string>());
const showUnsavedConfirmBanner = computed(() => props.dirtyUnsaved && props.persistedConfirmed === false);
function createDefaultStage(type: VCSplitStageType): VCSplitStage {
const stageId = newClientId('stage');
if (type === 'split_lines') {
return {
stage_id: stageId,
type,
trim: true,
remove_empty_lines: true,
line_breaks: ['\r\n', '\r', '\n'],
};
}
if (type === 'select_line') return { stage_id: stageId, type, line_index: 1 };
if (type === 'select_line_range') return { stage_id: stageId, type, line_start: 1, line_end: 2, join_with: 'newline' };
if (type === 'extract_prefix') return {
stage_id: stageId,
type,
value: '',
separators: [':', ':'],
case_sensitive: false,
};
if (type === 'regex_capture') return { stage_id: stageId, type, pattern: '', capture_group: 1 };
if (type === 'replace') return { stage_id: stageId, type, find: '', replace_with: '' };
if (type === 'substring') return { stage_id: stageId, type, start: 0, end: null };
return { stage_id: stageId, type: 'normalize', trim: true, remove_empty_lines: true };
}
function createDefaultPipelineStages(lineIndex = 1): VCSplitStage[] {
return [
createDefaultStage('split_lines'),
{ ...createDefaultStage('select_line'), line_index: lineIndex },
];
}
function matcherFromExtraction(mode: ExtractionMode, stage: Partial<VCSplitStage>, order: number): VCSplitMatcher {
if (mode === 'extract_prefix') {
return {
type: 'prefix',
value: String(stage.value || ''),
separators: (stage.separators && stage.separators.length) ? stage.separators : [':', ':'],
case_sensitive: Boolean(stage.case_sensitive),
};
}
if (mode === 'regex_capture') {
return {
type: 'regex',
pattern: String(stage.pattern || ''),
capture_group: stage.capture_group ?? 1,
case_sensitive: Boolean(stage.case_sensitive),
};
}
return {
type: 'position',
line_index: Number(stage.line_index || stage.line_start || order || 1),
};
}
function hashRuleSet(ruleSet: VCSplitRuleSet | null | undefined): string {
if (!ruleSet) return '';
return JSON.stringify(ruleSet);
}
function invalidatePreview(): void {
splitPreview.value = null;
splitPreviewRuleSetHash.value = null;
splitPreviewConfirmationToken.value = null;
}
function ensureRuleSet(): VCSplitRuleSet {
if (props.ruleSet) return props.ruleSet;
const ruleSet: VCSplitRuleSet = {
rule_set_id: newClientId('rs'),
rule_version: 1,
normalization: { trim: true, remove_empty_lines: true, line_breaks: ['\r\n', '\r', '\n'] },
rules: [],
unmatched_line_policy: 'evidence_only',
duplicate_match_policy: 'needs_review',
same_field_multiple_segment_policy: 'needs_review',
source: 'user',
status: 'draft',
requires_confirmation: true,
};
emit('update:ruleSet', ruleSet);
invalidatePreview();
emitDraftTriggerForSplitChanged();
return ruleSet;
}
function markRuleSetDirty(ruleSet: VCSplitRuleSet): VCSplitRuleSet {
const wasConfirmed = ruleSet.status === 'confirmed' || ruleSet.status === 'published';
return {
...ruleSet,
status: 'draft',
requires_confirmation: true,
rule_version: wasConfirmed ? ruleSet.rule_version + 1 : ruleSet.rule_version,
};
}
function normalizeRuleOrders(rules: VCSplitRule[]): VCSplitRule[] {
return [...rules]
.sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
.map((rule, index) => ({ ...rule, order: index + 1 }));
}
function writeRuleSet(ruleSet: VCSplitRuleSet, emitDraft = true): void {
emit('update:ruleSet', ruleSet);
invalidatePreview();
if (emitDraft) {
emitDraftTriggerForSplitChanged();
}
}
function applyRuleSetChange(updater: (ruleSet: VCSplitRuleSet) => VCSplitRuleSet): void {
const current = ensureRuleSet();
writeRuleSet(markRuleSetDirty(updater(current)));
}
function emitDraftTriggerForSplitChanged(): void {
const trigger: VCProfileDraftTrigger = {
named_regions_changed: false,
field_source_mappings_changed: true,
requires_draft_reset: true,
reasons: [{ kind: 'field_source_mapping_split_rule_changed' }],
};
emit('draftRequired', trigger);
}
function addRule(): void {
if (props.readonly) return;
const ruleSet = ensureRuleSet();
const order = (ruleSet.rules?.length || 0) + 1;
const stages = createDefaultPipelineStages(order);
const nextRule: VCSplitRule = {
rule_id: newClientId('rule'),
order,
matcher: matcherFromExtraction('select_line', stages[1] || {}, order),
segment: {
segment_id: newClientId('seg'),
segment_code: '',
display_name: '',
handling: 'evidence_only',
target_field_id: null,
target_field_code: props.selectedFieldCode,
note: null,
},
};
writeRuleSet(markRuleSetDirty({
...ruleSet,
rules: normalizeRuleOrders([...(ruleSet.rules || []), nextRule]),
}));
const next = new Set(splitCollapsedRules.value);
next.delete(nextRule.rule_id);
splitCollapsedRules.value = next;
}
function deleteRule(ruleId: string): void {
applyRuleSetChange((current) => ({
...current,
rules: normalizeRuleOrders(current.rules.filter((r) => r.rule_id !== ruleId)),
}));
const next = new Set(splitCollapsedRules.value);
next.delete(ruleId);
splitCollapsedRules.value = next;
}
function moveRule(ruleId: string, direction: 'up' | 'down'): void {
const current = ensureRuleSet();
const rules = [...current.rules];
const idx = rules.findIndex((r) => r.rule_id === ruleId);
if (idx < 0) return;
const swapIdx = direction === 'up' ? idx - 1 : idx + 1;
if (swapIdx < 0 || swapIdx >= rules.length) return;
const currentRule = rules[idx];
const swapRule = rules[swapIdx];
if (!currentRule || !swapRule) return;
[rules[idx], rules[swapIdx]] = [swapRule, currentRule];
applyRuleSetChange((rs) => ({ ...rs, rules: normalizeRuleOrders(rules) }));
}
function toggleRule(ruleId: string): void {
const next = new Set(splitCollapsedRules.value);
if (next.has(ruleId)) next.delete(ruleId);
else next.add(ruleId);
splitCollapsedRules.value = next;
}
function toggleAdvanced(ruleId: string): void {
const next = new Set(splitAdvancedRules.value);
if (next.has(ruleId)) next.delete(ruleId);
else next.add(ruleId);
splitAdvancedRules.value = next;
}
function extractionStage(rule: VCSplitRule): VCSplitStage {
if (rule.matcher?.type === 'prefix') {
return {
...createDefaultStage('extract_prefix'),
value: rule.matcher.value ?? undefined,
separators: rule.matcher.separators,
case_sensitive: rule.matcher.case_sensitive,
};
}
if (rule.matcher?.type === 'regex') {
return {
...createDefaultStage('regex_capture'),
pattern: rule.matcher.pattern ?? undefined,
capture_group: rule.matcher.capture_group ?? undefined,
case_sensitive: rule.matcher.case_sensitive,
};
}
if (rule.matcher?.type === 'position') {
return {
...createDefaultStage('select_line'),
line_index: rule.matcher.line_index ?? rule.order ?? 1,
};
}
return { ...createDefaultStage('select_line'), line_index: rule.order ?? 1 };
}
function extractionMode(rule: VCSplitRule): ExtractionMode {
if (rule.matcher?.type === 'prefix') return 'extract_prefix';
if (rule.matcher?.type === 'regex') return 'regex_capture';
if (rule.matcher?.type === 'position') return 'select_line';
return 'select_line';
}
function updateRule(ruleId: string, patch: VCSplitRulePatch): void {
applyRuleSetChange((current) => ({
...current,
rules: current.rules.map((rule) => {
if (rule.rule_id !== ruleId) return rule;
return {
...rule,
...patch,
segment: patch.segment ? { ...rule.segment, ...patch.segment } : rule.segment,
matcher: patch.matcher !== undefined ? patch.matcher : rule.matcher,
};
}),
}));
}
function changeExtractionMode(rule: VCSplitRule, mode: ExtractionMode): void {
const extraction = createDefaultStage(mode);
if (mode === 'select_line') extraction.line_index = rule.order ?? 1;
if (mode === 'select_line_range') {
extraction.line_start = rule.order ?? 1;
extraction.line_end = (rule.order ?? 1) + 1;
}
updateRule(rule.rule_id, {
matcher: matcherFromExtraction(mode, extraction, rule.order ?? 1),
});
}
function updateExtraction(rule: VCSplitRule, patch: Partial<VCSplitStage>): void {
const current = extractionStage(rule);
const nextStage = { ...current, ...patch };
const mode = extractionMode(rule);
updateRule(rule.rule_id, {
matcher: matcherFromExtraction(mode, nextStage, rule.order ?? 1),
});
}
function updateUnmatchedPolicy(policy: 'evidence_only' | 'needs_review'): void {
applyRuleSetChange((current) => ({ ...current, unmatched_line_policy: policy }));
}
function updateNormalization(patch: Partial<VCSplitNormalization>): void {
applyRuleSetChange((current) => ({
...current,
normalization: { ...(current.normalization || {}), ...patch },
}));
}
function previewValueFor(rule: VCSplitRule): string | null {
const segment = splitPreview.value?.segments?.find((s) => s.rule_id === rule.rule_id);
return segment ? (segment.normalized_text || segment.raw_text) : null;
}
function previewLineLabel(lineStart?: number | null, lineEnd?: number | null): string {
if (!lineStart) return '—';
return lineEnd && lineEnd !== lineStart ? `${lineStart}–${lineEnd}` : String(lineStart);
}
async function runPreview(): Promise<void> {
const ruleSet = ensureRuleSet();
splitLoading.value = true;
try {
// TODO: 后端 API stub,后续接入实际 endpoint
// 预期:POST /admin/shipping/document-profiles/{profileId}/documents/{documentId}/preview-split
// 请求体:{ rule_set: ruleSet, field_code: selectedFieldCode }
splitPreview.value = {
status: 'parsed',
rule_set_id: ruleSet.rule_set_id,
rule_version: ruleSet.rule_version,
mapped_fields: {},
segments: [],
evidence_only_segments: [],
diagnostics: [],
};
splitPreviewRuleSetHash.value = hashRuleSet(ruleSet);
splitPreviewConfirmationToken.value = `stub-${Date.now()}`;
} catch (error) {
message.error(error instanceof BusinessError ? error.message : '预览失败');
} finally {
splitLoading.value = false;
}
}
function confirmRules(): void {
const ruleSet = ensureRuleSet();
const currentHash = hashRuleSet(ruleSet);
if (!splitPreview.value || splitPreviewRuleSetHash.value !== currentHash || !splitPreviewConfirmationToken.value) {
message.error('确认前请先预览当前规则集');
return;
}
if (splitPreview.value.status === 'needs_review' || (splitPreview.value.diagnostics || []).length > 0) {
message.error('存在 needs_review 或诊断错误,无法确认');
return;
}
const confirmedRuleSet: VCSplitRuleSet = {
...ruleSet,
source: 'user',
status: 'confirmed',
requires_confirmation: false,
};
emit('update:ruleSet', confirmedRuleSet);
emit('confirmed', confirmedRuleSet, splitPreviewConfirmationToken.value);
}
function lineBreaksToDisplay(breaks: string[] | undefined): string {
return (breaks || []).map((item) => item
.replace(/\\/g, '\\\\')
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')).join(', ');
}
function parseLineBreaks(value: string): string[] {
return value.split(',')
.map((item) => item.trim())
.filter(Boolean)
.map((token) => token
.replace(/\\r\\n/g, '\r\n')
.replace(/\\n/g, '\n')
.replace(/\\r/g, '\r')
.replace(/\\t/g, '\t')
.replace(/\\\\/g, '\\'));
}
function separatorsToString(separators: string[] | undefined): string {
return (separators || []).join(', ');
}
function parseSeparators(value: string): string[] {
return value.split(',').map((item) => item.trim()).filter(Boolean);
}
watch(() => props.visible, (v) => {
if (v) {
ensureRuleSet();
}
});
</script>
<template>
<div v-if="visible" class="vc-split-editor">
<div v-if="showUnsavedConfirmBanner" class="vc-map__banner" role="status">
已确认的规则集有未保存改动,保存后将重置为 Draft。
</div>
<div class="vc-split-editor__header">
<h4>拆分规则编辑器 · {{ selectedFieldCode }}</h4>
<div class="vc-split-editor__toolbar">
<button
type="button"
:disabled="readonly"
@click="addRule()"
>
新增拆分规则
</button>
<button
type="button"
:disabled="splitLoading"
@click="runPreview()"
>
{{ splitLoading ? '预览中…' : '预览拆分' }}
</button>
<button
type="button"
:disabled="readonly || !splitPreview || !splitPreviewConfirmationToken"
@click="confirmRules()"
>
确认规则
</button>
<span class="vc-map__split-status">
状态:{{ ruleSet?.status || 'draft' }}
· v{{ ruleSet?.rule_version || 1 }}
</span>
</div>
</div>
<fieldset class="vc-map__split-ruleset">
<legend>规则集设置</legend>
<label>
未匹配策略
<select
:disabled="readonly"
:value="ruleSet?.unmatched_line_policy || 'evidence_only'"
@change="updateUnmatchedPolicy(($event.target as HTMLSelectElement).value as 'evidence_only' | 'needs_review')"
>
<option value="evidence_only">仅留证据 (evidence_only)</option>
<option value="needs_review">需复核 (needs_review)</option>
</select>
</label>
<div class="vc-map__split-normalization">
<label class="vc-map__checkbox">
<input
type="checkbox"
:disabled="readonly"
:checked="ruleSet?.normalization?.trim ?? true"
@change="updateNormalization({ trim: ($event.target as HTMLInputElement).checked })"
/>
trim
</label>
<label class="vc-map__checkbox">
<input
type="checkbox"
:disabled="readonly"
:checked="ruleSet?.normalization?.remove_empty_lines ?? true"
@change="updateNormalization({ remove_empty_lines: ($event.target as HTMLInputElement).checked })"
/>
去空行
</label>
<label>
换行
<input
:disabled="readonly"
:value="lineBreaksToDisplay(ruleSet?.normalization?.line_breaks)"
:placeholder="'\r\n, \r, \n'"
@change="updateNormalization({ line_breaks: parseLineBreaks(($event.target as HTMLInputElement).value) })"
/>
</label>
</div>
</fieldset>
<div v-if="splitPreview" class="vc-map__split-preview">
<h5>拆分预览(stub,后端 API 待接入)</h5>
<p>status: {{ splitPreview.status }}</p>
<table v-if="splitPreview.segments?.length" class="vc-map__table">
<thead>
<tr>
<th>行</th><th>segment_code</th><th>提取方式</th><th>识别值</th>
</tr>
</thead>
<tbody>
<tr v-for="seg in splitPreview.segments" :key="seg.segment_id">
<td>{{ previewLineLabel(seg.line_no, seg.line_end_no) }}</td>
<td>{{ seg.segment_code }}</td>
<td>{{ seg.matcher_type }}</td>
<td>{{ seg.normalized_text || seg.raw_text }}</td>
</tr>
</tbody>
</table>
<ul v-if="splitPreview.diagnostics?.length" class="vc-map__diagnostics">
<li v-for="(d, i) in splitPreview.diagnostics" :key="i">
<strong>{{ d.code }}</strong>: {{ d.message }}
</li>
</ul>
</div>
<ul class="vc-map__split-rules">
<li
v-for="(rule, idx) in (ruleSet?.rules || [])"
:key="rule.rule_id"
>
<div class="vc-map__split-rule-header">
<button type="button" class="vc-map__split-rule-title" @click="toggleRule(rule.rule_id)">
<span>{{ splitCollapsedRules.has(rule.rule_id) ? '›' : '⌄' }}</span>
<strong>规则 {{ idx + 1 }}</strong>
<span>{{ rule.segment.display_name || rule.segment.segment_code || '未命名' }}</span>
</button>
<div class="vc-map__split-rule-actions">
<button
type="button"
:disabled="readonly || idx === 0"
@click="moveRule(rule.rule_id, 'up')"
>
↑
</button>
<button
type="button"
:disabled="readonly || idx === (ruleSet?.rules?.length || 0) - 1"
@click="moveRule(rule.rule_id, 'down')"
>
↓
</button>
<button
type="button"
:disabled="readonly"
@click="toggleAdvanced(rule.rule_id)"
>
{{ splitAdvancedRules.has(rule.rule_id) ? '高级 ▾' : '高级 ▸' }}
</button>
<button
type="button"
class="danger"
:disabled="readonly"
@click="deleteRule(rule.rule_id)"
>
删除
</button>
</div>
</div>
<div v-if="!splitCollapsedRules.has(rule.rule_id)" class="vc-map__split-rule-detail">
<label>
segment_code
<input
:disabled="readonly"
:value="rule.segment.segment_code"
@input="updateRule(rule.rule_id, { segment: { segment_code: ($event.target as HTMLInputElement).value } })"
/>
</label>
<label>
display_name
<input
:disabled="readonly"
:value="rule.segment.display_name"
@input="updateRule(rule.rule_id, { segment: { display_name: ($event.target as HTMLInputElement).value } })"
/>
</label>
<label>
提取方式
<select
:disabled="readonly"
:value="extractionMode(rule)"
@change="changeExtractionMode(rule, ($event.target as HTMLSelectElement).value as ExtractionMode)"
>
<option value="select_line">按行号 (position)</option>
<option value="extract_prefix">按前缀标签 (prefix)</option>
<option value="regex_capture">按正则捕获 (regex)</option>
</select>
</label>
<label v-if="extractionMode(rule) === 'select_line'">
行号
<input
type="number"
min="1"
:disabled="readonly"
:value="extractionStage(rule).line_index ?? (rule.order ?? 1)"
@input="updateExtraction(rule, { line_index: Number(($event.target as HTMLInputElement).value) || 1 })"
/>
</label>
<template v-if="extractionMode(rule) === 'extract_prefix'">
<label>
前缀
<input
:disabled="readonly"
:value="extractionStage(rule).value || ''"
@input="updateExtraction(rule, { value: ($event.target as HTMLInputElement).value })"
/>
</label>
<label>
分隔符
<input
:disabled="readonly"
:value="separatorsToString(extractionStage(rule).separators)"
@input="updateExtraction(rule, { separators: parseSeparators(($event.target as HTMLInputElement).value) })"
/>
</label>
</template>
<template v-if="extractionMode(rule) === 'regex_capture'">
<label>
正则
<input
:disabled="readonly"
:value="extractionStage(rule).pattern || ''"
@input="updateExtraction(rule, { pattern: ($event.target as HTMLInputElement).value })"
/>
</label>
<label>
捕获组
<input
type="number"
min="0"
:disabled="readonly"
:value="extractionStage(rule).capture_group ?? 1"
@input="updateExtraction(rule, { capture_group: Number(($event.target as HTMLInputElement).value) || 0 })"
/>
</label>
</template>
<div v-if="splitAdvancedRules.has(rule.rule_id)" class="vc-map__split-rule-advanced">
<label>
handling
<select
:disabled="readonly"
:value="rule.segment.handling"
@change="updateRule(rule.rule_id, { segment: { handling: ($event.target as HTMLSelectElement).value as 'mapped' | 'evidence_only' } })"
>
<option value="evidence_only">仅证据 (evidence_only)</option>
<option value="mapped">映射字段 (mapped)</option>
</select>
</label>
<label>
note
<input
:disabled="readonly"
:value="rule.segment.note || ''"
@input="updateRule(rule.rule_id, { segment: { note: ($event.target as HTMLInputElement).value || null } })"
/>
</label>
</div>
<div class="vc-map__split-inline-preview">
<span>识别值:</span>
<strong v-if="previewValueFor(rule)">{{ previewValueFor(rule) }}</strong>
<span v-else>需预览</span>
</div>
</div>
</li>
</ul>
</div>
</template>
<style scoped>
.vc-split-editor {
display: flex;
flex-direction: column;
gap: 10px;
padding: 10px;
border: 1px solid var(--border-default);
border-radius: 8px;
background: var(--bg-primary);
}
.vc-split-editor__header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
flex-wrap: wrap;
}
.vc-split-editor__header h4 {
margin: 0;
font-size: 0.95rem;
}
.vc-split-editor__toolbar {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.vc-split-editor__toolbar button {
padding: 4px 10px;
border: 1px solid var(--border-default);
border-radius: 4px;
background: var(--bg-primary);
cursor: pointer;
font-size: 0.78rem;
}
.vc-split-editor__toolbar button:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.vc-map__banner {
padding: 8px 10px;
border-radius: 6px;
background: var(--status-warning-bg);
color: var(--status-warning-fg);
font-size: 0.85rem;
}
.vc-map__split-status {
margin-left: auto;
font-size: 0.75rem;
color: var(--text-muted);
}
.vc-map__split-ruleset {
display: flex;
flex-direction: column;
gap: 4px;
padding: 6px;
border: 1px solid var(--border-default);
border-radius: 6px;
}
.vc-map__split-ruleset legend {
font-size: 0.8rem;
font-weight: 600;
padding: 0 4px;
}
.vc-map__split-normalization {
display: flex;
flex-direction: column;
gap: 4px;
}
.vc-map__checkbox {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 0.8rem;
}
.vc-map__split-preview {
padding: 6px;
border: 1px solid var(--border-default);
border-radius: 6px;
font-size: 0.78rem;
background: var(--bg-primary);
}
.vc-map__split-preview h5 {
margin: 0 0 6px 0;
font-size: 0.82rem;
}
.vc-map__table {
width: 100%;
border-collapse: collapse;
font-size: 0.78rem;
}
.vc-map__table th,
.vc-map__table td {
border: 1px solid var(--border-default);
padding: 4px 6px;
text-align: left;
vertical-align: top;
}
.vc-map__table th {
background: var(--bg-elevated);
}
.vc-map__diagnostics {
list-style: none;
padding: 0;
margin: 6px 0 0 0;
color: var(--text-danger);
}
.vc-map__split-rules {
list-style: none;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
gap: 6px;
}
.vc-map__split-rules > li {
border: 1px solid var(--border-default);
border-radius: 6px;
background: var(--bg-primary);
}
.vc-map__split-rule-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 6px;
padding: 6px 8px;
}
.vc-map__split-rule-title {
display: inline-flex;
align-items: center;
gap: 6px;
background: none;
border: none;
cursor: pointer;
padding: 2px 4px;
font-size: 0.82rem;
}
.vc-map__split-rule-title span {
font-family: monospace;
}
.vc-map__split-rule-actions {
display: flex;
gap: 4px;
}
.vc-map__split-rule-actions button {
padding: 2px 8px;
border: 1px solid var(--border-default);
border-radius: 4px;
background: var(--bg-primary);
cursor: pointer;
font-size: 0.75rem;
}
.vc-map__split-rule-actions button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.vc-map__split-rule-actions .danger {
color: var(--text-danger);
}
.vc-map__split-rule-detail {
padding: 6px 8px;
border-top: 1px dashed var(--border-default);
display: grid;
gap: 6px;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.vc-map__split-rule-detail label {
display: grid;
grid-template-columns: 100px 1fr;
align-items: center;
gap: 6px;
font-size: 0.78rem;
}
.vc-map__split-rule-detail select,
.vc-map__split-rule-detail input,
.vc-map__split-ruleset select,
.vc-map__split-ruleset input {
padding: 4px 6px;
border: 1px solid var(--border-default);
border-radius: 4px;
font-size: 0.78rem;
}
.vc-map__split-rule-advanced {
grid-column: 1 / -1;
display: grid;
gap: 6px;
grid-template-columns: repeat(2, minmax(0, 1fr));
padding: 6px;
border: 1px dashed var(--border-default);
border-radius: 4px;
background: var(--bg-elevated);
}
.vc-map__split-inline-preview {
grid-column: 1 / -1;
font-size: 0.78rem;
color: var(--text-muted);
}
.danger { color: var(--text-danger); }
</style>
@@ -546,6 +546,28 @@ describe('XfaSplitRulePanel', () => {
]);
});
it('keeps advanced processing attached to a position matcher rule', async () => {
const ruleSet = makePipelineRuleSet({
rules: [{
...makePipelineRuleSet().rules[0],
matcher: { type: 'position', line_index: 3 },
}],
});
const wrapper = mountPanel({
definition: { ...baseDefinition, split_rules: [ruleSet] },
});
const advancedButton = wrapper.findAll('button').find((btn) => btn.text().includes('高级处理'));
await advancedButton!.trigger('click');
const addAdvanced = wrapper.find('.xfa-split__add-stage-select');
await addAdvanced.setValue('extract_prefix');
await addAdvanced.trigger('change');
const emitted = wrapper.emitted('update:split-rules');
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
expect(last?.[0]?.rules[0]?.stages.map((stage) => stage.type)).toEqual([
'split_lines', 'select_line', 'extract_prefix',
]);
});
it('adds a rule after mounting when autoAddRule is enabled', () => {
const wrapper = mountPanel({
autoAddRule: true,
@@ -577,6 +599,73 @@ describe('XfaSplitRulePanel', () => {
expect(previewMock).toHaveBeenCalledWith(85, expect.not.objectContaining({ reveal: expect.anything() }));
});
it('sends formal matcher post-processors instead of UI-only pipeline fields to preview', async () => {
previewMock.mockResolvedValue({
preview: { status: 'ok', mapped_fields: {}, segments: [], evidence_only_segments: [], diagnostics: [] },
});
const wrapper = mountPanel({
definition: {
...baseDefinition,
split_rules: [makePipelineRuleSet({
strategy: 'pipeline',
rules: [{
...makePipelineRuleSet().rules[0],
order: 3,
matcher: { type: 'position', line_index: 3 },
stages: [
{ stage_id: 'split', type: 'split_lines', line_breaks: ['\\n'] },
{ stage_id: 'line', type: 'select_line', line_index: 3 },
{ stage_id: 'mpn', type: 'extract_prefix', value: 'MPN', separators: [':', ':'] },
],
}],
})],
},
});
await exposedActions(wrapper).runPreview();
await flushPromises();
expect(previewMock).toHaveBeenCalledWith(85, expect.objectContaining({
rule_set: expect.objectContaining({
rules: [expect.objectContaining({
matcher: expect.objectContaining({
type: 'position',
line_index: 3,
post_processors: [{ type: 'prefix', value: 'MPN', separators: [':', ':'], case_sensitive: false }],
}),
})],
}),
}));
const request = previewMock.mock.calls[0]?.[1] as { rule_set: Record<string, unknown> };
expect(request.rule_set).not.toHaveProperty('strategy');
expect(request.rule_set.rules[0]).not.toHaveProperty('order');
expect(request.rule_set.rules[0]).not.toHaveProperty('stages');
});
it('reprojects saved formal post-processors into the advanced editor', async () => {
const wrapper = mountPanel({
definition: {
...baseDefinition,
split_rules: [makePipelineRuleSet({
rules: [{
...makePipelineRuleSet().rules[0],
stages: [],
matcher: {
type: 'position',
line_index: 3,
post_processors: [{ type: 'prefix', value: 'MPN', separators: [':', ':'] }],
},
}],
})],
},
});
const advancedButton = wrapper.findAll('button').find((btn) => btn.text().includes('高级处理'));
await advancedButton!.trigger('click');
expect(wrapper.findAll('input').some((input) => input.element.value === 'MPN')).toBe(true);
});
it('ignores exposed edit actions when canEdit is false', () => {
const wrapper = mountPanel({ canEdit: false });
exposedActions(wrapper).addRule();
@@ -2,8 +2,8 @@
features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue
用途:XFA 字段拆分规则编辑——matcher 优先(prefix/regex/position),兼容历史 stages[] 投影。
依赖:shipping-order-document-profile API、vue-i18n、Schema 字段列表。
逻辑:编辑 definition.split_rules;新增/改提取方式同步写入 matcher;stages 保留供 UI 与兼容预览;
确认前须预览当前 rule_set 哈希;预览直接返回完整识别值。
逻辑:编辑 definition.split_rules;新增/改提取方式同步写入 matcher;stages 仅保留编辑态;
预览和确认统一投影为正式 matcher DTO,确认前须校验同一正式 DTO 哈希。
-->
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
@@ -106,8 +106,38 @@ function newClientId(prefix: 'seg' | 'rule' | 'stage'): string {
* 对 rule_set 做 JSON 哈希,用于确认前校验预览是否针对当前规则集。
*/
function hashRuleSet(ruleSet: XfaSplitRuleSet | null | undefined): string {
if (!ruleSet) return '';
return JSON.stringify(ruleSet);
return JSON.stringify(toFormalRuleSet(ruleSet));
}
/**
* 将编辑器的历史 pipeline 投影为后端正式规则;不把 UI 排序/阶段字段送入业务契约。
* 当前已正式支持的高级语义只有“标签后取值”;其余高级阶段必须先在契约中实现,不能静默丢失。
*/
function toFormalRuleSet(ruleSet: XfaSplitRuleSet | null | undefined): Record<string, unknown> | null {
if (!ruleSet) return null;
const rules = (ruleSet.rules || []).map((rule) => {
const unsupported = advancedStages(rule).find((stage) => stage.type !== 'extract_prefix');
if (unsupported) {
throw new Error(`Unsupported formal post processor: ${unsupported.type}`);
}
const postProcessors = advancedStages(rule).map((stage) => ({
type: 'prefix' as const,
value: String(stage.value || ''),
separators: (stage.separators && stage.separators.length) ? stage.separators : [':', ':'],
case_sensitive: Boolean(stage.case_sensitive),
}));
return {
rule_id: rule.rule_id,
matcher: { ...(rule.matcher || matcherFromExtraction(extractionMode(rule), extractionStage(rule), rule.order || 1)), ...(postProcessors.length ? { post_processors: postProcessors } : {}) },
segment: rule.segment,
};
});
const { strategy: _strategy, rule_id, rule_set_id, ...formal } = ruleSet;
return {
...formal,
rule_set_id: rule_set_id || rule_id,
rules,
};
}
/**
@@ -275,9 +305,10 @@ async function runPreview(): Promise<void> {
if (!props.selectedPathId || !activeRuleSet.value || props.canPreview === false) return;
loading.value = true;
try {
const formalRuleSet = toFormalRuleSet(activeRuleSet.value);
const result = await previewOrderProfileSampleXfaSplitRules(props.documentId, {
path_id: props.selectedPathId,
rule_set: activeRuleSet.value as unknown as Record<string, unknown>,
rule_set: formalRuleSet || {},
profile_id: props.profileId,
});
preview.value = result.preview;
@@ -321,16 +352,16 @@ function confirmRules(): void {
diagnostics: diagCount,
});
if (!window.confirm(summary)) return;
const confirmedRuleSet: XfaSplitRuleSet = {
...activeRuleSet.value,
const confirmedRuleSet = {
...(toFormalRuleSet(activeRuleSet.value) || {}),
source: 'user',
status: 'confirmed',
requires_confirmation: false,
};
} as XfaSplitRuleSet;
const confirmedRules = [
...(props.definition.split_rules || []).filter(
(item) => item.source_path_id !== confirmedRuleSet.source_path_id,
),
...(props.definition.split_rules || [])
.filter((item) => item.source_path_id !== confirmedRuleSet.source_path_id)
.map((item) => toFormalRuleSet(item) as unknown as XfaSplitRuleSet),
confirmedRuleSet,
];
const tokens = { [confirmedRuleSet.source_path_id]: previewConfirmationToken.value };
@@ -403,6 +434,17 @@ function toggleAdvanced(ruleId: string): void {
/** 返回规则的业务提取步骤;优先由 matcher 合成,兼容历史 pipeline stages。 */
function extractionStage(rule: XfaSplitRule): XfaSplitStage {
// 优先使用持久化 stages 中的真实主提取阶段;position matcher 的兼容投影
// 不能通过临时 stage_id 定位,否则高级处理无法挂接到规则 2。
const stages = rule.stages || [];
const persisted = stages.find((stage) => (
stage.type === 'select_line'
|| stage.type === 'select_line_range'
|| stage.type === 'extract_prefix'
|| stage.type === 'regex_capture'
|| stage.type === 'substring'
));
if (persisted && (!rule.matcher || rule.matcher.type === 'position')) return persisted;
if (rule.matcher?.type === 'prefix') {
return {
...createDefaultStage('extract_prefix'),
@@ -425,14 +467,7 @@ function extractionStage(rule: XfaSplitRule): XfaSplitStage {
line_index: rule.matcher.line_index ?? rule.order ?? 1,
};
}
const stages = rule.stages || [];
return stages.find((stage) => (
stage.type === 'select_line'
|| stage.type === 'select_line_range'
|| stage.type === 'extract_prefix'
|| stage.type === 'regex_capture'
|| stage.type === 'substring'
)) || { ...createDefaultStage('select_line'), line_index: rule.order ?? 1 };
return { ...createDefaultStage('select_line'), line_index: rule.order ?? 1 };
}
function extractionMode(rule: XfaSplitRule): ExtractionMode {
@@ -449,15 +484,41 @@ function extractionMode(rule: XfaSplitRule): ExtractionMode {
/** 返回主提取之后顺序执行的高级处理步骤。 */
function advancedStages(rule: XfaSplitRule): XfaSplitStage[] {
const stages = rule.stages || [];
if (!stages.length) {
return (rule.matcher?.post_processors || []).map((processor, index) => ({
stage_id: `formal-${rule.rule_id}-post-${index}`,
type: 'extract_prefix' as const,
value: processor.value,
separators: processor.separators,
case_sensitive: processor.case_sensitive,
}));
}
const primary = extractionStage(rule);
const primaryIndex = stages.findIndex((stage) => stage.stage_id === primary.stage_id);
if (primaryIndex < 0) return [];
return stages.slice(primaryIndex + 1);
}
/** 将已保存的正式规则按需投影为可编辑 pipeline;只有用户编辑时才写回 stages。 */
function editableStages(rule: XfaSplitRule): XfaSplitStage[] {
if ((rule.stages || []).length) return rule.stages;
const primary = extractionStage(rule);
return [
{
stage_id: `formal-${rule.rule_id}-split`,
type: 'split_lines',
trim: true,
remove_empty_lines: true,
line_breaks: ['\r\n', '\r', '\n'],
},
{ ...primary, stage_id: `formal-${rule.rule_id}-primary` },
...advancedStages(rule),
];
}
/** 更换提取方式,同时同步正式 matcher 与兼容 stages。 */
function changeExtractionMode(rule: XfaSplitRule, mode: ExtractionMode): void {
const stages = rule.stages || [];
const stages = editableStages(rule);
const split = stages.find((stage) => stage.type === 'split_lines') || createDefaultStage('split_lines');
const advanced = advancedStages(rule);
const extraction = createDefaultStage(mode);
@@ -484,8 +545,8 @@ function updateExtraction(rule: XfaSplitRule, patch: XfaSplitStagePatch): void {
const nextStage = { ...current, ...patch };
const mode = extractionMode(rule);
updateRule(rule.rule_id, {
stages: (rule.stages || []).map((stage) => (
stage.stage_id === current.stage_id ? nextStage : stage
stages: editableStages(rule).map((stage) => (
stage.stage_id === current.stage_id || stage.type === current.type ? { ...nextStage, stage_id: stage.stage_id } : stage
)),
matcher: matcherFromExtraction(mode, nextStage, rule.order ?? 1),
});
@@ -587,7 +648,7 @@ function updateNormalization(patch: Partial<XfaSplitNormalization>): void {
function addStage(ruleId: string, type: XfaSplitStageType): void {
const rule = activeRuleSet.value?.rules.find((item) => item.rule_id === ruleId);
if (!rule) return;
updateRule(ruleId, { stages: [...(rule.stages || []), createDefaultStage(type)] });
updateRule(ruleId, { stages: [...editableStages(rule), createDefaultStage(type)] });
}
/**
@@ -595,8 +656,9 @@ function addStage(ruleId: string, type: XfaSplitStageType): void {
*/
function deleteStage(ruleId: string, stageId: string): void {
const rule = activeRuleSet.value?.rules.find((item) => item.rule_id === ruleId);
if (!rule || (rule.stages || []).length <= 1) return;
updateRule(ruleId, { stages: rule.stages.filter((item) => item.stage_id !== stageId) });
const stages = rule ? editableStages(rule) : [];
if (!rule || stages.length <= 1) return;
updateRule(ruleId, { stages: stages.filter((item) => item.stage_id !== stageId) });
}
/**
@@ -605,7 +667,7 @@ function deleteStage(ruleId: string, stageId: string): void {
function moveStage(ruleId: string, stageId: string, direction: -1 | 1): void {
const rule = activeRuleSet.value?.rules.find((item) => item.rule_id === ruleId);
if (!rule) return;
const stages = [...(rule.stages || [])];
const stages = [...editableStages(rule)];
const index = stages.findIndex((item) => item.stage_id === stageId);
const target = index + direction;
if (index < 0 || target < 0 || target >= stages.length) return;
@@ -624,7 +686,7 @@ function updateStage(ruleId: string, stageId: string, patch: XfaSplitStagePatch)
const rule = activeRuleSet.value?.rules.find((item) => item.rule_id === ruleId);
if (!rule) return;
updateRule(ruleId, {
stages: (rule.stages || []).map((stage) => (
stages: editableStages(rule).map((stage) => (
stage.stage_id === stageId ? { ...stage, ...patch } : stage
)),
});
@@ -365,7 +365,7 @@ describe('useOrderProfileValueAdapter', () => {
expect(payload?.definition.bindings.map((item) => item.binding_id)).toEqual(['customer-part', 'internal-part']);
});
it('blocks saving when an existing formal datasets binding has no shared visual layout', async () => {
it('restores a missing formal datasets visual layout from the last saved definition', async () => {
const enabled = ref(false);
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
@@ -378,6 +378,19 @@ describe('useOrderProfileValueAdapter', () => {
mount(Harness, { global: { plugins: [i18n] } });
await desk?.load();
await desk!.applySavedDraft({
id: 9,
lock_version: 2,
definition: {
...desk!.definition.value!,
order_field_layouts: [{
layout_id: 'xfa_header_currency', field_id: 'field-currency', field_code: 'currency', scope: 'header',
page_scope: 'exact_page', page_no: 1,
anchor_region: { x0: .1, y0: .1, x1: .2, y1: .15 },
fallback_value_region: { x0: .2, y0: .1, x1: .4, y1: .15 },
}],
},
} as unknown as import('@/features/admin/types/shipping-order-document-profile.types').ShippingOrderDocumentProfile);
desk!.authoritativePathId.value = 'root';
desk!.definition.value = {
...desk!.definition.value!,
@@ -394,8 +407,13 @@ describe('useOrderProfileValueAdapter', () => {
const payload = desk!.buildDraftPayload(visualDefinition);
// 关键断言:正式 datasets binding 不得因本次画布缺少其共同框而被静默删除。
expect(payload).toBeNull();
// 关键断言:正式 datasets binding 的共享框从已保存定义恢复,不再阻断或静默删除。
expect(payload?.definition.order_field_layouts).toEqual(expect.arrayContaining([
expect.objectContaining({ layout_id: 'xfa_header_currency', field_code: 'currency' }),
]));
expect(payload?.definition.bindings).toEqual(expect.arrayContaining([
expect.objectContaining({ binding_id: 'currency-binding', field_layout_id: 'xfa_header_currency' }),
]));
});
it('carries an explicit formal binding deletion through the save payload', async () => {
@@ -487,6 +487,25 @@ export function useOrderProfileValueAdapter(options: UseOrderProfileValueAdapter
header_layouts: (table.header_layouts || []).map(restoreTableLayoutFields),
line_layouts: (table.line_layouts || []).map(restoreTableLayoutFields),
}));
// 正式 datasets binding 的 field_layout_id 是视觉框的稳定身份。当前画布可能因
// 自动标注替换、短暂渲染状态或误删遗漏该框;此时恢复最后成功保存的同 ID 订单字段框,
// 而不是每次自动保存都报错。显式解绑会先移除 binding,不会走此恢复路径。
const savedOrderFieldLayouts = savedSnapshot.value?.order_field_layouts || [];
const currentOrderFieldLayoutIds = new Set(
restoredOrderFieldLayouts.map((layout) => String(layout.layout_id || '')),
);
const missingBoundOrderFieldLayoutIds = new Set(
(definition.value.bindings || [])
.filter((binding) => Boolean(binding.value_binding?.path_id?.trim()))
.map((binding) => String(binding.field_layout_id || '').trim())
.filter((layoutId) => layoutId && !currentOrderFieldLayoutIds.has(layoutId)),
);
for (const layout of savedOrderFieldLayouts) {
const layoutId = String(layout.layout_id || '').trim();
if (!layoutId || !missingBoundOrderFieldLayoutIds.has(layoutId)) continue;
restoredOrderFieldLayouts.push(cloneXfaData(layout));
currentOrderFieldLayoutIds.add(layoutId);
}
// 共同视觉身份既包含订单字段,也包含每个明细行布局中的字段;XFA 只能在这份
// 既有身份上追加 datasets path,不能只保存订单字段而让明细 binding 静默丢失。
const sharedLayouts = [
@@ -6,6 +6,7 @@
*/
import { describe, expect, it } from 'vitest';
import { reactive } from 'vue';
import {
mergeOrderProfileHeaderLabels,
restoreOrderProfileRegionPageNo,
@@ -13,19 +14,76 @@ import {
shouldShowStandardOrderProfilePreview,
toOrderProfileAnchorId,
buildOrderProfileRecognitionResults,
buildOrderProfileCanvasLineFieldValues,
selectCurrentDatasetsValidationEvidence,
normalizeOrderProfileRelativeRegion,
restoreReservationIdRegion,
groupUniqueOrderProfileLineFields,
restoreFormalBindingFieldCodes,
reconcileAutomarkOrderFieldRegions,
buildAutomarkSuggestedRegions,
normalizeAutomarkFieldCandidates,
preferredAutomarkTableSource,
selectAutomarkReconstruction,
summarizeAutomarkTableCandidates,
toOrderProfileHeaderFieldRegion,
resolveCoordinateFieldScope,
isOrderProfileVisualFieldEligible,
buildAutomarkSuggestionSummary,
} from './orderProfileForm.utils';
describe('order profile form rules', () => {
it('restores a Reservation ID region from a Vue reactive profile without structured-clone failure', () => {
const persisted = reactive({
region: { x0: .05, y0: .71, x1: .28, y1: .73 },
page_scope: 'exact_page' as const,
page_no: 1,
});
const restored = restoreReservationIdRegion(persisted);
// 关键断言:接口列表响应被 Vue 包装为 Proxy 后,重新打开草稿仍须恢复为可编辑的普通坐标对象。
expect(restored).toEqual({
region: { x0: .05, y0: .71, x1: .28, y1: .73 },
page_scope: 'exact_page',
page_no: 1,
});
});
it('keeps an automark suggestion audit identity frozen after the canvas page changes', () => {
const frozenContext = {
documentId: 285,
tableId: 'mineru-table-84a701e5693e0907',
pageNo: 1,
automarkJobId: 7267,
};
const summary = buildAutomarkSuggestionSummary(frozenContext, {
regionCount: 3,
regionKinds: ['line', 'field', 'field'],
evidenceSourceRequired: false,
selectedEvidenceSource: 'pdf_coordinate',
selectedFieldEvidenceSources: {},
});
// 翻页会更新当前画布状态,但接受建议必须仍携带入队时冻结的 Job 身份。
expect(summary).toMatchObject({
document_id: 285,
table_id: 'mineru-table-84a701e5693e0907',
page_no: 1,
automark_job_id: 7267,
});
});
it('preselects native PDF evidence while allowing OCR fallback', () => {
// 关键断言:PDF 只是默认建议;候选列表仍保留 OCR,供人工切换复核。
expect(preferredAutomarkTableSource([
{ source: 'ocr_coordinate' }, { source: 'pdf_coordinate' },
])).toBe('pdf_coordinate');
expect(preferredAutomarkTableSource([{ source: 'ocr_coordinate' }])).toBe('ocr_coordinate');
expect(preferredAutomarkTableSource([])).toBe('');
});
it('keeps datasets-only Schema fields available for XFA visual positioning only', () => {
const datasetsOnly = { enabled: true, allowed_sources: ['xfa_dataset'] };
@@ -372,6 +430,131 @@ describe('order profile form rules', () => {
});
});
it('projects Reservation evidence to the header or its referenced logical line', () => {
const results = buildOrderProfileRecognitionResults([], [], {
table_id: 'table-1', row_count: 3, column_count: 1,
rows: [['part_number'], ['PN-1'], ['PN-2']],
row_roles: ['header', 'data', 'data'], source_row_indices: [[], [1], [2]], status: 'needs_review',
}, 'ready', null, [
{ value: '33008', line_no: null, scope: 'header', raw_text: 'Reservation#33008', status: 'header' },
{ value: '3000098851', line_no: 1, scope: 'line', raw_text: 'Reservation#3000098851 for line#1', status: 'mapped' },
]);
// 无行号值必须显示在订单表头;带行号值只显示在对应的逻辑明细行。
expect(results.header).toContainEqual(expect.objectContaining({
fieldCode: 'reservation_id', value: '33008', status: 'read',
}));
expect(results.line).toContainEqual(expect.objectContaining({
fieldCode: 'reservation_id', value: '3000098851', rowNo: 1, status: 'read',
}));
expect(results.line).not.toContainEqual(expect.objectContaining({
fieldCode: 'reservation_id', rowNo: 2,
}));
});
it('does not project a Widget row that overlaps the fused table header as a line field', () => {
const regions = buildAutomarkSuggestedRegions({
reconstruction: {
table_id: 'table-1', status: 'needs_review',
header_regions: [{
region: { x0: .1, y0: .15, x1: .9, y1: .2 },
fields: [{
text: 'ITEM', field_code: 'line_no',
region: { x0: .1, y0: .15, x1: .3, y1: .2 },
}],
}],
// 动态 XFA 的表头控件带有展示值时,Widget 几何会把它误聚为首条明细行。
subrow_layouts: [{
row_offset: 0, column_boundaries: [0, .25, 1],
region: { x0: .1, y0: .15, x1: .9, y1: .2 },
suggested_field_codes: ['line_no', null],
}],
},
orderFieldCandidates: [], pageNo: 1,
unboundColumnLabel: (count) => `Unbound ${count}`,
lineLabel: (count) => `Line ${count}`,
});
// 表头视觉证据已存在时,同一 y 带不能再成为可保存的明细布局。
expect(regions.filter((region) => region.kind === 'header_field')).toHaveLength(1);
expect(regions.some((region) => region.kind === 'line' || region.kind === 'field')).toBe(false);
});
it('maps reconstructed line values to canvas field region ids', () => {
const values = buildOrderProfileCanvasLineFieldValues([
{ id: 'line_1_1-field-0', kind: 'field', label: 'customer_po_line_no', fieldCode: 'customer_po_line_no', pageNo: 1, parentId: 'line_1_1', region: { x0: .1, y0: .3, x1: .2, y1: .4 } },
{ id: 'line_1_1-field-1', kind: 'field', label: 'qty', fieldCode: 'qty', pageNo: 1, parentId: 'line_1_1', region: { x0: .2, y0: .3, x1: .3, y1: .4 } },
], {
table_id: 'table-1', row_count: 2, column_count: 2,
rows: [['customer_po_line_no', 'qty'], ['10', '3.000']],
row_roles: ['header', 'data'], source_row_indices: [[], [1]], status: 'needs_review',
});
expect(values).toEqual({
'line_1_1-field-0': '10',
'line_1_1-field-1': '3.000',
});
});
it('restores a formal datasets field only for the same automark line and column', () => {
const existing = [{
id: 'line_1_1-field-2', kind: 'field' as const, parentId: 'line_1_1',
fieldCode: 'qty', label: 'qty', pageNo: 1,
region: { x0: .3, y0: .3, x1: .4, y1: .4 },
}];
const suggested = [{
id: 'line_1_1-field-2', kind: 'field' as const, parentId: 'line_1_1',
fieldCode: null, label: 'Unbound 2', pageNo: 1,
region: { x0: .3, y0: .3, x1: .4, y1: .4 },
}, {
id: 'line_1_1-field-3', kind: 'field' as const, parentId: 'line_1_1',
fieldCode: null, label: 'Unbound 3', pageNo: 1,
region: { x0: .4, y0: .3, x1: .5, y1: .4 },
}];
const restored = restoreFormalBindingFieldCodes(existing, suggested, new Set(['line_1_1:qty']));
// 关键断言:同一稳定区域才可恢复字段身份,新增列仍保持待人工绑定。
expect(restored.map((region) => region.fieldCode)).toEqual(['qty', null]);
});
it('reuses an existing formal XFA order-field identity instead of adding a duplicate', () => {
const existing = [{
id: 'order_field_1_7', kind: 'order_field' as const, label: 'PO', pageNo: 1,
orderFieldId: 'order_field_1_7', fieldCode: 'customer_po_number',
region: { x0: .4, y0: .1, x1: .8, y1: .16 },
}];
const suggested = [{
id: 'order_field_1_customer_po_number_1', kind: 'order_field' as const, label: 'PO', pageNo: 1,
orderFieldId: 'order_field_1_customer_po_number_1', fieldCode: 'customer_po_number',
region: { x0: .4, y0: .1, x1: .8, y1: .16 },
}];
const reconciled = reconcileAutomarkOrderFieldRegions(existing, suggested);
// 关键断言:同页、同字段、同视觉框必须继续使用正式 datasets 引用的 layout ID。
expect(reconciled[0]).toMatchObject({ id: 'order_field_1_7', orderFieldId: 'order_field_1_7' });
});
it('does not reuse a formal identity when the same field moved to a different visual box', () => {
const existing = [{
id: 'order_field_1_7', kind: 'order_field' as const, label: 'PO', pageNo: 1,
orderFieldId: 'order_field_1_7', fieldCode: 'customer_po_number',
region: { x0: .4, y0: .1, x1: .8, y1: .16 },
}];
const suggested = [{
id: 'order_field_1_customer_po_number_1', kind: 'order_field' as const, label: 'PO', pageNo: 1,
orderFieldId: 'order_field_1_customer_po_number_1', fieldCode: 'customer_po_number',
region: { x0: .4, y0: .3, x1: .8, y1: .36 },
}];
const reconciled = reconcileAutomarkOrderFieldRegions(existing, suggested);
// 关键断言:视觉位置发生实质变化时保留新候选,避免把正式绑定静默迁移到错误区域。
expect(reconciled[0]?.id).toBe('order_field_1_customer_po_number_1');
});
it('preserves the backend evidence source when projecting automark field candidates', () => {
const candidates = normalizeAutomarkFieldCandidates([{
candidate_kind: 'field_binding',
@@ -112,6 +112,88 @@ export const groupUniqueOrderProfileLineFields = (
return { fieldsByLayout, boundRegionIds };
};
/**
* 在接受新自动标注前恢复已有 XFA 正式绑定的共同视觉字段身份。
* 核心逻辑:只允许同一行布局、同一自动列序号的候选继承字段码;缺少该严格对应关系时
* 保持未绑定,避免把 datasets 正式路径错误迁移到另一列。
* @param existingRegions - 当前已保存或待保存的画布区域。
* @param suggestedRegions - 当前待接受的自动标注区域。
* @param formalBindingLayoutIds - 已存在正式 datasets binding 的 field_layout_id 集合。
* @returns 仅补回可严格证明身份的候选字段码。
*/
export const restoreFormalBindingFieldCodes = (
existingRegions: OrderProfileCanvasRegion[],
suggestedRegions: OrderProfileCanvasRegion[],
formalBindingLayoutIds: ReadonlySet<string>,
): OrderProfileCanvasRegion[] => {
const fieldCodeByRegionId = new Map<string, string>();
for (const region of existingRegions) {
if (region.kind !== 'field' || !region.parentId || !region.fieldCode) continue;
const layoutId = `${region.parentId}:${region.fieldCode}`;
if (formalBindingLayoutIds.has(layoutId)) fieldCodeByRegionId.set(region.id, region.fieldCode);
}
return suggestedRegions.map((region) => {
if (region.kind !== 'field' || region.fieldCode) return region;
const fieldCode = fieldCodeByRegionId.get(region.id);
return fieldCode ? { ...region, fieldCode } : region;
});
};
/** 自动候选与既有共同订单字段框被视为同一视觉证据的最小 IoU。 */
const AUTOMARK_ORDER_FIELD_IDENTITY_IOU = 0.98;
/**
* 将自动标注的共同订单字段对账到已有画布视觉身份。
* 核心逻辑:datasets binding 以 field_layout_id 引用视觉框。自动候选的临时 ID 不可
* 替代该身份;只有同页、同字段码且几何几乎完全一致时,才继承既有 layout ID。
* @param existingRegions - 当前画布中已保存的区域。
* @param suggestedRegions - 自动标注产生的待接受区域。
* @returns 复用既有 order_field ID 后的候选;坐标变化的候选保持原 ID 供人工复核。
*/
export const reconcileAutomarkOrderFieldRegions = (
existingRegions: OrderProfileCanvasRegion[],
suggestedRegions: OrderProfileCanvasRegion[],
): OrderProfileCanvasRegion[] => {
const usedExistingIds = new Set<string>();
const matchingExistingId = (suggested: OrderProfileCanvasRegion): string | null => {
if (suggested.kind !== 'order_field' || !suggested.fieldCode) return null;
const candidates = existingRegions.filter((existing) => {
if (usedExistingIds.has(existing.id) || existing.kind !== 'order_field') return false;
if (existing.pageNo !== suggested.pageNo || existing.fieldCode !== suggested.fieldCode) return false;
const left = Math.max(existing.region.x0, suggested.region.x0);
const top = Math.max(existing.region.y0, suggested.region.y0);
const right = Math.min(existing.region.x1, suggested.region.x1);
const bottom = Math.min(existing.region.y1, suggested.region.y1);
const intersection = Math.max(0, right - left) * Math.max(0, bottom - top);
const existingArea = Math.max(0, existing.region.x1 - existing.region.x0) * Math.max(0, existing.region.y1 - existing.region.y0);
const suggestedArea = Math.max(0, suggested.region.x1 - suggested.region.x0) * Math.max(0, suggested.region.y1 - suggested.region.y0);
const union = existingArea + suggestedArea - intersection;
return union > 0 && intersection / union >= AUTOMARK_ORDER_FIELD_IDENTITY_IOU;
});
if (candidates.length !== 1) return null;
usedExistingIds.add(candidates[0]!.id);
return candidates[0]!.id;
};
const layoutIds = new Map<string, string>();
suggestedRegions.forEach((region) => {
if (region.kind === 'order_field') {
const existingId = matchingExistingId(region);
if (existingId) layoutIds.set(region.id, existingId);
}
});
return suggestedRegions.map((region) => {
if (region.kind === 'order_field' && layoutIds.has(region.id)) {
const orderFieldId = layoutIds.get(region.id)!;
return { ...region, id: orderFieldId, orderFieldId };
}
if (region.kind === 'order_anchor' && region.orderFieldId && layoutIds.has(region.orderFieldId)) {
const orderFieldId = layoutIds.get(region.orderFieldId)!;
return { ...region, id: `${orderFieldId}_anchor`, orderFieldId };
}
return region;
});
};
/**
* 将画布或历史草稿的区域限制为页面归一化坐标。
* @param region - 可能来自拖拽、自动建议或历史模板的页面区域。
@@ -129,6 +211,65 @@ export const normalizeOrderProfileRelativeRegion = (
return x0 < x1 && y0 < y1 ? { x0, y0, x1, y1 } : null;
};
/**
* 从持久化定义恢复 Reservation ID 专用区域。
* 核心逻辑:Profile 列表被 Vue 包装后内部对象是 Proxy,不能直接传入 structuredClone;
* 此处只读取四个坐标值并构造普通对象,避免草稿重新打开时抛出 DataCloneError。
* @param rawRegion - 接口返回的 Reservation 区域,可为 Vue Proxy 或缺省值。
* @returns 可编辑的普通区域;定义缺失或坐标无效时返回 null。
*/
export const restoreReservationIdRegion = (rawRegion: unknown): {
region: OrderProfileRelativeRegion;
page_scope: 'exact_page';
page_no: number;
} | null => {
if (!rawRegion || typeof rawRegion !== 'object') return null;
const record = rawRegion as { region?: OrderProfileRelativeRegion; page_no?: unknown };
const region = record.region ? normalizeOrderProfileRelativeRegion(record.region) : null;
const pageNo = Number(record.page_no);
if (!region || !Number.isInteger(pageNo) || pageNo < 1) return null;
return { region, page_scope: 'exact_page', page_no: pageNo };
};
/** 自动标注任务启动时冻结的样本身份;候选在跨页浏览期间不得重新读取可变画布状态。 */
export interface AutomarkSuggestionContext {
documentId: number;
tableId: string;
pageNo: number;
automarkJobId: number | string;
}
/**
* 构造待确认自动标注的审计摘要。
* 核心逻辑:Job 已按 document/table/page 冻结证据身份;摘要必须复用同一身份,
* 防止管理员翻页或切换表格后,接受请求被服务端判定为另一份 Job 的候选。
* @param context - 自动标注入队并成功完成后冻结的样本、页面和 Job 身份。
* @param details - 可随管理员选择证据来源而更新的候选描述。
* @returns 后端 suggestion decision 契约所需的完整且稳定摘要。
*/
export const buildAutomarkSuggestionSummary = (
context: AutomarkSuggestionContext,
details: {
regionCount: number;
regionKinds: string[];
evidenceSourceRequired: boolean;
selectedEvidenceSource: string | null;
selectedFieldEvidenceSources: Record<string, string>;
},
): Record<string, unknown> => ({
algorithm_version: 'coordinate-suggest-v1',
kind: 'page_regions',
page_no: context.pageNo,
document_id: context.documentId,
table_id: context.tableId,
automark_job_id: context.automarkJobId,
region_count: details.regionCount,
region_kinds: details.regionKinds,
evidence_source_required: details.evidenceSourceRequired,
selected_evidence_source: details.selectedEvidenceSource,
selected_field_evidence_sources: details.selectedFieldEvidenceSources,
});
/**
* 将统一自动标记结果投影为画布区域。
* 核心逻辑:字段视觉候选与行重建是并行证据;行重建缺失时仍保留抬头字段框供人工复核,
@@ -146,6 +287,9 @@ export const buildAutomarkSuggestedRegions = (options: {
}): OrderProfileCanvasRegion[] => {
const { reconstruction, orderFieldCandidates, pageNo, unboundColumnLabel, lineLabel } = options;
const suggestedRegions: OrderProfileCanvasRegion[] = [];
const headerRegions = (reconstruction?.header_regions || [])
.map((header) => header.region)
.filter((region): region is OrderProfileRelativeRegion => Boolean(region));
for (const [index, header] of (reconstruction?.header_regions || []).entries()) {
const headerId = `header_${pageNo}_${index + 1}`;
for (const [fieldIndex, field] of (header.fields || []).entries()) {
@@ -177,7 +321,21 @@ export const buildAutomarkSuggestedRegions = (options: {
}
const layouts = (reconstruction?.subrow_layouts || []).slice().sort(
(left, right) => left.row_offset - right.row_offset,
);
).filter((layout) => {
const region = layout.region;
if (!region) return true;
return !headerRegions.some((headerRegion) => {
const horizontalOverlap = Math.max(0, Math.min(region.x1, headerRegion.x1) - Math.max(region.x0, headerRegion.x0));
const verticalOverlap = Math.max(0, Math.min(region.y1, headerRegion.y1) - Math.max(region.y0, headerRegion.y0));
const layoutWidth = region.x1 - region.x0;
const headerWidth = headerRegion.x1 - headerRegion.x0;
const layoutHeight = region.y1 - region.y0;
const headerHeight = headerRegion.y1 - headerRegion.y0;
return layoutWidth > 0 && headerWidth > 0 && layoutHeight > 0 && headerHeight > 0
&& horizontalOverlap / Math.min(layoutWidth, headerWidth) >= 0.8
&& verticalOverlap / Math.min(layoutHeight, headerHeight) >= 0.8;
});
});
for (const layout of layouts) {
const lineId = `line_${pageNo}_${layout.row_offset + 1}`;
const region = layout.region || {
@@ -273,6 +431,19 @@ export const summarizeAutomarkTableCandidates = (
});
};
/**
* 为多来源自动标注候选提供可审阅的默认来源。
* 原生 PDF 坐标是首选建议,但这只是预选,不绕过人工接受和 Review 门禁;
* 没有原生候选时才使用候选列表中的第一来源。
*/
export const preferredAutomarkTableSource = (
candidates: Array<{ source: string }>,
): string => (
candidates.find((candidate) => candidate.source === 'pdf_coordinate')?.source
|| candidates[0]?.source
|| ''
);
/**
* 将后端统一 field_binding DTO 转为旧页面候选形状,并保留真实证据来源。
* 核心逻辑:只接受视觉 binding;evidence_sources 为空时按不可确认处理,禁止默认宣称 native。
@@ -282,9 +453,11 @@ export const summarizeAutomarkTableCandidates = (
*/
export const normalizeAutomarkFieldCandidates = (
candidates: Array<Record<string, unknown>>,
): OrderFieldLayoutSuggestion[] => candidates
): OrderFieldLayoutSuggestion[] => {
const merged = new Map<string, OrderFieldLayoutSuggestion>();
candidates
.filter((item) => item.candidate_kind === 'field_binding' && item.binding && typeof item.binding === 'object')
.map((item) => {
.forEach((item) => {
const binding = item.binding as Record<string, unknown>;
const visual = binding.visual_binding && typeof binding.visual_binding === 'object'
? binding.visual_binding as Record<string, unknown> : {};
@@ -294,7 +467,7 @@ export const normalizeAutomarkFieldCandidates = (
const source = sources[0] === 'ocr_coordinate' || sources[0] === 'acroform_widget'
? sources[0] : 'pdf_coordinate';
const needsReview = item.needs_review === true || !sources.length;
return {
const next = {
field_id: String(binding.field_id || ''),
field_code: String(binding.field_code || ''),
// 未匹配的 XFA/AcroForm Widget 只有技术控件名和几何;它必须作为
@@ -308,7 +481,17 @@ export const normalizeAutomarkFieldCandidates = (
anchor_region: undefined,
value_region: visual.normalized_bbox as OrderProfileRelativeRegion | undefined,
} satisfies OrderFieldLayoutSuggestion;
const bbox = next.value_region;
const key = `${next.field_id}|${next.scope}|${JSON.stringify(bbox || {})}`;
const previous = merged.get(key);
if (previous) {
previous.issue = previous.issue || next.issue;
return;
}
merged.set(key, next);
});
return [...merged.values()];
};
/**
* 判断是否显示普通表格预览;可直接创建 Profile 的表格不受上一张表多物理行状态影响。
@@ -384,6 +567,48 @@ export interface OrderProfileRecognitionResult {
rowNo?: number;
}
/** Reservation 专用证据区域的后端统一候选;前端只按已给出的 scope 投影展示。 */
export interface ReservationRegionRecognitionCandidate {
value: string;
line_no: number | null;
scope: 'header' | 'line';
raw_text: string;
status: string;
}
/**
* 将坐标重建的首条数据行映射到画布上的明细字段框。
* @param pageRegions - 当前页画布区域。
* @param reconstruction - 坐标重建接口返回的表头与数据行。
* @returns region id 到当前样本明细值的映射;无值或无匹配框时不返回该项。
*/
export const buildOrderProfileCanvasLineFieldValues = (
pageRegions: OrderProfileCanvasRegion[],
reconstruction: CoordinateReconstructionPreview | null,
): Record<string, string> => {
const regionsByCode = new Map(
pageRegions
.filter((item) => item.kind === 'field' && item.fieldCode)
.reduce<[string, string][]>((entries, item) => {
if (!entries.some(([fieldCode]) => fieldCode === item.fieldCode)) {
entries.push([item.fieldCode!, item.id]);
}
return entries;
}, []),
);
if (!reconstruction) return {};
const fieldCodes = reconstruction.rows[0] || [];
const dataIndex = reconstruction.row_roles.findIndex((role, index) => index > 0 && role === 'data');
if (dataIndex < 0) return {};
return Object.fromEntries(
fieldCodes.flatMap((fieldCode, columnIndex) => {
const regionId = regionsByCode.get(fieldCode);
const value = reconstruction.rows[dataIndex]?.[columnIndex] || '';
return regionId && value ? [[regionId, value] as const] : [];
}),
);
};
/**
* 将已有坐标预览和值读取结果变为可反向定位的结构化复核项。
* @param pageRegions - 当前页画布区域;未标注字段不会伪装成可定位项。
@@ -397,6 +622,7 @@ export const buildOrderProfileRecognitionResults = (
reconstruction: CoordinateReconstructionPreview | null,
fieldValueState: 'idle' | 'loading' | 'ready' | 'failed' = 'idle',
datasetsEvidence: OrderProfileValidationEvidence | null = null,
reservationCandidates: ReservationRegionRecognitionCandidate[] = [],
): { header: OrderProfileRecognitionResult[]; line: OrderProfileRecognitionResult[] } => {
const valuesByCode = new Map(fieldValues.map((item) => [item.field_code, item]));
const header = pageRegions
@@ -434,9 +660,13 @@ export const buildOrderProfileRecognitionResults = (
rowNo: row.row_index + 1,
}))
));
return { header, line };
return applyReservationRegionRecognitionResults(
header, line, reservationCandidates, datasetsEvidence.lines.length,
);
}
if (!reconstruction) {
return applyReservationRegionRecognitionResults(header, [], reservationCandidates, 0);
}
if (!reconstruction) return { header, line: [] };
const fieldCodes = reconstruction.rows[0] || [];
const line = reconstruction.rows.slice(1).flatMap((row, rowIndex) => {
const sourceIndex = rowIndex + 1;
@@ -447,13 +677,54 @@ export const buildOrderProfileRecognitionResults = (
key: `${sourceIndex}-${fieldCode}`,
fieldCode,
value: row[columnIndex] || null,
status: role === 'deleted'
? 'deleted' as const
: row[columnIndex] ? 'read' as const : 'unavailable' as const,
status: role === 'deleted'
? 'deleted' as const
: row[columnIndex] ? 'read' as const : 'unavailable' as const,
rowNo: rowIndex + 1,
}));
});
return { header, line };
return applyReservationRegionRecognitionResults(
header, line, reservationCandidates,
reconstruction.row_roles.filter((role) => role === 'data').length,
);
};
/**
* 将服务端已归属的 Reservation 候选投影到右侧正式结果区。
*
* 这里不解析文本、不猜测行号:无行号候选只进订单表头,带行号候选只进对应
* 逻辑明细行。专用区域没有普通字段框,因此条目不可点击定位到字段框。
*/
const applyReservationRegionRecognitionResults = (
header: OrderProfileRecognitionResult[],
line: OrderProfileRecognitionResult[],
candidates: ReservationRegionRecognitionCandidate[],
logicalLineCount: number,
): { header: OrderProfileRecognitionResult[]; line: OrderProfileRecognitionResult[] } => {
const reservationHeaders = candidates
.filter((item) => item.scope === 'header' && item.value)
.map((item, index) => ({
id: null,
key: `reservation-region-header-${index}-${item.value}`,
fieldCode: 'reservation_id',
value: item.value,
status: 'read' as const,
}));
const reservationLines = candidates.flatMap((item, index) => {
if (
item.scope !== 'line' || item.line_no === null || !item.value
|| item.line_no < 1 || item.line_no > logicalLineCount
) return [];
return [{
id: null,
key: `reservation-region-line-${item.line_no}-${index}-${item.value}`,
fieldCode: 'reservation_id',
value: item.value,
status: 'read' as const,
rowNo: item.line_no,
}];
});
return { header: [...header, ...reservationHeaders], line: [...line, ...reservationLines] };
};
/**