feat(shipping-notice): 收敛复核状态隔离、STP 重试幂等与 XFA 合成预览标注

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-07 02:58:28 +08:00
1 parent 84a881b554
commit 74270adc22
149 files changed
+20111 -3871

No files matched your search

@@ -36,6 +36,7 @@ const documentId = ref(0);
const tableId = ref('');
const authoritativePathId = ref('');
const mirrorPathIds = ref<string[]>([]);
const xfaContextReady = ref(false);
const browserSessionId = crypto.randomUUID();
let sampleRefreshTimer: ReturnType<typeof setTimeout> | null = null;
@@ -50,7 +51,7 @@ const stepThreeLabel = computed(() => (
const canNext = computed(() => {
if (step.value === 1) return Boolean(identity.displayName.trim() && identity.schemaId);
if (step.value === 2) return Boolean(documentId.value);
if (isXfaSample.value) return Boolean(authoritativePathId.value);
if (isXfaSample.value) return Boolean(xfaContextReady.value && authoritativePathId.value);
return Boolean(tableId.value);
});
const steps = computed(() => [
@@ -111,6 +112,7 @@ watch(documentId, async (id) => {
tableId.value = '';
authoritativePathId.value = '';
mirrorPathIds.value = [];
xfaContextReady.value = false;
tables.value = [];
if (!id) return;
await loadTables(id);
@@ -222,6 +224,7 @@ onBeforeUnmount(stopSampleRefresh);
:mirror-path-ids="mirrorPathIds"
@update:authoritative-path-id="authoritativePathId = $event"
@update:mirror-path-ids="mirrorPathIds = $event"
@update:context-ready="xfaContextReady = $event"
/>
<OrderProfileModelStartStep v-else v-model="tableId" :tables="tables" />
</main>
@@ -1,12 +1,15 @@
/**
* features/admin/modules/shipping-order-document-profiles/OrderProfileXfaWorkbench.spec.ts
* 用途:挂载统一编辑器 desk 内 XFA 片段并验证布局与诊断抽屉(无独立 Header)。
* 依赖:Vitest、@vue/test-utils、OrderProfileXfaWorkbench。
* 用途:冒烟验证弃用薄包装与 useOrderProfileXfaDesk 默认 synthetic / dirty 契约。
* 依赖:Vitest、@vue/test-utils、OrderProfileXfaWorkbench、useOrderProfileXfaDesk。
* 逻辑:不再断言三栏 datasets 左栏;断言 desk 可加载且默认原生 PDF 画布。
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { mount, flushPromises } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { defineComponent, h, nextTick } from 'vue';
import OrderProfileXfaWorkbench from './OrderProfileXfaWorkbench.vue';
import { useOrderProfileXfaDesk } from './composables/useOrderProfileXfaDesk';
const { saveDraftMock, splitPreviewMock, detailDefinition } = vi.hoisted(() => ({
saveDraftMock: vi.fn(),
@@ -39,6 +42,7 @@ const baseDefinition = {
total_amount_policy: 'must_equal_line_sum' as const,
},
split_rules: [],
bindings: [],
};
vi.mock('vue-router', () => ({
@@ -47,7 +51,7 @@ vi.mock('vue-router', () => ({
}));
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => ({ success: vi.fn(), error: vi.fn() }),
useMessage: () => ({ success: vi.fn(), error: vi.fn(), info: vi.fn() }),
}));
vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
@@ -88,6 +92,40 @@ vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
pages: [{ page_no: 1, preview_token: 'token' }],
expires_in_seconds: 60,
})),
requestOrderProfileSampleXfaSyntheticPreview: vi.fn(async () => ({
document_id: 85,
identity: {
document_id: 85,
layout_version_id: 1,
structure_analysis_id: 1,
source_content_hash: 'a'.repeat(64),
template_packet_checksum: 't',
datasets_packet_checksum: 'd',
dataset_structure_fingerprint: 'f',
preview_render_checksum: 'r'.repeat(64),
render_mode: 'xfa_dataset_preview',
renderer_version: 'hxops.xfa_static_preview.v1',
page_count: 1,
},
status: 'ready',
render_mode: 'xfa_dataset_preview',
renderer_version: 'hxops.xfa_static_preview.v1',
preview_render_checksum: 'r'.repeat(64),
page_count: 1,
pages: [{ page_no: 1, preview_token: 'synth-token' }],
expires_in_seconds: 60,
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),
})),
acceptOrderProfileXfaOcrAutomarkSuggestion: vi.fn(),
rejectOrderProfileXfaOcrAutomarkSuggestion: vi.fn(),
suggestOrderProfileXfaUnifiedMapping: vi.fn(),
acquireOrderDocumentProfileEditLease: vi.fn(async () => ({ lease_token: 'lease', expires_at: new Date().toISOString() })),
renewOrderDocumentProfileEditLease: vi.fn(),
@@ -95,6 +133,8 @@ vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
saveOrderDocumentProfileDraft: (...args: unknown[]) => saveDraftMock(...args),
previewOrderProfileSampleXfaSplitRules: (...args: unknown[]) => splitPreviewMock(...args),
previewOrderProfileSampleXfaValue: vi.fn(),
confirmOrderProfileXfaVisualBinding: vi.fn(),
rejectOrderProfileXfaVisualBinding: vi.fn(),
}));
vi.mock('@/features/admin/api/shipping-order-schema.api', () => ({
@@ -107,110 +147,32 @@ vi.mock('@/features/admin/api/shipping-order-schema.api', () => ({
enabled: true, aliases: [], normalizer_key: 'trim', validator_keys: [], enum_options: [],
evidence_policy: { required: false, source_precedence: [], conflict_policy: 'fail', allow_single_source: true },
comparator_key: 'exact',
}, {
field_id: 'f-bill', field_code: 'bill_to_customer', scope: 'header', display_name: '账款客户', required: false,
enabled: true, aliases: [], normalizer_key: 'trim', validator_keys: [], enum_options: [],
evidence_policy: { required: false, source_precedence: [], conflict_policy: 'fail', allow_single_source: true },
comparator_key: 'exact',
}, {
field_id: 'f-line', field_code: 'part_number', scope: 'line', display_name: '料号', required: false,
enabled: true, aliases: [], normalizer_key: 'trim', validator_keys: [], enum_options: [],
evidence_policy: { required: false, source_precedence: [], conflict_policy: 'fail', allow_single_source: true },
comparator_key: 'exact',
}],
},
}],
})),
}));
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
fallbackLocale: 'zh-CN',
messages: {
'zh-CN': {
common: { yes: '是', no: '否', close: '关闭' },
admin: {
shippingOrderProfiles: {
templateModes: { xfa_dataset: 'XFA' },
workbench: {
headerReturnToLibrary: '返回',
headerSaveDraft: '保存',
headerValidate: '验证',
headerRecoverLease: '恢复',
headerTakeOverLease: '接管',
saveStatus: { saved: '已保存', saving: '保存中', failed: '失败', readonly: '只读' },
leaveConfirm: '离开?',
annotationCanvasAriaLabel: '画布',
loadingPage: '加载',
selectBoundPdf: '选择 PDF',
zoomIn: '+', zoomOut: '-', fitPage: '适合',
pageNavigation: '页',
},
xfaUnified: {
drawFieldBox: '画框',
suggesting: '分析中',
openDiagnostics: '高级诊断',
diagnosticsDrawerTitle: '诊断',
diagnosticsSummary: '{mapped}/{total}',
candidatePanelTitle: '候选',
acceptCandidate: '采用',
confirmVisual: '确认',
rejectVisual: '驳回',
visualStatus: { suggested: '建议', confirmed: '已确认', rejected: '已驳回', needs_review: '待复核' },
},
xfaWorkbench: {
loading: '加载', loadFailed: '失败', saved: '已保存', saveFailed: '失败', scopeMismatch: 'scope',
treeTitle: '树', searchPaths: '搜', collectionBadge: '集合', treeEmpty: '空',
schemaTitle: 'Schema', selectLeafFirst: '选叶子', unbind: '解除',
filter: { all: '全部', unmapped: '未映射', required: '必填' },
scope: { header: '表头', line: '明细' },
previewTitle: '预览', blockersTitle: '阻断', currentNode: '节点', noneSelected: '无',
headerMaps: '表头映射', lineMaps: '明细映射', requiredCoverage: '{mapped}/{total}',
maskedSample: '脱敏', noMappings: '无映射', crossChecksTitle: '交叉校验',
crossCheck: { acroform: 'AcroForm', mirror: '镜像', lineAmount: '金额', totalAmount: '总额' },
previewHint: '验证页', retryLoad: '重试',
blocker: {
authoritative_collection_required: '权威必选',
duplicate_field_binding: '重复',
required_fields_unmapped: '必填未映射',
},
collectionsTitle: '集合', authoritativeCollection: '权威', selectAuthoritative: '选择',
mirrorCollections: '镜像', rowCount: '{count} 行',
},
xfaUnified: {
drawFieldBox: '画字段框', suggesting: '匹配中', suggestFailed: '建议失败',
candidatePanelTitle: '候选', acceptCandidate: '采用',
confirmVisual: '确认', rejectVisual: '驳回',
confirmSuccess: '确认成功', confirmFailed: '确认失败',
rejectSuccess: '驳回成功', rejectFailed: '驳回失败',
diagnosticsSummary: '{mapped}/{total}', openDiagnostics: '高级诊断',
diagnosticsDrawerTitle: '诊断',
visualStatus: { suggested: '建议', confirmed: '已确认', rejected: '已驳回', needs_review: '待复核' },
},
xfaSplit: {
title: '拆分', addRule: '新增', deleteConfirm: '删除?', deleteRule: '删', ruleLabel: '规则 {index}', unnamedRule: '未命名',
},
},
},
},
},
});
describe('OrderProfileXfaWorkbench (deprecated thin wrapper)', () => {
const i18n = createI18n({
legacy: false,
locale: 'zh',
messages: { zh: { common: { close: '关闭' }, admin: { shippingOrderProfiles: { xfaWorkbench: { loading: '加载中' } } } } },
});
describe('OrderProfileXfaWorkbench', () => {
beforeEach(() => {
detailDefinition.value = structuredClone(baseDefinition);
saveDraftMock.mockReset();
splitPreviewMock.mockReset();
detailDefinition.value = null;
vi.stubGlobal('fetch', vi.fn(async () => ({
ok: true,
blob: async () => new Blob([new Uint8Array([137, 80, 78, 71])], { type: 'image/png' }),
})));
vi.stubGlobal('URL', {
...URL,
createObjectURL: vi.fn(() => 'blob:mock-page'),
revokeObjectURL: vi.fn(),
});
// Canvas-related absolute URL safety: relative /api fetch must not throw in jsdom.
vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
expect(url.startsWith('/') || url.startsWith('http')).toBe(true);
return {
ok: true,
blob: async () => new Blob(['png'], { type: 'image/png' }),
};
}));
});
const mountPage = async () => {
@@ -218,40 +180,215 @@ describe('OrderProfileXfaWorkbench', () => {
props: defaultProps,
global: { plugins: [i18n] },
});
for (let i = 0; i < 20; i += 1) {
for (let i = 0; i < 30; i += 1) {
await flushPromises();
await new Promise((resolve) => setTimeout(resolve, 0));
if (wrapper.find('.xfa-workbench__desk').exists()) break;
await nextTick();
if (wrapper.find('[data-testid="xfa-thin-canvas"]').exists()) break;
}
return wrapper;
};
it('mounts canvas-first desk after bootstrap without standalone header', async () => {
it('mounts thin deprecated desk without three-column left datasets tree', async () => {
const wrapper = await mountPage();
expect(wrapper.find('[data-testid="xfa-workbench-deprecated"]').exists()).toBe(true);
expect(wrapper.find('.xfa-workbench__desk').exists()).toBe(true);
expect(wrapper.find('.xfa-workbench__header').exists()).toBe(false);
expect(wrapper.find('.xfa-workbench__canvas').exists()).toBe(true);
expect(wrapper.find('.canvas-shell').exists()).toBe(true);
expect(wrapper.find('.xfa-tree').exists()).toBe(false);
await wrapper.find('.xfa-workbench__diagnostics-trigger button').trigger('click');
await flushPromises();
expect(wrapper.find('.diagnostics-drawer').exists()).toBe(true);
expect(wrapper.find('.diagnostics-drawer .xfa-tree').exists()).toBe(true);
expect(wrapper.find('.diagnostics-drawer .add-rule').exists()).toBe(false);
expect(wrapper.find('.xfa-workbench__left').exists()).toBe(false);
expect(wrapper.find('.xfa-workbench__panel').exists()).toBe(false);
}, 15000);
it('opens readonly diagnostics drawer from panel footer', async () => {
it('defaults to native preview mode after load', async () => {
const wrapper = await mountPage();
expect(wrapper.find('.xfa-workbench__panel').exists()).toBe(true);
await wrapper.find('.xfa-workbench__diagnostics-trigger button').trigger('click');
await flushPromises();
expect(wrapper.find('.diagnostics-drawer').exists()).toBe(true);
expect(wrapper.find('.diagnostics-drawer .add-rule').exists()).toBe(false);
});
const vm = wrapper.vm as unknown as { getDesk: () => { previewMode: string; syntheticPreviewStatus: string } };
const desk = vm.getDesk();
expect(desk.previewMode).toBe('native');
expect(['ready', 'loading', 'unavailable', 'failed', 'stale', 'idle']).toContain(desk.syntheticPreviewStatus);
}, 15000);
it('emits dirty-change when local definition diverges from saved snapshot', async () => {
const wrapper = await mountPage();
expect(wrapper.emitted('dirty-change')?.[0]).toEqual([false]);
});
});
describe('useOrderProfileXfaDesk', () => {
beforeEach(() => {
detailDefinition.value = structuredClone(baseDefinition);
vi.stubGlobal('fetch', vi.fn(async () => ({
ok: true,
blob: async () => new Blob(['png'], { type: 'image/png' }),
})));
});
it('demotes confirmed visual bindings when collections are reconfirmed', async () => {
detailDefinition.value = {
...structuredClone(baseDefinition),
bindings: [{
binding_id: 'b1',
field_id: 'f1',
field_code: 'customer_po_no',
scope: 'header',
value_binding: { type: 'xfa_dataset', path_id: 'invoiced-to-path', data_path: null },
visual_binding: {
page_no: 1,
normalized_bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
source: 'user_drawn',
status: 'confirmed',
region_kind: 'field',
confirmed_on: 'xfa_dataset_preview',
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: { blocker: { authoritative_collection_required: 'need auth' }, loadFailed: 'fail' },
xfaDesk: { collectionsReconfirmedHint: 'ok' },
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
} } } } })],
},
});
for (let i = 0; i < 40; i += 1) {
await flushPromises();
if (!desk.loading.value && desk.definition.value) break;
}
expect(desk.definition.value).toBeTruthy();
expect(desk.loadError.value).toBe(false);
desk.draftAuthoritativePathId.value = 'items-data';
desk.draftMirrorPathIds.value = [];
desk.confirmReconfirmCollections();
expect(desk.authoritativePathId.value).toBe('items-data');
expect(desk.definition.value?.bindings?.[0]?.visual_binding.status).toBe('suggested');
}, 15000);
it('duplicateSelectedBinding clears path/schema and keeps geometry', async () => {
detailDefinition.value = {
...structuredClone(baseDefinition),
bindings: [{
binding_id: 'b1',
field_id: 'f1',
field_code: 'customer_po_no',
scope: 'header',
value_binding: { type: 'xfa_dataset', path_id: 'invoiced-to-path', data_path: null },
visual_binding: {
page_no: 1,
normalized_bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
source: 'user_drawn',
status: 'confirmed',
region_kind: 'header',
confirmed_on: 'xfa_dataset_preview',
},
}],
};
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' },
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
} } } } })],
},
});
for (let i = 0; i < 40; i += 1) {
await flushPromises();
if (!desk.loading.value && desk.definition.value) break;
}
desk.selectedBindingId.value = 'b1';
desk.duplicateSelectedBinding();
const copy = desk.definition.value?.bindings?.find((item) => item.binding_id !== 'b1');
expect(copy).toBeTruthy();
expect(copy?.field_code).toBe('');
expect(copy?.value_binding.path_id).toBe('');
expect(copy?.visual_binding.status).toBe('suggested');
expect((copy?.visual_binding as { region_kind?: string }).region_kind).toBe('header');
expect(copy?.visual_binding.normalized_bbox).toEqual({ x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 });
}, 15000);
it('annotationDisabled when native pages missing; datasets hidden for anchor', async () => {
detailDefinition.value = structuredClone(baseDefinition);
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' },
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
} } } } })],
},
});
for (let i = 0; i < 40; i += 1) {
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' };
desk.pageLoadError.value = null;
desk.syntheticPreviewStatus.value = 'unavailable';
expect(desk.annotationDisabled.value).toBe(false);
desk.pageGrant.value = null;
desk.pageGrants.value = [];
expect(desk.annotationDisabled.value).toBe(true);
desk.definition.value = {
...desk.definition.value!,
bindings: [{
binding_id: 'anchor-1',
field_id: 'a1',
field_code: '',
scope: 'header',
value_binding: { type: 'xfa_dataset', path_id: '', data_path: null },
visual_binding: {
page_no: 1,
normalized_bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
source: 'user_drawn',
status: 'suggested',
region_kind: 'anchor',
},
}],
};
desk.selectedBindingId.value = 'anchor-1';
expect(desk.showDatasetsSection.value).toBe(false);
}, 15000);
});
@@ -1,9 +1,9 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue
用途:展示受控 PDF 单页预览,并以相对坐标框支持选择、拖动和缩放区域。
用途:展示受控 PDF/XFA flatten 单页预览,并以相对坐标框支持选择、拖动和缩放区域。
依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion。
逻辑:父级签发单页令牌并提供分页动作;mode=readonly 时只允许查看/缩放/切页,不允许写入任何标注改动;
画布区域 aria-label 走四语言 i18n,供辅助技术正确读出只读/标注模式。
画布区域 aria-label 走四语言 i18n;可选 emptyHint/loadError 区分 XFA page_unavailable 与 PDF 缺样本空态。
-->
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue';
@@ -36,6 +36,10 @@ const props = defineProps<{
orderFieldValueState?: 'idle' | 'loading' | 'ready' | 'failed';
/** full=坐标全工具;xfa_visual=仅 XFA 画框。 */
annotationToolSet?: 'full' | 'xfa_visual';
/** 无图时空态文案;缺省为「选择已绑定的 PDF 样本」。 */
emptyHint?: string | null;
/** 外部注入的页加载错误(如 XFA page_unavailable);优先于空态提示。 */
loadError?: string | null;
}>();
const { t } = useI18n();
const readonlyMode = computed(() => props.mode === 'readonly');
@@ -56,10 +60,16 @@ const emit = defineEmits<{
page: [pageNo: number];
acceptSuggestion: [];
rejectSuggestion: [];
/** 页图拉取失败(父级可标 page_unavailable)。 */
loadFailed: [];
/** 用户点击重试(父级决定重拉 grant 或 flatten)。 */
retry: [];
}>();
const imageUrl = ref('');
const loading = ref(false);
/** 本组件内 fetch 失败文案;与 props.loadError 合并展示。 */
const internalLoadError = ref<string | null>(null);
const canvas = ref<HTMLElement | null>(null);
const viewport = ref<HTMLElement | null>(null);
const zoom = ref(1);
@@ -72,12 +82,26 @@ let activePan: { startX: number; startY: number; scrollLeft: number; scrollTop:
let creationStart: { x: number; y: number } | null = null;
const creationRegion = ref<OrderProfileCanvasRegion['region'] | null>(null);
/** 下载一次性 PNG 并在组件卸载或切页时回收浏览器 blob。 */
const displayLoadError = computed(() => props.loadError || internalLoadError.value || null);
const emptyStateText = computed(() => (
props.emptyHint || t('admin.shippingOrderProfiles.workbench.selectBoundPdf')
));
/**
* 下载一次性 PNG 并在组件卸载或切页时回收浏览器 blob。
* 核心逻辑:失败时写入 internalLoadError 并 emit loadFailed,避免误导为「未绑定样本」。
*/
const loadPage = async () => {
if (!props.profileId || !props.grant) return;
if (!props.profileId || !props.grant) {
URL.revokeObjectURL(imageUrl.value);
imageUrl.value = '';
internalLoadError.value = null;
return;
}
loading.value = true;
URL.revokeObjectURL(imageUrl.value);
imageUrl.value = '';
internalLoadError.value = null;
try {
const previewPath = props.previewPagePath
|| `/api/admin/shipping-notice/order-document-profiles/${props.profileId}/preview-pages`;
@@ -87,11 +111,22 @@ const loadPage = async () => {
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
imageUrl.value = URL.createObjectURL(await response.blob());
} catch {
internalLoadError.value = t('admin.shippingOrderProfiles.workbench.canvasUnavailable');
emit('loadFailed');
} finally {
loading.value = false;
}
};
/**
* 用户点击画布重试:清除内部错误并通知父级。
*/
const onRetryClick = () => {
internalLoadError.value = null;
emit('retry');
};
/** 将指针移动映射为相对坐标;readonly 模式只保留选中,不允许几何变化。 */
const move = (event: PointerEvent) => {
if (!activeDrag || !canvas.value || readonlyMode.value) return;
@@ -253,7 +288,13 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
</div>
</header>
<div v-if="loading" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}</div>
<div v-else-if="!imageUrl" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.selectBoundPdf') }}</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 class="canvas-work-area" :class="{ readonly: readonlyMode }">
<aside v-if="!readonlyMode" class="annotation-tools">
<template v-if="xfaVisualTools">
@@ -323,7 +364,22 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
.zoom-control { justify-self: end; }
.canvas-toolbar output { min-width: 3.4rem; color: #f8fafc; text-align: center; }
.zoom-control .fit-action { padding-inline: .65rem; }
.canvas-state { display: grid; min-height: 32rem; place-items: center; color: #94a3b8; font-size: .875rem; }
.canvas-state { display: grid; min-height: 32rem; place-items: center; color: #94a3b8; font-size: .875rem; gap: .75rem; }
.canvas-state--error { color: #fecaca; }
.canvas-retry {
display: inline-flex;
min-height: 2rem;
align-items: center;
justify-content: center;
border: 1px solid #475569;
border-radius: .35rem;
background: #1e293b;
padding: .35rem .75rem;
color: #e2e8f0;
font-size: .78rem;
cursor: pointer;
}
.canvas-retry:hover { border-color: #60a5fa; background: #26364f; }
.canvas-work-area { display: flex; min-height: 0; flex: 1; gap: .6rem; }
.canvas-work-area.readonly { gap: 0; }
.canvas-viewport { position: relative; min-width: 0; flex: 1; overflow: auto; }
@@ -0,0 +1,115 @@
/**
* features/admin/modules/shipping-order-document-profiles/components/OrderProfileXfaConfirmStep.spec.ts
* 用途:验证 XFA 集合候选在未选择权威集合时仍可见,且真正无候选时才显示空状态。
* 依赖:Vitest、@vue/test-utils、OrderProfileXfaConfirmStep 及其 XFA API。
*/
import { describe, expect, it, vi } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import OrderProfileXfaConfirmStep from './OrderProfileXfaConfirmStep.vue';
const { getFieldTree, getCollections, reparseSample } = vi.hoisted(() => ({
getFieldTree: vi.fn(),
getCollections: vi.fn(),
reparseSample: vi.fn(),
}));
vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
getOrderProfileSampleXfaFieldTree: getFieldTree,
getOrderProfileSampleXfaCollections: getCollections,
reparseOrderProfileSampleLayout: reparseSample,
}));
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
admin: {
shippingOrderProfiles: {
wizard: {
sampleSelected: '已选样本',
xfa: {
loading: '加载中',
loadErrorTitle: '加载失败',
loadErrorHint: '请重试',
reload: '重新加载',
reparseSample: '重新解析样本',
noCollections: '没有可用数据集',
intro: 'XFA',
noBlankPdf: '不使用空白 PDF',
scriptNotice: '不会执行脚本',
},
},
xfaUnified: { createBlockersTitle: '创建前阻断项' },
xfaWorkbench: {
collectionsTitle: '集合',
collectionEvidenceHint: '证据',
authoritativeCollection: '权威集合',
mirrorCollections: '镜像集合',
recommendedAuthoritative: '推荐权威',
selectedAuthoritative: '已选权威',
rowCount: '{count} 行',
nonEmptyCoverage: '{filled}/{total} {percent}',
excludedCollections: '排除集合 {count}',
allCandidatesExcluded: '全部被排除',
emptyStructureReason: '空结构',
collectionReason: { data_description_structure: '结构描述', empty_structure: '空结构' },
},
xfa: { documentKinds: { xfa_hybrid: 'XFA 动态表单' } },
},
},
},
},
});
const sample = {
document_id: 132,
intake_id: 1,
intake_no: 'INT-1',
filename: '4510039227.pdf',
table_count: 0,
document_kind: 'xfa_hybrid',
xfa_analysis_ready: true,
purpose: 'order_document_profile_sample' as const,
parse_status: 'ready',
is_template_sample: true,
can_delete: true,
};
function mountStep() {
return mount(OrderProfileXfaConfirmStep, {
global: { plugins: [i18n] },
props: { documentId: 132, sample, authoritativePathId: '', mirrorPathIds: [] },
});
}
describe('OrderProfileXfaConfirmStep', () => {
it('未选择权威集合时仍显示可选数据集', async () => {
getFieldTree.mockResolvedValue({ tree: {} });
getCollections.mockResolvedValue({
collection_candidates: [{
path_id: 'items', collection_path_hash: 'h1', row_count: 1,
path_label: 'datasets / data / ITEMS / DATA', field_names: ['MATNR'],
field_count: 1, non_empty_field_count: 1, non_empty_rate: 1,
sample_fields: [{ field_name: 'MATNR', display_value: 'TEMP-S', display_policy: 'partial' }],
selectable: true, recommended_role: 'authoritative',
}],
excluded_collection_candidates: [],
});
const wrapper = mountStep();
await vi.waitFor(() => expect(wrapper.text()).toContain('datasets / data / ITEMS / DATA'));
expect(wrapper.find('input[type="radio"]').exists()).toBe(true);
expect(wrapper.text()).toContain('创建前阻断项');
});
it('没有任何候选集合时才显示空状态', async () => {
getFieldTree.mockResolvedValue({ tree: {} });
getCollections.mockResolvedValue({ collection_candidates: [], excluded_collection_candidates: [] });
const wrapper = mountStep();
await vi.waitFor(() => expect(wrapper.text()).toContain('没有可用数据集'));
expect(wrapper.find('input[type="radio"]').exists()).toBe(false);
});
});
@@ -1,18 +1,19 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/OrderProfileXfaConfirmStep.vue
用途:创建向导第三步——XFA 样本结构与明细集合确认(不要求 table_id)。
依赖:XFA collections API、XfaCollectionSelector、vue-i18n。
逻辑:父级传入 documentId 与 v-model 集合 path_id;watch(immediate) 加载上下文,
避免 onMounted 再次触发导致重复请求。
依赖:XFA collections/field-tree API、layout-reparse API、XfaCollectionSelector、vue-i18n。
逻辑:父级传入 documentId 与 v-model 集合 path_id;加载失败以独立错误态阻断创建,
区分「无合格集合」与「分析不可用」;重新解析需二次确认且不自动触发。
-->
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
getOrderProfileSampleXfaCollections,
getOrderProfileSampleXfaFieldTree,
reparseOrderProfileSampleLayout,
} from '@/features/admin/api/shipping-order-document-profile.api';
import type { OrderProfileSampleDocument } from '@/features/admin/types/shipping-order-document-profile.types';
import { flattenXfaTreeNodes } from '../xfaProfileMapping.utils';
@@ -27,19 +28,27 @@ const props = defineProps<{
const emit = defineEmits<{
'update:authoritativePathId': [value: string];
'update:mirrorPathIds': [value: string[]];
/** 加载失败态变化:父级须据此阻断创建按钮 */
'update:contextReady': [value: boolean];
}>();
const { t } = useI18n();
const message = useMessage();
const loading = ref(false);
const reparsing = ref(false);
const loadError = ref<{ code?: string; message: string } | null>(null);
const collections = ref<Awaited<ReturnType<typeof getOrderProfileSampleXfaCollections>> | null>(null);
const flatNodes = ref(flattenXfaTreeNodes(null));
const excludedCollections = computed(() => collections.value?.excluded_collection_candidates || []);
const contextReady = computed(() => !loading.value && !loadError.value && collections.value != null);
/** 创建草稿前的阻断摘要(权威集合必选等)。 */
/**
* 创建草稿前的阻断摘要(权威集合必选等);加载失败时不计入“无集合”。
*/
const createBlockers = computed(() => {
if (loadError.value || !collections.value) return [];
const items: string[] = [];
const selectable = (collections.value?.collection_candidates || []).filter((item) => item.selectable !== false);
const selectable = (collections.value.collection_candidates || []).filter((item) => item.selectable !== false);
if (!props.authoritativePathId && selectable.length) {
items.push(t('admin.shippingOrderProfiles.xfaWorkbench.blocker.authoritative_collection_required'));
}
@@ -54,32 +63,87 @@ const documentKindLabel = computed(() => {
return t(`admin.shippingOrderProfiles.xfa.documentKinds.${kind}`, kind);
});
/**
* 将 BusinessError 映射为用户可见文案(优先四语言 errors.codes)。
* @param error - 捕获异常
*/
function resolveLoadErrorMessage(error: unknown): { code?: string; message: string } {
if (error instanceof BusinessError) {
const code = String(error.code || '').trim() || undefined;
return {
code,
message: resolveLocalizedErrorMessage(code, error.message)
|| t('admin.shippingOrderProfiles.wizard.xfa.loadFailed'),
};
}
return { message: t('admin.shippingOrderProfiles.wizard.xfa.loadFailed') };
}
/**
* 加载 XFA 集合候选与字段树(用于展示标签)。
* @returns 完成后更新 flatNodes 与 collections。
* 核心逻辑:并发请求;失败写入 loadError 且清空 collections,禁止误显示“没有集合”。
*/
async function loadXfaContext(): Promise<void> {
if (!props.documentId) return;
loading.value = true;
loadError.value = null;
collections.value = null;
flatNodes.value = flattenXfaTreeNodes(null);
emit('update:contextReady', false);
try {
const [treeResp, collectionResp] = await Promise.all([
getOrderProfileSampleXfaFieldTree(props.documentId),
getOrderProfileSampleXfaCollections(props.documentId),
]);
collections.value = collectionResp;
flatNodes.value = flattenXfaTreeNodes(treeResp.tree as import('@/features/admin/types/shipping-order-document-profile.types').XfaFieldTreeNode);
flatNodes.value = flattenXfaTreeNodes(
treeResp.tree as import('@/features/admin/types/shipping-order-document-profile.types').XfaFieldTreeNode,
);
if (!props.authoritativePathId && collectionResp.collection_candidates.length === 1) {
const only = collectionResp.collection_candidates[0];
if (only?.path_id) emit('update:authoritativePathId', only.path_id);
}
emit('update:contextReady', true);
} catch (error) {
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.xfa.loadFailed'));
loadError.value = resolveLoadErrorMessage(error);
message.error(loadError.value.message);
emit('update:contextReady', false);
} finally {
loading.value = false;
}
}
/**
* 仅重新请求字段树与集合(不触发样本重新解析)。
*/
async function reloadContext(): Promise<void> {
await loadXfaContext();
}
/**
* 独立“重新解析样本”:二次确认后调用 layout-reparse;成功后提示用户再点重新加载。
*/
async function reparseSample(): Promise<void> {
if (!props.documentId || reparsing.value) return;
const ok = window.confirm(t('admin.shippingOrderProfiles.wizard.xfa.reparseConfirm'));
if (!ok) return;
reparsing.value = true;
try {
await reparseOrderProfileSampleLayout(props.documentId);
message.success(t('admin.shippingOrderProfiles.wizard.xfa.reparseStarted'));
} catch (error) {
message.error(
error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: t('admin.shippingOrderProfiles.wizard.xfa.reparseFailed'),
);
} finally {
reparsing.value = false;
}
}
watch(() => props.documentId, () => void loadXfaContext(), { immediate: true });
watch(contextReady, (ready) => emit('update:contextReady', ready));
</script>
<template>
@@ -95,13 +159,29 @@ watch(() => props.documentId, () => void loadXfaContext(), { immediate: true });
<li>{{ t('admin.shippingOrderProfiles.wizard.xfa.scriptNotice') }}</li>
</ul>
</article>
<p v-if="loading" class="xfa-confirm-step__loading">{{ t('admin.shippingOrderProfiles.wizard.xfa.loading') }}</p>
<aside v-else-if="createBlockers.length" class="xfa-confirm-step__blockers" role="status">
<strong>{{ t('admin.shippingOrderProfiles.xfaUnified.createBlockersTitle') }}</strong>
<ul>
<li v-for="(item, index) in createBlockers" :key="index">{{ item }}</li>
</ul>
<aside v-else-if="loadError" class="xfa-confirm-step__error" role="alert">
<strong>{{ t('admin.shippingOrderProfiles.wizard.xfa.loadErrorTitle') }}</strong>
<p>{{ loadError.message }}</p>
<p v-if="loadError.code" class="xfa-confirm-step__error-code">{{ loadError.code }}</p>
<p class="xfa-confirm-step__error-hint">{{ t('admin.shippingOrderProfiles.wizard.xfa.loadErrorHint') }}</p>
<div class="xfa-confirm-step__error-actions">
<button type="button" class="xfa-confirm-step__btn" @click="reloadContext">
{{ t('admin.shippingOrderProfiles.wizard.xfa.reload') }}
</button>
<button
type="button"
class="xfa-confirm-step__btn xfa-confirm-step__btn--secondary"
:disabled="reparsing"
@click="reparseSample"
>
{{ t('admin.shippingOrderProfiles.wizard.xfa.reparseSample') }}
</button>
</div>
</aside>
<XfaCollectionSelector
v-else-if="collections && (collections.collection_candidates?.length || excludedCollections.length)"
:candidates="collections.collection_candidates || []"
@@ -111,7 +191,20 @@ watch(() => props.documentId, () => void loadXfaContext(), { immediate: true });
@update:authoritative-path-id="emit('update:authoritativePathId', $event)"
@update:mirror-path-ids="emit('update:mirrorPathIds', $event)"
/>
<p v-else-if="!loading" class="xfa-confirm-step__loading">{{ t('admin.shippingOrderProfiles.wizard.xfa.noCollections') }}</p>
<aside v-if="createBlockers.length" class="xfa-confirm-step__blockers" role="status">
<strong>{{ t('admin.shippingOrderProfiles.xfaUnified.createBlockersTitle') }}</strong>
<ul>
<li v-for="(item, index) in createBlockers" :key="index">{{ item }}</li>
</ul>
</aside>
<p
v-if="collections && !collections.collection_candidates?.length && !excludedCollections.length"
class="xfa-confirm-step__loading"
>
{{ t('admin.shippingOrderProfiles.wizard.xfa.noCollections') }}
</p>
</div>
</template>
@@ -124,4 +217,11 @@ watch(() => props.documentId, () => void loadXfaContext(), { immediate: true });
.xfa-confirm-step__loading { margin: 0; color: var(--text-muted); }
.xfa-confirm-step__blockers { padding: 12px 14px; border: 1px solid var(--status-warning-border); border-radius: var(--radius-control); background: var(--status-warning-bg); color: var(--status-warning-fg); font-size: .84rem; }
.xfa-confirm-step__blockers ul { margin: 6px 0 0; padding-left: 18px; }
.xfa-confirm-step__error { padding: 14px 16px; border: 1px solid var(--status-danger-border, #f1aeb5); border-radius: var(--radius-control); background: var(--status-danger-bg, #fff5f5); color: var(--status-danger-fg, #9b1c1c); font-size: .86rem; display: flex; flex-direction: column; gap: 8px; }
.xfa-confirm-step__error-code { margin: 0; font-family: ui-monospace, monospace; font-size: .75rem; opacity: .85; }
.xfa-confirm-step__error-hint { margin: 0; color: var(--text-secondary); }
.xfa-confirm-step__error-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 4px; }
.xfa-confirm-step__btn { padding: 6px 12px; border-radius: var(--radius-control); border: 1px solid var(--border-default); background: var(--bg-surface); cursor: pointer; font-size: .84rem; }
.xfa-confirm-step__btn--secondary { background: transparent; }
.xfa-confirm-step__btn:disabled { opacity: .6; cursor: not-allowed; }
</style>
@@ -0,0 +1,281 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/XfaAutoMarkPanel.vue
用途:XFA OCR/Widget 自动标记建议面板;支持轮询进度与接受/调整/拒绝。
依赖:vue-i18n;由 OrderProfileEditorPage(XFA desk)嵌入并接线 automark API。
逻辑:props 驱动 suggestions/jobStatus;动作按钮在非 disabled 时 emit 给父级持久化。
-->
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
/** 自动标记建议条目。 */
export interface XfaAutoMarkSuggestion {
suggestion_id: string;
field_key?: string | null;
field_code?: string | null;
suggestion_origin?: 'widget_template' | 'ocr' | string | null;
confidence?: number | null;
status?: string | null;
match_class?: string | null;
summary?: string | null;
ocr_text?: string | null;
dataset_value?: string | null;
iou?: number | null;
needs_review?: boolean | null;
}
const props = withDefaults(defineProps<{
suggestions?: XfaAutoMarkSuggestion[];
disabled?: boolean;
initiallyExpanded?: boolean;
/** queued|running|succeeded|failed|idle */
jobStatus?: string | null;
jobError?: string | null;
}>(), {
suggestions: () => [],
disabled: false,
initiallyExpanded: true,
jobStatus: 'idle',
jobError: null,
});
const emit = defineEmits<{
accept: [suggestion: XfaAutoMarkSuggestion];
adjust: [suggestion: XfaAutoMarkSuggestion];
reject: [suggestion: XfaAutoMarkSuggestion];
retry: [];
'run-full': [];
}>();
const { t } = useI18n();
const expanded = ref(props.initiallyExpanded);
watch(() => props.initiallyExpanded, (v) => { expanded.value = v; });
const items = computed(() => props.suggestions || []);
const empty = computed(() => items.value.length === 0);
const running = computed(() => ['queued', 'running', 'pending'].includes(String(props.jobStatus || '')));
/**
* 切换面板展开/收起。
*/
function toggleExpanded(): void {
expanded.value = !expanded.value;
}
/**
* 发出接受建议事件。
*/
function onAccept(suggestion: XfaAutoMarkSuggestion): void {
if (props.disabled || suggestion.needs_review || suggestion.match_class === 'needs_review') return;
emit('accept', suggestion);
}
/**
* 发出调整建议事件(定位到画布手工改框)。
*/
function onAdjust(suggestion: XfaAutoMarkSuggestion): void {
if (props.disabled) return;
emit('adjust', suggestion);
}
/**
* 发出驳回建议事件。
*/
function onReject(suggestion: XfaAutoMarkSuggestion): void {
if (props.disabled) return;
emit('reject', suggestion);
}
/**
* 解析建议来源展示文案。
*/
function originLabel(origin: string | null | undefined): string {
if (origin === 'widget_template') return t('admin.shippingOrderProfiles.xfaAutoMark.originWidget');
if (origin === 'ocr') return t('admin.shippingOrderProfiles.xfaAutoMark.originOcr');
return t('admin.shippingOrderProfiles.xfaAutoMark.originUnknown');
}
/**
* mismatch / needs_review 禁止直接接受。
*/
function acceptBlocked(item: XfaAutoMarkSuggestion): boolean {
return Boolean(item.needs_review || item.match_class === 'needs_review');
}
</script>
<template>
<section class="xfa-auto-mark" :aria-label="t('admin.shippingOrderProfiles.xfaAutoMark.title')">
<button
type="button"
class="xfa-auto-mark__header"
:aria-expanded="expanded"
@click="toggleExpanded"
>
<span class="xfa-auto-mark__title">
{{ t('admin.shippingOrderProfiles.xfaAutoMark.title') }}
</span>
<span class="xfa-auto-mark__count">
{{ t('admin.shippingOrderProfiles.xfaAutoMark.count', { count: items.length }) }}
</span>
<span v-if="running" class="xfa-auto-mark__job">{{ t('admin.shippingOrderProfiles.xfaAutoMark.running') }}</span>
<span class="xfa-auto-mark__chevron">{{ expanded ? '▾' : '▸' }}</span>
</button>
<div v-if="expanded" class="xfa-auto-mark__body">
<p class="xfa-auto-mark__hint">
{{ t('admin.shippingOrderProfiles.xfaAutoMark.hint') }}
</p>
<div class="xfa-auto-mark__toolbar">
<button type="button" class="action-btn" :disabled="disabled || running" @click="emit('run-full')">
{{ t('admin.shippingOrderProfiles.xfaAutoMark.runFull') }}
</button>
<button
v-if="jobStatus === 'failed'"
type="button"
class="action-btn"
:disabled="disabled"
@click="emit('retry')"
>
{{ t('admin.shippingOrderProfiles.xfaAutoMark.retry') }}
</button>
</div>
<p v-if="jobError" class="xfa-auto-mark__error">{{ jobError }}</p>
<p v-if="empty && !running" class="xfa-auto-mark__empty">
{{ t('admin.shippingOrderProfiles.xfaAutoMark.empty') }}
</p>
<ul v-else class="xfa-auto-mark__list">
<li
v-for="item in items"
:key="item.suggestion_id"
class="xfa-auto-mark__item"
>
<div class="xfa-auto-mark__meta">
<span class="xfa-auto-mark__field">
{{ item.field_code || item.field_key || item.suggestion_id }}
</span>
<span class="xfa-auto-mark__origin">{{ originLabel(item.suggestion_origin) }}</span>
<span v-if="item.match_class" class="xfa-auto-mark__class">{{ item.match_class }}</span>
<span v-if="item.confidence != null" class="xfa-auto-mark__confidence">
{{ t('admin.shippingOrderProfiles.xfaAutoMark.confidence', {
value: Math.round(Number(item.confidence) * 100),
}) }}
</span>
</div>
<p v-if="item.summary" class="xfa-auto-mark__summary">{{ item.summary }}</p>
<p v-else-if="item.ocr_text || item.dataset_value" class="xfa-auto-mark__summary">
OCR: {{ item.ocr_text || '—' }} · datasets: {{ item.dataset_value || '—' }}
</p>
<div class="xfa-auto-mark__actions">
<button
type="button"
class="action-btn action-btn--active"
:disabled="disabled || acceptBlocked(item)"
@click="onAccept(item)"
>
{{ t('admin.shippingOrderProfiles.xfaAutoMark.accept') }}
</button>
<button
type="button"
class="action-btn action-btn--active"
:disabled="disabled"
@click="onAdjust(item)"
>
{{ t('admin.shippingOrderProfiles.xfaAutoMark.adjust') }}
</button>
<button
type="button"
class="action-btn action-btn--active action-btn--danger"
:disabled="disabled"
@click="onReject(item)"
>
{{ t('admin.shippingOrderProfiles.xfaAutoMark.reject') }}
</button>
</div>
</li>
</ul>
</div>
</section>
</template>
<style scoped>
.xfa-auto-mark {
border-top: 1px solid #7dd3fc;
border-radius: 0;
background: #ecfeff;
overflow: hidden;
color: #155e75;
}
.xfa-auto-mark__header {
display: flex;
align-items: center;
gap: 0.5rem;
width: 100%;
padding: 0.65rem 0.9rem;
border: 0;
background: transparent;
cursor: pointer;
text-align: left;
color: #155e75;
}
.xfa-auto-mark__title { font-size: 0.75rem; font-weight: 600; }
.xfa-auto-mark__count, .xfa-auto-mark__job {
border-radius: 999px;
background: #bae6fd;
padding: 0.15rem 0.4rem;
font-size: 0.72rem;
color: #0e7490;
}
.xfa-auto-mark__chevron { margin-left: auto; color: #0e7490; font-size: 0.75rem; }
.xfa-auto-mark__body { padding: 0 0.9rem 0.75rem; border-top: 1px solid #a5f3fc; }
.xfa-auto-mark__hint, .xfa-auto-mark__empty { margin: 0.5rem 0 0; font-size: 0.75rem; color: #0e7490; }
.xfa-auto-mark__error { margin: 0.35rem 0 0; font-size: 0.75rem; color: #b91c1c; }
.xfa-auto-mark__toolbar { display: flex; gap: 0.35rem; margin-top: 0.45rem; }
.xfa-auto-mark__toolbar .action-btn {
border: 1px solid #0891b2;
border-radius: 0.35rem;
background: #fff;
padding: 0.35rem 0.55rem;
color: #0e7490;
font-size: 0.75rem;
}
.xfa-auto-mark__list {
list-style: none;
margin: 0.5rem 0 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 0.5rem;
max-height: 220px;
overflow: auto;
}
.xfa-auto-mark__item {
padding: 0.5rem;
border: 1px solid #e2e8f0;
border-radius: 0.375rem;
background: #fff;
}
.xfa-auto-mark__meta { display: flex; flex-wrap: wrap; gap: 0.4rem; align-items: center; }
.xfa-auto-mark__field { font-size: 0.8125rem; font-weight: 600; color: #0f172a; }
.xfa-auto-mark__origin, .xfa-auto-mark__confidence, .xfa-auto-mark__class {
font-size: 0.6875rem;
color: #64748b;
background: #f1f5f9;
border-radius: 0.25rem;
padding: 0.1rem 0.35rem;
}
.xfa-auto-mark__summary { margin: 0.35rem 0 0; font-size: 0.75rem; color: #475569; }
.xfa-auto-mark__actions { display: flex; gap: 0.35rem; margin-top: 0.45rem; }
.action-btn {
font-size: 0.75rem;
padding: 0.2rem 0.5rem;
border-radius: 0.25rem;
border: 1px solid #cbd5e1;
background: #f8fafc;
color: #334155;
}
.action-btn:disabled { cursor: not-allowed; opacity: 0.45; }
.action-btn--active { cursor: pointer; opacity: 1; }
.action-btn--active:hover:not(:disabled) { border-color: #60a5fa; background: #eff6ff; }
.action-btn--danger { color: #991b1b; border-color: #fecaca; }
</style>
@@ -0,0 +1,151 @@
<!--
features/admin/modules/shipping-order-document-profiles/components/XfaPreviewModeToggle.vue
用途:【已废止 / DEPRECATED】原 XFA 原始 PDF / 合成预览双模式切换。
依赖:vue-i18n、XfaPreviewCanvasMode 类型。
逻辑:硬冻结后 EditorPage 不再导入;保留文件仅防旧引用,请勿在新产品路径使用。
替代:唯一 flatten 合成图源;见 useOrderProfileXfaDesk + OrderProfileEditorPage 共享 desk。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { XfaPreviewCanvasMode } from '@/features/admin/types/shipping-order-document-profile.types';
/** @deprecated 双预览模式已废止;请勿再挂载本组件。 */
const props = withDefaults(defineProps<{
modelValue: XfaPreviewCanvasMode;
status?: 'idle' | 'loading' | 'ready' | 'failed' | 'stale' | 'unavailable';
pageCount?: number;
disabled?: boolean;
}>(), {
status: 'idle',
pageCount: 0,
disabled: false,
});
const emit = defineEmits<{
'update:modelValue': [mode: XfaPreviewCanvasMode];
'mode-change': [mode: XfaPreviewCanvasMode];
}>();
const { t } = useI18n();
const statusText = computed(() => {
switch (props.status) {
case 'loading':
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusLoading');
case 'ready':
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusReady', {
pages: props.pageCount || 0,
});
case 'failed':
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusFailed');
case 'stale':
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusStale');
case 'unavailable':
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusUnavailable');
default:
return '';
}
});
/**
* 切换预览模式并同步 v-model / mode-change。
* @param mode 目标模式
*/
function selectMode(mode: XfaPreviewCanvasMode): void {
if (props.disabled || mode === props.modelValue) return;
emit('update:modelValue', mode);
emit('mode-change', mode);
}
</script>
<template>
<div
class="xfa-preview-mode-toggle"
role="group"
:aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.label')"
>
<span class="xfa-preview-mode-toggle__label">
{{ t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.label') }}
</span>
<div class="xfa-preview-mode-toggle__buttons">
<button
type="button"
class="mode-btn"
:class="{ active: modelValue === 'original' }"
:disabled="disabled"
:aria-pressed="modelValue === 'original'"
@click="selectMode('original')"
>
{{ t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.original') }}
</button>
<button
type="button"
class="mode-btn"
:class="{ active: modelValue === 'synthetic' }"
:disabled="disabled"
:aria-pressed="modelValue === 'synthetic'"
@click="selectMode('synthetic')"
>
{{ t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.synthetic') }}
</button>
</div>
<p v-if="statusText" class="xfa-preview-mode-toggle__status" :data-status="status">
{{ statusText }}
</p>
</div>
</template>
<style scoped>
.xfa-preview-mode-toggle {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem 0.75rem;
margin-bottom: 0.5rem;
padding: 0.35rem 0;
}
.xfa-preview-mode-toggle__label {
font-size: 0.75rem;
font-weight: 600;
color: #475569;
}
.xfa-preview-mode-toggle__buttons {
display: inline-flex;
border: 1px solid #cbd5e1;
border-radius: 0.375rem;
overflow: hidden;
}
.mode-btn {
appearance: none;
border: 0;
background: #f8fafc;
color: #334155;
font-size: 0.75rem;
padding: 0.3rem 0.65rem;
cursor: pointer;
}
.mode-btn + .mode-btn {
border-left: 1px solid #cbd5e1;
}
.mode-btn.active {
background: #0f172a;
color: #f8fafc;
}
.mode-btn:disabled {
opacity: 0.55;
cursor: not-allowed;
}
.xfa-preview-mode-toggle__status {
margin: 0;
font-size: 0.7rem;
color: #64748b;
}
.xfa-preview-mode-toggle__status[data-status='failed'],
.xfa-preview-mode-toggle__status[data-status='stale'] {
color: #b45309;
}
.xfa-preview-mode-toggle__status[data-status='ready'] {
color: #047857;
}
</style>