feat(shipping-notice): 增强发货通知与订单抽取功能,支持多进程处理与紧急停止

- 移除不再使用的 SHIPPING_NOTICE_LAYOUT_PARSER_REVISION 配置
- 在环境配置中新增 SHIPPING_NOTICE_WORKER_CONCURRENCY 和 SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS
- 实现发货通知 worker 进程,支持并发处理订单抽取任务
- 引入紧急停止功能,允许管理员在运行中控制订单解析状态
- 更新相关 API,支持读取与设置紧急停止状态
- 增强文档与代码注释,反映新的业务逻辑与功能要求
This commit is contained in:
hugo committed 2026-07-31 18:00:49 +08:00
1 parent d0fe084999
commit b352c281d5
149 files changed
+12550 -1874

No files matched your search

@@ -164,7 +164,7 @@ onBeforeUnmount(stopSampleRefresh);
:schemas-resolved="schemasResolved"
@update:model-value="updateIdentity"
/>
<OrderProfileSampleStep v-else-if="step === 2" v-model="documentId" :samples="samples" @uploaded="refreshSamples" />
<OrderProfileSampleStep v-else-if="step === 2" v-model="documentId" :samples="samples" @uploaded="refreshSamples(false)" @refresh="refreshSamples()" />
<OrderProfileModelStartStep v-else v-model="tableId" :tables="tables" />
</main>
@@ -48,6 +48,7 @@ import type {
OrderProfileRelativeRegion,
OrderProfileBoundSample,
OrderFieldLayoutSuggestion,
OrderProfileRowReconstructionMode,
ShippingOrderDocumentProfile,
} from "@/features/admin/types/shipping-order-document-profile.types";
import type {
@@ -61,9 +62,7 @@ import {
toOrderProfileAnchorId,
buildOrderProfileRecognitionResults,
groupUniqueOrderProfileLineFields,
isOrderProfileAnchorRelativeCandidate,
normalizeOrderProfileRelativeRegion,
toOrderProfileAnchorRelativeRegion,
} from "./orderProfileForm.utils";
const { t } = useI18n();
@@ -157,6 +156,11 @@ const form = reactive({
changeNote: "",
});
const regions = ref<OrderProfileCanvasRegion[]>([]);
/** 每个明细表区的重建策略与页范围独立保存,避免画布重开/保存时回退为默认固定子行。 */
const tableRegionSettings = reactive<Record<number, {
rowReconstructionMode: OrderProfileRowReconstructionMode;
pageScope: 'first_page' | 'all_pages' | 'continuation_pages' | 'exact_page';
}>>({});
/** 文档匹配锚点独立于字段坐标;必须以固定标签和固定值关系区分模板。 */
const documentMatch = reactive({
requiredAnchors: [] as OrderProfileDocumentMatchAnchor[],
@@ -206,6 +210,22 @@ const headerFields = computed<ShippingOrderFieldConfig[]>(
const pageRegions = computed(() =>
regions.value.filter((item) => item.pageNo === pageNo.value),
);
const activePageHasLines = computed(() => pageRegions.value.some((item) => item.kind === 'line'));
const activeTableRegionSetting = computed(() => tableRegionSettings[pageNo.value] || {
rowReconstructionMode: 'fixed_subrows' as const,
pageScope: 'exact_page' as const,
});
const ensureTableRegionSetting = (targetPageNo: number) => {
tableRegionSettings[targetPageNo] ||= {
rowReconstructionMode: 'fixed_subrows',
pageScope: 'exact_page',
};
return tableRegionSettings[targetPageNo];
};
const updateActiveTableRegionSetting = () => {
checkpoint();
schedulePreview();
};
const selectedRegion = computed(
() => pageRegions.value.find((item) => item.id === selectedId.value) || null,
);
@@ -213,7 +233,6 @@ const selectedRegion = computed(
const selectedRegionSampleValue = computed(() => {
const region = selectedRegion.value;
if (!region || region.kind !== 'order_field') return null;
if (region.suggestedValue) return region.suggestedValue;
if (!region.fieldCode) return null;
return orderFieldValuePreviews.value.find((item) => item.field_code === region.fieldCode)?.value || null;
});
@@ -762,6 +781,7 @@ const definition = () => {
)]
.sort((left, right) => left - right)
.map((regionPageNo) => {
const regionSettings = ensureTableRegionSetting(regionPageNo);
const pageItems = normalizedRegions.filter(
(item) => item.pageNo === regionPageNo,
);
@@ -834,10 +854,11 @@ const definition = () => {
);
return {
region_id: `main_lines_page_${regionPageNo}`,
page_scope: "exact_page" as const,
page_no: regionPageNo,
page_scope: regionSettings.pageScope,
page_no: regionSettings.pageScope === 'exact_page' ? regionPageNo : null,
region: tableRegion,
line_start_field_code: resolveLineStartFieldCode(mainLineFieldCodes),
row_reconstruction_mode: regionSettings.rowReconstructionMode,
header_layouts: headerLayouts,
line_layouts: lineRegions.map((line, index) => {
const fieldRegions = fieldRegionsFor(line.id);
@@ -894,11 +915,6 @@ const definition = () => {
(candidate.id === item.parentId || candidate.orderFieldId === item.orderFieldId),
);
const anchorId = toOrderProfileAnchorId(anchor);
const isAnchorRelative = Boolean(anchor && anchorId && ["right_of_anchor", "below_anchor"].includes(item.valueMode || "")
&& isOrderProfileAnchorRelativeCandidate(item.region, anchor.region));
const relativeValueRegion = isAnchorRelative && anchor
? toOrderProfileAnchorRelativeRegion(item.region, anchor.region)
: null;
return {
layout_id: item.orderFieldId || item.id,
field_id: "",
@@ -915,13 +931,12 @@ const definition = () => {
aliases: [],
match_mode: "exact" as const,
region: anchor.region,
position_locked: !isAnchorRelative,
position_locked: true,
minimum_evidence_level: "coordinate" as const,
}
: null,
// 画布框是读取边界;锚点只用于定位字段,不能再参与值框二次投影。
value_region: relativeValueRegion,
absolute_value_region: anchor && anchorId && !relativeValueRegion ? item.region : null,
absolute_value_region: anchor && anchorId ? item.region : null,
fallback_value_region: anchor && anchorId ? null : item.region,
value_mode: item.valueMode || "single_line",
stop_anchors:
@@ -952,11 +967,6 @@ const definition = () => {
candidate.kind === "order_anchor" &&
(candidate.id === item.parentId || candidate.orderFieldId === layoutId),
);
const isAnchorRelative = Boolean(anchor && ["right_of_anchor", "below_anchor"].includes(item.valueMode || "")
&& isOrderProfileAnchorRelativeCandidate(item.region, anchor.region));
const relativeValueRegion = isAnchorRelative && anchor
? toOrderProfileAnchorRelativeRegion(item.region, anchor.region)
: null;
return {
layout_id: layoutId,
label: item.label,
@@ -969,12 +979,11 @@ const definition = () => {
aliases: [],
match_mode: "exact" as const,
region: anchor.region,
position_locked: !isAnchorRelative,
position_locked: true,
minimum_evidence_level: "coordinate" as const,
}
: null,
value_region: relativeValueRegion,
absolute_value_region: anchor && !relativeValueRegion ? item.region : null,
absolute_value_region: anchor ? item.region : null,
fallback_value_region: anchor ? null : item.region,
value_mode: item.valueMode || "single_line",
stop_anchors:
@@ -1517,6 +1526,14 @@ const mergeEquivalentOrderAnchors = (items: OrderProfileCanvasRegion[]) => {
/** 从 v2 定义恢复区域,供草稿重开后继续在画布上编辑。 */
const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
for (const key of Object.keys(tableRegionSettings)) delete tableRegionSettings[Number(key)];
for (const table of profile.definition.table_regions) {
const regionPageNo = restoreOrderProfileRegionPageNo(table);
tableRegionSettings[regionPageNo] = {
rowReconstructionMode: table.row_reconstruction_mode || 'fixed_subrows',
pageScope: table.page_scope,
};
}
const restored: OrderProfileCanvasRegion[] = [
...(profile.definition.document_match.required_anchors || []).flatMap<OrderProfileCanvasRegion>((anchor) => {
if (!anchor.label_region || !anchor.value_region || !anchor.page_no) return [];
@@ -1530,7 +1547,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
}),
...(profile.definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
const pageNo = item.page_scope === "exact_page" ? item.page_no || 1 : 1;
if (!item.anchor?.region || (!item.value_region && !item.absolute_value_region)) {
if (!item.anchor?.region || !item.absolute_value_region) {
return [{
id: `unbound-${item.layout_id}`,
kind: "order_field" as const,
@@ -1553,13 +1570,11 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
kind: "order_field" as const,
label: item.label,
region: {
x0: item.absolute_value_region?.x0 ?? anchor.x0 + item.value_region!.x0 * (anchor.x1 - anchor.x0),
y0: item.absolute_value_region?.y0 ?? anchor.y0 + item.value_region!.y0 * (anchor.y1 - anchor.y0),
x1: item.absolute_value_region?.x1 ?? anchor.x0 + item.value_region!.x1 * (anchor.x1 - anchor.x0),
y1: item.absolute_value_region?.y1 ?? anchor.y0 + item.value_region!.y1 * (anchor.y1 - anchor.y0),
...item.absolute_value_region,
},
fieldCode: null,
orderFieldId: item.layout_id,
valueMode: item.value_mode,
pageNo,
}];
}),
@@ -1572,7 +1587,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
pageNo: item.page_scope === "exact_page" ? item.page_no || 1 : 1,
})),
...(profile.definition.order_field_layouts || []).flatMap((item) => {
if (!item.anchor?.region || (!item.value_region && !item.absolute_value_region)) return [];
if (!item.anchor?.region || !item.absolute_value_region) return [];
const anchor = item.anchor.region;
return [{
id: item.anchor.anchor_id,
@@ -1586,10 +1601,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
kind: "order_field" as const,
label: schemaFieldLabel(item.field_code),
region: {
x0: item.absolute_value_region?.x0 ?? anchor.x0 + item.value_region!.x0 * (anchor.x1 - anchor.x0),
y0: item.absolute_value_region?.y0 ?? anchor.y0 + item.value_region!.y0 * (anchor.y1 - anchor.y0),
x1: item.absolute_value_region?.x1 ?? anchor.x0 + item.value_region!.x1 * (anchor.x1 - anchor.x0),
y1: item.absolute_value_region?.y1 ?? anchor.y0 + item.value_region!.y1 * (anchor.y1 - anchor.y0),
...item.absolute_value_region,
},
fieldCode: item.field_code,
orderFieldId: item.layout_id,
@@ -2076,6 +2088,36 @@ onBeforeUnmount(() => {
<p v-if="!documentMatch.requiredAnchors.length" class="document-match-editor__warning">{{ t('admin.shippingOrderProfiles.workbench.documentMatchAnchorEmpty') }}</p>
<p v-if="documentAnchorNotice" class="document-match-editor__warning">{{ documentAnchorNotice }}</p>
</section>
<section v-if="activePageHasLines" class="table-region-editor">
<strong>{{ t('admin.shippingOrderProfiles.workbench.tableRegionSettings') }}</strong>
<label>{{ t('admin.shippingOrderProfiles.workbench.rowReconstructionMode') }}
<select
:value="activeTableRegionSetting.rowReconstructionMode"
class="select-field"
:disabled="compactEditor || saveState === 'readonly'"
@focus="beginFormEdit"
@change="(event) => { ensureTableRegionSetting(pageNo).rowReconstructionMode = (event.target as HTMLSelectElement).value as OrderProfileRowReconstructionMode; updateActiveTableRegionSetting(); }"
>
<option value="fixed_subrows">{{ t('admin.shippingOrderProfiles.workbench.rowReconstructionModes.fixedSubrows') }}</option>
<option value="adaptive_record_columns">{{ t('admin.shippingOrderProfiles.workbench.rowReconstructionModes.adaptiveRecordColumns') }}</option>
</select>
</label>
<p>{{ t(`admin.shippingOrderProfiles.workbench.rowReconstructionHints.${activeTableRegionSetting.rowReconstructionMode}`) }}</p>
<label>{{ t('admin.shippingOrderProfiles.workbench.tableRegionPageScope') }}
<select
:value="activeTableRegionSetting.pageScope"
class="select-field"
:disabled="compactEditor || saveState === 'readonly'"
@focus="beginFormEdit"
@change="(event) => { ensureTableRegionSetting(pageNo).pageScope = (event.target as HTMLSelectElement).value as typeof activeTableRegionSetting.pageScope; updateActiveTableRegionSetting(); }"
>
<option value="exact_page">{{ t('admin.shippingOrderProfiles.workbench.tableRegionPageScopes.exactPage') }}</option>
<option value="first_page">{{ t('admin.shippingOrderProfiles.workbench.tableRegionPageScopes.firstPage') }}</option>
<option value="all_pages">{{ t('admin.shippingOrderProfiles.workbench.tableRegionPageScopes.allPages') }}</option>
<option value="continuation_pages">{{ t('admin.shippingOrderProfiles.workbench.tableRegionPageScopes.continuationPages') }}</option>
</select>
</label>
</section>
<section v-if="selectedRegion" class="editor">
<div class="selected-region-meta">
<span>{{ t('admin.shippingOrderProfiles.workbench.selectedRegion') }}</span>
@@ -2508,6 +2550,18 @@ onBeforeUnmount(() => {
padding: 0.85rem;
background: #f8fafc;
}
.table-region-editor {
display: grid;
gap: 0.55rem;
margin-bottom: 0.8rem;
padding: 0.75rem;
border: 1px solid #dbe5f0;
border-radius: 0.5rem;
background: #f8fafc;
}
.table-region-editor > strong { font-size: 0.84rem; }
.table-region-editor > label { display: grid; gap: 0.3rem; font-size: 0.78rem; color: #475569; }
.table-region-editor > p { margin: 0; font-size: 0.72rem; color: #64748b; }
.document-match-editor__heading { display: flex; gap: 0.5rem; align-items: start; }
.document-match-editor__heading strong { font-size: 0.84rem; }
.document-match-editor__heading p { margin: 0.3rem 0 0; font-size: 0.72rem; color: #64748b; }
@@ -2651,6 +2705,8 @@ onBeforeUnmount(() => {
.editor-title { min-width: 0; }
.editor-workbench .desk { max-width: none; min-height: calc(100vh - 7rem); border-inline: 0; box-shadow: none; }
.editor-desk { grid-template-columns: minmax(0, 1fr) 20rem; }
.editor-desk > main { min-height: 0; }
.editor-workbench .config { max-height: calc(100vh - 5rem); overflow-y: auto; }
.editor-bottom-drawer { max-width: none; border-top: 1px solid #334155; background: #f8fafc; }
.suggestion-decision { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; border-top: 1px solid #7dd3fc; background: #ecfeff; padding: .65rem .9rem; color: #155e75; }
.suggestion-decision span { border-radius: 999px; background: #bae6fd; padding: .15rem .4rem; font-size: .72rem; }.suggestion-decision button,.suggestion-decision .select-field { border: 1px solid #0891b2; border-radius: .35rem; background: #fff; padding: .35rem .55rem; color: #0e7490; font-size: .75rem; }
@@ -3090,7 +3146,7 @@ onBeforeUnmount(() => {
}
@media (max-width: 767px) {
.editor-desk { grid-template-columns: 1fr; min-height: auto; }
.editor-workbench .config { border-left: 0; border-top: 1px solid #cbd5e1; }
.editor-workbench .config { max-height: none; overflow-y: visible; border-left: 0; border-top: 1px solid #cbd5e1; }
.editor-bottom-drawer__content { grid-template-columns: 1fr; }
}
.order-field-list {
@@ -104,15 +104,20 @@ async function loadContext(): Promise<void> {
/** Schema 显示名称服务于业务核对;稳定编码仅作为辅助追溯信息保留。 */
function fieldName(fieldCode: string): string { return fieldNames.value.get(fieldCode) || fieldCode; }
/** 使用本次草稿定义重读表头和明细;结果只来自实时接口,不回退历史建议文本。 */
/** 使用本次草稿定义重读全部已绑定表头页和明细;结果只来自实时接口,不回退历史建议文本。 */
async function loadReadResults(): Promise<void> {
if (!profile.value || !sample.value?.table_id) return;
resultLoading.value = true;
resultFailed.value = false;
try {
const pageNo = sample.value.table_identity_snapshot?.page_no || 1;
const pageNos = Array.from(new Set((profile.value.definition.order_field_layouts || []).map((item) => (
item.page_scope === 'exact_page' ? (item.page_no || 1) : 1
)))).sort((left, right) => left - right);
const pageNo = pageNos[0] || sample.value.table_identity_snapshot?.page_no || 1;
const [headers, lines] = await Promise.all([
previewOrderProfileOrderFieldValues(sample.value.document_id, profile.value.schema_version_id, pageNo, profile.value.definition),
previewOrderProfileOrderFieldValues(
sample.value.document_id, profile.value.schema_version_id, pageNo, profile.value.definition, pageNos,
),
previewOrderProfileRegion(profileId, sample.value.document_id, sample.value.table_id, profile.value.definition),
]);
headerValues.value = headers.fields;
@@ -168,8 +173,9 @@ function backToEditor(): void {
onMounted(async () => {
await Promise.all([loadRuns(), loadContext()]);
await loadReadResults();
if (canStartBlindTest.value) {
await Promise.all([loadBlindTestSuite(), loadReadResults()]);
await loadBlindTestSuite();
}
});
</script>
@@ -212,13 +218,13 @@ onMounted(async () => {
<div class="gate-actions"><strong :class="`status ${blindTestSuite?.status || 'pending'}`">{{ t(`admin.shippingOrderProfiles.blindTest.status.${blindTestSuite?.status || 'missing'}`) }}</strong><button type="button" class="btn-secondary" @click="goToBlindTest">{{ t('admin.shippingOrderProfiles.blindTest.title') }}</button></div>
</section>
<section v-if="canStartBlindTest" class="results" :aria-label="t('admin.orderProfileValidation.resultsTitle')">
<section v-if="profile && sample" class="results" :aria-label="t('admin.orderProfileValidation.resultsTitle')">
<div class="results-heading"><div><h2>{{ t('admin.orderProfileValidation.resultsTitle') }}</h2><p>{{ t('admin.orderProfileValidation.resultsHint') }}</p></div><button type="button" class="btn-secondary btn-sm" :disabled="resultLoading" @click="loadReadResults">{{ t('admin.orderProfileValidation.refreshResults') }}</button></div>
<p v-if="resultLoading">{{ t('admin.orderProfileValidation.resultsLoading') }}</p>
<p v-else-if="resultFailed" class="result-error">{{ t('admin.orderProfileValidation.resultsFailed') }}</p>
<template v-else>
<h3>{{ t('admin.orderProfileValidation.headerResults') }}</h3>
<dl v-if="headerValues.length" class="header-results"><div v-for="field in headerValues" :key="field.field_id"><dt>{{ fieldName(field.field_code) }}</dt><dd class="field-code">{{ field.field_code }}</dd><dd>{{ field.value || t('admin.orderProfileValidation.noValue') }}</dd></div></dl>
<dl v-if="headerValues.length" class="header-results"><div v-for="field in headerValues" :key="`${field.field_id}:${field.page_no || 0}`" :class="`field-${field.status}`"><dt>{{ fieldName(field.field_code) }}</dt><dd class="field-code">{{ field.field_code }} · P{{ field.page_no || '-' }}</dd><dd>{{ field.value || t('admin.orderProfileValidation.noValue') }}</dd><dd v-if="field.issues.length" class="field-issues">{{ field.issues.join(', ') }}</dd></div></dl>
<p v-else>{{ t('admin.orderProfileValidation.noHeaderResults') }}</p>
<h3>{{ t('admin.orderProfileValidation.lineResults') }}</h3>
<div v-if="linePreview?.rows?.length" class="line-results"><table><thead><tr><th v-for="field in linePreview.rows[0]" :key="field"><span>{{ fieldName(field) }}</span><small>{{ field }}</small></th><th>{{ t('admin.orderProfileValidation.rowStatus') }}</th></tr></thead><tbody><tr v-for="(row, index) in linePreview.rows.slice(1)" :key="index" :class="linePreview.row_roles[index + 1] === 'deleted' ? 'deleted-row' : ''"><td v-for="(value, cellIndex) in row" :key="cellIndex">{{ value || t('admin.orderProfileValidation.noValue') }}</td><td>{{ linePreview.row_roles[index + 1] === 'deleted' ? t('admin.orderProfileValidation.deleted') : t('admin.orderProfileValidation.read') }}</td></tr></tbody></table></div>
@@ -241,5 +247,6 @@ button:disabled { cursor: not-allowed; opacity: .55; }
.current-draft-validation { display: grid; gap: 16px; margin-top: 20px; padding: 16px; }.current-draft-validation > header { align-items: center; }.current-draft-validation > header > div { min-width: 0; }.current-draft-validation > header button { flex: 0 0 auto; }.checks { display: grid; gap: 10px; }.checks article { display: flex; align-items: center; justify-content: space-between; gap: 20px; border-radius: 8px; padding: 15px 16px; }.status { min-width: 72px; text-align: right; font-size: 13px; font-weight: 600; }.passed { color: #15803d; }.failed, .stale { color: #b91c1c; }.pending, .running { color: #64748b; }
.blind-test-gate { display: flex; align-items: center; justify-content: space-between; gap: 20px; margin-top: 20px; padding: 16px; }.blind-test-gate h2 { margin: 0; color: #1e293b; font-size: 15px; font-weight: 600; }.gate-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }.gate-actions .approved { color: #15803d; }.gate-actions .draft, .gate-actions .missing { color: #b45309; }
.results { margin-top: 20px; padding: 16px; }.results-heading { display: flex; align-items: center; justify-content: space-between; gap: 16px; }.results h2, .results h3 { margin: 0; color: #1e293b; }.results h2 { font-size: 15px; }.results h3 { margin-top: 20px; font-size: 14px; }.results-heading p { margin: 5px 0 0; color: #64748b; font-size: 13px; line-height: 1.5; }.header-results { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px; margin: 12px 0 0; }.header-results div { border: 1px solid #e5ebf1; border-radius: 6px; background: #fbfdff; padding: 10px; }.header-results dt { color: #475569; font-size: 13px; font-weight: 600; }.header-results dd { margin: 4px 0 0; overflow-wrap: anywhere; }.header-results .field-code, .line-results th small { color: #94a3b8; font-size: 11px; font-weight: 400; }.line-results { margin-top: 12px; overflow-x: auto; border: 1px solid #e5ebf1; border-radius: 6px; }.line-results table { width: 100%; min-width: 560px; border-collapse: collapse; }.line-results th, .line-results td { padding: 10px 12px; border-bottom: 1px solid #e5ebf1; text-align: left; vertical-align: top; overflow-wrap: anywhere; }.line-results tbody tr:last-child td { border-bottom: 0; }.line-results th { background: #f8fafc; color: #64748b; font-size: 12px; font-weight: 600; }.line-results th span, .line-results th small { display: block; }.deleted-row { color: #94a3b8; text-decoration: line-through; }.result-error { color: #b91c1c; }
.header-results .field-needs_review, .header-results .field-unavailable { border-color: #fed7aa; background: #fff7ed; }.header-results .field-issues { color: #b45309; font-size: 11px; }
@media (max-width: 767px) { .validation-page { padding: 16px; } header, .validation-state, .current-draft-validation > header, .checks article, .blind-test-gate, .results-heading { display: grid; }.validation-state button, .current-draft-validation > header button, .blind-test-gate button, .results-heading button { width: 100%; } }
</style>
@@ -2,10 +2,11 @@
features/admin/modules/shipping-order-document-profiles/OrderProfileVersionDetailPage.vue
用途:订单模板版本中心详情页,支持刷新恢复与分享。
依赖:版本详情 composable、配置概览组件、版本中心 API。
逻辑:当前已接入配置概览、只读样本画布、服务端语义 diff、审计时间线与实际使用;后续仅剩盲测隔离与发布治理收口。
逻辑:当前已接入配置概览、只读样本画布、服务端语义 diff、审计时间线与实际使用;
Schema 迁移弹窗按模态语义提供初始焦点、Tab 陷阱、Escape 关闭与焦点恢复。
-->
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import { BusinessError } from "@/shared/api/client";
@@ -35,6 +36,19 @@ const migrating = ref(false);
const migrationOpen = ref(false);
const publishedSchema = ref<ShippingOrderSchemaVersion | null>(null);
const migrationResolutions = ref<Record<string, { action: "unbind" } | { replacement_field_id: string }>>({});
const migrationPanelRef = ref<HTMLElement | null>(null);
const migrationCancelRef = ref<HTMLButtonElement | null>(null);
let previouslyFocused: HTMLElement | null = null;
const FOCUSABLE_SELECTOR = [
"a[href]",
"button:not([disabled])",
"textarea:not([disabled])",
"input:not([disabled])",
"select:not([disabled])",
'[tabindex]:not([tabindex="-1"])',
].join(",");
const {
activeTab,
detail,
@@ -62,6 +76,53 @@ const loadPublishedSchema = async () => {
}
};
/** 收集迁移弹窗内可聚焦控件。 */
function migrationFocusableNodes(): HTMLElement[] {
if (!migrationPanelRef.value) return [];
return Array.from(migrationPanelRef.value.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR))
.filter((node) => !node.hasAttribute("disabled") && node.getAttribute("aria-hidden") !== "true");
}
/** 关闭 Schema 迁移弹窗。 */
function closeSchemaMigration(): void {
if (migrating.value) return;
migrationOpen.value = false;
}
/**
* Escape 关闭;Tab 在弹窗内循环,阻止焦点逃逸到背景页。
*/
function onMigrationKeydown(event: KeyboardEvent): void {
if (!migrationOpen.value) return;
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
closeSchemaMigration();
return;
}
if (event.key !== "Tab") return;
const nodes = migrationFocusableNodes();
const first = nodes[0];
const last = nodes[nodes.length - 1];
if (!first || !last) {
event.preventDefault();
return;
}
const active = document.activeElement as HTMLElement | null;
const inside = Boolean(active && migrationPanelRef.value?.contains(active));
if (event.shiftKey) {
if (!inside || active === first) {
event.preventDefault();
last.focus();
}
return;
}
if (!inside || active === last) {
event.preventDefault();
first.focus();
}
}
const openSchemaMigration = () => {
migrationResolutions.value = Object.fromEntries(
breakingChanges.value.map((change) => [change.field_id, { action: "unbind" }]),
@@ -125,6 +186,35 @@ const migrateSchema = async () => {
onMounted(() => { void loadPublishedSchema(); });
watch(
() => migrationOpen.value,
async (open, wasOpen) => {
if (typeof document === "undefined") return;
if (open && !wasOpen) {
previouslyFocused = document.activeElement instanceof HTMLElement
? document.activeElement
: null;
document.addEventListener("keydown", onMigrationKeydown, true);
await nextTick();
(migrationCancelRef.value || migrationFocusableNodes()[0])?.focus();
return;
}
if (!open && wasOpen) {
document.removeEventListener("keydown", onMigrationKeydown, true);
const restoreTarget = previouslyFocused;
previouslyFocused = null;
await nextTick();
restoreTarget?.focus?.();
}
},
);
onBeforeUnmount(() => {
if (typeof document !== "undefined") {
document.removeEventListener("keydown", onMigrationKeydown, true);
}
});
watch([detail, publishedSchema, () => route.query.migrate], () => {
if (route.query.migrate !== "1" || !canMigrateSchema.value || migrationOpen.value) return;
openSchemaMigration();
@@ -312,8 +402,21 @@ const createNewVersion = async () => {
</section>
</div>
</template>
<div v-if="migrationOpen" class="migration-backdrop" role="presentation" @click.self="migrationOpen = false">
<section class="migration-dialog" role="dialog" aria-modal="true" :aria-label="t('admin.shippingOrderProfiles.schemaMigration.title')">
<div
v-if="migrationOpen"
class="migration-backdrop"
role="presentation"
data-testid="order-profile-schema-migration-backdrop"
@click.self="closeSchemaMigration"
>
<section
ref="migrationPanelRef"
class="migration-dialog"
role="dialog"
aria-modal="true"
:aria-label="t('admin.shippingOrderProfiles.schemaMigration.title')"
data-testid="order-profile-schema-migration-dialog"
>
<h2>{{ t("admin.shippingOrderProfiles.schemaMigration.title") }}</h2>
<p>{{ t("admin.shippingOrderProfiles.schemaMigration.description", { from: detail?.schema_version, to: publishedSchema?.version }) }}</p>
<p class="migration-note">{{ t("admin.shippingOrderProfiles.schemaMigration.revalidation") }}</p>
@@ -337,8 +440,19 @@ const createNewVersion = async () => {
</div>
<p v-else class="migration-note">{{ t("admin.shippingOrderProfiles.schemaMigration.noBreakingChanges") }}</p>
<footer>
<button type="button" class="btn-secondary" :disabled="migrating" @click="migrationOpen = false">{{ t("admin.shippingOrderProfiles.schemaMigration.cancel") }}</button>
<button type="button" class="btn-primary" :disabled="migrating" @click="migrateSchema">{{ migrating ? t("admin.shippingOrderProfiles.saving") : t("admin.shippingOrderProfiles.schemaMigration.confirm") }}</button>
<button
ref="migrationCancelRef"
type="button"
class="btn-secondary"
:disabled="migrating"
data-testid="order-profile-schema-migration-cancel"
@click="closeSchemaMigration"
>
{{ t("admin.shippingOrderProfiles.schemaMigration.cancel") }}
</button>
<button type="button" class="btn-primary" :disabled="migrating" @click="migrateSchema">
{{ migrating ? t("admin.shippingOrderProfiles.saving") : t("admin.shippingOrderProfiles.schemaMigration.confirm") }}
</button>
</footer>
</section>
</div>
@@ -2,7 +2,8 @@
features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue
用途:展示受控 PDF 单页预览,并以相对坐标框支持选择、拖动和缩放区域。
依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion。
逻辑:父级签发单页令牌并提供分页动作;mode=readonly 时只允许查看/缩放/切页,不允许写入任何标注改动。
逻辑:父级签发单页令牌并提供分页动作;mode=readonly 时只允许查看/缩放/切页,不允许写入任何标注改动;
画布区域 aria-label 走四语言 i18n,供辅助技术正确读出只读/标注模式。
-->
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue';
@@ -171,8 +172,11 @@ const endCreation = () => {
};
const selected = computed(() => new Set([props.selectedRegionId]));
/** 订单字段标签只使用父级本次坐标读取结果,模板定义仍只保存字段与坐标。 */
/** 在画布徽标展示字段身份和实际识别值;编辑态订单字段继续使用工作台即时读取状态。 */
const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
if (readonlyMode.value && !['line', 'exclusion'].includes(region.kind)) {
return `${region.label} · ${region.recognizedValue || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable')}`;
}
if (region.kind !== 'order_field') return region.label;
const state = props.orderFieldValueState || 'idle';
const value = region.fieldCode ? props.orderFieldValues?.[region.fieldCode] : null;
@@ -202,7 +206,12 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
</script>
<template>
<section class="canvas-shell" :aria-label="readonlyMode ? 'Document readonly canvas' : 'Document annotation canvas'">
<section
class="canvas-shell"
:aria-label="readonlyMode
? t('admin.shippingOrderProfiles.workbench.readonlyCanvasAriaLabel')
: t('admin.shippingOrderProfiles.workbench.annotationCanvasAriaLabel')"
>
<header v-if="imageUrl" class="canvas-toolbar">
<div class="toolbar-actions">
<template v-if="!readonlyMode">
@@ -277,7 +286,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
</template>
<style scoped>
.canvas-shell { min-height: 36rem; background: #101827; padding: 0 1rem 1rem; overflow: hidden; }
.canvas-shell { display: flex; height: calc(100vh - 5rem); min-height: 48rem; flex-direction: column; background: #101827; padding: 0 1rem 1rem; overflow: hidden; }
.canvas-toolbar { position: sticky; top: 0; z-index: 4; display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: .75rem; margin: 0 -1rem 1rem; padding: .55rem 1rem; border-bottom: 1px solid #26354b; background: rgb(15 23 42 / .98); color: #cbd5e1; font-size: .75rem; }
.canvas-toolbar > div { display: flex; align-items: center; gap: .35rem; }
.canvas-toolbar button { display: inline-flex; min-width: 2rem; height: 2rem; align-items: center; justify-content: center; gap: .35rem; border: 1px solid #475569; border-radius: .35rem; background: #1e293b; padding: .3rem .5rem; color: #e2e8f0; font-size: .72rem; }
@@ -300,7 +309,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
.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-work-area { display: flex; max-height: 43rem; gap: .6rem; }
.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; }
.canvas-viewport.panning { cursor: grab; }
@@ -355,6 +364,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
.region.selected:not(.region-line) { z-index: 4; }
.canvas-stage.drawing .region { pointer-events: none; }
@media (max-width: 900px) {
.canvas-shell { height: auto; min-height: 36rem; }
.canvas-toolbar { grid-template-columns: 1fr auto; }
.page-control { grid-column: 1 / -1; grid-row: 2; }
.zoom-control { justify-self: end; }
@@ -8,10 +8,14 @@
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { authorizeOrderProfileFrozenSamplePreviewPages } from '@/features/admin/api/shipping-order-document-profile.api';
import {
authorizeOrderProfileFrozenSamplePreviewPages,
getOrderProfileFrozenSampleRegionDiagnostics,
} from '@/features/admin/api/shipping-order-document-profile.api';
import type {
OrderProfileBoundSample,
OrderProfilePreviewPages,
OrderProfileRegionDiagnostic,
ShippingOrderDocumentProfile,
} from '@/features/admin/types/shipping-order-document-profile.types';
import OrderProfileDocumentCanvas from './OrderProfileDocumentCanvas.vue';
@@ -28,6 +32,8 @@ const errorMessage = ref('');
const selectedSampleId = ref<number | null>(null);
const selectedRegionId = ref<string | null>(null);
const previewPages = ref<OrderProfilePreviewPages | null>(null);
const regionDiagnostics = ref(new Map<string, OrderProfileRegionDiagnostic>());
const diagnosticsLoading = ref(false);
const pageNo = ref(1);
const readonlySamples = computed(() =>
@@ -36,7 +42,15 @@ const readonlySamples = computed(() =>
const selectedSample = computed<OrderProfileBoundSample | null>(() =>
readonlySamples.value.find((sample) => sample.id === selectedSampleId.value) || null,
);
const readonlyRegions = computed(() => buildOrderProfileReadonlyRegions(props.detail));
const readonlyRegions = computed(() => buildOrderProfileReadonlyRegions(props.detail).map((region) => {
const diagnostic = regionDiagnostics.value.get(region.id);
return diagnostic ? {
...region,
recognizedValue: diagnostic.recognized_value,
configuredValue: diagnostic.configured_value,
matchesConfigured: diagnostic.matches_configured,
} : region;
}));
const pageRegions = computed(() => readonlyRegions.value.filter((region) => region.pageNo === pageNo.value));
const selectedRegion = computed(() => pageRegions.value.find((region) => region.id === selectedRegionId.value) || null);
const currentGrant = computed(() =>
@@ -48,6 +62,9 @@ const previewPagePath = computed(() => (
: null
));
const immutable = computed(() => props.detail.status !== 'draft');
const selectedDiagnostic = computed(() => (
selectedRegion.value ? regionDiagnostics.value.get(selectedRegion.value.id) || null : null
));
const sampleLabel = (sample: OrderProfileBoundSample) => {
const tableLabel = sample.table_identity_snapshot?.table_id || sample.table_id || '-';
@@ -57,6 +74,7 @@ const sampleLabel = (sample: OrderProfileBoundSample) => {
const loadPreview = async (sampleId: number | null) => {
if (!sampleId || !immutable.value) {
previewPages.value = null;
regionDiagnostics.value = new Map();
errorMessage.value = '';
return;
}
@@ -78,6 +96,27 @@ const loadPreview = async (sampleId: number | null) => {
}
};
/** 读取当前冻结样本页的受控区域识别值,并按 region ID 合并到只读画布。 */
const loadRegionDiagnostics = async (): Promise<void> => {
const sampleId = selectedSampleId.value;
if (!sampleId || !immutable.value) {
regionDiagnostics.value = new Map();
return;
}
diagnosticsLoading.value = true;
try {
const payload = await getOrderProfileFrozenSampleRegionDiagnostics(props.detail.id, sampleId, pageNo.value);
regionDiagnostics.value = new Map(payload.items.map((item) => [item.region_id, item]));
} catch (error) {
regionDiagnostics.value = new Map();
errorMessage.value = error instanceof BusinessError
? error.message
: t('admin.shippingOrderProfiles.versionCenter.regionDiagnosticsLoadFailed');
} finally {
diagnosticsLoading.value = false;
}
};
watch(
() => props.detail.id,
() => {
@@ -90,6 +129,10 @@ watch(
watch(selectedSampleId, (value) => {
void loadPreview(value);
}, { immediate: true });
watch([selectedSampleId, pageNo], () => {
void loadRegionDiagnostics();
}, { immediate: true });
</script>
<template>
@@ -134,6 +177,7 @@ watch(selectedSampleId, (value) => {
<OrderProfileFrozenEvidencePanel :sample="selectedSample" />
<section class="panel">
<h3>{{ t('admin.shippingOrderProfiles.versionCenter.regionSummaryTitle') }}</h3>
<p v-if="diagnosticsLoading" class="diagnostic-state">{{ t('admin.shippingOrderProfiles.versionCenter.regionDiagnosticsLoading') }}</p>
<p v-if="!selectedRegion" class="empty">{{ t('admin.shippingOrderProfiles.versionCenter.selectRegionHint') }}</p>
<dl v-else class="grid">
<div>
@@ -152,6 +196,22 @@ watch(selectedSampleId, (value) => {
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.regionPageTitle') }}</dt>
<dd>{{ selectedRegion.pageNo }}</dd>
</div>
<div class="wide-row">
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.recognizedValueTitle') }}</dt>
<dd class="diagnostic-value">{{ selectedDiagnostic?.recognized_value || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable') }}</dd>
</div>
<div v-if="selectedDiagnostic?.configured_value != null" class="wide-row">
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.configuredValueTitle') }}</dt>
<dd class="diagnostic-value">{{ selectedDiagnostic.configured_value }}</dd>
</div>
<div v-if="selectedDiagnostic?.matches_configured != null" class="wide-row">
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.matchResultTitle') }}</dt>
<dd :class="selectedDiagnostic.matches_configured ? 'match-ok' : 'match-failed'">
{{ selectedDiagnostic.matches_configured
? t('admin.shippingOrderProfiles.versionCenter.matchResultMatched')
: t('admin.shippingOrderProfiles.versionCenter.matchResultMismatched') }}
</dd>
</div>
</dl>
</section>
</div>
@@ -225,6 +285,45 @@ watch(selectedSampleId, (value) => {
word-break: break-word;
}
.wide-row {
grid-column: 1 / -1;
}
.diagnostic-state {
margin: 0.75rem 0 0;
color: #0369a1;
font-size: 0.78rem;
}
.diagnostic-value {
border-left: 3px solid #0ea5e9;
background: #f0f9ff;
padding: 0.65rem 0.75rem;
color: #0f172a;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
line-height: 1.55;
white-space: pre-wrap;
}
.match-ok,
.match-failed {
display: inline-flex;
width: fit-content;
border-radius: 999px;
padding: 0.3rem 0.65rem;
font-weight: 700;
}
.match-ok {
background: #dcfce7;
color: #166534;
}
.match-failed {
background: #fee2e2;
color: #991b1b;
}
.warning-text {
margin: 0;
color: #b45309;
@@ -5,7 +5,7 @@
逻辑:上传后轮询同一 Intake;只有 ready 样本进入父级选择值,避免要求管理员重复选择刚上传的文件。
-->
<script setup lang="ts">
import { computed, onBeforeUnmount, ref } from 'vue';
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import { CheckCircle2, Clock3, UploadCloud } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
@@ -15,11 +15,12 @@ import { createOrderProfileSample, getOrderProfileSampleStatus } from '@/feature
type Sample = { document_id: number; filename?: string | null; table_count: number; intake_no: string };
const props = defineProps<{ samples: Sample[]; modelValue: number }>();
const emit = defineEmits<{ 'update:modelValue': [value: number]; uploaded: []; }>();
const emit = defineEmits<{ 'update:modelValue': [value: number]; uploaded: [intakeNo: string]; refresh: []; }>();
const { t } = useI18n();
const message = useMessage();
const uploading = ref(false);
const pendingIntake = ref<{ intakeNo: string; filename: string; state: 'parsing' | 'failed'; errorCode?: string | null } | null>(null);
type PendingState = 'uploading' | 'queued' | 'parsing' | 'syncing' | 'failed';
const pendingIntake = ref<{ intakeNo?: string; filename: string; state: PendingState; errorCode?: string | null } | null>(null);
let pollingTimer: number | null = null;
const selectedSample = computed(() => props.samples.find((item) => item.document_id === props.modelValue) || null);
@@ -39,19 +40,26 @@ function selectUploadedSample(intakeNo: string): boolean {
const sample = props.samples.find((item) => item.intake_no === intakeNo);
if (!sample) return false;
emit('update:modelValue', sample.document_id);
stopPolling();
pendingIntake.value = null;
return true;
}
/** 父级完成样本列表请求后立即选中同一 Intake,避免固定延时与接口响应竞态。 */
watch(() => props.samples, () => {
const intakeNo = pendingIntake.value?.intakeNo;
if (intakeNo && pendingIntake.value?.state === 'syncing' && selectUploadedSample(intakeNo)) {
message.success(t('admin.shippingOrderProfiles.wizard.sampleReady'));
}
}, { deep: false });
/** 查询异步解析状态,完成后请求父级刷新列表并自动选中当前上传的样本。 */
async function pollIntake(intakeNo: string): Promise<void> {
try {
const result = await getOrderProfileSampleStatus(intakeNo);
if (result.parse_status === 'parsed' && result.document_count > 0) {
emit('uploaded');
window.setTimeout(() => {
if (selectUploadedSample(intakeNo)) message.success(t('admin.shippingOrderProfiles.wizard.sampleReady'));
else pollingTimer = window.setTimeout(() => void pollIntake(intakeNo), 800);
}, 350);
pendingIntake.value = { intakeNo, filename: pendingIntake.value?.filename || '', state: 'syncing' };
emit('uploaded', intakeNo);
// 列表可能比状态接口晚一个轮询周期可见,保持轮询直到父级刷新后精确选中。
pollingTimer = window.setTimeout(() => void pollIntake(intakeNo), 1000);
return;
}
if (['failed', 'error'].includes(result.parse_status)) {
@@ -60,6 +68,7 @@ async function pollIntake(intakeNo: string): Promise<void> {
};
return;
}
if (pendingIntake.value) pendingIntake.value.state = result.document_count ? 'parsing' : 'queued';
pollingTimer = window.setTimeout(() => void pollIntake(intakeNo), 1500);
} catch {
pollingTimer = window.setTimeout(() => void pollIntake(intakeNo), 2000);
@@ -74,12 +83,14 @@ async function upload(event: Event): Promise<void> {
if (!/\.(pdf|eml)$/i.test(file.name)) { message.error(t('admin.shippingOrderProfiles.sampleFileTypeInvalid')); return; }
stopPolling();
uploading.value = true;
pendingIntake.value = { filename: file.name, state: 'uploading' };
try {
const asset = await uploadFileAsset(file);
const intake = await createOrderProfileSample(asset.asset_no);
pendingIntake.value = { intakeNo: intake.intake_no, filename: file.name, state: 'parsing' };
pendingIntake.value = { intakeNo: intake.intake_no, filename: file.name, state: 'queued' };
void pollIntake(intake.intake_no);
} catch (error) {
pendingIntake.value = null;
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.uploadFailed'));
} finally { uploading.value = false; }
}
@@ -95,8 +106,13 @@ onBeforeUnmount(stopPolling);
</section>
<div v-if="pendingIntake" class="parse-status" :class="{ failed: pendingIntake.state === 'failed' }">
<Clock3 v-if="pendingIntake.state === 'parsing'" :size="19" /><span v-else>!</span>
<div><strong>{{ pendingIntake.filename }}</strong><p>{{ pendingIntake.state === 'parsing' ? t('admin.shippingOrderProfiles.wizard.sampleParsing') : sampleFailureMessage(pendingIntake.errorCode) }}</p></div>
<Clock3 v-if="pendingIntake.state !== 'failed'" :size="19" /><span v-else>!</span>
<div>
<strong>{{ pendingIntake.filename }}</strong>
<p v-if="pendingIntake.state === 'failed'">{{ sampleFailureMessage(pendingIntake.errorCode) }}</p>
<p v-else>{{ t(`admin.shippingOrderProfiles.wizard.sampleStatus.${pendingIntake.state}`) }}</p>
<button v-if="pendingIntake.state !== 'uploading' && pendingIntake.state !== 'failed'" type="button" class="refresh-status" @click="emit('refresh')">{{ t('admin.shippingOrderProfiles.wizard.refreshSamples') }}</button>
</div>
</div>
<div v-if="selectedSample" class="selected-sample"><CheckCircle2 :size="20" /><div><strong>{{ t('admin.shippingOrderProfiles.wizard.sampleSelected') }}</strong><span>{{ selectedSample.filename || selectedSample.intake_no }} · {{ selectedSample.table_count }} {{ t('admin.shippingOrderProfiles.tablesUnit') }}</span></div></div>
@@ -109,5 +125,5 @@ onBeforeUnmount(stopPolling);
</template>
<style scoped>
.sample-step { display: grid; gap: 18px; max-width: 640px; }.upload-panel,.reuse-panel,.parse-status,.selected-sample { border: 1px solid var(--border-default); border-radius: 12px; background: var(--bg-surface); }.upload-panel { display: grid; grid-template-columns: auto 1fr auto; gap: 14px; align-items: center; padding: 18px; background: var(--bg-surface-soft); }.upload-panel__icon { display: grid; width: 42px; height: 42px; place-items: center; border-radius: 10px; color: var(--status-info-fg); background: var(--status-info-bg); }.upload-panel h3,.reuse-panel h3,.parse-status p,.selected-sample span { margin: 0; }.upload-panel h3,.reuse-panel h3 { color: var(--text-primary); font-size: 1rem; }.upload-panel p,.reuse-panel p { margin: 5px 0 0; color: var(--text-muted); font-size: .84rem; }.upload-action { display: inline-flex; min-height: 38px; align-items: center; border-radius: 8px; padding: 0 13px; color: #fff; background: #1677d2; font-weight: 700; cursor: pointer; }.upload-action input { position: absolute; width: 1px; height: 1px; overflow: hidden; opacity: 0; }.parse-status,.selected-sample { display: flex; gap: 10px; align-items: center; padding: 13px 15px; color: var(--status-info-fg); background: var(--status-info-bg); }.parse-status strong,.selected-sample strong { display: block; color: var(--text-primary); }.parse-status p,.selected-sample span { display: block; margin-top: 3px; color: var(--text-muted); font-size: .83rem; }.parse-status.failed { color: var(--status-error-fg); border-color: var(--status-error-border); background: var(--status-error-bg); }.parse-status.failed > span { display: grid; width: 19px; height: 19px; place-items: center; border-radius: 50%; color: #fff; background: var(--status-error-fg); font-weight: 800; }.selected-sample { color: var(--status-success-fg); border-color: var(--status-success-border); background: var(--status-success-bg); }.reuse-panel { padding: 18px; }.reuse-panel__heading { margin-bottom: 14px; }.field { display: grid; gap: 7px; color: var(--text-secondary); font-size: .88rem; font-weight: 700; }.field .select-field { min-height: 44px; font: inherit; } @media (max-width: 640px) { .upload-panel { grid-template-columns: auto 1fr; }.upload-action { grid-column: 1 / -1; justify-content: center; } }
.sample-step { display: grid; gap: 18px; max-width: 640px; }.upload-panel,.reuse-panel,.parse-status,.selected-sample { border: 1px solid var(--border-default); border-radius: 12px; background: var(--bg-surface); }.upload-panel { display: grid; grid-template-columns: auto 1fr auto; gap: 14px; align-items: center; padding: 18px; background: var(--bg-surface-soft); }.upload-panel__icon { display: grid; width: 42px; height: 42px; place-items: center; border-radius: 10px; color: var(--status-info-fg); background: var(--status-info-bg); }.upload-panel h3,.reuse-panel h3,.parse-status p,.selected-sample span { margin: 0; }.upload-panel h3,.reuse-panel h3 { color: var(--text-primary); font-size: 1rem; }.upload-panel p,.reuse-panel p { margin: 5px 0 0; color: var(--text-muted); font-size: .84rem; }.upload-action { display: inline-flex; min-height: 38px; align-items: center; border-radius: 8px; padding: 0 13px; color: #fff; background: #1677d2; font-weight: 700; cursor: pointer; }.upload-action input { position: absolute; width: 1px; height: 1px; overflow: hidden; opacity: 0; }.parse-status,.selected-sample { display: flex; gap: 10px; align-items: center; padding: 13px 15px; color: var(--status-info-fg); background: var(--status-info-bg); }.parse-status strong,.selected-sample strong { display: block; color: var(--text-primary); }.parse-status p,.selected-sample span { display: block; margin-top: 3px; color: var(--text-muted); font-size: .83rem; }.refresh-status { margin-top: 6px; padding: 0; border: 0; color: inherit; background: transparent; font: inherit; font-size: .8rem; font-weight: 700; cursor: pointer; text-decoration: underline; }.parse-status.failed { color: var(--status-error-fg); border-color: var(--status-error-border); background: var(--status-error-bg); }.parse-status.failed > span { display: grid; width: 19px; height: 19px; place-items: center; border-radius: 50%; color: #fff; background: var(--status-error-fg); font-weight: 800; }.selected-sample { color: var(--status-success-fg); border-color: var(--status-success-border); background: var(--status-success-bg); }.reuse-panel { padding: 18px; }.reuse-panel__heading { margin-bottom: 14px; }.field { display: grid; gap: 7px; color: var(--text-secondary); font-size: .88rem; font-weight: 700; }.field .select-field { min-height: 44px; font: inherit; } @media (max-width: 640px) { .upload-panel { grid-template-columns: auto 1fr; }.upload-action { grid-column: 1 / -1; justify-content: center; } }
</style>
@@ -15,9 +15,7 @@ import {
shouldShowStandardOrderProfilePreview,
toOrderProfileAnchorId,
buildOrderProfileRecognitionResults,
isOrderProfileAnchorRelativeCandidate,
normalizeOrderProfileRelativeRegion,
toOrderProfileAnchorRelativeRegion,
groupUniqueOrderProfileLineFields,
} from './orderProfileForm.utils';
@@ -226,24 +224,4 @@ describe('order profile form rules', () => {
expect(normalizeOrderProfileRelativeRegion({ x0: 1.1, y0: .2, x1: 1.2, y1: .3 })).toBeNull();
});
it('serializes a right-of-anchor value box as a movable anchor-relative region', () => {
expect(toOrderProfileAnchorRelativeRegion(
{ x0: .42, y0: .80, x1: .50, y1: .82 },
{ x0: .30, y0: .80, x1: .41, y1: .82 },
)).toEqual({ x0: expect.closeTo(1.090909), y0: 0, x1: expect.closeTo(1.818181), y1: 1 });
});
it('keeps a remote legacy value box absolute instead of creating invalid relative offsets', () => {
expect(isOrderProfileAnchorRelativeCandidate(
{ x0: .33, y0: .58, x1: .72, y1: .60 },
{ x0: .02, y0: .10, x1: .15, y1: .12 },
)).toBe(false);
});
it('keeps a same-row auto suggestion absolute when its tiny label makes the relative span exceed the contract', () => {
expect(isOrderProfileAnchorRelativeCandidate(
{ x0: .30, y0: .40, x1: .95, y1: .42 },
{ x0: .20, y0: .40, x1: .21, y1: .42 },
)).toBe(false);
});
});
@@ -68,43 +68,6 @@ export const normalizeOrderProfileRelativeRegion = (
return x0 < x1 && y0 < y1 ? { x0, y0, x1, y1 } : null;
};
/** 将页面值框换算为锚点尺寸的相对偏移,供标签右侧字段随标签移动读取。 */
export const toOrderProfileAnchorRelativeRegion = (
valueRegion: OrderProfileRelativeRegion,
anchorRegion: OrderProfileRelativeRegion,
): OrderProfileRelativeRegion | null => {
const width = anchorRegion.x1 - anchorRegion.x0;
const height = anchorRegion.y1 - anchorRegion.y0;
if (width <= 0 || height <= 0) return null;
const relative = {
x0: (valueRegion.x0 - anchorRegion.x0) / width,
y0: (valueRegion.y0 - anchorRegion.y0) / height,
x1: (valueRegion.x1 - anchorRegion.x0) / width,
y1: (valueRegion.y1 - anchorRegion.y0) / height,
};
return Number.isFinite(relative.x0) && Number.isFinite(relative.y0)
&& Number.isFinite(relative.x1) && Number.isFinite(relative.y1)
&& relative.x0 < relative.x1 && relative.y0 < relative.y1 ? relative : null;
};
/** 判断标签和值框是否是同一视觉行,只有这种画布关系可安全改为随标签移动。 */
export const isOrderProfileAnchorRelativeCandidate = (
valueRegion: OrderProfileRelativeRegion,
anchorRegion: OrderProfileRelativeRegion,
): boolean => {
const anchorHeight = anchorRegion.y1 - anchorRegion.y0;
const valueHeight = valueRegion.y1 - valueRegion.y0;
if (anchorHeight <= 0 || valueHeight <= 0) return false;
const tolerance = Math.max(anchorHeight, valueHeight) * 2;
if (!(valueRegion.y0 <= anchorRegion.y1 + tolerance
&& anchorRegion.y0 <= valueRegion.y1 + tolerance)) return false;
const relative = toOrderProfileAnchorRelativeRegion(valueRegion, anchorRegion);
// Backend intentionally bounds offsets to prevent a tiny auto-detected label
// from producing an unbounded template rule. Fall back to the page box here.
return relative !== null && [relative.x0, relative.y0, relative.x1, relative.y1]
.every((value) => value >= -12 && value <= 12);
};
/**
* 判断是否显示普通表格预览;可直接创建 Profile 的表格不受上一张表多物理行状态影响。
* @param profileCreationAllowed - 当前表格是否可直接创建 Profile
@@ -0,0 +1,43 @@
/**
* features/admin/modules/shipping-order-document-profiles/orderProfileReadonlyCanvas.utils.spec.ts
* 用途:验证版本只读画布完整恢复模板定义中的诊断区域。
* 依赖:Vitest、orderProfileReadonlyCanvas.utils。
* 逻辑:已发布版本的必需锚点必须同时显示标签框和值框,且区域 ID 与冻结诊断接口一致。
*/
import { describe, expect, it } from 'vitest';
import type { ShippingOrderDocumentProfile } from '@/features/admin/types/shipping-order-document-profile.types';
import { buildOrderProfileReadonlyRegions } from './orderProfileReadonlyCanvas.utils';
describe('buildOrderProfileReadonlyRegions', () => {
it('restores required anchor label and value regions on the published canvas', () => {
const profile = {
definition: {
document_match: {
required_anchors: [{
anchor_id: 'plant_address',
label: 'PLANT ADDR:',
value: 'No. 88',
value_position: 'right',
page_no: 1,
label_region: { x0: .1, y0: .1, x1: .2, y1: .15 },
value_region: { x0: .2, y0: .1, x1: .5, y1: .2 },
minimum_evidence_level: 'coordinate',
}],
optional_anchors: [],
},
table_regions: [],
order_field_layouts: [],
draft_unbound_order_field_layouts: [],
},
} as unknown as ShippingOrderDocumentProfile;
const regions = buildOrderProfileReadonlyRegions(profile);
// 关键断言:版本画布与后端诊断接口使用同一 region ID,标签和值均不可丢失。
expect(regions).toEqual(expect.arrayContaining([
expect.objectContaining({ id: 'plant_address_label', kind: 'document_anchor_label', configuredValue: 'PLANT ADDR:' }),
expect.objectContaining({ id: 'plant_address_value', kind: 'document_anchor_value', configuredValue: 'No. 88' }),
]));
});
});
@@ -61,9 +61,29 @@ export const buildOrderProfileReadonlyRegions = (
profile: ShippingOrderDocumentProfile,
): OrderProfileCanvasRegion[] => {
const restored: OrderProfileCanvasRegion[] = [
...(profile.definition.document_match.required_anchors || []).flatMap<OrderProfileCanvasRegion>((anchor) => {
if (!anchor.label_region || !anchor.value_region || !anchor.page_no) return [];
return [{
id: `${anchor.anchor_id}_label`,
kind: 'document_anchor_label',
label: anchor.label,
configuredValue: anchor.label,
region: anchor.label_region,
parentId: anchor.anchor_id,
pageNo: anchor.page_no,
}, {
id: `${anchor.anchor_id}_value`,
kind: 'document_anchor_value',
label: anchor.value,
configuredValue: anchor.value,
region: anchor.value_region,
parentId: anchor.anchor_id,
pageNo: anchor.page_no,
}];
}),
...(profile.definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
const pageNo = pageNoOf(item.page_scope, item.page_no);
if (!item.anchor?.region || !item.value_region) {
if (!item.anchor?.region || !item.absolute_value_region) {
return [{
id: `unbound-${item.layout_id}`,
kind: 'order_field',
@@ -74,8 +94,6 @@ export const buildOrderProfileReadonlyRegions = (
}];
}
const anchor = item.anchor.region;
const width = anchor.x1 - anchor.x0;
const height = anchor.y1 - anchor.y0;
return [{
id: `unbound-${item.anchor.anchor_id}`,
kind: 'order_anchor',
@@ -87,12 +105,7 @@ export const buildOrderProfileReadonlyRegions = (
id: `unbound-${item.layout_id}`,
kind: 'order_field',
label: item.label,
region: {
x0: anchor.x0 + item.value_region.x0 * width,
y0: anchor.y0 + item.value_region.y0 * height,
x1: anchor.x0 + item.value_region.x1 * width,
y1: anchor.y0 + item.value_region.y1 * height,
},
region: item.absolute_value_region,
fieldCode: null,
orderFieldId: item.layout_id,
pageNo,
@@ -107,10 +120,8 @@ export const buildOrderProfileReadonlyRegions = (
pageNo: pageNoOf(item.page_scope, item.page_no),
})),
...(profile.definition.order_field_layouts || []).flatMap((item) => {
if (!item.anchor?.region || !item.value_region) return [];
if (!item.anchor?.region || !item.absolute_value_region) return [];
const anchor = item.anchor.region;
const width = anchor.x1 - anchor.x0;
const height = anchor.y1 - anchor.y0;
return [{
id: item.anchor.anchor_id,
kind: 'order_anchor' as const,
@@ -122,12 +133,7 @@ export const buildOrderProfileReadonlyRegions = (
id: item.layout_id,
kind: 'order_field' as const,
label: item.field_code,
region: {
x0: anchor.x0 + item.value_region.x0 * width,
y0: anchor.y0 + item.value_region.y0 * height,
x1: anchor.x0 + item.value_region.x1 * width,
y1: anchor.y0 + item.value_region.y1 * height,
},
region: item.absolute_value_region,
fieldCode: item.field_code,
orderFieldId: item.layout_id,
valueMode: item.value_mode,