chore(shipping-notice): 统一货代发货生命周期阶段命名并优化全链路业务逻辑

This commit is contained in:
hugo committed 2026-08-17 19:56:51 +08:00
1 parent 5ef8329bd8
commit 4ec4e57005
183 files changed
+14653 -3936

No files matched your search

@@ -21,13 +21,15 @@ import { BusinessError } from "@/shared/api/client";
import { useMessage } from "@/shared/composables/useMessage";
import { getShippingOrderSchemaState } from "@/features/admin/api/shipping-order-schema.api";
import {
authorizeOrderProfilePreviewPages,
authorizeOrderProfilePdfPreview,
addOrderProfileTrainingSample,
listOrderDocumentProfiles,
acquireOrderDocumentProfileEditLease,
decideOrderDocumentProfileSuggestion,
enqueueOrderProfilePdfAutomark,
generateOrderProfileOcrCoordinateEvidence,
getOrderDocumentProfileDetail,
getOrderProfilePdfAutomarkJob,
getOrderProfileSampleTables,
listOrderProfileBoundSamples,
listOrderProfileSamples,
@@ -37,9 +39,7 @@ import {
renewOrderDocumentProfileEditLease,
readOrderProfilePreviewPageRegionText,
suggestOrderProfileHeader,
suggestOrderProfileOrderFields,
saveOrderDocumentProfileDraft,
suggestOrderProfileCoordinateReconstruction,
} from "@/features/admin/api/shipping-order-document-profile.api";
import type {
CoordinateReconstructionPreview,
@@ -52,7 +52,6 @@ import type {
OrderFieldLayoutSuggestion,
OrderProfileRowReconstructionMode,
ShippingOrderDocumentProfile,
XfaValueBindingType,
} from "@/features/admin/types/shipping-order-document-profile.types";
import {
asCoordinateProfileDefinition,
@@ -124,8 +123,9 @@ const samples = ref<
const schemas = ref<ShippingOrderSchemaVersion[]>([]);
const active = ref<ShippingOrderDocumentProfile | null>(null);
const boundSamples = ref<OrderProfileBoundSample[]>([]);
const pageGrant = ref<{ page_no: number; preview_token: string } | null>(null);
const pageGrants = ref<Array<{ page_no: number; preview_token: string }>>([]);
/** 坐标 PDF 与 XFA 共用原 PDF + PDF.js 画布;PDFium 页图仅留给后端证据生成。 */
const pdfPreviewGrant = ref<{ document_id: number; preview_token: string; expires_in_seconds: number } | null>(null);
const pdfPageCount = ref(1);
const pageNo = ref(1);
const sampleTables = ref<
Array<{
@@ -234,15 +234,13 @@ function onDeskAcceptXfaSuggestion(): void {
}
/**
* 驳回首条 XFA OCR 建议,或关闭视觉候选(工具栏「拒绝建议」入口)。
* 驳回首条 XFA OCR 建议(工具栏「拒绝建议」入口)。
*/
function onDeskRejectXfaSuggestion(): void {
const next = xfaDesk.autoMarkSuggestions[0];
if (next) {
void xfaDesk.onRejectAutomark(next);
return;
}
xfaDesk.dismissPendingSuggestion();
}
@@ -260,14 +258,6 @@ function assignXfaSplitRulePanel(el: unknown): void {
xfaDesk.splitRulePanel = (el as typeof xfaDesk.splitRulePanel) || null;
}
/**
* 更新选中绑定的正式取值模式。
*/
function onXfaReadingModeChange(event: Event): void {
const value = (event.target as HTMLSelectElement).value as XfaValueBindingType;
xfaDesk.updateSelectedReadingMode(value);
}
/**
* 共享画布是否只读:XFA 在页授权失败 / 页不可用时禁用标注工具;
* 右侧非视觉字段(数据源/拆分等)不受此约束。
@@ -345,28 +335,11 @@ const xfaTableRegionSetting = computed(() => {
* XFA 后台仍可走 automark Job,但 UI 不再使用专用 OCR 底栏。
*/
async function onDeskCanvasSuggest(): Promise<void> {
if (isXfaTemplate.value) {
if (suggestingRegions.value || deskCanvasReadonly.value) return;
suggestingRegions.value = true;
suggestionProgress.value = t('admin.shippingOrderProfiles.workbench.autoSuggestAnalyzing');
try {
await xfaDesk.startAutomarkJob(true);
const count = xfaDesk.autoMarkSuggestions.length;
suggestionProgress.value = count > 0
? t('admin.shippingOrderProfiles.workbench.autoSuggestComplete')
: t('admin.shippingOrderProfiles.workbench.autoSuggestNoRows');
} catch {
suggestionProgress.value = t('admin.shippingOrderProfiles.workbench.autoSuggestFailed');
} finally {
suggestingRegions.value = false;
}
return;
}
void suggestRegions();
}
/**
* 画布创建框:XFA 走统一 mapping;PDF 落本地区域。
* 画布创建框:XFA/PDF 均立即落本地视觉框;XFA 正式 datasets 映射由右侧配置完成。
*/
function onDeskCanvasCreate(region: OrderProfileRelativeRegion): void {
if (isXfaTemplate.value) {
@@ -742,11 +715,7 @@ const selectedHeaderLayoutId = computed(() => {
const selected = selectedRegion.value;
return selected?.kind === "header_field" ? selected.parentId || null : null;
});
const pageCount = computed(() =>
pageGrants.value.length
? Math.max(...pageGrants.value.map((item) => item.page_no))
: 1,
);
const pageCount = computed(() => pdfPageCount.value);
/** 将任意订单字段编码转换为当前冻结 Schema 的业务名称,避免单头候选泄露内部编码。 */
const schemaFieldLabel = (fieldCode: string) =>
[...headerFields.value, ...lineFields.value].find(
@@ -1548,51 +1517,56 @@ const save = async (automatic = false) => {
/** 创建只含主行区域的最小草稿并自动绑定样本,之后才允许打开受控页面画布标注。 */
/** 以启用的 Schema 字段规则和冻结坐标生成待复核标记,绝不自动发布模板。 */
const suggestRegions = async () => {
if (!form.documentId || !form.tableId || suggestingRegions.value) return;
if (suggestingRegions.value || !active.value) return;
// XFA desk owns the annotation sample lifecycle. The coordinate editor's
// form.documentId can still be empty while the XFA desk has already loaded
// its authoritative annotation sample, so do not silently drop the action.
const documentId = isXfaTemplate.value
? xfaDesk.annotationDocumentId
: form.documentId;
if (!documentId) {
suggestionProgress.value = t("admin.shippingOrderProfiles.workbench.autoSuggestFailed");
message.error(t("admin.shippingOrderProfiles.workbench.autoSuggestFailed"));
return;
}
if (!isXfaTemplate.value && !form.tableId) return;
suggestingRegions.value = true;
suggestionProgress.value = t(
"admin.shippingOrderProfiles.workbench.autoSuggestCheckingCoordinates",
);
try {
const orderFields = await suggestOrderProfileOrderFields(
form.documentId,
form.schemaId,
pageNo.value,
);
let suggestion;
try {
suggestionProgress.value = t(
"admin.shippingOrderProfiles.workbench.autoSuggestAnalyzing",
);
suggestion = await suggestOrderProfileCoordinateReconstruction(
form.documentId,
form.tableId,
undefined,
form.schemaId,
);
} catch (error) {
if (
!(error instanceof BusinessError) ||
error.code !==
"SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE"
)
throw error;
suggestionProgress.value = t(
"admin.shippingOrderProfiles.workbench.autoSuggestOcr",
);
await generateOrderProfileOcrCoordinateEvidence(
form.documentId,
form.tableId,
);
suggestionProgress.value = t(
"admin.shippingOrderProfiles.workbench.autoSuggestAnalyzing",
);
suggestion = await suggestOrderProfileCoordinateReconstruction(
form.documentId,
form.tableId,
undefined,
form.schemaId,
);
suggestionProgress.value = t("admin.shippingOrderProfiles.workbench.autoSuggestAnalyzing");
const queued = await enqueueOrderProfilePdfAutomark(active.value.id, {
document_id: documentId,
table_id: isXfaTemplate.value ? undefined : form.tableId,
schema_version_id: form.schemaId,
page_no: pageNo.value,
force: true,
});
let job;
for (;;) {
job = await getOrderProfilePdfAutomarkJob(active.value.id, queued.job_id);
if (!['queued', 'running', 'pending'].includes(String(job.status || ''))) break;
await new Promise<void>((resolve) => { window.setTimeout(resolve, 500); });
}
if (String(job.status) !== 'success') {
throw new Error(String(job.error_code || job.message || 'PDF automark failed'));
}
const candidates = Array.isArray(job.candidates) ? job.candidates : [];
if (job.kind === 'visual_binding') {
xfaDesk.applyPdfAutomarkCandidates(candidates);
xfaDesk.applyPdfAutomarkRenderIdentity(job.preview_render_checksum);
suggestionProgress.value = candidates.length
? t("admin.shippingOrderProfiles.workbench.autoSuggestComplete")
: t("admin.shippingOrderProfiles.workbench.autoSuggestNoRows");
return;
}
const reconstructionCandidate = candidates.find((item) => item?.candidate_kind === 'coordinate_reconstruction');
const orderFieldCandidate = candidates.find((item) => item?.candidate_kind === 'order_fields');
const suggestion = reconstructionCandidate?.payload as import('@/features/admin/types/shipping-order-document-profile.types').CoordinateReconstructionSuggestion | undefined;
const orderFields = orderFieldCandidate?.payload as { order_field_candidates: OrderFieldLayoutSuggestion[] } | undefined;
if (!suggestion || !orderFields) {
throw new Error('Unified PDF automark returned incomplete coordinate candidates');
}
if (!suggestion.subrow_layouts.length && !orderFields.order_field_candidates.some((item) => item.status === "suggested")) {
suggestionProgress.value = t(
@@ -1701,7 +1675,7 @@ const suggestRegions = async () => {
});
});
}
const summary = { algorithm_version: 'coordinate-suggest-v1', kind: 'page_regions', page_no: pageNo.value, document_id: form.documentId, table_id: form.tableId, region_count: suggestedRegions.length, region_kinds: suggestedRegions.map((item) => item.kind) };
const summary = { algorithm_version: 'coordinate-suggest-v1', kind: 'page_regions', page_no: pageNo.value, document_id: documentId, table_id: form.tableId, region_count: suggestedRegions.length, region_kinds: suggestedRegions.map((item) => item.kind) };
const serialized = canonicalSuggestionJson(summary);
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized));
const checksum = Array.from(new Uint8Array(digest)).map((item) => item.toString(16).padStart(2, '0')).join('');
@@ -1863,28 +1837,24 @@ const schedulePreview = () => {
}
}, 400);
};
/** 签发当前绑定样本的单用途画布令牌;令牌失败仅降级画布,不能掩盖草稿保存成功。 */
/** 签发当前绑定样本的原 PDF 单用途画布令牌;坐标 PDF 与 XFA 共用 PDF.js 渲染。 */
const loadPages = async () => {
if (!active.value || !form.documentId) return;
try {
const grants = await authorizeOrderProfilePreviewPages(
pdfPreviewGrant.value = await authorizeOrderProfilePdfPreview(
active.value.id,
form.documentId,
);
pageGrants.value = grants.pages;
pageGrant.value =
grants.pages.find((item) => item.page_no === pageNo.value) ||
grants.pages[0] ||
null;
pageNo.value = pageGrant.value?.page_no || 1;
pageNo.value = 1;
pdfPageCount.value = 1;
canvasUnavailable.value = false;
} catch {
pageGrant.value = null;
pageGrants.value = [];
pdfPreviewGrant.value = null;
pdfPageCount.value = 1;
canvasUnavailable.value = true;
}
};
/** 切页时重新签发整个页面列表,避免已消费的单页令牌被重复使用。 */
/** PDF.js 已在内存中持有原件,切页只切换页码,避免消费新的预览令牌。 */
/** 切换 PDF 页时同步选择该页表格,使局部候选与当前标注页使用同一份坐标证据。 */
const selectPage = async (nextPageNo: number) => {
if (nextPageNo === pageNo.value) return;
@@ -1894,7 +1864,6 @@ const selectPage = async (nextPageNo: number) => {
(item) => item.page_no === nextPageNo,
);
form.tableId = pageTable?.table_id || "";
await loadPages();
await refreshOrderFieldSuggestionValues();
};
/** 请求当前或全部表头的只读精确别名建议;结果不自动修改人工字段绑定。 */
@@ -2371,8 +2340,8 @@ watch(
() => form.documentId,
() => {
form.tableId = "";
pageGrant.value = null;
pageGrants.value = [];
pdfPreviewGrant.value = null;
pdfPageCount.value = 1;
canvasUnavailable.value = false;
if (restoringProfile) return;
void loadSampleTables();
@@ -2568,17 +2537,15 @@ onBeforeUnmount(() => {
ref="documentCanvas"
:profile-id="active?.id || null"
:mode="deskCanvasReadonly ? 'readonly' : 'edit'"
:grant="isXfaTemplate ? xfaDesk.activePageGrant : pageGrant"
:preview-page-path="isXfaTemplate ? xfaDesk.activePreviewPagePath : undefined"
:pdf-preview="isXfaTemplate ? xfaDesk.activeXfaPdfGrant : pdfPreviewGrant"
:preview-page-path="isXfaTemplate ? xfaDesk.activePreviewPagePath : `/api/admin/shipping-notice/order-document-profiles/${active?.id || 0}/pdf-preview`"
:regions="isXfaTemplate ? xfaDesk.canvasRegions : pageRegions"
:selected-region-id="isXfaTemplate ? xfaDesk.selectedBindingId : selectedId"
:creation-kind="isXfaTemplate ? xfaDesk.creationKind : creationKind"
:annotation-tool-set="'full'"
:auto-suggest-disabled="isXfaTemplate ? deskCanvasReadonly : (compactEditor || !form.documentId || !form.tableId)"
:suggesting="suggestingRegions || (isXfaTemplate && xfaDesk.suggestingBinding)"
:suggestion-progress="suggestionProgress || (isXfaTemplate && xfaDesk.suggestingBinding
? t('admin.shippingOrderProfiles.xfaUnified.suggesting')
: '')"
:suggesting="suggestingRegions"
:suggestion-progress="suggestionProgress"
:undo-disabled="isXfaTemplate
? (!xfaDesk.bindingHistory.length || deskCanvasReadonly)
: !history.length"
@@ -2596,7 +2563,7 @@ onBeforeUnmount(() => {
:save-disabled="isXfaTemplate ? !xfaDesk.dirty : issues.length > 0"
:saving="saving"
:pending-suggestion-count="isXfaTemplate
? (xfaDesk.autoMarkSuggestions.length || xfaDesk.pendingCandidateCount)
? xfaDesk.autoMarkSuggestions.length
: (pendingSuggestion?.regions.length || 0)"
:order-field-values="isXfaTemplate ? undefined : orderFieldValues"
:order-field-value-state="isXfaTemplate ? undefined : orderFieldValueState"
@@ -2608,6 +2575,7 @@ onBeforeUnmount(() => {
@delete="onDeskCanvasDelete"
@save="() => void save()"
@page="onDeskCanvasPage"
@page-count="(count) => { if (isXfaTemplate) xfaDesk.setRenderedPageCount(count); else pdfPageCount = count; }"
@draw="onDeskCanvasDraw"
@suggest="() => void onDeskCanvasSuggest()"
@create="onDeskCanvasCreate"
@@ -2632,34 +2600,6 @@ onBeforeUnmount(() => {
@load-failed="onDeskCanvasLoadFailed"
@retry="onDeskCanvasRetry"
/>
<section
v-if="isXfaTemplate && xfaDesk.pendingSuggestion?.visual_suggestion?.candidates?.length"
class="suggestion-decision"
role="status"
:aria-label="t('admin.shippingOrderProfiles.workbench.suggestionReadyForDecision')"
>
<strong>{{ t('admin.shippingOrderProfiles.workbench.suggestionReadyForDecision') }}</strong>
<span>{{ xfaDesk.pendingCandidateCount }}</span>
<button type="button" class="link" @click="xfaDesk.dismissPendingSuggestion()">{{ t('common.close') }}</button>
<div
v-for="candidate in xfaDesk.pendingSuggestion.visual_suggestion.candidates"
:key="candidate.candidate_id"
class="xfa-candidate-inline"
>
<span>{{ candidate.acroform_field_name_tail || candidate.widget_id }}</span>
<span>{{ Math.round((candidate.confidence || 0) * 100) }}%</span>
<template v-for="path in (candidate.path_candidates || [])" :key="`${candidate.candidate_id}-${path.path_id}`">
<span>{{ path.dataset_value_masked || path.path_id }}</span>
<button
type="button"
:disabled="deskCanvasReadonly"
@click="xfaDesk.applyVisualCandidate(candidate, path.path_id)"
>
{{ t('admin.shippingOrderProfiles.xfaUnified.acceptCandidate') }}
</button>
</template>
</div>
</section>
<section v-if="!isXfaTemplate && pendingSuggestion" class="suggestion-decision" role="status">
<strong>{{ t('admin.shippingOrderProfiles.workbench.suggestionReadyForDecision') }}</strong>
<span>{{ pendingSuggestion.regions.length }}</span>
@@ -2910,21 +2850,6 @@ onBeforeUnmount(() => {
</option>
</select>
</label>
<label>{{ t('admin.shippingOrderProfiles.xfaDesk.readingMode') }}
<select
class="select-field"
:value="xfaDesk.selectedReadingMode"
:disabled="xfaConfigReadonly"
@change="onXfaReadingModeChange"
>
<option value="pdf_coordinate">{{ t('admin.shippingOrderProfiles.xfaDesk.readingModes.pdf_coordinate') }}</option>
<option value="ocr_coordinate">{{ t('admin.shippingOrderProfiles.xfaDesk.readingModes.ocr_coordinate') }}</option>
<option value="xfa_dataset">{{ t('admin.shippingOrderProfiles.xfaDesk.readingModes.xfa_dataset') }}</option>
</select>
</label>
<p v-if="xfaDesk.readingModeWarning" class="schema-warning" role="status">
{{ t('admin.shippingOrderProfiles.xfaDesk.readingModeWarning') }}
</p>
</template>
<template v-if="xfaDesk.showDatasetsSection">
@@ -11,9 +11,15 @@ import { defineComponent, h, nextTick } from 'vue';
import OrderProfileXfaWorkbench from './OrderProfileXfaWorkbench.vue';
import { useOrderProfileXfaDesk } from './composables/useOrderProfileXfaDesk';
const { saveDraftMock, splitPreviewMock, detailDefinition } = vi.hoisted(() => ({
const { authorizePreviewPagesMock, authorizePdfPreviewMock, saveDraftMock, splitPreviewMock, enqueueAutomarkMock, getAutomarkJobMock, suggestUnifiedMappingMock, messageErrorMock, detailDefinition } = vi.hoisted(() => ({
authorizePreviewPagesMock: vi.fn(),
authorizePdfPreviewMock: vi.fn(),
saveDraftMock: vi.fn(),
splitPreviewMock: vi.fn(),
enqueueAutomarkMock: vi.fn(),
getAutomarkJobMock: vi.fn(),
suggestUnifiedMappingMock: vi.fn(),
messageErrorMock: vi.fn(),
detailDefinition: { value: null as Record<string, unknown> | null },
}));
@@ -51,7 +57,7 @@ vi.mock('vue-router', () => ({
}));
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => ({ success: vi.fn(), error: vi.fn(), info: vi.fn() }),
useMessage: () => ({ success: vi.fn(), error: messageErrorMock, info: vi.fn() }),
}));
vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
@@ -86,12 +92,8 @@ vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
getOrderProfileSampleXfaCollections: vi.fn(async () => ({
collection_candidates: [{ path_id: 'items-data', collection_path_hash: 'h', row_count: 1 }],
})),
authorizeOrderProfilePreviewPages: vi.fn(async () => ({
document_id: 85,
page_count: 1,
pages: [{ page_no: 1, preview_token: 'token' }],
expires_in_seconds: 60,
})),
authorizeOrderProfilePreviewPages: (...args: unknown[]) => authorizePreviewPagesMock(...args),
authorizeOrderProfilePdfPreview: (...args: unknown[]) => authorizePdfPreviewMock(...args),
requestOrderProfileSampleXfaSyntheticPreview: vi.fn(async () => ({
document_id: 85,
identity: {
@@ -117,16 +119,11 @@ vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
cache_hit: false,
})),
listOrderProfileSampleXfaSyntheticPreviewPages: vi.fn(),
enqueueOrderProfileXfaOcrAutomark: vi.fn(async () => ({ job_id: 9, status: 'queued' })),
getOrderProfileXfaOcrAutomarkJob: vi.fn(async () => ({
job_id: 9,
status: 'succeeded',
suggestions: [],
preview_render_checksum: 'r'.repeat(64),
})),
enqueueOrderProfilePdfAutomark: (...args: unknown[]) => enqueueAutomarkMock(...args),
getOrderProfilePdfAutomarkJob: (...args: unknown[]) => getAutomarkJobMock(...args),
acceptOrderProfileXfaOcrAutomarkSuggestion: vi.fn(),
rejectOrderProfileXfaOcrAutomarkSuggestion: vi.fn(),
suggestOrderProfileXfaUnifiedMapping: vi.fn(),
suggestOrderProfileXfaUnifiedMapping: (...args: unknown[]) => suggestUnifiedMappingMock(...args),
acquireOrderDocumentProfileEditLease: vi.fn(async () => ({ lease_token: 'lease', expires_at: new Date().toISOString() })),
renewOrderDocumentProfileEditLease: vi.fn(),
releaseOrderDocumentProfileEditLease: vi.fn(),
@@ -162,6 +159,31 @@ describe('OrderProfileXfaWorkbench (deprecated thin wrapper)', () => {
beforeEach(() => {
detailDefinition.value = structuredClone(baseDefinition);
enqueueAutomarkMock.mockReset();
enqueueAutomarkMock.mockResolvedValue({ job_id: 9, status: 'queued' });
getAutomarkJobMock.mockReset();
getAutomarkJobMock.mockResolvedValue({
job_id: 9,
status: 'succeeded',
kind: 'visual_binding',
candidates: [],
preview_render_checksum: 'r'.repeat(64),
});
messageErrorMock.mockReset();
suggestUnifiedMappingMock.mockReset();
authorizePreviewPagesMock.mockReset();
authorizePreviewPagesMock.mockResolvedValue({
document_id: 85,
page_count: 1,
pages: [{ page_no: 1, preview_token: 'token' }],
expires_in_seconds: 60,
});
authorizePdfPreviewMock.mockReset();
authorizePdfPreviewMock.mockResolvedValue({
document_id: 85,
preview_token: 'xfa-pdf-token',
expires_in_seconds: 120,
});
saveDraftMock.mockReset();
splitPreviewMock.mockReset();
// Canvas-related absolute URL safety: relative /api fetch must not throw in jsdom.
@@ -213,6 +235,31 @@ describe('OrderProfileXfaWorkbench (deprecated thin wrapper)', () => {
describe('useOrderProfileXfaDesk', () => {
beforeEach(() => {
detailDefinition.value = structuredClone(baseDefinition);
enqueueAutomarkMock.mockReset();
enqueueAutomarkMock.mockResolvedValue({ job_id: 9, status: 'queued' });
getAutomarkJobMock.mockReset();
getAutomarkJobMock.mockResolvedValue({
job_id: 9,
status: 'succeeded',
kind: 'visual_binding',
candidates: [],
preview_render_checksum: 'r'.repeat(64),
});
messageErrorMock.mockReset();
suggestUnifiedMappingMock.mockReset();
authorizePreviewPagesMock.mockReset();
authorizePreviewPagesMock.mockResolvedValue({
document_id: 85,
page_count: 1,
pages: [{ page_no: 1, preview_token: 'token' }],
expires_in_seconds: 60,
});
authorizePdfPreviewMock.mockReset();
authorizePdfPreviewMock.mockResolvedValue({
document_id: 85,
preview_token: 'xfa-pdf-token',
expires_in_seconds: 120,
});
vi.stubGlobal('fetch', vi.fn(async () => ({
ok: true,
blob: async () => new Blob(['png'], { type: 'image/png' }),
@@ -360,15 +407,13 @@ describe('useOrderProfileXfaDesk', () => {
await flushPromises();
if (!desk.loading.value && desk.definition.value) break;
}
// 原生页授权就绪后,synthetic 失败不应禁标注。
desk.pageGrants.value = [{ page_no: 1, preview_token: 'token' }];
desk.pageGrant.value = { page_no: 1, preview_token: 'token' };
// 原 PDF 授权就绪后,合成预览失败不应禁标注。
desk.xfaPdfGrant.value = { document_id: 85, preview_token: 'token', expires_in_seconds: 120 };
desk.pageLoadError.value = null;
desk.syntheticPreviewStatus.value = 'unavailable';
expect(desk.annotationDisabled.value).toBe(false);
desk.pageGrant.value = null;
desk.pageGrants.value = [];
desk.xfaPdfGrant.value = null;
expect(desk.annotationDisabled.value).toBe(true);
desk.definition.value = {
@@ -391,4 +436,279 @@ describe('useOrderProfileXfaDesk', () => {
desk.selectedBindingId.value = 'anchor-1';
expect(desk.showDatasetsSection.value).toBe(false);
}, 15000);
it('keeps XFA mapping ready but reports a native PDF page authorization failure', async () => {
// 该 suite 保留多个 mounted desk;持续拒绝确保本用例的异步 loadPages 不会被旧实例抢先消费。
authorizePdfPreviewMock.mockRejectedValue(new Error('PDF preview unavailable'));
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
const Host = defineComponent({
setup() {
desk = useOrderProfileXfaDesk({
profileId: 52,
leaseToken: 'lease',
saveState: 'saved',
editorSessionId: 'sess',
enabled: true,
});
return () => h('div');
},
});
mount(Host, {
global: {
plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
} } } } })],
},
});
for (let i = 0; i < 40; i += 1) {
await flushPromises();
if (!desk.loading.value) break;
}
// 断言:XFA 字段建模不依赖 synthetic preview;仅原生 PDF 页进入可重试失败态。
expect(desk.definition.value).toBeTruthy();
expect(desk.loadError.value).toBe(false);
expect(desk.pageUnavailable.value).toBe(true);
expect(desk.pageLoadError.value).toBe('native page unavailable');
}, 15000);
it('uses the single-use XFA PDF grant instead of PDFium page grants', async () => {
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
const Host = defineComponent({
setup() {
desk = useOrderProfileXfaDesk({
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
});
return () => h('div');
},
});
mount(Host, {
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
workbench: { regionLabels: { order_field: '字段 {count}' } },
} } } } })] },
});
for (let i = 0; i < 40; i += 1) {
await flushPromises();
if (!desk.loading.value) break;
}
expect(authorizePdfPreviewMock).toHaveBeenCalledWith(52, 85);
expect(authorizePreviewPagesMock).not.toHaveBeenCalled();
expect(desk.activeXfaPdfGrant.value?.preview_token).toBe('xfa-pdf-token');
}, 15000);
it('creates a local XFA visual box immediately without requesting mapping suggestions', async () => {
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
const Host = defineComponent({
setup() {
desk = useOrderProfileXfaDesk({
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
});
return () => h('div');
},
});
mount(Host, {
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
workbench: { regionLabels: { order_field: '字段 {count}' } },
} } } } })] },
});
for (let i = 0; i < 40; i += 1) {
await flushPromises();
if (!desk.loading.value) break;
}
await desk.onCanvasCreate({ x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 });
expect(suggestUnifiedMappingMock).not.toHaveBeenCalled();
expect(desk.selectedBindingId.value).toBeTruthy();
expect(desk.creationKind.value).toBeNull();
expect(desk.canvasRegions.value).toEqual(expect.arrayContaining([expect.objectContaining({
id: desk.selectedBindingId.value,
kind: 'xfa_visual',
pageNo: 1,
region: { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
visualBindingStatus: 'suggested',
})]));
}, 15000);
it('blocks saving a drawn XFA box until Schema and datasets bindings are completed', async () => {
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
const Host = defineComponent({
setup() {
desk = useOrderProfileXfaDesk({
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
});
return () => h('div');
},
});
mount(Host, {
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
xfaWorkbench: {
loadFailed: 'fail', pageUnavailable: 'native page unavailable',
blocker: { incomplete_visual_binding: '请先完成每个手工视觉框的 Schema 字段和 datasets 路径绑定' },
},
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
workbench: { regionLabels: { order_field: '字段 {count}' } },
} } } } })] },
});
for (let i = 0; i < 40; i += 1) {
await flushPromises();
if (!desk.loading.value) break;
}
await desk.onCanvasCreate({ x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 });
await expect(desk.saveDraft()).resolves.toBe(false);
expect(saveDraftMock).not.toHaveBeenCalled();
expect(messageErrorMock).toHaveBeenCalledWith('请先完成每个手工视觉框的 Schema 字段和 datasets 路径绑定');
}, 15000);
it('shows the OCR worker error code when an automark job fails', async () => {
getAutomarkJobMock.mockResolvedValueOnce({
job_id: 9,
status: 'failed',
error_code: 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_UNAVAILABLE',
message: 'XFA native PDF OCR is unavailable',
suggestions: [],
});
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
const Host = defineComponent({
setup() {
desk = useOrderProfileXfaDesk({
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
});
return () => h('div');
},
});
mount(Host, {
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
xfaAutoMark: { enqueueFailed: '入队失败', jobFailed: '任务失败', jobFailedWithCode: '自动标记不可用({code}):{message}' },
} } } } })] },
});
for (let i = 0; i < 40; i += 1) {
await flushPromises();
if (!desk.loading.value) break;
}
await expect(desk.startAutomarkJob()).rejects.toThrow('SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_UNAVAILABLE');
expect(messageErrorMock).toHaveBeenCalledWith(
'自动标记不可用(SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_UNAVAILABLE):XFA native PDF OCR is unavailable',
);
}, 15000);
it('projects XFA automark suggestions onto the shared canvas without persisting bindings', async () => {
getAutomarkJobMock.mockResolvedValueOnce({
job_id: 9,
status: 'success',
kind: 'visual_binding',
candidates: [{
suggestion_id: 'sugg-1',
field_key: 'invoiced-to-path',
field_code: 'customer_po_no',
page_no: 1,
normalized_bbox: { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
match_class: 'medium',
suggestion_origin: 'ocr',
confidence: 0.95,
needs_review: false,
}],
preview_render_checksum: 'r'.repeat(64),
});
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
const Host = defineComponent({
setup() {
desk = useOrderProfileXfaDesk({
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
});
return () => h('div');
},
});
mount(Host, {
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
xfaAutoMark: { enqueueFailed: '入队失败', jobFailed: '任务失败' },
} } } } })] },
});
for (let i = 0; i < 40; i += 1) {
await flushPromises();
if (!desk.loading.value) break;
}
expect(desk.activeXfaPdfGrant.value?.preview_token).toBe('xfa-pdf-token');
await desk.startAutomarkJob();
// XFA 自动标注必须以 XFA desk 选定的 annotation sample 为输入,
// 不允许退回到普通 PDF 表单的 documentId。
expect(enqueueAutomarkMock).toHaveBeenCalledWith(52, expect.objectContaining({
document_id: 85,
page_no: 1,
}));
expect(desk.definition.value?.bindings).toHaveLength(0);
expect(desk.canvasRegions.value).toEqual(expect.arrayContaining([expect.objectContaining({
id: 'automark:sugg-1',
kind: 'xfa_visual',
pageNo: 1,
region: { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
visualBindingStatus: 'suggested',
})]));
}, 15000);
it('restores only unresolved persisted automark suggestions for the annotation document', async () => {
detailDefinition.value = {
...structuredClone(baseDefinition),
xfa_ocr_automark: {
job_id: 11,
document_id: 85,
preview_render_checksum: 'r'.repeat(64),
render_mode: 'native_pdf',
suggestions: [
{
suggestion_id: 'open-suggestion',
field_key: 'invoiced-to-path',
field_code: 'customer_po_no',
page_no: 1,
normalized_bbox: { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
match_class: 'medium',
},
{
suggestion_id: 'resolved-suggestion',
field_key: 'invoiced-to-path',
field_code: 'customer_po_no',
page_no: 1,
normalized_bbox: { x0: 0.5, y0: 0.6, x1: 0.7, y1: 0.8 },
decision: 'rejected',
},
],
},
};
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
const Host = defineComponent({
setup() {
desk = useOrderProfileXfaDesk({
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
});
return () => h('div');
},
});
mount(Host, {
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
xfaAutoMark: { enqueueFailed: '入队失败', jobFailed: '任务失败' },
} } } } })] },
});
for (let i = 0; i < 40; i += 1) {
await flushPromises();
if (!desk.loading.value) break;
}
expect(desk.autoMarkSuggestions.value.map((item) => item.suggestion_id)).toEqual(['open-suggestion']);
expect(desk.canvasRegions.value.map((item) => item.id)).toContain('automark:open-suggestion');
expect(desk.canvasRegions.value.map((item) => item.id)).not.toContain('automark:resolved-suggestion');
expect(desk.definition.value?.bindings).toHaveLength(0);
}, 15000);
});
@@ -0,0 +1,85 @@
/**
* 用途:验证 XFA 受控原 PDF 预览使用 PDF.js 普通页面外观渲染。
* 依赖:Vitest、Vue Test Utils、OrderProfileDocumentCanvas。
* 逻辑:hybrid XFA 的 getXfa() 可为空;预览必须走 page.render(),保留实际页面外观流。
*/
import { flushPromises, mount } from '@vue/test-utils';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createI18n } from 'vue-i18n';
import OrderProfileDocumentCanvas from './OrderProfileDocumentCanvas.vue';
const { getDocumentMock, getPageMock, renderMock } = vi.hoisted(() => ({
getDocumentMock: vi.fn(),
getPageMock: vi.fn(),
renderMock: vi.fn(),
}));
vi.mock('pdfjs-dist', () => ({
GlobalWorkerOptions: {},
getDocument: (...args: unknown[]) => getDocumentMock(...args),
}));
vi.mock('pdfjs-dist/build/pdf.worker.min.mjs?url', () => ({ default: '/pdf.worker.min.mjs' }));
vi.mock('@/shared/utils/auth', () => ({ getAuthHeaders: () => ({ Authorization: 'Bearer test' }) }));
describe('OrderProfileDocumentCanvas PDF preview', () => {
beforeEach(() => {
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({} as CanvasRenderingContext2D);
renderMock.mockReset();
renderMock.mockReturnValue({ promise: Promise.resolve() });
getPageMock.mockReset();
getPageMock.mockResolvedValue({
getViewport: vi.fn(({ scale }: { scale: number }) => ({ width: 600 * scale, height: 800 * scale })),
render: renderMock,
getXfa: vi.fn(async () => null),
});
getDocumentMock.mockReset();
getDocumentMock.mockReturnValue({ promise: Promise.resolve({ numPages: 2, getPage: getPageMock }) });
vi.stubGlobal('fetch', vi.fn(async () => new Response(new Uint8Array([37, 80, 68, 70]), { status: 200 })));
});
it('renders hybrid XFA through the ordinary page appearance when getXfa is empty', async () => {
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();
// 关键断言:hybrid XFA 不依赖 getXfa/XfaLayer,使用页面外观流渲染动态可见值。
expect(getDocumentMock).toHaveBeenCalledWith(expect.objectContaining({ data: expect.any(Uint8Array) }));
expect(getPageMock).toHaveBeenCalledWith(1);
expect(renderMock).toHaveBeenCalledWith(expect.objectContaining({ canvasContext: expect.anything() }));
expect(wrapper.find('canvas.pdf-page').exists()).toBe(true);
expect(wrapper.emitted('pageCount')?.[0]).toEqual([2]);
});
it('keeps XFA suggestion regions on the same scaled coordinate plane as the PDF page', async () => {
const wrapper = mount(OrderProfileDocumentCanvas, {
props: {
profileId: 71,
pdfPreview: { preview_token: 'single-use-token' },
regions: [{
id: 'automark:sugg-1', kind: 'xfa_visual', label: '自动标注', pageNo: 1,
region: { x0: .5, y0: .5, x1: .75, y1: .75 },
}],
pageNo: 1,
pageCount: 1,
},
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] },
});
await flushPromises();
await flushPromises();
await wrapper.findAll('.zoom-control button')[1].trigger('click');
await flushPromises();
await flushPromises();
// PDF.js 的 viewport 已是 125%(750px);覆盖框必须以同一宽度百分比定位,不能二次放大到 937.5px。
expect(wrapper.find('.canvas-stage').attributes('style')).toContain('width: 750px');
expect(wrapper.find('.region').attributes('style')).toContain('left: 50%');
});
});
@@ -6,17 +6,38 @@
画布区域 aria-label 走四语言 i18n;可选 emptyHint/loadError 区分 XFA page_unavailable 与 PDF 缺样本空态。
-->
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue';
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 { getAuthHeaders } from '@/shared/utils/auth';
import type { OrderProfileCanvasRegion, OrderProfilePreviewPageGrant } from '@/features/admin/types/shipping-order-document-profile.types';
import type { PDFDocumentProxy } from 'pdfjs-dist';
type PdfJsModule = typeof import('pdfjs-dist');
let pdfjsLoader: Promise<PdfJsModule> | null = null;
/** 动态加载 PDF.js 与 worker;坐标 PDF 与 XFA 在受控管理员画布按需共用。 */
async function loadPdfJs(): Promise<PdfJsModule> {
if (!pdfjsLoader) {
pdfjsLoader = (async () => {
const [pdfjs, workerMod] = await Promise.all([
import('pdfjs-dist'),
import('pdfjs-dist/build/pdf.worker.min.mjs?url'),
]);
pdfjs.GlobalWorkerOptions.workerSrc = workerMod.default;
return pdfjs;
})();
}
return pdfjsLoader;
}
const props = defineProps<{
profileId: number | null;
grant?: OrderProfilePreviewPageGrant | null;
mode?: 'edit' | 'readonly';
previewPagePath?: string | null;
/** 原 PDF 令牌;启用后用 PDF.js 页面外观流渲染,绝不生成可下载 URL。 */
pdfPreview?: { preview_token: string } | null;
regions: OrderProfileCanvasRegion[];
selectedRegionId?: string | null;
creationKind?: OrderProfileCanvasRegion['kind'] | null;
@@ -58,6 +79,7 @@ const emit = defineEmits<{
delete: [];
save: [];
page: [pageNo: number];
pageCount: [count: number];
acceptSuggestion: [];
rejectSuggestion: [];
/** 页图拉取失败(父级可标 page_unavailable)。 */
@@ -67,6 +89,10 @@ const emit = defineEmits<{
}>();
const imageUrl = ref('');
const pdfCanvas = ref<HTMLCanvasElement | null>(null);
const pdfRendered = ref(false);
const pdfPageSize = ref<{ width: number; height: number } | null>(null);
let pdfDocument: PDFDocumentProxy | null = null;
const loading = ref(false);
/** 本组件内 fetch 失败文案;与 props.loadError 合并展示。 */
const internalLoadError = ref<string | null>(null);
@@ -87,26 +113,62 @@ const emptyStateText = computed(() => (
props.emptyHint || t('admin.shippingOrderProfiles.workbench.selectBoundPdf')
));
/**
* 将内存中的原 PDF 按真实页面外观流绘制到 Canvas。
* 核心逻辑:坐标 PDF 与 hybrid XFA 都用 page.render(),不生成可下载 URL。
*/
const renderPdfPage = async (pdf: PDFDocumentProxy) => {
await nextTick();
const targetPage = Math.min(Math.max(props.pageNo, 1), pdf.numPages);
const page = await pdf.getPage(targetPage);
const canvas = pdfCanvas.value;
const context = canvas?.getContext('2d');
if (!canvas || !context) throw new Error('PDF canvas is unavailable');
const viewport = page.getViewport({ scale: zoom.value });
pdfPageSize.value = { width: viewport.width, height: viewport.height };
canvas.width = Math.ceil(viewport.width);
canvas.height = Math.ceil(viewport.height);
await page.render({ canvas, canvasContext: context, viewport }).promise;
pdfRendered.value = true;
};
/**
* 下载一次性 PNG 并在组件卸载或切页时回收浏览器 blob。
* 核心逻辑:失败时写入 internalLoadError 并 emit loadFailed,避免误导为「未绑定样本」。
*/
const loadPage = async () => {
if (!props.profileId || !props.grant) {
if (!props.profileId || (!props.grant && !props.pdfPreview)) {
URL.revokeObjectURL(imageUrl.value);
imageUrl.value = '';
pdfRendered.value = false;
internalLoadError.value = null;
return;
}
loading.value = true;
URL.revokeObjectURL(imageUrl.value);
imageUrl.value = '';
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) {
const response = await fetch(
`${previewPath}?preview_token=${encodeURIComponent(props.pdfPreview.preview_token)}`,
{ headers: getAuthHeaders(), cache: 'no-store' },
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const pdfjs = await loadPdfJs();
const bytes = new Uint8Array(await response.arrayBuffer());
pdfDocument = await pdfjs.getDocument({ data: bytes, enableXfa: true }).promise;
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}/${props.grant.page_no}?preview_token=${encodeURIComponent(props.grant.preview_token)}`,
`${previewPath}/${grant.page_no}?preview_token=${encodeURIComponent(grant.preview_token)}`,
{ headers: getAuthHeaders(), cache: 'no-store' },
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
@@ -244,8 +306,14 @@ const goToPage = () => {
if (nextPage !== props.pageNo) emit('page', nextPage);
};
defineExpose({ zoomIn: () => adjustZoom(.25), zoomOut: () => adjustZoom(-.25), resetZoom });
watch(() => props.grant?.preview_token, () => { void loadPage(); }, { immediate: true });
watch(() => props.pageNo, (value) => { pageInput.value = value; });
watch(() => [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);
});
watch(zoom, async () => {
if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument);
});
onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(imageUrl.value); });
</script>
@@ -256,7 +324,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
? t('admin.shippingOrderProfiles.workbench.readonlyCanvasAriaLabel')
: t('admin.shippingOrderProfiles.workbench.annotationCanvasAriaLabel')"
>
<header v-if="imageUrl" class="canvas-toolbar">
<header v-if="imageUrl || pdfRendered" class="canvas-toolbar">
<div class="toolbar-actions">
<template v-if="!readonlyMode">
<button type="button" :disabled="undoDisabled" :title="t('admin.shippingOrderProfiles.workbench.undo')" @click="emit('undo')"><RotateCcw /></button>
@@ -287,14 +355,14 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
<button type="button" class="fit-action" @click="resetZoom">{{ t('admin.shippingOrderProfiles.workbench.fitPage') }}</button>
</div>
</header>
<div v-if="loading" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}</div>
<div v-if="loading && !pdfPreview" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}</div>
<div v-else-if="displayLoadError" class="canvas-state canvas-state--error" role="alert">
<p>{{ displayLoadError }}</p>
<button type="button" class="canvas-retry" @click="onRetryClick">
{{ t('admin.shippingOrderProfiles.workbench.retryCanvas') }}
</button>
</div>
<div v-else-if="!imageUrl" class="canvas-state">{{ emptyStateText }}</div>
<div v-else-if="!imageUrl && !pdfRendered && !pdfPreview" class="canvas-state">{{ emptyStateText }}</div>
<div v-else class="canvas-work-area" :class="{ readonly: readonlyMode }">
<aside v-if="!readonlyMode" class="annotation-tools">
<template v-if="xfaVisualTools">
@@ -313,8 +381,17 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
<p v-if="suggestionProgress" class="suggestion-progress" :class="{ failed: !suggesting }">{{ suggestionProgress }}</p>
</aside>
<div ref="viewport" class="canvas-viewport" :class="{ panning: !creationKind || readonlyMode }" @wheel.prevent="handleWheel">
<div ref="canvas" class="canvas-stage" :class="{ drawing: creationKind && !readonlyMode }" :style="{ '--canvas-zoom': zoom }" @pointerdown="beginCreation">
<img :src="imageUrl" :alt="t('admin.shippingOrderProfiles.workbench.pagePreviewAlt')" draggable="false" />
<div
ref="canvas"
class="canvas-stage"
:class="{ drawing: creationKind && !readonlyMode, 'canvas-stage--xfa': Boolean(pdfPageSize) }"
:style="pdfPageSize
? { width: `${pdfPageSize.width}px`, minWidth: '0', '--canvas-zoom': zoom }
: { '--canvas-zoom': zoom }"
@pointerdown="beginCreation"
>
<img v-if="imageUrl" :src="imageUrl" :alt="t('admin.shippingOrderProfiles.workbench.pagePreviewAlt')" draggable="false" />
<canvas v-else ref="pdfCanvas" class="pdf-page" aria-label="XFA PDF preview" />
<div
v-for="region in regions"
:key="region.id"
@@ -387,6 +464,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
.canvas-viewport.panning:active { cursor: grabbing; }
.canvas-stage { position: relative; margin: auto; width: calc(100% * var(--canvas-zoom)); min-width: 42rem; box-shadow: 0 16px 40px rgba(0,0,0,.35); }
.canvas-stage img { display: block; width: 100%; user-select: none; }
.canvas-stage canvas.pdf-page { display: block; background: white; pointer-events: none; user-select: none; }
.canvas-stage.drawing { cursor: crosshair; }
.creation-region { position: absolute; z-index: 5; box-sizing: border-box; border: 2px dashed #34d399; background: rgb(16 185 129 / .18); pointer-events: none; }
.annotation-tools { display: grid; align-content: start; gap: .3rem; flex: 0 0 2.65rem; padding: .3rem; border: 1px solid rgb(71 85 105 / .9); border-radius: .5rem; background: rgb(15 23 42 / .94); box-shadow: 0 8px 24px rgb(15 23 42 / .3); }
@@ -432,7 +510,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
.region-exclusion .region-label, .region-exclusion .resize-handle { background: #b91c1c; }
.region-xfa_visual { z-index: 2; border: 1.5px solid #38bdf8; background: rgb(14 165 233 / .12); }
.region-xfa_visual .region-label, .region-xfa_visual .resize-handle { background: #0369a1; }
.region-visual--suggested { border-color: #f59e0b; background: rgb(245 158 11 / .14); }
.region-visual--suggested { 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); }
.region-visual--confirmed .region-label { background: #15803d; }
@@ -1,7 +1,7 @@
/**
* features/admin/modules/shipping-order-document-profiles/composables/useOrderProfileXfaDesk.ts
* 用途:XFA 混合数据源标注的数据层(definition、原生 PDF 页授权、视觉绑定、OCR automark、拆分、集合重确认)。
* 依赖:Profile/XFA API、automark API、xfaProfileMapping.utils、vue-i18n、useMessage。
* 用途:XFA 混合数据源标注的数据层(definition、原生 PDF 页授权、视觉绑定、统一 PDF automark、拆分、集合重确认)。
* 依赖:Profile/XFA API、统一 PDF automark API、xfaProfileMapping.utils、vue-i18n、useMessage。
* 逻辑:仅由 OrderProfileEditorPage 消费;不渲染独立工作台/画布;不请求 /xfa/preview;
* datasets 覆盖为建模辅助;OCR 仅由工具栏触发;旧 worker 的 PREVIEW_UNAVAILABLE 按空建议软成功。
*/
@@ -12,31 +12,28 @@ import { useMessage } from '@/shared/composables/useMessage';
import { getShippingOrderSchemaState } from '@/features/admin/api/shipping-order-schema.api';
import {
acceptOrderProfileXfaOcrAutomarkSuggestion,
authorizeOrderProfilePreviewPages,
authorizeOrderProfilePdfPreview,
confirmOrderProfileXfaVisualBinding,
enqueueOrderProfileXfaOcrAutomark,
enqueueOrderProfilePdfAutomark,
getOrderDocumentProfileDetail,
getOrderProfileSampleXfaCollections,
getOrderProfileSampleXfaFieldTree,
getOrderProfileXfaOcrAutomarkJob,
getOrderProfilePdfAutomarkJob,
previewOrderProfileSampleXfaSplitRules,
listOrderProfileBoundSamples,
rejectOrderProfileXfaOcrAutomarkSuggestion,
rejectOrderProfileXfaVisualBinding,
saveOrderDocumentProfileDraft,
suggestOrderProfileXfaUnifiedMapping,
} from '@/features/admin/api/shipping-order-document-profile.api';
import type {
OrderProfileCanvasRegion,
OrderProfilePreviewPageGrant,
OrderProfileXfaPdfPreviewGrant,
OrderXfaDatasetProfileDefinition,
XfaCollectionCandidate,
XfaFieldTreeNode,
XfaSplitRuleSet,
XfaUnifiedFieldBinding,
XfaUnifiedMappingSuggestResponse,
XfaValueBindingType,
XfaVisualBindingCandidate,
} from '@/features/admin/types/shipping-order-document-profile.types';
import { isXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
import type { ShippingOrderFieldConfig } from '@/features/admin/types/shipping-order-schema.types';
@@ -87,6 +84,7 @@ export interface XfaAutoMarkSuggestion {
iou?: number | null;
needs_review?: boolean | null;
reason_code?: string | null;
/** Worker 产出的页面定位;仅用于临时建议框,不属于 datasets 正式值。 */
page_no?: number;
normalized_bbox?: {
x0: number;
@@ -95,6 +93,14 @@ export interface XfaAutoMarkSuggestion {
y1: number;
};
}
interface PersistedXfaAutomarkResult {
job_id?: number | string | null;
document_id?: number | string | null;
preview_render_checksum?: string | null;
render_mode?: string | null;
suggestions?: unknown;
}
export type XfaDeskSaveState = 'saved' | 'saving' | 'failed' | 'readonly';
export interface UseOrderProfileXfaDeskOptions {
@@ -152,8 +158,8 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
const displayName = ref('');
const profileCode = ref('');
const schemaVersionId = ref(0);
const pageGrant = ref<OrderProfilePreviewPageGrant | null>(null);
const pageGrants = ref<OrderProfilePreviewPageGrant[]>([]);
/** XFA 原 PDF 只读一次性授权;PDF.js 直接消费为内存字节。 */
const xfaPdfGrant = ref<OrderProfileXfaPdfPreviewGrant | null>(null);
const pageNo = ref(1);
const pageCount = ref(1);
/** 画布唯一模式:原生 PDF 页图(与非 XFA 同路径)。 */
@@ -176,6 +182,60 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
const automarkJobError = ref<string | null>(null);
let automarkPollTimer: ReturnType<typeof setInterval> | null = null;
/**
* 归一化 Worker/已持久化 automark 建议,确保轮询与刷新恢复投影相同的临时画框。
* @param item - Worker Job 或 definition.xfa_ocr_automark 中的一条原始建议
*/
function mapAutomarkSuggestion(item: Record<string, any>): XfaAutoMarkSuggestion {
return {
suggestion_id: String(item.suggestion_id || ''),
field_key: item.field_key,
field_code: item.field_code,
page_no: Number(item.page_no || 0) || undefined,
normalized_bbox: item.normalized_bbox,
suggestion_origin: item.suggestion_origin,
confidence: item.confidence,
status: item.status,
match_class: item.match_class,
summary: item.summary,
ocr_text: item.ocr_text,
dataset_value: item.dataset_value,
iou: item.iou,
needs_review: Boolean(item.needs_review || item.match_class === 'needs_review'),
};
}
/**
* 从 Profile definition 恢复当前标注样本尚未处理的 automark 建议。
* 核心逻辑:结果必须属于当前 annotation document;含 decision 的建议已由服务端处理,
* 禁止再次投影到画布或误导用户重复接受/驳回。
* @param rawDefinition - Detail API 返回的原始 XFA definition
*/
function restorePersistedAutomarkSuggestions(
rawDefinition: OrderXfaDatasetProfileDefinition,
): void {
const persisted = (rawDefinition as OrderXfaDatasetProfileDefinition & {
xfa_ocr_automark?: PersistedXfaAutomarkResult;
}).xfa_ocr_automark;
automarkJobStatus.value = 'idle';
automarkJobError.value = null;
automarkJobId.value = null;
autoMarkSuggestions.value = [];
if (!persisted || Number(persisted.document_id || 0) !== annotationDocumentId.value) return;
const jobId = Number(persisted.job_id || 0);
automarkJobId.value = jobId > 0 ? jobId : null;
const checksum = String(persisted.preview_render_checksum || '').trim();
if (checksum) syntheticPreviewChecksum.value = checksum;
syntheticRenderMode.value = String(persisted.render_mode || 'native_pdf');
const suggestions = Array.isArray(persisted.suggestions) ? persisted.suggestions : [];
autoMarkSuggestions.value = suggestions
.filter((item): item is Record<string, any> => Boolean(item && typeof item === 'object'))
.filter((item) => !item.decision)
.map(mapAutomarkSuggestion)
.filter((item) => item.suggestion_id);
}
/** 画布工具 kind → visual_binding.region_kind。 */
function mapCreationKindToRegionKind(kind: OrderProfileCanvasRegion['kind'] | null): string {
switch (kind) {
@@ -221,7 +281,7 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
return { ...def, bindings };
}
const pagesReady = computed(() => pageGrants.value.length > 0 && Boolean(pageGrant.value));
const pagesReady = computed(() => Boolean(xfaPdfGrant.value));
/** 兼容旧名:编辑画布就绪 = 原生 PDF 页授权成功。 */
const syntheticReady = computed(() => pagesReady.value);
/** 编辑态不再因 synthetic 失败阻断标注。 */
@@ -238,15 +298,13 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
readonly.value
|| pageUnavailable.value
));
const activePageGrant = computed(() => pageGrant.value);
/** 复用普通 PDF 预览路径(undefined 时 canvas 使用默认 preview-pages)。 */
const activePreviewPagePath = computed(() => undefined as string | undefined);
const activeXfaPdfGrant = computed(() => xfaPdfGrant.value);
/** XFA 画布只通过受控原件入口读取 PDF.js 输入。 */
const activePreviewPagePath = computed(() => '/api/admin/shipping-notice/order-document-profiles/'
+ `${profileId.value}/pdf-preview`);
const creationKind = ref<OrderProfileCanvasRegion['kind'] | null>('order_field');
const selectedBindingId = ref<string | null>(null);
const diagnosticsOpen = ref(false);
const suggestingBinding = ref(false);
const pendingSuggestion = ref<XfaUnifiedMappingSuggestResponse | null>(null);
const pendingDrawRegion = ref<OrderProfileCanvasRegion['region'] | null>(null);
const bindingHistory = ref<XfaUnifiedFieldBinding[][]>([]);
const bindingFuture = ref<XfaUnifiedFieldBinding[][]>([]);
const diagnosticsPanel = ref<HTMLElement | null>(null);
@@ -256,17 +314,13 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
let focusTrapCleanup: (() => void) | null = null;
let dragCheckpointTaken = false;
const pendingCandidateCount = computed(() => (
pendingSuggestion.value?.visual_suggestion?.candidates?.length || 0
));
const flatNodes = computed(() => flattenXfaTreeNodes(tree.value));
/** 将 definition.bindings 投影为当前页画布区域(可选叠加 datasets 样本辅助文案)。 */
const canvasRegions = computed((): OrderProfileCanvasRegion[] => {
if (!definition.value?.bindings?.length) return [];
const bindings = definition.value?.bindings || [];
const byPath = new Map(flatNodes.value.map((item) => [item.pathId, item]));
return definition.value.bindings
const persisted = bindings
.filter((item) => item.visual_binding?.page_no === pageNo.value)
.map((item) => {
const sample = datasetsOverlayEnabled.value
@@ -285,6 +339,18 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
visualBindingStatus: item.visual_binding.status,
};
});
const suggested = autoMarkSuggestions.value
.filter((item) => item.page_no === pageNo.value && item.normalized_bbox)
.map((item) => ({
id: `automark:${item.suggestion_id}`,
kind: 'xfa_visual' as const,
label: item.field_code || item.field_key || item.suggestion_id,
region: item.normalized_bbox!,
fieldCode: item.field_code || null,
pageNo: item.page_no!,
visualBindingStatus: 'suggested' as const,
}));
return [...persisted, ...suggested];
});
const selectedPathLabel = computed(() => (
@@ -524,6 +590,18 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
authoritativePathId.value,
));
const blockers = computed(() => summarizeXfaMappingBlockers(coverage.value));
/** 手工视觉框可先留在浏览器草稿,但保存前必须完成 Schema 与 datasets 正式绑定。 */
const incompleteVisualBindingCount = computed(() => (
(definition.value?.bindings || []).filter((binding) => {
const fieldBound = schemaFields.value.some((field) => (
field.enabled !== false
&& field.field_id === binding.field_id
&& field.field_code === binding.field_code
&& field.scope === binding.scope
));
return !fieldBound || !String(binding.value_binding?.path_id || '').trim();
}).length
));
const splitRuleSummary = computed(() => {
const sets = definition.value?.split_rules || [];
const total = sets.length;
@@ -600,14 +678,10 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
await restoreCollectionSelection(profile.definition);
await refreshSplitRulePreviews(profile.definition.split_rules || []);
await loadPages();
pageLoadError.value = null;
// 编辑路径仅用原生 PDF 页;不自动请求 /xfa/preview,不自动跑 OCR(由工具栏触发)。
syntheticPreviewStatus.value = 'idle';
stopAutomarkPoll();
automarkJobStatus.value = 'idle';
automarkJobError.value = null;
automarkJobId.value = null;
autoMarkSuggestions.value = [];
restorePersistedAutomarkSuggestions(profile.definition as OrderXfaDatasetProfileDefinition);
} catch (error) {
loadError.value = true;
definition.value = null;
@@ -649,18 +723,20 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
/**
* 申请受控 PDF 单页预览令牌,供画布渲染。
* 核心逻辑:XFA 映射与原生 PDF 页授权独立;授权失败保留页级错误,
* 让用户重试页图而非误判 datasets 解析失败。
*/
async function loadPages(): Promise<void> {
if (!annotationDocumentId.value) return;
try {
const pages = await authorizeOrderProfilePreviewPages(profileId.value, annotationDocumentId.value);
pageGrants.value = pages.pages || [];
pageCount.value = pages.page_count || 1;
pageNo.value = Math.min(Math.max(1, pageNo.value), pageCount.value);
pageGrant.value = pageGrants.value.find((item) => item.page_no === pageNo.value) || pageGrants.value[0] || null;
const grant = await authorizeOrderProfilePdfPreview(profileId.value, annotationDocumentId.value);
xfaPdfGrant.value = grant;
pageCount.value = 1;
pageNo.value = 1;
pageLoadError.value = null;
} catch {
pageGrant.value = null;
pageGrants.value = [];
xfaPdfGrant.value = null;
pageLoadError.value = t('admin.shippingOrderProfiles.xfaWorkbench.pageUnavailable');
}
}
@@ -676,7 +752,7 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
}
/**
* 入队 OCR 自动标记并轮询至终态(仅工具栏「自动标记」主动触发)。
* 入队统一 PDF 自动标记并轮询至终态(仅工具栏「自动标记」主动触发)。
* 核心逻辑:UI 进度由调用方 suggestionProgress 驱动;本函数不渲染专用底栏;
* 旧 worker 的 XFA_PREVIEW_UNAVAILABLE 按空建议软成功,不弹错误码。
* @param force 是否强制重跑
@@ -687,15 +763,13 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
automarkJobError.value = null;
automarkJobStatus.value = 'queued';
try {
const res = await enqueueOrderProfileXfaOcrAutomark(profileId.value, {
const res = await enqueueOrderProfilePdfAutomark(profileId.value, {
document_id: annotationDocumentId.value,
page_no: Number(pageNo.value) || 1,
force,
});
automarkJobId.value = Number(res.job_id);
automarkJobStatus.value = String(res.status || 'queued');
if (res.preview_render_checksum) {
syntheticPreviewChecksum.value = String(res.preview_render_checksum);
}
syntheticRenderMode.value = 'native_pdf';
// 同步轮询至终态,供页面复用 suggestingRegions / suggestionProgress。
@@ -723,27 +797,19 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
}
/**
* 单次拉取 OCR Job;终态写入建议;硬失败抛错;预览不可用按空建议软成功。
* 单次拉取统一 PDF Job;终态写入视觉绑定建议;硬失败抛错;预览不可用按空建议软成功。
*/
async function pollAutomarkJob(): Promise<void> {
if (!automarkJobId.value) return;
const res = await getOrderProfileXfaOcrAutomarkJob(profileId.value, automarkJobId.value);
const res = await getOrderProfilePdfAutomarkJob(profileId.value, automarkJobId.value);
automarkJobStatus.value = String(res.status || 'running');
const suggestions = Array.isArray(res.suggestions) ? res.suggestions : [];
autoMarkSuggestions.value = suggestions.map((item: any) => ({
suggestion_id: String(item.suggestion_id || ''),
field_key: item.field_key,
field_code: item.field_code,
suggestion_origin: item.suggestion_origin,
confidence: item.confidence,
status: item.status,
match_class: item.match_class,
summary: item.summary,
ocr_text: item.ocr_text,
dataset_value: item.dataset_value,
iou: item.iou,
needs_review: Boolean(item.needs_review || item.match_class === 'needs_review'),
})).filter((item) => item.suggestion_id);
const suggestions = res.kind === 'visual_binding' && Array.isArray(res.candidates)
? res.candidates
: [];
autoMarkSuggestions.value = suggestions
.filter((item): item is Record<string, any> => Boolean(item && typeof item === 'object'))
.map(mapAutomarkSuggestion)
.filter((item) => item.suggestion_id);
const status = automarkJobStatus.value;
if (status === 'failed' || status === 'dead') {
@@ -756,14 +822,17 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
if (isSoftEmptyAutomarkFailure(failCode, failText)) {
return;
}
throw new Error(t('admin.shippingOrderProfiles.xfaAutoMark.jobFailed'));
const errorMessage = failCode
? t('admin.shippingOrderProfiles.xfaAutoMark.jobFailedWithCode', {
code: failCode,
message: failText || t('admin.shippingOrderProfiles.xfaAutoMark.jobFailed'),
})
: (failText || t('admin.shippingOrderProfiles.xfaAutoMark.jobFailed'));
throw new Error(errorMessage);
}
if (['succeeded', 'success'].includes(status)) {
stopAutomarkPoll();
automarkJobStatus.value = 'idle';
if (res.preview_render_checksum) {
syntheticPreviewChecksum.value = String(res.preview_render_checksum);
}
}
}
@@ -868,30 +937,73 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
function onCanvasPage(nextPage: number): void {
pageNo.value = nextPage;
pageLoadError.value = null;
pageGrant.value = pageGrants.value.find((item) => item.page_no === nextPage) || null;
syntheticPageGrant.value = syntheticPageGrants.value.find((item) => item.page_no === nextPage) || null;
}
/**
* 画框完成后调用统一 mapping 建议 API,展示候选面板。
* 接收统一 PDF Job 返回的视觉绑定候选并投影到共享画布状态。
*
* 自动标注任务由父工作台统一发起和轮询;本函数只处理 XFA 特有的
* datasets 视觉绑定候选,不重新入队,也不决定 PDF 文档类型。
*/
function applyPdfAutomarkCandidates(candidates: Array<Record<string, unknown>>): void {
autoMarkSuggestions.value = candidates
.filter((item): item is Record<string, any> => Boolean(item && typeof item === 'object'))
.map(mapAutomarkSuggestion)
.filter((item) => item.suggestion_id);
}
/** 将统一 Job 的原生 PDF 渲染身份写入后续视觉绑定确认上下文。 */
function applyPdfAutomarkRenderIdentity(checksum?: string | null): void {
if (checksum) syntheticPreviewChecksum.value = String(checksum);
syntheticRenderMode.value = 'native_pdf';
}
/** 接收 PDF.js 实际页数,避免 XFA 原件被错误固定为一页。 */
function setRenderedPageCount(count: number): void {
pageCount.value = Math.max(1, Math.floor(Number(count) || 1));
pageNo.value = Math.min(pageNo.value, pageCount.value);
}
/**
* 手工画框后立即创建本地视觉绑定并选中,和普通 PDF 的手工标注保持一致。
* 核心逻辑:视觉框只作为待复核证据,正式 Schema/datasets 映射仍由右侧配置完成;
* 不调用机器候选接口,也不产生自动标注底栏。
* @param region 归一化相对坐标框
*/
async function onCanvasCreate(region: OrderProfileCanvasRegion['region']): Promise<void> {
if (readonly.value || !annotationDocumentId.value) return;
pendingDrawRegion.value = region;
suggestingBinding.value = true;
pendingSuggestion.value = null;
try {
pendingSuggestion.value = await suggestOrderProfileXfaUnifiedMapping(profileId.value, {
document_id: annotationDocumentId.value,
if (readonly.value || !definition.value) return;
checkpointBindings();
const bindingId = crypto.randomUUID().replace(/-/g, '').slice(0, 24);
const sequence = (definition.value.bindings || []).length + 1;
const nextBinding: XfaUnifiedFieldBinding = {
binding_id: bindingId,
// 未选择 Schema 字段前仅在浏览器草稿存在;服务端保存契约会拒绝该未完成映射。
field_id: bindingId,
field_code: t('admin.shippingOrderProfiles.workbench.regionLabels.order_field', { count: sequence }),
scope: 'header',
value_binding: {
type: 'xfa_dataset',
path_id: null,
data_path: null,
},
visual_binding: {
page_no: pageNo.value,
normalized_bbox: region,
});
} catch (error) {
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.xfaUnified.suggestFailed'));
} finally {
suggestingBinding.value = false;
}
source: 'user_drawn',
status: 'suggested',
region_kind: mapCreationKindToRegionKind(creationKind.value),
},
};
definition.value = {
...definition.value,
bindings: [...(definition.value.bindings || []), nextBinding],
};
selectedBindingId.value = bindingId;
selectedPathId.value = null;
selectedPathIsLeaf.value = false;
selectedRuleId.value = null;
creationKind.value = null;
}
/**
@@ -899,6 +1011,16 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
* @param bindingId binding_id
*/
function onCanvasSelect(bindingId: string): void {
if (bindingId.startsWith('automark:')) {
const suggestionId = bindingId.slice('automark:'.length);
const suggestion = autoMarkSuggestions.value.find((item) => item.suggestion_id === suggestionId);
if (suggestion?.field_key) {
selectedPathId.value = String(suggestion.field_key);
selectedPathIsLeaf.value = true;
selectedRuleId.value = null;
}
return;
}
selectedBindingId.value = bindingId;
const binding = definition.value?.bindings?.find((item) => item.binding_id === bindingId);
const pathId = binding?.value_binding.path_id;
@@ -909,48 +1031,6 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
}
}
/**
* 将视觉候选写入本地 bindings(suggested),并关联当前选中 Schema 字段(若有)。
* @param candidate 视觉候选
* @param pathId 选中的 datasets path_id
*/
function applyVisualCandidate(candidate: XfaVisualBindingCandidate, pathId: string): void {
if (!definition.value || !pendingDrawRegion.value) return;
checkpointBindings();
const field = schemaFields.value.find((item) => selectedPathId.value && item.field_id);
const node = flatNodes.value.find((item) => item.pathId === pathId);
const bindingId = crypto.randomUUID().replace(/-/g, '').slice(0, 24);
const scope = node ? resolveXfaNodeScope(pathId, authoritativePathId.value, flatNodes.value) : 'header';
const nextBinding: XfaUnifiedFieldBinding = {
binding_id: bindingId,
field_id: field?.field_id || bindingId,
field_code: field?.field_code || node?.localName || pathId,
scope: scope || 'header',
value_binding: {
type: 'xfa_dataset',
path_id: pathId,
data_path: null,
},
visual_binding: {
page_no: pageNo.value,
normalized_bbox: pendingDrawRegion.value,
source: 'user_drawn',
status: 'suggested',
confidence: candidate.confidence,
region_kind: mapCreationKindToRegionKind(creationKind.value),
} as any,
};
definition.value = {
...definition.value,
bindings: [...(definition.value.bindings || []), nextBinding],
};
selectedBindingId.value = bindingId;
selectedPathId.value = pathId;
selectedPathIsLeaf.value = true;
pendingSuggestion.value = null;
pendingDrawRegion.value = null;
}
/**
* 确认视觉绑定:若本地尚未持久化该 binding,先保存草稿再调 confirm API。
* @param bindingId 目标 binding_id
@@ -1057,11 +1137,6 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
}
}
function dismissPendingSuggestion(): void {
pendingSuggestion.value = null;
pendingDrawRegion.value = null;
}
/**
* 绑定选中叶子或规则结果到同作用域 Schema 字段。
* 规则继承源节点作用域,避免 Header 源规则被错误限制为明细字段。
@@ -1162,6 +1237,10 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
message.error(t('admin.shippingOrderProfiles.xfaWorkbench.blocker.authoritative_collection_required'));
return false;
}
if (incompleteVisualBindingCount.value) {
message.error(t('admin.shippingOrderProfiles.xfaWorkbench.blocker.incomplete_visual_binding'));
return false;
}
const pendingConfirmPaths = Object.keys(splitRuleConfirmationTokens.value);
try {
const payloadDefinition: OrderXfaDatasetProfileDefinition & Record<string, unknown> = {
@@ -1344,19 +1423,12 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
return flatNodes.value.find((item) => item.pathId === pathId)?.sampleValueDisplay || '';
});
const selectedReadingMode = computed(() => (
selectedBinding.value?.value_binding?.type || 'xfa_dataset'
) as XfaValueBindingType);
/** datasets 增量区:仅正式取值为 xfa_dataset 且非锚点/排除时显示。 */
/** datasets 增量区:XFA 正式值固定来自 datasets;视觉框/OCR 只承担定位、证据和复核。 */
const showDatasetsSection = computed(() => (
Boolean(selectedBinding.value)
&& !DATASETS_HIDDEN_KINDS.has(selectedRegionKind.value)
&& selectedReadingMode.value === 'xfa_dataset'
));
const readingModeWarning = computed(() => false);
const collectionSummaryLabel = computed(() => {
const auth = authoritativePathId.value
? (buildXfaPathLabel(authoritativePathId.value, flatNodes.value) || authoritativePathId.value)
@@ -1450,21 +1522,6 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
};
}
/**
* 更新正式取值模式;非 datasets 时右侧展示警告。
*/
function updateSelectedReadingMode(mode: XfaValueBindingType): void {
if (!definition.value || !selectedBindingId.value || readonly.value) return;
definition.value = {
...definition.value,
bindings: (definition.value.bindings || []).map((item) => (
item.binding_id === selectedBindingId.value
? { ...item, value_binding: { ...item.value_binding, type: mode } }
: item
)),
};
}
/**
* 从 datasets 树选择器写入 path_id。
*/
@@ -1580,8 +1637,7 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
mirrorPathIds,
pageNo,
pageCount,
pageGrant,
pageGrants,
xfaPdfGrant,
pagesReady,
previewMode,
syntheticPreviewStatus,
@@ -1591,7 +1647,7 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
pageLoadError,
pageUnavailable,
annotationDisabled,
activePageGrant,
activeXfaPdfGrant,
activePreviewPagePath,
datasetsOverlayEnabled,
creationKind,
@@ -1601,13 +1657,9 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
isFieldLikeSelection,
showDatasetsSection,
selectedSampleValue,
selectedReadingMode,
readingModeWarning,
collectionSummaryLabel,
canvasRegions,
pendingCandidateCount,
pendingSuggestion,
suggestingBinding,
incompleteVisualBindingCount,
bindingHistory,
bindingFuture,
autoMarkSuggestions,
@@ -1629,6 +1681,7 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
onCanvasDragEnd,
onCanvasRegionChange,
onCanvasPage,
setRenderedPageCount,
onCanvasCreate,
onCanvasSelect,
loadSyntheticPreview,
@@ -1636,11 +1689,11 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
reportPageLoadError,
clearPageLoadError,
startAutomarkJob,
applyPdfAutomarkCandidates,
applyPdfAutomarkRenderIdentity,
onAcceptAutomark,
onAdjustAutomark,
onRejectAutomark,
applyVisualCandidate,
dismissPendingSuggestion,
confirmVisualBinding,
rejectVisualBinding,
onBindField,
@@ -1661,7 +1714,6 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
confirmReconfirmCollections,
updateSelectedLabel,
updateSelectedSchemaField,
updateSelectedReadingMode,
updateSelectedDatasetsPath,
};
}