fix(shipping-notice): 修复订单模板未绑定框展示与翻页画布失效

强制展示未绑定字段框并支持清除;预览令牌 TTL 内可复用,避免翻页后画布不可用。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-09-07 18:28:33 +08:00
1 parent 9d82eafcc9
commit 83da5f326d
14 files changed
+453 -46

No files matched your search

@@ -4,11 +4,13 @@
依赖:受控预览 API、Schema API、DocumentCanvas、useOrderProfileValueAdapter、
XfaDatasetTree、XfaCollectionSelector、XfaSplitRulePanel、shippingOrderField.utils。
逻辑:PDF 与 XFA 共用同一 desk DOM(main + aside.config + OrderProfileDocumentCanvas);
XFA 仅在属性区插入读取方式/数据源/拆分/样本显示增量;OCR 建议进入普通建议区。
XFA 仅在属性区插入读取方式/数据源/拆分/样本显示增量;OCR 建议进入普通建议区;
未绑定订单字段框通过横幅 + 画布高亮强制展示,避免空白底图漏看导致发布失败。
-->
<script setup lang="ts">
import {
computed,
nextTick,
onBeforeUnmount,
onMounted,
reactive,
@@ -104,6 +106,7 @@ import {
toOrderProfileHeaderFieldRegion,
resolveCoordinateFieldScope,
isOrderProfileVisualFieldEligible,
isUnboundOrderFieldCanvasRegion,
buildAutomarkSuggestionSummary,
type AutomarkSuggestionContext,
} from "./orderProfileForm.utils";
@@ -193,6 +196,7 @@ const documentCanvas = ref<{
zoomOut: () => void;
resetZoom: () => void;
captureRegion: (region: OrderProfileRelativeRegion) => string | null;
scrollRegionIntoView?: (regionId: string) => void;
} | null>(null);
const previewState = ref<"idle" | "updating" | "ready" | "failed">("idle");
const canvasUnavailable = ref(false);
@@ -506,9 +510,42 @@ const headerFields = computed<ShippingOrderFieldConfig[]>(
) || [],
);
const pageRegions = computed(() =>
regions.value.filter((item) => item.pageNo === pageNo.value),
regions.value.filter((item) => Number(item.pageNo) === Number(pageNo.value)),
);
/** 草稿中全部未绑定订单字段框(跨页);发布硬门禁同源,编辑时强制列出。 */
const unboundOrderFieldRegions = computed(() =>
regions.value.filter((item) => isUnboundOrderFieldCanvasRegion(item)),
);
const activePageHasLines = computed(() => pageRegions.value.some((item) => item.kind === 'line'));
/**
* 切到未绑定框所在页并选中,强制在画布上滚入视野以便删除。
* 核心逻辑:先 selectPage 再设 selectedId,并请求画布 scrollRegionIntoView。
*/
async function focusUnboundOrderFieldRegion(regionId: string): Promise<void> {
const target = unboundOrderFieldRegions.value.find((item) => item.id === regionId);
if (!target) return;
if (Number(target.pageNo) !== Number(pageNo.value)) {
await selectPage(Number(target.pageNo));
}
selectedId.value = target.id;
reservationIdRegionSelected.value = false;
await nextTick();
documentCanvas.value?.scrollRegionIntoView?.(target.id);
}
/**
* 一键删除全部未绑定订单字段框,避免签名空白区 12 个框只能逐个清。
* 核心逻辑:checkpoint 后过滤 regions,保留已绑定与非 order_field 区域。
*/
function clearUnboundOrderFieldRegions(): void {
if (!unboundOrderFieldRegions.value.length || saveState.value === 'readonly') return;
checkpoint();
const removed = new Set(unboundOrderFieldRegions.value.map((item) => item.id));
regions.value = regions.value.filter((item) => !removed.has(item.id));
if (selectedId.value && removed.has(selectedId.value)) selectedId.value = null;
scheduleAutosave();
}
const ensureTableRegionSetting = (targetPageNo: number) => {
tableRegionSettings[targetPageNo] ||= {
visualEvidenceSource: null,
@@ -546,7 +583,7 @@ const visualCanvas = computed<OrderProfileVisualCanvasAdapter>(() => {
actions: coordinateCanvasActions.value,
documentReady: Boolean(form.documentId && form.tableId),
preview: pdfPreviewGrant.value,
grant: previewPages.value?.pages.find((item) => item.page_no === pageNo.value) || null,
grant: previewPages.value?.pages.find((item) => Number(item.page_no) === Number(pageNo.value)) || null,
previewPagePath: valueAdapterKey.value === 'xfa_dataset'
? `/api/admin/shipping-notice/order-document-profiles/${active.value?.id || 0}/pdf-preview`
: `/api/admin/shipping-notice/order-document-profiles/${active.value?.id || 0}/preview-pages`,
@@ -719,7 +756,23 @@ const deskCanvasReadonly = computed(() => visualCanvas.value.canvasReadonly);
const deskCanvasWarningVisible = computed(() => visualCanvas.value.warningVisible);
const deskCanvasWarningText = computed(() => visualCanvas.value.warningText || '');
const onDeskCanvasRetry = () => visualCanvas.value.retryCanvas();
const onDeskCanvasLoadFailed = () => visualCanvas.value.reportCanvasLoadFailed();
/** 页图 token 失效时自动重签一批预览令牌,避免翻页后只能手动点「重试画布」。 */
let previewReauthInFlight = false;
const onDeskCanvasLoadFailed = async () => {
if (previewReauthInFlight) {
visualCanvas.value.reportCanvasLoadFailed();
return;
}
previewReauthInFlight = true;
try {
await loadPages();
canvasUnavailable.value = false;
} catch {
visualCanvas.value.reportCanvasLoadFailed();
} finally {
previewReauthInFlight = false;
}
};
const deskCanvasCanRender = computed(() => visualCanvas.value.canRender);
const deskCanvasRetryLabel = computed(() => visualCanvas.value.retryLabel);
const onDeskAcceptSuggestion = () => visualCanvas.value.acceptSuggestion();
@@ -2336,9 +2389,11 @@ const schedulePreview = () => {
* 签发当前样本的受控画布预览。
* 核心逻辑:普通坐标 PDF 使用服务端 PDFium PNG,保证内嵌繁体字形一致;只有显式
* XFA datasets 模板才保留 PDF.js 原 PDF 渲染,以显示动态表单外观。
* 不得把当前页强制打回第 1 页,否则第 2 页未绑定框会从画布过滤掉只剩顶部横幅。
*/
const loadPages = async () => {
if (!active.value || !form.documentId) return;
const preferredPageNo = Math.max(1, Number(pageNo.value) || 1);
try {
if (valueAdapterKey.value === 'xfa_dataset') {
previewPages.value = null;
@@ -2347,13 +2402,15 @@ const loadPages = async () => {
pdfPreviewGrant.value = null;
previewPages.value = await authorizeOrderProfilePreviewPages(active.value.id, form.documentId);
}
pageNo.value = 1;
pdfPageCount.value = previewPages.value?.page_count || 1;
const pageCount = Math.max(1, Number(previewPages.value?.page_count) || pdfPageCount.value || 1);
pdfPageCount.value = pageCount;
pageNo.value = Math.min(preferredPageNo, pageCount);
canvasUnavailable.value = false;
} catch {
pdfPreviewGrant.value = null;
previewPages.value = null;
pdfPageCount.value = 1;
pageNo.value = 1;
canvasUnavailable.value = true;
}
};
@@ -2374,14 +2431,15 @@ const reprocessCurrentSampleLayout = async (): Promise<void> => {
reparsingLayout.value = false;
}
};
/** PDF.js 已在内存中持有原件,切页只切换页码,避免消费新的预览令牌。 */
/** PDF.js 已在内存中持有原件,切页只切换页码;PNG 页图由画布按页缓存,避免一次性 token 翻页失效。 */
/** 切换 PDF 页时同步选择该页表格,使局部候选与当前标注页使用同一份坐标证据。 */
const selectPage = async (nextPageNo: number) => {
if (nextPageNo === pageNo.value) return;
pageNo.value = nextPageNo;
selectedId.value = null;
canvasUnavailable.value = false;
// 翻页只改变当前页预览表,模板主表仍由 mainTableId 单独冻结。
const pageTable = sampleTables.value.find((item) => item.page_no === nextPageNo);
const pageTable = sampleTables.value.find((item) => Number(item.page_no) === Number(nextPageNo));
form.tableId = pageTable?.table_id || '';
await refreshOrderFieldSuggestionValues();
};
@@ -2567,7 +2625,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
}];
}),
...(definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
const pageNo = item.page_scope === "exact_page" ? item.page_no || 1 : 1;
const regionPageNo = item.page_scope === "exact_page" ? Number(item.page_no) || 1 : 1;
if (!item.anchor?.region || !item.absolute_value_region) {
return [{
id: `unbound-${item.layout_id}`,
@@ -2575,7 +2633,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
label: item.label,
region: item.fallback_value_region || { x0: .1, y0: .1, x1: .2, y1: .15 },
fieldCode: null,
pageNo,
pageNo: regionPageNo,
}];
}
const anchor = item.anchor.region;
@@ -2585,7 +2643,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
label: item.anchor.text,
region: anchor,
orderFieldId: item.layout_id,
pageNo,
pageNo: regionPageNo,
}, {
id: `unbound-${item.layout_id}`,
kind: "order_field" as const,
@@ -2596,7 +2654,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
fieldCode: null,
orderFieldId: item.layout_id,
valueMode: item.value_mode,
pageNo,
pageNo: regionPageNo,
}];
}),
...(definition.order_field_layouts || []).filter((item) => !item.anchor).map((item) => ({
@@ -2805,8 +2863,24 @@ const edit = async (profile: ShippingOrderDocumentProfile) => {
form.tableId = visualTableId;
pageNo.value = sampleTables.value.find((item) => item.table_id === visualTableId)?.page_no || pageNo.value;
}
// 未绑定订单字段常落在签名页;优先停在含未绑定框的页,再签发预览(loadPages 必须保留该页码)。
const firstUnbound = unboundOrderFieldRegions.value[0];
if (
firstUnbound
&& !unboundOrderFieldRegions.value.some((item) => Number(item.pageNo) === Number(pageNo.value))
) {
pageNo.value = Number(firstUnbound.pageNo) || pageNo.value;
}
await refreshAutomarkSampleReadiness();
await loadPages();
// loadPages 保留 preferred 页;若预览页数更短则已钳制。再确保未绑定页仍可见。
if (
firstUnbound
&& !unboundOrderFieldRegions.value.some((item) => Number(item.pageNo) === Number(pageNo.value))
&& Number(firstUnbound.pageNo) <= Number(pdfPageCount.value)
) {
pageNo.value = Number(firstUnbound.pageNo);
}
} catch (error) {
fail(error);
} finally {
@@ -3167,6 +3241,40 @@ onBeforeUnmount(() => {
</div>
</div>
</section>
<section
v-if="unboundOrderFieldRegions.length"
class="unbound-regions-banner"
:aria-label="t('admin.shippingOrderProfiles.workbench.unboundRegionsBannerAria')"
>
<div class="unbound-regions-banner__heading">
<p>
{{ t('admin.shippingOrderProfiles.workbench.unboundRegionsBanner', { count: unboundOrderFieldRegions.length }) }}
</p>
<button
type="button"
class="btn-secondary unbound-regions-banner__clear"
:disabled="saveState === 'readonly'"
@click="clearUnboundOrderFieldRegions"
>
{{ t('admin.shippingOrderProfiles.workbench.clearUnboundRegions') }}
</button>
</div>
<div class="unbound-regions-banner__list">
<button
v-for="region in unboundOrderFieldRegions"
:key="region.id"
type="button"
class="unbound-regions-banner__item"
:class="{ active: selectedId === region.id }"
@click="() => void focusUnboundOrderFieldRegion(region.id)"
>
{{ t('admin.shippingOrderProfiles.workbench.unboundRegionChip', {
page: region.pageNo,
label: region.label,
}) }}
</button>
</div>
</section>
<OrderProfileDocumentCanvas
v-if="deskCanvasCanRender"
ref="documentCanvas"
@@ -4207,6 +4315,49 @@ onBeforeUnmount(() => {
.editor-workbench .config { max-height: calc(100vh - 5rem); overflow-y: auto; }
.editor-bottom-drawer { max-width: none; border-top: 1px solid #334155; background: #f8fafc; }
.automark-status-panel { position: sticky; top: .5rem; z-index: 6; display: grid; gap: .65rem; margin: 0 0 .75rem; border: 1px solid #7dd3fc; border-radius: .45rem; background: #f0f9ff; padding: .75rem .9rem; color: #164e63; box-shadow: 0 8px 20px rgb(14 116 144 / .12); }
.unbound-regions-banner {
position: sticky;
top: .5rem;
z-index: 6;
display: grid;
gap: .55rem;
margin: 0 0 .75rem;
border: 1px solid #f59e0b;
border-radius: .45rem;
background: #fffbeb;
padding: .75rem .9rem;
color: #92400e;
box-shadow: 0 8px 20px rgb(180 83 9 / .12);
}
.unbound-regions-banner p { margin: 0; font-size: .8rem; font-weight: 650; }
.unbound-regions-banner__heading {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: .55rem;
}
.unbound-regions-banner__clear { min-height: 1.9rem; padding-inline: .7rem; font-size: .72rem; }
.unbound-regions-banner__list { display: flex; flex-wrap: wrap; gap: .4rem; }
.unbound-regions-banner__item {
display: inline-flex;
max-width: 100%;
min-height: 1.8rem;
align-items: center;
border: 1px solid #d97706;
border-radius: .35rem;
background: #fff7ed;
padding: .2rem .55rem;
color: #9a3412;
font-size: .72rem;
cursor: pointer;
}
.unbound-regions-banner__item:hover,
.unbound-regions-banner__item.active {
border-color: #b45309;
background: #fdba74;
color: #7c2d12;
}
.automark-status-panel__heading { display: flex; align-items: flex-start; justify-content: space-between; gap: .75rem; }
.automark-status-panel__heading strong { display: block; color: #0c4a6e; font-size: .82rem; }
.automark-status-panel__heading p { margin: .2rem 0 0; color: #475569; font-size: .75rem; }
@@ -104,6 +104,44 @@ describe('OrderProfileDocumentCanvas PDF preview', () => {
);
});
it('force-highlights unbound order-field boxes on blank page imagery', async () => {
const wrapper = mount(OrderProfileDocumentCanvas, {
props: {
profileId: 5,
grant: { page_no: 2, preview_token: 'page-token' },
previewPagePath: '/api/admin/shipping-notice/order-document-profiles/5/preview-pages',
regions: [{
id: 'unbound-order_field_2__1',
kind: 'order_field',
label: 'Sign12 · 待绑定列 1',
pageNo: 2,
fieldCode: null,
region: { x0: .02, y0: .89, x1: .15, y1: .92 },
}],
pageNo: 2,
pageCount: 2,
},
global: {
plugins: [createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
admin: { shippingOrderProfiles: { workbench: { unbound: '待绑定', pagePreviewAlt: 'page' } } },
},
},
})],
},
});
await flushPromises();
// 关键断言:未绑定框必须带 region--unbound,否则签名空白底图上看不见。
const region = wrapper.find('.region--unbound');
expect(region.exists()).toBe(true);
expect(region.classes()).toContain('region-order_field');
expect(region.attributes('aria-label')).toContain('待绑定');
});
it('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');
@@ -1,8 +1,10 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue
用途:展示受控 PDF/XFA flatten 单页预览,并以相对坐标框支持选择、拖动和缩放区域。
依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion。
依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion、isUnboundOrderFieldCanvasRegion。
逻辑:父级签发单页令牌并提供分页动作;mode=readonly 时只允许查看/缩放/切页,不允许写入任何标注改动;
PNG 预览 token 为一次性消费,组件内按页缓存 blob,翻页回访不再重新拉 token;
未绑定订单字段框强制高亮(region--unbound),并暴露 scrollRegionIntoView 供横幅定位删除;
画布区域 aria-label 走四语言 i18n;可选 emptyHint/loadError 区分 XFA page_unavailable 与 PDF 缺样本空态。
-->
<script setup lang="ts">
@@ -11,6 +13,7 @@ import { useI18n } from 'vue-i18n';
import { Anchor, ArrowLeft, ArrowRight, Columns3, Copy, Eraser, MessageSquareText, Minus, Plus, Redo2, RotateCcw, Rows3, Save, TableProperties, Tag, TextCursorInput, Trash2, WandSparkles } from 'lucide-vue-next';
import { getAuthHeaders } from '@/shared/utils/auth';
import type { OrderProfileCanvasRegion, OrderProfilePreviewPageGrant } from '@/features/admin/types/shipping-order-document-profile.types';
import { isUnboundOrderFieldCanvasRegion } from '../orderProfileForm.utils';
import type { PDFDocumentProxy } from 'pdfjs-dist';
type PdfJsModule = typeof import('pdfjs-dist');
@@ -98,6 +101,10 @@ const internalLoadError = ref<string | null>(null);
const canvas = ref<HTMLElement | null>(null);
const viewport = ref<HTMLElement | null>(null);
const zoom = ref(1);
/** 按页缓存已消费 token 拉取的 PNG,翻页回访不再触发一次性 token 失效。 */
const pageImageCache = new Map<string, string>();
let loadGeneration = 0;
let cachedProfileId: number | null = null;
const zoomPercent = computed(() => Math.round(zoom.value * 100));
const pageInput = ref(props.pageNo);
type ResizeHandle = 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'nw';
@@ -132,26 +139,69 @@ const renderPdfPage = async (pdf: PDFDocumentProxy) => {
};
/**
* 下载一次性 PNG 并在组件卸载或切页时回收浏览器 blob。
* 核心逻辑:失败时写入 internalLoadError 并 emit loadFailed,避免误导为「未绑定样本」。
* 回收某次会话内全部页图 blob;切换样本 Profile 或卸载时调用。
*/
const clearPageImageCache = () => {
for (const url of pageImageCache.values()) URL.revokeObjectURL(url);
pageImageCache.clear();
inflightPageLoads.clear();
};
/** 同一页的并发拉取共用一个 Promise,成功后必入缓存(即使请求已过期)。 */
const inflightPageLoads = new Map<string, Promise<string>>();
/**
* 拉取单页 PNG;命中缓存或 in-flight 时不重复请求。
*/
const fetchPageImage = async (
previewPath: string,
grant: { page_no: number; preview_token: string },
): Promise<string> => {
const cacheKey = String(grant.page_no);
const cached = pageImageCache.get(cacheKey);
if (cached) return cached;
const inflight = inflightPageLoads.get(cacheKey);
if (inflight) return inflight;
const pending = (async () => {
const response = await fetch(
`${previewPath}/${grant.page_no}?preview_token=${encodeURIComponent(grant.preview_token)}`,
{ headers: getAuthHeaders(), cache: 'no-store' },
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const blobUrl = URL.createObjectURL(await response.blob());
pageImageCache.set(cacheKey, blobUrl);
return blobUrl;
})().finally(() => {
inflightPageLoads.delete(cacheKey);
});
inflightPageLoads.set(cacheKey, pending);
return pending;
};
/**
* 下载页 PNG;同页再次展示走缓存。后端 grant 在 TTL 内可重复 get,缓存作防御性加速。
* 核心逻辑:generation 守卫丢掉过期 UI 更新;页图本身仍保留在 cache 供回访。
*/
const loadPage = async () => {
if (!props.profileId || (!props.grant && !props.pdfPreview)) {
URL.revokeObjectURL(imageUrl.value);
const generation = ++loadGeneration;
if (cachedProfileId !== props.profileId) {
clearPageImageCache();
cachedProfileId = props.profileId;
}
if (!props.profileId || (!props.grant && !props.pdfPreview)) {
imageUrl.value = '';
pdfRendered.value = false;
pdfRendered.value = false;
internalLoadError.value = null;
return;
}
loading.value = true;
URL.revokeObjectURL(imageUrl.value);
imageUrl.value = '';
pdfRendered.value = false;
pdfRendered.value = false;
internalLoadError.value = null;
try {
const previewPath = props.previewPagePath
|| `/api/admin/shipping-notice/order-document-profiles/${props.profileId}/preview-pages`;
if (props.pdfPreview) {
imageUrl.value = '';
const response = await fetch(
`${previewPath}?preview_token=${encodeURIComponent(props.pdfPreview.preview_token)}`,
{ headers: getAuthHeaders(), cache: 'no-store' },
@@ -160,31 +210,38 @@ const loadPage = async () => {
const pdfjs = await loadPdfJs();
const bytes = new Uint8Array(await response.arrayBuffer());
pdfDocument = await pdfjs.getDocument({ data: bytes, enableXfa: true }).promise;
if (generation !== loadGeneration) return;
emit('pageCount', pdfDocument.numPages);
await renderPdfPage(pdfDocument);
return;
}
const grant = props.grant;
if (!grant) throw new Error('PDF preview grant is unavailable');
const response = await fetch(
`${previewPath}/${grant.page_no}?preview_token=${encodeURIComponent(grant.preview_token)}`,
{ headers: getAuthHeaders(), cache: 'no-store' },
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
imageUrl.value = URL.createObjectURL(await response.blob());
const blobUrl = await fetchPageImage(previewPath, grant);
if (generation !== loadGeneration) return;
imageUrl.value = blobUrl;
} catch {
if (generation !== loadGeneration) return;
const fallback = props.grant ? pageImageCache.get(String(props.grant.page_no)) : null;
if (fallback) {
imageUrl.value = fallback;
internalLoadError.value = null;
return;
}
imageUrl.value = '';
internalLoadError.value = t('admin.shippingOrderProfiles.workbench.canvasUnavailable');
emit('loadFailed');
} finally {
loading.value = false;
if (generation === loadGeneration) loading.value = false;
}
};
/**
* 用户点击画布重试:清除内部错误并通知父级。
* 用户点击画布重试:清除内部错误并通知父级重新签发页令牌。
*/
const onRetryClick = () => {
internalLoadError.value = null;
clearPageImageCache();
emit('retry');
};
@@ -282,6 +339,10 @@ const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
}
return region.label;
}
// 未绑定框不拼「样本值不可用」,改用明确的待绑定徽标,避免与空白底图混淆。
if (isUnboundOrderFieldCanvasRegion(region)) {
return `${region.label} · ${t('admin.shippingOrderProfiles.workbench.unbound')}`;
}
const state = props.orderFieldValueState || 'idle';
const value = region.fieldCode ? props.orderFieldValues?.[region.fieldCode] : null;
const suffix = state === 'loading'
@@ -321,8 +382,33 @@ const captureRegion = (region: OrderProfileCanvasRegion['region']): string | nul
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 });
defineExpose({
zoomIn: () => adjustZoom(.25),
zoomOut: () => adjustZoom(-.25),
resetZoom,
captureRegion,
/**
* 将指定区域滚入画布视口中央,供未绑定框定位删除。
* @param regionId - 画布区域 id。
*/
scrollRegionIntoView: (regionId: string) => {
const viewportEl = viewport.value;
const target = canvas.value?.querySelector(`[data-region-id="${CSS.escape(regionId)}"]`) as HTMLElement | null;
if (!viewportEl || !target) return;
const viewportRect = viewportEl.getBoundingClientRect();
const targetRect = target.getBoundingClientRect();
const nextTop = viewportEl.scrollTop + (targetRect.top - viewportRect.top)
- (viewportRect.height / 2) + (targetRect.height / 2);
const nextLeft = viewportEl.scrollLeft + (targetRect.left - viewportRect.left)
- (viewportRect.width / 2) + (targetRect.width / 2);
viewportEl.scrollTo({
top: Math.max(0, nextTop),
left: Math.max(0, nextLeft),
behavior: 'smooth',
});
},
});
watch(() => [props.grant?.page_no, props.grant?.preview_token, props.pdfPreview?.preview_token], () => { void loadPage(); }, { immediate: true });
watch(() => props.pageNo, async (value) => {
pageInput.value = value;
if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument);
@@ -330,7 +416,13 @@ watch(() => props.pageNo, async (value) => {
watch(zoom, async () => {
if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument);
});
onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(imageUrl.value); });
onBeforeUnmount(() => {
endMove();
endPan();
endCreation();
clearPageImageCache();
imageUrl.value = '';
});
</script>
<template>
@@ -409,7 +501,16 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
role="button"
tabindex="0"
class="region"
:class="[`region-${region.kind}`, { selected: selected.has(region.id), 'region-preview': region.isPreview }, region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '']"
:data-region-id="region.id"
:class="[
`region-${region.kind}`,
{
selected: selected.has(region.id),
'region-preview': region.isPreview,
'region--unbound': isUnboundOrderFieldCanvasRegion(region),
},
region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '',
]"
:style="{ left: `${region.region.x0 * 100}%`, top: `${region.region.y0 * 100}%`, 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')"
@@ -502,6 +603,24 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
.region-header_field .region-label, .region-header_field .resize-handle { background: #b45309; }
.region-order_field { z-index: 2; border: 1.5px solid #22c55e; background: rgb(34 197 94 / .08); }
.region-order_field .region-label, .region-order_field .resize-handle { background: #15803d; }
/* 未绑定订单字段:底图常为空白(如签名控件),必须用高对比框强制可见。 */
.region--unbound {
z-index: 6;
min-width: 14px;
min-height: 14px;
border: 2.5px solid #d97706;
background: rgb(245 158 11 / .42);
box-shadow: 0 0 0 2px rgb(255 255 255 / .95), 0 0 14px rgb(245 158 11 / .75);
}
.region--unbound .region-label {
top: 0;
left: 0;
max-width: 100%;
border-radius: 0;
background: #b45309;
white-space: normal;
}
.region--unbound .resize-handle { background: #b45309; }
.region-order_anchor { z-index: 2; border: 1.5px solid #a855f7; background: rgb(168 85 247 / .08); }
.region-order_anchor .region-label, .region-order_anchor .resize-handle { background: #7e22ce; }
.region-document_anchor_label { z-index: 2; border: 1.5px solid #0ea5e9; background: rgb(14 165 233 / .1); }
@@ -29,10 +29,18 @@ import {
toOrderProfileHeaderFieldRegion,
resolveCoordinateFieldScope,
isOrderProfileVisualFieldEligible,
isUnboundOrderFieldCanvasRegion,
buildAutomarkSuggestionSummary,
} from './orderProfileForm.utils';
describe('order profile form rules', () => {
it('marks order fields without fieldCode as unbound for forced canvas display', () => {
// 关键断言:无 Schema 绑定的订单字段框必须被识别,供画布高亮与发布前横幅共用。
expect(isUnboundOrderFieldCanvasRegion({ kind: 'order_field', fieldCode: null })).toBe(true);
expect(isUnboundOrderFieldCanvasRegion({ kind: 'order_field', fieldCode: 'currency' })).toBe(false);
expect(isUnboundOrderFieldCanvasRegion({ kind: 'header_field', fieldCode: null })).toBe(false);
});
it('restores a Reservation ID region from a Vue reactive profile without structured-clone failure', () => {
const persisted = reactive({
region: { x0: .05, y0: .71, x1: .28, y1: .73 },
@@ -2,7 +2,8 @@
* features/admin/modules/shipping-order-document-profiles/orderProfileForm.utils.ts
* 用途:构造可视化订单模板的白名单列规则、明细字段分组,并控制样本表格配置区的安全显示。
* 依赖:订单 Profile DTO。
* 逻辑:页面状态只允许 direct 或已注册复合解析器;同一目标字段跨列只能出现一次。
* 逻辑:页面状态只允许 direct 或已注册复合解析器;同一目标字段跨列只能出现一次;
* 另提供「未绑定订单字段」判定,供画布强制高亮与编辑横幅共用。
*/
import type {
@@ -39,6 +40,17 @@ export const isOrderProfileVisualFieldEligible = (
&& (usesExternalValueSource || Boolean(field.allowed_sources?.includes('pdf_coordinate')))
);
/**
* 判断画布区域是否为「未绑定 Schema 字段」的订单字段框。
* 核心逻辑:仅 order_field 且无 fieldCode 视为未绑定;这些框会写入
* draft_unbound_order_field_layouts 并在发布时硬阻断,必须在画布强制可见。
* @param region - 画布区域。
* @returns 是否需要未绑定高亮与横幅列出。
*/
export const isUnboundOrderFieldCanvasRegion = (
region: Pick<OrderProfileCanvasRegion, 'kind' | 'fieldCode'>,
): boolean => region.kind === 'order_field' && !region.fieldCode;
/**
* 将画布中的视觉表头文字转换为 v2 字段区域。
* 核心逻辑:视觉位置不是业务 scope;调用方必须按 Schema 传入 header/line,
@@ -2,7 +2,8 @@
* features/admin/modules/shipping-order-document-profiles/orderProfileReadonlyCanvas.utils.spec.ts
* 用途:验证版本只读画布完整恢复模板定义中的诊断区域。
* 依赖:Vitest、orderProfileReadonlyCanvas.utils。
* 逻辑:已发布版本的必需锚点必须同时显示标签框和值框,且区域 ID 与冻结诊断接口一致。
* 逻辑:已发布版本的必需锚点必须同时显示标签框和值框,且区域 ID 与冻结诊断接口一致;
* 仅含 fallback 的未绑定订单字段框也必须恢复,供签名空白区强制可见。
*/
import { describe, expect, it } from 'vitest';
@@ -40,4 +41,40 @@ describe('buildOrderProfileReadonlyRegions', () => {
expect.objectContaining({ id: 'plant_address_value', kind: 'document_anchor_value', configuredValue: 'No. 88' }),
]));
});
it('restores fallback-only unbound order fields so blank signature areas stay visible', () => {
const profile = {
definition: {
document_match: { required_anchors: [], optional_anchors: [] },
table_regions: [],
order_field_layouts: [],
draft_unbound_order_field_layouts: [{
layout_id: 'order_field_2__1',
label: 'Sign12 · 待绑定列 1',
page_scope: 'exact_page',
page_no: 2,
anchor: null,
absolute_value_region: null,
fallback_value_region: { x0: .02, y0: .89, x1: .15, y1: .92 },
value_mode: 'single_line',
stop_anchors: [],
minimum_evidence_level: 'coordinate',
}],
},
} as unknown as ShippingOrderDocumentProfile;
const regions = buildOrderProfileReadonlyRegions(profile);
// 关键断言:无 anchor/absolute 时仍用 fallback 恢复未绑定框,否则签名空白区会漏展示。
expect(regions).toEqual(expect.arrayContaining([
expect.objectContaining({
id: 'unbound-order_field_2__1',
kind: 'order_field',
fieldCode: null,
pageNo: 2,
label: 'Sign12 · 待绑定列 1',
region: { x0: .02, y0: .89, x1: .15, y1: .92 },
}),
]));
});
});
@@ -85,6 +85,7 @@ export const buildOrderProfileReadonlyRegions = (
}),
...(definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
const pageNo = pageNoOf(item.page_scope, item.page_no);
// 仅有 fallback 的未绑定框也必须恢复;签名区底图常空白,缺框会导致发布前无法发现。
if (!item.anchor?.region || !item.absolute_value_region) {
return [{
id: `unbound-${item.layout_id}`,