feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置 新增收料报表管理的前端页面、路由和侧边栏入口 新增后端收料报表配置接口、数据库模型和RPA脚本 优化发货通知流程的重试策略,将shipping相关job默认不自动重试 移除废弃的库存源确认相关逻辑,更新流程门禁规则 重构订单模板的值适配器模块,新增坐标OCR值适配器 清理前端shipping菜单和action的废弃选项 更新相关文档和测试用例,调整.gitignore忽略规则
This commit is contained in:
1 parent
260465b72d
commit
1b6483a4ea
466 files changed
+32115
-33796
No files matched your search
@@ -319,6 +319,14 @@ export const saveShippingInventorySource = (payload: Record<string, unknown>, id
|
||||
`/api/admin/shipping-notice/sources${id ? `/${id}` : ''}`,
|
||||
{ method: id ? 'PUT' : 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
/** 读取/保存站点独立收料配置;严禁通过库存站点保存接口夹带这些字段。 */
|
||||
export const getShippingReceiptReportConfig = (sourceId: number) => requestJson<Record<string, unknown> | null>(
|
||||
`/api/admin/shipping-notice/sources/${sourceId}/receipt-report-config`, auth(),
|
||||
);
|
||||
export const saveShippingReceiptReportConfig = (sourceId: number, payload: Record<string, unknown>) => requestJson<Record<string, unknown>>(
|
||||
`/api/admin/shipping-notice/sources/${sourceId}/receipt-report-config`,
|
||||
{ method: 'PUT', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
/** 直接绑定停用库存站点到已发布解析方案;服务端自动写入操作审计。 */
|
||||
export const bindShippingInventorySourceParsingProfile = (id: number, payload: { parsing_profile_id: number }) => requestJson<unknown>(
|
||||
`/api/admin/shipping-notice/sources/${id}/bind-parsing-profile`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
|
||||
@@ -249,14 +249,12 @@ export const generateOrderProfileOcrCoordinateEvidence = (documentId: number, ta
|
||||
},
|
||||
);
|
||||
|
||||
/** 三步向导的唯一落库动作:原子创建草稿、主样本、Revision 和编辑租约。 */
|
||||
/** 三步向导只冻结统一视觉主表;XFA datasets 集合与镜像在编辑阶段另行保存。 */
|
||||
export const completeOrderDocumentProfileWizard = (payload: {
|
||||
display_name: string;
|
||||
schema_version_id: number;
|
||||
document_id: number;
|
||||
main_table_id?: string;
|
||||
authoritative_collection_path_id?: string;
|
||||
mirror_collection_path_ids?: string[];
|
||||
main_table_id: string;
|
||||
browser_session_id: string;
|
||||
operation_id: string;
|
||||
}) => requestJson<ShippingOrderDocumentProfile & {
|
||||
@@ -269,14 +267,14 @@ export const completeOrderDocumentProfileWizard = (payload: {
|
||||
/** 读取样本文档 XFA 字段树(脱敏值,不含明文路径)。 */
|
||||
export const getOrderProfileSampleXfaFieldTree = (documentId: number) =>
|
||||
requestJson<import('../types/shipping-order-document-profile.types').XfaFieldTreeResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/field-tree`,
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/value-adapter/field-tree`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 读取 XFA 明细集合候选。 */
|
||||
export const getOrderProfileSampleXfaCollections = (documentId: number) =>
|
||||
requestJson<import('../types/shipping-order-document-profile.types').XfaCollectionsResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/collections`,
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/value-adapter/collections`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
@@ -287,34 +285,10 @@ export const previewOrderProfileSampleXfaValue = (
|
||||
options?: { reveal?: boolean },
|
||||
) =>
|
||||
requestJson<import('../types/shipping-order-document-profile.types').XfaValuePreviewResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/value-preview`,
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/value-adapter/value-preview`,
|
||||
{ method: 'POST', body: JSON.stringify({ path_id: pathId, reveal: Boolean(options?.reveal) }), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 生成或复用绑定冻结 Analysis 的 XFA 合成预览(身份 + 页元数据,不含大图)。 */
|
||||
export const requestOrderProfileSampleXfaSyntheticPreview = (
|
||||
documentId: number,
|
||||
options?: { force?: boolean },
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaSyntheticPreviewResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/preview`,
|
||||
{ method: 'POST', body: JSON.stringify({ force: Boolean(options?.force) }), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 列出最新 ready 合成预览页并重新签发短时 token。 */
|
||||
export const listOrderProfileSampleXfaSyntheticPreviewPages = (documentId: number) =>
|
||||
requestJson<import('../types/shipping-order-document-profile.types').XfaSyntheticPreviewResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/preview/pages`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/**
|
||||
* 合成预览单页 PNG 的受控路径(配合 preview_token 用 fetch 拉取 blob)。
|
||||
* @param documentId 样本文档 ID
|
||||
* @param pageNo 1-based 页码
|
||||
*/
|
||||
export const orderProfileSampleXfaSyntheticPreviewPagePath = (documentId: number, pageNo: number) =>
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/preview/pages/${pageNo}`;
|
||||
|
||||
/** 入队统一 PDF 自动标记;服务端按 Profile 能力选择坐标或 XFA 多源证据。 */
|
||||
export const enqueueOrderProfilePdfAutomark = (
|
||||
profileId: number,
|
||||
@@ -329,7 +303,7 @@ export const getOrderProfilePdfAutomarkJob = (profileId: number, jobId: number)
|
||||
requestJson<{
|
||||
job_id: number;
|
||||
status: string;
|
||||
kind?: 'coordinate_regions' | 'visual_binding' | null;
|
||||
kind?: 'field_binding_candidates' | null;
|
||||
candidates?: Array<Record<string, unknown>>;
|
||||
diagnostics?: Record<string, unknown>;
|
||||
preview_render_checksum?: string | null;
|
||||
@@ -341,60 +315,12 @@ export const getOrderProfilePdfAutomarkJob = (profileId: number, jobId: number)
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 入队 XFA OCR 自动标记 Job(须合成预览 ready)。 */
|
||||
export const enqueueOrderProfileXfaOcrAutomark = (
|
||||
profileId: number,
|
||||
payload: { document_id: number; force?: boolean },
|
||||
) => requestJson<{ job_id: number; status: string; preview_render_checksum?: string }>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/automark`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 轮询 OCR 自动标记 Job 状态与建议。 */
|
||||
export const getOrderProfileXfaOcrAutomarkJob = (profileId: number, jobId: number) =>
|
||||
requestJson<{
|
||||
job_id: number;
|
||||
status: string;
|
||||
suggestions?: Array<Record<string, unknown>>;
|
||||
error_code?: string | null;
|
||||
preview_render_checksum?: string | null;
|
||||
}>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/automark/jobs/${jobId}`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 接受自动标记建议(high→confirmed;medium/low→suggested)。 */
|
||||
export const acceptOrderProfileXfaOcrAutomarkSuggestion = (
|
||||
profileId: number,
|
||||
suggestionId: string,
|
||||
payload: {
|
||||
job_id?: number;
|
||||
preview_render_checksum: string;
|
||||
render_mode?: string;
|
||||
browser_session_id?: string;
|
||||
lease_token?: string;
|
||||
},
|
||||
) => requestJson<Record<string, unknown>>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/automark/suggestions/${encodeURIComponent(suggestionId)}/accept`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 拒绝自动标记建议。 */
|
||||
export const rejectOrderProfileXfaOcrAutomarkSuggestion = (
|
||||
profileId: number,
|
||||
suggestionId: string,
|
||||
payload?: { job_id?: number; browser_session_id?: string; lease_token?: string },
|
||||
) => requestJson<Record<string, unknown>>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/automark/suggestions/${encodeURIComponent(suggestionId)}/reject`,
|
||||
{ method: 'POST', body: JSON.stringify(payload || {}), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 预览拆分规则并签发确认令牌;默认脱敏,reveal 需敏感读权限。 */
|
||||
export const previewOrderProfileSampleXfaSplitRules = (
|
||||
documentId: number,
|
||||
payload: { path_id: string; rule_set: Record<string, unknown>; profile_id?: number; reveal?: boolean },
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaSplitRulesPreviewResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/split-rules/preview`,
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/value-adapter/split-rules/preview`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
@@ -403,7 +329,7 @@ export const validateOrderProfileXfaSplitRules = (
|
||||
profileId: number,
|
||||
payload: { split_rules?: import('../types/shipping-order-document-profile.types').XfaSplitRuleSet[] },
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaSplitRulesValidateResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/split-rules/validate`,
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/value-adapter/split-rules/validate`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
@@ -412,69 +338,7 @@ export const suggestOrderProfileXfaSplitRules = (
|
||||
profileId: number,
|
||||
payload: { document_id: number; path_id?: string | null },
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaSplitRulesSuggestResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/split-rules/suggest`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 统一返回视觉 + 拆分规则建议;不写 Draft。 */
|
||||
export const suggestOrderProfileXfaUnifiedMapping = (
|
||||
profileId: number,
|
||||
payload: {
|
||||
document_id: number;
|
||||
page_no: number;
|
||||
normalized_bbox: import('../types/shipping-order-document-profile.types').XfaNormalizedBBox;
|
||||
path_id?: string | null;
|
||||
include_visual?: boolean;
|
||||
include_split?: boolean;
|
||||
},
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaUnifiedMappingSuggestResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/unified-mapping/suggest`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 为页面区域生成 XFA 视觉绑定候选;歧义不自动确认。 */
|
||||
export const suggestOrderProfileXfaVisualBindings = (
|
||||
profileId: number,
|
||||
payload: {
|
||||
document_id: number;
|
||||
page_no: number;
|
||||
normalized_bbox: import('../types/shipping-order-document-profile.types').XfaNormalizedBBox;
|
||||
},
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaVisualBindingsSuggestResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/visual-bindings/suggest`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 确认视觉绑定;须携带 Lease / operation_id / 合成预览证据。 */
|
||||
export const confirmOrderProfileXfaVisualBinding = (
|
||||
profileId: number,
|
||||
bindingId: string,
|
||||
payload: {
|
||||
visual_binding: import('../types/shipping-order-document-profile.types').XfaVisualBinding;
|
||||
path_id?: string | null;
|
||||
browser_session_id: string;
|
||||
lease_token: string;
|
||||
operation_id: string;
|
||||
preview_render_checksum?: string | null;
|
||||
render_mode?: string | null;
|
||||
},
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaVisualBindingMutationResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/visual-bindings/${encodeURIComponent(bindingId)}/confirm`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 驳回视觉绑定建议;须携带 Lease / operation_id。 */
|
||||
export const rejectOrderProfileXfaVisualBinding = (
|
||||
profileId: number,
|
||||
bindingId: string,
|
||||
payload: {
|
||||
reason_code?: string | null;
|
||||
browser_session_id: string;
|
||||
lease_token: string;
|
||||
operation_id: string;
|
||||
},
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaVisualBindingMutationResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/visual-bindings/${encodeURIComponent(bindingId)}/reject`,
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/value-adapter/split-rules/suggest`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
@@ -587,11 +451,11 @@ export const runOrderProfileCurrentSample = (profileId: number, payload: {
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 生成当前草稿版面签名;服务端更新 Profile 轻量引用,不接收前端 matcher 分数。 */
|
||||
export const runOrderProfileLayoutSignature = (profileId: number, payload: {
|
||||
/** 生成当前草稿统一身份签名;值源算法仅在服务端 adapter 内选择。 */
|
||||
export const runOrderProfileIdentitySignature = (profileId: number, payload: {
|
||||
browser_session_id: string; lease_token: string; operation_id: string;
|
||||
}) => requestJson<import('@/features/admin/types/shipping-order-document-profile.types').OrderProfileValidationRun>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/validation-runs/layout-signature`,
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/validation-runs/profile-identity-signature`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
@@ -680,7 +544,6 @@ export const authorizeOrderProfilePdfPreview = (profileId: number, documentId: n
|
||||
);
|
||||
|
||||
/** @deprecated 旧 XFA 调用方兼容别名;新代码使用 authorizeOrderProfilePdfPreview。 */
|
||||
export const authorizeOrderProfileXfaPdfPreview = authorizeOrderProfilePdfPreview;
|
||||
|
||||
/** 为冻结样本绑定申请只读详情页逐页预览授权,禁止回退到当前 document layout。 */
|
||||
export const authorizeOrderProfileFrozenSamplePreviewPages = (profileId: number, sampleBindingId: number) =>
|
||||
|
||||
@@ -175,6 +175,29 @@
|
||||
</div>
|
||||
<button type="button" class="btn-secondary btn-sm full" @click="addParameter">{{ t('admin.shippingInventory.addParameter') }}</button>
|
||||
</template>
|
||||
<section v-if="selectedId" class="receipt-report-config full">
|
||||
<div class="subsection">{{ t('admin.shippingInventory.receiptReportConfig') }}<small>{{ t('admin.shippingInventory.receiptReportConfigHint') }}</small></div>
|
||||
<div class="switch-field"><span>{{ t('admin.shippingInventory.receiptReportEnabled') }}</span><button type="button" class="status-switch" :class="{ on: receiptConfig.enabled }" role="switch" :aria-checked="receiptConfig.enabled" @click="receiptConfig.enabled = !receiptConfig.enabled"><i></i><b>{{ receiptConfig.enabled ? t('admin.shippingInventory.enabledState') : t('admin.shippingInventory.disabledState') }}</b></button></div>
|
||||
<template v-if="source.connector_type === 'dbs'">
|
||||
<label><span>{{ t('admin.shippingInventory.programGroup') }}</span><input v-model="receiptConfig.report_path_json.program_group" class="input-field" required></label>
|
||||
<label><span>{{ t('admin.shippingInventory.programLabel') }}</span><input v-model="receiptConfig.report_path_json.program_label" class="input-field" required></label>
|
||||
<label><span>{{ t('admin.shippingInventory.reportGroup') }}</span><input v-model="receiptConfig.report_path_json.report_group" class="input-field" required></label>
|
||||
<label><span>{{ t('admin.shippingInventory.reportName') }}</span><input v-model="receiptConfig.report_path_json.report_name" class="input-field" required></label>
|
||||
<label class="full"><span>{{ t('admin.shippingInventory.receiptWarehouses') }}</span><input class="input-field" :value="receiptConfig.warehouse_ids_json.join(', ')" :placeholder="t('admin.shippingInventory.receiptWarehousesHint')" @input="receiptConfig.warehouse_ids_json = splitValues(($event.target as HTMLInputElement).value)"></label>
|
||||
<div class="subsection full">{{ t('admin.shippingInventory.receiptOptionalParameters') }}</div>
|
||||
<div v-for="(parameter, index) in receiptConfig.query_parameters_json" :key="`receipt-${index}-${parameter.name}`" class="parameter-row full">
|
||||
<input v-model="parameter.name" class="input-field" :placeholder="t('admin.shippingInventory.parameterName')">
|
||||
<select v-model="parameter.mode" class="select-field"><option value="single">{{ t('admin.shippingInventory.single') }}</option><option value="multi_text">{{ t('admin.shippingInventory.multiText') }}</option><option value="multi_select">{{ t('admin.shippingInventory.multiSelect') }}</option></select>
|
||||
<input class="input-field" :value="parameter.values.join(', ')" :placeholder="t('admin.shippingInventory.parameterValues')" @input="parameter.values = splitValues(($event.target as HTMLInputElement).value)">
|
||||
<label class="inline-check"><input v-model="parameter.required" type="checkbox">{{ t('admin.shippingInventory.required') }}</label>
|
||||
<label class="inline-check"><input v-model="parameter.select_all" type="checkbox">{{ t('admin.shippingInventory.selectAll') }}</label>
|
||||
<button type="button" class="btn-danger btn-sm" @click="receiptConfig.query_parameters_json.splice(index, 1)">{{ t('admin.delete') }}</button>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary btn-sm full" @click="addReceiptParameter">{{ t('admin.shippingInventory.addParameter') }}</button>
|
||||
</template>
|
||||
<p v-else class="form-tip full">{{ t('admin.shippingInventory.receiptCraneFixedPath') }}</p>
|
||||
<div class="receipt-config-actions full"><button type="button" class="btn-secondary btn-sm" :disabled="receiptConfigLoading || receiptConfigSaving" @click="saveReceiptConfig">{{ receiptConfigSaving ? t('admin.shippingInventory.saving') : t('admin.shippingInventory.saveReceiptReportConfig') }}</button></div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<template v-else-if="activeTab === 'parsing'">
|
||||
@@ -457,10 +480,13 @@ import {
|
||||
saveShippingInventorySource,
|
||||
saveShippingRpaProfile,
|
||||
bulkBindShippingInventorySourceParsingProfile,
|
||||
getShippingReceiptReportConfig,
|
||||
saveShippingReceiptReportConfig,
|
||||
} from '@/features/admin/api/admin.api';
|
||||
import type { ShippingInventoryConfigurationTest, ShippingInventoryReadinessCheck, ShippingInventoryValidationBatch } from '@/features/admin/api/admin.api';
|
||||
import { isConfigurationTestRunning, needsReadinessAction, readinessMarkerKind } from './shippingInventoryReadiness';
|
||||
import { normaliseInventoryReportPath } from './shippingInventorySourceForm';
|
||||
import { buildReceiptReportConfigPayload } from './receiptReportConfigForm';
|
||||
|
||||
type TabKey = 'profiles' | 'parsing' | 'inventoryFields' | 'templates' | 'sources' | 'rules' | 'snapshots' | 'exports' | 'mappings';
|
||||
type Item = Record<string, any>;
|
||||
@@ -548,6 +574,9 @@ const bulkBinding = reactive({ visible: false, sourceIds: [] as number[], profil
|
||||
const batchValidation = reactive({ visible: false, sourceIds: [] as number[], query: '', statusFilter: 'all' as 'all' | 'processing' | 'completed' | 'completed_empty' | 'failed', saving: false, result: null as ShippingInventoryValidationBatch | null });
|
||||
let batchValidationTimer: number | null = null;
|
||||
const source = reactive({ source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [] as Parameter[], enabled: false, activation: { ready: false, checks: [] as ShippingInventoryReadinessCheck[], missing_requirements: [] as string[] } as SourceActivation });
|
||||
const receiptConfig = reactive({ enabled: false, report_path_json: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '' } as Record<string, string>, query_parameters_json: [] as Parameter[], warehouse_ids_json: [] as string[] });
|
||||
const receiptConfigLoading = ref(false);
|
||||
const receiptConfigSaving = ref(false);
|
||||
const sourceBaseline = ref('');
|
||||
const rule = reactive({ rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', operator: 'prefix', expected: '' }] as RuleCondition[], source_codes: [] as string[] });
|
||||
const mapping = reactive({ inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true });
|
||||
@@ -766,6 +795,55 @@ async function load(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** 重置当前站点的独立收料表单,不借用库存报表路径或查询条件。 */
|
||||
function resetReceiptConfig(connectorType: unknown): void {
|
||||
Object.assign(receiptConfig, {
|
||||
enabled: false,
|
||||
report_path_json: String(connectorType || '').toLowerCase() === 'crane'
|
||||
? { report_name: 'Inbound Details' }
|
||||
: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '' },
|
||||
query_parameters_json: [],
|
||||
warehouse_ids_json: [],
|
||||
});
|
||||
}
|
||||
|
||||
/** 读取收料独立配置;读取失败不影响库存站点配置和既有库存运行。 */
|
||||
async function loadReceiptConfig(sourceId: number, connectorType: unknown): Promise<void> {
|
||||
receiptConfigLoading.value = true;
|
||||
resetReceiptConfig(connectorType);
|
||||
try {
|
||||
const config = await getShippingReceiptReportConfig(sourceId);
|
||||
if (!config) return;
|
||||
const isCrane = String(connectorType || '').toLowerCase() === 'crane';
|
||||
Object.assign(receiptConfig, {
|
||||
enabled: Boolean(config.enabled),
|
||||
report_path_json: isCrane
|
||||
? { report_name: 'Inbound Details' }
|
||||
: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '', ...((config.report_path_json || {}) as Record<string, string>) },
|
||||
query_parameters_json: Array.isArray(config.query_parameters_json) ? config.query_parameters_json.map((parameter) => ({ ...parameter })) : [],
|
||||
warehouse_ids_json: Array.isArray(config.warehouse_ids_json) ? [...config.warehouse_ids_json].map(String) : [],
|
||||
});
|
||||
} catch (cause) { showError(cause, 'loadFailed'); }
|
||||
finally { receiptConfigLoading.value = false; }
|
||||
}
|
||||
|
||||
/** 新增 DBS 可选收料条件;Crane 固定默认查询,不维护查询条件。 */
|
||||
function addReceiptParameter(): void {
|
||||
receiptConfig.query_parameters_json.push({ name: '', mode: 'single', values: [], required: false, select_all: false });
|
||||
}
|
||||
|
||||
/** 仅提交白名单收料字段到独立 API,绝不调用库存 Source 保存接口。 */
|
||||
async function saveReceiptConfig(): Promise<void> {
|
||||
if (!selectedId.value) return;
|
||||
receiptConfigSaving.value = true;
|
||||
try {
|
||||
await saveShippingReceiptReportConfig(selectedId.value, buildReceiptReportConfigPayload(receiptConfig));
|
||||
await loadReceiptConfig(selectedId.value, source.connector_type);
|
||||
message.success(t('admin.shippingInventory.receiptReportSaved'));
|
||||
} catch (cause) { showError(cause, 'saveFailed'); }
|
||||
finally { receiptConfigSaving.value = false; }
|
||||
}
|
||||
|
||||
/** 切换管理对象时同步深链并清空选择,避免不同对象的数据残留在编辑器中。 */
|
||||
function selectTab(tab: TabKey): void {
|
||||
activeTab.value = tab;
|
||||
@@ -809,6 +887,7 @@ function createNew(): void {
|
||||
}
|
||||
if (activeTab.value === 'sources') {
|
||||
Object.assign(source, { source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [], enabled: false, activation: { ready: false, checks: [], missing_requirements: ['configuration_test'] } });
|
||||
resetReceiptConfig('dbs');
|
||||
sourceBaseline.value = '';
|
||||
}
|
||||
if (activeTab.value === 'rules') Object.assign(rule, { rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', operator: 'prefix', expected: '' }], source_codes: [] });
|
||||
@@ -860,6 +939,7 @@ function selectItem(item: Item): void {
|
||||
Object.assign(source, { ...item, fixed_warehouse_id: item.fixed_warehouse_id || '', report_path_json: normaliseInventoryReportPath(item.connector_type, reportPath), query_parameters_json: (item.query_parameters_json || []).map((parameter: Parameter) => ({ ...parameter })) });
|
||||
sourceBaseline.value = serialiseSourceInput();
|
||||
void restoreConfigurationTest(Number(item.id));
|
||||
void loadReceiptConfig(Number(item.id), String(item.connector_type || ''));
|
||||
}
|
||||
if (activeTab.value === 'rules') Object.assign(rule, {
|
||||
rule_code: item.rule_code || '', rule_name: item.rule_name || '', scope: item.scope || 'line', priority: item.priority || 0,
|
||||
@@ -977,6 +1057,7 @@ function closeDrawer(): void {
|
||||
if (configurationTestTimer !== null) window.clearTimeout(configurationTestTimer);
|
||||
configurationTestTimer = null;
|
||||
configurationTest.value = null;
|
||||
resetReceiptConfig(source.connector_type);
|
||||
sourceBaseline.value = '';
|
||||
drawerOpen.value = false;
|
||||
selectedId.value = null;
|
||||
@@ -1523,6 +1604,9 @@ onMounted(load);
|
||||
.sample-evidence-card dl { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px 16px; margin: 0; }.sample-evidence-card dl div { min-width: 0; }.sample-evidence-card dt { color: #8190a0; font-size: 11px; }.sample-evidence-card dd { margin: 3px 0 0; overflow-wrap: anywhere; color: #475569; font-size: 12px; font-weight: 600; }
|
||||
.sample-replacement-input { display: grid; gap: 6px; border-top: 1px solid #e5edf3; padding-top: 11px; color: #52677a; font-size: 12px; font-weight: 600; }.sample-replacement-input input { max-width: 100%; }.sample-replacement-warning { border-left: 3px solid #e5a21a; background: #fff9eb; padding: 8px 10px; color: #855e00 !important; }.sample-replacement-warning p { margin: 0; }.sample-replacement-warning ul { display: grid; gap: 3px; margin: 7px 0 0; padding-left: 17px; }
|
||||
.parameter-row { display: grid; align-items: center; grid-template-columns: 1.1fr .9fr 1.25fr auto auto auto; gap: 8px; border-radius: 8px; background: #f8fafc; padding: 9px; }
|
||||
.receipt-report-config { display: grid; grid-column: 1 / -1; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; border-top: 1px solid #dbe8ee; margin-top: 8px; padding-top: 14px; }
|
||||
.receipt-report-config .subsection, .receipt-report-config .full { grid-column: 1 / -1; }
|
||||
.receipt-config-actions { display: flex; justify-content: flex-end; }
|
||||
.condition-row, .mapping-row, .template-mapping { display: grid; align-items: center; gap: 8px; border-radius: 8px; background: #f8fafc; padding: 9px; }
|
||||
.condition-row { grid-template-columns: 1.15fr .9fr 1fr auto; }
|
||||
.mapping-row { grid-template-columns: 1fr 1fr auto; }
|
||||
@@ -1563,5 +1647,5 @@ onMounted(load);
|
||||
.object-list .empty-state { grid-column: 1 / -1; display: grid; min-height: 260px; place-items: center; }
|
||||
.empty-state { border: 1px dashed #c9d7e5; border-radius: 10px; background: #f9fbfd; padding: 38px 18px; color: #7b899a; font-size: 13px; text-align: center; }
|
||||
@media (max-width: 980px) { .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card { grid-template-columns: 1fr 1fr; } .mapping-value-row { grid-template-columns: minmax(0, 1.6fr) minmax(180px, 1fr); }.readiness-audit { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@media (max-width: 640px) { .inventory-console { padding: 18px; } .editor-form, .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card, .mapping-value-row, .parsing-mapping-card, .readonly-mapping-section .parsing-mapping-card, .parsing-summary { grid-template-columns: 1fr; } .mapping-arrow { transform: rotate(90deg); }.workbench-heading { display: block; } .workbench-heading .btn-primary { margin-top: 12px; }.batch-source-list { grid-template-columns: 1fr; }.batch-stat-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }.batch-run { grid-template-columns: 9px minmax(0, 1fr); }.batch-run-error { grid-column: 2; }.readiness-heading { display: grid; }.readiness-count { justify-self: start; }.readiness-steps li { grid-template-columns: 24px minmax(0, 1fr); }.readiness-action { grid-column: 2; justify-self: start; }.readiness-footer { justify-content: stretch; }.readiness-footer .btn-primary { width: 100%; } }
|
||||
@media (max-width: 640px) { .inventory-console { padding: 18px; } .editor-form, .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card, .mapping-value-row, .parsing-mapping-card, .readonly-mapping-section .parsing-mapping-card, .parsing-summary, .receipt-report-config { grid-template-columns: 1fr; } .mapping-arrow { transform: rotate(90deg); }.workbench-heading { display: block; } .workbench-heading .btn-primary { margin-top: 12px; }.batch-source-list { grid-template-columns: 1fr; }.batch-stat-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }.batch-run { grid-template-columns: 9px minmax(0, 1fr); }.batch-run-error { grid-column: 2; }.readiness-heading { display: grid; }.readiness-count { justify-self: start; }.readiness-steps li { grid-template-columns: 24px minmax(0, 1fr); }.readiness-action { grid-column: 2; justify-self: start; }.readiness-footer { justify-content: stretch; }.readiness-footer .btn-primary { width: 100%; } }
|
||||
</style>
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-inventory/receiptReportConfigForm.spec.ts
|
||||
* 用途:覆盖收料报表表单的独立载荷边界。
|
||||
* 依赖:receiptReportConfigForm、vitest。
|
||||
* 逻辑:防止收料配置保存时把库存站点路径、库存查询条件或启停状态误发到库存接口。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildReceiptReportConfigPayload } from './receiptReportConfigForm';
|
||||
|
||||
describe('receiptReportConfigForm', () => {
|
||||
it('builds a receipt-only payload without inventory source fields', () => {
|
||||
// 关键断言:收料路径、条件与仓库必须走独立 API,不能夹带库存 RPA 配置。
|
||||
const payload = buildReceiptReportConfigPayload({
|
||||
enabled: true,
|
||||
report_path_json: { program_group: 'Bison', program_label: 'AWSBI', report_group: 'Inbound', report_name: 'Receipt Detail' },
|
||||
query_parameters_json: [{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false }],
|
||||
warehouse_ids_json: ['A', 'B'],
|
||||
source_code: 'INVENTORY-SHOULD-NOT-LEAK',
|
||||
snapshot_ttl_seconds: 86400,
|
||||
inventory_report_path_json: { report_name: 'On Hand' },
|
||||
});
|
||||
|
||||
expect(payload).toEqual({
|
||||
enabled: true,
|
||||
report_path_json: { program_group: 'Bison', program_label: 'AWSBI', report_group: 'Inbound', report_name: 'Receipt Detail' },
|
||||
query_parameters_json: [{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false }],
|
||||
warehouse_ids_json: ['A', 'B'],
|
||||
});
|
||||
expect(payload).not.toHaveProperty('source_code');
|
||||
expect(payload).not.toHaveProperty('snapshot_ttl_seconds');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-inventory/receiptReportConfigForm.ts
|
||||
* 用途:构建独立收料报表配置的受限保存载荷。
|
||||
* 依赖:无外部依赖。
|
||||
* 逻辑:页面仅将收料路径、可选条件和 Warehouse 列表提交到收料配置 API,隔离库存站点字段。
|
||||
*/
|
||||
|
||||
export type ReceiptReportConfigInput = {
|
||||
enabled: boolean;
|
||||
report_path_json: Record<string, unknown>;
|
||||
query_parameters_json: Array<Record<string, unknown>>;
|
||||
warehouse_ids_json: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* 构造独立收料配置保存载荷。
|
||||
* 核心逻辑:白名单复制可配置业务字段,不允许调用方把库存源、Profile 或启停字段带入收料 API。
|
||||
* @param input - 抽屉中的收料配置表单状态。
|
||||
* @returns 仅包含收料配置 API 支持字段的深拷贝载荷。
|
||||
*/
|
||||
export function buildReceiptReportConfigPayload(input: ReceiptReportConfigInput): ReceiptReportConfigInput {
|
||||
return {
|
||||
enabled: Boolean(input.enabled),
|
||||
report_path_json: { ...(input.report_path_json || {}) },
|
||||
query_parameters_json: (input.query_parameters_json || []).map((item) => ({ ...item })),
|
||||
warehouse_ids_json: [...(input.warehouse_ids_json || [])],
|
||||
};
|
||||
}
|
||||
+4
-23
@@ -2,8 +2,8 @@
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileBlindTestPage.vue
|
||||
用途:维护订单模板草稿的独立盲测证据,并完成执行和批准。
|
||||
依赖:盲测 API、Profile 详情、Vue Router、统一业务错误提示和四语言文案。
|
||||
逻辑:验证页进入本页;coordinate 走表格候选,xfa_dataset 走文档级结构分析候选;
|
||||
管理员复核候选后写入真值,再执行并批准,最后回到发布检查。不回显盲测真值。
|
||||
逻辑:验证页进入本页;所有模板按统一视觉表候选和字段证据复核;
|
||||
末端值源差异由服务端 adapter 投影,管理员复核后写入真值,再执行并批准。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
createOrderProfileTestSuite,
|
||||
executeOrderProfileTestSuite,
|
||||
createOrderProfileSample,
|
||||
getOrderDocumentProfileDetail,
|
||||
getOrderProfileSampleStatus,
|
||||
listOrderProfileBlindTestAvailableSamples,
|
||||
listOrderProfileBoundSamples,
|
||||
@@ -30,9 +29,7 @@ import type {
|
||||
OrderProfileBlindTestAvailableSample,
|
||||
OrderProfileBlindTestCandidate,
|
||||
OrderProfileTestSuite,
|
||||
OrderProfileTemplateMode,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { isXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
@@ -41,12 +38,9 @@ const { t } = useI18n();
|
||||
const profileId = Number(route.params.profileId);
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
|
||||
const suite = ref<OrderProfileTestSuite | null>(null);
|
||||
const templateMode = ref<OrderProfileTemplateMode>('coordinate');
|
||||
const availableSamples = ref<OrderProfileBlindTestAvailableSample[]>([]);
|
||||
const selectedSampleKey = ref('');
|
||||
const candidate = ref<OrderProfileBlindTestCandidate | null>(null);
|
||||
/** XFA 盲测使用文档级结构证据,不依赖坐标表格。 */
|
||||
const isXfa = computed(() => templateMode.value === 'xfa_dataset');
|
||||
const rowReviews = ref<Array<{ correct: boolean; correction: string }>>([]);
|
||||
const orderFieldReviews = ref<Record<string, { correct: boolean; value: string }>>({});
|
||||
const loading = ref(false);
|
||||
@@ -67,14 +61,6 @@ function sampleLabel(sample: OrderProfileBlindTestAvailableSample): string {
|
||||
if (sample.table_id === '__document_candidate__') {
|
||||
return t('admin.shippingOrderProfiles.blindTest.documentCandidateOption', { filename: sample.filename });
|
||||
}
|
||||
if (sample.table_id === 'xfa-authoritative-lines' || isXfa.value) {
|
||||
const identity = sample.header_preview.filter(Boolean).join(' · ');
|
||||
return t('admin.shippingOrderProfiles.blindTest.xfaSampleOption', {
|
||||
filename: sample.filename,
|
||||
rows: sample.row_count,
|
||||
identity: identity || '—',
|
||||
});
|
||||
}
|
||||
const header = sample.header_preview.join(' / ');
|
||||
return t('admin.shippingOrderProfiles.blindTest.sampleOption', {
|
||||
filename: sample.filename, page: sample.page_no, table: sample.table_index,
|
||||
@@ -136,15 +122,10 @@ function sampleFailureMessage(): string {
|
||||
async function loadSuite(): Promise<void> {
|
||||
loading.value = true;
|
||||
try {
|
||||
const [nextSuite, boundSamples, profile] = await Promise.all([
|
||||
const [nextSuite, boundSamples] = await Promise.all([
|
||||
createOrderProfileTestSuite(profileId),
|
||||
listOrderProfileBoundSamples(profileId),
|
||||
getOrderDocumentProfileDetail(profileId),
|
||||
]);
|
||||
templateMode.value = (
|
||||
profile.template_mode === 'xfa_dataset'
|
||||
|| isXfaDatasetProfileDefinition(profile.definition)
|
||||
) ? 'xfa_dataset' : 'coordinate';
|
||||
suite.value = nextSuite;
|
||||
hasTrainingSample.value = boundSamples.some((item) => item.sample_role === 'training');
|
||||
} catch (error) {
|
||||
@@ -425,7 +406,7 @@ onBeforeUnmount(() => {
|
||||
<header>
|
||||
<div>
|
||||
<h1 class="section-title">{{ t('admin.shippingOrderProfiles.blindTest.title') }}</h1>
|
||||
<p class="section-desc mt-1">{{ isXfa ? t('admin.shippingOrderProfiles.blindTest.xfaReviewHint') : t('admin.shippingOrderProfiles.blindTest.reviewHint') }}</p>
|
||||
<p class="section-desc mt-1">{{ t('admin.shippingOrderProfiles.blindTest.reviewHint') }}</p>
|
||||
</div>
|
||||
<div class="actions"><button type="button" class="btn-secondary" @click="backToValidation">{{ t('admin.shippingOrderProfiles.blindTest.backToValidation') }}</button><button v-if="suite?.status === 'approved'" type="button" class="btn-primary" @click="goToPublishCheck">{{ t('admin.shippingOrderProfiles.blindTest.goPublishCheck') }}</button></div>
|
||||
</header>
|
||||
|
||||
+15
-57
@@ -1,8 +1,8 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileCreateWizardPage.vue
|
||||
用途:以三步向导创建订单文档模板草稿(坐标或 XFA 自动分流)。
|
||||
依赖:Schema/样本/表格/XFA API、步骤组件和 Vue Router。
|
||||
逻辑:样本 xfa_analysis_ready 时第三步改为集合确认;否则保持表格选择;原子创建草稿与 Lease。
|
||||
用途:以三步向导创建订单文档模板草稿。
|
||||
依赖:Schema/样本/表格 API、步骤组件和 Vue Router。
|
||||
逻辑:所有有明细的样本在第三步选择同一视觉主表;XFA datasets/OCR 差异只在编辑器的字段取值映射中配置。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
|
||||
@@ -18,7 +18,6 @@ import type { ShippingOrderSchemaVersion } from '@/features/admin/types/shipping
|
||||
import OrderProfileIdentityStep from './components/OrderProfileIdentityStep.vue';
|
||||
import OrderProfileSampleStep from './components/OrderProfileSampleStep.vue';
|
||||
import OrderProfileModelStartStep from './components/OrderProfileModelStartStep.vue';
|
||||
import OrderProfileXfaConfirmStep from './components/OrderProfileXfaConfirmStep.vue';
|
||||
|
||||
type Identity = { displayName: string; schemaId: number };
|
||||
|
||||
@@ -34,24 +33,14 @@ const tables = ref<Array<{ table_id: string; page_no: number; row_count: number;
|
||||
const identity = reactive<Identity>({ displayName: '', schemaId: 0 });
|
||||
const documentId = ref(0);
|
||||
const tableId = ref('');
|
||||
const authoritativePathId = ref('');
|
||||
const mirrorPathIds = ref<string[]>([]);
|
||||
const xfaContextReady = ref(false);
|
||||
const browserSessionId = crypto.randomUUID();
|
||||
let sampleRefreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const selectedSample = computed(() => samples.value.find((item) => item.document_id === documentId.value) || null);
|
||||
const isXfaSample = computed(() => Boolean(selectedSample.value?.xfa_analysis_ready));
|
||||
const publishedSchemas = computed(() => schemas.value.filter((item) => item.status === 'published'));
|
||||
const stepThreeLabel = computed(() => (
|
||||
isXfaSample.value
|
||||
? t('admin.shippingOrderProfiles.wizard.xfa.stepTitle')
|
||||
: t('admin.shippingOrderProfiles.wizard.tableStep')
|
||||
));
|
||||
const stepThreeLabel = computed(() => t('admin.shippingOrderProfiles.wizard.tableStep'));
|
||||
const canNext = computed(() => {
|
||||
if (step.value === 1) return Boolean(identity.displayName.trim() && identity.schemaId);
|
||||
if (step.value === 2) return Boolean(documentId.value);
|
||||
if (isXfaSample.value) return Boolean(xfaContextReady.value && authoritativePathId.value);
|
||||
return Boolean(tableId.value);
|
||||
});
|
||||
const steps = computed(() => [
|
||||
@@ -98,21 +87,14 @@ function scheduleSampleRefresh(): void {
|
||||
});
|
||||
}
|
||||
|
||||
/** 加载选定样本的可用表格;XFA 样本跳过表格加载。 */
|
||||
/** 加载选定样本的统一视觉表格;XFA 与普通 PDF 走同一 main_table_id 选择。 */
|
||||
async function loadTables(id: number): Promise<void> {
|
||||
if (samples.value.find((item) => item.document_id === id)?.xfa_analysis_ready) {
|
||||
tables.value = [];
|
||||
return;
|
||||
}
|
||||
try { tables.value = (await getOrderProfileSampleTables(id)).tables; }
|
||||
catch (error) { message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.tableLoadFailed')); }
|
||||
}
|
||||
|
||||
watch(documentId, async (id) => {
|
||||
tableId.value = '';
|
||||
authoritativePathId.value = '';
|
||||
mirrorPathIds.value = [];
|
||||
xfaContextReady.value = false;
|
||||
tables.value = [];
|
||||
if (!id) return;
|
||||
await loadTables(id);
|
||||
@@ -123,7 +105,7 @@ watch(step, (currentStep) => {
|
||||
else stopSampleRefresh();
|
||||
});
|
||||
|
||||
/** 前进仅校验当前步骤;XFA 样本进入集合确认,单表坐标样本可直接创建。 */
|
||||
/** 前进仅校验当前步骤;所有模板共享视觉主表选择,单表样本可直接创建。 */
|
||||
async function next(): Promise<void> {
|
||||
if (!canNext.value) {
|
||||
message.error(step.value === 1 && !publishedSchemas.value.length
|
||||
@@ -132,10 +114,6 @@ async function next(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
if (step.value === 2) {
|
||||
if (isXfaSample.value) {
|
||||
step.value = 3;
|
||||
return;
|
||||
}
|
||||
if (!tables.value.length) await loadTables(documentId.value);
|
||||
const onlyTable = tables.value.length === 1 ? tables.value[0] : undefined;
|
||||
if (onlyTable) {
|
||||
@@ -151,29 +129,19 @@ async function next(): Promise<void> {
|
||||
if (step.value < 3) step.value += 1;
|
||||
}
|
||||
|
||||
/** 单事务完成后进入草稿编辑路由;XFA 与坐标共享同一审计动作入口。 */
|
||||
/** 单事务完成后进入统一草稿编辑路由;字段取值 source 在编辑器内配置。 */
|
||||
async function finish(enterEditor: boolean): Promise<void> {
|
||||
if (!canNext.value) return;
|
||||
saving.value = true;
|
||||
try {
|
||||
const payload = isXfaSample.value
|
||||
? {
|
||||
display_name: identity.displayName,
|
||||
schema_version_id: identity.schemaId,
|
||||
document_id: documentId.value,
|
||||
authoritative_collection_path_id: authoritativePathId.value,
|
||||
mirror_collection_path_ids: mirrorPathIds.value,
|
||||
browser_session_id: browserSessionId,
|
||||
operation_id: crypto.randomUUID(),
|
||||
}
|
||||
: {
|
||||
display_name: identity.displayName,
|
||||
schema_version_id: identity.schemaId,
|
||||
document_id: documentId.value,
|
||||
main_table_id: tableId.value,
|
||||
browser_session_id: browserSessionId,
|
||||
operation_id: crypto.randomUUID(),
|
||||
};
|
||||
const payload = {
|
||||
display_name: identity.displayName,
|
||||
schema_version_id: identity.schemaId,
|
||||
document_id: documentId.value,
|
||||
main_table_id: tableId.value,
|
||||
browser_session_id: browserSessionId,
|
||||
operation_id: crypto.randomUUID(),
|
||||
};
|
||||
const profile = await completeOrderDocumentProfileWizard(payload);
|
||||
message.success(t('admin.shippingOrderProfiles.created'));
|
||||
await router.push(enterEditor
|
||||
@@ -216,16 +184,6 @@ onBeforeUnmount(stopSampleRefresh);
|
||||
@update:model-value="updateIdentity"
|
||||
/>
|
||||
<OrderProfileSampleStep v-else-if="step === 2" v-model="documentId" :samples="samples" @uploaded="refreshSamples(false)" @refresh="refreshSamples()" />
|
||||
<OrderProfileXfaConfirmStep
|
||||
v-else-if="isXfaSample"
|
||||
:document-id="documentId"
|
||||
:sample="selectedSample"
|
||||
:authoritative-path-id="authoritativePathId"
|
||||
:mirror-path-ids="mirrorPathIds"
|
||||
@update:authoritative-path-id="authoritativePathId = $event"
|
||||
@update:mirror-path-ids="mirrorPathIds = $event"
|
||||
@update:context-ready="xfaContextReady = $event"
|
||||
/>
|
||||
<OrderProfileModelStartStep v-else v-model="tableId" :tables="tables" />
|
||||
</main>
|
||||
|
||||
|
||||
+818
-708
File diff suppressed because it is too large.
Load diff
+39
-33
@@ -35,10 +35,12 @@ const sessionId = String(route.query.editorSessionId || '').trim() || crypto.ran
|
||||
const leaseToken = ref('');
|
||||
|
||||
const validationRun = computed(() => runs.value.find((item) => item.run_type === 'current_sample' && item.status === 'passed') || null);
|
||||
const layoutSignatureRun = computed(() => runs.value.find((item) => item.run_type === 'layout_signature' && item.status === 'passed') || null);
|
||||
const xfaStructureSignatureRun = computed(() => runs.value.find((item) => item.run_type === 'xfa_structure_signature' && item.status === 'passed') || null);
|
||||
const signatureRun = computed(() => xfaStructureSignatureRun.value || layoutSignatureRun.value);
|
||||
const isXfaReport = computed(() => report.value?.template_mode === 'xfa_dataset' || !!report.value?.xfa_structure_signature_status);
|
||||
/** 所有模板共用同一份视觉 layout signature;datasets 身份在其 evidence 中展示。 */
|
||||
const signatureRun = computed(() => runs.value.find((item) => (
|
||||
item.run_type === 'layout_signature' && item.status === 'passed'
|
||||
)) || null);
|
||||
const signatureStatusDetail = computed(() => report.value?.profile_identity_signature_status || null);
|
||||
const signatureIdentityDetails = computed(() => signatureStatusDetail.value?.identity_details || null);
|
||||
const overlapRun = computed(() => runs.value.find((item) => item.run_type === 'cross_template_overlap' && item.status === 'passed') || null);
|
||||
const publishable = computed(() => report.value?.status === 'valid' && !report.value.blocking_items.length && confirmed.value.length === (report.value.warning_items?.length || 0));
|
||||
const conflictProfiles = computed<OrderProfileOverlapConflictProfile[]>(() => report.value?.conflict_profiles || report.value?.overlap_summary?.conflict_profiles || []);
|
||||
@@ -47,29 +49,37 @@ const gateStatus = computed<'pass' | 'blocked' | 'pending'>(() => {
|
||||
return report.value.blocking_items.length ? 'blocked' : 'pass';
|
||||
});
|
||||
|
||||
/** XFA 统一验证指标:来自 current_sample 运行 summary(阶段 5–6)。 */
|
||||
const xfaValidationMetrics = computed<{
|
||||
visual: number | null;
|
||||
mirror: number | null;
|
||||
evidence: number | null;
|
||||
} | null>(() => {
|
||||
if (!isXfaReport.value) return null;
|
||||
/**
|
||||
* 统一将 value adapter 的验证指标投影为键值项。
|
||||
* 核心逻辑:页面只渲染公共指标卡;coordinate adapter 可返回空数组,XFA datasets
|
||||
* 则提供视觉/镜像/evidence 门禁证据,避免模板类型决定 DOM 结构。
|
||||
*/
|
||||
const adapterValidationMetrics = computed<Array<{ label: string; value: number | null }>>(() => {
|
||||
const summary = validationRun.value?.summary;
|
||||
if (!summary || typeof summary !== 'object') return null;
|
||||
if (!summary || typeof summary !== 'object') return [];
|
||||
const asRate = (value: unknown): number | null => (
|
||||
typeof value === 'number' && Number.isFinite(value) ? value : null
|
||||
);
|
||||
const visual = asRate(summary.visual_coverage_rate);
|
||||
const mirror = asRate(summary.mirror_consistency_rate);
|
||||
const evidence = asRate(summary.evidence_retention_rate);
|
||||
if (visual == null && mirror == null && evidence == null) return null;
|
||||
return { visual, mirror, evidence };
|
||||
return [
|
||||
{ label: t('admin.orderProfilePublishCheck.xfaVisualCoverage'), value: asRate(summary.visual_coverage_rate) },
|
||||
{ label: t('admin.orderProfilePublishCheck.xfaMirrorConsistency'), value: asRate(summary.mirror_consistency_rate) },
|
||||
{ label: t('admin.orderProfilePublishCheck.xfaEvidenceRetention'), value: asRate(summary.evidence_retention_rate) },
|
||||
].filter((item) => item.value != null);
|
||||
});
|
||||
|
||||
/** 安全格式化 XFA 指标,避免 template 对 Record 字段推断为 unknown。 */
|
||||
function formatXfaMetric(value: number | null | undefined): string {
|
||||
return formatRate(value);
|
||||
}
|
||||
/** 将 identity adapter 返回的可选证据投影为通用签名指标。 */
|
||||
const signatureIdentityMetrics = computed<Array<{ label: string; value: string }>>(() => {
|
||||
const details = signatureIdentityDetails.value;
|
||||
if (!details) return [];
|
||||
const metrics: Array<{ label: string; value: string }> = [];
|
||||
if (typeof details.header_token_coverage === 'number') {
|
||||
metrics.push({ label: t('admin.orderProfilePublishCheck.signatureHeaderCoverage'), value: formatRate(details.header_token_coverage) });
|
||||
}
|
||||
if (details.dataset_structure_fingerprint) {
|
||||
metrics.push({ label: t('admin.orderProfilePublishCheck.xfaStructureFingerprint'), value: details.dataset_structure_fingerprint });
|
||||
}
|
||||
return metrics;
|
||||
});
|
||||
|
||||
/** 显示统一业务错误,避免发布页暴露服务端实现细节。 */
|
||||
function fail(error: unknown): void {
|
||||
@@ -164,8 +174,7 @@ function itemMessage(item: Record<string, unknown>): string {
|
||||
cross_template_margin_insufficient: t('admin.orderProfilePublishCheck.crossTemplateMarginInsufficient'),
|
||||
sample_role_pollution: t('admin.orderProfilePublishCheck.sampleRolePollution'),
|
||||
cross_template_conflict_profiles: t('admin.orderProfilePublishCheck.crossTemplateConflictProfiles'),
|
||||
xfa_visual_bindings_required: t('admin.orderProfilePublishCheck.xfaVisualBindingsRequired'),
|
||||
xfa_visual_binding_incomplete: t('admin.orderProfilePublishCheck.xfaVisualBindingIncomplete'),
|
||||
xfa_mapping_required: t('admin.orderProfilePublishCheck.xfaFieldMappingsRequired'),
|
||||
xfa_visual_coverage_insufficient: t('admin.orderProfilePublishCheck.xfaVisualCoverageInsufficient'),
|
||||
xfa_evidence_retention_insufficient: t('admin.orderProfilePublishCheck.xfaEvidenceRetentionInsufficient'),
|
||||
xfa_mirror_consistency_insufficient: t('admin.orderProfilePublishCheck.xfaMirrorConsistencyInsufficient'),
|
||||
@@ -242,13 +251,12 @@ onMounted(loadRuns);
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h3>{{ isXfaReport ? t('admin.orderProfilePublishCheck.xfaStructureSignatureTitle') : t('admin.orderProfilePublishCheck.layoutSignatureTitle') }}</h3>
|
||||
<h3>{{ t('admin.orderProfilePublishCheck.layoutSignatureTitle') }}</h3>
|
||||
<dl class="metrics">
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.signatureStatus') }}</dt><dd :class="`status-${(isXfaReport ? report.xfa_structure_signature_status : report.layout_signature_status)?.status || 'unknown'}`">{{ signatureStatus((isXfaReport ? report.xfa_structure_signature_status : report.layout_signature_status)?.status) }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.signatureSampleCount') }}</dt><dd>{{ (isXfaReport ? report.xfa_structure_signature_status : report.layout_signature_status)?.source_sample_count ?? '—' }}</dd></div>
|
||||
<div v-if="!isXfaReport"><dt>{{ t('admin.orderProfilePublishCheck.signatureHeaderCoverage') }}</dt><dd>{{ formatRate(report.layout_signature_status?.header_token_coverage) }}</dd></div>
|
||||
<div v-if="isXfaReport"><dt>{{ t('admin.orderProfilePublishCheck.xfaStructureFingerprint') }}</dt><dd>{{ report.xfa_structure_signature_status?.dataset_structure_fingerprint || report.xfa_structure_signature_summary?.dataset_structure_fingerprint || '—' }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.matcherPolicyVersion') }}</dt><dd>{{ report.matcher_policy_version || (isXfaReport ? report.xfa_structure_signature_status : report.layout_signature_status)?.matcher_policy_version || '—' }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.signatureStatus') }}</dt><dd :class="`status-${signatureStatusDetail?.status || 'unknown'}`">{{ signatureStatus(signatureStatusDetail?.status) }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.signatureSampleCount') }}</dt><dd>{{ signatureStatusDetail?.source_sample_count ?? '—' }}</dd></div>
|
||||
<div v-for="metric in signatureIdentityMetrics" :key="metric.label"><dt>{{ metric.label }}</dt><dd>{{ metric.value }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.matcherPolicyVersion') }}</dt><dd>{{ report.matcher_policy_version || signatureStatusDetail?.matcher_policy_version || '—' }}</dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
@@ -266,12 +274,10 @@ onMounted(loadRuns);
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section v-if="xfaValidationMetrics" class="card">
|
||||
<section v-if="adapterValidationMetrics.length" class="card">
|
||||
<h3>{{ t('admin.orderProfilePublishCheck.xfaUnifiedMetricsTitle') }}</h3>
|
||||
<dl class="metrics">
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.xfaVisualCoverage') }}</dt><dd>{{ formatXfaMetric(xfaValidationMetrics.visual) }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.xfaMirrorConsistency') }}</dt><dd>{{ formatXfaMetric(xfaValidationMetrics.mirror) }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.xfaEvidenceRetention') }}</dt><dd>{{ formatXfaMetric(xfaValidationMetrics.evidence) }}</dd></div>
|
||||
<div v-for="metric in adapterValidationMetrics" :key="metric.label"><dt>{{ metric.label }}</dt><dd>{{ formatRate(metric.value) }}</dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
|
||||
+57
-125
@@ -17,24 +17,18 @@ import {
|
||||
getOrderDocumentProfileDetail,
|
||||
listOrderProfileBoundSamples,
|
||||
listOrderProfileValidationRuns,
|
||||
previewOrderProfileOrderFieldValues,
|
||||
previewOrderProfileRegion,
|
||||
runOrderProfileCurrentSample,
|
||||
runOrderProfileInstantCheck,
|
||||
createOrderProfileTestSuite,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type {
|
||||
CoordinateReconstructionPreview,
|
||||
OrderFieldValuePreview,
|
||||
OrderProfileBoundSample,
|
||||
OrderProfileValidationEvidence,
|
||||
OrderProfileValidationEvidenceField,
|
||||
OrderProfileValidationRun,
|
||||
OrderProfileTestSuite,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import {
|
||||
asCoordinateProfileDefinition,
|
||||
isXfaDatasetProfileDefinition,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
@@ -47,27 +41,24 @@ const executing = ref(false);
|
||||
const leaseToken = ref('');
|
||||
const profile = ref<ShippingOrderDocumentProfile | null>(null);
|
||||
const sample = ref<OrderProfileBoundSample | null>(null);
|
||||
const headerValues = ref<OrderFieldValuePreview[]>([]);
|
||||
const linePreview = ref<CoordinateReconstructionPreview | null>(null);
|
||||
const resultLoading = ref(false);
|
||||
const resultFailed = ref(false);
|
||||
const fieldNames = ref(new Map<string, string>());
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
|
||||
const blindTestSuite = ref<OrderProfileTestSuite | null>(null);
|
||||
const isXfa = computed(() => (
|
||||
!!profile.value
|
||||
&& (profile.value.template_mode === 'xfa_dataset' || isXfaDatasetProfileDefinition(profile.value.definition))
|
||||
));
|
||||
const xfaSummary = computed(() => sampleRun.value?.summary || null);
|
||||
const xfaHeaderFields = computed(() => {
|
||||
const rows = xfaSummary.value?.header_fields;
|
||||
return Array.isArray(rows) ? rows as Array<Record<string, unknown>> : [];
|
||||
const validationEvidence = computed<OrderProfileValidationEvidence | null>(() => {
|
||||
const raw = sampleRun.value?.summary?.validation_evidence;
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
||||
const value = raw as Record<string, unknown>;
|
||||
return {
|
||||
header_fields: Array.isArray(value.header_fields) ? value.header_fields as OrderProfileValidationEvidenceField[] : [],
|
||||
lines: Array.isArray(value.lines) ? value.lines as OrderProfileValidationEvidence['lines'] : [],
|
||||
cross_checks: value.cross_checks && typeof value.cross_checks === 'object' && !Array.isArray(value.cross_checks)
|
||||
? value.cross_checks as Record<string, unknown>
|
||||
: {},
|
||||
};
|
||||
});
|
||||
const xfaLines = computed(() => {
|
||||
const rows = xfaSummary.value?.lines;
|
||||
return Array.isArray(rows) ? rows as Array<Record<string, unknown>> : [];
|
||||
});
|
||||
const XFA_CROSS_CHECK_KEYS = [
|
||||
const evidenceHeaderFields = computed(() => validationEvidence.value?.header_fields || []);
|
||||
const evidenceLines = computed(() => validationEvidence.value?.lines || []);
|
||||
const ADAPTER_CROSS_CHECK_KEYS = [
|
||||
'mirror_status',
|
||||
'acroform_status',
|
||||
'line_amount_status',
|
||||
@@ -75,37 +66,32 @@ const XFA_CROSS_CHECK_KEYS = [
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* 从字段预览中取标准化值。
|
||||
* 从统一字段预览中取标准化值。
|
||||
*/
|
||||
function xfaFieldNormalized(
|
||||
fields: Array<Record<string, unknown>>,
|
||||
function evidenceFieldNormalized(
|
||||
fields: OrderProfileValidationEvidenceField[],
|
||||
fieldCode: string,
|
||||
): string {
|
||||
const hit = fields.find((item) => String(item.field_code || '') === fieldCode);
|
||||
return String(hit?.normalized_value ?? '').trim();
|
||||
const hit = fields.find((item) => item.field_code === fieldCode);
|
||||
return (hit?.normalized_value ?? '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 将交叉校验技术状态映射为管理员可读说明(含金额计算过程)。
|
||||
* 将 adapter 交叉校验状态映射为管理员可读说明(含金额计算过程)。
|
||||
*/
|
||||
const xfaCrossCheckEntries = computed(() => {
|
||||
const checks = xfaSummary.value?.cross_checks;
|
||||
const adapterCrossCheckEntries = computed(() => {
|
||||
const checks = validationEvidence.value?.cross_checks;
|
||||
if (!checks || typeof checks !== 'object' || Array.isArray(checks)) return [];
|
||||
const map = checks as Record<string, unknown>;
|
||||
const firstLineFields = Array.isArray(xfaLines.value[0]?.fields)
|
||||
? (xfaLines.value[0].fields as Array<Record<string, unknown>>)
|
||||
: [];
|
||||
const qty = xfaFieldNormalized(firstLineFields, 'quantity');
|
||||
const unitPrice = xfaFieldNormalized(firstLineFields, 'unit_price');
|
||||
const priceUnit = xfaFieldNormalized(firstLineFields, 'price_unit') || '1';
|
||||
const amount = xfaFieldNormalized(firstLineFields, 'amount');
|
||||
const total = xfaFieldNormalized(xfaHeaderFields.value, 'total_amount')
|
||||
|| xfaFieldNormalized(xfaHeaderFields.value, 'order_amount');
|
||||
const lineSum = xfaLines.value.reduce((sum, line) => {
|
||||
const fields = Array.isArray(line.fields)
|
||||
? (line.fields as Array<Record<string, unknown>>)
|
||||
: [];
|
||||
const raw = xfaFieldNormalized(fields, 'amount').replace(/,/g, '');
|
||||
const firstLineFields = evidenceLines.value[0]?.fields || [];
|
||||
const qty = evidenceFieldNormalized(firstLineFields, 'quantity');
|
||||
const unitPrice = evidenceFieldNormalized(firstLineFields, 'unit_price');
|
||||
const amount = evidenceFieldNormalized(firstLineFields, 'amount');
|
||||
const total = evidenceFieldNormalized(evidenceHeaderFields.value, 'total_amount')
|
||||
|| evidenceFieldNormalized(evidenceHeaderFields.value, 'order_amount');
|
||||
const lineSum = evidenceLines.value.reduce((sum, line) => {
|
||||
const fields = line.fields || [];
|
||||
const raw = evidenceFieldNormalized(fields, 'amount').replace(/,/g, '');
|
||||
const n = Number(raw);
|
||||
return Number.isFinite(n) ? sum + n : sum;
|
||||
}, 0);
|
||||
@@ -113,7 +99,7 @@ const xfaCrossCheckEntries = computed(() => {
|
||||
? String(Number(lineSum.toFixed(2)))
|
||||
: amount;
|
||||
|
||||
return XFA_CROSS_CHECK_KEYS
|
||||
return ADAPTER_CROSS_CHECK_KEYS
|
||||
.filter((key) => map[key] != null && String(map[key]).trim() !== '')
|
||||
.map((key) => {
|
||||
const status = String(map[key] ?? '').trim().toLowerCase();
|
||||
@@ -124,10 +110,9 @@ const xfaCrossCheckEntries = computed(() => {
|
||||
);
|
||||
let detail = '';
|
||||
if (key === 'line_amount_status' && qty && unitPrice && amount) {
|
||||
detail = t('admin.orderProfileValidation.xfaAmountFormula', {
|
||||
detail = t('admin.orderProfileValidation.xfaAmountFormulaWithoutPriceUnit', {
|
||||
quantity: qty,
|
||||
unitPrice,
|
||||
priceUnit,
|
||||
amount,
|
||||
});
|
||||
} else if (key === 'total_amount_status' && total && lineSumText) {
|
||||
@@ -149,7 +134,8 @@ const xfaCrossCheckEntries = computed(() => {
|
||||
if (key === 'line_amount_status' && Array.isArray(map.line_amount_failures) && map.line_amount_failures.length) {
|
||||
detail = map.line_amount_failures.map((item) => {
|
||||
const failure = item as Record<string, unknown>;
|
||||
return `#${String(failure.row_index || '-')}: ${String(failure.quantity ?? '-')} × ${String(failure.unit_price ?? '-')} ÷ ${String(failure.price_unit ?? '1')} = ${String(failure.expected_amount ?? '?')},amount=${String(failure.amount ?? '-')}`;
|
||||
const formula = `${String(failure.quantity ?? '-')} × ${String(failure.unit_price ?? '-')}`;
|
||||
return `#${String(failure.row_index || '-')}: ${formula} = ${String(failure.expected_amount ?? '?')},amount=${String(failure.amount ?? '-')}`;
|
||||
}).join(';');
|
||||
}
|
||||
return { key, label, statusLabel, detail, status };
|
||||
@@ -215,47 +201,6 @@ async function loadContext(): Promise<void> {
|
||||
/** Schema 显示名称服务于业务核对;稳定编码仅作为辅助追溯信息保留。 */
|
||||
function fieldName(fieldCode: string): string { return fieldNames.value.get(fieldCode) || fieldCode; }
|
||||
|
||||
/** 使用本次草稿定义重读全部已绑定表头页和明细;XFA 从验证摘要读取字段级结果。 */
|
||||
async function loadReadResults(): Promise<void> {
|
||||
if (!profile.value || !sample.value) return;
|
||||
if (isXfa.value) {
|
||||
// XFA 字段级结果来自 current_sample summary,不请求坐标预览。
|
||||
headerValues.value = [];
|
||||
linePreview.value = null;
|
||||
resultFailed.value = false;
|
||||
return;
|
||||
}
|
||||
if (!sample.value.table_id) return;
|
||||
resultLoading.value = true;
|
||||
resultFailed.value = false;
|
||||
try {
|
||||
const definition = asCoordinateProfileDefinition(profile.value.definition);
|
||||
const pageNos = Array.from(new Set((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;
|
||||
let failed = false;
|
||||
try {
|
||||
const headers = await previewOrderProfileOrderFieldValues(
|
||||
sample.value.document_id, profile.value.schema_version_id, pageNo, definition, pageNos,
|
||||
);
|
||||
headerValues.value = headers.fields;
|
||||
} catch {
|
||||
headerValues.value = [];
|
||||
failed = true;
|
||||
}
|
||||
try {
|
||||
linePreview.value = await previewOrderProfileRegion(
|
||||
profileId, sample.value.document_id, sample.value.table_id || '', definition,
|
||||
);
|
||||
} catch {
|
||||
linePreview.value = null;
|
||||
failed = true;
|
||||
}
|
||||
resultFailed.value = failed;
|
||||
} finally { resultLoading.value = false; }
|
||||
}
|
||||
|
||||
/** 为本页获取单写者租约,避免验证或发布检查绕过草稿编辑保护。 */
|
||||
async function ensureLease(): Promise<boolean> {
|
||||
if (leaseToken.value) return true;
|
||||
@@ -284,7 +229,6 @@ async function validateCurrentDraft(): Promise<void> {
|
||||
// uses the same binding and definition that the server just validated.
|
||||
await loadContext();
|
||||
await loadBlindTestSuite();
|
||||
await loadReadResults();
|
||||
message.success(t('admin.orderProfileValidation.completed'));
|
||||
} catch (error) { report(error); } finally { executing.value = false; }
|
||||
}
|
||||
@@ -307,7 +251,6 @@ function backToEditor(): void {
|
||||
|
||||
onMounted(async () => {
|
||||
await Promise.all([loadRuns(), loadContext()]);
|
||||
await loadReadResults();
|
||||
if (canStartBlindTest.value) {
|
||||
await loadBlindTestSuite();
|
||||
}
|
||||
@@ -353,18 +296,14 @@ onMounted(async () => {
|
||||
</section>
|
||||
|
||||
<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>{{ isXfa ? t('admin.orderProfileValidation.xfaResultsHint') : t('admin.orderProfileValidation.resultsHint') }}</p></div><button v-if="!isXfa" type="button" class="btn-secondary btn-sm" :disabled="resultLoading" @click="loadReadResults">{{ t('admin.orderProfileValidation.refreshResults') }}</button></div>
|
||||
<template v-if="isXfa">
|
||||
<div class="results-heading"><div><h2>{{ t('admin.orderProfileValidation.resultsTitle') }}</h2><p>{{ t('admin.orderProfileValidation.resultsHint') }}</p></div></div>
|
||||
<template v-if="validationEvidence">
|
||||
<dl class="header-results">
|
||||
<div><dt>{{ t('admin.orderProfileValidation.xfaTemplateMode') }}</dt><dd>XFA</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfileValidation.xfaLineRows') }}</dt><dd>{{ xfaSummary?.line_row_count ?? '-' }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfileValidation.xfaCrossChecks') }}</dt><dd>{{ Array.isArray(xfaSummary?.cross_check_failures) && xfaSummary.cross_check_failures.length ? xfaSummary.cross_check_failures.join(', ') : t('admin.orderProfileValidation.xfaCrossChecksPassed') }}</dd></div>
|
||||
<div v-if="adapterCrossCheckEntries.length"><dt>{{ t('admin.orderProfileValidation.xfaCrossCheckStatus') }}</dt><dd>{{ adapterCrossCheckEntries.length }}</dd></div>
|
||||
</dl>
|
||||
|
||||
<h3>{{ t('admin.orderProfileValidation.xfaCrossCheckStatus') }}</h3>
|
||||
<dl v-if="xfaCrossCheckEntries.length" class="header-results">
|
||||
<dl v-if="adapterCrossCheckEntries.length" class="header-results">
|
||||
<div
|
||||
v-for="item in xfaCrossCheckEntries"
|
||||
v-for="item in adapterCrossCheckEntries"
|
||||
:key="item.key"
|
||||
:class="`field-${item.status === 'matched' || item.status === 'passed' || item.status === 'skipped' ? 'passed' : 'failed'}`"
|
||||
>
|
||||
@@ -374,51 +313,44 @@ onMounted(async () => {
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<h3>{{ t('admin.orderProfileValidation.xfaHeaderFields') }}</h3>
|
||||
<dl v-if="xfaHeaderFields.length" class="header-results">
|
||||
<h3>{{ t('admin.orderProfileValidation.headerResults') }}</h3>
|
||||
<dl v-if="evidenceHeaderFields.length" class="header-results">
|
||||
<div
|
||||
v-for="field in xfaHeaderFields"
|
||||
v-for="field in evidenceHeaderFields"
|
||||
:key="String(field.field_id || field.field_code)"
|
||||
:class="`field-${String(field.status || 'missing')}`"
|
||||
>
|
||||
<dt>{{ fieldName(String(field.field_code || '')) }}</dt>
|
||||
<dd class="field-code">{{ field.field_code }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaRawValue') }}:{{ field.raw_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaNormalized') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.read') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd v-if="field.raw_value && field.raw_value !== field.normalized_value" class="field-code">{{ field.raw_value }}</dd>
|
||||
<dd v-if="field.issues.length" class="field-issues">{{ field.issues.join(', ') }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p v-else>{{ t('admin.orderProfileValidation.xfaNoFieldPreview') }}</p>
|
||||
<p v-else>{{ t('admin.orderProfileValidation.noHeaderResults') }}</p>
|
||||
|
||||
<h3>{{ t('admin.orderProfileValidation.xfaLineFields') }}</h3>
|
||||
<div v-if="xfaLines.length" class="line-results">
|
||||
<article v-for="line in xfaLines" :key="String(line.row_index)" class="xfa-line-card">
|
||||
<h3>{{ t('admin.orderProfileValidation.lineResults') }}</h3>
|
||||
<div v-if="evidenceLines.length" class="line-results">
|
||||
<article v-for="line in evidenceLines" :key="String(line.row_index)" class="xfa-line-card">
|
||||
<h4>#{{ Number(line.row_index) + 1 }}</h4>
|
||||
<dl class="header-results">
|
||||
<div
|
||||
v-for="field in (Array.isArray(line.fields) ? line.fields : [])"
|
||||
v-for="field in line.fields"
|
||||
:key="String(field.field_id || field.field_code)"
|
||||
:class="`field-${String(field.status || 'missing')}`"
|
||||
>
|
||||
<dt>{{ fieldName(String(field.field_code || '')) }}</dt>
|
||||
<dd class="field-code">{{ field.field_code }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaRawValue') }}:{{ field.raw_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaNormalized') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.read') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd v-if="field.raw_value && field.raw_value !== field.normalized_value" class="field-code">{{ field.raw_value }}</dd>
|
||||
<dd v-if="field.issues.length" class="field-issues">{{ field.issues.join(', ') }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
</div>
|
||||
<p v-else>{{ t('admin.orderProfileValidation.xfaNoFieldPreview') }}</p>
|
||||
</template>
|
||||
<p v-else-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}:${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>
|
||||
<p v-else>{{ t('admin.orderProfileValidation.noLineResults') }}</p>
|
||||
</template>
|
||||
<p v-else class="result-error">{{ t('admin.orderProfileValidation.resultsFailed') }}</p>
|
||||
</section>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
-714
@@ -1,714 +0,0 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/OrderProfileXfaWorkbench.spec.ts
|
||||
* 用途:冒烟验证弃用薄包装与 useOrderProfileXfaDesk 默认 synthetic / dirty 契约。
|
||||
* 依赖:Vitest、@vue/test-utils、OrderProfileXfaWorkbench、useOrderProfileXfaDesk。
|
||||
* 逻辑:不再断言三栏 datasets 左栏;断言 desk 可加载且默认原生 PDF 画布。
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mount, flushPromises } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { defineComponent, h, nextTick } from 'vue';
|
||||
import OrderProfileXfaWorkbench from './OrderProfileXfaWorkbench.vue';
|
||||
import { useOrderProfileXfaDesk } from './composables/useOrderProfileXfaDesk';
|
||||
|
||||
const { authorizePreviewPagesMock, authorizePdfPreviewMock, saveDraftMock, splitPreviewMock, enqueueAutomarkMock, getAutomarkJobMock, suggestUnifiedMappingMock, messageErrorMock, detailDefinition } = vi.hoisted(() => ({
|
||||
authorizePreviewPagesMock: vi.fn(),
|
||||
authorizePdfPreviewMock: vi.fn(),
|
||||
saveDraftMock: vi.fn(),
|
||||
splitPreviewMock: vi.fn(),
|
||||
enqueueAutomarkMock: vi.fn(),
|
||||
getAutomarkJobMock: vi.fn(),
|
||||
suggestUnifiedMappingMock: vi.fn(),
|
||||
messageErrorMock: vi.fn(),
|
||||
detailDefinition: { value: null as Record<string, unknown> | null },
|
||||
}));
|
||||
|
||||
const defaultProps = {
|
||||
profileId: 52,
|
||||
leaseToken: 'lease',
|
||||
saveState: 'saved' as const,
|
||||
editorSessionId: 'editor-session',
|
||||
};
|
||||
|
||||
const baseDefinition = {
|
||||
template_mode: 'xfa_dataset' as const,
|
||||
source_contract: {
|
||||
template_packet_checksum: 'sha256:tpl',
|
||||
dataset_structure_fingerprint: 'sha256:fp',
|
||||
dataset_root_path: '/data',
|
||||
authoritative_line_collection_path: '/data/ITEMS/DATA',
|
||||
mirror_collection_paths: [],
|
||||
},
|
||||
header_mappings: [],
|
||||
line_mapping: { row_path: '/data/ITEMS/DATA', fields: [] },
|
||||
cross_checks: {
|
||||
acroform_enabled: true,
|
||||
mirror_collection_policy: 'must_match_when_present' as const,
|
||||
line_amount_formula: 'quantity_times_unit_price' as const,
|
||||
total_amount_policy: 'must_equal_line_sum' as const,
|
||||
},
|
||||
split_rules: [],
|
||||
bindings: [],
|
||||
};
|
||||
|
||||
vi.mock('vue-router', () => ({
|
||||
useRoute: () => ({ params: { profileId: '52', profileCode: 'ODP-TEST' }, query: {} }),
|
||||
useRouter: () => ({ push: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({ success: vi.fn(), error: messageErrorMock, info: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
|
||||
getOrderDocumentProfileDetail: vi.fn(async () => ({
|
||||
id: 52,
|
||||
profile_code: 'ODP-TEST',
|
||||
display_name: 'Fox PO',
|
||||
schema_version_id: 1,
|
||||
lock_version: 1,
|
||||
template_mode: 'xfa_dataset',
|
||||
definition: structuredClone(detailDefinition.value || baseDefinition),
|
||||
})),
|
||||
listOrderProfileBoundSamples: vi.fn(async () => [{ document_id: 85, sample_role: 'annotation' }]),
|
||||
getOrderProfileSampleXfaFieldTree: vi.fn(async () => ({
|
||||
tree: {
|
||||
path_id: 'root-data', local_name: 'data', data_path_hash: 'h0', depth: 0, cardinality: 'one',
|
||||
is_leaf: false, is_collection_candidate: false, children: [
|
||||
{
|
||||
path_id: 'invoiced-to-path', local_name: 'INVOICED_TO', data_path_hash: 'hh', depth: 1, cardinality: 'one',
|
||||
is_leaf: true, sample_value_display: 'Cloud Network', display_policy: 'full',
|
||||
},
|
||||
{
|
||||
path_id: 'items-data', local_name: 'DATA', data_path_hash: 'h', depth: 1, cardinality: 'many',
|
||||
is_leaf: false, is_collection_candidate: true, children: [{
|
||||
path_id: 'material-path', local_name: 'MATNR', data_path_hash: 'h2', depth: 2, cardinality: 'one',
|
||||
is_leaf: true, sample_value_display: 'TEMP-S', display_policy: 'full',
|
||||
}],
|
||||
},
|
||||
],
|
||||
},
|
||||
})),
|
||||
getOrderProfileSampleXfaCollections: vi.fn(async () => ({
|
||||
collection_candidates: [{ path_id: 'items-data', collection_path_hash: 'h', row_count: 1 }],
|
||||
})),
|
||||
authorizeOrderProfilePreviewPages: (...args: unknown[]) => authorizePreviewPagesMock(...args),
|
||||
authorizeOrderProfilePdfPreview: (...args: unknown[]) => authorizePdfPreviewMock(...args),
|
||||
requestOrderProfileSampleXfaSyntheticPreview: vi.fn(async () => ({
|
||||
document_id: 85,
|
||||
identity: {
|
||||
document_id: 85,
|
||||
layout_version_id: 1,
|
||||
structure_analysis_id: 1,
|
||||
source_content_hash: 'a'.repeat(64),
|
||||
template_packet_checksum: 't',
|
||||
datasets_packet_checksum: 'd',
|
||||
dataset_structure_fingerprint: 'f',
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
render_mode: 'xfa_dataset_preview',
|
||||
renderer_version: 'hxops.xfa_static_preview.v1',
|
||||
page_count: 1,
|
||||
},
|
||||
status: 'ready',
|
||||
render_mode: 'xfa_dataset_preview',
|
||||
renderer_version: 'hxops.xfa_static_preview.v1',
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
page_count: 1,
|
||||
pages: [{ page_no: 1, preview_token: 'synth-token' }],
|
||||
expires_in_seconds: 60,
|
||||
cache_hit: false,
|
||||
})),
|
||||
listOrderProfileSampleXfaSyntheticPreviewPages: vi.fn(),
|
||||
enqueueOrderProfilePdfAutomark: (...args: unknown[]) => enqueueAutomarkMock(...args),
|
||||
getOrderProfilePdfAutomarkJob: (...args: unknown[]) => getAutomarkJobMock(...args),
|
||||
acceptOrderProfileXfaOcrAutomarkSuggestion: vi.fn(),
|
||||
rejectOrderProfileXfaOcrAutomarkSuggestion: vi.fn(),
|
||||
suggestOrderProfileXfaUnifiedMapping: (...args: unknown[]) => suggestUnifiedMappingMock(...args),
|
||||
acquireOrderDocumentProfileEditLease: vi.fn(async () => ({ lease_token: 'lease', expires_at: new Date().toISOString() })),
|
||||
renewOrderDocumentProfileEditLease: vi.fn(),
|
||||
releaseOrderDocumentProfileEditLease: vi.fn(),
|
||||
saveOrderDocumentProfileDraft: (...args: unknown[]) => saveDraftMock(...args),
|
||||
previewOrderProfileSampleXfaSplitRules: (...args: unknown[]) => splitPreviewMock(...args),
|
||||
previewOrderProfileSampleXfaValue: vi.fn(),
|
||||
confirmOrderProfileXfaVisualBinding: vi.fn(),
|
||||
rejectOrderProfileXfaVisualBinding: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-schema.api', () => ({
|
||||
getShippingOrderSchemaState: vi.fn(async () => ({
|
||||
versions: [{
|
||||
id: 1,
|
||||
definition: {
|
||||
fields: [{
|
||||
field_id: 'f1', field_code: 'customer_po_no', scope: 'header', display_name: 'PO', required: true,
|
||||
enabled: true, aliases: [], normalizer_key: 'trim', validator_keys: [], enum_options: [],
|
||||
evidence_policy: { required: false, source_precedence: [], conflict_policy: 'fail', allow_single_source: true },
|
||||
comparator_key: 'exact',
|
||||
}],
|
||||
},
|
||||
}],
|
||||
})),
|
||||
}));
|
||||
|
||||
describe('OrderProfileXfaWorkbench (deprecated thin wrapper)', () => {
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh',
|
||||
messages: { zh: { common: { close: '关闭' }, admin: { shippingOrderProfiles: { xfaWorkbench: { loading: '加载中' } } } } },
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
detailDefinition.value = structuredClone(baseDefinition);
|
||||
enqueueAutomarkMock.mockReset();
|
||||
enqueueAutomarkMock.mockResolvedValue({ job_id: 9, status: 'queued' });
|
||||
getAutomarkJobMock.mockReset();
|
||||
getAutomarkJobMock.mockResolvedValue({
|
||||
job_id: 9,
|
||||
status: 'succeeded',
|
||||
kind: 'visual_binding',
|
||||
candidates: [],
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
});
|
||||
messageErrorMock.mockReset();
|
||||
suggestUnifiedMappingMock.mockReset();
|
||||
authorizePreviewPagesMock.mockReset();
|
||||
authorizePreviewPagesMock.mockResolvedValue({
|
||||
document_id: 85,
|
||||
page_count: 1,
|
||||
pages: [{ page_no: 1, preview_token: 'token' }],
|
||||
expires_in_seconds: 60,
|
||||
});
|
||||
authorizePdfPreviewMock.mockReset();
|
||||
authorizePdfPreviewMock.mockResolvedValue({
|
||||
document_id: 85,
|
||||
preview_token: 'xfa-pdf-token',
|
||||
expires_in_seconds: 120,
|
||||
});
|
||||
saveDraftMock.mockReset();
|
||||
splitPreviewMock.mockReset();
|
||||
// Canvas-related absolute URL safety: relative /api fetch must not throw in jsdom.
|
||||
vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
expect(url.startsWith('/') || url.startsWith('http')).toBe(true);
|
||||
return {
|
||||
ok: true,
|
||||
blob: async () => new Blob(['png'], { type: 'image/png' }),
|
||||
};
|
||||
}));
|
||||
});
|
||||
|
||||
const mountPage = async () => {
|
||||
const wrapper = mount(OrderProfileXfaWorkbench, {
|
||||
props: defaultProps,
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
for (let i = 0; i < 30; i += 1) {
|
||||
await flushPromises();
|
||||
await nextTick();
|
||||
if (wrapper.find('[data-testid="xfa-thin-canvas"]').exists()) break;
|
||||
}
|
||||
return wrapper;
|
||||
};
|
||||
|
||||
it('mounts thin deprecated desk without three-column left datasets tree', async () => {
|
||||
const wrapper = await mountPage();
|
||||
expect(wrapper.find('[data-testid="xfa-workbench-deprecated"]').exists()).toBe(true);
|
||||
expect(wrapper.find('.xfa-workbench__desk').exists()).toBe(true);
|
||||
expect(wrapper.find('.xfa-workbench__left').exists()).toBe(false);
|
||||
expect(wrapper.find('.xfa-workbench__panel').exists()).toBe(false);
|
||||
}, 15000);
|
||||
|
||||
it('defaults to native preview mode after load', async () => {
|
||||
const wrapper = await mountPage();
|
||||
const vm = wrapper.vm as unknown as { getDesk: () => { previewMode: string; syntheticPreviewStatus: string } };
|
||||
const desk = vm.getDesk();
|
||||
expect(desk.previewMode).toBe('native');
|
||||
expect(['ready', 'loading', 'unavailable', 'failed', 'stale', 'idle']).toContain(desk.syntheticPreviewStatus);
|
||||
}, 15000);
|
||||
|
||||
it('emits dirty-change when local definition diverges from saved snapshot', async () => {
|
||||
const wrapper = await mountPage();
|
||||
expect(wrapper.emitted('dirty-change')?.[0]).toEqual([false]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useOrderProfileXfaDesk', () => {
|
||||
beforeEach(() => {
|
||||
detailDefinition.value = structuredClone(baseDefinition);
|
||||
enqueueAutomarkMock.mockReset();
|
||||
enqueueAutomarkMock.mockResolvedValue({ job_id: 9, status: 'queued' });
|
||||
getAutomarkJobMock.mockReset();
|
||||
getAutomarkJobMock.mockResolvedValue({
|
||||
job_id: 9,
|
||||
status: 'succeeded',
|
||||
kind: 'visual_binding',
|
||||
candidates: [],
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
});
|
||||
messageErrorMock.mockReset();
|
||||
suggestUnifiedMappingMock.mockReset();
|
||||
authorizePreviewPagesMock.mockReset();
|
||||
authorizePreviewPagesMock.mockResolvedValue({
|
||||
document_id: 85,
|
||||
page_count: 1,
|
||||
pages: [{ page_no: 1, preview_token: 'token' }],
|
||||
expires_in_seconds: 60,
|
||||
});
|
||||
authorizePdfPreviewMock.mockReset();
|
||||
authorizePdfPreviewMock.mockResolvedValue({
|
||||
document_id: 85,
|
||||
preview_token: 'xfa-pdf-token',
|
||||
expires_in_seconds: 120,
|
||||
});
|
||||
vi.stubGlobal('fetch', vi.fn(async () => ({
|
||||
ok: true,
|
||||
blob: async () => new Blob(['png'], { type: 'image/png' }),
|
||||
})));
|
||||
});
|
||||
|
||||
it('demotes confirmed visual bindings when collections are reconfirmed', async () => {
|
||||
detailDefinition.value = {
|
||||
...structuredClone(baseDefinition),
|
||||
bindings: [{
|
||||
binding_id: 'b1',
|
||||
field_id: 'f1',
|
||||
field_code: 'customer_po_no',
|
||||
scope: 'header',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'invoiced-to-path', data_path: null },
|
||||
visual_binding: {
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
|
||||
source: 'user_drawn',
|
||||
status: 'confirmed',
|
||||
region_kind: 'field',
|
||||
confirmed_on: 'xfa_dataset_preview',
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
},
|
||||
}],
|
||||
};
|
||||
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52,
|
||||
leaseToken: 'lease',
|
||||
saveState: 'saved',
|
||||
editorSessionId: 'sess',
|
||||
enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: {
|
||||
plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { blocker: { authoritative_collection_required: 'need auth' }, loadFailed: 'fail' },
|
||||
xfaDesk: { collectionsReconfirmedHint: 'ok' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
} } } } })],
|
||||
},
|
||||
});
|
||||
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value && desk.definition.value) break;
|
||||
}
|
||||
expect(desk.definition.value).toBeTruthy();
|
||||
expect(desk.loadError.value).toBe(false);
|
||||
|
||||
desk.draftAuthoritativePathId.value = 'items-data';
|
||||
desk.draftMirrorPathIds.value = [];
|
||||
desk.confirmReconfirmCollections();
|
||||
expect(desk.authoritativePathId.value).toBe('items-data');
|
||||
expect(desk.definition.value?.bindings?.[0]?.visual_binding.status).toBe('suggested');
|
||||
}, 15000);
|
||||
|
||||
it('duplicateSelectedBinding clears path/schema and keeps geometry', async () => {
|
||||
detailDefinition.value = {
|
||||
...structuredClone(baseDefinition),
|
||||
bindings: [{
|
||||
binding_id: 'b1',
|
||||
field_id: 'f1',
|
||||
field_code: 'customer_po_no',
|
||||
scope: 'header',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'invoiced-to-path', data_path: null },
|
||||
visual_binding: {
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
|
||||
source: 'user_drawn',
|
||||
status: 'confirmed',
|
||||
region_kind: 'header',
|
||||
confirmed_on: 'xfa_dataset_preview',
|
||||
},
|
||||
}],
|
||||
};
|
||||
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52,
|
||||
leaseToken: 'lease',
|
||||
saveState: 'saved',
|
||||
editorSessionId: 'sess',
|
||||
enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: {
|
||||
plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
} } } } })],
|
||||
},
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value && desk.definition.value) break;
|
||||
}
|
||||
desk.selectedBindingId.value = 'b1';
|
||||
desk.duplicateSelectedBinding();
|
||||
const copy = desk.definition.value?.bindings?.find((item) => item.binding_id !== 'b1');
|
||||
expect(copy).toBeTruthy();
|
||||
expect(copy?.field_code).toBe('');
|
||||
expect(copy?.value_binding.path_id).toBe('');
|
||||
expect(copy?.visual_binding.status).toBe('suggested');
|
||||
expect((copy?.visual_binding as { region_kind?: string }).region_kind).toBe('header');
|
||||
expect(copy?.visual_binding.normalized_bbox).toEqual({ x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 });
|
||||
}, 15000);
|
||||
|
||||
it('annotationDisabled when native pages missing; datasets hidden for anchor', async () => {
|
||||
detailDefinition.value = structuredClone(baseDefinition);
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52,
|
||||
leaseToken: 'lease',
|
||||
saveState: 'saved',
|
||||
editorSessionId: 'sess',
|
||||
enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: {
|
||||
plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
} } } } })],
|
||||
},
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value && desk.definition.value) break;
|
||||
}
|
||||
// 原 PDF 授权就绪后,合成预览失败不应禁标注。
|
||||
desk.xfaPdfGrant.value = { document_id: 85, preview_token: 'token', expires_in_seconds: 120 };
|
||||
desk.pageLoadError.value = null;
|
||||
desk.syntheticPreviewStatus.value = 'unavailable';
|
||||
expect(desk.annotationDisabled.value).toBe(false);
|
||||
|
||||
desk.xfaPdfGrant.value = null;
|
||||
expect(desk.annotationDisabled.value).toBe(true);
|
||||
|
||||
desk.definition.value = {
|
||||
...desk.definition.value!,
|
||||
bindings: [{
|
||||
binding_id: 'anchor-1',
|
||||
field_id: 'a1',
|
||||
field_code: '',
|
||||
scope: 'header',
|
||||
value_binding: { type: 'xfa_dataset', path_id: '', data_path: null },
|
||||
visual_binding: {
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
|
||||
source: 'user_drawn',
|
||||
status: 'suggested',
|
||||
region_kind: 'anchor',
|
||||
},
|
||||
}],
|
||||
};
|
||||
desk.selectedBindingId.value = 'anchor-1';
|
||||
expect(desk.showDatasetsSection.value).toBe(false);
|
||||
}, 15000);
|
||||
|
||||
it('keeps XFA mapping ready but reports a native PDF page authorization failure', async () => {
|
||||
// 该 suite 保留多个 mounted desk;持续拒绝确保本用例的异步 loadPages 不会被旧实例抢先消费。
|
||||
authorizePdfPreviewMock.mockRejectedValue(new Error('PDF preview unavailable'));
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52,
|
||||
leaseToken: 'lease',
|
||||
saveState: 'saved',
|
||||
editorSessionId: 'sess',
|
||||
enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: {
|
||||
plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
} } } } })],
|
||||
},
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
// 断言:XFA 字段建模不依赖 synthetic preview;仅原生 PDF 页进入可重试失败态。
|
||||
expect(desk.definition.value).toBeTruthy();
|
||||
expect(desk.loadError.value).toBe(false);
|
||||
expect(desk.pageUnavailable.value).toBe(true);
|
||||
expect(desk.pageLoadError.value).toBe('native page unavailable');
|
||||
}, 15000);
|
||||
|
||||
it('uses the single-use XFA PDF grant instead of PDFium page grants', async () => {
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
workbench: { regionLabels: { order_field: '字段 {count}' } },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
expect(authorizePdfPreviewMock).toHaveBeenCalledWith(52, 85);
|
||||
expect(authorizePreviewPagesMock).not.toHaveBeenCalled();
|
||||
expect(desk.activeXfaPdfGrant.value?.preview_token).toBe('xfa-pdf-token');
|
||||
}, 15000);
|
||||
|
||||
it('creates a local XFA visual box immediately without requesting mapping suggestions', async () => {
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
workbench: { regionLabels: { order_field: '字段 {count}' } },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
await desk.onCanvasCreate({ x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 });
|
||||
|
||||
expect(suggestUnifiedMappingMock).not.toHaveBeenCalled();
|
||||
expect(desk.selectedBindingId.value).toBeTruthy();
|
||||
expect(desk.creationKind.value).toBeNull();
|
||||
expect(desk.canvasRegions.value).toEqual(expect.arrayContaining([expect.objectContaining({
|
||||
id: desk.selectedBindingId.value,
|
||||
kind: 'xfa_visual',
|
||||
pageNo: 1,
|
||||
region: { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
|
||||
visualBindingStatus: 'suggested',
|
||||
})]));
|
||||
}, 15000);
|
||||
|
||||
it('blocks saving a drawn XFA box until Schema and datasets bindings are completed', async () => {
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: {
|
||||
loadFailed: 'fail', pageUnavailable: 'native page unavailable',
|
||||
blocker: { incomplete_visual_binding: '请先完成每个手工视觉框的 Schema 字段和 datasets 路径绑定' },
|
||||
},
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
workbench: { regionLabels: { order_field: '字段 {count}' } },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
await desk.onCanvasCreate({ x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 });
|
||||
|
||||
await expect(desk.saveDraft()).resolves.toBe(false);
|
||||
expect(saveDraftMock).not.toHaveBeenCalled();
|
||||
expect(messageErrorMock).toHaveBeenCalledWith('请先完成每个手工视觉框的 Schema 字段和 datasets 路径绑定');
|
||||
}, 15000);
|
||||
|
||||
it('shows the OCR worker error code when an automark job fails', async () => {
|
||||
getAutomarkJobMock.mockResolvedValueOnce({
|
||||
job_id: 9,
|
||||
status: 'failed',
|
||||
error_code: 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_UNAVAILABLE',
|
||||
message: 'XFA native PDF OCR is unavailable',
|
||||
suggestions: [],
|
||||
});
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: '入队失败', jobFailed: '任务失败', jobFailedWithCode: '自动标记不可用({code}):{message}' },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
await expect(desk.startAutomarkJob()).rejects.toThrow('SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_UNAVAILABLE');
|
||||
expect(messageErrorMock).toHaveBeenCalledWith(
|
||||
'自动标记不可用(SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_UNAVAILABLE):XFA native PDF OCR is unavailable',
|
||||
);
|
||||
}, 15000);
|
||||
|
||||
it('projects XFA automark suggestions onto the shared canvas without persisting bindings', async () => {
|
||||
getAutomarkJobMock.mockResolvedValueOnce({
|
||||
job_id: 9,
|
||||
status: 'success',
|
||||
kind: 'visual_binding',
|
||||
candidates: [{
|
||||
suggestion_id: 'sugg-1',
|
||||
field_key: 'invoiced-to-path',
|
||||
field_code: 'customer_po_no',
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
|
||||
match_class: 'medium',
|
||||
suggestion_origin: 'ocr',
|
||||
confidence: 0.95,
|
||||
needs_review: false,
|
||||
}],
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
});
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: '入队失败', jobFailed: '任务失败' },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
expect(desk.activeXfaPdfGrant.value?.preview_token).toBe('xfa-pdf-token');
|
||||
await desk.startAutomarkJob();
|
||||
|
||||
// XFA 自动标注必须以 XFA desk 选定的 annotation sample 为输入,
|
||||
// 不允许退回到普通 PDF 表单的 documentId。
|
||||
expect(enqueueAutomarkMock).toHaveBeenCalledWith(52, expect.objectContaining({
|
||||
document_id: 85,
|
||||
page_no: 1,
|
||||
}));
|
||||
expect(desk.definition.value?.bindings).toHaveLength(0);
|
||||
expect(desk.canvasRegions.value).toEqual(expect.arrayContaining([expect.objectContaining({
|
||||
id: 'automark:sugg-1',
|
||||
kind: 'xfa_visual',
|
||||
pageNo: 1,
|
||||
region: { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
|
||||
visualBindingStatus: 'suggested',
|
||||
})]));
|
||||
}, 15000);
|
||||
|
||||
it('restores only unresolved persisted automark suggestions for the annotation document', async () => {
|
||||
detailDefinition.value = {
|
||||
...structuredClone(baseDefinition),
|
||||
xfa_ocr_automark: {
|
||||
job_id: 11,
|
||||
document_id: 85,
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
render_mode: 'native_pdf',
|
||||
suggestions: [
|
||||
{
|
||||
suggestion_id: 'open-suggestion',
|
||||
field_key: 'invoiced-to-path',
|
||||
field_code: 'customer_po_no',
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
|
||||
match_class: 'medium',
|
||||
},
|
||||
{
|
||||
suggestion_id: 'resolved-suggestion',
|
||||
field_key: 'invoiced-to-path',
|
||||
field_code: 'customer_po_no',
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.5, y0: 0.6, x1: 0.7, y1: 0.8 },
|
||||
decision: 'rejected',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: '入队失败', jobFailed: '任务失败' },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
expect(desk.autoMarkSuggestions.value.map((item) => item.suggestion_id)).toEqual(['open-suggestion']);
|
||||
expect(desk.canvasRegions.value.map((item) => item.id)).toContain('automark:open-suggestion');
|
||||
expect(desk.canvasRegions.value.map((item) => item.id)).not.toContain('automark:resolved-suggestion');
|
||||
expect(desk.definition.value?.bindings).toHaveLength(0);
|
||||
}, 15000);
|
||||
});
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileXfaWorkbench.vue
|
||||
用途:【已弃用】历史三栏 XFA Workbench 薄包装;正式 UI 由 OrderProfileEditorPage + useOrderProfileXfaDesk 承载。
|
||||
依赖:useOrderProfileXfaDesk。
|
||||
逻辑:仅暴露 saveDraft/reload 供遗留调用或冒烟测试;不再渲染独立三栏壳。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive } from 'vue';
|
||||
import { useOrderProfileXfaDesk } from './composables/useOrderProfileXfaDesk';
|
||||
|
||||
const props = defineProps<{
|
||||
profileId: number;
|
||||
leaseToken: string;
|
||||
saveState: 'saved' | 'saving' | 'failed' | 'readonly';
|
||||
editorSessionId: string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'dirty-change': [dirty: boolean];
|
||||
'save-request': [];
|
||||
'save-state-change': [state: 'saved' | 'saving' | 'failed' | 'readonly'];
|
||||
'profile-saved': [payload: { lockVersion: number }];
|
||||
'validate-blocked-change': [blocked: boolean];
|
||||
}>();
|
||||
|
||||
/**
|
||||
* 薄包装:复用统一 desk composable,不再自建三栏布局。
|
||||
*/
|
||||
const desk = reactive(useOrderProfileXfaDesk({
|
||||
profileId: computed(() => props.profileId),
|
||||
leaseToken: computed(() => props.leaseToken),
|
||||
saveState: computed(() => props.saveState),
|
||||
editorSessionId: computed(() => props.editorSessionId),
|
||||
enabled: computed(() => props.profileId > 0),
|
||||
onDirtyChange: (dirty) => emit('dirty-change', dirty),
|
||||
onSaveStateChange: (state) => emit('save-state-change', state),
|
||||
onProfileSaved: (payload) => emit('profile-saved', payload),
|
||||
onValidateBlockedChange: (blocked) => emit('validate-blocked-change', blocked),
|
||||
onSaveRequest: () => emit('save-request'),
|
||||
}));
|
||||
|
||||
defineExpose({
|
||||
saveDraft: () => desk.saveDraft(),
|
||||
reload: () => desk.load(),
|
||||
/** 测试用:暴露 desk 快照。 */
|
||||
getDesk: () => desk,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-workbench xfa-workbench--deprecated" data-testid="xfa-workbench-deprecated">
|
||||
<p v-if="desk.loading" class="loading">loading</p>
|
||||
<p v-else-if="desk.loadError" class="error">load-failed</p>
|
||||
<div v-else-if="desk.definition" class="xfa-workbench__desk xfa-workbench__desk--thin">
|
||||
<main class="xfa-workbench__canvas" data-testid="xfa-thin-canvas">
|
||||
<span>{{ desk.previewMode }}</span>
|
||||
<span>{{ desk.syntheticPreviewStatus }}</span>
|
||||
</main>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-workbench { display: flex; flex-direction: column; gap: 8px; }
|
||||
.xfa-workbench__desk--thin { display: block; }
|
||||
.loading, .error { padding: 16px; }
|
||||
</style>
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/canvasActions.utils.spec.ts
|
||||
* 用途:验证共享画布操作 adapter 的能力选择与事件转发。
|
||||
* 依赖:Vitest、canvasActions.utils。
|
||||
* 逻辑:编辑页按 Profile capability 选择 adapter;画布事件不再分别编排 XFA 与坐标流程。
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
resolveCanvasActions,
|
||||
resolveDeskAdapter,
|
||||
resolveSharedCanvasDocument,
|
||||
resolveValueAdapterKey,
|
||||
type OrderProfileCanvasActions,
|
||||
} from './canvasActions.utils';
|
||||
|
||||
function actions(): OrderProfileCanvasActions {
|
||||
return {
|
||||
create: vi.fn(), select: vi.fn(), dragStart: vi.fn(), dragEnd: vi.fn(), change: vi.fn(),
|
||||
undo: vi.fn(), redo: vi.fn(), duplicate: vi.fn(), remove: vi.fn(), page: vi.fn(), draw: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
describe('resolveCanvasActions', () => {
|
||||
it('selects one capability adapter for the entire shared canvas interaction', () => {
|
||||
const coordinate = actions();
|
||||
const xfa = actions();
|
||||
|
||||
const active = resolveCanvasActions({
|
||||
adapterKey: 'xfa_dataset', adapters: { coordinate_ocr: coordinate, xfa_dataset: xfa },
|
||||
});
|
||||
active.select('binding-1');
|
||||
active.undo();
|
||||
active.page(2);
|
||||
|
||||
expect(xfa.select).toHaveBeenCalledWith('binding-1');
|
||||
expect(xfa.undo).toHaveBeenCalledOnce();
|
||||
expect(xfa.page).toHaveBeenCalledWith(2);
|
||||
expect(coordinate.select).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('selects one desk adapter before shared save and sample lifecycle work begins', () => {
|
||||
const coordinate = { kind: 'coordinate', save: vi.fn() };
|
||||
const xfa = { kind: 'xfa', save: vi.fn() };
|
||||
|
||||
const active = resolveDeskAdapter({
|
||||
adapterKey: 'xfa_dataset', adapters: { coordinate_ocr: coordinate, xfa_dataset: xfa },
|
||||
});
|
||||
|
||||
expect(active).toBe(xfa);
|
||||
});
|
||||
|
||||
it('uses one editor-owned preview context without branching on the value adapter', () => {
|
||||
expect(resolveSharedCanvasDocument({
|
||||
documentId: 12,
|
||||
mainTableId: '',
|
||||
sampleTableId: 'table-1',
|
||||
})).toEqual({ documentId: 12, tableId: 'table-1' });
|
||||
expect(resolveSharedCanvasDocument({
|
||||
documentId: 12,
|
||||
mainTableId: 'visual-main-table',
|
||||
sampleTableId: 'table-1',
|
||||
})).toEqual({ documentId: 12, tableId: 'visual-main-table' });
|
||||
});
|
||||
|
||||
it('keeps the shared save shell independent from XFA confirmation-token naming', async () => {
|
||||
const saved = vi.fn().mockResolvedValue(true);
|
||||
const adapter = {
|
||||
hasUnsavedChanges: true,
|
||||
skipUnchangedManualSave: true,
|
||||
canSave: true,
|
||||
canValidate: false,
|
||||
exportDefinition: vi.fn(() => ({
|
||||
template_mode: 'xfa_dataset',
|
||||
source_contract: {},
|
||||
header_mappings: [],
|
||||
line_mapping: { fields: [] },
|
||||
cross_checks: [],
|
||||
main_table_id: 'table-1',
|
||||
bindings: [],
|
||||
})),
|
||||
buildPayload: vi.fn(() => ({
|
||||
definition: { template_mode: 'xfa_dataset' },
|
||||
splitRuleConfirmationTokens: { path_1: 'token_1' },
|
||||
})),
|
||||
applySavedDraft: saved,
|
||||
};
|
||||
|
||||
const payload = adapter.buildPayload();
|
||||
expect(payload?.splitRuleConfirmationTokens).toEqual({ path_1: 'token_1' });
|
||||
expect(adapter.exportDefinition()).toMatchObject({ template_mode: 'xfa_dataset' });
|
||||
expect(adapter.canValidate).toBe(false);
|
||||
await adapter.applySavedDraft({ id: 1 });
|
||||
expect(saved).toHaveBeenCalledWith({ id: 1 });
|
||||
});
|
||||
|
||||
it('resolves persisted format only at the adapter boundary', () => {
|
||||
expect(resolveValueAdapterKey({ template_mode: 'xfa_dataset' } as any)).toBe('xfa_dataset');
|
||||
expect(resolveValueAdapterKey({ template_mode: 'coordinate' } as any)).toBe('coordinate_ocr');
|
||||
});
|
||||
});
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/canvasActions.utils.ts
|
||||
* 用途:为订单模板共享 PDF 画布提供 capability-neutral 的操作接口。
|
||||
* 依赖:OrderProfileEditorPage 的末端值源 adapter。
|
||||
* 逻辑:页面按已持久化的模板能力选择一次 adapter;画布组件与工具栏只调用同一组动作。
|
||||
*/
|
||||
import type { OrderProfileCanvasRegion, OrderProfileRelativeRegion } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { OrderProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { ShippingOrderDocumentProfile } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { OrderProfileRecognitionResult } from './orderProfileForm.utils';
|
||||
|
||||
/** 共享画布需要的最小动作面;底层可以持有不同 adapter 的持久化载体。 */
|
||||
export interface OrderProfileCanvasActions {
|
||||
create(region: OrderProfileRelativeRegion): void | Promise<void>;
|
||||
select(id: string): void;
|
||||
dragStart(id: string): void;
|
||||
dragEnd(): void;
|
||||
change(id: string, region: OrderProfileRelativeRegion): void;
|
||||
undo(): void;
|
||||
redo(): void;
|
||||
duplicate(): void;
|
||||
remove(): void;
|
||||
page(pageNo: number): void;
|
||||
draw(kind: OrderProfileCanvasRegion['kind']): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 共享 Editor 消费的视觉画布状态。
|
||||
*
|
||||
* 取值 adapter 可以使用不同的持久化载体,但在
|
||||
* 进入 Editor 后都必须投影为这一份视觉状态。这样 PDF 预览、工具栏和 DocumentCanvas
|
||||
* 不再知道模板模式,更不能因此分出第二套交互生命周期。
|
||||
*/
|
||||
export interface OrderProfileVisualCanvasAdapter {
|
||||
actions: OrderProfileCanvasActions;
|
||||
documentReady: boolean;
|
||||
preview: { document_id: number; preview_token: string; expires_in_seconds: number } | null;
|
||||
previewPagePath: string;
|
||||
regions: OrderProfileCanvasRegion[];
|
||||
selectedRegionId: string | null;
|
||||
creationKind: OrderProfileCanvasRegion['kind'] | null;
|
||||
pageNo: number;
|
||||
pageCount: number;
|
||||
saveDisabled: boolean;
|
||||
autoSuggestDisabled: boolean;
|
||||
emptyHint: string | null;
|
||||
loadError: string | null;
|
||||
undoDisabled: boolean;
|
||||
redoDisabled: boolean;
|
||||
duplicateDisabled: boolean;
|
||||
deleteDisabled: boolean;
|
||||
setRenderedPageCount(count: number): void;
|
||||
hasSelection: boolean;
|
||||
selectedKindLabel: string;
|
||||
selectedGeometry: string;
|
||||
activePageHasLines: boolean;
|
||||
headerRecognitionResults: OrderProfileRecognitionResult[];
|
||||
lineRecognitionResults: OrderProfileRecognitionResult[];
|
||||
/** 共同画布状态与动作;错误语义由 adapter 投影,Editor 不再判断模板模式。 */
|
||||
canvasReadonly: boolean;
|
||||
warningVisible: boolean;
|
||||
warningText: string | null;
|
||||
retryCanvas(): void;
|
||||
reportCanvasLoadFailed(): void;
|
||||
applyAutomarkCandidates(candidates: Array<Record<string, unknown>>): boolean;
|
||||
canRender: boolean;
|
||||
retryLabel: string;
|
||||
acceptSuggestion(): void;
|
||||
rejectSuggestion(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 共享草稿保存 adapter。
|
||||
*
|
||||
* Editor 统一负责租约、乐观锁、Revision 保存和失败恢复;adapter 只把当前视觉标注
|
||||
* 转为其正式值源所需的 definition,并在服务端返回后消费该 adapter 的附加证据。
|
||||
*/
|
||||
export interface OrderProfileDraftSaveAdapter {
|
||||
hasUnsavedChanges: boolean;
|
||||
skipUnchangedManualSave: boolean;
|
||||
canSave: boolean;
|
||||
canValidate: boolean;
|
||||
exportDefinition(): OrderProfileDefinition | null;
|
||||
buildPayload(visualDefinition: OrderProfileDefinition): {
|
||||
definition: OrderProfileDefinition;
|
||||
splitRuleConfirmationTokens?: Record<string, string>;
|
||||
allowFormalBindingDeletions?: string[];
|
||||
} | null;
|
||||
applySavedDraft(saved: unknown): Promise<boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 Profile 的末端值源 capability key。
|
||||
* 编辑器只消费这个 capability,不得直接依据 PDF/XFA 格式分叉流程。
|
||||
*/
|
||||
export function resolveValueAdapterKey(profile: ShippingOrderDocumentProfile | null): string {
|
||||
return profile?.template_mode === 'xfa_dataset' ? 'xfa_dataset' : 'coordinate_ocr';
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回当前 Profile 的唯一画布动作 adapter。
|
||||
* 核心逻辑:选择只依据末端值源的 capability key;其后画布事件不再识别文件格式。
|
||||
* @param options.adapterKey - 已持久化的末端值源 capability key。
|
||||
* @param options.adapters - 各值源的画布状态 adapter。
|
||||
* @returns 当前画布应使用的统一动作集合。
|
||||
*/
|
||||
export function resolveCanvasActions(options: {
|
||||
adapterKey: string;
|
||||
adapters: Record<string, OrderProfileCanvasActions>;
|
||||
}): OrderProfileCanvasActions {
|
||||
const adapter = options.adapters[options.adapterKey];
|
||||
if (!adapter) throw new Error(`Unsupported order-profile value adapter: ${options.adapterKey}`);
|
||||
return adapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回共享编辑器壳层当前唯一的值源 desk adapter。
|
||||
* 核心逻辑:保存、样本上下文和自动标记 Job 由壳层统一编排;adapter 只生成
|
||||
* payload 或应用取值专属结果,避免这些公共生命周期再次分为 XFA/PDF 两条路径。
|
||||
*/
|
||||
export function resolveDeskAdapter<T>(options: {
|
||||
adapterKey: string;
|
||||
adapters: Record<string, T>;
|
||||
}): T {
|
||||
const adapter = options.adapters[options.adapterKey];
|
||||
if (!adapter) throw new Error(`Unsupported order-profile value adapter: ${options.adapterKey}`);
|
||||
return adapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回唯一由 Editor 消费的 PDF 画布文档上下文。
|
||||
* 核心逻辑:所有 Profile 先使用共同冻结的 annotation document + main_table_id;
|
||||
* 历史草稿缺失 main_table_id 时才回退样本 table_id。预览授权、页码和 PDF.js 渲染始终
|
||||
* 由共享 Editor 持有,值源 adapter 不得参与上下文选择。
|
||||
* @param options.documentId - 共同 annotation 文档身份。
|
||||
* @param options.mainTableId - definition 中冻结的共同视觉主表。
|
||||
* @param options.sampleTableId - 历史样本的兼容回退表身份。
|
||||
* @returns 共享画布唯一使用的文档和表身份。
|
||||
*/
|
||||
export function resolveSharedCanvasDocument(options: {
|
||||
documentId: number;
|
||||
mainTableId: string;
|
||||
sampleTableId: string;
|
||||
}): { documentId: number; tableId: string } {
|
||||
return {
|
||||
documentId: options.documentId,
|
||||
tableId: options.mainTableId || options.sampleTableId,
|
||||
};
|
||||
}
|
||||
+1
-1
@@ -32,7 +32,7 @@ const filters = reactive({
|
||||
createdTo: "",
|
||||
});
|
||||
|
||||
const VISUAL_EVENT_PREFIXES = ["xfa_visual_binding_", "xfa_split_", "order_profile_unified_migration_"];
|
||||
const VISUAL_EVENT_PREFIXES = ["xfa_split_", "order_profile_unified_migration_"];
|
||||
|
||||
/**
|
||||
* 判断是否为统一视觉 / 拆分 / 迁移审计事件。
|
||||
|
||||
+1
-1
@@ -63,7 +63,7 @@ describe('OrderProfileDocumentCanvas PDF preview', () => {
|
||||
profileId: 71,
|
||||
pdfPreview: { preview_token: 'single-use-token' },
|
||||
regions: [{
|
||||
id: 'automark:sugg-1', kind: 'xfa_visual', label: '自动标注', pageNo: 1,
|
||||
id: 'automark:sugg-1', kind: 'order_field', label: '自动标注', pageNo: 1,
|
||||
region: { x0: .5, y0: .5, x1: .75, y1: .75 },
|
||||
}],
|
||||
pageNo: 1,
|
||||
|
||||
-14
@@ -55,8 +55,6 @@ const props = defineProps<{
|
||||
pendingSuggestionCount?: number;
|
||||
orderFieldValues?: Record<string, string | null>;
|
||||
orderFieldValueState?: 'idle' | 'loading' | 'ready' | 'failed';
|
||||
/** full=坐标全工具;xfa_visual=仅 XFA 画框。 */
|
||||
annotationToolSet?: 'full' | 'xfa_visual';
|
||||
/** 无图时空态文案;缺省为「选择已绑定的 PDF 样本」。 */
|
||||
emptyHint?: string | null;
|
||||
/** 外部注入的页加载错误(如 XFA page_unavailable);优先于空态提示。 */
|
||||
@@ -64,7 +62,6 @@ const props = defineProps<{
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const readonlyMode = computed(() => props.mode === 'readonly');
|
||||
const xfaVisualTools = computed(() => props.annotationToolSet === 'xfa_visual');
|
||||
const emit = defineEmits<{
|
||||
select: [regionId: string];
|
||||
start: [regionId: string];
|
||||
@@ -278,10 +275,6 @@ const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
|
||||
return `${region.label} · ${region.recognizedValue || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable')}`;
|
||||
}
|
||||
if (region.kind !== 'order_field') {
|
||||
if (region.kind === 'xfa_visual' && region.visualBindingStatus) {
|
||||
const statusKey = `admin.shippingOrderProfiles.xfaUnified.visualStatus.${region.visualBindingStatus}`;
|
||||
return `${region.label} · ${t(statusKey)}`;
|
||||
}
|
||||
return region.label;
|
||||
}
|
||||
const state = props.orderFieldValueState || 'idle';
|
||||
@@ -365,10 +358,6 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
<div v-else-if="!imageUrl && !pdfRendered && !pdfPreview" class="canvas-state">{{ emptyStateText }}</div>
|
||||
<div v-else class="canvas-work-area" :class="{ readonly: readonlyMode }">
|
||||
<aside v-if="!readonlyMode" class="annotation-tools">
|
||||
<template v-if="xfaVisualTools">
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.xfaUnified.drawFieldBox')" :title="t('admin.shippingOrderProfiles.xfaUnified.drawFieldBox')" :class="{ active: creationKind === 'xfa_visual' }" @click="emit('draw', 'xfa_visual')"><TextCursorInput /></button>
|
||||
</template>
|
||||
<template v-else>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawDocumentMatchAnchorShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawDocumentMatchAnchorShortcut')" :class="{ active: creationKind === 'document_anchor_label' || creationKind === 'document_anchor_value' }" @click="emit('draw', 'document_anchor_label')"><Anchor /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawOrderAnchorShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawOrderAnchorShortcut')" :class="{ active: creationKind === 'order_anchor' }" @click="emit('draw', 'order_anchor')"><Tag /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawOrderFieldShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawOrderFieldShortcut')" :class="{ active: creationKind === 'order_field' }" @click="emit('draw', 'order_field')"><TextCursorInput /></button>
|
||||
@@ -377,7 +366,6 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawFieldShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawFieldShortcut')" :class="{ active: creationKind === 'field' }" @click="emit('draw', 'field')"><Columns3 /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawExclusionShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawExclusionShortcut')" :class="{ active: creationKind === 'exclusion' }" @click="emit('draw', 'exclusion')"><Eraser /></button>
|
||||
<button type="button" class="suggest" :aria-label="t('admin.shippingOrderProfiles.workbench.autoSuggestShortcut')" :title="t('admin.shippingOrderProfiles.workbench.autoSuggestShortcut')" :disabled="autoSuggestDisabled || suggesting" @click="emit('suggest')"><WandSparkles /></button>
|
||||
</template>
|
||||
<p v-if="suggestionProgress" class="suggestion-progress" :class="{ failed: !suggesting }">{{ suggestionProgress }}</p>
|
||||
</aside>
|
||||
<div ref="viewport" class="canvas-viewport" :class="{ panning: !creationKind || readonlyMode }" @wheel.prevent="handleWheel">
|
||||
@@ -508,8 +496,6 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
.line-hit-w { left: -6px; }
|
||||
.region-exclusion { z-index: 3; border-style: dashed; border-color: #f87171; background: rgb(248 113 113 / .1); }
|
||||
.region-exclusion .region-label, .region-exclusion .resize-handle { background: #b91c1c; }
|
||||
.region-xfa_visual { z-index: 2; border: 1.5px solid #38bdf8; background: rgb(14 165 233 / .12); }
|
||||
.region-xfa_visual .region-label, .region-xfa_visual .resize-handle { background: #0369a1; }
|
||||
.region-visual--suggested { border-style: dashed; border-color: #f59e0b; background: rgb(245 158 11 / .14); }
|
||||
.region-visual--suggested .region-label { background: #b45309; }
|
||||
.region-visual--confirmed { border-color: #22c55e; background: rgb(34 197 94 / .12); }
|
||||
|
||||
+4
-8
@@ -2,7 +2,8 @@
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileReadOnlyCanvas.vue
|
||||
用途:在版本详情页展示基于冻结样本绑定的只读画布。
|
||||
依赖:冻结样本预览 API、OrderProfileDocumentCanvas、冻结证据面板。
|
||||
逻辑:只允许 annotation/training 样本进入普通画布;blind_test 继续留在摘要层,不进入样本选择器。
|
||||
逻辑:所有模板共用 annotation/training 冻结样本画布;XFA datasets 映射仅作为侧栏证据,
|
||||
blind_test 继续留在摘要层,不进入样本选择器。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
@@ -22,17 +23,12 @@ import OrderProfileDocumentCanvas from './OrderProfileDocumentCanvas.vue';
|
||||
import OrderProfileFrozenEvidencePanel from './OrderProfileFrozenEvidencePanel.vue';
|
||||
import XfaReadOnlyMapping from './XfaReadOnlyMapping.vue';
|
||||
import { buildOrderProfileReadonlyRegions } from '../orderProfileReadonlyCanvas.utils';
|
||||
import { isXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const props = defineProps<{
|
||||
detail: ShippingOrderDocumentProfile;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const isXfa = computed(() => (
|
||||
props.detail.template_mode === 'xfa_dataset'
|
||||
|| isXfaDatasetProfileDefinition(props.detail.definition)
|
||||
));
|
||||
const loading = ref(false);
|
||||
const errorMessage = ref('');
|
||||
const selectedSampleId = ref<number | null>(null);
|
||||
@@ -144,8 +140,7 @@ watch([selectedSampleId, pageNo], () => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<XfaReadOnlyMapping v-if="isXfa" :detail="detail" />
|
||||
<section v-else class="readonly-layout">
|
||||
<section class="readonly-layout">
|
||||
<div v-if="!immutable" class="state-card">
|
||||
{{ t('admin.shippingOrderProfiles.versionCenter.draftCanvasHint') }}
|
||||
</div>
|
||||
@@ -184,6 +179,7 @@ watch([selectedSampleId, pageNo], () => {
|
||||
/>
|
||||
<div class="side-panel">
|
||||
<OrderProfileFrozenEvidencePanel :sample="selectedSample" />
|
||||
<XfaReadOnlyMapping :detail="detail" />
|
||||
<section class="panel">
|
||||
<h3>{{ t('admin.shippingOrderProfiles.versionCenter.regionSummaryTitle') }}</h3>
|
||||
<p v-if="diagnosticsLoading" class="diagnostic-state">{{ t('admin.shippingOrderProfiles.versionCenter.regionDiagnosticsLoading') }}</p>
|
||||
|
||||
+8
-35
@@ -8,7 +8,6 @@
|
||||
import { computed } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { ShippingOrderDocumentProfile } from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
import { isXfaDatasetProfileDefinition } from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
|
||||
const props = defineProps<{
|
||||
detail: ShippingOrderDocumentProfile;
|
||||
@@ -16,14 +15,8 @@ const props = defineProps<{
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
/** XFA 版本概览展示结构身份与路径映射规模,不展示坐标表区域指标。 */
|
||||
const isXfa = computed(() => (
|
||||
props.detail.template_mode === "xfa_dataset"
|
||||
|| isXfaDatasetProfileDefinition(props.detail.definition)
|
||||
|| props.detail.definition_stats?.template_mode === "xfa_dataset"
|
||||
));
|
||||
|
||||
const xfaIdentity = computed(() => props.detail.xfa_structure_identity || null);
|
||||
/** 末端值源证据由服务端 adapter 作为可选摘要投影,公共概览不判断模板模式。 */
|
||||
const valueSourceIdentity = computed(() => props.detail.value_source_identity || null);
|
||||
|
||||
const formatDateTime = (value?: string | null) =>
|
||||
value ? new Date(value).toLocaleString() : "-";
|
||||
@@ -50,11 +43,6 @@ const testStatusLabel = computed(() => {
|
||||
return t(`admin.shippingOrderProfiles.versionCenter.testStatus.${status}`);
|
||||
});
|
||||
|
||||
const templateModeLabel = computed(() => (
|
||||
isXfa.value
|
||||
? t("admin.shippingOrderProfiles.versionCenter.templateModeXfa")
|
||||
: t("admin.shippingOrderProfiles.versionCenter.templateModeCoordinate")
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -68,7 +56,6 @@ const templateModeLabel = computed(() => (
|
||||
</div>
|
||||
<div class="hero-meta">
|
||||
<span class="meta-chip meta-chip--status" :class="statusClass">{{ statusLabel }}</span>
|
||||
<span class="meta-chip">{{ templateModeLabel }}</span>
|
||||
<span class="meta-chip">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.schemaVersion") }}
|
||||
{{ detail.schema_summary?.version ?? "-" }}
|
||||
@@ -84,21 +71,7 @@ const templateModeLabel = computed(() => (
|
||||
<div class="summary-grid">
|
||||
<article class="summary-card">
|
||||
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.definitionStats") }}</h3>
|
||||
<dl v-if="isXfa">
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.headerMappings") }}</dt>
|
||||
<dd>{{ detail.definition_stats?.header_mapping_count || 0 }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.lineMappings") }}</dt>
|
||||
<dd>{{ detail.definition_stats?.line_mapping_count || 0 }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.mirrorCollections") }}</dt>
|
||||
<dd>{{ detail.definition_stats?.mirror_collection_count || 0 }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<dl v-else>
|
||||
<dl>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.tableRegions") }}</dt>
|
||||
<dd>{{ detail.definition_stats?.table_region_count || 0 }}</dd>
|
||||
@@ -118,24 +91,24 @@ const templateModeLabel = computed(() => (
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
<article v-if="isXfa && xfaIdentity" class="summary-card">
|
||||
<article v-if="valueSourceIdentity" class="summary-card">
|
||||
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.xfaStructureIdentity") }}</h3>
|
||||
<dl>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.xfaTemplateChecksum") }}</dt>
|
||||
<dd>{{ xfaIdentity.template_packet_checksum || "-" }}</dd>
|
||||
<dd>{{ valueSourceIdentity.template_packet_checksum || "-" }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.xfaDatasetFingerprint") }}</dt>
|
||||
<dd>{{ xfaIdentity.dataset_structure_fingerprint || "-" }}</dd>
|
||||
<dd>{{ valueSourceIdentity.dataset_structure_fingerprint || "-" }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.xfaAuthoritativeCollection") }}</dt>
|
||||
<dd>{{ xfaIdentity.has_authoritative_collection ? t("common.yes") : t("common.no") }}</dd>
|
||||
<dd>{{ valueSourceIdentity.has_authoritative_collection ? t("common.yes") : t("common.no") }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.mirrorCollections") }}</dt>
|
||||
<dd>{{ xfaIdentity.mirror_collection_count ?? 0 }}</dd>
|
||||
<dd>{{ valueSourceIdentity.mirror_collection_count ?? 0 }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
-115
@@ -1,115 +0,0 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/OrderProfileXfaConfirmStep.spec.ts
|
||||
* 用途:验证 XFA 集合候选在未选择权威集合时仍可见,且真正无候选时才显示空状态。
|
||||
* 依赖:Vitest、@vue/test-utils、OrderProfileXfaConfirmStep 及其 XFA API。
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import OrderProfileXfaConfirmStep from './OrderProfileXfaConfirmStep.vue';
|
||||
|
||||
const { getFieldTree, getCollections, reparseSample } = vi.hoisted(() => ({
|
||||
getFieldTree: vi.fn(),
|
||||
getCollections: vi.fn(),
|
||||
reparseSample: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
|
||||
getOrderProfileSampleXfaFieldTree: getFieldTree,
|
||||
getOrderProfileSampleXfaCollections: getCollections,
|
||||
reparseOrderProfileSampleLayout: reparseSample,
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
wizard: {
|
||||
sampleSelected: '已选样本',
|
||||
xfa: {
|
||||
loading: '加载中',
|
||||
loadErrorTitle: '加载失败',
|
||||
loadErrorHint: '请重试',
|
||||
reload: '重新加载',
|
||||
reparseSample: '重新解析样本',
|
||||
noCollections: '没有可用数据集',
|
||||
intro: 'XFA',
|
||||
noBlankPdf: '不使用空白 PDF',
|
||||
scriptNotice: '不会执行脚本',
|
||||
},
|
||||
},
|
||||
xfaUnified: { createBlockersTitle: '创建前阻断项' },
|
||||
xfaWorkbench: {
|
||||
collectionsTitle: '集合',
|
||||
collectionEvidenceHint: '证据',
|
||||
authoritativeCollection: '权威集合',
|
||||
mirrorCollections: '镜像集合',
|
||||
recommendedAuthoritative: '推荐权威',
|
||||
selectedAuthoritative: '已选权威',
|
||||
rowCount: '{count} 行',
|
||||
nonEmptyCoverage: '{filled}/{total} {percent}',
|
||||
excludedCollections: '排除集合 {count}',
|
||||
allCandidatesExcluded: '全部被排除',
|
||||
emptyStructureReason: '空结构',
|
||||
collectionReason: { data_description_structure: '结构描述', empty_structure: '空结构' },
|
||||
},
|
||||
xfa: { documentKinds: { xfa_hybrid: 'XFA 动态表单' } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const sample = {
|
||||
document_id: 132,
|
||||
intake_id: 1,
|
||||
intake_no: 'INT-1',
|
||||
filename: '4510039227.pdf',
|
||||
table_count: 0,
|
||||
document_kind: 'xfa_hybrid',
|
||||
xfa_analysis_ready: true,
|
||||
purpose: 'order_document_profile_sample' as const,
|
||||
parse_status: 'ready',
|
||||
is_template_sample: true,
|
||||
can_delete: true,
|
||||
};
|
||||
|
||||
function mountStep() {
|
||||
return mount(OrderProfileXfaConfirmStep, {
|
||||
global: { plugins: [i18n] },
|
||||
props: { documentId: 132, sample, authoritativePathId: '', mirrorPathIds: [] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('OrderProfileXfaConfirmStep', () => {
|
||||
it('未选择权威集合时仍显示可选数据集', async () => {
|
||||
getFieldTree.mockResolvedValue({ tree: {} });
|
||||
getCollections.mockResolvedValue({
|
||||
collection_candidates: [{
|
||||
path_id: 'items', collection_path_hash: 'h1', row_count: 1,
|
||||
path_label: 'datasets / data / ITEMS / DATA', field_names: ['MATNR'],
|
||||
field_count: 1, non_empty_field_count: 1, non_empty_rate: 1,
|
||||
sample_fields: [{ field_name: 'MATNR', display_value: 'TEMP-S', display_policy: 'partial' }],
|
||||
selectable: true, recommended_role: 'authoritative',
|
||||
}],
|
||||
excluded_collection_candidates: [],
|
||||
});
|
||||
|
||||
const wrapper = mountStep();
|
||||
await vi.waitFor(() => expect(wrapper.text()).toContain('datasets / data / ITEMS / DATA'), { timeout: 10000 });
|
||||
expect(wrapper.find('input[type="radio"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('创建前阻断项');
|
||||
}, 15000);
|
||||
|
||||
it('没有任何候选集合时才显示空状态', async () => {
|
||||
getFieldTree.mockResolvedValue({ tree: {} });
|
||||
getCollections.mockResolvedValue({ collection_candidates: [], excluded_collection_candidates: [] });
|
||||
|
||||
const wrapper = mountStep();
|
||||
await vi.waitFor(() => expect(wrapper.text()).toContain('没有可用数据集'), { timeout: 10000 });
|
||||
expect(wrapper.find('input[type="radio"]').exists()).toBe(false);
|
||||
}, 15000);
|
||||
});
|
||||
-227
@@ -1,227 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileXfaConfirmStep.vue
|
||||
用途:创建向导第三步——XFA 样本结构与明细集合确认(不要求 table_id)。
|
||||
依赖:XFA collections/field-tree API、layout-reparse API、XfaCollectionSelector、vue-i18n。
|
||||
逻辑:父级传入 documentId 与 v-model 集合 path_id;加载失败以独立错误态阻断创建,
|
||||
区分「无合格集合」与「分析不可用」;重新解析需二次确认且不自动触发。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
getOrderProfileSampleXfaCollections,
|
||||
getOrderProfileSampleXfaFieldTree,
|
||||
reparseOrderProfileSampleLayout,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type { OrderProfileSampleDocument } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { flattenXfaTreeNodes } from '../xfaProfileMapping.utils';
|
||||
import XfaCollectionSelector from './XfaCollectionSelector.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
documentId: number;
|
||||
sample?: OrderProfileSampleDocument | null;
|
||||
authoritativePathId: string;
|
||||
mirrorPathIds: string[];
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
'update:authoritativePathId': [value: string];
|
||||
'update:mirrorPathIds': [value: string[]];
|
||||
/** 加载失败态变化:父级须据此阻断创建按钮 */
|
||||
'update:contextReady': [value: boolean];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const message = useMessage();
|
||||
const loading = ref(false);
|
||||
const reparsing = ref(false);
|
||||
const loadError = ref<{ code?: string; message: string } | null>(null);
|
||||
const collections = ref<Awaited<ReturnType<typeof getOrderProfileSampleXfaCollections>> | null>(null);
|
||||
const flatNodes = ref(flattenXfaTreeNodes(null));
|
||||
const excludedCollections = computed(() => collections.value?.excluded_collection_candidates || []);
|
||||
const contextReady = computed(() => !loading.value && !loadError.value && collections.value != null);
|
||||
|
||||
/**
|
||||
* 创建草稿前的阻断摘要(权威集合必选等);加载失败时不计入“无集合”。
|
||||
*/
|
||||
const createBlockers = computed(() => {
|
||||
if (loadError.value || !collections.value) return [];
|
||||
const items: string[] = [];
|
||||
const selectable = (collections.value.collection_candidates || []).filter((item) => item.selectable !== false);
|
||||
if (!props.authoritativePathId && selectable.length) {
|
||||
items.push(t('admin.shippingOrderProfiles.xfaWorkbench.blocker.authoritative_collection_required'));
|
||||
}
|
||||
if (!selectable.length && !props.authoritativePathId) {
|
||||
items.push(t('admin.shippingOrderProfiles.xfaWorkbench.allCandidatesExcluded'));
|
||||
}
|
||||
return items;
|
||||
});
|
||||
|
||||
const documentKindLabel = computed(() => {
|
||||
const kind = props.sample?.document_kind || collections.value?.document_kind || 'xfa_hybrid';
|
||||
return t(`admin.shippingOrderProfiles.xfa.documentKinds.${kind}`, kind);
|
||||
});
|
||||
|
||||
/**
|
||||
* 将 BusinessError 映射为用户可见文案(优先四语言 errors.codes)。
|
||||
* @param error - 捕获异常
|
||||
*/
|
||||
function resolveLoadErrorMessage(error: unknown): { code?: string; message: string } {
|
||||
if (error instanceof BusinessError) {
|
||||
const code = String(error.code || '').trim() || undefined;
|
||||
return {
|
||||
code,
|
||||
message: resolveLocalizedErrorMessage(code, error.message)
|
||||
|| t('admin.shippingOrderProfiles.wizard.xfa.loadFailed'),
|
||||
};
|
||||
}
|
||||
return { message: t('admin.shippingOrderProfiles.wizard.xfa.loadFailed') };
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载 XFA 集合候选与字段树(用于展示标签)。
|
||||
* 核心逻辑:并发请求;失败写入 loadError 且清空 collections,禁止误显示“没有集合”。
|
||||
*/
|
||||
async function loadXfaContext(): Promise<void> {
|
||||
if (!props.documentId) return;
|
||||
loading.value = true;
|
||||
loadError.value = null;
|
||||
collections.value = null;
|
||||
flatNodes.value = flattenXfaTreeNodes(null);
|
||||
emit('update:contextReady', false);
|
||||
try {
|
||||
const [treeResp, collectionResp] = await Promise.all([
|
||||
getOrderProfileSampleXfaFieldTree(props.documentId),
|
||||
getOrderProfileSampleXfaCollections(props.documentId),
|
||||
]);
|
||||
collections.value = collectionResp;
|
||||
flatNodes.value = flattenXfaTreeNodes(
|
||||
treeResp.tree as import('@/features/admin/types/shipping-order-document-profile.types').XfaFieldTreeNode,
|
||||
);
|
||||
if (!props.authoritativePathId && collectionResp.collection_candidates.length === 1) {
|
||||
const only = collectionResp.collection_candidates[0];
|
||||
if (only?.path_id) emit('update:authoritativePathId', only.path_id);
|
||||
}
|
||||
emit('update:contextReady', true);
|
||||
} catch (error) {
|
||||
loadError.value = resolveLoadErrorMessage(error);
|
||||
message.error(loadError.value.message);
|
||||
emit('update:contextReady', false);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅重新请求字段树与集合(不触发样本重新解析)。
|
||||
*/
|
||||
async function reloadContext(): Promise<void> {
|
||||
await loadXfaContext();
|
||||
}
|
||||
|
||||
/**
|
||||
* 独立“重新解析样本”:二次确认后调用 layout-reparse;成功后提示用户再点重新加载。
|
||||
*/
|
||||
async function reparseSample(): Promise<void> {
|
||||
if (!props.documentId || reparsing.value) return;
|
||||
const ok = window.confirm(t('admin.shippingOrderProfiles.wizard.xfa.reparseConfirm'));
|
||||
if (!ok) return;
|
||||
reparsing.value = true;
|
||||
try {
|
||||
await reparseOrderProfileSampleLayout(props.documentId);
|
||||
message.success(t('admin.shippingOrderProfiles.wizard.xfa.reparseStarted'));
|
||||
} catch (error) {
|
||||
message.error(
|
||||
error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: t('admin.shippingOrderProfiles.wizard.xfa.reparseFailed'),
|
||||
);
|
||||
} finally {
|
||||
reparsing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.documentId, () => void loadXfaContext(), { immediate: true });
|
||||
watch(contextReady, (ready) => emit('update:contextReady', ready));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="xfa-confirm-step">
|
||||
<article v-if="sample" class="xfa-confirm-step__card">
|
||||
<header>
|
||||
<strong>{{ sample.filename || t('admin.shippingOrderProfiles.wizard.sampleSelected') }}</strong>
|
||||
<span class="xfa-confirm-step__badge">{{ documentKindLabel }}</span>
|
||||
</header>
|
||||
<p>{{ t('admin.shippingOrderProfiles.wizard.xfa.intro') }}</p>
|
||||
<ul class="xfa-confirm-step__checks">
|
||||
<li>{{ t('admin.shippingOrderProfiles.wizard.xfa.noBlankPdf') }}</li>
|
||||
<li>{{ t('admin.shippingOrderProfiles.wizard.xfa.scriptNotice') }}</li>
|
||||
</ul>
|
||||
</article>
|
||||
|
||||
<p v-if="loading" class="xfa-confirm-step__loading">{{ t('admin.shippingOrderProfiles.wizard.xfa.loading') }}</p>
|
||||
|
||||
<aside v-else-if="loadError" class="xfa-confirm-step__error" role="alert">
|
||||
<strong>{{ t('admin.shippingOrderProfiles.wizard.xfa.loadErrorTitle') }}</strong>
|
||||
<p>{{ loadError.message }}</p>
|
||||
<p v-if="loadError.code" class="xfa-confirm-step__error-code">{{ loadError.code }}</p>
|
||||
<p class="xfa-confirm-step__error-hint">{{ t('admin.shippingOrderProfiles.wizard.xfa.loadErrorHint') }}</p>
|
||||
<div class="xfa-confirm-step__error-actions">
|
||||
<button type="button" class="xfa-confirm-step__btn" @click="reloadContext">
|
||||
{{ t('admin.shippingOrderProfiles.wizard.xfa.reload') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="xfa-confirm-step__btn xfa-confirm-step__btn--secondary"
|
||||
:disabled="reparsing"
|
||||
@click="reparseSample"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.wizard.xfa.reparseSample') }}
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<XfaCollectionSelector
|
||||
v-else-if="collections && (collections.collection_candidates?.length || excludedCollections.length)"
|
||||
:candidates="collections.collection_candidates || []"
|
||||
:excluded-candidates="excludedCollections"
|
||||
:authoritative-path-id="authoritativePathId"
|
||||
:mirror-path-ids="mirrorPathIds"
|
||||
@update:authoritative-path-id="emit('update:authoritativePathId', $event)"
|
||||
@update:mirror-path-ids="emit('update:mirrorPathIds', $event)"
|
||||
/>
|
||||
|
||||
<aside v-if="createBlockers.length" class="xfa-confirm-step__blockers" role="status">
|
||||
<strong>{{ t('admin.shippingOrderProfiles.xfaUnified.createBlockersTitle') }}</strong>
|
||||
<ul>
|
||||
<li v-for="(item, index) in createBlockers" :key="index">{{ item }}</li>
|
||||
</ul>
|
||||
</aside>
|
||||
|
||||
<p
|
||||
v-if="collections && !collections.collection_candidates?.length && !excludedCollections.length"
|
||||
class="xfa-confirm-step__loading"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.wizard.xfa.noCollections') }}
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-confirm-step { display: flex; flex-direction: column; gap: 16px; }
|
||||
.xfa-confirm-step__card { padding: 16px 18px; border: 1px solid var(--border-default); border-radius: var(--radius-control); background: var(--bg-surface-soft); }
|
||||
.xfa-confirm-step__card header { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 8px; }
|
||||
.xfa-confirm-step__badge { padding: 2px 8px; border-radius: 999px; background: var(--status-info-bg); color: var(--status-info-fg); font-size: .72rem; font-weight: 700; }
|
||||
.xfa-confirm-step__checks { margin: 8px 0 0; padding-left: 18px; color: var(--text-secondary); font-size: .86rem; }
|
||||
.xfa-confirm-step__loading { margin: 0; color: var(--text-muted); }
|
||||
.xfa-confirm-step__blockers { padding: 12px 14px; border: 1px solid var(--status-warning-border); border-radius: var(--radius-control); background: var(--status-warning-bg); color: var(--status-warning-fg); font-size: .84rem; }
|
||||
.xfa-confirm-step__blockers ul { margin: 6px 0 0; padding-left: 18px; }
|
||||
.xfa-confirm-step__error { padding: 14px 16px; border: 1px solid var(--status-danger-border, #f1aeb5); border-radius: var(--radius-control); background: var(--status-danger-bg, #fff5f5); color: var(--status-danger-fg, #9b1c1c); font-size: .86rem; display: flex; flex-direction: column; gap: 8px; }
|
||||
.xfa-confirm-step__error-code { margin: 0; font-family: ui-monospace, monospace; font-size: .75rem; opacity: .85; }
|
||||
.xfa-confirm-step__error-hint { margin: 0; color: var(--text-secondary); }
|
||||
.xfa-confirm-step__error-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 4px; }
|
||||
.xfa-confirm-step__btn { padding: 6px 12px; border-radius: var(--radius-control); border: 1px solid var(--border-default); background: var(--bg-surface); cursor: pointer; font-size: .84rem; }
|
||||
.xfa-confirm-step__btn--secondary { background: transparent; }
|
||||
.xfa-confirm-step__btn:disabled { opacity: .6; cursor: not-allowed; }
|
||||
</style>
|
||||
+2
-3
@@ -82,7 +82,7 @@ const canvasRegions = computed<OrderProfileCanvasRegion[]>(() => {
|
||||
}
|
||||
regions.push({
|
||||
id: `vc:${nr.region_id}`,
|
||||
kind: 'xfa_visual',
|
||||
kind: 'order_field',
|
||||
label: nr.label,
|
||||
region: { ...nr.region },
|
||||
pageNo,
|
||||
@@ -294,10 +294,9 @@ const orderedRegions = computed(() => {
|
||||
:mode="readonly ? 'readonly' : 'edit'"
|
||||
:regions="canvasRegions"
|
||||
:selected-region-id="selectedOrderRegionId"
|
||||
:creation-kind="readonly ? null : 'xfa_visual'"
|
||||
:creation-kind="readonly ? null : 'order_field'"
|
||||
:page-no="pageNo"
|
||||
:page-count="pageCount"
|
||||
annotation-tool-set="xfa_visual"
|
||||
@select="onCanvasSelect"
|
||||
@create="onCanvasCreate"
|
||||
@change="onCanvasChange"
|
||||
|
||||
-281
@@ -1,281 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaAutoMarkPanel.vue
|
||||
用途:XFA OCR/Widget 自动标记建议面板;支持轮询进度与接受/调整/拒绝。
|
||||
依赖:vue-i18n;由 OrderProfileEditorPage(XFA desk)嵌入并接线 automark API。
|
||||
逻辑:props 驱动 suggestions/jobStatus;动作按钮在非 disabled 时 emit 给父级持久化。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
/** 自动标记建议条目。 */
|
||||
export interface XfaAutoMarkSuggestion {
|
||||
suggestion_id: string;
|
||||
field_key?: string | null;
|
||||
field_code?: string | null;
|
||||
suggestion_origin?: 'widget_template' | 'ocr' | string | null;
|
||||
confidence?: number | null;
|
||||
status?: string | null;
|
||||
match_class?: string | null;
|
||||
summary?: string | null;
|
||||
ocr_text?: string | null;
|
||||
dataset_value?: string | null;
|
||||
iou?: number | null;
|
||||
needs_review?: boolean | null;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
suggestions?: XfaAutoMarkSuggestion[];
|
||||
disabled?: boolean;
|
||||
initiallyExpanded?: boolean;
|
||||
/** queued|running|succeeded|failed|idle */
|
||||
jobStatus?: string | null;
|
||||
jobError?: string | null;
|
||||
}>(), {
|
||||
suggestions: () => [],
|
||||
disabled: false,
|
||||
initiallyExpanded: true,
|
||||
jobStatus: 'idle',
|
||||
jobError: null,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
accept: [suggestion: XfaAutoMarkSuggestion];
|
||||
adjust: [suggestion: XfaAutoMarkSuggestion];
|
||||
reject: [suggestion: XfaAutoMarkSuggestion];
|
||||
retry: [];
|
||||
'run-full': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const expanded = ref(props.initiallyExpanded);
|
||||
|
||||
watch(() => props.initiallyExpanded, (v) => { expanded.value = v; });
|
||||
|
||||
const items = computed(() => props.suggestions || []);
|
||||
const empty = computed(() => items.value.length === 0);
|
||||
const running = computed(() => ['queued', 'running', 'pending'].includes(String(props.jobStatus || '')));
|
||||
|
||||
/**
|
||||
* 切换面板展开/收起。
|
||||
*/
|
||||
function toggleExpanded(): void {
|
||||
expanded.value = !expanded.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发出接受建议事件。
|
||||
*/
|
||||
function onAccept(suggestion: XfaAutoMarkSuggestion): void {
|
||||
if (props.disabled || suggestion.needs_review || suggestion.match_class === 'needs_review') return;
|
||||
emit('accept', suggestion);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发出调整建议事件(定位到画布手工改框)。
|
||||
*/
|
||||
function onAdjust(suggestion: XfaAutoMarkSuggestion): void {
|
||||
if (props.disabled) return;
|
||||
emit('adjust', suggestion);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发出驳回建议事件。
|
||||
*/
|
||||
function onReject(suggestion: XfaAutoMarkSuggestion): void {
|
||||
if (props.disabled) return;
|
||||
emit('reject', suggestion);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析建议来源展示文案。
|
||||
*/
|
||||
function originLabel(origin: string | null | undefined): string {
|
||||
if (origin === 'widget_template') return t('admin.shippingOrderProfiles.xfaAutoMark.originWidget');
|
||||
if (origin === 'ocr') return t('admin.shippingOrderProfiles.xfaAutoMark.originOcr');
|
||||
return t('admin.shippingOrderProfiles.xfaAutoMark.originUnknown');
|
||||
}
|
||||
|
||||
/**
|
||||
* mismatch / needs_review 禁止直接接受。
|
||||
*/
|
||||
function acceptBlocked(item: XfaAutoMarkSuggestion): boolean {
|
||||
return Boolean(item.needs_review || item.match_class === 'needs_review');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-auto-mark" :aria-label="t('admin.shippingOrderProfiles.xfaAutoMark.title')">
|
||||
<button
|
||||
type="button"
|
||||
class="xfa-auto-mark__header"
|
||||
:aria-expanded="expanded"
|
||||
@click="toggleExpanded"
|
||||
>
|
||||
<span class="xfa-auto-mark__title">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.title') }}
|
||||
</span>
|
||||
<span class="xfa-auto-mark__count">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.count', { count: items.length }) }}
|
||||
</span>
|
||||
<span v-if="running" class="xfa-auto-mark__job">{{ t('admin.shippingOrderProfiles.xfaAutoMark.running') }}</span>
|
||||
<span class="xfa-auto-mark__chevron">{{ expanded ? '▾' : '▸' }}</span>
|
||||
</button>
|
||||
|
||||
<div v-if="expanded" class="xfa-auto-mark__body">
|
||||
<p class="xfa-auto-mark__hint">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.hint') }}
|
||||
</p>
|
||||
<div class="xfa-auto-mark__toolbar">
|
||||
<button type="button" class="action-btn" :disabled="disabled || running" @click="emit('run-full')">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.runFull') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="jobStatus === 'failed'"
|
||||
type="button"
|
||||
class="action-btn"
|
||||
:disabled="disabled"
|
||||
@click="emit('retry')"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.retry') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="jobError" class="xfa-auto-mark__error">{{ jobError }}</p>
|
||||
<p v-if="empty && !running" class="xfa-auto-mark__empty">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.empty') }}
|
||||
</p>
|
||||
<ul v-else class="xfa-auto-mark__list">
|
||||
<li
|
||||
v-for="item in items"
|
||||
:key="item.suggestion_id"
|
||||
class="xfa-auto-mark__item"
|
||||
>
|
||||
<div class="xfa-auto-mark__meta">
|
||||
<span class="xfa-auto-mark__field">
|
||||
{{ item.field_code || item.field_key || item.suggestion_id }}
|
||||
</span>
|
||||
<span class="xfa-auto-mark__origin">{{ originLabel(item.suggestion_origin) }}</span>
|
||||
<span v-if="item.match_class" class="xfa-auto-mark__class">{{ item.match_class }}</span>
|
||||
<span v-if="item.confidence != null" class="xfa-auto-mark__confidence">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.confidence', {
|
||||
value: Math.round(Number(item.confidence) * 100),
|
||||
}) }}
|
||||
</span>
|
||||
</div>
|
||||
<p v-if="item.summary" class="xfa-auto-mark__summary">{{ item.summary }}</p>
|
||||
<p v-else-if="item.ocr_text || item.dataset_value" class="xfa-auto-mark__summary">
|
||||
OCR: {{ item.ocr_text || '—' }} · datasets: {{ item.dataset_value || '—' }}
|
||||
</p>
|
||||
<div class="xfa-auto-mark__actions">
|
||||
<button
|
||||
type="button"
|
||||
class="action-btn action-btn--active"
|
||||
:disabled="disabled || acceptBlocked(item)"
|
||||
@click="onAccept(item)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.accept') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="action-btn action-btn--active"
|
||||
:disabled="disabled"
|
||||
@click="onAdjust(item)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.adjust') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="action-btn action-btn--active action-btn--danger"
|
||||
:disabled="disabled"
|
||||
@click="onReject(item)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.reject') }}
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-auto-mark {
|
||||
border-top: 1px solid #7dd3fc;
|
||||
border-radius: 0;
|
||||
background: #ecfeff;
|
||||
overflow: hidden;
|
||||
color: #155e75;
|
||||
}
|
||||
.xfa-auto-mark__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
padding: 0.65rem 0.9rem;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
color: #155e75;
|
||||
}
|
||||
.xfa-auto-mark__title { font-size: 0.75rem; font-weight: 600; }
|
||||
.xfa-auto-mark__count, .xfa-auto-mark__job {
|
||||
border-radius: 999px;
|
||||
background: #bae6fd;
|
||||
padding: 0.15rem 0.4rem;
|
||||
font-size: 0.72rem;
|
||||
color: #0e7490;
|
||||
}
|
||||
.xfa-auto-mark__chevron { margin-left: auto; color: #0e7490; font-size: 0.75rem; }
|
||||
.xfa-auto-mark__body { padding: 0 0.9rem 0.75rem; border-top: 1px solid #a5f3fc; }
|
||||
.xfa-auto-mark__hint, .xfa-auto-mark__empty { margin: 0.5rem 0 0; font-size: 0.75rem; color: #0e7490; }
|
||||
.xfa-auto-mark__error { margin: 0.35rem 0 0; font-size: 0.75rem; color: #b91c1c; }
|
||||
.xfa-auto-mark__toolbar { display: flex; gap: 0.35rem; margin-top: 0.45rem; }
|
||||
.xfa-auto-mark__toolbar .action-btn {
|
||||
border: 1px solid #0891b2;
|
||||
border-radius: 0.35rem;
|
||||
background: #fff;
|
||||
padding: 0.35rem 0.55rem;
|
||||
color: #0e7490;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.xfa-auto-mark__list {
|
||||
list-style: none;
|
||||
margin: 0.5rem 0 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
}
|
||||
.xfa-auto-mark__item {
|
||||
padding: 0.5rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 0.375rem;
|
||||
background: #fff;
|
||||
}
|
||||
.xfa-auto-mark__meta { display: flex; flex-wrap: wrap; gap: 0.4rem; align-items: center; }
|
||||
.xfa-auto-mark__field { font-size: 0.8125rem; font-weight: 600; color: #0f172a; }
|
||||
.xfa-auto-mark__origin, .xfa-auto-mark__confidence, .xfa-auto-mark__class {
|
||||
font-size: 0.6875rem;
|
||||
color: #64748b;
|
||||
background: #f1f5f9;
|
||||
border-radius: 0.25rem;
|
||||
padding: 0.1rem 0.35rem;
|
||||
}
|
||||
.xfa-auto-mark__summary { margin: 0.35rem 0 0; font-size: 0.75rem; color: #475569; }
|
||||
.xfa-auto-mark__actions { display: flex; gap: 0.35rem; margin-top: 0.45rem; }
|
||||
.action-btn {
|
||||
font-size: 0.75rem;
|
||||
padding: 0.2rem 0.5rem;
|
||||
border-radius: 0.25rem;
|
||||
border: 1px solid #cbd5e1;
|
||||
background: #f8fafc;
|
||||
color: #334155;
|
||||
}
|
||||
.action-btn:disabled { cursor: not-allowed; opacity: 0.45; }
|
||||
.action-btn--active { cursor: pointer; opacity: 1; }
|
||||
.action-btn--active:hover:not(:disabled) { border-color: #60a5fa; background: #eff6ff; }
|
||||
.action-btn--danger { color: #991b1b; border-color: #fecaca; }
|
||||
</style>
|
||||
-151
@@ -1,151 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaPreviewModeToggle.vue
|
||||
用途:【已废止 / DEPRECATED】原 XFA 原始 PDF / 合成预览双模式切换。
|
||||
依赖:vue-i18n、XfaPreviewCanvasMode 类型。
|
||||
逻辑:硬冻结后 EditorPage 不再导入;保留文件仅防旧引用,请勿在新产品路径使用。
|
||||
替代:唯一 flatten 合成图源;见 useOrderProfileXfaDesk + OrderProfileEditorPage 共享 desk。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { XfaPreviewCanvasMode } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
/** @deprecated 双预览模式已废止;请勿再挂载本组件。 */
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue: XfaPreviewCanvasMode;
|
||||
status?: 'idle' | 'loading' | 'ready' | 'failed' | 'stale' | 'unavailable';
|
||||
pageCount?: number;
|
||||
disabled?: boolean;
|
||||
}>(), {
|
||||
status: 'idle',
|
||||
pageCount: 0,
|
||||
disabled: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [mode: XfaPreviewCanvasMode];
|
||||
'mode-change': [mode: XfaPreviewCanvasMode];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const statusText = computed(() => {
|
||||
switch (props.status) {
|
||||
case 'loading':
|
||||
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusLoading');
|
||||
case 'ready':
|
||||
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusReady', {
|
||||
pages: props.pageCount || 0,
|
||||
});
|
||||
case 'failed':
|
||||
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusFailed');
|
||||
case 'stale':
|
||||
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusStale');
|
||||
case 'unavailable':
|
||||
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusUnavailable');
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 切换预览模式并同步 v-model / mode-change。
|
||||
* @param mode 目标模式
|
||||
*/
|
||||
function selectMode(mode: XfaPreviewCanvasMode): void {
|
||||
if (props.disabled || mode === props.modelValue) return;
|
||||
emit('update:modelValue', mode);
|
||||
emit('mode-change', mode);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="xfa-preview-mode-toggle"
|
||||
role="group"
|
||||
:aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.label')"
|
||||
>
|
||||
<span class="xfa-preview-mode-toggle__label">
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.label') }}
|
||||
</span>
|
||||
<div class="xfa-preview-mode-toggle__buttons">
|
||||
<button
|
||||
type="button"
|
||||
class="mode-btn"
|
||||
:class="{ active: modelValue === 'original' }"
|
||||
:disabled="disabled"
|
||||
:aria-pressed="modelValue === 'original'"
|
||||
@click="selectMode('original')"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.original') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="mode-btn"
|
||||
:class="{ active: modelValue === 'synthetic' }"
|
||||
:disabled="disabled"
|
||||
:aria-pressed="modelValue === 'synthetic'"
|
||||
@click="selectMode('synthetic')"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.synthetic') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="statusText" class="xfa-preview-mode-toggle__status" :data-status="status">
|
||||
{{ statusText }}
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-preview-mode-toggle {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem 0.75rem;
|
||||
margin-bottom: 0.5rem;
|
||||
padding: 0.35rem 0;
|
||||
}
|
||||
.xfa-preview-mode-toggle__label {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: #475569;
|
||||
}
|
||||
.xfa-preview-mode-toggle__buttons {
|
||||
display: inline-flex;
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 0.375rem;
|
||||
overflow: hidden;
|
||||
}
|
||||
.mode-btn {
|
||||
appearance: none;
|
||||
border: 0;
|
||||
background: #f8fafc;
|
||||
color: #334155;
|
||||
font-size: 0.75rem;
|
||||
padding: 0.3rem 0.65rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.mode-btn + .mode-btn {
|
||||
border-left: 1px solid #cbd5e1;
|
||||
}
|
||||
.mode-btn.active {
|
||||
background: #0f172a;
|
||||
color: #f8fafc;
|
||||
}
|
||||
.mode-btn:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.xfa-preview-mode-toggle__status {
|
||||
margin: 0;
|
||||
font-size: 0.7rem;
|
||||
color: #64748b;
|
||||
}
|
||||
.xfa-preview-mode-toggle__status[data-status='failed'],
|
||||
.xfa-preview-mode-toggle__status[data-status='stale'] {
|
||||
color: #b45309;
|
||||
}
|
||||
.xfa-preview-mode-toggle__status[data-status='ready'] {
|
||||
color: #047857;
|
||||
}
|
||||
</style>
|
||||
+17
-1
@@ -36,6 +36,22 @@ const i18n = createI18n({
|
||||
});
|
||||
|
||||
describe('XfaReadOnlyMapping', () => {
|
||||
it('renders the shared adapter-evidence empty state for coordinate profiles', () => {
|
||||
const wrapper = mount(XfaReadOnlyMapping, {
|
||||
props: {
|
||||
detail: {
|
||||
id: 2, profile_code: 'COORD', display_name: 'COORD', version: 1,
|
||||
status: 'published', schema_version_id: 1, structure_fingerprint: 'b'.repeat(64),
|
||||
definition: {}, template_mode: 'coordinate', lock_version: 1,
|
||||
} as never,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('暂无映射');
|
||||
expect(wrapper.text()).not.toContain('不显示空白 PDF');
|
||||
});
|
||||
|
||||
it('renders structure identity and mappings without requesting PDF', () => {
|
||||
const wrapper = mount(XfaReadOnlyMapping, {
|
||||
props: {
|
||||
@@ -50,7 +66,7 @@ describe('XfaReadOnlyMapping', () => {
|
||||
definition: { template_mode: 'xfa_dataset' },
|
||||
template_mode: 'xfa_dataset',
|
||||
lock_version: 1,
|
||||
xfa_readonly_mapping: {
|
||||
value_source_readonly_mapping: {
|
||||
source_contract: {
|
||||
template_packet_checksum: 'sha256:tpl',
|
||||
dataset_structure_fingerprint: 'sha256:fp',
|
||||
|
||||
+8
-6
@@ -1,8 +1,9 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaReadOnlyMapping.vue
|
||||
用途:版本详情页 XFA 只读映射证据,替代空白 PDF 画布。
|
||||
依赖:vue-i18n、XFA readonly mapping DTO。
|
||||
逻辑:展示结构身份、Header/Line 映射与集合策略;不请求 PDF 预览页。
|
||||
用途:版本详情页统一值源 adapter 的只读证据面板。
|
||||
依赖:vue-i18n、Profile readonly mapping DTO。
|
||||
逻辑:所有模板均挂载该面板;coordinate 没有额外值源证据时展示空态,
|
||||
XFA 才显示 datasets 结构身份、Header/Line 路径映射与集合策略;不请求 PDF 预览页。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
@@ -16,7 +17,7 @@ const props = defineProps<{
|
||||
const { t } = useI18n();
|
||||
|
||||
const mapping = computed(() => (props.detail as ShippingOrderDocumentProfile & {
|
||||
xfa_readonly_mapping?: {
|
||||
value_source_readonly_mapping?: {
|
||||
source_contract?: Record<string, unknown>;
|
||||
header_mappings?: Array<Record<string, unknown>>;
|
||||
line_mappings?: Array<Record<string, unknown>>;
|
||||
@@ -24,7 +25,8 @@ const mapping = computed(() => (props.detail as ShippingOrderDocumentProfile & {
|
||||
frozen_samples?: Array<Record<string, unknown>>;
|
||||
matching_signature_checksum?: string | null;
|
||||
};
|
||||
}).xfa_readonly_mapping || null);
|
||||
}).value_source_readonly_mapping || null);
|
||||
const hasValueSourceEvidence = computed(() => Boolean(mapping.value));
|
||||
|
||||
const source = computed(() => mapping.value?.source_contract || {});
|
||||
const headerMaps = computed(() => mapping.value?.header_mappings || []);
|
||||
@@ -33,7 +35,7 @@ const lineMaps = computed(() => mapping.value?.line_mappings || []);
|
||||
|
||||
<template>
|
||||
<section class="xfa-readonly" :aria-label="t('admin.shippingOrderProfiles.xfaReadonly.title')">
|
||||
<p class="hint">{{ t('admin.shippingOrderProfiles.xfaReadonly.noPdfHint') }}</p>
|
||||
<p v-if="hasValueSourceEvidence" class="hint">{{ t('admin.shippingOrderProfiles.xfaReadonly.noPdfHint') }}</p>
|
||||
<div v-if="!mapping" class="empty">{{ t('admin.shippingOrderProfiles.xfaReadonly.missing') }}</div>
|
||||
<template v-else>
|
||||
<div class="identity">
|
||||
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/XfaSchemaMappingPanel.spec.ts
|
||||
* 用途:验证 XFA Schema 映射面板渲染与 bind-field 事件。
|
||||
* 依赖:Vitest、@vue/test-utils、XfaSchemaMappingPanel。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import XfaSchemaMappingPanel from './XfaSchemaMappingPanel.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
xfaWorkbench: {
|
||||
schemaTitle: 'Schema',
|
||||
filter: { all: '全部', unmapped: '未映射' },
|
||||
scope: { header: '表头', line: '明细' },
|
||||
selectLeafFirst: '选叶子',
|
||||
unbind: '解除',
|
||||
requiredCoverage: '{mapped}/{total}',
|
||||
currentNode: '节点',
|
||||
noneSelected: '无',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const definition = {
|
||||
template_mode: 'xfa_dataset' as const,
|
||||
source_contract: {
|
||||
template_packet_checksum: 'a', dataset_structure_fingerprint: 'b', dataset_root_path: '/data',
|
||||
authoritative_line_collection_path: '/data/ITEMS', mirror_collection_paths: [],
|
||||
},
|
||||
header_mappings: [],
|
||||
line_mapping: { row_path: '/data/ITEMS', fields: [] },
|
||||
cross_checks: {
|
||||
acroform_enabled: true,
|
||||
mirror_collection_policy: 'must_match_when_present' as const,
|
||||
line_amount_formula: 'quantity_times_unit_price' as const,
|
||||
total_amount_policy: 'must_equal_line_sum' as const,
|
||||
},
|
||||
};
|
||||
|
||||
describe('XfaSchemaMappingPanel', () => {
|
||||
it('emits bind-field when a schema field is clicked with leaf selected', async () => {
|
||||
const wrapper = mount(XfaSchemaMappingPanel, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
schemaFields: [{
|
||||
field_id: 'f1', field_code: 'customer_po_no', scope: 'header', display_name: 'PO', required: true,
|
||||
enabled: true, aliases: [], normalizer_key: 'trim', validator_keys: [], enum_options: [],
|
||||
evidence_policy: { required: false, source_precedence: [], conflict_policy: 'fail', allow_single_source: true },
|
||||
comparator_key: 'exact',
|
||||
}],
|
||||
definition,
|
||||
selectedPathId: 'leaf-path',
|
||||
selectedPathIsLeaf: true,
|
||||
selectedSourceScope: 'header',
|
||||
},
|
||||
});
|
||||
await wrapper.find('button.field').trigger('click');
|
||||
expect(wrapper.emitted('bind-field')?.[0]?.[0]).toMatchObject({ field_code: 'customer_po_no' });
|
||||
});
|
||||
});
|
||||
-163
@@ -1,163 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaSchemaMappingPanel.vue
|
||||
用途:中栏 Schema 字段绑定面板(同 scope、类型兼容高亮)。
|
||||
依赖:vue-i18n、订单 Schema 字段。
|
||||
逻辑:点击字段绑定当前选中的原始 path 或拆分规则结果;仅过滤全部/未映射。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { OrderXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { ShippingOrderFieldConfig } from '@/features/admin/types/shipping-order-schema.types';
|
||||
|
||||
const props = defineProps<{
|
||||
schemaFields: ShippingOrderFieldConfig[];
|
||||
definition: OrderXfaDatasetProfileDefinition;
|
||||
selectedPathId?: string | null;
|
||||
selectedPathIsLeaf?: boolean;
|
||||
selectedRuleId?: string | null;
|
||||
selectedSourceScope?: 'header' | 'line' | null;
|
||||
filterMode?: 'all' | 'unmapped';
|
||||
mappedFieldPreviews?: {
|
||||
header: Array<{ fieldCode: string; pathLabel: string; value: string | null }>;
|
||||
line: Array<{ fieldCode: string; pathLabel: string; value: string | null }>;
|
||||
};
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
'bind-field': [field: ShippingOrderFieldConfig, scope: 'header' | 'line'];
|
||||
'unbind-field': [fieldId: string];
|
||||
'update:filterMode': [mode: 'all' | 'unmapped'];
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const localFilter = ref<'all' | 'unmapped'>(props.filterMode || 'all');
|
||||
|
||||
const boundIds = computed(() => {
|
||||
const ids = new Set<string>();
|
||||
for (const item of props.definition.header_mappings || []) ids.add(item.field_id);
|
||||
for (const item of props.definition.line_mapping?.fields || []) ids.add(item.field_id);
|
||||
for (const ruleSet of props.definition.split_rules || []) {
|
||||
for (const rule of ruleSet.rules || []) {
|
||||
if (rule.segment.handling === 'mapped' && rule.segment.target_field_id) ids.add(rule.segment.target_field_id);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
});
|
||||
|
||||
const mappingByFieldCode = computed(() => new Map(
|
||||
[...(props.mappedFieldPreviews?.header || []), ...(props.mappedFieldPreviews?.line || [])]
|
||||
.map((item) => [item.fieldCode, item]),
|
||||
));
|
||||
|
||||
/** 返回字段当前映射的路径与识别值,用于字段行内直接核对。 */
|
||||
function mappingFor(field: ShippingOrderFieldConfig) {
|
||||
return field.field_code ? mappingByFieldCode.value.get(field.field_code) : undefined;
|
||||
}
|
||||
|
||||
const groups = computed(() => {
|
||||
const mode = localFilter.value;
|
||||
const header: ShippingOrderFieldConfig[] = [];
|
||||
const line: ShippingOrderFieldConfig[] = [];
|
||||
for (const field of props.schemaFields) {
|
||||
if (!field.enabled) continue;
|
||||
const mapped = boundIds.value.has(field.field_id);
|
||||
if (mode === 'unmapped' && mapped) continue;
|
||||
if (field.scope === 'line') line.push(field);
|
||||
else header.push(field);
|
||||
}
|
||||
return { header, line };
|
||||
});
|
||||
|
||||
/**
|
||||
* 绑定当前原始叶子或拆分规则到 Schema 字段。
|
||||
* 拆分规则继承源节点作用域,只允许绑定同作用域字段。
|
||||
*/
|
||||
function bind(field: ShippingOrderFieldConfig): void {
|
||||
if (!props.selectedPathId || !props.selectedPathIsLeaf) return;
|
||||
if (props.selectedRuleId && field.scope !== props.selectedSourceScope) return;
|
||||
emit('bind-field', field, field.scope === 'line' ? 'line' : 'header');
|
||||
}
|
||||
|
||||
/** 将筛选按钮作为普通分段控制切换,避免声明不完整的 Tab 语义。 */
|
||||
function setFilter(mode: 'all' | 'unmapped'): void {
|
||||
localFilter.value = mode;
|
||||
emit('update:filterMode', mode);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-schema" :aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.schemaTitle')">
|
||||
<div class="xfa-schema__filters" role="group" :aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.filterLabel')">
|
||||
<button
|
||||
v-for="mode in (['all', 'unmapped'] as const)"
|
||||
:key="mode"
|
||||
type="button"
|
||||
:aria-pressed="localFilter === mode"
|
||||
:class="{ active: localFilter === mode }"
|
||||
@click="setFilter(mode)"
|
||||
>
|
||||
{{ t(`admin.shippingOrderProfiles.xfaWorkbench.filter.${mode}`) }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="!selectedPathIsLeaf" class="hint" id="xfa-schema-hint">{{ t('admin.shippingOrderProfiles.xfaWorkbench.selectLeafFirst') }}</p>
|
||||
<div v-for="(fields, scope) in { header: groups.header, line: groups.line }" :key="scope" class="group">
|
||||
<h3>{{ t(`admin.shippingOrderProfiles.xfaWorkbench.scope.${scope}`) }}</h3>
|
||||
<ul>
|
||||
<li v-for="field in fields" :key="field.field_id">
|
||||
<button
|
||||
type="button"
|
||||
class="field"
|
||||
:class="{ mapped: boundIds.has(field.field_id), disabled: !selectedPathIsLeaf || Boolean(selectedRuleId && field.scope !== selectedSourceScope) }"
|
||||
:disabled="!selectedPathIsLeaf || Boolean(selectedRuleId && field.scope !== selectedSourceScope)"
|
||||
:aria-describedby="!selectedPathIsLeaf ? 'xfa-schema-hint' : undefined"
|
||||
@click="bind(field)"
|
||||
>
|
||||
<span class="field__identity">
|
||||
<span>{{ field.display_name || field.field_code }}</span>
|
||||
<small>{{ field.field_code }}</small>
|
||||
</span>
|
||||
<span v-if="mappingFor(field)" class="field__mapping">
|
||||
<span class="field__path">← {{ mappingFor(field)?.pathLabel }}</span>
|
||||
<strong v-if="mappingFor(field)?.value" class="field__value">{{ mappingFor(field)?.value }}</strong>
|
||||
</span>
|
||||
<span v-else class="field__empty">{{ t('admin.shippingOrderProfiles.xfaWorkbench.unmappedValue') }}</span>
|
||||
<strong v-if="boundIds.has(field.field_id)" class="field__check">✓</strong>
|
||||
</button>
|
||||
<button
|
||||
v-if="boundIds.has(field.field_id)"
|
||||
type="button"
|
||||
class="unbind"
|
||||
@click="emit('unbind-field', field.field_id)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.unbind') }}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-schema { display: flex; flex-direction: column; gap: 12px; min-height: 0; height: 100%; overflow: auto; }
|
||||
.xfa-schema__filters { display: flex; gap: 6px; }
|
||||
.xfa-schema__filters button { padding: 6px 10px; border: 1px solid var(--border-default); border-radius: 999px; background: var(--bg-surface); color: var(--text-secondary); }
|
||||
.xfa-schema__filters button.active { border-color: var(--status-info-border); color: var(--status-info-fg); background: var(--status-info-bg); }
|
||||
.hint { margin: 0; color: var(--status-warning-fg); font-size: .85rem; }
|
||||
.group h3 { margin: 0 0 8px; font-size: .9rem; }
|
||||
.group ul { margin: 0 0 14px; padding: 0; list-style: none; }
|
||||
.group li { display: flex; gap: 6px; margin-bottom: 6px; }
|
||||
.field { flex: 1; display: grid; grid-template-columns: minmax(180px, .7fr) minmax(260px, 1.3fr) auto; gap: 12px; align-items: center; min-width: 0; padding: 9px 12px; border: 1px solid var(--border-default); border-radius: var(--radius-control); background: var(--bg-surface); color: var(--text-primary); text-align: left; }
|
||||
.field.mapped { border-color: var(--status-success-border); background: var(--status-success-bg); }
|
||||
.field:focus-visible { outline: 2px solid var(--focus-ring); }
|
||||
.field__identity { display: flex; min-width: 0; align-items: baseline; gap: 8px; }
|
||||
.field__identity > span, .field__identity small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.field small { color: var(--text-muted); }
|
||||
.field__mapping { display: flex; min-width: 0; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.field__path { min-width: 0; overflow: hidden; color: var(--text-secondary); font-size: .76rem; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.field__value { flex: 0 0 auto; max-width: 180px; overflow: hidden; color: var(--status-success-fg); font-size: .76rem; font-weight: 650; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.field__empty { color: var(--text-muted); font-size: .76rem; }
|
||||
.field__check { color: var(--status-success-fg); }
|
||||
.unbind { border: 0; background: transparent; color: var(--status-error-fg); cursor: pointer; }
|
||||
@media (max-width: 1100px) {
|
||||
.field { grid-template-columns: minmax(150px, .8fr) minmax(180px, 1.2fr) auto; }
|
||||
}
|
||||
</style>
|
||||
+110
@@ -244,6 +244,81 @@ describe('XfaSplitRulePanel', () => {
|
||||
expect(ruleSet?.requires_confirmation).toBe(true);
|
||||
});
|
||||
|
||||
it('maps a split segment only to an enabled Schema field and clears its target when kept as evidence', async () => {
|
||||
const wrapper = mountPanel({
|
||||
definition: { ...baseDefinition, split_rules: [makePipelineRuleSet()] },
|
||||
schemaFields: [
|
||||
{
|
||||
field_id: 'unit-price-id',
|
||||
field_code: 'unit_price',
|
||||
display_name: '单价',
|
||||
scope: 'line',
|
||||
enabled: true,
|
||||
required: false,
|
||||
value_type: 'decimal',
|
||||
aliases: [],
|
||||
normalizer_key: 'decimal',
|
||||
validator_keys: [],
|
||||
enum_options: [],
|
||||
evidence_policy: {
|
||||
required: true,
|
||||
source_precedence: [],
|
||||
conflict_policy: 'needs_review',
|
||||
allow_single_source: true,
|
||||
},
|
||||
comparator_key: 'decimal',
|
||||
},
|
||||
{
|
||||
field_id: 'retired-price-unit-id',
|
||||
field_code: 'price_unit',
|
||||
display_name: '价格单位',
|
||||
scope: 'line',
|
||||
enabled: false,
|
||||
required: false,
|
||||
value_type: 'decimal',
|
||||
aliases: [],
|
||||
normalizer_key: 'decimal',
|
||||
validator_keys: [],
|
||||
enum_options: [],
|
||||
evidence_policy: {
|
||||
required: true,
|
||||
source_precedence: [],
|
||||
conflict_policy: 'needs_review',
|
||||
allow_single_source: true,
|
||||
},
|
||||
comparator_key: 'decimal',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await wrapper.get('[data-testid="xfa-split-handling"]').setValue('mapped');
|
||||
let emitted = wrapper.emitted('update:split-rules');
|
||||
let nextDefinition = {
|
||||
...baseDefinition,
|
||||
split_rules: emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules,
|
||||
};
|
||||
await wrapper.setProps({ definition: nextDefinition });
|
||||
const target = wrapper.get('[data-testid="xfa-split-target-field"]');
|
||||
expect(target.text()).toContain('unit_price');
|
||||
expect(target.text()).not.toContain('price_unit');
|
||||
await target.setValue('unit-price-id');
|
||||
|
||||
emitted = wrapper.emitted('update:split-rules');
|
||||
let rule = (emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules)?.[0]?.rules[0];
|
||||
expect(rule?.segment).toMatchObject({
|
||||
handling: 'mapped',
|
||||
target_field_id: 'unit-price-id',
|
||||
target_field_code: 'unit_price',
|
||||
});
|
||||
|
||||
await wrapper.get('[data-testid="xfa-split-handling"]').setValue('evidence_only');
|
||||
emitted = wrapper.emitted('update:split-rules');
|
||||
rule = (emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules)?.[0]?.rules[0];
|
||||
expect(rule?.segment).toMatchObject({ handling: 'evidence_only' });
|
||||
expect(rule?.segment.target_field_id).toBeNull();
|
||||
expect(rule?.segment.target_field_code).toBeNull();
|
||||
});
|
||||
|
||||
it('editing a confirmed rule emits draft with bumped rule_version', async () => {
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
@@ -299,6 +374,41 @@ describe('XfaSplitRulePanel', () => {
|
||||
expect(confirmed).toBeFalsy();
|
||||
});
|
||||
|
||||
it('blocks confirm when a mapped segment has no Schema target', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview_token: 'tok-mapped-empty',
|
||||
preview: {
|
||||
status: 'ok',
|
||||
mapped_fields: {},
|
||||
segments: [],
|
||||
evidence_only_segments: [],
|
||||
diagnostics: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
split_rules: [makePipelineRuleSet({
|
||||
rules: [{
|
||||
...makePipelineRuleSet().rules[0],
|
||||
segment: {
|
||||
...makePipelineRuleSet().rules[0].segment,
|
||||
handling: 'mapped',
|
||||
target_field_id: null,
|
||||
target_field_code: null,
|
||||
},
|
||||
}],
|
||||
})],
|
||||
},
|
||||
});
|
||||
await exposedActions(wrapper).runPreview();
|
||||
await flushPromises();
|
||||
exposedActions(wrapper).confirmRules();
|
||||
|
||||
expect(messageError).toHaveBeenCalledWith('目标必填');
|
||||
expect(wrapper.emitted('confirmed')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('configures consecutive line extraction with range and join mode', async () => {
|
||||
const wrapper = mountPanel({
|
||||
definition: { ...baseDefinition, split_rules: [makePipelineRuleSet()] },
|
||||
|
||||
+68
@@ -24,6 +24,7 @@ import type {
|
||||
XfaSplitStage,
|
||||
XfaSplitStageType,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { ShippingOrderFieldConfig } from '@/features/admin/types/shipping-order-schema.types';
|
||||
|
||||
/** updateRule 局部补丁:segment/stages/matcher 允许浅合并字段 */
|
||||
type XfaSplitRulePatch = Omit<Partial<XfaSplitRule>, 'segment' | 'stages' | 'matcher'> & {
|
||||
@@ -49,6 +50,8 @@ const props = defineProps<{
|
||||
dirtyUnsaved?: boolean;
|
||||
persistedConfirmed?: boolean;
|
||||
autoAddRule?: boolean;
|
||||
/** 仅允许将 split segment 映射到当前启用 Schema 的正式字段。 */
|
||||
schemaFields?: ShippingOrderFieldConfig[];
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -71,6 +74,11 @@ const SEGMENT_CODE_RE = /^[a-z][a-z0-9_]{1,63}$/;
|
||||
|
||||
const isReadonly = computed(() => props.readonly || props.canEdit === false);
|
||||
|
||||
/** 可被拆分段正式写入的字段;Schema 外字段只能作为 evidence 保留。 */
|
||||
const splitTargetFields = computed(() => (props.schemaFields || []).filter((field) => (
|
||||
field.enabled !== false && Boolean(field.field_id && field.field_code)
|
||||
)));
|
||||
|
||||
const activeRuleSet = computed(() => {
|
||||
const pathId = props.selectedPathId || '';
|
||||
return (props.definition.split_rules || []).find((item) => item.source_path_id === pathId) || null;
|
||||
@@ -288,6 +296,13 @@ async function runPreview(): Promise<void> {
|
||||
*/
|
||||
function confirmRules(): void {
|
||||
if (!activeRuleSet.value || isReadonly.value) return;
|
||||
if (activeRuleSet.value.rules.some((rule) => (
|
||||
rule.segment.handling === 'mapped'
|
||||
&& (!rule.segment.target_field_id || !rule.segment.target_field_code)
|
||||
))) {
|
||||
message.error(t('admin.shippingOrderProfiles.xfaSplit.validationMappedTarget'));
|
||||
return;
|
||||
}
|
||||
const currentHash = hashRuleSet(activeRuleSet.value);
|
||||
if (!preview.value || previewRuleSetHash.value !== currentHash || !previewConfirmationToken.value) {
|
||||
message.error(t('admin.shippingOrderProfiles.xfaSplit.confirmNeedsPreview'));
|
||||
@@ -526,6 +541,29 @@ function updateRule(ruleId: string, patch: XfaSplitRulePatch): void {
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置拆分段的处理方式;仅证据段不可残留正式目标,避免后端隐式写值。
|
||||
*/
|
||||
function updateSegmentHandling(ruleId: string, handling: XfaSplitSegment['handling']): void {
|
||||
updateRule(ruleId, {
|
||||
segment: handling === 'evidence_only'
|
||||
? { handling, target_field_id: null, target_field_code: null }
|
||||
: { handling },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 mapped 拆分段绑定到 Schema 字段 ID;从白名单反查 code,拒绝任意前端注入字段。
|
||||
*/
|
||||
function updateSegmentTarget(ruleId: string, fieldId: string): void {
|
||||
const field = splitTargetFields.value.find((item) => item.field_id === fieldId);
|
||||
updateRule(ruleId, {
|
||||
segment: field
|
||||
? { handling: 'mapped', target_field_id: field.field_id, target_field_code: field.field_code || null }
|
||||
: { handling: 'mapped', target_field_id: null, target_field_code: null },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新 unmatched_line_policy。
|
||||
*/
|
||||
@@ -872,6 +910,36 @@ watch(activeRuleSet, (current, previous) => {
|
||||
@input="updateRule(rule.rule_id, { segment: { note: ($event.target as HTMLInputElement).value || null } })"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{{ t('admin.shippingOrderProfiles.xfaSplit.handling') }}
|
||||
<select
|
||||
data-testid="xfa-split-handling"
|
||||
:disabled="isReadonly"
|
||||
:value="rule.segment.handling"
|
||||
@change="updateSegmentHandling(rule.rule_id, ($event.target as HTMLSelectElement).value as XfaSplitSegment['handling'])"
|
||||
>
|
||||
<option value="evidence_only">{{ t('admin.shippingOrderProfiles.xfaSplit.evidenceOnly') }}</option>
|
||||
<option value="mapped">{{ t('admin.shippingOrderProfiles.xfaSplit.mapped') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label v-if="rule.segment.handling === 'mapped'">
|
||||
{{ t('admin.shippingOrderProfiles.xfaSplit.targetField') }}
|
||||
<select
|
||||
data-testid="xfa-split-target-field"
|
||||
:disabled="isReadonly"
|
||||
:value="rule.segment.target_field_id || ''"
|
||||
:class="{ 'xfa-split__invalid': !rule.segment.target_field_id }"
|
||||
@change="updateSegmentTarget(rule.rule_id, ($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option value="">{{ t('admin.shippingOrderProfiles.xfaSplit.selectField') }}</option>
|
||||
<option v-for="field in splitTargetFields" :key="field.field_id" :value="field.field_id">
|
||||
{{ field.display_name }} ({{ field.field_code }})
|
||||
</option>
|
||||
</select>
|
||||
<small v-if="!rule.segment.target_field_id" class="xfa-split__hint-error">
|
||||
{{ t('admin.shippingOrderProfiles.xfaSplit.validationMappedTarget') }}
|
||||
</small>
|
||||
</label>
|
||||
|
||||
<div class="xfa-split__extraction">
|
||||
<label>
|
||||
|
||||
-94
@@ -1,94 +0,0 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/XfaStructuredPreview.spec.ts
|
||||
* 用途:断言预览面板展示阻断摘要、脱敏样本与交叉校验策略。
|
||||
* 依赖:Vitest、@vue/test-utils、XfaStructuredPreview。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import XfaStructuredPreview from './XfaStructuredPreview.vue';
|
||||
import type { OrderXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
common: { yes: '是', no: '否' },
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
xfaWorkbench: {
|
||||
previewTitle: '预览', blockersTitle: '阻断', currentNode: '节点', noneSelected: '无',
|
||||
headerMaps: '表头', lineMaps: '明细', requiredCoverage: '必填 {mapped}/{total}',
|
||||
maskedSample: '脱敏样本值', noMappings: '暂无映射',
|
||||
crossChecksTitle: '交叉校验策略',
|
||||
crossCheck: {
|
||||
acroform: 'AcroForm 对账', mirror: '镜像集合',
|
||||
lineAmount: '明细金额公式', totalAmount: '表头总额策略',
|
||||
},
|
||||
previewHint: '请在验证页查看干跑结果',
|
||||
blocker: { required_fields_unmapped: '必填未映射' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const definition: OrderXfaDatasetProfileDefinition = {
|
||||
template_mode: 'xfa_dataset',
|
||||
source_contract: {
|
||||
template_packet_checksum: 'tpl', dataset_structure_fingerprint: 'fp', dataset_root_path: '/data',
|
||||
authoritative_line_collection_path: '/data/ITEMS/DATA', mirror_collection_paths: [],
|
||||
},
|
||||
header_mappings: [{
|
||||
mapping_id: 'm1', field_id: 'f1', field_code: 'customer_po_no',
|
||||
data_path: '', path_id: 'hdr-ebeln', value_type: 'string',
|
||||
}],
|
||||
line_mapping: { row_path: '/data/ITEMS/DATA', fields: [] },
|
||||
cross_checks: {
|
||||
acroform_enabled: true, mirror_collection_policy: 'must_match_when_present',
|
||||
line_amount_formula: 'quantity_times_unit_price', total_amount_policy: 'must_equal_line_sum',
|
||||
},
|
||||
};
|
||||
|
||||
describe('XfaStructuredPreview', () => {
|
||||
it('renders template-local blockers without Schema required coverage', () => {
|
||||
const wrapper = mount(XfaStructuredPreview, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
definition,
|
||||
coverage: {
|
||||
requiredTotal: 0, requiredMapped: 0,
|
||||
missingRequired: [],
|
||||
duplicateFieldIds: [], authoritativeMissing: true,
|
||||
},
|
||||
blockers: ['authoritative_collection_required'],
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[role="alert"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('shows compact mapping summary without internal cross-check details', () => {
|
||||
const wrapper = mount(XfaStructuredPreview, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
definition,
|
||||
coverage: {
|
||||
requiredTotal: 1, requiredMapped: 1,
|
||||
missingRequired: [], duplicateFieldIds: [], authoritativeMissing: false,
|
||||
},
|
||||
mappedFieldPreviews: {
|
||||
header: [{
|
||||
mappingId: 'm1', fieldCode: 'customer_po_no', pathId: 'hdr-ebeln',
|
||||
pathLabel: 'EBELN', value: '4510000227',
|
||||
}],
|
||||
line: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(wrapper.text()).toContain('customer_po_no');
|
||||
expect(wrapper.text()).not.toContain('交叉校验策略');
|
||||
expect(wrapper.text()).not.toContain('quantity_times_unit_price');
|
||||
});
|
||||
});
|
||||
-100
@@ -1,100 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaStructuredPreview.vue
|
||||
用途:右侧阻断摘要与已完成字段映射的紧凑预览。
|
||||
依赖:vue-i18n、覆盖率摘要类型。
|
||||
逻辑:仅展示需要即时处理的阻断项和已完成映射;当前节点由左侧树/中间编辑区表达,交叉校验策略由验证页承担。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type {
|
||||
OrderXfaDatasetProfileDefinition,
|
||||
XfaMappingCoverageSummary,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
export interface XfaMappedFieldPreviewRow {
|
||||
mappingId: string;
|
||||
fieldCode: string;
|
||||
pathId: string;
|
||||
pathLabel: string;
|
||||
value: string | null;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
definition: OrderXfaDatasetProfileDefinition;
|
||||
coverage: XfaMappingCoverageSummary;
|
||||
mappedFieldPreviews?: {
|
||||
header: XfaMappedFieldPreviewRow[];
|
||||
line: XfaMappedFieldPreviewRow[];
|
||||
};
|
||||
blockers?: string[];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const headerRows = computed(() => props.mappedFieldPreviews?.header?.length
|
||||
? props.mappedFieldPreviews.header
|
||||
: (props.definition.header_mappings || []).map((item) => ({
|
||||
mappingId: item.mapping_id,
|
||||
fieldCode: item.field_code,
|
||||
pathId: item.path_id,
|
||||
pathLabel: item.path_id,
|
||||
value: null as string | null,
|
||||
})));
|
||||
|
||||
const lineRows = computed(() => props.mappedFieldPreviews?.line?.length
|
||||
? props.mappedFieldPreviews.line
|
||||
: (props.definition.line_mapping?.fields || []).map((item) => ({
|
||||
mappingId: item.mapping_id,
|
||||
fieldCode: item.field_code,
|
||||
pathId: item.path_id,
|
||||
pathLabel: item.path_id,
|
||||
value: null as string | null,
|
||||
})));
|
||||
const mappingRows = computed(() => [...headerRows.value, ...lineRows.value]);
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-preview" :aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.previewTitle')">
|
||||
<div v-if="blockers?.length" class="blockers" role="alert" tabindex="-1">
|
||||
<h3>{{ t('admin.shippingOrderProfiles.xfaWorkbench.blockersTitle') }}</h3>
|
||||
<ul>
|
||||
<li v-for="code in blockers" :key="code">{{ t(`admin.shippingOrderProfiles.xfaWorkbench.blocker.${code}`) }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="maps">
|
||||
<div class="maps__heading">
|
||||
<h3>{{ t('admin.shippingOrderProfiles.xfaWorkbench.mappingRelations') }}</h3>
|
||||
<span>{{ mappingRows.length }}</span>
|
||||
</div>
|
||||
<ul v-if="mappingRows.length" class="maps__list">
|
||||
<li v-for="item in mappingRows" :key="item.mappingId">
|
||||
<strong>{{ item.fieldCode }}</strong>
|
||||
← {{ item.pathLabel }}
|
||||
<span v-if="item.value" class="value">({{ item.value }})</span>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="empty">{{ t('admin.shippingOrderProfiles.xfaWorkbench.noMappings') }}</p>
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-preview { display: flex; flex-direction: column; gap: 10px; min-height: 0; height: 100%; overflow: auto; }
|
||||
.blockers { padding: 10px; border: 1px solid var(--status-error-border); border-radius: var(--radius-control); background: var(--status-error-bg); color: var(--status-error-fg); }
|
||||
.blockers:focus { outline: 2px solid var(--focus-ring); }
|
||||
.maps { min-width: 0; padding: 10px; border: 1px solid var(--border-default); border-radius: var(--radius-control); background: var(--bg-surface); }
|
||||
.maps__heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.maps__heading span { min-width: 1.5rem; border-radius: 999px; background: var(--bg-page); color: var(--text-muted); font-size: .68rem; text-align: center; }
|
||||
.maps__heading--line { margin-top: 12px; }
|
||||
.maps__list { display: grid; gap: 4px; margin: 0; padding: 0; list-style: none; }
|
||||
.maps li { min-width: 0; overflow: hidden; color: var(--text-secondary); font-size: .75rem; line-height: 1.35; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.value { color: var(--status-success-fg); }
|
||||
.empty { margin: 4px 0 0; color: var(--text-muted); font-size: .78rem; }
|
||||
h3 { margin: 0 0 8px; font-size: .9rem; }
|
||||
p { margin: 0; color: var(--text-secondary); }
|
||||
</style>
|
||||
+552
@@ -0,0 +1,552 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/composables/useOrderProfileValueAdapter.spec.ts
|
||||
* 用途:验证 XFA datasets 末端值源不会吞掉共同画布字段选择。
|
||||
* 依赖:Vitest、Vue、useOrderProfileValueAdapter、Profile/Schema API mock。
|
||||
* 逻辑:共同 Editor 可先恢复并选中视觉字段;本测试确保 datasets 异步加载完成后仍创建
|
||||
* 未绑定值源槽位,供用户选择 path_id,且不影响共同 OCR 样本值展示流程。
|
||||
*/
|
||||
import { defineComponent, nextTick, ref } from 'vue';
|
||||
import { flushPromises, mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({ error: vi.fn(), info: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-schema.api', () => ({
|
||||
getShippingOrderSchemaState: vi.fn().mockResolvedValue({
|
||||
versions: [{
|
||||
id: 7,
|
||||
definition: { fields: [
|
||||
{ field_id: 'field-po', field_code: 'customer_po_number', scope: 'header' },
|
||||
{ field_id: 'field-material', field_code: 'material_number', scope: 'line' },
|
||||
] },
|
||||
}],
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
|
||||
getOrderDocumentProfileDetail: vi.fn().mockResolvedValue({
|
||||
id: 9,
|
||||
lock_version: 1,
|
||||
display_name: 'XFA sample',
|
||||
profile_code: 'XFA-TEST',
|
||||
schema_version_id: 7,
|
||||
definition: {
|
||||
template_mode: 'xfa_dataset',
|
||||
source_contract: {},
|
||||
header_mappings: [],
|
||||
line_mapping: { fields: [] },
|
||||
cross_checks: {},
|
||||
bindings: [],
|
||||
split_rules: [],
|
||||
},
|
||||
}),
|
||||
listOrderProfileBoundSamples: vi.fn().mockResolvedValue([{ document_id: 101, sample_role: 'annotation' }]),
|
||||
getOrderProfileSampleXfaFieldTree: vi.fn().mockResolvedValue({
|
||||
tree: {
|
||||
path_id: 'root', local_name: 'data', data_path_hash: 'root-hash', depth: 0,
|
||||
cardinality: 'one', is_leaf: false, children: [{
|
||||
path_id: 'header-po', parent_path_id: 'root', local_name: 'HEADER_PO', data_path_hash: 'header-po-hash', depth: 1,
|
||||
cardinality: 'one', is_leaf: true, children: [],
|
||||
}, {
|
||||
path_id: 'items-collection', parent_path_id: 'root', local_name: 'ITEMS', data_path_hash: 'items-hash', depth: 1,
|
||||
cardinality: 'many', is_leaf: false, children: [{
|
||||
path_id: 'po-path', parent_path_id: 'items-collection', local_name: 'EBELN', data_path_hash: 'po-hash', depth: 2,
|
||||
cardinality: 'one', is_leaf: true, children: [],
|
||||
}],
|
||||
}],
|
||||
},
|
||||
}),
|
||||
getOrderProfileSampleXfaCollections: vi.fn().mockResolvedValue({ collection_candidates: [], excluded_collection_candidates: [] }),
|
||||
previewOrderProfileSampleXfaValue: vi.fn().mockResolvedValue({
|
||||
path_id: 'po-path', display_value: '4510039227', sample_value_masked: '4510******', display_policy: 'full',
|
||||
}),
|
||||
previewOrderProfileSampleXfaSplitRules: vi.fn(),
|
||||
}));
|
||||
|
||||
import { useOrderProfileValueAdapter } from './useOrderProfileValueAdapter';
|
||||
import type { OrderProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const i18n = createI18n({ legacy: false, locale: 'zh-CN', messages: { 'zh-CN': {} } });
|
||||
|
||||
describe('useOrderProfileValueAdapter', () => {
|
||||
it('restores a shared visual selection made before the datasets definition finishes loading', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
// Assertion intent: canvas selection precedes the async datasets tree response.
|
||||
desk.selectSharedField('customer_po_number', 'order_field_1_1');
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
await flushPromises();
|
||||
await nextTick();
|
||||
|
||||
expect(desk?.selectedBinding.value?.field_layout_id).toBe('order_field_1_1');
|
||||
expect(desk?.selectedBinding.value?.value_binding.path_id).toBeNull();
|
||||
expect(desk?.showDatasetsSection.value).toBe(true);
|
||||
});
|
||||
|
||||
it('does not serialize a Schema-bound shared layout as an unbound datasets draft', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.authoritativePathId.value = 'root';
|
||||
const visualDefinition = {
|
||||
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
|
||||
table_regions: [],
|
||||
order_field_layouts: [{
|
||||
layout_id: 'order_field_1_1', field_id: 'field-po', field_code: 'customer_po_number',
|
||||
scope: 'header', page_scope: 'exact_page', page_no: 1, anchor: null,
|
||||
absolute_value_region: null, fallback_value_region: { x0: .1, y0: .1, x1: .2, y1: .2 },
|
||||
value_mode: 'single_line', stop_anchors: [], normalizer_key: 'trim', required: false,
|
||||
minimum_evidence_level: 'coordinate',
|
||||
}],
|
||||
draft_unbound_order_field_layouts: Array.from({ length: 6 }, () => ({
|
||||
layout_id: 'order_field_1_1', label: '客户 PO 号', page_scope: 'exact_page', page_no: 1,
|
||||
anchor: null, absolute_value_region: null,
|
||||
fallback_value_region: { x0: .1, y0: .1, x1: .2, y1: .2 },
|
||||
value_mode: 'single_line', stop_anchors: [], minimum_evidence_level: 'coordinate',
|
||||
})),
|
||||
} as unknown as OrderProfileDefinition;
|
||||
|
||||
const payload = desk?.buildDraftPayload(visualDefinition);
|
||||
|
||||
// 关键断言:datasets 尚未选择路径不改变共同 Schema 绑定,也不得制造 unbound 重复项。
|
||||
expect(payload?.definition.draft_unbound_order_field_layouts).toEqual([]);
|
||||
expect(payload?.definition.bindings).toEqual([]);
|
||||
});
|
||||
|
||||
it('loads the controlled datasets sample value after selecting a shared field path', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk?.selectSharedField('customer_po_number', 'order_field_1_2');
|
||||
desk?.updateSelectedDatasetsPath('po-path', true);
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:datasets 样本值来自受控 value-preview API,而不是树 DTO 的旧缓存。
|
||||
expect(desk?.selectedSampleValue.value).toBe('4510039227');
|
||||
});
|
||||
|
||||
it('keeps a datasets binding attached to a shared line field when saving', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.authoritativePathId.value = 'items-collection';
|
||||
desk?.selectSharedField('material_number', 'line_1:material_number');
|
||||
desk?.updateSelectedDatasetsPath('po-path', true);
|
||||
await flushPromises();
|
||||
const visualDefinition = {
|
||||
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
|
||||
order_field_layouts: [], draft_unbound_order_field_layouts: [],
|
||||
table_regions: [{
|
||||
region_id: 'main_lines_page_1', page_scope: 'exact_page', page_no: 1,
|
||||
region: { x0: .1, y0: .2, x1: .9, y1: .8 }, header_layouts: [],
|
||||
line_layouts: [{
|
||||
layout_id: 'line_1', row_offset: 0, role: 'main', region: { x0: .1, y0: .3, x1: .9, y1: .4 },
|
||||
field_regions: [{
|
||||
field_id: 'field-material', field_code: 'material_number', scope: 'line',
|
||||
region: { x0: .2, y0: .3, x1: .4, y1: .4 }, extractor_key: 'direct',
|
||||
allowed_sources: ['pdf_coordinate'], minimum_evidence_level: 'coordinate',
|
||||
}], new_line_anchor: null, continuation_conditions: [], required_fields: [], allowed_empty_fields: [],
|
||||
}], continuation_rule: { allow_cross_page: false, required_anchor_ids: [] },
|
||||
termination_rules: [], exclusion_regions: [],
|
||||
}],
|
||||
} as unknown as OrderProfileDefinition;
|
||||
|
||||
const payload = desk?.buildDraftPayload(visualDefinition);
|
||||
|
||||
// 关键断言:XFA 只追加 path;共同明细视觉框仍是唯一布局身份,保存不可丢 binding。
|
||||
expect(payload?.definition.bindings).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ field_layout_id: 'line_1:material_number', value_binding: expect.objectContaining({ path_id: 'po-path' }) }),
|
||||
]));
|
||||
});
|
||||
|
||||
it('uses the visual field scope when header and line reuse one Schema code', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.schemaFields.value = [
|
||||
{ field_id: 'reservation-header', field_code: 'reservation_id', scope: 'header' },
|
||||
{ field_id: 'reservation-line', field_code: 'reservation_id', scope: 'line' },
|
||||
];
|
||||
desk!.selectSharedField('reservation_id', 'line_1:reservation_id', 'line');
|
||||
|
||||
// 关键断言:相同 code 不能让明细画框错误绑定到 Header 字段。
|
||||
expect(desk!.selectedBinding.value).toMatchObject({
|
||||
field_id: 'reservation-line', field_code: 'reservation_id', scope: 'line',
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps a table-header visual field in the line datasets binding scope', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.schemaFields.value = [
|
||||
{ field_id: 'line-material', field_code: 'material_number', scope: 'line' },
|
||||
];
|
||||
desk!.selectSharedField('material_number', 'header_1:material_number', 'line');
|
||||
|
||||
// 关键断言:表格列头是明细字段的视觉入口,正式 datasets binding 仍必须落到 line scope。
|
||||
expect(desk!.selectedBinding.value).toMatchObject({
|
||||
field_id: 'line-material', field_code: 'material_number', scope: 'line',
|
||||
field_layout_id: 'header_1:material_number',
|
||||
});
|
||||
});
|
||||
|
||||
it('moves one configured datasets path when its shared visual field is rebound', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.schemaFields.value = [
|
||||
{ field_id: 'line-material', field_code: 'material_number', scope: 'line' },
|
||||
{ field_id: 'line-internal', field_code: 'part_number', scope: 'line' },
|
||||
];
|
||||
desk!.definition.value = {
|
||||
...desk!.definition.value!,
|
||||
bindings: [{
|
||||
binding_id: 'material-binding', field_id: 'line-material', field_code: 'material_number', scope: 'line',
|
||||
field_layout_id: 'header_1:material_number',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: '/data/items/material' },
|
||||
}],
|
||||
};
|
||||
|
||||
desk!.migrateUniqueSharedFieldBinding(
|
||||
'material_number', 'header_1:material_number', 'part_number', 'header_1:part_number', 'line',
|
||||
);
|
||||
|
||||
// 关键断言:用户改绑同一视觉列时,唯一正式路径随框迁移,不遗留孤儿旧 identity。
|
||||
expect(desk!.definition.value?.bindings).toEqual([expect.objectContaining({
|
||||
field_id: 'line-internal', field_code: 'part_number', scope: 'line',
|
||||
field_layout_id: 'header_1:part_number',
|
||||
value_binding: expect.objectContaining({ path_id: 'po-path' }),
|
||||
})]);
|
||||
});
|
||||
|
||||
it('does not infer a migration when one visual field has multiple formal bindings', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.schemaFields.value = [{ field_id: 'line-internal', field_code: 'part_number', scope: 'line' }];
|
||||
desk!.definition.value = {
|
||||
...desk!.definition.value!,
|
||||
bindings: [
|
||||
{ binding_id: 'first', field_id: 'one', field_code: 'one', scope: 'line', field_layout_id: 'line_1:old', value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: null } },
|
||||
{ binding_id: 'second', field_id: 'two', field_code: 'two', scope: 'line', field_layout_id: 'line_1:old', value_binding: { type: 'xfa_dataset', path_id: 'header-po', data_path: null } },
|
||||
],
|
||||
};
|
||||
|
||||
desk!.migrateUniqueSharedFieldBinding('old', 'line_1:old', 'part_number', 'line_1:part_number', 'line');
|
||||
|
||||
// 关键断言:多个正式字段共享一个视觉框时保持 fail-closed,不能擅自选一个迁移。
|
||||
expect(desk!.definition.value?.bindings.map((item) => item.field_layout_id)).toEqual(['line_1:old', 'line_1:old']);
|
||||
});
|
||||
|
||||
it('keeps multiple datasets bindings that intentionally share one visual field layout', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.authoritativePathId.value = 'items-collection';
|
||||
desk!.definition.value = {
|
||||
...desk!.definition.value!,
|
||||
bindings: [
|
||||
{
|
||||
binding_id: 'customer-part', field_id: 'field-customer-part', field_code: 'customer_part_number', scope: 'line',
|
||||
field_layout_id: 'line_1:customer_part_number',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'customer-path', data_path: '/data/items/MATNR' },
|
||||
},
|
||||
{
|
||||
binding_id: 'internal-part', field_id: 'field-internal-part', field_code: 'part_number', scope: 'line',
|
||||
field_layout_id: 'line_1:customer_part_number',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'internal-path', data_path: '/data/items/MATNR' },
|
||||
},
|
||||
],
|
||||
};
|
||||
const visualDefinition = {
|
||||
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
|
||||
order_field_layouts: [], draft_unbound_order_field_layouts: [],
|
||||
table_regions: [{
|
||||
region_id: 'main_lines_page_1', page_scope: 'exact_page', page_no: 1,
|
||||
region: { x0: .1, y0: .2, x1: .9, y1: .8 }, header_layouts: [],
|
||||
line_layouts: [{
|
||||
layout_id: 'line_1', row_offset: 0, role: 'main', region: { x0: .1, y0: .3, x1: .9, y1: .4 },
|
||||
field_regions: [{
|
||||
field_id: 'field-customer-part', field_code: 'customer_part_number', scope: 'line',
|
||||
region: { x0: .2, y0: .3, x1: .4, y1: .4 }, extractor_key: 'direct',
|
||||
allowed_sources: ['pdf_coordinate'], minimum_evidence_level: 'coordinate',
|
||||
}], new_line_anchor: null, continuation_conditions: [], required_fields: [], allowed_empty_fields: [],
|
||||
}], continuation_rule: { allow_cross_page: false, required_anchor_ids: [] },
|
||||
termination_rules: [], exclusion_regions: [],
|
||||
}],
|
||||
} as unknown as OrderProfileDefinition;
|
||||
|
||||
const payload = desk!.buildDraftPayload(visualDefinition);
|
||||
expect(payload?.definition.bindings.map((item) => item.binding_id)).toEqual(['customer-part', 'internal-part']);
|
||||
});
|
||||
|
||||
it('blocks saving when an existing formal datasets binding has no shared visual layout', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.authoritativePathId.value = 'root';
|
||||
desk!.definition.value = {
|
||||
...desk!.definition.value!,
|
||||
bindings: [{
|
||||
binding_id: 'currency-binding', field_id: 'field-currency', field_code: 'currency', scope: 'header',
|
||||
field_layout_id: 'xfa_header_currency',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: '/data/currency' },
|
||||
}],
|
||||
};
|
||||
const visualDefinition = {
|
||||
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
|
||||
order_field_layouts: [], draft_unbound_order_field_layouts: [], table_regions: [],
|
||||
} as unknown as OrderProfileDefinition;
|
||||
|
||||
const payload = desk!.buildDraftPayload(visualDefinition);
|
||||
|
||||
// 关键断言:正式 datasets binding 不得因本次画布缺少其共同框而被静默删除。
|
||||
expect(payload).toBeNull();
|
||||
});
|
||||
|
||||
it('carries an explicit formal binding deletion through the save payload', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.authoritativePathId.value = 'root';
|
||||
desk!.definition.value = {
|
||||
...desk!.definition.value!,
|
||||
bindings: [{
|
||||
binding_id: 'currency-binding', field_id: 'field-currency', field_code: 'currency', scope: 'header',
|
||||
field_layout_id: 'xfa_header_currency',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: '/data/currency' },
|
||||
}],
|
||||
};
|
||||
desk!.selectSharedField('currency', 'xfa_header_currency');
|
||||
desk!.deleteSelectedBinding();
|
||||
const payload = desk!.buildDraftPayload({
|
||||
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
|
||||
order_field_layouts: [], draft_unbound_order_field_layouts: [], table_regions: [],
|
||||
} as unknown as OrderProfileDefinition);
|
||||
|
||||
// 关键断言:只有用户明确解除后,保存请求才携带允许删除的正式 binding ID。
|
||||
expect(payload?.definition.bindings).toEqual([]);
|
||||
expect(payload?.allow_formal_binding_deletions).toEqual(['currency-binding']);
|
||||
});
|
||||
|
||||
it('restores an empty visual field id from its unique datasets binding when saving', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.authoritativePathId.value = 'root';
|
||||
desk!.definition.value = {
|
||||
...desk!.definition.value!,
|
||||
bindings: [{
|
||||
binding_id: 'line-material', field_id: 'field-material', field_code: 'material_number', scope: 'line',
|
||||
field_layout_id: 'line_1:material_number', value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: null },
|
||||
}],
|
||||
};
|
||||
const visualDefinition = {
|
||||
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
|
||||
order_field_layouts: [], draft_unbound_order_field_layouts: [],
|
||||
table_regions: [{
|
||||
region_id: 'main_lines_page_1', page_scope: 'exact_page', page_no: 1,
|
||||
region: { x0: .1, y0: .2, x1: .9, y1: .8 }, header_layouts: [],
|
||||
line_layouts: [{
|
||||
layout_id: 'line_1', row_offset: 0, role: 'main', region: { x0: .1, y0: .3, x1: .9, y1: .4 },
|
||||
field_regions: [{
|
||||
field_id: '', field_code: 'material_number', scope: 'line',
|
||||
region: { x0: .2, y0: .3, x1: .4, y1: .4 }, extractor_key: 'direct',
|
||||
allowed_sources: ['pdf_coordinate'], minimum_evidence_level: 'coordinate',
|
||||
}], new_line_anchor: null, continuation_conditions: [], required_fields: [], allowed_empty_fields: [],
|
||||
}], continuation_rule: { allow_cross_page: false, required_anchor_ids: [] },
|
||||
termination_rules: [], exclusion_regions: [],
|
||||
}],
|
||||
} as unknown as OrderProfileDefinition;
|
||||
|
||||
const payload = desk!.buildDraftPayload(visualDefinition);
|
||||
|
||||
// 关键断言:已有唯一正式 binding 时,视觉布局必须复用其 Schema ID,避免签名阶段失败。
|
||||
expect(payload?.definition.table_regions[0]?.line_layouts[0]?.field_regions[0]?.field_id).toBe('field-material');
|
||||
});
|
||||
|
||||
it('keeps a line Schema field bound from an auto-marked table header when saving', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.authoritativePathId.value = 'items-collection';
|
||||
desk!.definition.value = {
|
||||
...desk!.definition.value!,
|
||||
bindings: [{
|
||||
binding_id: 'header-material', field_id: 'field-material', field_code: 'material_number', scope: 'line',
|
||||
field_layout_id: 'header_1:material_number',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: '/data/items/material' },
|
||||
}],
|
||||
};
|
||||
const visualDefinition = {
|
||||
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
|
||||
order_field_layouts: [], draft_unbound_order_field_layouts: [],
|
||||
table_regions: [{
|
||||
region_id: 'main_lines_page_1', page_scope: 'exact_page', page_no: 1,
|
||||
region: { x0: .1, y0: .2, x1: .9, y1: .8 },
|
||||
header_layouts: [{
|
||||
layout_id: 'header_1', region: { x0: .1, y0: .2, x1: .9, y1: .3 },
|
||||
field_regions: [{
|
||||
field_id: '', field_code: 'material_number', scope: 'line',
|
||||
region: { x0: .2, y0: .2, x1: .4, y1: .3 }, extractor_key: 'direct',
|
||||
allowed_sources: ['pdf_coordinate'], minimum_evidence_level: 'coordinate',
|
||||
}],
|
||||
}],
|
||||
line_layouts: [], continuation_rule: { allow_cross_page: false, required_anchor_ids: [] },
|
||||
termination_rules: [], exclusion_regions: [],
|
||||
}],
|
||||
} as unknown as OrderProfileDefinition;
|
||||
|
||||
const payload = desk!.buildDraftPayload(visualDefinition);
|
||||
|
||||
// 关键断言:ITEM/QTY 等视觉表头可绑定 line 字段,二次保存不可将其视为缺失布局。
|
||||
expect(payload?.definition.table_regions[0]?.header_layouts[0]?.field_regions[0]?.field_id).toBe('field-material');
|
||||
expect(payload?.definition.bindings).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ field_layout_id: 'header_1:material_number' }),
|
||||
]));
|
||||
});
|
||||
|
||||
it('marks a Header datasets value chosen for a shared line field as inherited', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.authoritativePathId.value = 'items-collection';
|
||||
desk?.selectSharedField('material_number', 'line_1:material_number');
|
||||
desk?.updateSelectedDatasetsPath('header-po', true);
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:Header 叶子仍能绑定 line 字段,但 UI 必须明确展示逐行继承语义。
|
||||
expect(desk?.lineBindingInheritsHeader.value).toBe(true);
|
||||
});
|
||||
|
||||
});
|
||||
+1051
File diff suppressed because it is too large.
Load diff
-1720
File diff suppressed because it is too large.
Load diff
+254
@@ -13,11 +13,29 @@ import {
|
||||
shouldShowStandardOrderProfilePreview,
|
||||
toOrderProfileAnchorId,
|
||||
buildOrderProfileRecognitionResults,
|
||||
selectCurrentDatasetsValidationEvidence,
|
||||
normalizeOrderProfileRelativeRegion,
|
||||
groupUniqueOrderProfileLineFields,
|
||||
buildAutomarkSuggestedRegions,
|
||||
normalizeAutomarkFieldCandidates,
|
||||
selectAutomarkReconstruction,
|
||||
summarizeAutomarkTableCandidates,
|
||||
toOrderProfileHeaderFieldRegion,
|
||||
resolveCoordinateFieldScope,
|
||||
isOrderProfileVisualFieldEligible,
|
||||
} from './orderProfileForm.utils';
|
||||
|
||||
describe('order profile form rules', () => {
|
||||
it('keeps datasets-only Schema fields available for XFA visual positioning only', () => {
|
||||
const datasetsOnly = { enabled: true, allowed_sources: ['xfa_dataset'] };
|
||||
|
||||
// 关键断言:XFA 画框是定位证据,不能因没有 pdf_coordinate 正式取值权限而无法选择字段。
|
||||
expect(isOrderProfileVisualFieldEligible(datasetsOnly, true)).toBe(true);
|
||||
// 普通 PDF 仍不允许把未授权字段写入 coordinate definition。
|
||||
expect(isOrderProfileVisualFieldEligible(datasetsOnly, false)).toBe(false);
|
||||
expect(isOrderProfileVisualFieldEligible({ enabled: false, allowed_sources: ['xfa_dataset'] }, true)).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['line_no', 'customer_po_line_no'])(
|
||||
'keeps %s available after resolving the main-line fields',
|
||||
(startFieldCode) => {
|
||||
@@ -149,6 +167,55 @@ describe('order profile form rules', () => {
|
||||
expect(results.header).toMatchObject([{ id: 'address-value', value: null, status: 'unavailable' }]);
|
||||
});
|
||||
|
||||
it('displays the current AcroForm widget visual sample value for an XFA header frame', () => {
|
||||
const results = buildOrderProfileRecognitionResults([{
|
||||
id: 'po-value', kind: 'order_field' as const, label: 'PO', fieldCode: 'customer_po_number',
|
||||
pageNo: 1, region: { x0: .4, y0: .1, x1: .8, y1: .2 },
|
||||
}], [{
|
||||
field_id: 'po-field', field_code: 'customer_po_number', value: '4510039227',
|
||||
source: 'acroform_widget', status: 'needs_review', page_no: 1,
|
||||
issues: ['order_field_acroform_widget_needs_review'],
|
||||
}], null, 'ready');
|
||||
|
||||
// Widget 值来自当前受控视觉回读,必须显示,不得回退为自动标记缓存。
|
||||
expect(results.header).toMatchObject([{ id: 'po-value', value: '4510039227', status: 'read' }]);
|
||||
});
|
||||
|
||||
it('projects XFA line results only from datasets validation evidence', () => {
|
||||
const regions = [
|
||||
{ id: 'part-column', kind: 'field' as const, label: 'Part', fieldCode: 'customer_part_number', pageNo: 1, region: { x0: .1, y0: .3, x1: .2, y1: .4 } },
|
||||
{ id: 'qty-column', kind: 'field' as const, label: 'Qty', fieldCode: 'quantity', pageNo: 1, region: { x0: .2, y0: .3, x1: .3, y1: .4 } },
|
||||
];
|
||||
|
||||
const results = buildOrderProfileRecognitionResults(regions, [], null, 'ready', {
|
||||
header_fields: [],
|
||||
lines: [{ row_index: 0, fields: [
|
||||
{ field_id: 'part', field_code: 'customer_part_number', raw_value: 'TEMP-S000218922', normalized_value: 'TEMP-S000218922', status: 'passed', issues: [] },
|
||||
{ field_id: 'qty', field_code: 'quantity', raw_value: '30', normalized_value: '30', status: 'passed', issues: [] },
|
||||
] }],
|
||||
cross_checks: {},
|
||||
});
|
||||
|
||||
// XFA 的正式行值只能来自 datasets 验证证据;坐标表头/旧 preview 不得混入。
|
||||
expect(results.line).toMatchObject([
|
||||
{ id: 'part-column', fieldCode: 'customer_part_number', value: 'TEMP-S000218922', status: 'read', rowNo: 1 },
|
||||
{ id: 'qty-column', fieldCode: 'quantity', value: '30', status: 'read', rowNo: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('selects only the current XFA validation evidence for the active draft checksum', () => {
|
||||
const evidence = {
|
||||
header_fields: [], lines: [{ row_index: 0, fields: [] }], cross_checks: {},
|
||||
};
|
||||
|
||||
// 旧草稿或非当前样本 Run 不能回灌至共同工作台,避免显示过期的正式样本值。
|
||||
expect(selectCurrentDatasetsValidationEvidence([
|
||||
{ id: 3, run_type: 'current_sample', status: 'passed', definition_checksum: 'old', summary: { validation_evidence: evidence } },
|
||||
{ id: 2, run_type: 'instant_check', status: 'passed', definition_checksum: 'current', summary: { validation_evidence: evidence } },
|
||||
{ id: 1, run_type: 'current_sample', status: 'passed', definition_checksum: 'current', summary: { validation_evidence: evidence } },
|
||||
], 'current')).toEqual(evidence);
|
||||
});
|
||||
|
||||
it('reports reading and failure without reusing a prior suggested value', () => {
|
||||
const regions = [{
|
||||
id: 'address-value', kind: 'order_field' as const, label: 'Address', fieldCode: 'bill_to_address',
|
||||
@@ -188,4 +255,191 @@ describe('order profile form rules', () => {
|
||||
expect(normalizeOrderProfileRelativeRegion({ x0: 1.1, y0: .2, x1: 1.2, y1: .3 })).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps header field candidates when visual row reconstruction needs review', () => {
|
||||
const regions = buildAutomarkSuggestedRegions({
|
||||
reconstruction: null,
|
||||
orderFieldCandidates: [{
|
||||
field_id: 'po', field_code: 'customer_po_number', display_name: 'PO Number',
|
||||
source: 'ocr_coordinate', status: 'suggested', issue: null,
|
||||
value_region: { x0: .4, y0: .1, x1: .8, y1: .16 },
|
||||
}],
|
||||
pageNo: 1,
|
||||
unboundColumnLabel: (count) => `Unbound ${count}`,
|
||||
lineLabel: (count) => `Line ${count}`,
|
||||
});
|
||||
|
||||
// 行证据为空时,只保留可复核的抬头框;不得为了满足旧表格结构虚构明细行。
|
||||
expect(regions).toMatchObject([{
|
||||
kind: 'order_field', fieldCode: 'customer_po_number', pageNo: 1,
|
||||
region: { x0: .4, y0: .1, x1: .8, y1: .16 },
|
||||
}]);
|
||||
expect(regions.some((region) => region.kind === 'line' || region.kind === 'field')).toBe(false);
|
||||
});
|
||||
|
||||
it('serializes accepted header fields with header scope', () => {
|
||||
// 表头候选接受后必须进入 header_layouts;写成 line 会被后端契约拒绝,导致表头刷新后消失。
|
||||
expect(toOrderProfileHeaderFieldRegion({
|
||||
fieldCode: 'delivery_date',
|
||||
region: { x0: .2, y0: .1, x1: .4, y1: .16 },
|
||||
})).toEqual({
|
||||
field_id: '', field_code: 'delivery_date', scope: 'header',
|
||||
region: { x0: .2, y0: .1, x1: .4, y1: .16 },
|
||||
extractor_key: 'direct', allowed_sources: ['pdf_coordinate'], minimum_evidence_level: 'coordinate',
|
||||
});
|
||||
expect(toOrderProfileHeaderFieldRegion({
|
||||
fieldCode: null,
|
||||
region: { x0: .2, y0: .1, x1: .4, y1: .16 },
|
||||
})).toBeNull();
|
||||
// 视觉表头中的 ITEM/QTY 等列名属于明细 Schema,必须保留 line scope。
|
||||
expect(toOrderProfileHeaderFieldRegion({
|
||||
fieldCode: 'qty',
|
||||
region: { x0: .4, y0: .1, x1: .5, y1: .16 },
|
||||
}, 'line')?.scope).toBe('line');
|
||||
// Schema 只允许 datasets 时,视觉框不能丢失,也不能伪造 coordinate 正式绑定;
|
||||
// 页面定义序列化层会将其放入 draft_unbound_field_regions。
|
||||
});
|
||||
|
||||
it('keeps a cross-scope visual header candidate unbound until an administrator decides', () => {
|
||||
// 同名字段跨 header/line 时,仅凭视觉列名不足以做业务语义选择。
|
||||
expect(resolveCoordinateFieldScope('qty', ['customer_po_number'], ['qty'])).toBe('line');
|
||||
expect(resolveCoordinateFieldScope('customer_po_number', ['customer_po_number'], ['qty'])).toBe('header');
|
||||
expect(resolveCoordinateFieldScope('reservation_id', ['reservation_id'], ['reservation_id'])).toBeNull();
|
||||
expect(resolveCoordinateFieldScope('dataset_only', [], [])).toBeNull();
|
||||
});
|
||||
|
||||
it('does not choose a table layout when native and OCR candidates coexist', () => {
|
||||
const native = {
|
||||
table_id: 'table-1', subrow_layouts: [{ row_offset: 0, column_boundaries: [0, 1] }],
|
||||
};
|
||||
|
||||
// 两路候选即使暂未计算出冲突,画布也不能按 native 优先投影为已选择的明细框。
|
||||
expect(selectAutomarkReconstruction(native, [
|
||||
{ source: 'pdf_coordinate', status: 'needs_review' },
|
||||
{ source: 'ocr_coordinate', status: 'needs_review' },
|
||||
], [])).toBeNull();
|
||||
expect(selectAutomarkReconstruction(native, [
|
||||
{ source: 'pdf_coordinate', status: 'needs_review' },
|
||||
], [{ code: 'table_reconstruction_source_conflict' }])).toBeNull();
|
||||
expect(selectAutomarkReconstruction(native, [
|
||||
{ source: 'pdf_coordinate', status: 'needs_review' },
|
||||
], [])).toBe(native);
|
||||
});
|
||||
|
||||
it('uses the explicitly selected Widget table candidate when coordinate reconstruction is absent', () => {
|
||||
const widget = {
|
||||
table_id: 'table-1', status: 'needs_review' as const,
|
||||
subrow_layouts: [{ row_offset: 0, column_boundaries: [0, .5, 1] }],
|
||||
};
|
||||
|
||||
// XFA 外观层可能没有可重建的 native/OCR 文本行;管理员选择唯一 Widget 几何后,
|
||||
// 共同画布必须使用该结构生成待确认明细框,而不能退化为“无明细行”。
|
||||
expect(selectAutomarkReconstruction(null, [
|
||||
{ source: 'acroform_widget_geometry', status: 'needs_review' },
|
||||
], [], widget)).toBe(widget);
|
||||
});
|
||||
|
||||
it('projects fused Widget geometry and coordinate header text as header fields', () => {
|
||||
const widget = {
|
||||
table_id: 'table-1', status: 'needs_review' as const,
|
||||
subrow_layouts: [{
|
||||
row_offset: 0, column_boundaries: [0, .25, 1],
|
||||
suggested_field_codes: [null, null],
|
||||
}],
|
||||
header_regions: [{
|
||||
region: { x0: .1, y0: .15, x1: .9, y1: .2 },
|
||||
fields: [{
|
||||
text: 'ITEM', field_code: 'line_no',
|
||||
region: { x0: .1, y0: .15, x1: .3, y1: .2 },
|
||||
evidence_sources: ['acroform_widget_geometry', 'pdf_coordinate'],
|
||||
}],
|
||||
}],
|
||||
};
|
||||
|
||||
const regions = buildAutomarkSuggestedRegions({
|
||||
reconstruction: selectAutomarkReconstruction(null, [
|
||||
{ source: 'acroform_widget_geometry', status: 'needs_review' },
|
||||
], [], widget),
|
||||
orderFieldCandidates: [], pageNo: 1,
|
||||
unboundColumnLabel: (count) => `Unbound ${count}`,
|
||||
lineLabel: (count) => `Line ${count}`,
|
||||
});
|
||||
|
||||
// Widget 仅提供列几何;融合后的表头文字必须随所选候选进入共同画布。
|
||||
expect(regions).toContainEqual({
|
||||
id: 'header_1_1-field-1', kind: 'header_field', parentId: 'header_1_1',
|
||||
label: 'line_no', fieldCode: 'line_no', pageNo: 1,
|
||||
region: { x0: .1, y0: .15, x1: .3, y1: .2 },
|
||||
});
|
||||
});
|
||||
|
||||
it('preserves the backend evidence source when projecting automark field candidates', () => {
|
||||
const candidates = normalizeAutomarkFieldCandidates([{
|
||||
candidate_kind: 'field_binding',
|
||||
evidence_sources: ['ocr_coordinate'],
|
||||
needs_review: true,
|
||||
binding: {
|
||||
field_id: 'po', field_code: 'customer_po_number',
|
||||
visual_binding: { normalized_bbox: { x0: .4, y0: .1, x1: .8, y1: .16 } },
|
||||
},
|
||||
}]);
|
||||
|
||||
// OCR 视觉候选不能在前端被降级伪装为 native PDF 坐标候选。
|
||||
expect(candidates).toMatchObject([{
|
||||
source: 'ocr_coordinate', status: 'suggested',
|
||||
value_region: { x0: .4, y0: .1, x1: .8, y1: .16 },
|
||||
issue: 'visual_candidate_needs_review',
|
||||
}]);
|
||||
});
|
||||
|
||||
it('keeps AcroForm Widget as a visual-only candidate source', () => {
|
||||
const candidates = normalizeAutomarkFieldCandidates([{
|
||||
candidate_kind: 'field_binding',
|
||||
evidence_sources: ['acroform_widget'],
|
||||
needs_review: true,
|
||||
binding: {
|
||||
field_id: 'po', field_code: 'customer_po_number',
|
||||
visual_binding: { normalized_bbox: { x0: .4, y0: .1, x1: .8, y1: .16 } },
|
||||
},
|
||||
}]);
|
||||
|
||||
// Widget 只保留为待复核的定位来源;归一化 DTO 中没有也不得生成正式 value_binding。
|
||||
expect(candidates).toMatchObject([{
|
||||
source: 'acroform_widget', status: 'suggested',
|
||||
issue: 'visual_candidate_needs_review',
|
||||
}]);
|
||||
});
|
||||
|
||||
it('projects an unmatched AcroForm Widget as an unbound visual candidate', () => {
|
||||
const candidates = normalizeAutomarkFieldCandidates([{
|
||||
candidate_kind: 'field_binding',
|
||||
evidence_sources: ['acroform_widget'],
|
||||
needs_review: true,
|
||||
binding: {
|
||||
field_id: '', field_code: '', display_name: 'EBELN',
|
||||
visual_binding: { normalized_bbox: { x0: .4, y0: .1, x1: .8, y1: .16 } },
|
||||
},
|
||||
}]);
|
||||
|
||||
// Widget 名称不是业务字段映射;画布只能显示待确认框,不能自动写入 Schema field_code。
|
||||
expect(candidates).toMatchObject([{
|
||||
field_code: '', display_name: 'EBELN', source: 'acroform_widget',
|
||||
issue: 'visual_candidate_needs_review',
|
||||
}]);
|
||||
});
|
||||
|
||||
it('summarizes every parallel table candidate and marks source conflicts', () => {
|
||||
// 断言三路视觉候选都可见,摘要只提供结构信息,不替用户选正式值源。
|
||||
expect(summarizeAutomarkTableCandidates([
|
||||
{ source: 'pdf_coordinate', reconstruction: { table_id: 't', status: 'needs_review', subrow_layouts: [{ row_offset: 0, column_boundaries: [0, .5, 1] }] } },
|
||||
{ source: 'ocr_coordinate', reconstruction: { table_id: 't', status: 'needs_review', subrow_layouts: [{ row_offset: 0, column_boundaries: [0, 1] }, { row_offset: 1, column_boundaries: [0, 1] }] } },
|
||||
{ source: 'opencv_geometry', reconstruction: { table_id: 't', status: 'needs_review', subrow_layouts: [] } },
|
||||
{ source: 'acroform_widget_geometry', reconstruction: { table_id: 't', status: 'needs_review', subrow_layouts: [{ row_offset: 0, column_boundaries: [0, .25, .75, 1] }] } },
|
||||
], [{ code: 'table_reconstruction_source_conflict', sources: ['pdf_coordinate', 'opencv_geometry'] }])).toEqual([
|
||||
{ source: 'pdf_coordinate', rowCount: 1, columnCount: 2, conflictCodes: ['table_reconstruction_source_conflict'], status: 'needs_review' },
|
||||
{ source: 'ocr_coordinate', rowCount: 2, columnCount: 1, conflictCodes: [], status: 'needs_review' },
|
||||
{ source: 'opencv_geometry', rowCount: 0, columnCount: 0, conflictCodes: ['table_reconstruction_source_conflict'], status: 'needs_review' },
|
||||
{ source: 'acroform_widget_geometry', rowCount: 1, columnCount: 3, conflictCodes: [], status: 'needs_review' },
|
||||
]);
|
||||
});
|
||||
|
||||
});
|
||||
+294
-1
@@ -6,11 +6,16 @@
|
||||
*/
|
||||
|
||||
import type {
|
||||
CoordinateReconstructionSuggestion,
|
||||
CoordinateReconstructionPreview,
|
||||
OrderFieldLayoutSuggestion,
|
||||
OrderFieldValuePreview,
|
||||
OrderProfileCanvasRegion,
|
||||
OrderProfileFieldRegion,
|
||||
OrderProfileRelativeRegion,
|
||||
OrderProfileTableRegion,
|
||||
OrderProfileValidationEvidence,
|
||||
OrderProfileValidationRun,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
export interface OrderProfileLineFieldGroups {
|
||||
@@ -18,6 +23,68 @@ export interface OrderProfileLineFieldGroups {
|
||||
boundRegionIds: Set<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 Schema 字段能否出现在共同视觉画布的绑定下拉中。
|
||||
* 核心逻辑:普通 PDF 的视觉框同时承载 coordinate 正式取值,必须具备该证据授权;
|
||||
* XFA 的视觉框只承担定位和样本展示,正式值由 datasets binding 另行控制,因此只要字段启用即可。
|
||||
* @param field - Schema 字段的最小权限信息。
|
||||
* @param usesExternalValueSource - 是否使用 datasets 等独立正式值源。
|
||||
* @returns 字段是否可作为当前工作台的视觉绑定目标。
|
||||
*/
|
||||
export const isOrderProfileVisualFieldEligible = (
|
||||
field: { enabled?: boolean; allowed_sources?: string[] },
|
||||
usesExternalValueSource: boolean,
|
||||
): boolean => (
|
||||
field.enabled !== false
|
||||
&& (usesExternalValueSource || Boolean(field.allowed_sources?.includes('pdf_coordinate')))
|
||||
);
|
||||
|
||||
/**
|
||||
* 将画布中的视觉表头文字转换为 v2 字段区域。
|
||||
* 核心逻辑:视觉位置不是业务 scope;调用方必须按 Schema 传入 header/line,
|
||||
* 未绑定框由调用方进入草稿未绑定区,不能猜测业务字段。
|
||||
* @param item - 已确认的表头画布区域。
|
||||
* @param scope - Schema 规定的业务字段作用域;视觉表头中的列名通常是 line。
|
||||
* @returns 可持久化的表头字段区域;没有 fieldCode 时返回 null。
|
||||
*/
|
||||
export const toOrderProfileHeaderFieldRegion = (
|
||||
item: Pick<OrderProfileCanvasRegion, 'fieldCode' | 'region'>,
|
||||
scope: 'header' | 'line' = 'header',
|
||||
): OrderProfileFieldRegion | null => {
|
||||
if (!item.fieldCode) return null;
|
||||
return {
|
||||
field_id: '',
|
||||
field_code: item.fieldCode,
|
||||
scope,
|
||||
region: item.region,
|
||||
extractor_key: 'direct',
|
||||
allowed_sources: ['pdf_coordinate'],
|
||||
minimum_evidence_level: 'coordinate',
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 依据已获坐标证据授权的 Schema 字段解析视觉表头的业务作用域。
|
||||
* 核心逻辑:同一 field_code 同时存在 header/line 时,视觉文字不足以裁决业务语义;
|
||||
* 返回 null 使调用方保留未绑定框,等待管理员明确确认。
|
||||
* @param fieldCode - 自动候选给出的字段代码。
|
||||
* @param headerFieldCodes - 可使用坐标证据的 Header 字段代码。
|
||||
* @param lineFieldCodes - 可使用坐标证据的 Line 字段代码。
|
||||
* @returns 唯一作用域;未授权、未知或跨作用域歧义时返回 null。
|
||||
*/
|
||||
export const resolveCoordinateFieldScope = (
|
||||
fieldCode: string | null | undefined,
|
||||
headerFieldCodes: Iterable<string | null | undefined>,
|
||||
lineFieldCodes: Iterable<string | null | undefined>,
|
||||
): 'header' | 'line' | null => {
|
||||
if (!fieldCode) return null;
|
||||
const header = new Set([...headerFieldCodes].filter((code): code is string => Boolean(code)));
|
||||
const line = new Set([...lineFieldCodes].filter((code): code is string => Boolean(code)));
|
||||
const inHeader = header.has(fieldCode);
|
||||
const inLine = line.has(fieldCode);
|
||||
return inHeader === inLine ? null : inHeader ? 'header' : 'line';
|
||||
};
|
||||
|
||||
/**
|
||||
* 按物理行顺序收集唯一的明细字段绑定,供起行字段选择和最终定义复用同一份结果。
|
||||
* 核心逻辑:每个 Schema 字段只归属首个物理行;返回结果可重复读取,不会因预览起行字段而消费绑定。
|
||||
@@ -62,6 +129,187 @@ export const normalizeOrderProfileRelativeRegion = (
|
||||
return x0 < x1 && y0 < y1 ? { x0, y0, x1, y1 } : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 将统一自动标记结果投影为画布区域。
|
||||
* 核心逻辑:字段视觉候选与行重建是并行证据;行重建缺失时仍保留抬头字段框供人工复核,
|
||||
* 但绝不合成 line/field 明细区域。此函数不决定正式取值源。
|
||||
* @param options.reconstruction - 可选的表格行/列重建诊断。
|
||||
* @param options.orderFieldCandidates - 共同视觉字段框候选。
|
||||
* @returns 待确认画布区域,调用方再计算审计摘要和持久化建议。
|
||||
*/
|
||||
export const buildAutomarkSuggestedRegions = (options: {
|
||||
reconstruction: CoordinateReconstructionSuggestion | null | undefined;
|
||||
orderFieldCandidates: OrderFieldLayoutSuggestion[];
|
||||
pageNo: number;
|
||||
unboundColumnLabel: (count: number) => string;
|
||||
lineLabel: (count: number) => string;
|
||||
}): OrderProfileCanvasRegion[] => {
|
||||
const { reconstruction, orderFieldCandidates, pageNo, unboundColumnLabel, lineLabel } = options;
|
||||
const suggestedRegions: OrderProfileCanvasRegion[] = [];
|
||||
for (const [index, header] of (reconstruction?.header_regions || []).entries()) {
|
||||
const headerId = `header_${pageNo}_${index + 1}`;
|
||||
for (const [fieldIndex, field] of (header.fields || []).entries()) {
|
||||
suggestedRegions.push({
|
||||
id: `${headerId}-field-${fieldIndex + 1}`,
|
||||
kind: 'header_field', parentId: headerId,
|
||||
label: field.field_code || field.text || unboundColumnLabel(fieldIndex + 1),
|
||||
region: field.region, fieldCode: field.field_code || null, pageNo,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const [index, candidate] of orderFieldCandidates.entries()) {
|
||||
if (candidate.scope === 'line') continue;
|
||||
if (candidate.status !== 'suggested' || !candidate.value_region) continue;
|
||||
const orderFieldId = `order_field_${pageNo}_${candidate.field_code}_${index + 1}`;
|
||||
if (candidate.anchor_region && candidate.anchor_text) {
|
||||
suggestedRegions.push({
|
||||
id: `${orderFieldId}_anchor`, kind: 'order_anchor', label: candidate.anchor_text,
|
||||
region: candidate.anchor_region, orderFieldId, pageNo,
|
||||
});
|
||||
}
|
||||
suggestedRegions.push({
|
||||
id: orderFieldId, kind: 'order_field',
|
||||
label: candidate.field_code ? candidate.display_name : `${candidate.display_name} · ${unboundColumnLabel(index + 1)}`,
|
||||
region: candidate.value_region, fieldCode: candidate.field_code || null, orderFieldId,
|
||||
valueMode: candidate.value_mode, suggestedValue: candidate.suggested_value || null,
|
||||
evidenceSource: candidate.source, pageNo,
|
||||
});
|
||||
}
|
||||
const layouts = (reconstruction?.subrow_layouts || []).slice().sort(
|
||||
(left, right) => left.row_offset - right.row_offset,
|
||||
);
|
||||
for (const layout of layouts) {
|
||||
const lineId = `line_${pageNo}_${layout.row_offset + 1}`;
|
||||
const region = layout.region || {
|
||||
x0: 0.04, y0: 0.22 + layout.row_offset * 0.075,
|
||||
x1: 0.96, y1: 0.285 + layout.row_offset * 0.075,
|
||||
};
|
||||
suggestedRegions.push({
|
||||
id: lineId, kind: 'line', label: lineLabel(layout.row_offset + 1), region, pageNo,
|
||||
});
|
||||
layout.column_boundaries.slice(0, -1).forEach((left, index) => {
|
||||
const right = layout.column_boundaries[index + 1];
|
||||
if (right === undefined) return;
|
||||
const fieldCode = layout.row_offset === 0 ? layout.suggested_field_codes[index] || null : null;
|
||||
suggestedRegions.push({
|
||||
id: `${lineId}-field-${index + 1}`, kind: 'field', parentId: lineId,
|
||||
label: fieldCode || unboundColumnLabel(index + 1), fieldCode,
|
||||
region: {
|
||||
x0: region.x0 + (region.x1 - region.x0) * left, y0: region.y0,
|
||||
x1: region.x0 + (region.x1 - region.x0) * right, y1: region.y1,
|
||||
}, pageNo,
|
||||
});
|
||||
});
|
||||
}
|
||||
for (const [index, candidate] of orderFieldCandidates.entries()) {
|
||||
if (candidate.scope !== 'line' || candidate.status !== 'suggested' || !candidate.value_region) continue;
|
||||
const centerX = (candidate.value_region.x0 + candidate.value_region.x1) / 2;
|
||||
const centerY = (candidate.value_region.y0 + candidate.value_region.y1) / 2;
|
||||
const matchingLayouts = layouts.filter((layout) => {
|
||||
const region = layout.region || {
|
||||
x0: 0.04, y0: 0.22 + layout.row_offset * 0.075,
|
||||
x1: 0.96, y1: 0.285 + layout.row_offset * 0.075,
|
||||
};
|
||||
return centerX >= region.x0 && centerX <= region.x1 && centerY >= region.y0 && centerY <= region.y1;
|
||||
});
|
||||
// 无唯一候选行时不私自挂靠到任一明细行,保留待复核事实。
|
||||
if (matchingLayouts.length !== 1) continue;
|
||||
const lineId = `line_${pageNo}_${matchingLayouts[0]!.row_offset + 1}`;
|
||||
suggestedRegions.push({
|
||||
id: `${lineId}-widget-${index + 1}`,
|
||||
kind: 'field', parentId: lineId,
|
||||
label: candidate.field_code || candidate.display_name || unboundColumnLabel(index + 1),
|
||||
fieldCode: candidate.field_code || null,
|
||||
region: candidate.value_region,
|
||||
evidenceSource: candidate.source,
|
||||
pageNo,
|
||||
});
|
||||
}
|
||||
return suggestedRegions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 仅在没有多来源候选或结构冲突时选择行重建结果。
|
||||
* 核心逻辑:native/OCR 都是候选证据;多来源时禁止沿用后端的优先投影,避免前端静默裁决。
|
||||
* @param reconstruction - 后端为兼容旧画布返回的单一路径投影
|
||||
* @param tableReconstructions - 各证据来源的候选摘要
|
||||
* @param conflicts - 后端检测到的结构冲突
|
||||
* @returns 可安全用于生成行框的重建结果;存在并行候选或冲突时返回 null
|
||||
*/
|
||||
export const selectAutomarkReconstruction = (
|
||||
reconstruction: CoordinateReconstructionSuggestion | null | undefined,
|
||||
tableReconstructions: unknown,
|
||||
conflicts: unknown,
|
||||
selectedCandidate?: CoordinateReconstructionSuggestion | null,
|
||||
): CoordinateReconstructionSuggestion | null => {
|
||||
// 管理员已明确选择(或 UI 已确认唯一)的候选时,应使用该来源本身;特别是
|
||||
// 动态 XFA 只有 Widget 几何而 coordinate_reconstruction 为 null 的情形。
|
||||
if (selectedCandidate) return selectedCandidate;
|
||||
if (!reconstruction) return null;
|
||||
if (Array.isArray(conflicts) && conflicts.length > 0) return null;
|
||||
if (Array.isArray(tableReconstructions) && tableReconstructions.length > 1) return null;
|
||||
return reconstruction;
|
||||
};
|
||||
|
||||
/**
|
||||
* 为多证据表格候选生成只读摘要,供人工确认区展示。
|
||||
* 核心逻辑:摘要只反映行/列几何与冲突来源,不显示或选择任何正式 datasets 值。
|
||||
*/
|
||||
export const summarizeAutomarkTableCandidates = (
|
||||
candidates: Array<{ source: string; reconstruction: CoordinateReconstructionSuggestion }>,
|
||||
conflicts: unknown,
|
||||
): Array<{ source: string; rowCount: number; columnCount: number; conflictCodes: string[]; status: 'needs_review' }> => {
|
||||
const conflictItems = Array.isArray(conflicts) ? conflicts.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object')) : [];
|
||||
return candidates.map((candidate) => {
|
||||
const layouts = Array.isArray(candidate.reconstruction.subrow_layouts) ? candidate.reconstruction.subrow_layouts : [];
|
||||
const columnCount = layouts.reduce((max, layout) => {
|
||||
const boundaries = Array.isArray(layout.column_boundaries) ? layout.column_boundaries.length - 1 : 0;
|
||||
return Math.max(max, boundaries);
|
||||
}, 0);
|
||||
const conflictCodes = conflictItems
|
||||
.filter((item) => Array.isArray(item.sources) && item.sources.map(String).includes(candidate.source))
|
||||
.map((item) => String(item.code || 'table_reconstruction_source_conflict'));
|
||||
return { source: candidate.source, rowCount: layouts.length, columnCount, conflictCodes, status: 'needs_review' };
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 将后端统一 field_binding DTO 转为旧页面候选形状,并保留真实证据来源。
|
||||
* 核心逻辑:只接受视觉 binding;evidence_sources 为空时按不可确认处理,禁止默认宣称 native。
|
||||
* @param candidates - 自动标记 Job 返回的候选 DTO。
|
||||
* @param pageNo - 当前画布页码。
|
||||
* @returns 仅供页面复核的订单字段候选。
|
||||
*/
|
||||
export const normalizeAutomarkFieldCandidates = (
|
||||
candidates: Array<Record<string, unknown>>,
|
||||
): OrderFieldLayoutSuggestion[] => candidates
|
||||
.filter((item) => item.candidate_kind === 'field_binding' && item.binding && typeof item.binding === 'object')
|
||||
.map((item) => {
|
||||
const binding = item.binding as Record<string, unknown>;
|
||||
const visual = binding.visual_binding && typeof binding.visual_binding === 'object'
|
||||
? binding.visual_binding as Record<string, unknown> : {};
|
||||
const sources = Array.isArray(item.evidence_sources)
|
||||
? item.evidence_sources.map((source) => String(source || '')).filter(Boolean)
|
||||
: [];
|
||||
const source = sources[0] === 'ocr_coordinate' || sources[0] === 'acroform_widget'
|
||||
? sources[0] : 'pdf_coordinate';
|
||||
const needsReview = item.needs_review === true || !sources.length;
|
||||
return {
|
||||
field_id: String(binding.field_id || ''),
|
||||
field_code: String(binding.field_code || ''),
|
||||
// 未匹配的 XFA/AcroForm Widget 只有技术控件名和几何;它必须作为
|
||||
// 未绑定视觉候选进入共同画布,不能因 field_code 为空而丢失,也不能猜业务字段。
|
||||
display_name: String(binding.field_code || binding.display_name || binding.field_id || ''),
|
||||
scope: binding.scope === 'line' ? 'line' : 'header',
|
||||
source,
|
||||
status: 'suggested',
|
||||
issue: needsReview ? 'visual_candidate_needs_review' : null,
|
||||
anchor_text: undefined,
|
||||
anchor_region: undefined,
|
||||
value_region: visual.normalized_bbox as OrderProfileRelativeRegion | undefined,
|
||||
} satisfies OrderFieldLayoutSuggestion;
|
||||
});
|
||||
|
||||
/**
|
||||
* 判断是否显示普通表格预览;可直接创建 Profile 的表格不受上一张表多物理行状态影响。
|
||||
* @param profileCreationAllowed - 当前表格是否可直接创建 Profile
|
||||
@@ -148,6 +396,7 @@ export const buildOrderProfileRecognitionResults = (
|
||||
fieldValues: OrderFieldValuePreview[],
|
||||
reconstruction: CoordinateReconstructionPreview | null,
|
||||
fieldValueState: 'idle' | 'loading' | 'ready' | 'failed' = 'idle',
|
||||
datasetsEvidence: OrderProfileValidationEvidence | null = null,
|
||||
): { header: OrderProfileRecognitionResult[]; line: OrderProfileRecognitionResult[] } => {
|
||||
const valuesByCode = new Map(fieldValues.map((item) => [item.field_code, item]));
|
||||
const header = pageRegions
|
||||
@@ -165,12 +414,29 @@ export const buildOrderProfileRecognitionResults = (
|
||||
: fieldValueState === 'failed' ? 'failed' as const : 'unavailable' as const,
|
||||
};
|
||||
});
|
||||
if (!reconstruction) return { header, line: [] };
|
||||
const regionsByCode = new Map(
|
||||
pageRegions
|
||||
.filter((item) => item.kind === 'field' && item.fieldCode)
|
||||
.map((item) => [item.fieldCode!, item.id]),
|
||||
);
|
||||
// XFA datasets 是正式明细值源;共同视觉坐标只定位和交叉校验,不能把表头或
|
||||
// OCR 候选伪装成已读取的行值。传入此证据时完全忽略 coordinate reconstruction。
|
||||
if (datasetsEvidence) {
|
||||
const line = datasetsEvidence.lines.flatMap((row) => (
|
||||
row.fields.map((field) => ({
|
||||
id: regionsByCode.get(field.field_code) || null,
|
||||
key: `xfa-${row.row_index}-${field.field_code}`,
|
||||
fieldCode: field.field_code,
|
||||
value: field.normalized_value || null,
|
||||
status: field.status === 'passed' && field.normalized_value
|
||||
? 'read' as const
|
||||
: 'unavailable' as const,
|
||||
rowNo: row.row_index + 1,
|
||||
}))
|
||||
));
|
||||
return { header, line };
|
||||
}
|
||||
if (!reconstruction) return { header, line: [] };
|
||||
const fieldCodes = reconstruction.rows[0] || [];
|
||||
const line = reconstruction.rows.slice(1).flatMap((row, rowIndex) => {
|
||||
const sourceIndex = rowIndex + 1;
|
||||
@@ -190,6 +456,33 @@ export const buildOrderProfileRecognitionResults = (
|
||||
return { header, line };
|
||||
};
|
||||
|
||||
/**
|
||||
* 选择与当前草稿精确匹配的 XFA 当前样本正式证据。
|
||||
* 核心逻辑:验证 Run 是不可变的;只消费 current_sample、passed、checksum 相同的
|
||||
* datasets 证据,旧版本或其他运行类型不能在编辑工作台伪装成当前样本值。
|
||||
*/
|
||||
export const selectCurrentDatasetsValidationEvidence = (
|
||||
runs: OrderProfileValidationRun[],
|
||||
definitionChecksum: string | null | undefined,
|
||||
): OrderProfileValidationEvidence | null => {
|
||||
if (!definitionChecksum) return null;
|
||||
const run = runs.find((item) => (
|
||||
item.run_type === 'current_sample'
|
||||
&& item.status === 'passed'
|
||||
&& item.definition_checksum === definitionChecksum
|
||||
));
|
||||
const evidence = run?.summary?.validation_evidence;
|
||||
if (!evidence || typeof evidence !== 'object' || Array.isArray(evidence)) return null;
|
||||
const value = evidence as Partial<OrderProfileValidationEvidence>;
|
||||
if (!Array.isArray(value.header_fields) || !Array.isArray(value.lines)) return null;
|
||||
return {
|
||||
header_fields: value.header_fields,
|
||||
lines: value.lines,
|
||||
cross_checks: value.cross_checks && typeof value.cross_checks === 'object' && !Array.isArray(value.cross_checks)
|
||||
? value.cross_checks : {},
|
||||
} as OrderProfileValidationEvidence;
|
||||
};
|
||||
|
||||
/**
|
||||
* 根据已确认表头的横向覆盖关系建议明细字段;冲突或覆盖不足时拒绝猜测。
|
||||
* @param fieldRegion - 当前待绑定的明细字段区域
|
||||
|
||||
+2
-2
@@ -9,7 +9,7 @@ import type {
|
||||
OrderProfileCanvasRegion,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { asCoordinateProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { asVisualProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { restoreOrderProfileRegionPageNo } from './orderProfileForm.utils';
|
||||
|
||||
const mergeEquivalentOrderAnchors = (items: OrderProfileCanvasRegion[]) => {
|
||||
@@ -61,7 +61,7 @@ const pageNoOf = (pageScope: 'first_page' | 'all_pages' | 'exact_page', pageNo?:
|
||||
export const buildOrderProfileReadonlyRegions = (
|
||||
profile: ShippingOrderDocumentProfile,
|
||||
): OrderProfileCanvasRegion[] => {
|
||||
const definition = asCoordinateProfileDefinition(profile.definition);
|
||||
const definition = asVisualProfileDefinition(profile.definition);
|
||||
const restored: OrderProfileCanvasRegion[] = [
|
||||
...(definition.document_match.required_anchors || []).flatMap<OrderProfileCanvasRegion>((anchor) => {
|
||||
if (!anchor.label_region || !anchor.value_region || !anchor.page_no) return [];
|
||||
|
||||
+74
-1
@@ -9,9 +9,16 @@ import {
|
||||
collectBoundXfaFieldIds,
|
||||
computeXfaMappingCoverage,
|
||||
flattenXfaTreeNodes,
|
||||
hashXfaDataPath,
|
||||
resolveAuthoritativePathId,
|
||||
resolveMirrorPathIds,
|
||||
summarizeXfaMappingBlockers,
|
||||
} from './xfaProfileMapping.utils';
|
||||
import type { OrderXfaDatasetProfileDefinition, XfaFieldTreeNode } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type {
|
||||
OrderXfaDatasetProfileDefinition,
|
||||
XfaCollectionCandidate,
|
||||
XfaFieldTreeNode,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const baseDefinition: OrderXfaDatasetProfileDefinition = {
|
||||
template_mode: 'xfa_dataset',
|
||||
@@ -123,4 +130,70 @@ describe('xfaProfileMapping split utils', () => {
|
||||
const flatMulti = flattenXfaTreeNodes(multiline);
|
||||
expect((flatMulti[0]?.lineCount || 0) > 1).toBe(true);
|
||||
});
|
||||
|
||||
it('restores legacy source contract collection path ids by exact path hash', async () => {
|
||||
const authoritativePath = '/data/ORDER/ITEMS/DATA';
|
||||
const mirrorPath = '/data/ORDER/ITEMS_COPY/DATA';
|
||||
const candidates: XfaCollectionCandidate[] = [{
|
||||
path_id: 'path-unrelated',
|
||||
collection_path_hash: await hashXfaDataPath('/data/OTHER/DATA'),
|
||||
path_label: 'Same display name',
|
||||
local_name: 'DATA',
|
||||
field_names: [],
|
||||
field_count: 0,
|
||||
non_empty_field_count: 0,
|
||||
non_empty_rate: 0,
|
||||
row_count: 0,
|
||||
selectable: true,
|
||||
recommended_role: 'candidate',
|
||||
recommendation_reasons: [],
|
||||
exclusion_reasons: [],
|
||||
sibling_collection_path_hashes: [],
|
||||
}, {
|
||||
path_id: 'path-authoritative',
|
||||
collection_path_hash: await hashXfaDataPath(authoritativePath),
|
||||
path_label: 'Same display name',
|
||||
local_name: 'DATA',
|
||||
field_names: [],
|
||||
field_count: 0,
|
||||
non_empty_field_count: 0,
|
||||
non_empty_rate: 0,
|
||||
row_count: 1,
|
||||
selectable: true,
|
||||
recommended_role: 'authoritative',
|
||||
recommendation_reasons: [],
|
||||
exclusion_reasons: [],
|
||||
sibling_collection_path_hashes: [],
|
||||
}, {
|
||||
path_id: 'path-mirror',
|
||||
collection_path_hash: await hashXfaDataPath(mirrorPath),
|
||||
path_label: 'Same display name',
|
||||
local_name: 'DATA',
|
||||
field_names: [],
|
||||
field_count: 0,
|
||||
non_empty_field_count: 0,
|
||||
non_empty_rate: 0,
|
||||
row_count: 1,
|
||||
selectable: true,
|
||||
recommended_role: 'mirror',
|
||||
recommendation_reasons: [],
|
||||
exclusion_reasons: [],
|
||||
sibling_collection_path_hashes: [],
|
||||
}];
|
||||
const definition: OrderXfaDatasetProfileDefinition = {
|
||||
...baseDefinition,
|
||||
source_contract: {
|
||||
...baseDefinition.source_contract,
|
||||
authoritative_line_collection_path: authoritativePath,
|
||||
mirror_collection_paths: [mirrorPath],
|
||||
},
|
||||
};
|
||||
|
||||
const authoritativePathId = await resolveAuthoritativePathId(definition, candidates, []);
|
||||
const mirrorPathIds = await resolveMirrorPathIds(definition, candidates, authoritativePathId);
|
||||
|
||||
// 关键断言:历史定义只能以完整路径哈希恢复,不得按同名 DATA 或候选排序猜测。
|
||||
expect(authoritativePathId).toBe('path-authoritative');
|
||||
expect(mirrorPathIds).toEqual(['path-mirror']);
|
||||
});
|
||||
});
|
||||
@@ -65,23 +65,34 @@ export interface OrderProfileOrderFieldLayout { layout_id: string; field_id: str
|
||||
export interface OrderProfileDraftUnboundOrderFieldLayout { layout_id: string; label: string; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; minimum_evidence_level: OrderProfileEvidenceLevel; }
|
||||
export interface OrderProfileHeaderLayout { layout_id: string; region: OrderProfileRelativeRegion; field_regions: OrderProfileFieldRegion[]; }
|
||||
export interface OrderProfileLineLayout { layout_id: string; row_offset: number; role: 'main' | 'continuation'; region: OrderProfileRelativeRegion; field_regions: OrderProfileFieldRegion[]; new_line_anchor?: OrderProfileAnchorRule | null; continuation_conditions: OrderProfileAnchorRule[]; required_fields: string[]; allowed_empty_fields: string[]; }
|
||||
export interface OrderProfileTableRegion { region_id: string; page_scope: 'first_page' | 'all_pages' | 'continuation_pages' | 'exact_page'; page_no?: number | null; region: OrderProfileRelativeRegion; /** 逻辑明细起行锚点;默认 customer_po_line_no;line_no 为可识别内部项次亦可绑定。 */ line_start_field_code?: string; /** 默认固定子行;仅显式启用时允许在同一逻辑明细内跨视觉行按列重建。 */ row_reconstruction_mode?: OrderProfileRowReconstructionMode; header_layouts: OrderProfileHeaderLayout[]; line_layouts: OrderProfileLineLayout[]; continuation_rule: { allow_cross_page: boolean; required_anchor_ids: string[] }; termination_rules: Array<{ rule_id: string; anchor: OrderProfileAnchorRule }>; exclusion_regions: OrderProfileRelativeRegion[]; draft_unbound_field_regions?: Array<{ region_id: string; parent_layout_id: string; label: string; region: OrderProfileRelativeRegion }>; }
|
||||
export interface OrderProfileTableRegion { region_id: string; page_scope: 'first_page' | 'all_pages' | 'continuation_pages' | 'exact_page'; page_no?: number | null; region: OrderProfileRelativeRegion; /** 逻辑明细起行锚点;默认 customer_po_line_no;line_no 为可识别内部项次亦可绑定。 */ line_start_field_code?: string; /** 默认固定子行;仅显式启用时允许在同一逻辑明细内跨视觉行按列重建。 */ row_reconstruction_mode?: OrderProfileRowReconstructionMode; /** 管理员确认的视觉行结构来源;审计用途,不是字段正式值源。 */ visual_evidence_source?: 'pdf_coordinate' | 'ocr_coordinate' | 'opencv_geometry' | 'acroform_widget_geometry' | null; header_layouts: OrderProfileHeaderLayout[]; line_layouts: OrderProfileLineLayout[]; continuation_rule: { allow_cross_page: boolean; required_anchor_ids: string[] }; termination_rules: Array<{ rule_id: string; anchor: OrderProfileAnchorRule }>; exclusion_regions: OrderProfileRelativeRegion[]; draft_unbound_field_regions?: Array<{ region_id: string; parent_layout_id: string; label: string; region: OrderProfileRelativeRegion }>; }
|
||||
export interface OrderProfileDocumentMatch { document_type: 'purchase_order'; page_pattern: 'one_or_more'; required_anchors: OrderProfileDocumentMatchAnchor[]; optional_anchors: OrderProfileDocumentMatchAnchor[]; minimum_score: number; minimum_margin: number; }
|
||||
|
||||
/** coordinate 模式 definition:不得与 XFA 映射字段混用。 */
|
||||
export interface OrderCoordinateProfileDefinition {
|
||||
template_mode?: 'coordinate';
|
||||
/**
|
||||
* 所有模板共用的视觉 matcher 与画布定义。
|
||||
*
|
||||
* PDF/OCR 与 XFA 都用同一份 document/table/field 几何配置选择 Profile、编辑、
|
||||
* 预览、自动标注和盲测;最终字段值如何读取不属于这一层。
|
||||
*/
|
||||
export interface OrderProfileVisualDefinition {
|
||||
main_table_id?: string | null;
|
||||
document_match: OrderProfileDocumentMatch;
|
||||
table_regions: OrderProfileTableRegion[];
|
||||
order_field_layouts?: OrderProfileOrderFieldLayout[];
|
||||
draft_unbound_order_field_layouts?: OrderProfileDraftUnboundOrderFieldLayout[];
|
||||
}
|
||||
|
||||
/** coordinate/OCR adapter 仅复用共同视觉定义,不增加独立生命周期字段。 */
|
||||
export interface OrderCoordinateProfileDefinition extends OrderProfileVisualDefinition {
|
||||
template_mode?: 'coordinate';
|
||||
}
|
||||
|
||||
export interface XfaSourceContract {
|
||||
template_packet_checksum: string;
|
||||
dataset_structure_fingerprint: string;
|
||||
dataset_root_path: string;
|
||||
authoritative_line_collection_path: string;
|
||||
/** 编辑器配置前允许为空;发布检查必须补齐。 */
|
||||
authoritative_line_collection_path?: string | null;
|
||||
mirror_collection_paths: string[];
|
||||
}
|
||||
|
||||
@@ -97,7 +108,8 @@ export interface XfaFieldMapping {
|
||||
}
|
||||
|
||||
export interface XfaLineMapping {
|
||||
row_path: string;
|
||||
/** 编辑器配置前允许为空;配置字段值映射后必须与权威集合一致。 */
|
||||
row_path?: string | null;
|
||||
fields: XfaFieldMapping[];
|
||||
}
|
||||
|
||||
@@ -116,12 +128,12 @@ export interface XfaNormalizedBBox {
|
||||
y1: number;
|
||||
}
|
||||
|
||||
export type XfaValueBindingType = 'xfa_dataset' | 'pdf_coordinate' | 'ocr_coordinate';
|
||||
export type XfaValueBindingType = 'xfa_dataset';
|
||||
export type XfaVisualBindingSource = 'acroform_widget' | 'user_drawn' | 'system_suggested';
|
||||
export type XfaVisualBindingStatus = 'suggested' | 'confirmed' | 'rejected' | 'needs_review';
|
||||
export type XfaBindingScope = 'header' | 'line';
|
||||
|
||||
/** 正式值绑定:XFA 仅 datasets 路径;普通 PDF 允许坐标/OCR。 */
|
||||
/** 正式值绑定:XFA 仅 datasets 路径;共同字段布局负责视觉标签与值区域。 */
|
||||
export interface XfaValueBinding {
|
||||
type: XfaValueBindingType;
|
||||
path_id?: string | null;
|
||||
@@ -129,7 +141,7 @@ export interface XfaValueBinding {
|
||||
region_id?: string | null;
|
||||
}
|
||||
|
||||
/** 视觉绑定:页码 + 归一化框 + 确认状态;发布前正式字段须 confirmed。 */
|
||||
/** @deprecated 历史 XFA 草稿视觉绑定;新保存只引用共同 order_field_layouts。 */
|
||||
export interface XfaVisualBinding {
|
||||
page_no: number;
|
||||
normalized_bbox: XfaNormalizedBBox;
|
||||
@@ -153,19 +165,21 @@ export interface XfaSplitRuleRef {
|
||||
segment_id: string;
|
||||
}
|
||||
|
||||
/** 统一字段绑定:value_binding + visual_binding + 可选 split_rule_ref。 */
|
||||
/** XFA 末端适配:共同字段布局引用 + datasets 路径 + 可选拆分段。 */
|
||||
export interface XfaUnifiedFieldBinding {
|
||||
binding_id: string;
|
||||
field_id: string;
|
||||
field_code: string;
|
||||
scope: XfaBindingScope;
|
||||
field_layout_id?: string | null;
|
||||
value_binding: XfaValueBinding;
|
||||
visual_binding: XfaVisualBinding;
|
||||
/** 仅用于读取尚未重存的历史草稿。 */
|
||||
visual_binding?: XfaVisualBinding | null;
|
||||
split_rule_ref?: XfaSplitRuleRef | null;
|
||||
}
|
||||
|
||||
/** xfa_dataset 模式 definition:禁止混入 table_regions / order_field_layouts。 */
|
||||
export interface OrderXfaDatasetProfileDefinition {
|
||||
/** XFA datasets adapter:在共同视觉定义之外增加末端权威取值契约。 */
|
||||
export interface OrderXfaDatasetProfileDefinition extends OrderProfileVisualDefinition {
|
||||
template_mode: 'xfa_dataset';
|
||||
source_contract: XfaSourceContract;
|
||||
header_mappings: XfaFieldMapping[];
|
||||
@@ -319,46 +333,6 @@ export interface XfaSplitRulesValidateResponse {
|
||||
}
|
||||
|
||||
/** 视觉绑定候选(suggest 返回;歧义不自动确认)。 */
|
||||
export interface XfaVisualPathCandidate {
|
||||
path_id: string;
|
||||
dataset_value_masked?: string | null;
|
||||
score?: number;
|
||||
reason_codes?: string[];
|
||||
}
|
||||
|
||||
export interface XfaVisualBindingCandidate {
|
||||
candidate_id?: string;
|
||||
binding_id?: string;
|
||||
widget_id?: string;
|
||||
page_no?: number;
|
||||
normalized_bbox?: XfaNormalizedBBox;
|
||||
acroform_field_name_tail?: string | null;
|
||||
path_id?: string | null;
|
||||
field_code?: string | null;
|
||||
display_name?: string | null;
|
||||
confidence?: number;
|
||||
status?: XfaVisualBindingStatus | 'suggested';
|
||||
visual_binding?: XfaVisualBinding;
|
||||
path_candidates?: Array<XfaVisualPathCandidate & {
|
||||
data_path_hash?: string;
|
||||
match_hint?: string;
|
||||
confidence?: number;
|
||||
}>;
|
||||
reason_codes?: string[];
|
||||
}
|
||||
|
||||
export interface XfaVisualBindingsSuggestResponse {
|
||||
profile_id?: number;
|
||||
document_id: number;
|
||||
page_no?: number;
|
||||
normalized_bbox?: XfaNormalizedBBox;
|
||||
candidates: XfaVisualBindingCandidate[];
|
||||
diagnostics?: Array<{ code: string; message: string }> | Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** @deprecated 使用 XfaVisualBindingsSuggestResponse */
|
||||
export type XfaVisualBindingSuggestResponse = XfaVisualBindingsSuggestResponse;
|
||||
|
||||
export interface XfaVisualBindingMutationResponse {
|
||||
binding_id: string;
|
||||
visual_binding?: XfaVisualBinding;
|
||||
@@ -383,17 +357,6 @@ export interface XfaSplitRulesSuggestResponse {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface XfaUnifiedMappingSuggestResponse {
|
||||
profile_id: number;
|
||||
document_id: number;
|
||||
suggestion_status?: string;
|
||||
suggestion_id?: string;
|
||||
suggestion_checksum?: string;
|
||||
visual_suggestion?: XfaVisualBindingsSuggestResponse | null;
|
||||
split_rule_suggestion?: XfaSplitRulesSuggestResponse | null;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export type OrderProfileDefinition = OrderCoordinateProfileDefinition | OrderXfaDatasetProfileDefinition;
|
||||
|
||||
/**
|
||||
@@ -407,18 +370,19 @@ export function isXfaDatasetProfileDefinition(
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 definition 收窄为 coordinate 分支;XFA 模式不得进入坐标画布逻辑。
|
||||
* 返回所有模板共有的视觉定义,供同一张 PDF 画布恢复区域。
|
||||
* 最终值源 adapter 由调用方另行处理,不能在此拒绝 XFA 的共同视觉字段。
|
||||
* @param definition Profile definition 联合类型
|
||||
*/
|
||||
export function asCoordinateProfileDefinition(
|
||||
export function asVisualProfileDefinition(
|
||||
definition: OrderProfileDefinition,
|
||||
): OrderCoordinateProfileDefinition {
|
||||
if (isXfaDatasetProfileDefinition(definition)) {
|
||||
throw new Error('XFA dataset definition cannot be projected as coordinate regions');
|
||||
}
|
||||
): OrderProfileVisualDefinition {
|
||||
return definition;
|
||||
}
|
||||
|
||||
/** @deprecated 使用 asVisualProfileDefinition;保留兼容旧调用方。 */
|
||||
export const asCoordinateProfileDefinition = asVisualProfileDefinition;
|
||||
|
||||
export interface XfaFieldEvidenceRef {
|
||||
source: 'xfa_dataset';
|
||||
document_id: number;
|
||||
@@ -442,6 +406,8 @@ export interface ShippingOrderDocumentProfile {
|
||||
schema_checksum?: string | null;
|
||||
definition: OrderProfileDefinition;
|
||||
checksum?: string | null;
|
||||
/** 当前草稿定义的服务端冻结结构指纹;用于拒绝旧验证证据的回显。 */
|
||||
structure_fingerprint?: string | null;
|
||||
lock_version: number;
|
||||
change_note?: string | null;
|
||||
source_profile_id?: number | null;
|
||||
@@ -493,7 +459,7 @@ export interface ShippingOrderDocumentProfile {
|
||||
line_mapping_count?: number;
|
||||
mirror_collection_count?: number;
|
||||
};
|
||||
xfa_structure_identity?: {
|
||||
value_source_identity?: {
|
||||
template_packet_checksum?: string | null;
|
||||
dataset_structure_fingerprint?: string | null;
|
||||
has_authoritative_collection?: boolean;
|
||||
@@ -501,7 +467,7 @@ export interface ShippingOrderDocumentProfile {
|
||||
header_mapping_count?: number;
|
||||
line_mapping_count?: number;
|
||||
} | null;
|
||||
xfa_readonly_mapping?: {
|
||||
value_source_readonly_mapping?: {
|
||||
source_contract?: Record<string, unknown>;
|
||||
header_mappings?: Array<Record<string, unknown>>;
|
||||
line_mappings?: Array<Record<string, unknown>>;
|
||||
@@ -568,6 +534,29 @@ export interface OrderProfileEditLease {
|
||||
lock_version: number;
|
||||
}
|
||||
|
||||
/** 当前样本验证的统一字段证据;value adapter 仅改变证据产生方式。 */
|
||||
export interface OrderProfileValidationEvidenceField {
|
||||
field_id: string;
|
||||
field_code: string;
|
||||
raw_value: string | null;
|
||||
normalized_value: string | null;
|
||||
status: 'passed' | 'failed' | 'missing' | string;
|
||||
issues: string[];
|
||||
}
|
||||
|
||||
/** 当前样本验证的统一明细行证据。 */
|
||||
export interface OrderProfileValidationEvidenceLine {
|
||||
row_index: number;
|
||||
fields: OrderProfileValidationEvidenceField[];
|
||||
}
|
||||
|
||||
/** 所有模板共用的当前样本验证证据投影;XFA 对账仅作为 cross_checks 扩展。 */
|
||||
export interface OrderProfileValidationEvidence {
|
||||
header_fields: OrderProfileValidationEvidenceField[];
|
||||
lines: OrderProfileValidationEvidenceLine[];
|
||||
cross_checks: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** 绑定精确草稿 checksum 的不可变验证运行摘要。 */
|
||||
export interface OrderProfileValidationRun {
|
||||
id: number;
|
||||
@@ -600,6 +589,15 @@ export interface OrderProfileLayoutSignatureStatus {
|
||||
template_packet_checksum?: string | null;
|
||||
matcher_policy_version?: string | null;
|
||||
provider_versions?: Array<Record<string, unknown>> | null;
|
||||
adapter_run_type?: 'layout_signature' | 'xfa_structure_signature' | null;
|
||||
identity_details?: {
|
||||
adapter?: 'coordinate_ocr' | 'xfa_dataset';
|
||||
header_token_coverage?: number | null;
|
||||
dataset_structure_fingerprint?: string | null;
|
||||
template_packet_checksum?: string | null;
|
||||
parser_identity?: string | null;
|
||||
analysis_count?: number | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface OrderProfileOverlapConflictProfile {
|
||||
@@ -649,10 +647,8 @@ export interface OrderProfilePublishCheckReport {
|
||||
operation_id: string;
|
||||
created_at: string;
|
||||
consumed_at: string | null;
|
||||
layout_signature_status?: OrderProfileLayoutSignatureStatus | null;
|
||||
layout_signature_summary?: Record<string, unknown> | null;
|
||||
xfa_structure_signature_status?: OrderProfileLayoutSignatureStatus | null;
|
||||
xfa_structure_signature_summary?: Record<string, unknown> | null;
|
||||
profile_identity_signature_status?: OrderProfileLayoutSignatureStatus | null;
|
||||
profile_identity_signature_summary?: Record<string, unknown> | null;
|
||||
template_mode?: 'coordinate' | 'xfa_dataset' | null;
|
||||
overlap_summary?: OrderProfileOverlapSummary | null;
|
||||
conflict_profiles?: OrderProfileOverlapConflictProfile[];
|
||||
@@ -829,71 +825,6 @@ export interface OrderProfilePdfPreviewGrant { document_id: number; preview_toke
|
||||
/** @deprecated 使用 OrderProfilePdfPreviewGrant;保留给旧 XFA 调用方。 */
|
||||
export type OrderProfileXfaPdfPreviewGrant = OrderProfilePdfPreviewGrant;
|
||||
|
||||
/** XFA 合成预览身份上下文(与后端 PreviewIdentityContext 对齐)。 */
|
||||
export interface XfaSyntheticPreviewIdentity {
|
||||
document_id: number | null;
|
||||
layout_version_id: number | null;
|
||||
structure_analysis_id: number | string | null;
|
||||
source_content_hash: string;
|
||||
template_packet_checksum: string;
|
||||
datasets_packet_checksum: string;
|
||||
dataset_structure_fingerprint: string;
|
||||
preview_render_checksum: string;
|
||||
render_mode: string;
|
||||
renderer_version: string;
|
||||
page_count: number;
|
||||
}
|
||||
|
||||
/** 合成预览页元数据(含短时 token,不含 PNG)。 */
|
||||
export interface XfaSyntheticPreviewPageMeta {
|
||||
page_no: number;
|
||||
preview_token: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
drawn_echo_count?: number;
|
||||
}
|
||||
|
||||
/** 可写入 definition.xfa_preview 的发布证据(无 PNG)。 */
|
||||
export interface XfaPreviewDefinitionMeta {
|
||||
status?: string | null;
|
||||
preview_render_checksum?: string | null;
|
||||
render_mode?: string;
|
||||
renderer_version?: string;
|
||||
page_count?: number;
|
||||
pages_ready?: number[];
|
||||
source_page_count?: number | null;
|
||||
synthetic_page_count?: number | null;
|
||||
pages?: Array<{
|
||||
page_no?: number;
|
||||
source_page_box?: Record<string, number>;
|
||||
synthetic_page_box?: Record<string, number>;
|
||||
page_identity_hash?: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
/** POST/GET xfa/preview 响应摘要。 */
|
||||
export interface XfaSyntheticPreviewResponse {
|
||||
document_id: number | null;
|
||||
identity: XfaSyntheticPreviewIdentity;
|
||||
status: 'ready' | 'needs_review' | 'failed' | 'stale' | string;
|
||||
error_code?: string | null;
|
||||
render_mode: string;
|
||||
renderer_version: string;
|
||||
page_count: number;
|
||||
preview_render_checksum?: string | null;
|
||||
pages: XfaSyntheticPreviewPageMeta[];
|
||||
expires_in_seconds: number;
|
||||
cache_hit: boolean;
|
||||
diagnostics?: Record<string, unknown>;
|
||||
/** BE-3:前端落库 definition.xfa_preview 用 */
|
||||
definition_preview_meta?: XfaPreviewDefinitionMeta;
|
||||
source_page_count?: number | null;
|
||||
synthetic_page_count?: number | null;
|
||||
}
|
||||
|
||||
/** 工作台预览模式:原始 PDFium 对照 vs datasets 合成权威画布。 */
|
||||
export type XfaPreviewCanvasMode = 'original' | 'synthetic';
|
||||
|
||||
export interface OrderProfileBoundSample {
|
||||
id: number;
|
||||
document_id: number;
|
||||
@@ -988,7 +919,7 @@ export interface OrderProfileBlindTestCandidate {
|
||||
/** 工作台的本地几何状态;保存前转为 v2 相对区域定义。 */
|
||||
export interface OrderProfileCanvasRegion {
|
||||
id: string;
|
||||
kind: 'header' | 'header_field' | 'line' | 'field' | 'order_anchor' | 'order_field' | 'exclusion' | 'document_anchor_label' | 'document_anchor_value' | 'xfa_visual';
|
||||
kind: 'header' | 'header_field' | 'line' | 'field' | 'order_anchor' | 'order_field' | 'exclusion' | 'document_anchor_label' | 'document_anchor_value';
|
||||
label: string;
|
||||
region: OrderProfileRelativeRegion;
|
||||
fieldCode?: string | null;
|
||||
@@ -1006,11 +937,11 @@ export interface OrderProfileCanvasRegion {
|
||||
/** 必需锚点固定值是否命中;普通字段没有配置值时为 null。 */
|
||||
matchesConfigured?: boolean | null;
|
||||
/** 自动建议实际使用的坐标证据来源,保存时映射到最小证据等级。 */
|
||||
evidenceSource?: 'pdf_coordinate' | 'ocr_coordinate';
|
||||
evidenceSource?: 'pdf_coordinate' | 'ocr_coordinate' | 'acroform_widget';
|
||||
stopAnchorText?: string | null;
|
||||
/** 标记所属文档页;画布切页时仅渲染当前页的区域。 */
|
||||
pageNo: number;
|
||||
/** XFA 视觉绑定确认状态;仅 kind=xfa_visual 时使用。 */
|
||||
/** datasets adapter 可附加的视觉证据确认状态,不影响共同画布区域种类。 */
|
||||
visualBindingStatus?: XfaVisualBindingStatus;
|
||||
}
|
||||
|
||||
@@ -1024,7 +955,6 @@ export interface OrderProfileSampleDocument {
|
||||
provider_version?: string | null;
|
||||
table_count: number;
|
||||
document_kind?: string | null;
|
||||
xfa_analysis_ready?: boolean;
|
||||
created_at?: string | null;
|
||||
purpose: 'order_document_profile_sample';
|
||||
parse_status: string;
|
||||
@@ -1185,7 +1115,10 @@ export interface OrderFieldLayoutSuggestion {
|
||||
field_id: string;
|
||||
field_code: string;
|
||||
display_name: string;
|
||||
source: 'pdf_coordinate' | 'ocr_coordinate';
|
||||
/** 仅由已冻结主表几何归类为 line;不代表已映射 Schema 字段。 */
|
||||
scope?: 'header' | 'line';
|
||||
/** 仅限画布定位/复核证据;不能替代 XFA datasets 正式取值绑定。 */
|
||||
source: 'pdf_coordinate' | 'ocr_coordinate' | 'acroform_widget';
|
||||
status: 'suggested' | 'ambiguous' | 'unavailable';
|
||||
binding_status?: 'bound' | 'unbound';
|
||||
issue: string | null;
|
||||
@@ -1209,6 +1142,7 @@ export interface OrderFieldValuePreview {
|
||||
field_code: string;
|
||||
value: string | null;
|
||||
status: 'confirmed' | 'needs_review' | 'unavailable';
|
||||
source?: 'pdf_coordinate' | 'ocr_coordinate' | 'acroform_widget' | null;
|
||||
page_no: number | null;
|
||||
issues: string[];
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user