feat(shipping-notice): 新增通用解析能力,优化性能并清理遗留废弃代码
This commit is contained in:
1 parent
935bf26fa6
commit
7cfd5d167e
230 files changed
+9337
-10989
No files matched your search
+235
-62
@@ -29,6 +29,7 @@ import {
|
||||
enqueueOrderProfilePdfAutomark,
|
||||
generateOrderProfileOcrCoordinateEvidence,
|
||||
getOrderProfilePdfAutomarkJob,
|
||||
getOrderProfileSampleStatus,
|
||||
getOrderProfileSampleTables,
|
||||
listOrderProfileValidationRuns,
|
||||
listOrderProfileBoundSamples,
|
||||
@@ -55,6 +56,7 @@ import type {
|
||||
OrderFieldLayoutSuggestion,
|
||||
OrderProfileRowReconstructionMode,
|
||||
ShippingOrderDocumentProfile,
|
||||
OrderProfileSampleIntake,
|
||||
OrderProfileValidationRun,
|
||||
} from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
import {
|
||||
@@ -85,14 +87,18 @@ import {
|
||||
buildOrderProfileRecognitionResults,
|
||||
selectCurrentDatasetsValidationEvidence,
|
||||
groupUniqueOrderProfileLineFields,
|
||||
restoreFormalBindingFieldCodes,
|
||||
normalizeOrderProfileRelativeRegion,
|
||||
buildAutomarkSuggestedRegions,
|
||||
normalizeAutomarkFieldCandidates,
|
||||
preferredAutomarkTableSource,
|
||||
selectAutomarkReconstruction,
|
||||
summarizeAutomarkTableCandidates,
|
||||
toOrderProfileHeaderFieldRegion,
|
||||
resolveCoordinateFieldScope,
|
||||
isOrderProfileVisualFieldEligible,
|
||||
buildAutomarkSuggestionSummary,
|
||||
type AutomarkSuggestionContext,
|
||||
} from "./orderProfileForm.utils";
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -118,6 +124,8 @@ const samples = ref<
|
||||
const schemas = ref<ShippingOrderSchemaVersion[]>([]);
|
||||
const active = ref<ShippingOrderDocumentProfile | null>(null);
|
||||
const boundSamples = ref<OrderProfileBoundSample[]>([]);
|
||||
/** 自动标注前必须由服务端确认当前 annotation 样本的 Layout/主表/证据三项均已就绪。 */
|
||||
const automarkSampleReadiness = ref<OrderProfileSampleIntake | null>(null);
|
||||
/** 坐标 PDF 与 XFA 共用原 PDF + PDF.js 画布;PDFium 页图仅留给后端证据生成。 */
|
||||
const pdfPreviewGrant = ref<{ document_id: number; preview_token: string; expires_in_seconds: number } | null>(null);
|
||||
const pdfPageCount = ref(1);
|
||||
@@ -153,7 +161,14 @@ const headerSuggestions = ref<
|
||||
}>
|
||||
>([]);
|
||||
const orderFieldSuggestions = ref<OrderFieldLayoutSuggestion[]>([]);
|
||||
const pendingSuggestion = ref<{ id: string; checksum: string; summary: Record<string, unknown>; regions: OrderProfileCanvasRegion[] } | null>(null);
|
||||
/** 待确认候选冻结任务身份;翻页只能改变画布视图,不能改变接受请求的审计身份。 */
|
||||
const pendingSuggestion = ref<{
|
||||
id: string;
|
||||
checksum: string;
|
||||
context: AutomarkSuggestionContext;
|
||||
summary: Record<string, unknown>;
|
||||
regions: OrderProfileCanvasRegion[];
|
||||
} | null>(null);
|
||||
const automarkTableCandidates = ref<Array<{ source: string; reconstruction: import('@/features/admin/types/shipping-order-document-profile.types').CoordinateReconstructionSuggestion }>>([]);
|
||||
const automarkTableCandidateSummaries = ref<Array<{ source: string; rowCount: number; columnCount: number; conflictCodes: string[]; status: 'needs_review' }>>([]);
|
||||
const selectedAutomarkTableSource = ref('');
|
||||
@@ -175,6 +190,12 @@ const leaveConfirmOpen = ref(false);
|
||||
let resolveRouteLeave: ((allowed: boolean) => void) | null = null;
|
||||
const suggestingRegions = ref(false);
|
||||
const suggestionProgress = ref("");
|
||||
type AutomarkStage = 'idle' | 'checking' | 'queued' | 'analyzing' | 'building' | 'review' | 'failed' | 'complete';
|
||||
const automarkStage = ref<AutomarkStage>('idle');
|
||||
const automarkStagePercent: Record<AutomarkStage, number> = {
|
||||
idle: 0, checking: 15, queued: 30, analyzing: 55, building: 75, review: 100, failed: 100, complete: 100,
|
||||
};
|
||||
const automarkProgressPercent = computed(() => automarkStagePercent[automarkStage.value]);
|
||||
const creationKind = ref<OrderProfileCanvasRegion["kind"] | null>(null);
|
||||
const pendingDocumentAnchorLabel = ref<OrderProfileCanvasRegion | null>(null);
|
||||
const pendingOrderFieldAnchor = ref<OrderProfileCanvasRegion | null>(null);
|
||||
@@ -256,6 +277,10 @@ const xfaConfigReadonly = computed(() => (
|
||||
* XFA 后台仍可走 automark Job,但 UI 不再使用专用 OCR 底栏。
|
||||
*/
|
||||
async function onDeskCanvasSuggest(): Promise<void> {
|
||||
if (!automarkSampleReadiness.value?.automark_ready) {
|
||||
message.warning(automarkReadinessMessage(automarkSampleReadiness.value?.automark_reason_code));
|
||||
return;
|
||||
}
|
||||
void suggestRegions();
|
||||
}
|
||||
|
||||
@@ -592,10 +617,55 @@ const draftSaveAdapter = computed<OrderProfileDraftSaveAdapter>(() => (
|
||||
const deskCanvasDocumentReady = computed(() => visualCanvas.value.documentReady);
|
||||
const deskCanvasPreview = computed(() => visualCanvas.value.preview);
|
||||
const deskCanvasPreviewPagePath = computed(() => visualCanvas.value.previewPagePath);
|
||||
const deskCanvasRegions = computed(() => visualCanvas.value.regions);
|
||||
/**
|
||||
* 把待确认候选投影为只读预览层;正式 regions 始终保持不变,接受建议后才落盘。
|
||||
* 同 ID 的旧自动区域由候选替换,避免用户同时看到两套重叠框。
|
||||
*/
|
||||
const deskCanvasRegions = computed(() => {
|
||||
const current = visualCanvas.value.regions;
|
||||
const pending = pendingSuggestion.value;
|
||||
if (!pending) return current;
|
||||
const pendingIds = new Set(pending.regions.map((region) => region.id));
|
||||
const previewRegions = pending.regions
|
||||
.filter((region) => region.pageNo === pageNo.value)
|
||||
.map((region) => ({ ...region, isPreview: true }));
|
||||
return [
|
||||
...current.filter((region) => !pendingIds.has(region.id)),
|
||||
...previewRegions,
|
||||
];
|
||||
});
|
||||
const deskSelectedRegionId = computed(() => visualCanvas.value.selectedRegionId);
|
||||
const deskCreationKind = computed(() => visualCanvas.value.creationKind);
|
||||
const deskAutoSuggestDisabled = computed(() => visualCanvas.value.autoSuggestDisabled);
|
||||
const automarkReadinessMessage = (reasonCode?: string | null): string => {
|
||||
const keyByReason: Record<string, string> = {
|
||||
layout_not_ready: 'autoSuggestLayoutNotReady',
|
||||
main_table_missing: 'autoSuggestMainTableRequired',
|
||||
main_table_ambiguous: 'autoSuggestMainTableAmbiguous',
|
||||
layout_content_hash_mismatch: 'autoSuggestLayoutStale',
|
||||
layout_checksum_mismatch: 'autoSuggestLayoutStale',
|
||||
document_missing: 'autoSuggestSampleMissing',
|
||||
};
|
||||
return t(`admin.shippingOrderProfiles.workbench.${keyByReason[reasonCode || ''] || 'autoSuggestEvidencePending'}`);
|
||||
};
|
||||
/** 刷新当前 annotation 文档对应 Intake;服务端会在此处幂等补齐可安全冻结的证据。 */
|
||||
const refreshAutomarkSampleReadiness = async (): Promise<OrderProfileSampleIntake | null> => {
|
||||
const intakeNo = samples.value.find((item) => item.document_id === form.documentId)?.intake_no;
|
||||
if (!intakeNo) {
|
||||
automarkSampleReadiness.value = null;
|
||||
return null;
|
||||
}
|
||||
const status = await getOrderProfileSampleStatus(intakeNo);
|
||||
const currentProfileState = status.sample_readiness?.find(
|
||||
(item) => item.profile_id === active.value?.id && item.document_id === form.documentId,
|
||||
);
|
||||
automarkSampleReadiness.value = currentProfileState
|
||||
? { ...status, ...currentProfileState, sample_readiness: [currentProfileState] }
|
||||
: { ...status, automark_ready: false, automark_reason_code: 'document_missing' };
|
||||
return automarkSampleReadiness.value;
|
||||
};
|
||||
const deskAutoSuggestDisabled = computed(() => (
|
||||
visualCanvas.value.autoSuggestDisabled || !automarkSampleReadiness.value?.automark_ready
|
||||
));
|
||||
const deskPageNo = computed(() => visualCanvas.value.pageNo);
|
||||
const deskPageCount = computed(() => visualCanvas.value.pageCount);
|
||||
const deskSaveDisabled = computed(() => visualCanvas.value.saveDisabled);
|
||||
@@ -629,6 +699,15 @@ const onDeskRejectSuggestion = () => visualCanvas.value.rejectSuggestion();
|
||||
const deskPendingSuggestionCount = computed(() => (
|
||||
pendingSuggestion.value?.regions.length || 0
|
||||
));
|
||||
const pendingSuggestionPageNo = computed(() => pendingSuggestion.value?.context.pageNo || null);
|
||||
const pendingSuggestionIsOffCanvasPage = computed(() => (
|
||||
pendingSuggestionPageNo.value !== null && pendingSuggestionPageNo.value !== pageNo.value
|
||||
));
|
||||
/** 返回待确认候选的冻结页面;不限制管理员先浏览其他页面。 */
|
||||
const returnToPendingSuggestionPage = (): void => {
|
||||
const targetPageNo = pendingSuggestionPageNo.value;
|
||||
if (targetPageNo !== null) void selectPage(targetPageNo);
|
||||
};
|
||||
const hasAutomarkTableChoice = computed(() => automarkTableCandidates.value.length > 1);
|
||||
const automarkTableChoiceRequired = computed(() => hasAutomarkTableChoice.value && !selectedAutomarkTableSource.value);
|
||||
const automarkFieldChoiceRequired = computed(() => automarkFieldConflicts.value.some((item) => !selectedAutomarkFieldSources[item.field_id]));
|
||||
@@ -1595,6 +1674,8 @@ const save = async (automatic = false) => {
|
||||
autosaveFailures = 0;
|
||||
if (!automatic) message.success(t("admin.shippingOrderProfiles.updated"));
|
||||
profiles.value = profiles.value.map((item) => item.id === savedProfile.id ? savedProfile : item);
|
||||
// 保存主表后后端会冻结当前 Layout 身份;立即同步门禁,避免管理员必须重开编辑页。
|
||||
await refreshAutomarkSampleReadiness();
|
||||
await refreshOrderFieldSuggestionValues();
|
||||
if (localChangeVersion !== savingChangeVersion) scheduleAutosave();
|
||||
return true;
|
||||
@@ -1631,16 +1712,27 @@ const suggestRegions = async () => {
|
||||
if (suggestingRegions.value || !active.value) return;
|
||||
const { documentId, tableId, pageNo: targetPageNo } = deskAnnotationContext.value;
|
||||
if (!documentId) {
|
||||
automarkStage.value = 'failed';
|
||||
suggestionProgress.value = t("admin.shippingOrderProfiles.workbench.autoSuggestFailed");
|
||||
message.error(t("admin.shippingOrderProfiles.workbench.autoSuggestFailed"));
|
||||
return;
|
||||
}
|
||||
if (!tableId) return;
|
||||
suggestingRegions.value = true;
|
||||
automarkStage.value = 'checking';
|
||||
suggestionProgress.value = t(
|
||||
"admin.shippingOrderProfiles.workbench.autoSuggestCheckingCoordinates",
|
||||
);
|
||||
try {
|
||||
// 入队前使用当前服务端状态:它会幂等补齐样本证据,不能相信进入编辑页时的旧快照。
|
||||
const readiness = await refreshAutomarkSampleReadiness();
|
||||
if (!readiness?.automark_ready) {
|
||||
automarkStage.value = 'failed';
|
||||
suggestionProgress.value = automarkReadinessMessage(readiness?.automark_reason_code);
|
||||
message.warning(suggestionProgress.value);
|
||||
return;
|
||||
}
|
||||
automarkStage.value = 'queued';
|
||||
suggestionProgress.value = t("admin.shippingOrderProfiles.workbench.autoSuggestAnalyzing");
|
||||
const queued = await enqueueOrderProfilePdfAutomark(active.value.id, {
|
||||
document_id: documentId,
|
||||
@@ -1652,6 +1744,8 @@ const suggestRegions = async () => {
|
||||
let job;
|
||||
for (;;) {
|
||||
job = await getOrderProfilePdfAutomarkJob(active.value.id, queued.job_id);
|
||||
if (String(job.status) === 'queued') automarkStage.value = 'queued';
|
||||
else if (['running', 'pending'].includes(String(job.status || ''))) automarkStage.value = 'analyzing';
|
||||
if (!['queued', 'running', 'pending'].includes(String(job.status || ''))) break;
|
||||
await new Promise<void>((resolve) => { window.setTimeout(resolve, 500); });
|
||||
}
|
||||
@@ -1688,14 +1782,14 @@ const suggestRegions = async () => {
|
||||
.filter((item) => item.field_id && item.sources.length > 1)
|
||||
: [];
|
||||
for (const key of Object.keys(selectedAutomarkFieldSources)) delete selectedAutomarkFieldSources[key];
|
||||
selectedAutomarkTableSource.value = automarkTableCandidates.value.length === 1
|
||||
? automarkTableCandidates.value[0]!.source : '';
|
||||
selectedAutomarkTableSource.value = preferredAutomarkTableSource(automarkTableCandidates.value);
|
||||
// 新一轮自动标记不能沿用上一轮已确认来源;单一路候选仍保留其来源以便
|
||||
// 草稿版本可追溯,多路候选则必须等待用户选择。
|
||||
ensureTableRegionSetting(pageNo.value).visualEvidenceSource = selectedAutomarkTableSource.value
|
||||
ensureTableRegionSetting(targetPageNo).visualEvidenceSource = selectedAutomarkTableSource.value
|
||||
? selectedAutomarkTableSource.value as 'pdf_coordinate' | 'ocr_coordinate' | 'opencv_geometry' | 'acroform_widget_geometry'
|
||||
: null;
|
||||
if (visualCanvas.value.applyAutomarkCandidates(candidates)) {
|
||||
automarkStage.value = 'complete';
|
||||
suggestionProgress.value = candidates.length
|
||||
? t("admin.shippingOrderProfiles.workbench.autoSuggestComplete")
|
||||
: t("admin.shippingOrderProfiles.workbench.autoSuggestNoRows");
|
||||
@@ -1723,6 +1817,7 @@ const suggestRegions = async () => {
|
||||
const orderFields = { order_field_candidates: normalizeAutomarkFieldCandidates(selectedFieldCandidates) };
|
||||
orderFieldSuggestions.value = orderFields.order_field_candidates;
|
||||
if (!suggestion && !orderFields.order_field_candidates.length && !automarkFieldConflicts.value.length) {
|
||||
automarkStage.value = 'complete';
|
||||
suggestionProgress.value = t(
|
||||
"admin.shippingOrderProfiles.workbench.autoSuggestNoRows",
|
||||
);
|
||||
@@ -1731,26 +1826,32 @@ const suggestRegions = async () => {
|
||||
suggestionProgress.value = t(
|
||||
"admin.shippingOrderProfiles.workbench.autoSuggestApplying",
|
||||
);
|
||||
automarkStage.value = 'building';
|
||||
const suggestedRegions = buildAutomarkSuggestedRegions({
|
||||
reconstruction: suggestion,
|
||||
orderFieldCandidates: orderFields.order_field_candidates,
|
||||
pageNo: pageNo.value,
|
||||
pageNo: targetPageNo,
|
||||
unboundColumnLabel: (count) => t("admin.shippingOrderProfiles.workbench.unboundColumn", { count }),
|
||||
lineLabel: (count) => t("admin.shippingOrderProfiles.workbench.regionLabels.line", { count }),
|
||||
});
|
||||
const summary = {
|
||||
algorithm_version: 'coordinate-suggest-v1', kind: 'page_regions', page_no: pageNo.value,
|
||||
document_id: documentId, table_id: form.tableId, automark_job_id: job.job_id,
|
||||
region_count: suggestedRegions.length,
|
||||
region_kinds: suggestedRegions.map((item) => item.kind),
|
||||
evidence_source_required: hasParallelTableCandidates,
|
||||
selected_evidence_source: hasParallelTableCandidates ? null : (selectedAutomarkTableSource.value || null),
|
||||
selected_field_evidence_sources: { ...selectedAutomarkFieldSources },
|
||||
const context: AutomarkSuggestionContext = {
|
||||
documentId,
|
||||
tableId,
|
||||
pageNo: targetPageNo,
|
||||
automarkJobId: job.job_id,
|
||||
};
|
||||
const summary = buildAutomarkSuggestionSummary(context, {
|
||||
regionCount: suggestedRegions.length,
|
||||
regionKinds: suggestedRegions.map((item) => item.kind),
|
||||
evidenceSourceRequired: hasParallelTableCandidates,
|
||||
// 多来源仍要求人工接受;预选 PDF 只避免下拉框显示已选但摘要为空。
|
||||
selectedEvidenceSource: selectedAutomarkTableSource.value || null,
|
||||
selectedFieldEvidenceSources: { ...selectedAutomarkFieldSources },
|
||||
});
|
||||
const serialized = canonicalSuggestionJson(summary);
|
||||
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized));
|
||||
const checksum = Array.from(new Uint8Array(digest)).map((item) => item.toString(16).padStart(2, '0')).join('');
|
||||
pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, summary, regions: suggestedRegions };
|
||||
pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, context, summary, regions: suggestedRegions };
|
||||
message.success(
|
||||
t("admin.shippingOrderProfiles.workbench.suggestionReadyForDecision"),
|
||||
);
|
||||
@@ -1758,11 +1859,26 @@ const suggestRegions = async () => {
|
||||
suggestionProgress.value = hasParallelTableCandidates
|
||||
? t("admin.shippingOrderProfiles.workbench.autoSuggestMultiEvidenceReview")
|
||||
: t("admin.shippingOrderProfiles.workbench.autoSuggestComplete");
|
||||
automarkStage.value = hasParallelTableCandidates ? 'review' : 'complete';
|
||||
} catch (error) {
|
||||
suggestionProgress.value =
|
||||
error instanceof BusinessError
|
||||
? error.message
|
||||
: t("admin.shippingOrderProfiles.workbench.autoSuggestFailed");
|
||||
if (error instanceof BusinessError) {
|
||||
const reasonByCode: Record<string, string> = {
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_NOT_READY': 'layout_not_ready',
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_MAIN_TABLE_REQUIRED': 'main_table_missing',
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_MAIN_TABLE_AMBIGUOUS': 'main_table_ambiguous',
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE': 'layout_checksum_mismatch',
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND': 'document_missing',
|
||||
};
|
||||
const reason = reasonByCode[error.code];
|
||||
if (reason) {
|
||||
suggestionProgress.value = automarkReadinessMessage(reason);
|
||||
message.warning(suggestionProgress.value);
|
||||
return;
|
||||
}
|
||||
}
|
||||
suggestionProgress.value = error instanceof BusinessError
|
||||
? error.message : t("admin.shippingOrderProfiles.workbench.autoSuggestFailed");
|
||||
automarkStage.value = 'failed';
|
||||
fail(error);
|
||||
} finally {
|
||||
suggestingRegions.value = false;
|
||||
@@ -1772,28 +1888,31 @@ const suggestRegions = async () => {
|
||||
/** 用户选择 native/OCR 表格候选后,重新生成待确认建议并刷新其审计摘要。 */
|
||||
const chooseAutomarkTableSource = async (source: string) => {
|
||||
selectedAutomarkTableSource.value = source;
|
||||
ensureTableRegionSetting(pageNo.value).visualEvidenceSource = source as 'pdf_coordinate' | 'ocr_coordinate' | 'opencv_geometry' | 'acroform_widget_geometry';
|
||||
const pending = pendingSuggestion.value;
|
||||
if (!pending) return;
|
||||
ensureTableRegionSetting(pending.context.pageNo).visualEvidenceSource = source as 'pdf_coordinate' | 'ocr_coordinate' | 'opencv_geometry' | 'acroform_widget_geometry';
|
||||
const candidate = automarkTableCandidates.value.find((item) => item.source === source);
|
||||
if (!candidate || !pendingSuggestion.value) return;
|
||||
if (!candidate) return;
|
||||
const regions = buildAutomarkSuggestedRegions({
|
||||
reconstruction: candidate.reconstruction,
|
||||
orderFieldCandidates: orderFieldSuggestions.value,
|
||||
pageNo: pageNo.value,
|
||||
pageNo: pending.context.pageNo,
|
||||
unboundColumnLabel: (count) => t("admin.shippingOrderProfiles.workbench.unboundColumn", { count }),
|
||||
lineLabel: (count) => t("admin.shippingOrderProfiles.workbench.regionLabels.line", { count }),
|
||||
});
|
||||
const summary = { ...pendingSuggestion.value.summary, selected_evidence_source: source, region_count: regions.length, region_kinds: regions.map((item) => item.kind) };
|
||||
const summary = { ...pending.summary, selected_evidence_source: source, region_count: regions.length, region_kinds: regions.map((item) => item.kind) };
|
||||
const serialized = canonicalSuggestionJson(summary);
|
||||
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized));
|
||||
const checksum = Array.from(new Uint8Array(digest)).map((item) => item.toString(16).padStart(2, '0')).join('');
|
||||
pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, summary, regions };
|
||||
pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, context: pending.context, summary, regions };
|
||||
schedulePreview();
|
||||
};
|
||||
|
||||
/** 选择冲突字段的视觉来源;只将该来源的框加入待确认画布,不影响 XFA datasets 正式值源。 */
|
||||
const chooseAutomarkFieldSource = async (fieldId: string, source: string) => {
|
||||
selectedAutomarkFieldSources[fieldId] = source;
|
||||
if (!pendingSuggestion.value) return;
|
||||
const pending = pendingSuggestion.value;
|
||||
if (!pending) return;
|
||||
const selectedCandidates = automarkCandidates.value.filter((item) => {
|
||||
if (item.candidate_kind !== 'field_binding' || !item.binding || typeof item.binding !== 'object') return true;
|
||||
const currentFieldId = String((item.binding as Record<string, unknown>).field_id || '');
|
||||
@@ -1809,12 +1928,12 @@ const chooseAutomarkFieldSource = async (fieldId: string, source: string) => {
|
||||
const regions = buildAutomarkSuggestedRegions({
|
||||
reconstruction: selectedTable,
|
||||
orderFieldCandidates: orderFieldSuggestions.value,
|
||||
pageNo: pageNo.value,
|
||||
pageNo: pending.context.pageNo,
|
||||
unboundColumnLabel: (count) => t("admin.shippingOrderProfiles.workbench.unboundColumn", { count }),
|
||||
lineLabel: (count) => t("admin.shippingOrderProfiles.workbench.regionLabels.line", { count }),
|
||||
});
|
||||
const summary = {
|
||||
...pendingSuggestion.value.summary,
|
||||
...pending.summary,
|
||||
selected_field_evidence_sources: { ...selectedAutomarkFieldSources },
|
||||
region_count: regions.length,
|
||||
region_kinds: regions.map((item) => item.kind),
|
||||
@@ -1822,7 +1941,7 @@ const chooseAutomarkFieldSource = async (fieldId: string, source: string) => {
|
||||
const serialized = canonicalSuggestionJson(summary);
|
||||
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized));
|
||||
const checksum = Array.from(new Uint8Array(digest)).map((item) => item.toString(16).padStart(2, '0')).join('');
|
||||
pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, summary, regions };
|
||||
pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, context: pending.context, summary, regions };
|
||||
schedulePreview();
|
||||
};
|
||||
/**
|
||||
@@ -1859,6 +1978,9 @@ const decidePendingSuggestion = async (decision: 'accepted' | 'accepted_adjusted
|
||||
suggestionPages.has(region.pageNo) &&
|
||||
(region.id.startsWith(`header_${region.pageNo}_`) ||
|
||||
region.id.startsWith(`line_${region.pageNo}_`));
|
||||
const replaceableAutoRegionIds = new Set(
|
||||
regions.value.filter(isReplaceableAutoTableRegion).map((region) => region.id),
|
||||
);
|
||||
// A new suggestion is a complete table layout for its page. Replace its
|
||||
// previous generated header/line frames before appending it, otherwise a
|
||||
// changed suggestion ID leaves geometrically overlapping regions behind.
|
||||
@@ -1866,7 +1988,18 @@ const decidePendingSuggestion = async (decision: 'accepted' | 'accepted_adjusted
|
||||
(region) => !isReplaceableAutoTableRegion(region),
|
||||
);
|
||||
const existingIds = new Set(regions.value.map((region) => region.id));
|
||||
const acceptedRegions = item.regions.filter((region) => !existingIds.has(region.id)).map((region) => ({ ...region, fieldCode: decision === 'accepted_adjusted' && region.id === firstSuggestedField?.id ? replacementFieldCode : region.fieldCode }));
|
||||
const formalBindingLayoutIds = new Set(
|
||||
(valueAdapterDesk.definition?.bindings || [])
|
||||
.filter((binding) => Boolean(binding.value_binding?.path_id?.trim()))
|
||||
.map((binding) => String(binding.field_layout_id || '').trim()),
|
||||
);
|
||||
const acceptedRegions = restoreFormalBindingFieldCodes(
|
||||
regions.value,
|
||||
item.regions.filter((region) => (
|
||||
!existingIds.has(region.id) || replaceableAutoRegionIds.has(region.id)
|
||||
)),
|
||||
formalBindingLayoutIds,
|
||||
).map((region) => ({ ...region, fieldCode: decision === 'accepted_adjusted' && region.id === firstSuggestedField?.id ? replacementFieldCode : region.fieldCode }));
|
||||
const suggestedLines = acceptedRegions.filter((region) => region.kind === 'line');
|
||||
if (suggestedLines.length) {
|
||||
const fieldParentIds = new Set(
|
||||
@@ -1891,6 +2024,7 @@ const decidePendingSuggestion = async (decision: 'accepted' | 'accepted_adjusted
|
||||
selectedId.value = item.regions.find((region) => region.fieldCode)?.id || item.regions[0]?.id || null;
|
||||
}
|
||||
pendingSuggestion.value = null;
|
||||
automarkStage.value = decision === 'rejected' ? 'idle' : 'complete';
|
||||
suggestionAdjustmentField.value = '';
|
||||
} catch (error) { fail(error); }
|
||||
};
|
||||
@@ -2055,6 +2189,7 @@ const reprocessCurrentSampleLayout = async (): Promise<void> => {
|
||||
await reparseOrderProfileSampleLayout(form.documentId);
|
||||
message.success(t('admin.shippingOrderProfiles.blindTest.layoutReparseStarted'));
|
||||
await loadSampleTables();
|
||||
await refreshAutomarkSampleReadiness();
|
||||
await loadPages();
|
||||
await refreshOrderFieldSuggestionValues();
|
||||
} catch (error) {
|
||||
@@ -2443,6 +2578,7 @@ const edit = async (profile: ShippingOrderDocumentProfile) => {
|
||||
form.tableId = visualTableId;
|
||||
pageNo.value = sampleTables.value.find((item) => item.table_id === visualTableId)?.page_no || pageNo.value;
|
||||
}
|
||||
await refreshAutomarkSampleReadiness();
|
||||
await loadPages();
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
@@ -2568,6 +2704,7 @@ watch(
|
||||
canvasUnavailable.value = false;
|
||||
if (restoringProfile) return;
|
||||
void loadSampleTables();
|
||||
void refreshAutomarkSampleReadiness();
|
||||
if (active.value) void loadPages();
|
||||
},
|
||||
);
|
||||
@@ -2750,6 +2887,54 @@ onBeforeUnmount(() => {
|
||||
{{ t('admin.shippingOrderProfiles.blindTest.reprocessLayout') }}
|
||||
</button>
|
||||
</div>
|
||||
<section v-if="suggestingRegions || pendingSuggestion" class="automark-status-panel" role="status" aria-live="polite">
|
||||
<div class="automark-status-panel__heading">
|
||||
<div>
|
||||
<strong>{{ pendingSuggestion ? t('admin.shippingOrderProfiles.workbench.suggestionReadyForDecision') : t('admin.shippingOrderProfiles.workbench.autoSuggestRunning') }}</strong>
|
||||
<p>{{ suggestionProgress || t('admin.shippingOrderProfiles.workbench.autoSuggestCheckingCoordinates') }}</p>
|
||||
</div>
|
||||
<span class="automark-status-panel__count" v-if="pendingSuggestion">{{ pendingSuggestion.regions.length }} {{ t('admin.shippingOrderProfiles.workbench.suggestionPreviewBadge') }}</span>
|
||||
</div>
|
||||
<div class="automark-progress" role="progressbar" :aria-valuenow="automarkProgressPercent" aria-valuemin="0" aria-valuemax="100">
|
||||
<span :style="{ width: `${automarkProgressPercent}%` }" />
|
||||
</div>
|
||||
<div v-if="pendingSuggestion" class="automark-status-panel__body">
|
||||
<div v-if="pendingSuggestionIsOffCanvasPage" class="automark-candidate-page-notice" role="status">
|
||||
<span>{{ t('admin.shippingOrderProfiles.workbench.suggestionOnPage', { page: pendingSuggestionPageNo }) }}</span>
|
||||
<button type="button" class="btn-secondary" @click="returnToPendingSuggestionPage">{{ t('admin.shippingOrderProfiles.workbench.returnToSuggestionPage') }}</button>
|
||||
</div>
|
||||
<div v-if="hasAutomarkTableChoice" class="automark-choice-block">
|
||||
<label>
|
||||
{{ t('admin.shippingOrderProfiles.workbench.autoSuggestEvidenceSource') }}
|
||||
<select :value="selectedAutomarkTableSource" class="select-field" :disabled="saveState === 'readonly'" @change="(event) => void chooseAutomarkTableSource((event.target as HTMLSelectElement).value)">
|
||||
<option value="">{{ t('admin.shippingOrderProfiles.workbench.autoSuggestChooseEvidence') }}</option>
|
||||
<option v-for="candidate in automarkTableCandidates" :key="candidate.source" :value="candidate.source">{{ candidate.source }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<div class="suggestion-evidence-summary" aria-label="automark evidence summaries">
|
||||
<span v-for="summary in automarkTableCandidateSummaries" :key="summary.source" :class="{ 'is-conflict': summary.conflictCodes.length > 0 }">
|
||||
{{ t('admin.shippingOrderProfiles.workbench.autoSuggestCandidateSummary', { source: summary.source, rows: summary.rowCount, columns: summary.columnCount }) }}
|
||||
<em v-if="summary.conflictCodes.length > 0">{{ t('admin.shippingOrderProfiles.workbench.autoSuggestCandidateConflict') }}</em>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="automarkFieldConflicts.length > 0" class="automark-choice-block automark-choice-block--fields">
|
||||
<label v-for="conflict in automarkFieldConflicts" :key="conflict.field_id">
|
||||
{{ conflict.field_code || conflict.field_id }} · {{ t('admin.shippingOrderProfiles.workbench.autoSuggestEvidenceSource') }}
|
||||
<select :value="selectedAutomarkFieldSources[conflict.field_id] || ''" class="select-field" :disabled="saveState === 'readonly'" @change="(event) => void chooseAutomarkFieldSource(conflict.field_id, (event.target as HTMLSelectElement).value)">
|
||||
<option value="">{{ t('admin.shippingOrderProfiles.workbench.autoSuggestChooseEvidence') }}</option>
|
||||
<option v-for="source in conflict.sources" :key="source" :value="source">{{ source }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="automark-status-panel__actions">
|
||||
<select v-model="suggestionAdjustmentField" class="select-field" :disabled="saveState === 'readonly'" :aria-label="t('admin.shippingOrderProfiles.workbench.suggestionAdjustmentField')"><option value="">{{ t('admin.shippingOrderProfiles.workbench.suggestionAdjustmentField') }}</option><option v-for="field in lineFields" :key="field.field_code" :value="field.field_code">{{ field.display_name }} · {{ field.field_code }}</option></select>
|
||||
<button type="button" class="btn-primary" :disabled="saveState === 'readonly' || automarkTableChoiceRequired || automarkFieldChoiceRequired" @click="() => void decidePendingSuggestion('accepted')">{{ t('admin.shippingOrderProfiles.workbench.acceptSuggestion') }}</button>
|
||||
<button type="button" class="btn-secondary" :disabled="saveState === 'readonly' || !suggestionAdjustmentField" @click="() => void decidePendingSuggestion('accepted_adjusted')">{{ t('admin.shippingOrderProfiles.workbench.acceptAdjustedSuggestion') }}</button>
|
||||
<button type="button" class="btn-secondary" :disabled="saveState === 'readonly'" @click="() => void decidePendingSuggestion('rejected')">{{ t('admin.shippingOrderProfiles.workbench.rejectSuggestion') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<OrderProfileDocumentCanvas
|
||||
v-if="deskCanvasCanRender"
|
||||
ref="documentCanvas"
|
||||
@@ -2795,36 +2980,6 @@ onBeforeUnmount(() => {
|
||||
@load-failed="onDeskCanvasLoadFailed"
|
||||
@retry="onDeskCanvasRetry"
|
||||
/>
|
||||
<section v-if="pendingSuggestion" class="suggestion-decision" role="status">
|
||||
<strong>{{ t('admin.shippingOrderProfiles.workbench.suggestionReadyForDecision') }}</strong>
|
||||
<span>{{ pendingSuggestion.regions.length }}</span>
|
||||
<template v-if="hasAutomarkTableChoice">
|
||||
<label>
|
||||
{{ t('admin.shippingOrderProfiles.workbench.autoSuggestEvidenceSource') }}
|
||||
<select :value="selectedAutomarkTableSource" class="select-field" :disabled="saveState === 'readonly'" @change="(event) => void chooseAutomarkTableSource((event.target as HTMLSelectElement).value)">
|
||||
<option value="">{{ t('admin.shippingOrderProfiles.workbench.autoSuggestChooseEvidence') }}</option>
|
||||
<option v-for="candidate in automarkTableCandidates" :key="candidate.source" :value="candidate.source">{{ candidate.source }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<div class="suggestion-evidence-summary" aria-label="automark evidence summaries">
|
||||
<span v-for="summary in automarkTableCandidateSummaries" :key="summary.source" :class="{ 'is-conflict': summary.conflictCodes.length > 0 }">
|
||||
{{ t('admin.shippingOrderProfiles.workbench.autoSuggestCandidateSummary', { source: summary.source, rows: summary.rowCount, columns: summary.columnCount }) }}
|
||||
<em v-if="summary.conflictCodes.length > 0">{{ t('admin.shippingOrderProfiles.workbench.autoSuggestCandidateConflict') }}</em>
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
<template v-if="automarkFieldConflicts.length > 0">
|
||||
<label v-for="conflict in automarkFieldConflicts" :key="conflict.field_id">
|
||||
{{ conflict.field_code || conflict.field_id }} · {{ t('admin.shippingOrderProfiles.workbench.autoSuggestEvidenceSource') }}
|
||||
<select :value="selectedAutomarkFieldSources[conflict.field_id] || ''" class="select-field" :disabled="saveState === 'readonly'" @change="(event) => void chooseAutomarkFieldSource(conflict.field_id, (event.target as HTMLSelectElement).value)">
|
||||
<option value="">{{ t('admin.shippingOrderProfiles.workbench.autoSuggestChooseEvidence') }}</option>
|
||||
<option v-for="source in conflict.sources" :key="source" :value="source">{{ source }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</template>
|
||||
<select v-model="suggestionAdjustmentField" class="select-field" :disabled="saveState === 'readonly'" :aria-label="t('admin.shippingOrderProfiles.workbench.suggestionAdjustmentField')"><option value="">{{ t('admin.shippingOrderProfiles.workbench.suggestionAdjustmentField') }}</option><option v-for="field in lineFields" :key="field.field_code" :value="field.field_code">{{ field.display_name }} · {{ field.field_code }}</option></select>
|
||||
<button type="button" :disabled="saveState === 'readonly'" @click="() => void decidePendingSuggestion('accepted_adjusted')">{{ t('admin.shippingOrderProfiles.workbench.acceptAdjustedSuggestion') }}</button>
|
||||
</section>
|
||||
</template>
|
||||
</main>
|
||||
|
||||
@@ -3791,8 +3946,26 @@ onBeforeUnmount(() => {
|
||||
.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; }
|
||||
.automark-status-panel { position: sticky; top: .5rem; z-index: 6; display: grid; gap: .65rem; margin: 0 0 .75rem; border: 1px solid #7dd3fc; border-radius: .45rem; background: #f0f9ff; padding: .75rem .9rem; color: #164e63; box-shadow: 0 8px 20px rgb(14 116 144 / .12); }
|
||||
.automark-status-panel__heading { display: flex; align-items: flex-start; justify-content: space-between; gap: .75rem; }
|
||||
.automark-status-panel__heading strong { display: block; color: #0c4a6e; font-size: .82rem; }
|
||||
.automark-status-panel__heading p { margin: .2rem 0 0; color: #475569; font-size: .75rem; }
|
||||
.automark-status-panel__count { flex: 0 0 auto; border-radius: 999px; background: #bae6fd; padding: .2rem .5rem; font-size: .7rem; font-weight: 700; }
|
||||
.automark-progress { height: .35rem; overflow: hidden; border-radius: 999px; background: #dbeafe; }
|
||||
.automark-progress span { display: block; height: 100%; border-radius: inherit; background: #0284c7; transition: width .25s ease; }
|
||||
.automark-status-panel__body { display: grid; gap: .6rem; }
|
||||
.automark-candidate-page-notice { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .45rem; border: 1px solid #bae6fd; border-radius: .35rem; background: #fff; padding: .45rem .55rem; color: #0c4a6e; font-size: .75rem; }
|
||||
.automark-choice-block { display: grid; gap: .45rem; }
|
||||
.automark-choice-block label { display: flex; flex-wrap: wrap; align-items: center; gap: .45rem; color: #334155; font-size: .74rem; font-weight: 700; }
|
||||
.automark-choice-block--fields { grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr)); }
|
||||
.automark-status-panel__actions { display: flex; flex-wrap: wrap; align-items: center; gap: .45rem; }
|
||||
.automark-status-panel__actions .select-field { min-width: 12rem; }
|
||||
@media (max-width: 640px) {
|
||||
.automark-status-panel { top: 0; }
|
||||
.automark-status-panel__actions { align-items: stretch; }
|
||||
.automark-status-panel__actions > * { flex: 1 1 100%; }
|
||||
.automark-status-panel__actions .select-field { min-width: 0; }
|
||||
}
|
||||
.suggestion-evidence-summary { display: flex; flex-wrap: wrap; gap: .35rem; width: 100%; font-size: .72rem; }
|
||||
.suggestion-evidence-summary span { background: #e0f2fe; color: #075985; }
|
||||
.suggestion-evidence-summary span.is-conflict { background: #fee2e2; color: #991b1b; }
|
||||
|
||||
+8
-6
@@ -215,7 +215,7 @@ const move = (event: PointerEvent) => {
|
||||
const beginDrag = (event: PointerEvent, region: OrderProfileCanvasRegion, mode: DragMode) => {
|
||||
event.preventDefault();
|
||||
emit('select', region.id);
|
||||
if (readonlyMode.value) return;
|
||||
if (readonlyMode.value || region.isPreview) return;
|
||||
emit('start', region.id);
|
||||
activeDrag = { id: region.id, mode, startX: event.clientX, startY: event.clientY, region: { ...region.region } };
|
||||
window.addEventListener('pointermove', move);
|
||||
@@ -330,8 +330,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
<template v-if="pendingSuggestionCount">
|
||||
<span class="toolbar-divider" aria-hidden="true" />
|
||||
<span class="suggestion-count">{{ pendingSuggestionCount }}</span>
|
||||
<button type="button" class="suggestion-action" @click="emit('acceptSuggestion')">{{ t('admin.shippingOrderProfiles.workbench.acceptSuggestion') }}</button>
|
||||
<button type="button" class="suggestion-action suggestion-action--reject" @click="emit('rejectSuggestion')">{{ t('admin.shippingOrderProfiles.workbench.rejectSuggestion') }}</button>
|
||||
<span class="suggestion-preview-badge">{{ t('admin.shippingOrderProfiles.workbench.suggestionPreviewBadge') }}</span>
|
||||
</template>
|
||||
</template>
|
||||
<span v-else class="readonly-badge">{{ t('admin.shippingOrderProfiles.versionCenter.readonlyCanvasBadge') }}</span>
|
||||
@@ -386,7 +385,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
role="button"
|
||||
tabindex="0"
|
||||
class="region"
|
||||
:class="[`region-${region.kind}`, { selected: selected.has(region.id) }, region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '']"
|
||||
:class="[`region-${region.kind}`, { selected: selected.has(region.id), 'region-preview': region.isPreview }, region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '']"
|
||||
:style="{ left: `${region.region.x0 * 100}%`, top: `${region.region.y0 * 100}%`, width: `${(region.region.x1 - region.region.x0) * 100}%`, height: `${(region.region.y1 - region.region.y0) * 100}%` }"
|
||||
:aria-label="displayRegionLabel(region)"
|
||||
@pointerdown.stop="beginDrag($event, region, 'move')"
|
||||
@@ -394,10 +393,10 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
@keydown.space.prevent="emit('select', region.id)"
|
||||
>
|
||||
<span class="region-label" :title="displayRegionLabel(region)" @pointerdown.stop="beginDrag($event, region, 'move')">{{ displayRegionLabel(region) }}</span>
|
||||
<template v-if="region.kind === 'line' && !readonlyMode">
|
||||
<template v-if="region.kind === 'line' && !readonlyMode && !region.isPreview">
|
||||
<span v-for="edge in ['n', 'e', 's', 'w']" :key="edge" class="line-hit-edge" :class="`line-hit-${edge}`" @pointerdown.stop="beginDrag($event, region, 'move')" />
|
||||
</template>
|
||||
<button v-if="!readonlyMode" v-for="handle in ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'] as ResizeHandle[]" :key="handle" type="button" class="resize-handle" :class="`handle-${handle}`" :aria-label="t('admin.shippingOrderProfiles.workbench.resizeHandle', { direction: handle })" @pointerdown.stop="beginDrag($event, region, handle)" />
|
||||
<button v-if="!readonlyMode && !region.isPreview" v-for="handle in ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'] as ResizeHandle[]" :key="handle" type="button" class="resize-handle" :class="`handle-${handle}`" :aria-label="t('admin.shippingOrderProfiles.workbench.resizeHandle', { direction: handle })" @pointerdown.stop="beginDrag($event, region, handle)" />
|
||||
</div>
|
||||
<div v-if="creationRegion" class="creation-region" :style="{ left: `${creationRegion.x0 * 100}%`, top: `${creationRegion.y0 * 100}%`, width: `${(creationRegion.x1 - creationRegion.x0) * 100}%`, height: `${(creationRegion.y1 - creationRegion.y0) * 100}%` }" />
|
||||
</div>
|
||||
@@ -462,6 +461,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
.annotation-tools button:disabled { cursor: not-allowed; opacity: .45; }
|
||||
.suggestion-progress { margin: .1rem; color: #bae6fd; font-size: .66rem; line-height: 1.35; }
|
||||
.suggestion-progress.failed { color: #fca5a5; }
|
||||
.suggestion-preview-badge { color: #fbbf24; font-size: .68rem; }
|
||||
.region { position: absolute; box-sizing: border-box; z-index: 2; border: 2px solid #38bdf8; background: rgb(14 165 233 / .10); color: #e0f2fe; cursor: move; text-align: left; touch-action: none; }
|
||||
.region:focus-visible { outline: 3px solid white; outline-offset: 2px; }
|
||||
.region-label { position: absolute; top: -1.65rem; left: -2px; max-width: min(18rem, 100%); overflow: hidden; border: 1px solid rgb(255 255 255 / .7); border-radius: .25rem .25rem 0 0; background: #0369a1; padding: .2rem .45rem; color: white; font: 700 .7rem/1.15 ui-monospace, SFMono-Regular, Menlo, monospace; text-overflow: ellipsis; white-space: nowrap; }
|
||||
@@ -505,6 +505,8 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
.region:not(.selected) .resize-handle { display: none; }
|
||||
.region.selected { outline: 3px solid white; outline-offset: 2px; }
|
||||
.region.selected:not(.region-line) { z-index: 4; }
|
||||
.region-preview { z-index: 5; border-style: dashed; border-width: 2px; border-color: #fbbf24; background: rgb(245 158 11 / .18); color: #fef3c7; cursor: default; pointer-events: auto; }
|
||||
.region-preview .region-label { background: #a16207; }
|
||||
.canvas-stage.drawing .region { pointer-events: none; }
|
||||
@media (max-width: 900px) {
|
||||
.canvas-shell { height: auto; min-height: 36rem; }
|
||||
|
||||
+59
@@ -16,16 +16,53 @@ import {
|
||||
selectCurrentDatasetsValidationEvidence,
|
||||
normalizeOrderProfileRelativeRegion,
|
||||
groupUniqueOrderProfileLineFields,
|
||||
restoreFormalBindingFieldCodes,
|
||||
buildAutomarkSuggestedRegions,
|
||||
normalizeAutomarkFieldCandidates,
|
||||
preferredAutomarkTableSource,
|
||||
selectAutomarkReconstruction,
|
||||
summarizeAutomarkTableCandidates,
|
||||
toOrderProfileHeaderFieldRegion,
|
||||
resolveCoordinateFieldScope,
|
||||
isOrderProfileVisualFieldEligible,
|
||||
buildAutomarkSuggestionSummary,
|
||||
} from './orderProfileForm.utils';
|
||||
|
||||
describe('order profile form rules', () => {
|
||||
it('keeps an automark suggestion audit identity frozen after the canvas page changes', () => {
|
||||
const frozenContext = {
|
||||
documentId: 285,
|
||||
tableId: 'mineru-table-84a701e5693e0907',
|
||||
pageNo: 1,
|
||||
automarkJobId: 7267,
|
||||
};
|
||||
|
||||
const summary = buildAutomarkSuggestionSummary(frozenContext, {
|
||||
regionCount: 3,
|
||||
regionKinds: ['line', 'field', 'field'],
|
||||
evidenceSourceRequired: false,
|
||||
selectedEvidenceSource: 'pdf_coordinate',
|
||||
selectedFieldEvidenceSources: {},
|
||||
});
|
||||
|
||||
// 翻页会更新当前画布状态,但接受建议必须仍携带入队时冻结的 Job 身份。
|
||||
expect(summary).toMatchObject({
|
||||
document_id: 285,
|
||||
table_id: 'mineru-table-84a701e5693e0907',
|
||||
page_no: 1,
|
||||
automark_job_id: 7267,
|
||||
});
|
||||
});
|
||||
|
||||
it('preselects native PDF evidence while allowing OCR fallback', () => {
|
||||
// 关键断言:PDF 只是默认建议;候选列表仍保留 OCR,供人工切换复核。
|
||||
expect(preferredAutomarkTableSource([
|
||||
{ source: 'ocr_coordinate' }, { source: 'pdf_coordinate' },
|
||||
])).toBe('pdf_coordinate');
|
||||
expect(preferredAutomarkTableSource([{ source: 'ocr_coordinate' }])).toBe('ocr_coordinate');
|
||||
expect(preferredAutomarkTableSource([])).toBe('');
|
||||
});
|
||||
|
||||
it('keeps datasets-only Schema fields available for XFA visual positioning only', () => {
|
||||
const datasetsOnly = { enabled: true, allowed_sources: ['xfa_dataset'] };
|
||||
|
||||
@@ -372,6 +409,28 @@ describe('order profile form rules', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('restores a formal datasets field only for the same automark line and column', () => {
|
||||
const existing = [{
|
||||
id: 'line_1_1-field-2', kind: 'field' as const, parentId: 'line_1_1',
|
||||
fieldCode: 'qty', label: 'qty', pageNo: 1,
|
||||
region: { x0: .3, y0: .3, x1: .4, y1: .4 },
|
||||
}];
|
||||
const suggested = [{
|
||||
id: 'line_1_1-field-2', kind: 'field' as const, parentId: 'line_1_1',
|
||||
fieldCode: null, label: 'Unbound 2', pageNo: 1,
|
||||
region: { x0: .3, y0: .3, x1: .4, y1: .4 },
|
||||
}, {
|
||||
id: 'line_1_1-field-3', kind: 'field' as const, parentId: 'line_1_1',
|
||||
fieldCode: null, label: 'Unbound 3', pageNo: 1,
|
||||
region: { x0: .4, y0: .3, x1: .5, y1: .4 },
|
||||
}];
|
||||
|
||||
const restored = restoreFormalBindingFieldCodes(existing, suggested, new Set(['line_1_1:qty']));
|
||||
|
||||
// 关键断言:同一稳定区域才可恢复字段身份,新增列仍保持待人工绑定。
|
||||
expect(restored.map((region) => region.fieldCode)).toEqual(['qty', null]);
|
||||
});
|
||||
|
||||
it('preserves the backend evidence source when projecting automark field candidates', () => {
|
||||
const candidates = normalizeAutomarkFieldCandidates([{
|
||||
candidate_kind: 'field_binding',
|
||||
|
||||
+79
@@ -112,6 +112,33 @@ export const groupUniqueOrderProfileLineFields = (
|
||||
return { fieldsByLayout, boundRegionIds };
|
||||
};
|
||||
|
||||
/**
|
||||
* 在接受新自动标注前恢复已有 XFA 正式绑定的共同视觉字段身份。
|
||||
* 核心逻辑:只允许同一行布局、同一自动列序号的候选继承字段码;缺少该严格对应关系时
|
||||
* 保持未绑定,避免把 datasets 正式路径错误迁移到另一列。
|
||||
* @param existingRegions - 当前已保存或待保存的画布区域。
|
||||
* @param suggestedRegions - 当前待接受的自动标注区域。
|
||||
* @param formalBindingLayoutIds - 已存在正式 datasets binding 的 field_layout_id 集合。
|
||||
* @returns 仅补回可严格证明身份的候选字段码。
|
||||
*/
|
||||
export const restoreFormalBindingFieldCodes = (
|
||||
existingRegions: OrderProfileCanvasRegion[],
|
||||
suggestedRegions: OrderProfileCanvasRegion[],
|
||||
formalBindingLayoutIds: ReadonlySet<string>,
|
||||
): OrderProfileCanvasRegion[] => {
|
||||
const fieldCodeByRegionId = new Map<string, string>();
|
||||
for (const region of existingRegions) {
|
||||
if (region.kind !== 'field' || !region.parentId || !region.fieldCode) continue;
|
||||
const layoutId = `${region.parentId}:${region.fieldCode}`;
|
||||
if (formalBindingLayoutIds.has(layoutId)) fieldCodeByRegionId.set(region.id, region.fieldCode);
|
||||
}
|
||||
return suggestedRegions.map((region) => {
|
||||
if (region.kind !== 'field' || region.fieldCode) return region;
|
||||
const fieldCode = fieldCodeByRegionId.get(region.id);
|
||||
return fieldCode ? { ...region, fieldCode } : region;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 将画布或历史草稿的区域限制为页面归一化坐标。
|
||||
* @param region - 可能来自拖拽、自动建议或历史模板的页面区域。
|
||||
@@ -129,6 +156,45 @@ export const normalizeOrderProfileRelativeRegion = (
|
||||
return x0 < x1 && y0 < y1 ? { x0, y0, x1, y1 } : null;
|
||||
};
|
||||
|
||||
/** 自动标注任务启动时冻结的样本身份;候选在跨页浏览期间不得重新读取可变画布状态。 */
|
||||
export interface AutomarkSuggestionContext {
|
||||
documentId: number;
|
||||
tableId: string;
|
||||
pageNo: number;
|
||||
automarkJobId: number | string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造待确认自动标注的审计摘要。
|
||||
* 核心逻辑:Job 已按 document/table/page 冻结证据身份;摘要必须复用同一身份,
|
||||
* 防止管理员翻页或切换表格后,接受请求被服务端判定为另一份 Job 的候选。
|
||||
* @param context - 自动标注入队并成功完成后冻结的样本、页面和 Job 身份。
|
||||
* @param details - 可随管理员选择证据来源而更新的候选描述。
|
||||
* @returns 后端 suggestion decision 契约所需的完整且稳定摘要。
|
||||
*/
|
||||
export const buildAutomarkSuggestionSummary = (
|
||||
context: AutomarkSuggestionContext,
|
||||
details: {
|
||||
regionCount: number;
|
||||
regionKinds: string[];
|
||||
evidenceSourceRequired: boolean;
|
||||
selectedEvidenceSource: string | null;
|
||||
selectedFieldEvidenceSources: Record<string, string>;
|
||||
},
|
||||
): Record<string, unknown> => ({
|
||||
algorithm_version: 'coordinate-suggest-v1',
|
||||
kind: 'page_regions',
|
||||
page_no: context.pageNo,
|
||||
document_id: context.documentId,
|
||||
table_id: context.tableId,
|
||||
automark_job_id: context.automarkJobId,
|
||||
region_count: details.regionCount,
|
||||
region_kinds: details.regionKinds,
|
||||
evidence_source_required: details.evidenceSourceRequired,
|
||||
selected_evidence_source: details.selectedEvidenceSource,
|
||||
selected_field_evidence_sources: details.selectedFieldEvidenceSources,
|
||||
});
|
||||
|
||||
/**
|
||||
* 将统一自动标记结果投影为画布区域。
|
||||
* 核心逻辑:字段视觉候选与行重建是并行证据;行重建缺失时仍保留抬头字段框供人工复核,
|
||||
@@ -273,6 +339,19 @@ export const summarizeAutomarkTableCandidates = (
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 为多来源自动标注候选提供可审阅的默认来源。
|
||||
* 原生 PDF 坐标是首选建议,但这只是预选,不绕过人工接受和 Review 门禁;
|
||||
* 没有原生候选时才使用候选列表中的第一来源。
|
||||
*/
|
||||
export const preferredAutomarkTableSource = (
|
||||
candidates: Array<{ source: string }>,
|
||||
): string => (
|
||||
candidates.find((candidate) => candidate.source === 'pdf_coordinate')?.source
|
||||
|| candidates[0]?.source
|
||||
|| ''
|
||||
);
|
||||
|
||||
/**
|
||||
* 将后端统一 field_binding DTO 转为旧页面候选形状,并保留真实证据来源。
|
||||
* 核心逻辑:只接受视觉 binding;evidence_sources 为空时按不可确认处理,禁止默认宣称 native。
|
||||
|
||||
Reference in new issue
Block a user