feat(shipping-notice): 完善 XFA 模板映射与订单审核流程
- 统一 XFA 数据集、字段拆分、校验及运行时解析 - 完善订单模板管理、发布检查与迁移状态 - 优化订单审核草稿、预约回退及 STP 投影缓存 - 更新前端模板编辑器、映射组件与多语言错误文案 - 补充后端与前端测试,并更新本地集成启动配置
This commit is contained in:
1 parent
43a30a7489
commit
4ec436d44c
67 files changed
+5411
-528
No files matched your search
@@ -811,9 +811,19 @@ def approve_order_document_profile_test_suite(suite_id: int):
|
||||
)
|
||||
@require_admin
|
||||
def get_order_document_profile_sample_value_field_tree(document_id: int):
|
||||
"""返回当前值源字段树安全投影;不含原始正文。"""
|
||||
"""
|
||||
返回当前值源字段树安全投影。
|
||||
|
||||
核心逻辑:默认脱敏展示;reveal=true 且具备 audit_sensitive_read 时,
|
||||
树节点 sample_value_display 写入完整样本值(仍不输出 raw_value 键),供映射台选型。
|
||||
"""
|
||||
reveal = str(request.args.get('reveal') or '').strip().lower() in {'1', 'true', 'yes'}
|
||||
if reveal:
|
||||
_require_audit_sensitive_read_permission()
|
||||
return _private_ok(_sample_mapping_adapter(document_id).mapping_field_tree(
|
||||
document_id=document_id, actor_id=_actor_id(),
|
||||
document_id=document_id,
|
||||
actor_id=_actor_id(),
|
||||
include_full_values=reveal,
|
||||
))
|
||||
|
||||
|
||||
@@ -922,7 +932,7 @@ def _require_value_mapping_edit_permission() -> None:
|
||||
)
|
||||
@require_admin
|
||||
def suggest_order_document_profile_value_split_rules(profile_id: int):
|
||||
"""生成 MATNR 类拆分规则建议;不写 Draft、不 commit。"""
|
||||
"""生成拆分规则建议(任意 datasets 源字段);不写 Draft、不 commit。"""
|
||||
_require_value_mapping_preview_permission()
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _private_ok(suggestion_service.suggest_xfa_split_rules(
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/document_layout/field_split_core.py
|
||||
|
||||
用途:共享的声明式字段拆分核心——承接 XFA(XML Forms Architecture)拆分引擎的纯文本执行能力,
|
||||
为 Vendor Comments / Coordinate Region 等非 XFA 数据源提供统一的 prefix / regex / position
|
||||
匹配、优先级仲裁、多规则冲突诊断、mapped/evidence_only 处理与规则内容指纹。
|
||||
匹配(position 支持连续多行合并)、优先级仲裁、多规则冲突诊断、mapped/evidence_only 处理与规则内容指纹。
|
||||
依赖:Pydantic 2、xfa_contract(复用 XfaContractModel 作为 Base Model 保持一致性)、
|
||||
xfa_safe_regex(危险正则黑名单、超时限制、最大捕获组校验)。
|
||||
逻辑:对外暴露 BaseSplit* 契约与 execute_base_split_rule_set() 执行入口;
|
||||
@@ -55,6 +55,7 @@ SPLIT_UNMATCHED_PRIORITY: Final[int] = 3
|
||||
|
||||
SplitHandling = Literal['mapped', 'evidence_only']
|
||||
SplitMatcherType = Literal['position', 'prefix', 'regex']
|
||||
SplitJoinWith = Literal['newline', 'space', 'comma']
|
||||
SplitSourceScope = Literal['header', 'line']
|
||||
SplitUnmatchedPolicy = Literal['evidence_only', 'needs_review']
|
||||
SplitDuplicatePolicy = Literal['needs_review']
|
||||
@@ -63,6 +64,12 @@ SplitRuleSource = Literal['system_suggestion', 'user', 'imported']
|
||||
RelationCaptureType = Literal['line_reference']
|
||||
RelationPolicyType = Literal['bind_target_line', 'annotation_only']
|
||||
|
||||
_JOIN_WITH_SEPARATORS: Final[dict[str, str]] = {
|
||||
'newline': '\n',
|
||||
'space': ' ',
|
||||
'comma': ', ',
|
||||
}
|
||||
|
||||
_SEGMENT_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,63}$')
|
||||
|
||||
|
||||
@@ -190,15 +197,18 @@ class BaseSplitSegment(XfaContractModel):
|
||||
|
||||
class BaseSplitMatcher(XfaContractModel):
|
||||
"""
|
||||
共享单行匹配器:position / prefix / regex。
|
||||
共享匹配器:position(可连续多行)/ prefix / regex。
|
||||
优先级由引擎固定为 prefix > regex > position;契约仅声明字段形状。
|
||||
|
||||
position 可通过 line_end(含)与 join_with 合并连续多行;缺省时仍为单行。
|
||||
新增 relation_capture:当前仅 line_reference(Q2);XFA 链路当前不启用,
|
||||
但 Base 契约提前引入避免阶段 2 再次改造。
|
||||
"""
|
||||
|
||||
type: SplitMatcherType
|
||||
line_index: int | None = Field(default=None, ge=1, le=1000)
|
||||
line_end: int | None = Field(default=None, ge=1, le=1000)
|
||||
join_with: SplitJoinWith | None = None
|
||||
value: str | None = Field(default=None, max_length=SPLIT_MAX_PREFIX_LENGTH)
|
||||
separators: list[str] = Field(default_factory=lambda: [':', ':'])
|
||||
case_sensitive: bool = False
|
||||
@@ -216,6 +226,19 @@ class BaseSplitMatcher(XfaContractModel):
|
||||
if self.type == 'position':
|
||||
if self.line_index is None:
|
||||
raise ValueError('position matcher requires line_index (1-based)')
|
||||
# 单行保持 line_end=None,避免历史确认指纹漂移;连续多行才写入 line_end。
|
||||
if self.line_end is not None:
|
||||
if int(self.line_end) < int(self.line_index):
|
||||
raise ValueError('position matcher line_end must be >= line_index')
|
||||
if int(self.line_end) == int(self.line_index):
|
||||
object.__setattr__(self, 'line_end', None)
|
||||
object.__setattr__(self, 'join_with', None)
|
||||
elif self.join_with is None:
|
||||
object.__setattr__(self, 'join_with', 'newline')
|
||||
elif self.join_with not in _JOIN_WITH_SEPARATORS:
|
||||
raise ValueError('position matcher join_with must be newline/space/comma')
|
||||
else:
|
||||
object.__setattr__(self, 'join_with', None)
|
||||
elif self.type == 'prefix':
|
||||
label = str(self.value or '').strip()
|
||||
if not label:
|
||||
@@ -356,6 +379,7 @@ def base_split_content_fingerprint(rule_set: BaseSplitRuleSet | dict[str, Any])
|
||||
核心逻辑:只冻结 matcher、normalization 与 relation_capture 定义;
|
||||
segment 的 Schema 映射字段(handling/target_field_*)不属于拆分逻辑本身,
|
||||
后续绑定或解绑目标字段不得取消已确认状态。
|
||||
单行 position 的空 line_end/join_with 不进入指纹,避免新增可选字段导致历史令牌失效。
|
||||
|
||||
Args:
|
||||
rule_set: 模型或 dict。
|
||||
@@ -374,7 +398,16 @@ def base_split_content_fingerprint(rule_set: BaseSplitRuleSet | dict[str, Any])
|
||||
payload.pop('rule_version', None)
|
||||
payload.pop('rule_id', None)
|
||||
for rule in payload.get('rules') or []:
|
||||
segment = rule.get('segment') if isinstance(rule, dict) else None
|
||||
if not isinstance(rule, dict):
|
||||
continue
|
||||
matcher = rule.get('matcher')
|
||||
if isinstance(matcher, dict):
|
||||
# [STEP] 单行 position 不序列化空连续行字段,保持与升级前指纹兼容。
|
||||
if matcher.get('line_end') in (None, matcher.get('line_index')):
|
||||
matcher.pop('line_end', None)
|
||||
if not matcher.get('join_with'):
|
||||
matcher.pop('join_with', None)
|
||||
segment = rule.get('segment')
|
||||
if not isinstance(segment, dict):
|
||||
continue
|
||||
segment.pop('handling', None)
|
||||
@@ -445,7 +478,7 @@ class _CoreSplitEngineResult:
|
||||
|
||||
@dataclass
|
||||
class _LineMatch:
|
||||
"""单行候选命中(共享核心版,含 relation 捕获)。"""
|
||||
"""单行/连续多行候选命中(共享核心版,含 relation 捕获)。"""
|
||||
|
||||
rule: BaseSplitRule
|
||||
matcher_type: str
|
||||
@@ -453,9 +486,43 @@ class _LineMatch:
|
||||
line_text: str
|
||||
normalized_text: str
|
||||
raw_line: str
|
||||
line_end_no: int | None = None
|
||||
claimed_line_nos: tuple[int, ...] = ()
|
||||
captured_relation: CoreCapturedRelation | None = None
|
||||
|
||||
|
||||
def position_line_span(matcher: BaseSplitMatcher) -> tuple[int, int]:
|
||||
"""
|
||||
解析 position matcher 的起止行(1-based,含两端)。
|
||||
|
||||
Args:
|
||||
matcher: position 匹配器。
|
||||
|
||||
Returns:
|
||||
(line_start, line_end)。
|
||||
"""
|
||||
start = int(matcher.line_index or 0)
|
||||
end = int(matcher.line_end or start or 0)
|
||||
if end < start:
|
||||
end = start
|
||||
return start, end
|
||||
|
||||
|
||||
def join_position_lines(lines: list[str], join_with: str | None) -> str:
|
||||
"""
|
||||
按 join_with 合并连续多行文本。
|
||||
|
||||
Args:
|
||||
lines: 已按行号切好的原文行。
|
||||
join_with: newline / space / comma;缺省按换行合并。
|
||||
|
||||
Returns:
|
||||
合并后的文本。
|
||||
"""
|
||||
separator = _JOIN_WITH_SEPARATORS.get(str(join_with or 'newline'), '\n')
|
||||
return separator.join(lines)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# [STEP 3] 纯文本执行函数——从 XFA 拆分引擎原封不动迁移,保持字节级一致
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -599,9 +666,17 @@ def _match_line(
|
||||
line_no: int,
|
||||
line: str,
|
||||
rule: BaseSplitRule,
|
||||
*,
|
||||
inventory: list[str] | None = None,
|
||||
) -> tuple[_LineMatch | None, str | None]:
|
||||
"""
|
||||
判断单条规则是否命中指定行(共享核心版,支持 relation 捕获)。
|
||||
判断单条规则是否命中指定行(共享核心版,支持 relation 捕获与连续多行 position)。
|
||||
|
||||
Args:
|
||||
line_no: 当前行号(1-based)。
|
||||
line: 当前行文本。
|
||||
rule: 待匹配规则。
|
||||
inventory: 完整行清单;position 连续多行时用于合并起止范围内的文本。
|
||||
|
||||
Returns:
|
||||
(match, error_code):命中时 error_code 为 None;未命中时 match 为 None。
|
||||
@@ -612,16 +687,27 @@ def _match_line(
|
||||
return None, 'unknown_matcher'
|
||||
|
||||
if matcher.type == 'position':
|
||||
if int(matcher.line_index or 0) != line_no:
|
||||
start, end = position_line_span(matcher)
|
||||
if int(start) != line_no:
|
||||
return None, None
|
||||
normalized = line.strip() if line else ''
|
||||
lines = list(inventory or [])
|
||||
if not lines:
|
||||
lines = [line]
|
||||
if end > len(lines):
|
||||
return None, 'position_line_range_out_of_bounds'
|
||||
span_lines = lines[start - 1:end]
|
||||
joined_raw = join_position_lines(span_lines, matcher.join_with) if end > start else line
|
||||
normalized = joined_raw.strip() if joined_raw else ''
|
||||
claimed = tuple(range(start, end + 1))
|
||||
return _LineMatch(
|
||||
rule=rule,
|
||||
matcher_type='position',
|
||||
priority=priority,
|
||||
line_text=line,
|
||||
line_text=joined_raw,
|
||||
normalized_text=normalized,
|
||||
raw_line=line,
|
||||
raw_line=joined_raw,
|
||||
line_end_no=end,
|
||||
claimed_line_nos=claimed,
|
||||
), None
|
||||
|
||||
if matcher.type == 'prefix':
|
||||
@@ -635,6 +721,8 @@ def _match_line(
|
||||
line_text=line,
|
||||
normalized_text=extracted,
|
||||
raw_line=line,
|
||||
line_end_no=line_no,
|
||||
claimed_line_nos=(line_no,),
|
||||
), None
|
||||
|
||||
if matcher.type == 'regex':
|
||||
@@ -650,6 +738,8 @@ def _match_line(
|
||||
line_text=line,
|
||||
normalized_text=value,
|
||||
raw_line=line,
|
||||
line_end_no=line_no,
|
||||
claimed_line_nos=(line_no,),
|
||||
captured_relation=relation,
|
||||
), None
|
||||
|
||||
@@ -712,6 +802,7 @@ def execute_base_split_rule_set(
|
||||
核心逻辑:
|
||||
1. normalization.line_breaks 拆行;
|
||||
2. 逐行收集命中规则,按 prefix > regex > position 决出唯一 segment;
|
||||
position 可声明 line_end 合并连续多行,并一次性认领起止范围内行;
|
||||
3. 同优先级多个 mapped 命中 → duplicate_line_match / needs_review;
|
||||
4. 未认领行按 unmatched_line_policy;
|
||||
5. evidence_only 全部保留;
|
||||
@@ -741,15 +832,17 @@ def execute_base_split_rule_set(
|
||||
segments: list[_CoreSegmentResult] = []
|
||||
claimed_lines: set[int] = set()
|
||||
|
||||
# [STEP 1] 逐行匹配并按优先级决出胜出规则。
|
||||
# [STEP 1] 逐行匹配并按优先级决出胜出规则;连续多行 position 一次性认领范围。
|
||||
for line_no, line in enumerate(inventory, start=1):
|
||||
if line_no in claimed_lines:
|
||||
continue
|
||||
matches: list[_LineMatch] = []
|
||||
for rule in rule_set.rules:
|
||||
outcome, error = _match_line(line_no, line, rule)
|
||||
outcome, error = _match_line(line_no, line, rule, inventory=inventory)
|
||||
if error:
|
||||
diagnostics.append(CoreSplitDiagnostic(
|
||||
code=error,
|
||||
message=f'Rule {rule.rule_id} regex failed on line {line_no}',
|
||||
message=f'Rule {rule.rule_id} failed on line {line_no}',
|
||||
line_no=line_no,
|
||||
field_code=rule.segment.target_field_code,
|
||||
rule_ids=[rule.rule_id],
|
||||
@@ -762,7 +855,9 @@ def execute_base_split_rule_set(
|
||||
if winner is None:
|
||||
continue
|
||||
|
||||
claimed_lines.add(line_no)
|
||||
span = winner.claimed_line_nos or (line_no,)
|
||||
claimed_lines.update(span)
|
||||
line_end_no = winner.line_end_no or max(span)
|
||||
seg = winner.rule.segment
|
||||
status = 'parsed'
|
||||
if not str(winner.normalized_text).strip() and seg.handling == 'mapped':
|
||||
@@ -779,7 +874,7 @@ def execute_base_split_rule_set(
|
||||
segment_code=seg.segment_code,
|
||||
display_name=seg.display_name,
|
||||
line_no=line_no,
|
||||
line_end_no=line_no,
|
||||
line_end_no=line_end_no,
|
||||
raw_text=winner.raw_line,
|
||||
normalized_text=winner.normalized_text,
|
||||
handling=seg.handling,
|
||||
|
||||
@@ -147,6 +147,9 @@ class FieldRegion(OrderProfileModel):
|
||||
field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
scope: Literal['header', 'line']
|
||||
region: RelativeRegion
|
||||
# 画布框稳定身份;XFA datasets binding.field_layout_id 优先引用本字段,
|
||||
# 避免仅用「行:field_code」时同名字段/复制框互相抢绑。
|
||||
region_id: str | None = Field(default=None, max_length=128)
|
||||
extractor_key: Literal['direct', 'temp_internal_parts', 'quantity_uom', 'amount_currency', 'price_currency'] = 'direct'
|
||||
allowed_sources: list[Literal['pdf_coordinate', 'ocr_coordinate']] = Field(min_length=1)
|
||||
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
|
||||
|
||||
@@ -602,6 +602,7 @@ def rebuild_tree_dto_from_analysis(
|
||||
pdf_bytes: bytes,
|
||||
*,
|
||||
include_values: bool = False,
|
||||
include_full_values: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
按需从 PDF 重建字段树 DTO(管理员 API 用,不持久化 XML)。
|
||||
@@ -610,6 +611,7 @@ def rebuild_tree_dto_from_analysis(
|
||||
analysis: 已有结构分析记录。
|
||||
pdf_bytes: 原始 PDF 字节。
|
||||
include_values: 是否包含脱敏值。
|
||||
include_full_values: 是否写入完整 sample_value_display(需上游权限门禁)。
|
||||
|
||||
Returns:
|
||||
字段树 DTO。
|
||||
@@ -618,7 +620,15 @@ def rebuild_tree_dto_from_analysis(
|
||||
if outcome.dataset_analysis is None:
|
||||
return project_field_tree(analysis, include_values=include_values)
|
||||
root = outcome.dataset_analysis.nodes[0] if outcome.dataset_analysis.nodes else None
|
||||
tree = serialize_tree_node(root, include_values=include_values) if root else {}
|
||||
tree = (
|
||||
serialize_tree_node(
|
||||
root,
|
||||
include_values=include_values,
|
||||
include_full_values=include_full_values,
|
||||
)
|
||||
if root
|
||||
else {}
|
||||
)
|
||||
return sanitize_xfa_dto({
|
||||
'analysis_id': analysis.id,
|
||||
'document_kind': analysis.document_kind,
|
||||
@@ -626,4 +636,5 @@ def rebuild_tree_dto_from_analysis(
|
||||
'tree': tree,
|
||||
'header_candidates': outcome.dataset_analysis.header_candidates,
|
||||
'stats': outcome.dataset_analysis.stats,
|
||||
'full_values_revealed': bool(include_full_values),
|
||||
})
|
||||
@@ -679,8 +679,8 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
raise ValueError('field_layout_id must reference an order_field_layouts entry')
|
||||
layout_field_code = str(layout.get('field_code') or '')
|
||||
if layout_field_code != binding.field_code:
|
||||
# 一个多行源值(MATNR)可以通过已确认拆分规则产出多个行字段。
|
||||
# 每个目标仍指向同一个真实 MATNR 框,避免伪造重叠视觉框。
|
||||
# 同一 datasets 源字段经已确认拆分规则可产出多个行字段。
|
||||
# 每个目标仍指向同一个真实视觉框,避免伪造重叠框。
|
||||
split_ref = binding.split_rule_ref
|
||||
segment = split_segments.get(str(split_ref.segment_id)) if split_ref else None
|
||||
is_split_target_visual_reuse = bool(
|
||||
|
||||
@@ -559,13 +559,20 @@ def read_collection_rows(
|
||||
return rows
|
||||
|
||||
|
||||
def serialize_tree_node(node: XfaDatasetNode, *, include_values: bool = False) -> dict[str, Any]:
|
||||
def serialize_tree_node(
|
||||
node: XfaDatasetNode,
|
||||
*,
|
||||
include_values: bool = False,
|
||||
include_full_values: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
序列化单个树节点供 API 返回。
|
||||
|
||||
Args:
|
||||
node: 数据集树节点。
|
||||
include_values: 是否包含受控的样本展示值;不得暴露 raw_value。
|
||||
include_values: 是否包含受控的样本展示值;默认不得暴露 raw_value。
|
||||
include_full_values: 为 True 时把内存 raw_value 写入 sample_value_display
|
||||
(仅供已鉴权的映射台 reveal 路径;仍不输出 raw_value 键)。
|
||||
|
||||
Returns:
|
||||
安全 DTO 字典。
|
||||
@@ -580,16 +587,30 @@ def serialize_tree_node(node: XfaDatasetNode, *, include_values: bool = False) -
|
||||
'is_leaf': node.is_leaf,
|
||||
'is_header_candidate': node.is_header_candidate,
|
||||
'is_collection_candidate': node.is_collection_candidate,
|
||||
'children': [serialize_tree_node(child, include_values=include_values) for child in node.children],
|
||||
'children': [
|
||||
serialize_tree_node(
|
||||
child,
|
||||
include_values=include_values,
|
||||
include_full_values=include_full_values,
|
||||
)
|
||||
for child in node.children
|
||||
],
|
||||
}
|
||||
if include_values and node.is_leaf:
|
||||
# 字段树是批量 DTO:即使管理端需要映射辅助,也绝不能把 datasets
|
||||
# 原文放入可缓存/可下载的树响应。完整值只能经单值受控读取与审计接口取得。
|
||||
# 默认批量树只给脱敏/分级展示;完整值须经 reveal + 敏感读权限,且不输出 raw_value 键。
|
||||
payload['sample_value_masked'] = str(node.sample_value_masked or '')
|
||||
payload['sample_value_display'] = str(node.sample_value_display or '')
|
||||
payload['display_policy'] = str(node.display_policy or 'empty')
|
||||
payload['can_reveal'] = bool(node.can_reveal)
|
||||
payload['line_count'] = len(node.lines or [])
|
||||
raw = str(node.raw_value or '')
|
||||
if include_full_values and raw:
|
||||
payload['sample_value_display'] = raw
|
||||
payload['display_policy'] = 'full'
|
||||
payload['can_reveal'] = False
|
||||
payload['full_value_revealed'] = True
|
||||
else:
|
||||
payload['sample_value_display'] = str(node.sample_value_display or '')
|
||||
payload['display_policy'] = str(node.display_policy or 'empty')
|
||||
payload['can_reveal'] = bool(node.can_reveal)
|
||||
payload['full_value_revealed'] = False
|
||||
return payload
|
||||
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ backend/app/services/shipping_notice/document_layout/xfa_profile_extraction.py
|
||||
order_profile_extractors。
|
||||
逻辑:由 order_extraction_workflow XFA 分支在精确命中后调用;正式提取仅读 bindings[],
|
||||
无 bindings 或仍含 header_mappings/line_mapping.fields 时 fail-closed;
|
||||
header 带 split_rule_ref 的目标跳过 STEP1 直读,仅由拆分规则产出(与 line 对齐);
|
||||
类型/normalizer/validator 取自 schema_fields;失败由上层回退坐标/OCR/通用。
|
||||
"""
|
||||
|
||||
@@ -574,10 +575,12 @@ def extract_xfa_profile(
|
||||
header_bindings = _bindings_for_scope(profile, 'header')
|
||||
line_bindings = _bindings_for_scope(profile, 'line')
|
||||
|
||||
# [STEP 1] Header bindings
|
||||
# [STEP 1] Header bindings:带 split_rule_ref 的目标由后续拆分产出,禁止再读源全文。
|
||||
header_fields: list[XfaExtractedField] = []
|
||||
header_issues: list[str] = []
|
||||
for binding in header_bindings:
|
||||
if binding.split_rule_ref is not None:
|
||||
continue
|
||||
data_path = str(binding.value_binding.data_path or '')
|
||||
value_type, normalizer_key, validator_key = _schema_metadata_for_field(
|
||||
schema_fields=schema_fields,
|
||||
|
||||
@@ -8,6 +8,7 @@ services/shipping_notice/document_layout/xfa_split_rule_contract.py
|
||||
BaseSplitSegment / BaseSplitRule / BaseSplitRuleSet)。
|
||||
逻辑:仅声明式校验,不执行规则、不读 PDF、不接网络;非法契约以 ValidationError
|
||||
或 ValueError 拒绝;匹配优先级由引擎固定 prefix > regex > position > unmatched;
|
||||
position 支持 line_end + join_with 合并连续多行;
|
||||
XfaSplit* 系列继承共享核心 BaseSplit*,但保留 XFA 专属字段(source_path_id /
|
||||
source_data_path 等)和 XFA 前缀的环境变量读取,保持对外行为零漂移。
|
||||
"""
|
||||
@@ -195,14 +196,17 @@ class XfaSplitPostProcessor(XfaContractModel):
|
||||
|
||||
class XfaSplitMatcher(BaseSplitMatcher):
|
||||
"""
|
||||
单行匹配器:position / prefix / regex。
|
||||
匹配器:position(可连续多行)/ prefix / regex。
|
||||
|
||||
优先级由引擎固定为 prefix > regex > position;契约仅声明字段形状。
|
||||
继承共享核心 BaseSplitMatcher;保留 XFA 自己的校验器与 XFA_ 前缀长度常量。
|
||||
position 可通过 line_end(含)与 join_with 合并连续多行。
|
||||
"""
|
||||
|
||||
type: XfaSplitMatcherType
|
||||
line_index: int | None = Field(default=None, ge=1, le=1000)
|
||||
line_end: int | None = Field(default=None, ge=1, le=1000)
|
||||
join_with: Literal['newline', 'space', 'comma'] | None = None
|
||||
value: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_PREFIX_LENGTH)
|
||||
separators: list[str] = Field(default_factory=lambda: [':', ':'])
|
||||
case_sensitive: bool = False
|
||||
@@ -220,6 +224,19 @@ class XfaSplitMatcher(BaseSplitMatcher):
|
||||
if self.type == 'position':
|
||||
if self.line_index is None:
|
||||
raise ValueError('position matcher requires line_index (1-based)')
|
||||
# 单行保持 line_end=None,避免历史确认指纹漂移;连续多行才写入 line_end。
|
||||
if self.line_end is not None:
|
||||
if int(self.line_end) < int(self.line_index):
|
||||
raise ValueError('position matcher line_end must be >= line_index')
|
||||
if int(self.line_end) == int(self.line_index):
|
||||
object.__setattr__(self, 'line_end', None)
|
||||
object.__setattr__(self, 'join_with', None)
|
||||
elif self.join_with is None:
|
||||
object.__setattr__(self, 'join_with', 'newline')
|
||||
elif self.join_with not in {'newline', 'space', 'comma'}:
|
||||
raise ValueError('position matcher join_with must be newline/space/comma')
|
||||
else:
|
||||
object.__setattr__(self, 'join_with', None)
|
||||
elif self.type == 'prefix':
|
||||
label = str(self.value or '').strip()
|
||||
if not label:
|
||||
@@ -374,6 +391,7 @@ def split_rule_content_fingerprint(rule_set: XfaSplitRuleSet | dict[str, Any]) -
|
||||
|
||||
核心逻辑:只冻结 matcher 与 normalization;segment 的 Schema 映射字段不属于拆分逻辑,
|
||||
后续绑定或解绑目标字段不得取消已确认状态。
|
||||
单行 position 的空 line_end/join_with 不进入指纹,避免新增可选字段导致历史令牌失效。
|
||||
|
||||
【重要】:XFA 版指纹实现独立保留,不直接调用共享核心 base_split_content_fingerprint。
|
||||
原因:未来若共享核心为 Vendor Comments 增加 relation_capture 字段纳入指纹计算,
|
||||
@@ -399,7 +417,15 @@ def split_rule_content_fingerprint(rule_set: XfaSplitRuleSet | dict[str, Any]) -
|
||||
# 将同一规则对象交给 normalize/save,原地 pop 会使已确认草稿不可再次编辑。
|
||||
payload = json.loads(json.dumps(payload))
|
||||
for rule in payload.get('rules') or []:
|
||||
segment = rule.get('segment') if isinstance(rule, dict) else None
|
||||
if not isinstance(rule, dict):
|
||||
continue
|
||||
matcher = rule.get('matcher')
|
||||
if isinstance(matcher, dict):
|
||||
if matcher.get('line_end') in (None, matcher.get('line_index')):
|
||||
matcher.pop('line_end', None)
|
||||
if not matcher.get('join_with'):
|
||||
matcher.pop('join_with', None)
|
||||
segment = rule.get('segment')
|
||||
if not isinstance(segment, dict):
|
||||
continue
|
||||
segment.pop('handling', None)
|
||||
|
||||
@@ -385,6 +385,7 @@ def _validate_acroform(
|
||||
核心逻辑:
|
||||
- 允许展示格式不同,标准化后必须相同;
|
||||
- 明细按 AcroForm 同名多实例下标与提取行一一对应,禁止“全行扫到首个 field_code”;
|
||||
- 带 split_rule_ref 的 binding(表头/明细)跳过源 Widget 全文对账,正式值由拆分产出;
|
||||
- 无 Fields / 无重叠字段 → unavailable;仅部分字段可对 → partial;冲突 → mismatched。
|
||||
|
||||
Returns:
|
||||
@@ -405,10 +406,12 @@ def _validate_acroform(
|
||||
missing_counterpart = 0
|
||||
mismatches: list[dict[str, Any]] = []
|
||||
|
||||
# [STEP 1] Header:每个 binding 对应短名的首个 AcroForm 实例。
|
||||
# [STEP 1] Header:每个 binding 对应短名的首个 AcroForm 实例;拆分目标跳过源全文对账。
|
||||
for binding in profile.bindings:
|
||||
if binding.scope != 'header':
|
||||
continue
|
||||
if binding.split_rule_ref is not None:
|
||||
continue
|
||||
data_path = str(binding.value_binding.data_path or '')
|
||||
local = data_path.rsplit('/', 1)[-1].upper()
|
||||
acro_values = by_name.get(local) or []
|
||||
|
||||
@@ -7,7 +7,10 @@ services/shipping_notice/document_profile_quality_service.py
|
||||
共同坐标回放完成视觉证据,末端值源 adapter 再补充正式字段和结构校验;
|
||||
策略需复核时仍展示最佳努力明细供人工核对,正式自动建单仍要求策略 selected;
|
||||
盲测主明细仅 business_lines,随后按 LN 合并 line_field_supplement 料号;
|
||||
盲测执行附加 visual/split/evidence 指标,XFA 任一指标 < 1.0 即失败;样本通过并批准后才放行自动建单。
|
||||
盲测执行附加 visual/split/evidence 指标供展示;XFA 硬失败只认 datasets 抽取与真值比对;
|
||||
OCR↔datasets / 视觉覆盖不足写入 soft_diagnostics,不计入硬失败;
|
||||
XFA 确认真值:bindings 表头必须齐全,允许候选额外含仅有视觉框的表头(如 bill_to);
|
||||
样本通过并批准后才放行自动建单。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -272,9 +275,13 @@ def _expected_rows(raw: Any) -> list[dict[str, Any]]:
|
||||
|
||||
|
||||
def _expected_order_fields(raw: Any, *, parser: Any) -> dict[str, Any]:
|
||||
"""校验订单字段盲测真值;按共同字段契约读取,不判断值源实现。"""
|
||||
"""校验订单字段盲测真值;按共同字段契约读取,不判断值源实现。
|
||||
|
||||
核心逻辑:XFA bindings 表头必须齐全;候选还可含视觉框/拆分产出的额外表头
|
||||
(如 bill_to_* 仅有 order_field_layouts、尚无 path binding),不得因多出来的键拒绝确认。
|
||||
"""
|
||||
# [STEP 1] bindings-only XFA 已禁止 legacy header_mappings;盲测 Header
|
||||
# 真值必须由共同 bindings[] 推导,不能因迁移字段为空而静默保存为 {}。
|
||||
# 真值必须覆盖共同 bindings[],不能因迁移字段为空而静默保存为 {}。
|
||||
binding_headers = [
|
||||
item for item in (getattr(parser, 'bindings', None) or [])
|
||||
if str(getattr(item, 'scope', '') or '') == 'header'
|
||||
@@ -289,11 +296,25 @@ def _expected_order_fields(raw: Any, *, parser: Any) -> dict[str, Any]:
|
||||
}
|
||||
if not expected_keys:
|
||||
return {}
|
||||
if not isinstance(raw, dict) or set(raw) != expected_keys or any(value in (None, '') for value in raw.values()):
|
||||
if not isinstance(raw, dict):
|
||||
raise ValidationError(
|
||||
'expected_order_fields must contain every bound header field',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID',
|
||||
)
|
||||
missing = sorted(key for key in expected_keys if key not in raw)
|
||||
empty_bound = sorted(
|
||||
key for key in expected_keys
|
||||
if key in raw and raw.get(key) in (None, '')
|
||||
)
|
||||
if missing or empty_bound or any(value in (None, '') for value in raw.values()):
|
||||
raise ValidationError(
|
||||
'expected_order_fields must contain every bound header field',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID',
|
||||
details={
|
||||
'missing_keys': missing[:20],
|
||||
'empty_bound_keys': empty_bound[:20],
|
||||
},
|
||||
)
|
||||
return dict(raw)
|
||||
header_mappings = getattr(parser, 'header_mappings', [])
|
||||
if header_mappings:
|
||||
@@ -675,7 +696,7 @@ def _compare_blind_candidate(
|
||||
"""比较任意 value adapter 的盲测候选与人工冻结真值。
|
||||
|
||||
核心逻辑:adapter 已统一返回 order_fields 与 rows;本函数只做共同的字段确认、
|
||||
标准化值和行值对照。XFA 的视觉/镜像/证据完整性在调用前另行作为 adapter 门禁。
|
||||
标准化值和行值对照。XFA 视觉/镜像/证据指标仅作展示与 soft 诊断,不在此硬拦。
|
||||
|
||||
Args:
|
||||
candidate: coordinate 或 XFA adapter 产生的脱敏候选。
|
||||
@@ -1052,7 +1073,13 @@ def remove_sample(*, suite_id: int, sample_id: int, actor_id: int) -> dict[str,
|
||||
|
||||
|
||||
def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
"""用与候选预览相同的当前 Profile 路径执行盲测;任何差异都不得批准。"""
|
||||
"""
|
||||
用与候选预览相同的当前 Profile 路径执行盲测;任何差异都不得批准。
|
||||
|
||||
核心逻辑:公共流程拉候选 → 真值比对 → 汇总 Run。XFA adapter 的
|
||||
visual/mirror/evidence 与 OCR↔datasets 对照写入 soft_diagnostics,不计入硬失败;
|
||||
硬失败仅来自 datasets 抽取失败或与人工真值不一致。
|
||||
"""
|
||||
suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id))
|
||||
if suite is None:
|
||||
raise NotFoundError('Order document profile test suite not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_FOUND')
|
||||
@@ -1076,12 +1103,35 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
'key_field_accuracy_rate': 1.0,
|
||||
}
|
||||
metrics_samples = 0
|
||||
soft_diagnostics: list[dict[str, Any]] = []
|
||||
for sample in suite.samples:
|
||||
try:
|
||||
candidate = _adapter_blind_candidate(profile=profile, sample=sample)
|
||||
except (NotFoundError, ValidationError):
|
||||
failures.append(f'sample:{sample.id}:{_adapter_evidence_missing_code(adapter)}_evidence_missing')
|
||||
continue
|
||||
# XFA OCR↔datasets 不一致:保留字段级诊断,不计入硬失败。
|
||||
ocr_check = candidate.get('ocr_datasets_cross_check') if isinstance(candidate, dict) else None
|
||||
if isinstance(ocr_check, dict) and ocr_check.get('status') == 'mismatched':
|
||||
mismatches = [
|
||||
item for item in (ocr_check.get('mismatches') or [])
|
||||
if isinstance(item, dict) and str(item.get('field_code') or '').strip()
|
||||
]
|
||||
soft_diagnostics.append({
|
||||
'sample_id': int(sample.id),
|
||||
'code': 'ocr_datasets_mismatch',
|
||||
'mismatch_count': int(ocr_check.get('mismatch_count') or len(mismatches)),
|
||||
'fields': [
|
||||
{
|
||||
'scope': str(item.get('scope') or ''),
|
||||
'field_code': str(item.get('field_code') or ''),
|
||||
'row_index': item.get('row_index'),
|
||||
'ocr_value': str(item.get('ocr_value') or ''),
|
||||
'datasets_value': str(item.get('datasets_value') or ''),
|
||||
}
|
||||
for item in mismatches[:20]
|
||||
],
|
||||
})
|
||||
adapter_failures, adapter_metrics = _adapter_blind_gate_failures(
|
||||
adapter=adapter, candidate=candidate, sample_id=sample.id,
|
||||
)
|
||||
@@ -1090,6 +1140,24 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
for key, value in adapter_metrics.items():
|
||||
metrics_agg[key] = min(metrics_agg[key], value)
|
||||
metrics_samples += 1
|
||||
# [STEP] XFA 视觉/镜像/留痕不足:仅 soft 诊断,不否决样本。
|
||||
soft_metric_codes = [
|
||||
(key, code)
|
||||
for key, code in (
|
||||
('visual_coverage_rate', 'visual_coverage_soft'),
|
||||
('mirror_consistency_rate', 'mirror_consistency_soft'),
|
||||
('evidence_retention_rate', 'evidence_retention_soft'),
|
||||
)
|
||||
if float(adapter_metrics.get(key) or 1.0) < 1.0
|
||||
]
|
||||
for _key, code in soft_metric_codes:
|
||||
soft_diagnostics.append({
|
||||
'sample_id': int(sample.id),
|
||||
'code': code,
|
||||
'mismatch_count': 0,
|
||||
'fields': [],
|
||||
'rate': float(adapter_metrics.get(_key) or 0.0),
|
||||
})
|
||||
line_schema_by_code = _adapter_line_schema_by_code(parser, schema_fields)
|
||||
comparison_failures, key_total, key_matched = _compare_blind_candidate(
|
||||
candidate=candidate,
|
||||
@@ -1114,6 +1182,7 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
'value_adapter': adapter.key,
|
||||
'metrics': metrics_agg,
|
||||
'adapter_metrics_available': metrics_samples > 0,
|
||||
'soft_diagnostics': soft_diagnostics,
|
||||
},
|
||||
executed_by_id=actor_id,
|
||||
)
|
||||
@@ -1489,6 +1558,7 @@ def serialize_suite(suite: ShippingDocumentProfileTestSuite) -> dict[str, Any]:
|
||||
latest = suite.runs[-1] if suite.runs else None
|
||||
evidence = dict(getattr(latest, 'evidence_json', {}) or {}) if latest is not None else {}
|
||||
metrics = evidence.get('metrics') if isinstance(evidence.get('metrics'), dict) else None
|
||||
soft_diagnostics = evidence.get('soft_diagnostics') if isinstance(evidence.get('soft_diagnostics'), list) else []
|
||||
failure_codes = [str(code or '') for code in list(latest.failure_codes_json or [])] if latest is not None else []
|
||||
return {
|
||||
'id': suite.id, 'profile_id': suite.profile_id, 'profile_checksum': suite.profile_checksum,
|
||||
@@ -1500,5 +1570,7 @@ def serialize_suite(suite: ShippingDocumentProfileTestSuite) -> dict[str, Any]:
|
||||
'passed_sample_count': latest.passed_sample_count,
|
||||
'failure_codes': failure_codes,
|
||||
'metrics': metrics,
|
||||
# 字段级 OCR↔datasets 对照诊断(含两侧截断值),供管理端标明差异。
|
||||
'soft_diagnostics': soft_diagnostics,
|
||||
},
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_service.py
|
||||
|
||||
Profile Run
|
||||
ShippingOrderDocumentProfile Schema document_layout.order_profile
|
||||
field_code field_id Schema
|
||||
CASCADE 500?
|
||||
用途:订单文档 Profile 的保存、发布、预览授权与共同视觉契约还原。
|
||||
依赖:OrderCoordinateProfile、Schema 模型、preview_grant_store、value adapter 注册表。
|
||||
逻辑:管理 API / 盲测质量服务调用本模块;`_definition_contract` 供候选预览与样本回放
|
||||
构造坐标契约,并回填 XFA 草稿中空的 order_field field_id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -727,9 +727,10 @@ def _normalize_visual_definition_for_preview(
|
||||
"""将任意值源草稿投影为共同视觉定义,供画布样本值预览使用。
|
||||
|
||||
核心逻辑:PDFium/OCR 视觉取值只依赖文档匹配、表区和视觉字段布局,不能因为 XFA
|
||||
datasets 终值映射尚未完成而拒绝预览。该函数刻意丢弃 template_mode、bindings、path_id
|
||||
与 datasets 契约;保存、发布和正式提取仍必须走 ``_normalize_definition`` 的完整 adapter
|
||||
校验,绝不在此放宽正式值源规则。
|
||||
datasets 终值映射尚未完成、或草稿存在重复 Schema 绑定而拒绝预览。该函数刻意丢弃
|
||||
template_mode、bindings、path_id 与 datasets 契约,并对重复 field_code 仅保留首个
|
||||
布局;保存、发布和正式提取仍必须走 ``_normalize_definition`` 的完整校验,绝不在
|
||||
此放宽正式值源规则。
|
||||
|
||||
Args:
|
||||
raw: 编辑器当前草稿,可能包含 coordinate 或 XFA datasets 的末端值配置。
|
||||
@@ -743,7 +744,20 @@ def _normalize_visual_definition_for_preview(
|
||||
'Order profile definition must be an object',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
order_field_layouts = raw.get('order_field_layouts') or []
|
||||
# [STEP] 预览只读:草稿可能已存在重复订单字段绑定;保留每个 field_code 的首个布局,
|
||||
# 让进入编辑页即可读取样本值。保存路径仍走完整 _normalize_definition 硬阻断。
|
||||
seen_order_field_codes: set[str] = set()
|
||||
order_field_layouts: list[Any] = []
|
||||
for item in raw.get('order_field_layouts') or []:
|
||||
if not isinstance(item, dict):
|
||||
order_field_layouts.append(item)
|
||||
continue
|
||||
code = str(item.get('field_code') or '').strip()
|
||||
if code and code in seen_order_field_codes:
|
||||
continue
|
||||
if code:
|
||||
seen_order_field_codes.add(code)
|
||||
order_field_layouts.append(item)
|
||||
bound_layout_ids = {
|
||||
str(item.get('layout_id') or '').strip()
|
||||
for item in order_field_layouts
|
||||
@@ -798,19 +812,135 @@ def _normalize_visual_definition_for_preview(
|
||||
return _normalize_definition(visual, schema_version=schema_version, preferred_template_mode='coordinate')
|
||||
|
||||
|
||||
def _hydrate_coordinate_layout_field_ids(
|
||||
*,
|
||||
definition: dict[str, Any],
|
||||
schema_version: ShippingOrderSchemaVersion | None,
|
||||
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""
|
||||
为共同视觉坐标契约回填空 field_id,避免盲测/候选预览直接校验已保存草稿时 500。
|
||||
|
||||
核心逻辑:XFA 画布保存时常把 order_field_layouts.field_id 写成空串,正式 field_id
|
||||
在 Schema 或 bindings 上。按 (scope, field_code) 取 Schema,再按 field_layout_id
|
||||
回退 binding.field_id;表内 field_regions 同样处理。不改写 profile.definition_json。
|
||||
|
||||
Args:
|
||||
definition: Profile.definition_json 字典。
|
||||
schema_version: Profile 绑定的 Schema 版本;缺失时仅尝试 bindings。
|
||||
|
||||
Returns:
|
||||
(order_field_layouts, table_regions) 的浅拷贝列表,已尽量补齐 field_id。
|
||||
"""
|
||||
profile_fields = _schema_profile_fields(schema_version) if schema_version is not None else {}
|
||||
bindings_by_layout = {
|
||||
str(item.get('field_layout_id') or '').strip(): item
|
||||
for item in (definition.get('bindings') or [])
|
||||
if isinstance(item, dict) and str(item.get('field_layout_id') or '').strip()
|
||||
}
|
||||
|
||||
def resolve_field_id(*, field_id: Any, field_code: Any, scope: Any, layout_id: Any) -> str:
|
||||
current = str(field_id or '').strip()
|
||||
if current:
|
||||
return current
|
||||
code = str(field_code or '').strip()
|
||||
field_scope = str(scope or 'header').strip() or 'header'
|
||||
schema_field = profile_fields.get((field_scope, code)) if code else None
|
||||
if isinstance(schema_field, dict) and str(schema_field.get('field_id') or '').strip():
|
||||
return str(schema_field['field_id']).strip()
|
||||
binding = bindings_by_layout.get(str(layout_id or '').strip())
|
||||
if isinstance(binding, dict) and str(binding.get('field_id') or '').strip():
|
||||
return str(binding['field_id']).strip()
|
||||
return current
|
||||
|
||||
order_field_layouts: list[dict[str, Any]] = []
|
||||
for item in definition.get('order_field_layouts') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
layout = dict(item)
|
||||
layout['field_id'] = resolve_field_id(
|
||||
field_id=layout.get('field_id'),
|
||||
field_code=layout.get('field_code'),
|
||||
scope=layout.get('scope') or 'header',
|
||||
layout_id=layout.get('layout_id'),
|
||||
)
|
||||
order_field_layouts.append(layout)
|
||||
|
||||
table_regions: list[dict[str, Any]] = []
|
||||
for raw_table in definition.get('table_regions') or []:
|
||||
if not isinstance(raw_table, dict):
|
||||
continue
|
||||
table = dict(raw_table)
|
||||
|
||||
def hydrate_layout_fields(raw_layout: Any) -> dict[str, Any] | None:
|
||||
if not isinstance(raw_layout, dict):
|
||||
return None
|
||||
layout = dict(raw_layout)
|
||||
parent_id = str(layout.get('layout_id') or '').strip()
|
||||
hydrated_fields: list[dict[str, Any]] = []
|
||||
for raw_field in layout.get('field_regions') or []:
|
||||
if not isinstance(raw_field, dict):
|
||||
continue
|
||||
field = dict(raw_field)
|
||||
region_id = str(field.get('region_id') or '').strip()
|
||||
layout_key = region_id or (
|
||||
f'{parent_id}:{str(field.get("field_code") or "").strip()}'.strip(':')
|
||||
)
|
||||
field['field_id'] = resolve_field_id(
|
||||
field_id=field.get('field_id'),
|
||||
field_code=field.get('field_code'),
|
||||
scope=field.get('scope') or 'line',
|
||||
layout_id=layout_key,
|
||||
)
|
||||
hydrated_fields.append(field)
|
||||
layout['field_regions'] = hydrated_fields
|
||||
return layout
|
||||
|
||||
table['header_layouts'] = [
|
||||
hydrated
|
||||
for item in (table.get('header_layouts') or [])
|
||||
if (hydrated := hydrate_layout_fields(item)) is not None
|
||||
]
|
||||
table['line_layouts'] = [
|
||||
hydrated
|
||||
for item in (table.get('line_layouts') or [])
|
||||
if (hydrated := hydrate_layout_fields(item)) is not None
|
||||
]
|
||||
table_regions.append(table)
|
||||
|
||||
return order_field_layouts, table_regions
|
||||
|
||||
|
||||
def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderCoordinateProfile:
|
||||
""" v1 Profile v2?"""
|
||||
"""
|
||||
把已保存 Profile 还原为共同视觉坐标契约,供盲测/样本候选抽取使用。
|
||||
|
||||
核心逻辑:先回填空 field_id(XFA 草稿常见),再构造 OrderCoordinateProfile;
|
||||
契约非法时转为业务 ValidationError,禁止冒泡成 SYSTEM.INTERNAL_ERROR 500。
|
||||
"""
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
return OrderCoordinateProfile(
|
||||
profile_code=profile.profile_code,
|
||||
version=profile.version,
|
||||
document_match=definition.get('document_match'),
|
||||
table_regions=definition.get('table_regions'),
|
||||
order_field_layouts=definition.get('order_field_layouts') or [],
|
||||
draft_unbound_order_field_layouts=definition.get('draft_unbound_order_field_layouts') or [],
|
||||
coordinate_model=definition.get('coordinate_model') or {},
|
||||
reference_page_frames=definition.get('reference_page_frames') or {},
|
||||
order_field_layouts, table_regions = _hydrate_coordinate_layout_field_ids(
|
||||
definition=definition,
|
||||
schema_version=profile.schema_version,
|
||||
)
|
||||
try:
|
||||
return OrderCoordinateProfile(
|
||||
profile_code=profile.profile_code,
|
||||
version=profile.version,
|
||||
document_match=definition.get('document_match'),
|
||||
table_regions=table_regions,
|
||||
order_field_layouts=order_field_layouts,
|
||||
draft_unbound_order_field_layouts=definition.get('draft_unbound_order_field_layouts') or [],
|
||||
coordinate_model=definition.get('coordinate_model') or {},
|
||||
reference_page_frames=definition.get('reference_page_frames') or {},
|
||||
)
|
||||
except (TypeError, ValueError) as exc:
|
||||
validation_errors = getattr(exc, 'errors', lambda: [])()
|
||||
location = validation_errors[0].get('loc', ()) if validation_errors else ()
|
||||
raise ValidationError(
|
||||
'Order profile definition is invalid',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
details={'reason': 'coordinate_contract_invalid', 'location': list(location)},
|
||||
) from exc
|
||||
|
||||
|
||||
def payload(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
|
||||
@@ -176,27 +176,27 @@ def _require_xfa_draft(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
return dict(profile.definition_json or {})
|
||||
|
||||
|
||||
def _resolve_matnr_path_id(
|
||||
def _resolve_split_source_path_id(
|
||||
*,
|
||||
definition: dict[str, Any],
|
||||
path_context: dict[str, Any],
|
||||
path_id: str | None,
|
||||
) -> tuple[str, str]:
|
||||
"""
|
||||
解析 MATNR 类拆分源 path_id 与 data_path。
|
||||
解析拆分规则建议的源 path_id 与 data_path(通用,不绑死字段名)。
|
||||
|
||||
核心逻辑:显式 path_id 优先;否则在权威行集合下查找 local_name=MATNR 的路径。
|
||||
核心逻辑:显式 path_id 优先;未传时仅作兼容回退,在权威行集合下查找常见料号叶子名。
|
||||
|
||||
Args:
|
||||
definition: 当前 Profile definition。
|
||||
path_context: 当前末端值源 adapter 的冻结路径上下文。
|
||||
path_id: 可选显式 path_id。
|
||||
path_id: 可选显式 path_id(UI 选中源字段时应必传)。
|
||||
|
||||
Returns:
|
||||
(path_id, data_path) 元组。
|
||||
|
||||
Raises:
|
||||
ValidationError: 无法定位 MATNR 路径。
|
||||
ValidationError: 无法定位源路径。
|
||||
"""
|
||||
path_map: dict[str, str] = dict(path_context.get('path_map') or {})
|
||||
if path_id:
|
||||
@@ -209,24 +209,31 @@ def _resolve_matnr_path_id(
|
||||
)
|
||||
return str(path_id), resolved
|
||||
|
||||
# 兼容旧调用:未传 path_id 时按常见料号叶子名回退,不是运行时拆分引擎的字段硬编码。
|
||||
source = definition.get('source_contract') if isinstance(definition.get('source_contract'), dict) else {}
|
||||
auth_path = str(source.get('authoritative_line_collection_path') or '').rstrip('/')
|
||||
fallback_leaf_names = ('MATNR', 'PARTS', 'PART_NO', 'MATERIAL')
|
||||
candidates = [
|
||||
(pid, data_path)
|
||||
for pid, data_path in path_map.items()
|
||||
if data_path.endswith('/MATNR') or data_path == f'{auth_path}/MATNR'
|
||||
for leaf in fallback_leaf_names
|
||||
if data_path.endswith(f'/{leaf}') or data_path == f'{auth_path}/{leaf}'
|
||||
]
|
||||
if not candidates:
|
||||
raise ValidationError(
|
||||
'MATNR source path is not available for split rule suggestion',
|
||||
'Split source path_id is required when no common material leaf can be inferred',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
|
||||
details={'reason': 'matnr_path_missing'},
|
||||
details={'reason': 'split_source_path_missing'},
|
||||
)
|
||||
if len(candidates) > 1:
|
||||
candidates.sort(key=lambda item: item[1])
|
||||
return candidates[0]
|
||||
|
||||
|
||||
# 兼容旧名:历史测试/调用仍可能引用 MATNR 命名;实现已改为通用源路径解析。
|
||||
_resolve_matnr_path_id = _resolve_split_source_path_id
|
||||
|
||||
|
||||
def _schema_field_ids(profile_id: int) -> dict[str, dict[str, Any]]:
|
||||
"""
|
||||
读取 Profile 绑定 Schema 的 field_code → 字段定义。
|
||||
@@ -241,21 +248,36 @@ def _schema_field_ids(profile_id: int) -> dict[str, dict[str, Any]]:
|
||||
return get_value_adapter(dict(profile.definition_json or {})).mapping_schema_fields(profile_id=profile_id)
|
||||
|
||||
|
||||
def build_matnr_split_rule_suggestion(
|
||||
def _source_field_code_from_data_path(data_path: str) -> str:
|
||||
"""
|
||||
从 data_path 取叶子名作为 source_field_code(通用,不写死 MATNR)。
|
||||
|
||||
Args:
|
||||
data_path: datasets 绝对路径。
|
||||
|
||||
Returns:
|
||||
路径最后一段;空路径时返回空串。
|
||||
"""
|
||||
parts = [part for part in str(data_path or '').split('/') if part]
|
||||
return parts[-1] if parts else ''
|
||||
|
||||
|
||||
def build_multiline_part_split_rule_suggestion(
|
||||
*,
|
||||
path_id: str,
|
||||
data_path: str,
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
生成 MATNR 类五行样本的拆分规则建议(matcher 模型)。
|
||||
生成「多行料号描述」类拆分规则建议(matcher 模型,仅建议草稿)。
|
||||
|
||||
核心逻辑:position:1→customer_part_number;prefix MPN→part_number;
|
||||
核心逻辑:这是可选的系统建议模板,不是运行时拆分引擎;运行时只认用户确认后的
|
||||
split_rules。position:1→customer_part_number;prefix MPN→part_number;
|
||||
其余 unmatched→evidence_only;status=draft、source=system_suggestion。
|
||||
|
||||
Args:
|
||||
path_id: 源 datasets path_id。
|
||||
data_path: 源 data_path(写入 source_data_path)。
|
||||
path_id: 源 datasets path_id(任意叶子,不限 MATNR)。
|
||||
data_path: 源 data_path(写入 source_data_path / source_field_code)。
|
||||
schema_fields: Schema field_code 索引。
|
||||
|
||||
Returns:
|
||||
@@ -266,12 +288,13 @@ def build_matnr_split_rule_suggestion(
|
||||
rule_set_id = f'rs-{secrets.token_hex(8)}'
|
||||
segment_cpn = new_segment_id()
|
||||
segment_mpn = new_segment_id()
|
||||
source_field_code = _source_field_code_from_data_path(data_path) or 'SOURCE'
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_set_id=rule_set_id,
|
||||
rule_version=1,
|
||||
source_path_id=str(path_id),
|
||||
source_scope='line',
|
||||
source_field_code='MATNR',
|
||||
source_field_code=source_field_code,
|
||||
source_data_path=str(data_path),
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
@@ -319,6 +342,10 @@ def build_matnr_split_rule_suggestion(
|
||||
return dumped
|
||||
|
||||
|
||||
# 兼容旧名:历史 MATNR 样本建议入口;实现已改为任意源字段。
|
||||
build_matnr_split_rule_suggestion = build_multiline_part_split_rule_suggestion
|
||||
|
||||
|
||||
def suggest_xfa_split_rules(
|
||||
profile_id: int,
|
||||
*,
|
||||
@@ -328,12 +355,14 @@ def suggest_xfa_split_rules(
|
||||
write_audit: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为 MATNR 类字段生成拆分规则建议(不写 Draft、不 commit)。
|
||||
为指定 datasets 源字段生成拆分规则建议(不写 Draft、不 commit)。
|
||||
|
||||
核心逻辑:建议模板仅辅助配置;运行时拆分只执行用户已确认的通用 split_rules。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
document_id: 绑定样本 document ID。
|
||||
path_id: 可选显式源 path_id;省略时自动定位 MATNR。
|
||||
path_id: 源 path_id;省略时仅兼容回退常见料号叶子。
|
||||
actor_id: 管理员 ID。
|
||||
write_audit: 为 True 时写只读建议审计(默认 False,零写库)。
|
||||
|
||||
@@ -354,13 +383,13 @@ def suggest_xfa_split_rules(
|
||||
profile_service._bound_sample_document(int(profile_id), int(document_id))
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
path_context = get_value_adapter(definition).prepare_context(document)
|
||||
resolved_path_id, data_path = _resolve_matnr_path_id(
|
||||
resolved_path_id, data_path = _resolve_split_source_path_id(
|
||||
definition=definition,
|
||||
path_context=path_context,
|
||||
path_id=str(path_id).strip() if path_id else None,
|
||||
)
|
||||
schema_fields = _schema_field_ids(profile.id)
|
||||
rule_set = build_matnr_split_rule_suggestion(
|
||||
rule_set = build_multiline_part_split_rule_suggestion(
|
||||
path_id=resolved_path_id,
|
||||
data_path=data_path,
|
||||
schema_fields=schema_fields,
|
||||
|
||||
@@ -5,6 +5,7 @@ backend/app/services/shipping_notice/order_extraction_workflow.py
|
||||
依赖:MinerU 紧凑快照、订单 Profile(coordinate / xfa_dataset)、Schema 校验、
|
||||
order_extraction_route_contract、xfa_profile_*、line_field_supplement_merge、统一错误类型。
|
||||
逻辑:Worker 先调用本模块裁决;所有 PDF 先走共同视觉路径,datasets 仅在末端取正式值;
|
||||
XFA(xfa_dataset)正式值只认 datasets;OCR/坐标 confirmed 仅供点击定位,不得否决或覆盖;
|
||||
datasets 缺失或冲突时共同 OCR 仅作复核/兜底证据并强制 needs_review;
|
||||
唯一 PO 提升到 Header 后从明细剥离,避免 persist 因 scope 不匹配失败;
|
||||
路由产出 Candidate 后由 Candidate Qualification 统一评估自动建单资格;
|
||||
@@ -1691,8 +1692,63 @@ def _validate_locked_layout_fields(document: dict[str, Any], *, orders: list[dic
|
||||
)
|
||||
|
||||
|
||||
def _orders_use_xfa_dataset_formal_values(orders: list[dict[str, Any]]) -> bool:
|
||||
"""
|
||||
判断订单列表是否已携带 XFA datasets 正式值。
|
||||
|
||||
核心逻辑:任一 observation / evidence_ref / value_source 标明 xfa_dataset 即视为正式值源,
|
||||
此时坐标 confirmed 锁仅作定位参考,不得参与合并或冲突否决。
|
||||
|
||||
Args:
|
||||
orders: 单 Unit 订单列表。
|
||||
|
||||
Returns:
|
||||
True 表示应以 datasets 为准,跳过坐标 confirmed 字段合并。
|
||||
"""
|
||||
for order in orders or []:
|
||||
if not isinstance(order, dict):
|
||||
continue
|
||||
groups: list[Any] = [order.get('header_fields') or []]
|
||||
groups.extend(
|
||||
line.get('fields') or []
|
||||
for line in (order.get('lines') or [])
|
||||
if isinstance(line, dict)
|
||||
)
|
||||
for fields in groups:
|
||||
if not isinstance(fields, list):
|
||||
continue
|
||||
for field in fields:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
if str(field.get('value_source') or '') == 'xfa_dataset':
|
||||
return True
|
||||
for observation in field.get('observations') or []:
|
||||
if not isinstance(observation, dict):
|
||||
continue
|
||||
if str(observation.get('source') or observation.get('value_source') or '') == 'xfa_dataset':
|
||||
return True
|
||||
layout_evidence = observation.get('layout_evidence')
|
||||
if not isinstance(layout_evidence, dict):
|
||||
continue
|
||||
if str(layout_evidence.get('source') or '') == 'xfa_dataset':
|
||||
return True
|
||||
evidence_ref = layout_evidence.get('evidence_ref')
|
||||
if isinstance(evidence_ref, dict) and str(evidence_ref.get('source') or '') == 'xfa_dataset':
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _merge_confirmed_profile_order_fields(run: Any, *, unit: Any, orders: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""注入 confirmed 订单字段并拒绝 Provider 显式冲突;Provider 省略它们是合法的。"""
|
||||
"""
|
||||
注入 confirmed 订单字段并拒绝 Provider 显式冲突;Provider 省略它们是合法的。
|
||||
|
||||
核心逻辑:坐标模板下,confirmed 字段不可被 Provider 改写。
|
||||
XFA(datasets 正式值)订单跳过本合并——OCR/坐标 confirmed 只供点击定位,
|
||||
不得否决或覆盖 datasets(避免「b) Issue invoice to:」类标签 OCR 锁死整单)。
|
||||
"""
|
||||
# [STEP] XFA 正式值优先:坐标 confirmed 锁不得介入。
|
||||
if _orders_use_xfa_dataset_formal_values(orders):
|
||||
return orders
|
||||
locked = {
|
||||
str(item.get('field_id') or ''): item for item in _confirmed_profile_order_fields(run, unit=unit)
|
||||
if item.get('field_id')
|
||||
|
||||
@@ -5,6 +5,8 @@ services/shipping_notice/order_profile_unified_migration.py
|
||||
依赖:xfa_contract、xfa_acroform、order_document_profile_service、SQLAlchemy ORM。
|
||||
逻辑:CLI / Admin API 调用本模块;Dry Run 只产出报告与审计;Execute 生成新 Draft Revision
|
||||
并写入 before/after 审计。报告存审计 detail,不新增表字段(无 Alembic)。
|
||||
摘要 pending_visual:仅统计无 field_layout_id 且 visual_binding 未 confirmed 的 binding
|
||||
(现代 XFA 编辑器靠 order_field_layouts + field_layout_id,可不写 visual_binding)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -821,8 +823,10 @@ def summarize_unified_migration_status(
|
||||
"""
|
||||
轻量汇总模板统一 binding 迁移状态(不读 PDF / AcroForm)。
|
||||
|
||||
核心逻辑:已有 bindings[] 时统计未确认视觉框;否则对 definition 做内存转换预览
|
||||
needs_migration / pending_visual / field_diff,不写库。
|
||||
核心逻辑:已有 bindings[] 时,仅将「无 field_layout_id 且 visual_binding.status
|
||||
非 confirmed」计为待补框;已挂 field_layout_id(共享 order_field_layouts)的
|
||||
XFA 绑定视为视觉已就绪,即使缺少 visual_binding。无 bindings 时对 definition
|
||||
做内存转换预览 needs_migration / pending_visual / field_diff,不写库。
|
||||
|
||||
Args:
|
||||
definition: Profile definition_json。
|
||||
@@ -835,10 +839,12 @@ def summarize_unified_migration_status(
|
||||
mode = str(template_mode or safe_definition.get('template_mode') or 'coordinate').strip()
|
||||
bindings = [item for item in (safe_definition.get('bindings') or []) if isinstance(item, dict)]
|
||||
if bindings:
|
||||
# [STEP] 现代 XFA:field_layout_id → order_field_layouts,无需再确认 visual_binding。
|
||||
pending = sum(
|
||||
1
|
||||
for item in bindings
|
||||
if str((item.get('visual_binding') or {}).get('status') or '').strip() != 'confirmed'
|
||||
if not str(item.get('field_layout_id') or '').strip()
|
||||
and str((item.get('visual_binding') or {}).get('status') or '').strip() != 'confirmed'
|
||||
)
|
||||
status = 'ready' if pending == 0 else 'pending_visual'
|
||||
return {
|
||||
|
||||
@@ -50,7 +50,7 @@ class OrderProfileValueAdapter:
|
||||
def business_fingerprint(self, definition: dict[str, Any]) -> str | None: return self._call('business_fingerprint', definition)
|
||||
def record_mapping_audit(self, **context: Any) -> None: self._call('record_mapping_audit', **context)
|
||||
def identity_summary(self, summary: dict[str, Any], snapshot: dict[str, Any]) -> dict[str, Any]: return self._call('identity_summary', summary, snapshot)
|
||||
def mapping_field_tree(self, *, document_id: int, actor_id: int | None) -> dict[str, Any]: return self._call('mapping_field_tree', document_id=document_id, actor_id=actor_id)
|
||||
def mapping_field_tree(self, *, document_id: int, actor_id: int | None, include_full_values: bool = False) -> dict[str, Any]: return self._call('mapping_field_tree', document_id=document_id, actor_id=actor_id, include_full_values=include_full_values)
|
||||
def mapping_collections(self, *, document_id: int, actor_id: int | None) -> dict[str, Any]: return self._call('mapping_collections', document_id=document_id, actor_id=actor_id)
|
||||
def mapping_value_preview(self, *, document_id: int, path_id: str, actor_id: int | None, include_full_value: bool) -> dict[str, Any]: return self._call('mapping_value_preview', document_id=document_id, path_id=path_id, actor_id=actor_id, include_full_value=include_full_value)
|
||||
def mapping_split_preview(self, **context: Any) -> dict[str, Any]: return self._call('mapping_split_preview', **context)
|
||||
|
||||
@@ -3,6 +3,15 @@
|
||||
用途:在共同视觉/OCR 解析完成后,以 XFA datasets 作为正式字段值并提供交叉校验。
|
||||
依赖:共同 Route 的视觉匹配与 coordinate/OCR 提取,以及 document_layout 的 XFA datasets 解析。
|
||||
逻辑:本模块绝不另行选择模板或推进业务状态;先直接调用共同 OCR 提取,最后覆盖正式值。
|
||||
normalize_definition 须回填 order_field_layouts.field_id(画布常交空串),与表内 field_regions 一致。
|
||||
发布门禁 shared_layout_ids:优先 field.region_id,无则回退 parent:field_code。
|
||||
盲测 rows:剔除挂到每行的 header field_code(与 _field_preview_rows 对齐);空视觉
|
||||
reservation 不得冲掉 datasets 单头值。
|
||||
OCR↔datasets 对照仅为诊断,不得写入盲测 reason_codes / 样本验证失败 / 正式抽取 fallback。
|
||||
盲测硬门禁只认 datasets 抽取状态与 reason_codes;visual/mirror/evidence 指标仅展示。
|
||||
发布 path 覆盖:line.reservation_id 可由 header 映射或 reservation_id_region 覆盖
|
||||
(与 runtime compute_effective_reservation_id 一致),不强制再绑行级 datasets path。
|
||||
正式抽取:datasets 通过后剔除 OCR 侧 PARSE_STRATEGY_* 等 fallback,不得否决正式值。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -232,7 +241,26 @@ def normalize_definition(raw: dict[str, Any], *, schema_version: Any, path_conte
|
||||
# 共同视觉布局仍须冻结 Schema field_id,即使 XFA 的正式值来自 datasets。
|
||||
# 表头文字(ITEM/QTY 等)可映射到 Line Schema 字段,因而 header_layouts 与
|
||||
# line_layouts 必须使用同一套 scope/code 规范化;否则保存后快照无法证明字段身份。
|
||||
shared_layouts = [item for item in (raw.get('order_field_layouts') or []) if isinstance(item, dict)]
|
||||
# order_field_layouts 同样回填 field_id:画布常提交空串,盲测 _definition_contract
|
||||
# 虽可临时候补,但持久化定义必须自洽,避免旧进程/旁路仍读到 '' 触发契约失败。
|
||||
order_field_layouts: list[dict[str, Any]] = []
|
||||
for item in raw.get('order_field_layouts') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
layout = dict(item)
|
||||
scope = str(layout.get('scope') or 'header').strip() or 'header'
|
||||
field_code = str(layout.get('field_code') or '').strip()
|
||||
schema_field = profile_fields.get((scope, field_code))
|
||||
if schema_field is None:
|
||||
raise ValidationError(
|
||||
'Order field binding must target a header Schema field',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
|
||||
details={'field_code': field_code or None, 'scope': scope},
|
||||
)
|
||||
layout['field_id'] = str(schema_field['field_id'])
|
||||
layout['scope'] = scope
|
||||
order_field_layouts.append(layout)
|
||||
shared_layouts = list(order_field_layouts)
|
||||
for table in raw.get('table_regions') or []:
|
||||
if not isinstance(table, dict):
|
||||
continue
|
||||
@@ -332,7 +360,7 @@ def normalize_definition(raw: dict[str, Any], *, schema_version: Any, path_conte
|
||||
segment['target_field_id'] = str(field['field_id']); rule['segment'] = segment
|
||||
rules.append(dumped)
|
||||
cross = raw.get('cross_checks') if isinstance(raw.get('cross_checks'), dict) else {}
|
||||
payload = {'template_mode': 'xfa_dataset', 'main_table_id': str(raw.get('main_table_id') or '').strip() or None, 'document_match': raw.get('document_match'), 'table_regions': raw.get('table_regions') or [], 'order_field_layouts': raw.get('order_field_layouts') or [], 'draft_unbound_order_field_layouts': raw.get('draft_unbound_order_field_layouts') or [], 'source_contract': {'template_packet_checksum': template_checksum, 'dataset_structure_fingerprint': fingerprint, 'dataset_root_path': root_path, 'authoritative_line_collection_path': auth_path or None, 'mirror_collection_paths': mirrors}, 'header_mappings': [], 'line_mapping': {'row_path': auth_path or None, 'fields': []}, 'cross_checks': {'acroform_enabled': bool(cross.get('acroform_enabled', True)), 'mirror_collection_policy': str(cross.get('mirror_collection_policy') or 'must_match_when_present'), 'line_amount_formula': str(cross.get('line_amount_formula') or 'quantity_times_unit_price'), 'total_amount_policy': str(cross.get('total_amount_policy') or 'must_equal_line_sum')}, 'split_rules': rules, 'bindings': [rewrite_binding(item) for item in bindings_raw]}
|
||||
payload = {'template_mode': 'xfa_dataset', 'main_table_id': str(raw.get('main_table_id') or '').strip() or None, 'document_match': raw.get('document_match'), 'table_regions': raw.get('table_regions') or [], 'order_field_layouts': order_field_layouts, 'draft_unbound_order_field_layouts': raw.get('draft_unbound_order_field_layouts') or [], 'source_contract': {'template_packet_checksum': template_checksum, 'dataset_structure_fingerprint': fingerprint, 'dataset_root_path': root_path, 'authoritative_line_collection_path': auth_path or None, 'mirror_collection_paths': mirrors}, 'header_mappings': [], 'line_mapping': {'row_path': auth_path or None, 'fields': []}, 'cross_checks': {'acroform_enabled': bool(cross.get('acroform_enabled', True)), 'mirror_collection_policy': str(cross.get('mirror_collection_policy') or 'must_match_when_present'), 'line_amount_formula': str(cross.get('line_amount_formula') or 'quantity_times_unit_price'), 'total_amount_policy': str(cross.get('total_amount_policy') or 'must_equal_line_sum')}, 'split_rules': rules, 'bindings': [rewrite_binding(item) for item in bindings_raw]}
|
||||
try:
|
||||
return validate_xfa_dataset_definition(payload).model_dump(mode='json')
|
||||
except (TypeError, ValueError) as exc:
|
||||
@@ -478,8 +506,17 @@ def identity_summary(summary: dict[str, Any], _snapshot: dict[str, Any]) -> dict
|
||||
return {'adapter': 'xfa_dataset', 'template_packet_checksum': summary.get('template_packet_checksum'), 'dataset_structure_fingerprint': summary.get('dataset_structure_fingerprint'), 'parser_identity': summary.get('parser_identity'), 'analysis_count': summary.get('analysis_count')}
|
||||
|
||||
|
||||
def mapping_field_tree(*, document_id: int, actor_id: int | None) -> dict[str, Any]:
|
||||
"""返回 datasets 字段树;仅供末端映射工作区使用。"""
|
||||
def mapping_field_tree(
|
||||
*,
|
||||
document_id: int,
|
||||
actor_id: int | None,
|
||||
include_full_values: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""返回 datasets 字段树;仅供末端映射工作区使用。
|
||||
|
||||
include_full_values=True 时写入完整 sample_value_display,供管理端字段选型;
|
||||
仍不输出 raw_value 键,并由上游要求 audit_sensitive_read。
|
||||
"""
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import FileAsset, ShippingOrderDocument, ShippingOrderDocumentProfileAudit
|
||||
@@ -500,12 +537,23 @@ def mapping_field_tree(*, document_id: int, actor_id: int | None) -> dict[str, A
|
||||
asset = db.session.get(FileAsset, int(document.asset_id or 0)) if document.asset_id else None
|
||||
if asset is None:
|
||||
raise ValidationError('Value-source sample asset is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_UNAVAILABLE', details={'document_id': int(document.id), 'reason': 'asset_missing'})
|
||||
payload = rebuild_tree_dto_from_analysis(analysis, read_asset_bytes(asset), include_values=True)
|
||||
reveal = bool(include_full_values)
|
||||
payload = rebuild_tree_dto_from_analysis(
|
||||
analysis,
|
||||
read_asset_bytes(asset),
|
||||
include_values=True,
|
||||
include_full_values=reveal,
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type='xfa_field_tree_accessed', aggregate_type='shipping_notice_document',
|
||||
aggregate_id=str(document.id), document_id=document.id, actor_type='admin', actor_id=actor_id,
|
||||
result='success', action='mapping_field_tree', sensitivity_level='internal',
|
||||
after={'analysis_id': analysis.id, 'layout_version_id': int(layout_version.id)},
|
||||
result='success', action='mapping_field_tree',
|
||||
sensitivity_level='sensitive' if reveal else 'internal',
|
||||
after={
|
||||
'analysis_id': analysis.id,
|
||||
'layout_version_id': int(layout_version.id),
|
||||
'full_values_revealed': reveal,
|
||||
},
|
||||
)
|
||||
return sanitize_xfa_dto(payload)
|
||||
|
||||
@@ -1071,13 +1119,89 @@ def _field_preview_rows(*, extraction: Any, validation: Any) -> dict[str, Any]:
|
||||
return {'header_fields': header_fields, 'lines': lines, 'cross_checks': dict(getattr(validation, 'cross_check_summary', None) or {})}
|
||||
|
||||
|
||||
def _blind_rows_excluding_header_fields(
|
||||
*,
|
||||
extraction: Any,
|
||||
json_value,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
将提取行投影为盲测 rows;表头字段只进 order_fields,不进明细 JSON。
|
||||
|
||||
核心逻辑:正式提取会把 header 挂到每行供建单聚合,盲测复核必须与
|
||||
`_field_preview_rows` 一样剔除这些 header field_code。
|
||||
|
||||
Args:
|
||||
extraction: extract_xfa_profile 结果。
|
||||
json_value: 值序列化函数(通常 quality_service._json_value)。
|
||||
|
||||
Returns:
|
||||
仅含明细 field_code 的行字典列表。
|
||||
"""
|
||||
header_codes = {
|
||||
str(item.field_code or '')
|
||||
for item in (getattr(extraction, 'header_fields', None) or [])
|
||||
if str(getattr(item, 'field_code', '') or '')
|
||||
}
|
||||
rows: list[dict[str, Any]] = []
|
||||
for row in getattr(extraction, 'rows', None) or []:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
projected = {
|
||||
str(field['field_code']): json_value(field.get('value'))
|
||||
for field in (row.get('fields') or [])
|
||||
if isinstance(field, dict)
|
||||
and field.get('field_code')
|
||||
and str(field.get('field_code') or '') not in header_codes
|
||||
}
|
||||
if projected:
|
||||
rows.append(projected)
|
||||
return rows
|
||||
|
||||
|
||||
def _merge_visual_reservation_into_blind_candidate(
|
||||
*,
|
||||
datasets_candidate: dict[str, Any],
|
||||
visual_candidate: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
将视觉 Reservation 专区结果并入盲测候选(原地修改)。
|
||||
|
||||
核心逻辑:仅当视觉侧有非空 reservation_id 时覆盖 datasets;空视觉结果不得
|
||||
冲掉已抽取的单头值(否则复核卡显示「未识别到值」而明细 JSON 仍有值)。
|
||||
"""
|
||||
visual_reservation_headers = [
|
||||
item for item in visual_candidate.get('order_fields') or []
|
||||
if isinstance(item, dict)
|
||||
and item.get('field_code') == 'reservation_id'
|
||||
and item.get('value') not in (None, '')
|
||||
]
|
||||
if visual_reservation_headers:
|
||||
datasets_candidate['order_fields'] = [
|
||||
item for item in datasets_candidate['order_fields']
|
||||
if not (item.get('field_code') == 'reservation_id' and item.get('scope') == 'header')
|
||||
] + visual_reservation_headers
|
||||
for index, visual_row in enumerate(visual_candidate.get('rows') or []):
|
||||
if index >= len(datasets_candidate['rows']) or not isinstance(visual_row, dict):
|
||||
continue
|
||||
if visual_row.get('reservation_id') not in (None, ''):
|
||||
datasets_candidate['rows'][index]['reservation_id'] = visual_row['reservation_id']
|
||||
|
||||
|
||||
def _clip_diagnostic_value(value: Any, *, limit: int = 160) -> str:
|
||||
"""将对照诊断值截断为可展示短文本(管理端定位差异,不无限回传长原文)。"""
|
||||
text = str(value if value is not None else '').strip()
|
||||
if len(text) <= limit:
|
||||
return text
|
||||
return f'{text[: max(0, limit - 1)]}…'
|
||||
|
||||
|
||||
def _validation_evidence_cross_check(
|
||||
*, visual_evidence: dict[str, Any], datasets_evidence: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""对共同 OCR 验证证据与 datasets 正式字段做脱敏交叉裁决。
|
||||
"""对共同 OCR 验证证据与 datasets 正式字段做交叉裁决。
|
||||
|
||||
OCR 不产生正式值;这里只返回可审计的字段位置,任何同字段冲突均由调用方
|
||||
转成 Review/验证失败。没有共同 OCR 字段时明确为 unavailable,不能伪造一致。
|
||||
OCR 不产生正式值;返回字段位置及两侧截断展示值,供管理端标明「哪里不一样」。
|
||||
没有共同 OCR 字段时明确为 unavailable,不能伪造一致。
|
||||
"""
|
||||
def values(evidence: dict[str, Any]) -> dict[tuple[str, int | None, str], str]:
|
||||
result: dict[tuple[str, int | None, str], str] = {}
|
||||
@@ -1098,16 +1222,26 @@ def _validation_evidence_cross_check(
|
||||
|
||||
visual_values, dataset_values = values(visual_evidence), values(datasets_evidence)
|
||||
shared = sorted(set(visual_values).intersection(dataset_values))
|
||||
mismatches = [
|
||||
{'scope': scope, 'row_index': row_index, 'field_code': field_code}
|
||||
for scope, row_index, field_code in shared
|
||||
if visual_values[(scope, row_index, field_code)] != dataset_values[(scope, row_index, field_code)]
|
||||
]
|
||||
mismatches = []
|
||||
for scope, row_index, field_code in shared:
|
||||
left = visual_values[(scope, row_index, field_code)]
|
||||
right = dataset_values[(scope, row_index, field_code)]
|
||||
if left == right:
|
||||
continue
|
||||
mismatches.append({
|
||||
'scope': scope,
|
||||
'row_index': row_index,
|
||||
'field_code': field_code,
|
||||
'ocr_value': _clip_diagnostic_value(left),
|
||||
'datasets_value': _clip_diagnostic_value(right),
|
||||
})
|
||||
if len(mismatches) >= 20:
|
||||
break
|
||||
return {
|
||||
'status': 'mismatched' if mismatches else ('matched' if shared else 'unavailable'),
|
||||
'compared_field_count': len(shared),
|
||||
'mismatch_count': len(mismatches),
|
||||
'mismatches': mismatches[:20],
|
||||
'mismatches': mismatches,
|
||||
}
|
||||
|
||||
|
||||
@@ -1184,13 +1318,15 @@ def extract_current_sample(*, profile: Any, sample: Any, actor_id: int | None) -
|
||||
ocr_comparison = _validation_evidence_cross_check(
|
||||
visual_evidence=visual_evidence, datasets_evidence=preview,
|
||||
)
|
||||
if ocr_comparison['status'] == 'mismatched':
|
||||
failures.append('ocr_datasets_mismatch')
|
||||
summary['cross_check_failures'] = list(dict.fromkeys(
|
||||
list(summary.get('cross_check_failures') or []) + ['ocr_datasets_mismatch'],
|
||||
))
|
||||
status = 'failed'
|
||||
summary.update({'header_fields': preview['header_fields'], 'lines': preview['lines'], 'validation_evidence': preview, 'visual_validation_evidence': visual_evidence, 'visual_validation_status': visual_status, 'ocr_datasets_cross_check': ocr_comparison})
|
||||
# XFA:datasets 为正式值;OCR 仅定位/旁路对照。不一致写入诊断,不否决样本验证。
|
||||
summary.update({
|
||||
'header_fields': preview['header_fields'],
|
||||
'lines': preview['lines'],
|
||||
'validation_evidence': preview,
|
||||
'visual_validation_evidence': visual_evidence,
|
||||
'visual_validation_status': visual_status,
|
||||
'ocr_datasets_cross_check': ocr_comparison,
|
||||
})
|
||||
if status == 'passed' and extraction.status != 'parsed':
|
||||
summary['failure_code'] = (extraction.reason_codes or ['xfa_required_field_missing'])[0]
|
||||
return 'failed', summary, {}
|
||||
@@ -1339,31 +1475,21 @@ def blind_candidate(*, profile: Any, sample: Any) -> dict[str, Any]:
|
||||
field_ids = {str(item.get('field_id') or '') for item in (schema_definition.get('fields') or []) if isinstance(item, dict) and item.get('enabled', True) and item.get('field_id')}
|
||||
validation = validate_xfa_extraction(raw_profile=raw_profile, dataset_analysis=outcome.dataset_analysis, extraction=extraction, pdf_bytes=pdf_bytes, schema_field_ids=field_ids)
|
||||
metrics = build_xfa_validation_metrics(definition=definition, extraction=extraction, cross_check_summary=validation.cross_check_summary, schema_field_ids=field_ids)
|
||||
rows = [{str(field['field_code']): quality_service._json_value(field.get('value')) for field in row.get('fields') or [] if isinstance(field, dict) and field.get('field_code')} for row in extraction.rows]
|
||||
datasets_candidate = {'order_fields': [{'field_code': item.field_code, 'value': quality_service._json_value(item.normalized_value), 'status': 'confirmed' if item.normalized_value not in (None, '') and not item.issues else 'failed', 'field_id': item.field_id, 'scope': 'header', 'page_no': 1, 'issues': list(item.issues)} for item in extraction.header_fields], 'rows': [row for row in rows if row]}
|
||||
# 正式提取会把 header 挂到每行;盲测复核与验证页一致,明细 rows 剔除表头 field_code。
|
||||
rows = _blind_rows_excluding_header_fields(
|
||||
extraction=extraction, json_value=quality_service._json_value,
|
||||
)
|
||||
datasets_candidate = {'order_fields': [{'field_code': item.field_code, 'value': quality_service._json_value(item.normalized_value), 'status': 'confirmed' if item.normalized_value not in (None, '') and not item.issues else 'failed', 'field_id': item.field_id, 'scope': 'header', 'page_no': 1, 'issues': list(item.issues)} for item in extraction.header_fields], 'rows': rows}
|
||||
# Reservation 专用证据区不是 XFA 的拆分映射:它和坐标模板盲测共用同一解析器。
|
||||
# 视觉候选中的整单值与指定行覆盖值应参与最终 blind candidate,避免盲测与正式
|
||||
# 公共建单路径出现不同结果。
|
||||
visual_reservation_headers = [
|
||||
item for item in visual_candidate.get('order_fields') or []
|
||||
if isinstance(item, dict) and item.get('field_code') == 'reservation_id'
|
||||
]
|
||||
if visual_reservation_headers:
|
||||
datasets_candidate['order_fields'] = [
|
||||
item for item in datasets_candidate['order_fields']
|
||||
if not (item.get('field_code') == 'reservation_id' and item.get('scope') == 'header')
|
||||
] + visual_reservation_headers
|
||||
for index, visual_row in enumerate(visual_candidate.get('rows') or []):
|
||||
if index >= len(datasets_candidate['rows']) or not isinstance(visual_row, dict):
|
||||
continue
|
||||
if visual_row.get('reservation_id') not in (None, ''):
|
||||
datasets_candidate['rows'][index]['reservation_id'] = visual_row['reservation_id']
|
||||
# 仅非空视觉结果可覆盖 datasets,避免空视觉冲掉已抽取的单头 reservation_id。
|
||||
_merge_visual_reservation_into_blind_candidate(
|
||||
datasets_candidate=datasets_candidate, visual_candidate=visual_candidate,
|
||||
)
|
||||
ocr_comparison = _blind_candidate_cross_check(
|
||||
visual_candidate=visual_candidate, datasets_candidate=datasets_candidate,
|
||||
)
|
||||
# XFA:datasets 正式抽取失败才进 reason_codes;OCR↔datasets 不一致仅诊断,不硬拦盲测。
|
||||
reason_codes = list(extraction.reason_codes or []) + list(validation.reason_codes or [])
|
||||
if ocr_comparison['status'] == 'mismatched':
|
||||
reason_codes.append('ocr_datasets_mismatch')
|
||||
return {
|
||||
'document_id': document.id, 'table_id': visual_table_id, **datasets_candidate,
|
||||
'extraction_status': extraction.status, 'reason_codes': reason_codes,
|
||||
@@ -1380,12 +1506,32 @@ def blind_candidate(*, profile: Any, sample: Any) -> dict[str, Any]:
|
||||
|
||||
|
||||
def blind_gate_failures(*, candidate: dict[str, Any], sample_id: int) -> tuple[list[str], dict[str, float]]:
|
||||
"""校验 datasets 正式值的视觉覆盖、镜像与留痕完整性。"""
|
||||
visual, mirror, evidence = float(candidate.get('visual_coverage_rate') or 0.0), float(candidate.get('mirror_consistency_rate') or 0.0), float(candidate.get('evidence_retention_rate') or 0.0)
|
||||
failures = ([f'sample:{sample_id}:visual_coverage_insufficient'] if visual < 1.0 else []) + ([f'sample:{sample_id}:mirror_consistency_insufficient'] if mirror < 1.0 else []) + ([f'sample:{sample_id}:evidence_retention_insufficient'] if evidence < 1.0 else [])
|
||||
"""
|
||||
XFA 盲测硬门禁:只拦 datasets 正式抽取失败,不拦视觉/OCR/镜像指标。
|
||||
|
||||
核心逻辑:visual_coverage / mirror_consistency / evidence_retention 仍回传供
|
||||
管理端展示与 soft 诊断;正式对账以 datasets 抽取 status/reason_codes 为准。
|
||||
OCR↔datasets 不一致由公共 execute_suite 写入 soft_diagnostics,不经本函数。
|
||||
|
||||
Args:
|
||||
candidate: blind_candidate 产出(须含 extraction_status / reason_codes / 指标)。
|
||||
sample_id: 盲测样本主键,用于失败码前缀。
|
||||
|
||||
Returns:
|
||||
(硬失败码列表, 指标字典)。指标 < 1.0 不产生硬失败。
|
||||
"""
|
||||
visual = float(candidate.get('visual_coverage_rate') or 0.0)
|
||||
mirror = float(candidate.get('mirror_consistency_rate') or 0.0)
|
||||
evidence = float(candidate.get('evidence_retention_rate') or 0.0)
|
||||
failures: list[str] = []
|
||||
# [STEP 1] 仅 datasets 抽取失败硬拦;视觉定位/镜像/留痕不否决盲测通过。
|
||||
if candidate.get('extraction_status') != 'parsed' or candidate.get('reason_codes'):
|
||||
failures.append(f"sample:{sample_id}:extraction:{(candidate.get('reason_codes') or ['failed'])[0]}")
|
||||
return failures, {'visual_coverage_rate': visual, 'mirror_consistency_rate': mirror, 'evidence_retention_rate': evidence}
|
||||
return failures, {
|
||||
'visual_coverage_rate': visual,
|
||||
'mirror_consistency_rate': mirror,
|
||||
'evidence_retention_rate': evidence,
|
||||
}
|
||||
|
||||
|
||||
def _blocking_shared_field_labels(*, definition: dict[str, Any], schema_field_ids: set[str]) -> list[dict[str, Any]]:
|
||||
@@ -1406,9 +1552,8 @@ def _blocking_shared_field_labels(*, definition: dict[str, Any], schema_field_id
|
||||
if not bindings:
|
||||
return blocking
|
||||
formal_ids = collect_formal_schema_field_ids(definition, schema_field_ids=schema_field_ids or None)
|
||||
# 共同视觉标签既包含订单抬头值框,也包含每个明细行的字段框。XFA binding 的
|
||||
# field_layout_id 使用 `${line_layout_id}:${field_code}`,必须按相同身份验证,
|
||||
# 否则明细 datasets 映射会被错误要求创建一个无关的抬头框。
|
||||
# 共同视觉标签:优先 field.region_id(画布框稳定身份);无 region_id 时回退
|
||||
# legacy `${parent_layout_id}:{field_code}`。表头/明细 field_regions 均计入。
|
||||
shared_layout_ids = {
|
||||
str(item.get('layout_id') or '')
|
||||
for item in (definition.get('order_field_layouts') or [])
|
||||
@@ -1417,18 +1562,20 @@ def _blocking_shared_field_labels(*, definition: dict[str, Any], schema_field_id
|
||||
for table in definition.get('table_regions') or []:
|
||||
if not isinstance(table, dict):
|
||||
continue
|
||||
for line in table.get('line_layouts') or []:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
line_layout_id = str(line.get('layout_id') or '').strip()
|
||||
if not line_layout_id:
|
||||
continue
|
||||
for field in line.get('field_regions') or []:
|
||||
if not isinstance(field, dict):
|
||||
for layout_key in ('header_layouts', 'line_layouts'):
|
||||
for layout in table.get(layout_key) or []:
|
||||
if not isinstance(layout, dict):
|
||||
continue
|
||||
field_code = str(field.get('field_code') or '').strip()
|
||||
if field_code:
|
||||
shared_layout_ids.add(f'{line_layout_id}:{field_code}')
|
||||
parent_layout_id = str(layout.get('layout_id') or '').strip()
|
||||
for field in layout.get('field_regions') or []:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
region_id = str(field.get('region_id') or '').strip()
|
||||
field_code = str(field.get('field_code') or '').strip()
|
||||
if region_id:
|
||||
shared_layout_ids.add(region_id)
|
||||
elif parent_layout_id and field_code:
|
||||
shared_layout_ids.add(f'{parent_layout_id}:{field_code}')
|
||||
publishable: dict[str, bool] = {}
|
||||
for raw in bindings:
|
||||
if not isinstance(raw, dict):
|
||||
@@ -1463,10 +1610,57 @@ def _blocking_validation_metrics(summary: dict[str, Any]) -> list[dict[str, Any]
|
||||
]
|
||||
|
||||
|
||||
def _extend_mapped_ids_with_reservation_coverage(
|
||||
*,
|
||||
definition: dict[str, Any],
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
mapped_ids: set[str],
|
||||
) -> set[str]:
|
||||
"""
|
||||
将 Reservation 覆盖规则并入已映射 field_id 集合。
|
||||
|
||||
核心逻辑:与 Schema Runtime ``compute_effective_reservation_id`` 对齐——
|
||||
行级 reservation_id 可回退到头字段;``reservation_id_region`` 可同时覆盖头/行。
|
||||
XFA 模板通常只绑 header datasets path(如 SHIPMENT_TEXT),不得再强制行级 path。
|
||||
|
||||
Args:
|
||||
definition: Profile definition。
|
||||
schema_fields: 启用中的 Schema field_id → 配置。
|
||||
mapped_ids: 已由 bindings/拆分覆盖的 field_id。
|
||||
|
||||
Returns:
|
||||
扩展后的 mapped_ids(新集合,不修改入参)。
|
||||
"""
|
||||
covered = set(mapped_ids)
|
||||
header_ids = {
|
||||
field_id
|
||||
for field_id, cfg in schema_fields.items()
|
||||
if str(cfg.get('field_code') or '') == 'reservation_id'
|
||||
and str(cfg.get('scope') or '') == 'header'
|
||||
}
|
||||
line_ids = {
|
||||
field_id
|
||||
for field_id, cfg in schema_fields.items()
|
||||
if str(cfg.get('field_code') or '') == 'reservation_id'
|
||||
and str(cfg.get('scope') or '') == 'line'
|
||||
}
|
||||
region = definition.get('reservation_id_region')
|
||||
has_region = isinstance(region, dict) and bool(region)
|
||||
# [STEP 1] 专区存在时:头/行 reservation 均视为已有正式取值路径(专区解析,非 OCR)。
|
||||
if has_region:
|
||||
covered |= header_ids | line_ids
|
||||
return covered
|
||||
# [STEP 2] 仅有头 datasets 映射时:行级建单键可回退头值,记入已覆盖。
|
||||
if header_ids & covered:
|
||||
covered |= line_ids
|
||||
return covered
|
||||
|
||||
|
||||
def publish_checks(profile: Any, *, validation: Any | None) -> list[dict[str, Any]]:
|
||||
"""执行 datasets 值源的既有发布门禁,不参与共同发布生命周期。
|
||||
|
||||
核心逻辑:沿用已发布的路径、集合、拆分规则、共同视觉绑定及当前样本对账门禁;
|
||||
line.reservation_id 可由 header 映射或 reservation_id_region 覆盖;
|
||||
调用方只接收稳定 blocking_items,不能在公共服务判断 XFA。
|
||||
"""
|
||||
definition = dict(profile.definition_json or {})
|
||||
@@ -1508,6 +1702,10 @@ def publish_checks(profile: Any, *, validation: Any | None) -> list[dict[str, An
|
||||
for rule in rule_set.rules:
|
||||
if rule.segment.handling == 'mapped' and rule.segment.target_field_id:
|
||||
mapped_ids.add(str(rule.segment.target_field_id))
|
||||
# [STEP] Reservation:头 path / 专区即可覆盖行级建单键,与 runtime 回退口径一致。
|
||||
mapped_ids = _extend_mapped_ids_with_reservation_coverage(
|
||||
definition=definition, schema_fields=schema_fields, mapped_ids=mapped_ids,
|
||||
)
|
||||
missing_fields = [
|
||||
{
|
||||
'field_id': field_id,
|
||||
@@ -1559,21 +1757,60 @@ def _field_values(table: dict[str, Any] | None) -> dict[tuple[int, str], str]:
|
||||
return values
|
||||
|
||||
|
||||
def _fallback_codes_after_datasets_success(codes: list[Any] | None) -> list[str]:
|
||||
"""
|
||||
datasets 正式抽取与校验已通过时,剔除仅反映 OCR/视觉侧的 fallback 码。
|
||||
|
||||
核心逻辑:共同视觉路径可能留下 PARSE_STRATEGY_* / 无表/多表/坐标证据不可用;
|
||||
这些不能否决已通过的 datasets 正式值。其它码原样保留。
|
||||
|
||||
Args:
|
||||
codes: OCR 决策上遗留的 fallback_reason_codes。
|
||||
|
||||
Returns:
|
||||
过滤后的稳定码列表(去空、保序)。
|
||||
"""
|
||||
drop = {
|
||||
'business_table_not_found',
|
||||
'multiple_business_tables',
|
||||
'ocr_datasets_mismatch',
|
||||
'coordinate_evidence_unavailable',
|
||||
}
|
||||
kept: list[str] = []
|
||||
for raw in codes or []:
|
||||
code = str(raw or '').strip()
|
||||
if not code:
|
||||
continue
|
||||
if code in drop or code.startswith('PARSE_STRATEGY_'):
|
||||
continue
|
||||
kept.append(code)
|
||||
return kept
|
||||
|
||||
|
||||
def _ocr_cross_check(*, ocr_table: dict[str, Any] | None, datasets_table: dict[str, Any]) -> dict[str, Any]:
|
||||
"""对照两种值源的重叠字段,输出数量与差异定位但不写入业务字段原文。"""
|
||||
"""对照两种值源的重叠字段;输出定位与两侧截断值,供诊断,不否决 datasets 正式结果。"""
|
||||
ocr_values = _field_values(ocr_table)
|
||||
dataset_values = _field_values(datasets_table)
|
||||
shared = sorted(set(ocr_values).intersection(dataset_values))
|
||||
mismatches = [
|
||||
{'row_index': row_index, 'field_id': field_id}
|
||||
for row_index, field_id in shared
|
||||
if ocr_values[(row_index, field_id)] != dataset_values[(row_index, field_id)]
|
||||
]
|
||||
mismatches = []
|
||||
for row_index, field_id in shared:
|
||||
left = ocr_values[(row_index, field_id)]
|
||||
right = dataset_values[(row_index, field_id)]
|
||||
if left == right:
|
||||
continue
|
||||
mismatches.append({
|
||||
'row_index': row_index,
|
||||
'field_id': field_id,
|
||||
'ocr_value': _clip_diagnostic_value(left),
|
||||
'datasets_value': _clip_diagnostic_value(right),
|
||||
})
|
||||
if len(mismatches) >= 20:
|
||||
break
|
||||
return {
|
||||
'status': 'mismatched' if mismatches else ('matched' if shared else 'unavailable'),
|
||||
'compared_field_count': len(shared),
|
||||
'mismatch_count': len(mismatches),
|
||||
'mismatches': mismatches[:20],
|
||||
'mismatches': mismatches,
|
||||
}
|
||||
|
||||
|
||||
@@ -1585,7 +1822,8 @@ def extract(
|
||||
"""从 XFA datasets 解析正式值,并直接复用共同 OCR/视觉提取作双向校验。
|
||||
|
||||
核心逻辑:共同 OCR 先产出相同视觉表与字段证据;datasets 仅在最后覆盖正式字段值。
|
||||
datasets 缺失或与 OCR 冲突时仍保留 OCR 证据,但写入 Review 原因码,不能直通。
|
||||
datasets 完整通过后剔除 OCR 侧 PARSE_STRATEGY_* / 无表等 fallback,不得否决正式值;
|
||||
datasets 缺失或业务校验失败时仍强制 Review,禁止 OCR 静默直通。
|
||||
|
||||
Args:
|
||||
run: 冻结的订单抽取运行。
|
||||
@@ -1731,15 +1969,10 @@ def extract(
|
||||
}
|
||||
comparison = _ocr_cross_check(ocr_table=ocr_result.table, datasets_table=table)
|
||||
decision['ocr_datasets_cross_check'] = comparison
|
||||
# OCR 作为共同视觉证据:若 datasets 已完整通过,它的“未找到/多表”只说明
|
||||
# 无法交叉比对,不能替代 datasets 否决最终字段。真正的 datasets 身份、映射和
|
||||
# 业务校验失败均已在上方 fail-closed。
|
||||
decision['fallback_reason_codes'] = [
|
||||
code for code in (decision.get('fallback_reason_codes') or [])
|
||||
if str(code) not in {'business_table_not_found', 'multiple_business_tables'}
|
||||
]
|
||||
if comparison['status'] == 'mismatched':
|
||||
decision['fallback_reason_codes'] = ['ocr_datasets_mismatch']
|
||||
# OCR 作为共同视觉证据:datasets 已完整通过时,视觉行重建/无表等码不得否决正式值。
|
||||
decision['fallback_reason_codes'] = _fallback_codes_after_datasets_success(
|
||||
decision.get('fallback_reason_codes'),
|
||||
)
|
||||
return workflow.ValueAdapterExtractionResult(
|
||||
decision=decision, table=table,
|
||||
evidence={'formal_evidence_summary': extraction.evidence_summary, 'value_source_identity': decision['xfa_structure']},
|
||||
|
||||
@@ -1160,9 +1160,9 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
'Customer is not confirmed',
|
||||
code='SHIPPING.REVIEW_CUSTOMER_UNRESOLVED',
|
||||
)
|
||||
# Candidate normalization adds fulfillment-only derived fields such as
|
||||
# effective_reservation_id. Extraction is the frozen Schema record and
|
||||
# must receive the unmodified reviewed summary for strict field checks.
|
||||
# Candidate normalization 还会附加 fulfillment 派生字段(如 effective_reservation_id)。
|
||||
# Extraction 只物化 Schema 业务字段;行级 reservation_id 已由
|
||||
# build_confirmable_draft_summary 按表头回退写回,此处仍传 summary 而非 normalized。
|
||||
normalized = normalize_candidate_business_summary(summary)
|
||||
extraction = _materialize_extraction(case=case, intake_id=int(intake.id), summary=summary, actor_id=int(user_id))
|
||||
candidate = _create_review_candidate(
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
services/shipping_notice/order_review_draft_service.py
|
||||
|
||||
用途:建单前订单复核草稿的编辑、校验与统一审计;含库存源路由重算、采用建议与保留人工决定。
|
||||
依赖:Review Case/Draft、Run 冻结 Schema、订单字段规则、order_build_eligibility_service、
|
||||
依赖:Review Case/Draft、Run 冻结 Schema、订单字段规则(含 compute_effective_reservation_id)、
|
||||
order_build_eligibility_service、
|
||||
candidate_qualification_service.resolve_review_case_customer_resolved、
|
||||
fulfillment_audit、order_review_progress_bridge、process_gate_bridge、
|
||||
workflow_ledger_service.assert_case_is_current_workflow_version。
|
||||
@@ -10,6 +11,8 @@ services/shipping_notice/order_review_draft_service.py
|
||||
追加 CaseEvent + ShippingAuditEvent,并镜像 review_field_changed 到订单抽取进度流;
|
||||
Item 已关闭/重识别中的冲突经 `_reject_draft_operation` 落 rejected 审计;
|
||||
整单校验汇总客户确认、有效 Reservation、行级库存源候选与自动建单资格;
|
||||
行级必填 reservation_id 空值时先回退表头(与建单资格 / Schema Runtime 一致),再报缺失;
|
||||
确认建单摘要同样回填行级 reservation_id,供物化 FieldValue / 冻结门禁消费;
|
||||
履约波次确认经 build_confirmable_draft_summary(draft_line_ids) 仅对选中行重算 validation;
|
||||
库存路由恢复使用最新已发布规则与库存源启停,不重新识别 PDF,不静默覆盖人工决定;
|
||||
路由恢复幂等键写入 Draft 历史集合(非仅最近一次),旧键重试可安全重放;
|
||||
@@ -47,6 +50,7 @@ from app.services.shipping_notice.order_build_eligibility_service import (
|
||||
from app.services.shipping_notice.recovery_contract import build_review_revalidate_job_ref
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
compute_effective_reservation_id,
|
||||
normalize_order_field_value,
|
||||
validate_order_field_value,
|
||||
)
|
||||
@@ -429,6 +433,8 @@ def _validation(
|
||||
核心逻辑:投影 field_code 值后调用资格服务;多候选不阻断;客户确认按真实
|
||||
Bill-to / Candidate 状态评估(禁止硬编码已确认);结果写入
|
||||
validation_result_json(含 line_projections)供工作台展示。
|
||||
行级必填 reservation_id 空时先按表头回退(与 compute_effective_reservation_id /
|
||||
Schema Runtime STEP 3.5 一致),避免「表头已有预约单号、行格空」误报缺失。
|
||||
可选 raw_lines:仅对给定完整明细行重算(履约波次),禁止继承未选中行导致的整单失败。
|
||||
|
||||
Args:
|
||||
@@ -464,8 +470,22 @@ def _validation(
|
||||
if str(field.get('scope')) != 'line':
|
||||
continue
|
||||
value = _current_value(raw_line, field_id)
|
||||
line[str(field.get('field_code') or field_id)] = value
|
||||
field_code = str(field.get('field_code') or field_id)
|
||||
line[field_code] = value
|
||||
normalized = normalize_order_field_value(value, field)
|
||||
# [STEP] 行预约单号空:先回退表头,再决定是否报 Schema 必填缺失。
|
||||
if (
|
||||
field.get('required')
|
||||
and normalized in (None, '')
|
||||
and field_code == 'reservation_id'
|
||||
):
|
||||
effective = compute_effective_reservation_id(
|
||||
line_reservation_id=None,
|
||||
header_reservation_id=header.get('reservation_id'),
|
||||
)
|
||||
if effective:
|
||||
line[field_code] = effective
|
||||
continue
|
||||
if field.get('required') and normalized in (None, ''):
|
||||
issues.append({'code': 'required_field_missing', 'field_id': field_id, 'draft_line_id': raw_line.get('draft_line_id'), 'severity': 'blocking'})
|
||||
elif normalized is not None and not validate_order_field_value(normalized, field):
|
||||
@@ -564,6 +584,10 @@ def build_confirmable_draft_summary(
|
||||
"""
|
||||
从冻结 Schema 投影完整草稿并重跑确认校验,供原子建单服务使用。
|
||||
|
||||
核心逻辑:投影 header/lines 后,行级 reservation_id 空时回填表头有效值
|
||||
(与 compute_effective_reservation_id / 草稿校验一致),确保确认物化写入
|
||||
行级 FieldValue,冻结门禁不会因「仅表头有预约单号」误拦。
|
||||
|
||||
Args:
|
||||
case: 复核 Case。
|
||||
draft_line_ids: 可选;仅投影这些完整明细行(履约波次),禁止拆分数量。
|
||||
@@ -606,6 +630,15 @@ def build_confirmable_draft_summary(
|
||||
key = str(raw_line.get('draft_line_id') or '').strip()
|
||||
if key and idx < len(lines):
|
||||
lines[idx]['draft_line_id'] = key
|
||||
# [STEP] 行预约单号空:回填表头有效值,供物化 Extraction / 冻结门禁消费。
|
||||
header_reservation = header.get('reservation_id')
|
||||
for line in lines:
|
||||
effective = compute_effective_reservation_id(
|
||||
line_reservation_id=line.get('reservation_id'),
|
||||
header_reservation_id=header_reservation,
|
||||
)
|
||||
if effective:
|
||||
line['reservation_id'] = effective
|
||||
# [STEP] 履约波次必须按选中行重算 can_build/status,禁止继承未选中行的整单失败态。
|
||||
validation = _validation(case, raw_lines=raw_lines)
|
||||
return {**header, 'lines': lines}, validation
|
||||
|
||||
@@ -346,6 +346,18 @@ def _project_case_automation_status(
|
||||
or result.get('reason_code')
|
||||
or 'stp_job_failed'
|
||||
)
|
||||
# 冻结门禁每次 confirm 重算;预约单号等修复后仍须允许技术重试入队。
|
||||
blocking_code = (
|
||||
blocking_reason.get('code')
|
||||
if isinstance(blocking_reason, dict)
|
||||
else str(blocking_reason or '').strip()
|
||||
)
|
||||
if (
|
||||
blocking_code == 'SHIPPING.ORDER_FREEZE_BLOCKED'
|
||||
and can_auto
|
||||
and can_build
|
||||
):
|
||||
retryable = True
|
||||
next_action = result.get('next_action')
|
||||
details = result.get('blocking_reason_details') if isinstance(
|
||||
result.get('blocking_reason_details'), dict,
|
||||
|
||||
@@ -11,7 +11,8 @@ backend/app/services/shipping_notice/order_schema/runtime.py
|
||||
Decision.selected_observation_id 对齐最终选中 Observation,禁止固定取第一条;
|
||||
仅 required 或 auto_create_key_field 字段可进入 blocked_fields;
|
||||
可选非关键字段证据不足只生成 diagnostic Finding,不阻断建单;
|
||||
必填门禁按最终投影判定;
|
||||
必填门禁按最终投影判定;行级 reservation_id 缺失时先回退表头再判完整性
|
||||
(与 compute_effective_reservation_id / 建单资格一致);
|
||||
published_version 固定读取唯一 Schema STANDARD_SHIPPING_NOTICE(兼容历史 SHIPPING_ORDER)。
|
||||
"""
|
||||
|
||||
@@ -1295,6 +1296,16 @@ def persist_dynamic_order(
|
||||
# [STEP 3] 内部项次由系统按解析行顺序生成;不读取或执行任何派生规则。
|
||||
field_lineage: list[dict[str, Any]] = []
|
||||
|
||||
# [STEP 3.5] 行级 reservation 回退表头,再进入完整性门禁(与建单资格一致)。
|
||||
header_reservation = header.get('reservation_id')
|
||||
for projection in line_projections:
|
||||
effective = compute_effective_reservation_id(
|
||||
line_reservation_id=projection.get('reservation_id'),
|
||||
header_reservation_id=header_reservation,
|
||||
)
|
||||
if effective:
|
||||
projection['reservation_id'] = effective
|
||||
|
||||
# [STEP 4] 关键字段完整性按最终投影检查。
|
||||
for config in all_configs.values():
|
||||
if not field_may_block_process(config):
|
||||
|
||||
@@ -279,12 +279,15 @@ def find_active_stp_job(*, business_ref: str) -> Job | None:
|
||||
if not key:
|
||||
return None
|
||||
cache = db.session.info.get('shipping_conversation_projection_read_cache')
|
||||
# 缓存仅在「已加载该键」时可信;空壳缓存(仅 Gate)不得冒充无 Job。
|
||||
if isinstance(cache, dict):
|
||||
jobs = cache.get('stp_jobs_by_ref', {}).get(key, [])
|
||||
return next(
|
||||
(job for job in jobs if str(job.status or '').strip().lower() in {'queued', 'running'}),
|
||||
None,
|
||||
)
|
||||
by_ref = cache.get('stp_jobs_by_ref')
|
||||
if isinstance(by_ref, dict) and key in by_ref:
|
||||
jobs = by_ref.get(key) or []
|
||||
return next(
|
||||
(job for job in jobs if str(job.status or '').strip().lower() in {'queued', 'running'}),
|
||||
None,
|
||||
)
|
||||
return (
|
||||
Job.query
|
||||
.filter(
|
||||
@@ -312,9 +315,12 @@ def find_latest_stp_job(*, business_ref: str) -> Job | None:
|
||||
if not key:
|
||||
return None
|
||||
cache = db.session.info.get('shipping_conversation_projection_read_cache')
|
||||
# 缓存仅在「已加载该键」时可信;空壳缓存不得把失败 Job 误判为缺失。
|
||||
if isinstance(cache, dict):
|
||||
jobs = cache.get('stp_jobs_by_ref', {}).get(key, [])
|
||||
return jobs[0] if jobs else None
|
||||
by_ref = cache.get('stp_jobs_by_ref')
|
||||
if isinstance(by_ref, dict) and key in by_ref:
|
||||
jobs = by_ref.get(key) or []
|
||||
return jobs[0] if jobs else None
|
||||
return (
|
||||
Job.query
|
||||
.filter(
|
||||
|
||||
@@ -297,6 +297,19 @@ def project_case_automation_status(
|
||||
or result.get('reason_code')
|
||||
or 'stp_job_failed'
|
||||
)
|
||||
# 冻结门禁每次 confirm 重算;预约单号等修复后仍须允许技术重试入队
|
||||
#(与 order_review_projection._project_case_automation_status 同源)。
|
||||
blocking_code = (
|
||||
blocking_reason_raw.get('code')
|
||||
if isinstance(blocking_reason_raw, dict)
|
||||
else str(blocking_reason_raw or '').strip()
|
||||
)
|
||||
if (
|
||||
blocking_code == 'SHIPPING.ORDER_FREEZE_BLOCKED'
|
||||
and can_auto
|
||||
and can_build
|
||||
):
|
||||
retryable = True
|
||||
next_action = result.get('next_action')
|
||||
details = (
|
||||
result.get('blocking_reason_details')
|
||||
@@ -929,10 +942,13 @@ def _project_fine_grained_pre_stp_blocking(
|
||||
if run_no and document_id is not None and draft_version is not None:
|
||||
business_ref_prefix = f"stp-auto:{run_no}:doc-{int(document_id)}:"
|
||||
cache = db.session.info.get('shipping_conversation_projection_read_cache')
|
||||
prefix_jobs = (
|
||||
cache.get('stp_jobs_by_prefix', {}).get(business_ref_prefix, [])
|
||||
if isinstance(cache, dict) else None
|
||||
)
|
||||
# 仅当缓存已加载该前缀的 STP Job 列表时才用缓存;空壳 Gate 缓存必须回落 DB,
|
||||
# 否则会把历史 failed Job 误判为「未入队」并错误投影 retry_stp_auto_create。
|
||||
prefix_jobs = None
|
||||
if isinstance(cache, dict):
|
||||
by_prefix = cache.get('stp_jobs_by_prefix')
|
||||
if isinstance(by_prefix, dict) and business_ref_prefix in by_prefix:
|
||||
prefix_jobs = by_prefix.get(business_ref_prefix) or []
|
||||
active_job = (
|
||||
next(
|
||||
(job for job in prefix_jobs if str(job.status or '').strip().lower() in {'queued', 'running'}),
|
||||
@@ -1070,10 +1086,11 @@ def _project_fine_grained_pre_stp_blocking(
|
||||
if run_no and document_id is not None and draft_version is not None:
|
||||
business_ref_prefix = f"stp-auto:{run_no}:doc-{int(document_id)}:"
|
||||
cache = db.session.info.get('shipping_conversation_projection_read_cache')
|
||||
prefix_jobs = (
|
||||
cache.get('stp_jobs_by_prefix', {}).get(business_ref_prefix, [])
|
||||
if isinstance(cache, dict) else None
|
||||
)
|
||||
prefix_jobs = None
|
||||
if isinstance(cache, dict):
|
||||
by_prefix = cache.get('stp_jobs_by_prefix')
|
||||
if isinstance(by_prefix, dict) and business_ref_prefix in by_prefix:
|
||||
prefix_jobs = by_prefix.get(business_ref_prefix) or []
|
||||
queued_job = (
|
||||
next((job for job in prefix_jobs if str(job.status or '').strip().lower() == 'queued'), None)
|
||||
if prefix_jobs is not None else (
|
||||
|
||||
@@ -781,12 +781,17 @@ def assert_case_not_blocked_manual(*, case_no: str, case: ShippingOrderReviewCas
|
||||
# 兼容修复前已落库的技术异常:旧结果被错误写成 retryable=false,
|
||||
# 但 SHIPPING.STP_AUTO_CREATE_UNEXPECTED 本身不是业务裁决原因,普通
|
||||
# retry 应创建新的 Job,而不是强制用户走 reconcile-and-progress。
|
||||
# ORDER_FREEZE_BLOCKED:冻结门禁每次 confirm 重算(如预约单号表头回退已修复),
|
||||
# 允许技术重试再入队,避免 UI/API 死锁在「人工裁决」文案上。
|
||||
effective_error_code = error_code or (
|
||||
blocking_reason.get('code')
|
||||
if isinstance(blocking_reason, dict)
|
||||
else str(blocking_reason or '').strip()
|
||||
)
|
||||
if not retryable_flag and effective_error_code == 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED':
|
||||
if not retryable_flag and effective_error_code in {
|
||||
'SHIPPING.STP_AUTO_CREATE_UNEXPECTED',
|
||||
'SHIPPING.ORDER_FREEZE_BLOCKED',
|
||||
}:
|
||||
return
|
||||
if should_general_retry_be_removed(retryable_flag=retryable_flag, blocking_reason=blocking_reason):
|
||||
raise ConflictError(
|
||||
|
||||
@@ -74,8 +74,11 @@ def test_blocking_xfa_definition_flags_missing_paths_and_collection():
|
||||
assert 'xfa_required_path_coverage_incomplete' in keys
|
||||
|
||||
|
||||
def test_xfa_path_coverage_reports_scope_when_same_code_exists_twice():
|
||||
"""关键断言:同名 header/line 字段缺路径时,发布诊断必须保留真实字段身份。"""
|
||||
def test_xfa_path_coverage_header_reservation_covers_line_key():
|
||||
"""
|
||||
关键断言:header.reservation_id 已绑 datasets path 时,line.reservation_id
|
||||
建单键不再因缺行级 path 阻断发布(与 runtime 头→行回退一致)。
|
||||
"""
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code='XFA_SCOPE_DIAGNOSTIC', display_name='XFA Scope', version=1, status='draft',
|
||||
schema_version_id=1, structure_fingerprint='c' * 64, template_mode='xfa_dataset',
|
||||
@@ -91,6 +94,36 @@ def test_xfa_path_coverage_reports_scope_when_same_code_exists_twice():
|
||||
'field_code': 'reservation_id', 'scope': 'header', 'field_layout_id': 'header-reservation',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': 'header-path', 'data_path': '/data/HEADER/RESERVATION'},
|
||||
}],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': 'header-reservation', 'field_code': 'reservation_id', 'scope': 'header',
|
||||
'page_no': 1, 'region': {'x0': 0.1, 'y0': 0.1, 'x1': 0.2, 'y1': 0.2},
|
||||
}],
|
||||
'header_mappings': [], 'line_mapping': {'row_path': '/data/ITEMS', 'fields': []},
|
||||
'cross_checks': {},
|
||||
},
|
||||
)
|
||||
profile.schema_version = type('SV', (), {'definition_json': {'fields': [
|
||||
{'field_id': 'reservation-header', 'field_code': 'reservation_id', 'scope': 'header', 'enabled': True, 'required': False},
|
||||
{'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line', 'enabled': True, 'required': True, 'auto_create_key_field': True},
|
||||
]}})()
|
||||
|
||||
blocking = xfa_dataset.publish_checks(profile=profile, validation=None)
|
||||
assert 'xfa_required_path_coverage_incomplete' not in {item['key'] for item in blocking}
|
||||
|
||||
|
||||
def test_xfa_path_coverage_reports_line_reservation_when_header_unmapped():
|
||||
"""关键断言:头/行 reservation 均未映射时,诊断须标明缺失的是 line.reservation_id。"""
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code='XFA_SCOPE_MISSING', display_name='XFA Scope Missing', version=1, status='draft',
|
||||
schema_version_id=1, structure_fingerprint='d' * 64, template_mode='xfa_dataset',
|
||||
definition_json={
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:template', 'dataset_structure_fingerprint': 'sha256:structure',
|
||||
'dataset_root_path': '/data', 'authoritative_line_collection_path': '/data/ITEMS',
|
||||
'mirror_collection_paths': [],
|
||||
},
|
||||
'bindings': [],
|
||||
'header_mappings': [], 'line_mapping': {'row_path': '/data/ITEMS', 'fields': []},
|
||||
'cross_checks': {},
|
||||
},
|
||||
@@ -102,8 +135,6 @@ def test_xfa_path_coverage_reports_scope_when_same_code_exists_twice():
|
||||
|
||||
blocking = xfa_dataset.publish_checks(profile=profile, validation=None)
|
||||
coverage = next(item for item in blocking if item['key'] == 'xfa_required_path_coverage_incomplete')
|
||||
|
||||
# 同名显示码只是辅助信息;管理员必须能识别真正缺失的是 line 的 reservation_id。
|
||||
assert coverage['field_codes'] == ['reservation_id']
|
||||
assert coverage['missing_fields'] == [{
|
||||
'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
|
||||
@@ -4,6 +4,7 @@ backend/tests/test_shipping_document_profile_quality.py
|
||||
用途:验证订单文档模板的独立盲测候选、批准资格和冻结 checksum 门禁。
|
||||
依赖:Profile 服务、布局快照、模板盲测服务与测试数据库。
|
||||
逻辑:管理员固化一份独立样本真值;通过且批准后才可放行确定性自动建单。
|
||||
XFA 确认真值允许候选含 bindings 以外的视觉表头(如 bill_to)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -42,6 +43,47 @@ def _memory_file_asset_storage(monkeypatch):
|
||||
monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'delete_object', lambda storage_key: objects.pop(storage_key, None))
|
||||
|
||||
|
||||
def test_expected_order_fields_allows_extra_visual_header_keys_for_xfa_bindings():
|
||||
"""XFA 确认:bindings 表头齐全即可;候选额外含 bill_to 等视觉框不得拒绝。"""
|
||||
binding = SimpleNamespace(
|
||||
scope='header',
|
||||
field_code='customer_po_number',
|
||||
value_binding=SimpleNamespace(path_id='po-path'),
|
||||
)
|
||||
parser = SimpleNamespace(bindings=[binding], header_mappings=[], order_field_layouts=[])
|
||||
raw = {
|
||||
'header:customer_po_number': '4510039229',
|
||||
'header:bill_to_customer': 'Cloud Network Technology Kft.',
|
||||
'header:bill_to_address': 'Bánki Donát u. 1',
|
||||
}
|
||||
|
||||
result = quality._expected_order_fields(raw, parser=parser)
|
||||
|
||||
# 关键断言:正式绑定键保留,额外视觉表头一并写入盲测真值。
|
||||
assert result == raw
|
||||
|
||||
|
||||
def test_expected_order_fields_still_requires_every_bound_header_for_xfa():
|
||||
"""XFA 确认:缺少 bindings 表头仍须拒绝,避免静默漏掉正式 path 字段。"""
|
||||
parser = SimpleNamespace(
|
||||
bindings=[
|
||||
SimpleNamespace(scope='header', field_code='customer_po_number'),
|
||||
SimpleNamespace(scope='header', field_code='currency'),
|
||||
],
|
||||
header_mappings=[],
|
||||
order_field_layouts=[],
|
||||
)
|
||||
|
||||
with pytest.raises(Exception) as caught:
|
||||
quality._expected_order_fields(
|
||||
{'header:customer_po_number': '4510039229', 'header:bill_to_customer': 'X'},
|
||||
parser=parser,
|
||||
)
|
||||
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID'
|
||||
assert 'header:currency' in (getattr(caught.value, 'details', {}) or {}).get('missing_keys', [])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
('actual', 'expected', 'config'),
|
||||
[
|
||||
|
||||
@@ -134,9 +134,57 @@ def test_position_matcher_line_index_1based():
|
||||
parsed_seg = [s for s in result.segments if s.rule_id == 'pos1'][0]
|
||||
assert parsed_seg.normalized_text == 'Vendor Comments:'
|
||||
assert parsed_seg.line_no == 1
|
||||
assert parsed_seg.line_end_no == 1
|
||||
assert parsed_seg.handling == 'evidence_only'
|
||||
|
||||
|
||||
def test_position_matcher_joins_consecutive_lines():
|
||||
"""连续多行 position:line_end + join_with 合并文本并认领范围内行。"""
|
||||
seg = BaseSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='bill_to_address',
|
||||
display_name='账款地址',
|
||||
handling='mapped',
|
||||
target_field_id='f-addr',
|
||||
target_field_code='bill_to_address',
|
||||
)
|
||||
rule_set = _base_rule_set([
|
||||
BaseSplitRule(
|
||||
rule_id='addr-range',
|
||||
matcher=BaseSplitMatcher(
|
||||
type='position',
|
||||
line_index=2,
|
||||
line_end=4,
|
||||
join_with='newline',
|
||||
),
|
||||
segment=seg,
|
||||
),
|
||||
])
|
||||
raw = (
|
||||
'Cloud Network Technology Kft.\n'
|
||||
'Bánki Donát u. 1.\n'
|
||||
'2900 Komárom\n'
|
||||
'Hungary'
|
||||
)
|
||||
result = execute_base_split_rule_set(raw_value=raw, rule_set=rule_set)
|
||||
assert result.status == 'parsed'
|
||||
assert result.mapped_fields['bill_to_address'] == (
|
||||
'Bánki Donát u. 1.\n2900 Komárom\nHungary'
|
||||
)
|
||||
parsed_seg = [s for s in result.segments if s.rule_id == 'addr-range'][0]
|
||||
assert parsed_seg.line_no == 2
|
||||
assert parsed_seg.line_end_no == 4
|
||||
unmatched = [s for s in result.segments if s.matcher_type == 'unmatched']
|
||||
assert len(unmatched) == 1
|
||||
assert unmatched[0].line_no == 1
|
||||
|
||||
|
||||
def test_position_matcher_rejects_inverted_line_range():
|
||||
"""line_end < line_index 时契约拒绝。"""
|
||||
with pytest.raises(Exception):
|
||||
BaseSplitMatcher(type='position', line_index=3, line_end=1)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# [TEST 2] 优先级仲裁——prefix > regex > position > unmatched
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -183,6 +183,51 @@ def test_reference_page_frames_read_annotation_coordinate_evidence():
|
||||
}
|
||||
|
||||
|
||||
def test_definition_contract_hydrates_empty_order_field_id_from_schema():
|
||||
"""盲测候选预览:已保存空 field_id 必须从 Schema 回填,禁止 Pydantic 500。"""
|
||||
schema = SimpleNamespace(definition_json={'fields': [
|
||||
{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'line-start', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'part-field', 'field_code': 'part_number', 'scope': 'line',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
]})
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'order_field_1_9',
|
||||
'field_id': '',
|
||||
'field_code': 'customer_po_number',
|
||||
'scope': 'header',
|
||||
'page_scope': 'exact_page',
|
||||
'page_no': 1,
|
||||
'anchor': None,
|
||||
'fallback_value_region': {'x0': .1, 'y0': .1, 'x1': .4, 'y1': .15},
|
||||
'value_mode': 'single_line',
|
||||
'stop_anchors': [],
|
||||
'required': False,
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}]
|
||||
profile = SimpleNamespace(
|
||||
profile_code='FOX_HUNGARY',
|
||||
version=1,
|
||||
definition_json=definition,
|
||||
schema_version=schema,
|
||||
)
|
||||
|
||||
contract = service._definition_contract(profile)
|
||||
|
||||
# 关键断言:空串 field_id 已按 Schema 回填,坐标契约可构造。
|
||||
assert contract.order_field_layouts[0].field_id == 'po-field'
|
||||
assert contract.order_field_layouts[0].layout_id == 'order_field_1_9'
|
||||
|
||||
|
||||
def test_reservation_region_rejects_schema_without_header_scope():
|
||||
"""无行号 Reservation 需要稳定 Header 落点,只有 Line 字段时不得保存。"""
|
||||
schema = SimpleNamespace(definition_json={'fields': [{
|
||||
@@ -603,6 +648,54 @@ def test_visual_sample_preview_discards_duplicate_unbound_layout_for_bound_field
|
||||
assert result['fields'][0]['value'] == '4510039227'
|
||||
|
||||
|
||||
def test_visual_sample_preview_soft_dedupes_duplicate_order_field_codes(app, monkeypatch):
|
||||
"""进入编辑页时草稿若已重复绑定同一 Header 字段,预览须去重后继续返回样本值。"""
|
||||
glyphs = [
|
||||
{
|
||||
'text': character,
|
||||
'bbox': {'x0': 20 + index * 8, 'y0': 10, 'x1': 26 + index * 8, 'y1': 18},
|
||||
}
|
||||
for index, character in enumerate('4510039227')
|
||||
]
|
||||
schema = SimpleNamespace(definition_json={'fields': [{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
}]})
|
||||
document = SimpleNamespace(id=101)
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': glyphs},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 101 else None)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda _value: schema)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
|
||||
definition = {
|
||||
'document_match': {'required_anchors': []}, 'table_regions': [],
|
||||
'draft_unbound_order_field_layouts': [],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': f'customer_po_{index}', 'field_id': '', 'field_code': 'customer_po_number',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': None, 'fallback_value_region': {'x0': .05, 'y0': .05, 'x1': .60, 'y1': .25},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'normalizer_key': None,
|
||||
'required': False, 'minimum_evidence_level': 'coordinate',
|
||||
} for index in (1, 2)],
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
result = service.preview_order_field_values({
|
||||
'document_id': 101, 'schema_version_id': 7, 'page_no': 1, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
# 关键断言:预览只保留首个重复字段布局,不因 order_field_duplicate 拒绝进入编辑页。
|
||||
assert len(result['fields']) == 1
|
||||
assert result['fields'][0]['field_code'] == 'customer_po_number'
|
||||
assert result['fields'][0]['value'] == '4510039227'
|
||||
|
||||
|
||||
def test_visual_sample_preview_reads_order_field_before_table_region_is_drawn(app, monkeypatch):
|
||||
"""共同视觉预览在明细表尚未标注时,仍可读取已标注的订单级 PO 字段。"""
|
||||
glyphs = [
|
||||
|
||||
@@ -873,3 +873,44 @@ def test_provider_omission_is_merged_but_override_of_confirmed_order_field_is_re
|
||||
assert error.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE'
|
||||
else:
|
||||
raise AssertionError('confirmed order field override must be rejected')
|
||||
|
||||
|
||||
def test_merge_confirmed_fields_skips_lock_when_orders_use_xfa_dataset():
|
||||
"""
|
||||
XFA:datasets 为正式值;坐标 confirmed 锁(含标签 OCR 垃圾值)不得否决或覆盖。
|
||||
关键断言:bill_to 保留 datasets 客户名,且不抛 ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE。
|
||||
"""
|
||||
from unittest.mock import patch
|
||||
|
||||
unit = type('Unit', (), {'document_id': 247})()
|
||||
xfa_orders = [{
|
||||
'header_fields': [{
|
||||
'field_id': '9a81b044-b49f-4ed3-8c09-2aec85fb1470',
|
||||
'value_source': 'xfa_dataset',
|
||||
'observations': [{
|
||||
'value': 'Cloud Network Technology Kft.',
|
||||
'source': 'xfa_dataset',
|
||||
'document_id': 247,
|
||||
'layout_evidence': {
|
||||
'source': 'xfa_dataset',
|
||||
'evidence_ref': {'source': 'xfa_dataset'},
|
||||
},
|
||||
}],
|
||||
}],
|
||||
'lines': [],
|
||||
}]
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_workflow._confirmed_profile_order_fields',
|
||||
lambda _run, unit: [{
|
||||
'field_id': '9a81b044-b49f-4ed3-8c09-2aec85fb1470',
|
||||
'value': 'b) Issue invoice to:',
|
||||
'status': 'confirmed',
|
||||
'source': 'pdf_coordinate',
|
||||
}],
|
||||
):
|
||||
merged = _merge_confirmed_profile_order_fields(object(), unit=unit, orders=xfa_orders)
|
||||
|
||||
obs = merged[0]['header_fields'][0]['observations'][0]
|
||||
assert obs['value'] == 'Cloud Network Technology Kft.'
|
||||
assert obs['source'] == 'xfa_dataset'
|
||||
@@ -0,0 +1,91 @@
|
||||
"""
|
||||
tests/test_shipping_order_profile_unified_migration_status.py
|
||||
|
||||
用途:锁定 summarize_unified_migration_status 的 pending_visual 计数规则。
|
||||
依赖:order_profile_unified_migration.summarize_unified_migration_status。
|
||||
逻辑:纯摘要单测;不读 PDF / 不写库。现代 XFA 绑定靠 field_layout_id,不得因缺少
|
||||
visual_binding 被计为「待补框」。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.order_profile_unified_migration import (
|
||||
summarize_unified_migration_status,
|
||||
)
|
||||
|
||||
|
||||
def test_summarize_skips_pending_when_field_layout_id_present():
|
||||
"""
|
||||
有 field_layout_id 的 XFA binding 即使无 visual_binding,也不计 pending_visual。
|
||||
"""
|
||||
summary = summarize_unified_migration_status(
|
||||
{
|
||||
'template_mode': 'xfa_dataset',
|
||||
'bindings': [
|
||||
{
|
||||
'binding_id': 'bind-po',
|
||||
'field_code': 'customer_po_number',
|
||||
'scope': 'header',
|
||||
'field_layout_id': 'header_po_box',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': 'header-po'},
|
||||
},
|
||||
{
|
||||
'binding_id': 'bind-mat',
|
||||
'field_code': 'material_number',
|
||||
'scope': 'line',
|
||||
'field_layout_id': 'line_1:material_number',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': 'matnr-path'},
|
||||
# visual_binding 缺失或非 confirmed 都不应计入 pending。
|
||||
'visual_binding': {'status': 'suggested'},
|
||||
},
|
||||
],
|
||||
},
|
||||
template_mode='xfa_dataset',
|
||||
)
|
||||
|
||||
# 关键断言:库列表「待补框」不得把已挂共享布局的 XFA 绑定算进去。
|
||||
assert summary['already_unified'] is True
|
||||
assert summary['needs_migration'] is False
|
||||
assert summary['binding_count'] == 2
|
||||
assert summary['pending_visual_count'] == 0
|
||||
assert summary['unified_binding_status'] == 'ready'
|
||||
|
||||
|
||||
def test_summarize_counts_pending_without_field_layout_or_confirmed_visual():
|
||||
"""
|
||||
无 field_layout_id 且 visual 未 confirmed 的 binding 仍计为 pending_visual。
|
||||
"""
|
||||
summary = summarize_unified_migration_status(
|
||||
{
|
||||
'template_mode': 'coordinate',
|
||||
'bindings': [
|
||||
{
|
||||
'binding_id': 'bind-ready',
|
||||
'field_code': 'order_date',
|
||||
'scope': 'header',
|
||||
'field_layout_id': '',
|
||||
'visual_binding': {'status': 'confirmed'},
|
||||
'value_binding': {'type': 'ocr_region'},
|
||||
},
|
||||
{
|
||||
'binding_id': 'bind-pending',
|
||||
'field_code': 'customer_po_number',
|
||||
'scope': 'header',
|
||||
'visual_binding': {'status': 'suggested'},
|
||||
'value_binding': {'type': 'ocr_region'},
|
||||
},
|
||||
{
|
||||
'binding_id': 'bind-missing-visual',
|
||||
'field_code': 'ship_to',
|
||||
'scope': 'header',
|
||||
'value_binding': {'type': 'ocr_region'},
|
||||
},
|
||||
],
|
||||
},
|
||||
template_mode='coordinate',
|
||||
)
|
||||
|
||||
# 关键断言:仅无布局且未确认视觉的两条计入 pending。
|
||||
assert summary['binding_count'] == 3
|
||||
assert summary['pending_visual_count'] == 2
|
||||
assert summary['unified_binding_status'] == 'pending_visual'
|
||||
@@ -0,0 +1,281 @@
|
||||
"""
|
||||
tests/test_shipping_order_review_draft_reservation_fallback.py
|
||||
|
||||
用途:回归「表头已有预约单号、明细行格空」时草稿校验与确认摘要同一回退规则。
|
||||
依赖:order_review_draft_service._validation / build_confirmable_draft_summary、
|
||||
field_rules.compute_effective_reservation_id。
|
||||
逻辑:资格服务已算 effective_reservation_id,但确认物化/冻结只认行级 reservation_id;
|
||||
本测试锁定校验不误拦,且确认摘要必须把表头值写回行字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
_validation,
|
||||
build_confirmable_draft_summary,
|
||||
)
|
||||
|
||||
|
||||
def _string_field(field_id: str, field_code: str, *, scope: str, required: bool) -> dict:
|
||||
"""构造草稿校验用的最小 Schema 字段配置。"""
|
||||
return {
|
||||
'field_id': field_id,
|
||||
'field_code': field_code,
|
||||
'scope': scope,
|
||||
'value_type': 'string',
|
||||
'required': required,
|
||||
'normalizer_key': 'reservation_id' if field_code == 'reservation_id' else 'trim',
|
||||
'validator_keys': ['reservation_id'] if field_code == 'reservation_id' else [],
|
||||
'display_name': field_code,
|
||||
}
|
||||
|
||||
|
||||
def test_draft_validation_accepts_required_line_reservation_from_header():
|
||||
"""
|
||||
表头预约单号有效、行格空时:不得再发 required_field_missing;
|
||||
投影行应带上表头有效值供资格服务使用。
|
||||
"""
|
||||
fields = {
|
||||
'h-res': _string_field('h-res', 'reservation_id', scope='header', required=False),
|
||||
'l-res': _string_field('l-res', 'reservation_id', scope='line', required=True),
|
||||
'part-id': {
|
||||
**_string_field('part-id', 'part_number', scope='line', required=True),
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['atomic_part_number'],
|
||||
},
|
||||
'qty-id': {
|
||||
'field_id': 'qty-id',
|
||||
'field_code': 'qty',
|
||||
'scope': 'line',
|
||||
'value_type': 'decimal',
|
||||
'required': True,
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['positive_decimal'],
|
||||
'display_name': 'qty',
|
||||
},
|
||||
}
|
||||
draft = SimpleNamespace(
|
||||
header_values_json={
|
||||
'machine_fields': [
|
||||
{'field_id': 'h-res', 'observations': [{'value': '2000485916'}]},
|
||||
],
|
||||
'values': {},
|
||||
},
|
||||
lines_json=[{
|
||||
'draft_line_id': 'machine-1',
|
||||
'machine_fields': [
|
||||
{'field_id': 'part-id', 'observations': [{'value': 'A001'}]},
|
||||
{'field_id': 'qty-id', 'observations': [{'value': '1'}]},
|
||||
# 行预约单号故意缺失:应回退表头。
|
||||
],
|
||||
'values': {},
|
||||
}],
|
||||
draft_version=1,
|
||||
)
|
||||
case = SimpleNamespace(
|
||||
current_draft=draft,
|
||||
candidate_id=None,
|
||||
unit=None,
|
||||
unit_id=None,
|
||||
run=None,
|
||||
run_id=None,
|
||||
case_no='CASE-RES-FALLBACK',
|
||||
document_id=1,
|
||||
)
|
||||
captured_lines: list[dict] = []
|
||||
|
||||
def _fake_eligibility(*, lines, **_kwargs):
|
||||
captured_lines.extend(lines)
|
||||
return {
|
||||
'can_build': True,
|
||||
'can_auto_create': True,
|
||||
'shadow_would_auto_create': False,
|
||||
'gates': {'required_fields_complete': True},
|
||||
'failed_gates': [],
|
||||
'issues': [],
|
||||
'line_projections': [{
|
||||
'draft_line_id': 'machine-1',
|
||||
'effective_reservation_id': '2000485916',
|
||||
}],
|
||||
'qualification': {},
|
||||
'assessment': {
|
||||
'can_create_task': True,
|
||||
'missing_required_fields': [],
|
||||
'invalid_lines': [],
|
||||
},
|
||||
'enabled_inventory_source_codes': [],
|
||||
}
|
||||
|
||||
with (
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service._schema_fields',
|
||||
return_value=fields,
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service.assess_order_build_eligibility',
|
||||
side_effect=_fake_eligibility,
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.candidate_qualification_service.resolve_review_case_customer_resolved',
|
||||
return_value=True,
|
||||
),
|
||||
):
|
||||
result = _validation(case)
|
||||
|
||||
# 关键断言:表头回退后不再把行预约单号标成 Schema 必填缺失。
|
||||
assert not any(
|
||||
str(item.get('code') or '') == 'required_field_missing'
|
||||
and str(item.get('field_id') or '') == 'l-res'
|
||||
for item in (result.get('issues') or [])
|
||||
)
|
||||
assert captured_lines and captured_lines[0].get('reservation_id') == '2000485916'
|
||||
assert result['can_build'] is True
|
||||
|
||||
|
||||
def test_draft_validation_still_blocks_when_header_and_line_reservation_missing():
|
||||
"""表头与行均无有效预约单号时,行必填仍应阻断。"""
|
||||
fields = {
|
||||
'h-res': _string_field('h-res', 'reservation_id', scope='header', required=False),
|
||||
'l-res': _string_field('l-res', 'reservation_id', scope='line', required=True),
|
||||
'part-id': {
|
||||
**_string_field('part-id', 'part_number', scope='line', required=True),
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['atomic_part_number'],
|
||||
},
|
||||
'qty-id': {
|
||||
'field_id': 'qty-id',
|
||||
'field_code': 'qty',
|
||||
'scope': 'line',
|
||||
'value_type': 'decimal',
|
||||
'required': True,
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['positive_decimal'],
|
||||
'display_name': 'qty',
|
||||
},
|
||||
}
|
||||
draft = SimpleNamespace(
|
||||
header_values_json={'machine_fields': [], 'values': {}},
|
||||
lines_json=[{
|
||||
'draft_line_id': 'machine-1',
|
||||
'machine_fields': [
|
||||
{'field_id': 'part-id', 'observations': [{'value': 'A001'}]},
|
||||
{'field_id': 'qty-id', 'observations': [{'value': '1'}]},
|
||||
],
|
||||
'values': {},
|
||||
}],
|
||||
draft_version=1,
|
||||
)
|
||||
case = SimpleNamespace(
|
||||
current_draft=draft,
|
||||
candidate_id=None,
|
||||
unit=None,
|
||||
unit_id=None,
|
||||
run=None,
|
||||
run_id=None,
|
||||
case_no='CASE-RES-MISSING',
|
||||
document_id=1,
|
||||
)
|
||||
|
||||
with (
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service._schema_fields',
|
||||
return_value=fields,
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service.assess_order_build_eligibility',
|
||||
return_value={
|
||||
'can_build': True,
|
||||
'can_auto_create': False,
|
||||
'shadow_would_auto_create': False,
|
||||
'gates': {},
|
||||
'failed_gates': [],
|
||||
'issues': [],
|
||||
'line_projections': [],
|
||||
'qualification': {},
|
||||
'assessment': {
|
||||
'can_create_task': True,
|
||||
'missing_required_fields': [],
|
||||
'invalid_lines': [],
|
||||
},
|
||||
'enabled_inventory_source_codes': [],
|
||||
},
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.candidate_qualification_service.resolve_review_case_customer_resolved',
|
||||
return_value=True,
|
||||
),
|
||||
):
|
||||
result = _validation(case)
|
||||
|
||||
# 关键断言:双端皆空时仍报行级预约单号缺失。
|
||||
assert any(
|
||||
str(item.get('code') or '') == 'required_field_missing'
|
||||
and str(item.get('field_id') or '') == 'l-res'
|
||||
for item in (result.get('issues') or [])
|
||||
)
|
||||
assert result['can_build'] is False
|
||||
|
||||
|
||||
def test_build_confirmable_draft_summary_fills_line_reservation_from_header():
|
||||
"""
|
||||
确认建单摘要必须把表头有效预约单号写进行级 reservation_id,
|
||||
否则物化 Extraction 无行 FieldValue,冻结门禁会 ORDER_FREEZE_BLOCKED。
|
||||
"""
|
||||
fields = {
|
||||
'h-res': _string_field('h-res', 'reservation_id', scope='header', required=False),
|
||||
'l-res': _string_field('l-res', 'reservation_id', scope='line', required=True),
|
||||
'part-id': {
|
||||
**_string_field('part-id', 'part_number', scope='line', required=True),
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['atomic_part_number'],
|
||||
},
|
||||
'qty-id': {
|
||||
'field_id': 'qty-id',
|
||||
'field_code': 'qty',
|
||||
'scope': 'line',
|
||||
'value_type': 'decimal',
|
||||
'required': True,
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['positive_decimal'],
|
||||
'display_name': 'qty',
|
||||
},
|
||||
}
|
||||
draft = SimpleNamespace(
|
||||
header_values_json={
|
||||
'machine_fields': [
|
||||
{'field_id': 'h-res', 'observations': [{'value': '2000485916'}]},
|
||||
],
|
||||
'values': {},
|
||||
},
|
||||
lines_json=[{
|
||||
'draft_line_id': 'machine-1',
|
||||
'machine_fields': [
|
||||
{'field_id': 'part-id', 'observations': [{'value': 'A001'}]},
|
||||
{'field_id': 'qty-id', 'observations': [{'value': '1'}]},
|
||||
],
|
||||
'values': {},
|
||||
}],
|
||||
draft_version=3,
|
||||
schema_version_id=1,
|
||||
)
|
||||
case = SimpleNamespace(current_draft=draft)
|
||||
|
||||
with (
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service._schema_fields',
|
||||
return_value=fields,
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service._validation',
|
||||
return_value={'status': 'ready', 'can_build': True, 'issues': []},
|
||||
),
|
||||
):
|
||||
summary, _validation_result = build_confirmable_draft_summary(case)
|
||||
|
||||
# 关键断言:确认摘要行上须带有效预约单号,供物化/冻结消费。
|
||||
assert summary.get('reservation_id') == '2000485916'
|
||||
assert summary['lines'][0].get('reservation_id') == '2000485916'
|
||||
assert summary['lines'][0].get('draft_line_id') == 'machine-1'
|
||||
@@ -681,7 +681,7 @@ def test_runtime_preserves_customer_po_line_number_without_system_line_projectio
|
||||
|
||||
|
||||
def test_runtime_projects_effective_reservation_with_line_override(app):
|
||||
"""行级 Reservation 优先,缺失时回退订单头,二者均可选不构成阶段 0 门禁。"""
|
||||
"""行级 Reservation 优先;缺失时回退订单头,且不得再因行缺值误拦完整性门禁。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
header_reservation = service.save_field(
|
||||
@@ -691,9 +691,11 @@ def test_runtime_projects_effective_reservation_with_line_override(app):
|
||||
{'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
line_cfg = _config(line_reservation['id'], '行预约单号', value_type='string')
|
||||
line_cfg.update({'auto_create_key_field': True, 'minimum_confidence': 0.95})
|
||||
published = _save_and_publish(draft, [
|
||||
_config(header_reservation['id'], '订单预约单号', value_type='string'),
|
||||
_config(line_reservation['id'], '行预约单号', value_type='string'),
|
||||
line_cfg,
|
||||
])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
document = documents[1]
|
||||
@@ -715,7 +717,13 @@ def test_runtime_projects_effective_reservation_with_line_override(app):
|
||||
intake_id=intake_id, snapshot_hash='r' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
|
||||
assert [item['effective_reservation_id'] for item in result['system_line_projections']] == ['3000000001', '3000000002']
|
||||
assert [item['effective_reservation_id'] for item in result['system_line_projections']] == [
|
||||
'3000000001', '3000000002',
|
||||
]
|
||||
# 关键断言:行投影已回填表头值;完整性不得因「行格空」阻断预约单号。
|
||||
assert result['lines'][0].get('reservation_id') == '3000000001'
|
||||
assert result['lines'][1].get('reservation_id') == '3000000002'
|
||||
assert 'reservation_id' not in (result.get('blocked_fields') or [])
|
||||
|
||||
|
||||
def test_dynamic_schema_contract_and_cross_document_persistence(app):
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""
|
||||
tests/test_shipping_stp_projection_cache_shell.py
|
||||
|
||||
用途:空壳投影缓存不得把已失败的 STP Job 误判为「未入队」;
|
||||
ORDER_FREEZE_BLOCKED 在 can_auto+can_build 时须投影为可技术重试。
|
||||
依赖:order_stp_auto_create_service.find_latest_stp_job、
|
||||
reconciliation_projector.project_case_automation_status。
|
||||
逻辑:Gate 投影会写入无 stp_jobs_* 的 session 缓存;若按「缺键=空列表」处理,
|
||||
UI 会错误展示重试自动推进,而 API 又因真实 failed Job 抛 RETRY_STP_BLOCKED_MANUAL。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from app import db
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import find_latest_stp_job
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_case_automation_status,
|
||||
)
|
||||
|
||||
|
||||
def test_find_latest_stp_job_falls_back_when_cache_shell_has_no_ref(app):
|
||||
"""空壳缓存有 dict 但无该 business_ref 时,必须查库而非返回 None。"""
|
||||
with app.app_context():
|
||||
db.session.info['shipping_conversation_projection_read_cache'] = {
|
||||
'gates_by_execution_id': {},
|
||||
'stp_jobs_by_ref': {},
|
||||
}
|
||||
sentinel = SimpleNamespace(id=1904, status='failed', business_ref='stp-auto:r:doc-1:v3')
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.Job'
|
||||
) as job_model:
|
||||
query = job_model.query.filter.return_value.order_by.return_value
|
||||
query.first.return_value = sentinel
|
||||
found = find_latest_stp_job(business_ref='stp-auto:r:doc-1:v3')
|
||||
assert found is sentinel
|
||||
|
||||
|
||||
def test_order_freeze_blocked_projects_retryable_when_can_auto(app):
|
||||
"""
|
||||
历史 Job 以 ORDER_FREEZE_BLOCKED + retryable=false 落库时,
|
||||
若当前仍可建单,投影必须允许技术重试(与 assert_case_not_blocked_manual 放行一致)。
|
||||
"""
|
||||
with app.app_context():
|
||||
draft = SimpleNamespace(draft_version=3)
|
||||
case = SimpleNamespace(
|
||||
case_no='SORC-TEST-FREEZE',
|
||||
status='ready',
|
||||
confirmed_task_id=None,
|
||||
document_id=246,
|
||||
current_draft=draft,
|
||||
run=SimpleNamespace(run_no='SNER-TEST'),
|
||||
candidate_id=None,
|
||||
)
|
||||
failed_job = SimpleNamespace(
|
||||
id=1904,
|
||||
status='failed',
|
||||
result_json={
|
||||
'retryable': False,
|
||||
'blocking_reason': 'SHIPPING.ORDER_FREEZE_BLOCKED',
|
||||
'error_code': 'SHIPPING.ORDER_FREEZE_BLOCKED',
|
||||
},
|
||||
)
|
||||
validation = {'status': 'ready', 'can_auto_create': True, 'can_build': True}
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.build_stp_idempotency_key',
|
||||
return_value='stp-auto:SNER-TEST:doc-246:v3',
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.find_active_stp_job',
|
||||
return_value=None,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.find_latest_stp_job',
|
||||
return_value=failed_job,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_workbench_projection.resolve_formal_ot',
|
||||
return_value={'has_formal_ot': False, 'task_missing': False},
|
||||
):
|
||||
auto = project_case_automation_status(
|
||||
case, validation=validation, post_confirm=None,
|
||||
)
|
||||
|
||||
assert auto['status'] == 'failed'
|
||||
assert auto['retryable'] is True
|
||||
assert auto['job_id'] == 1904
|
||||
assert auto['blocking_reason'] == 'SHIPPING.ORDER_FREEZE_BLOCKED'
|
||||
@@ -80,6 +80,34 @@ def test_tree_nodes_have_path_id_and_no_raw_paths_in_serialized_dto():
|
||||
assert payload['data_path_hash'].startswith('sha256:')
|
||||
assert 'data_path' not in payload
|
||||
assert '4510039227' not in json.dumps(payload)
|
||||
assert 'raw_value' not in json.dumps(payload)
|
||||
|
||||
|
||||
def test_tree_nodes_can_reveal_full_sample_display_without_raw_value_key():
|
||||
"""断言意图:reveal 路径可把完整样本写入 display,但仍禁止 raw_value 键。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
root = analysis.nodes[0]
|
||||
payload = serialize_tree_node(root, include_values=True, include_full_values=True)
|
||||
dumped = json.dumps(payload)
|
||||
assert 'raw_value' not in dumped
|
||||
assert '4510039227' in dumped
|
||||
assert 'data_path' not in payload
|
||||
|
||||
def find_leaf(node: dict):
|
||||
if node.get('is_leaf'):
|
||||
return node
|
||||
for child in node.get('children') or []:
|
||||
found = find_leaf(child)
|
||||
if found:
|
||||
return found
|
||||
return None
|
||||
|
||||
leaf = find_leaf(payload)
|
||||
assert leaf is not None
|
||||
assert leaf.get('full_value_revealed') is True
|
||||
assert leaf.get('display_policy') == 'full'
|
||||
assert '•' not in str(leaf.get('sample_value_display') or '')
|
||||
assert '…' not in str(leaf.get('sample_value_display') or '')
|
||||
|
||||
|
||||
def test_mask_value_for_dto():
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_formal_extraction_route.py
|
||||
|
||||
用途:阶段 3 正式 Worker 路由端到端——精确命中 published XFA Profile 后产出 golden 字段。
|
||||
用途:阶段 3 正式 Worker 路由端到端——精确命中 published XFA Profile 后产出 golden 字段;
|
||||
另锁定盲测 rows 剔除表头、空视觉 reservation 不冲掉 datasets。
|
||||
依赖:order_extraction_workflow、xfa helpers、pytest。
|
||||
逻辑:合成 hybrid PDF + 冻结 Profile 快照 → route_deterministic_unit;
|
||||
断言 A/B 字段、needs_review 失败关闭、无通用回退、snapshot 冻结 parser identity。
|
||||
@@ -36,11 +37,16 @@ def test_datasets_adapter_uses_ocr_only_as_cross_check_evidence():
|
||||
assert result['status'] == 'mismatched'
|
||||
assert result['compared_field_count'] == 1
|
||||
assert result['mismatch_count'] == 1
|
||||
assert result['mismatches'] == [{'row_index': 0, 'field_id': 'material'}]
|
||||
assert result['mismatches'] == [{
|
||||
'row_index': 0,
|
||||
'field_id': 'material',
|
||||
'ocr_value': 'OCR-M1',
|
||||
'datasets_value': 'DATA-M1',
|
||||
}]
|
||||
|
||||
|
||||
def test_datasets_validation_cross_check_reports_shared_ocr_mismatch():
|
||||
"""关键断言:验证/盲测阶段也必须拒绝 OCR 与 datasets 的字段冲突。"""
|
||||
"""关键断言:验证/盲测对照须标出 OCR 与 datasets 冲突字段及两侧截断值。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_validation_evidence_cross_check,
|
||||
)
|
||||
@@ -58,11 +64,17 @@ def test_datasets_validation_cross_check_reports_shared_ocr_mismatch():
|
||||
|
||||
assert result['status'] == 'mismatched'
|
||||
assert result['compared_field_count'] == 2
|
||||
assert result['mismatches'] == [{'scope': 'header', 'row_index': None, 'field_code': 'customer_po_no'}]
|
||||
assert result['mismatches'] == [{
|
||||
'scope': 'header',
|
||||
'row_index': None,
|
||||
'field_code': 'customer_po_no',
|
||||
'ocr_value': 'OCR-PO',
|
||||
'datasets_value': 'DATA-PO',
|
||||
}]
|
||||
|
||||
|
||||
def test_datasets_blind_cross_check_reports_shared_ocr_mismatch():
|
||||
"""关键断言:盲测也复用共同视觉候选,只把 datasets 保留为正式值。"""
|
||||
"""关键断言:盲测也复用共同视觉候选,只把 datasets 保留为正式值;对照带两侧值。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_blind_candidate_cross_check,
|
||||
)
|
||||
@@ -80,7 +92,13 @@ def test_datasets_blind_cross_check_reports_shared_ocr_mismatch():
|
||||
|
||||
assert result['status'] == 'mismatched'
|
||||
assert result['compared_field_count'] == 2
|
||||
assert result['mismatches'] == [{'scope': 'header', 'row_index': None, 'field_code': 'customer_po_no'}]
|
||||
assert result['mismatches'] == [{
|
||||
'scope': 'header',
|
||||
'row_index': None,
|
||||
'field_code': 'customer_po_no',
|
||||
'ocr_value': 'OCR-PO',
|
||||
'datasets_value': 'DATA-PO',
|
||||
}]
|
||||
|
||||
|
||||
def test_datasets_overlap_reuses_common_visual_evidence_then_appends_identity_conflict(monkeypatch):
|
||||
@@ -186,6 +204,226 @@ def test_datasets_overlap_parse_result_uses_formal_datasets_extraction(monkeypat
|
||||
assert result == {'passed': True, 'reason_codes': []}
|
||||
|
||||
|
||||
def test_blind_rows_exclude_header_fields_copied_onto_line_rows():
|
||||
"""
|
||||
正式提取会把单头挂到每行;盲测明细 JSON 必须剔除这些 header field_code。
|
||||
关键断言:currency/reservation_id 等只应出现在 order_fields,不得留在 rows。
|
||||
"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_blind_rows_excluding_header_fields,
|
||||
)
|
||||
|
||||
extraction = SimpleNamespace(
|
||||
header_fields=[
|
||||
SimpleNamespace(field_code='currency'),
|
||||
SimpleNamespace(field_code='reservation_id'),
|
||||
SimpleNamespace(field_code='bill_to_customer'),
|
||||
],
|
||||
rows=[{
|
||||
'fields': [
|
||||
{'field_code': 'currency', 'value': 'USD'},
|
||||
{'field_code': 'reservation_id', 'value': '1000144510'},
|
||||
{'field_code': 'bill_to_customer', 'value': 'Cloud Network'},
|
||||
{'field_code': 'part_number', 'value': 'D4-A08'},
|
||||
{'field_code': 'qty', 'value': 1},
|
||||
],
|
||||
}],
|
||||
)
|
||||
rows = _blind_rows_excluding_header_fields(
|
||||
extraction=extraction, json_value=lambda value: value,
|
||||
)
|
||||
assert rows == [{'part_number': 'D4-A08', 'qty': 1}]
|
||||
|
||||
|
||||
def test_empty_visual_reservation_does_not_wipe_datasets_header():
|
||||
"""空视觉 reservation 不得冲掉 datasets 已抽取的单头值。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_merge_visual_reservation_into_blind_candidate,
|
||||
)
|
||||
|
||||
datasets_candidate = {
|
||||
'order_fields': [{
|
||||
'field_code': 'reservation_id', 'value': '1000144510',
|
||||
'scope': 'header', 'status': 'confirmed', 'field_id': 'f-res',
|
||||
}],
|
||||
'rows': [{'part_number': 'P1'}],
|
||||
}
|
||||
_merge_visual_reservation_into_blind_candidate(
|
||||
datasets_candidate=datasets_candidate,
|
||||
visual_candidate={
|
||||
'order_fields': [{
|
||||
'field_code': 'reservation_id', 'value': None,
|
||||
'scope': 'header', 'status': 'unavailable', 'field_id': 'f-res',
|
||||
}],
|
||||
'rows': [{}],
|
||||
},
|
||||
)
|
||||
reservation = next(
|
||||
item for item in datasets_candidate['order_fields']
|
||||
if item['field_code'] == 'reservation_id'
|
||||
)
|
||||
assert reservation['value'] == '1000144510'
|
||||
|
||||
|
||||
def test_non_empty_visual_reservation_overrides_datasets_header():
|
||||
"""非空视觉 Reservation 专区结果应覆盖 datasets 单头。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_merge_visual_reservation_into_blind_candidate,
|
||||
)
|
||||
|
||||
datasets_candidate = {
|
||||
'order_fields': [{
|
||||
'field_code': 'reservation_id', 'value': 'OLD',
|
||||
'scope': 'header', 'status': 'confirmed', 'field_id': 'f-res',
|
||||
}],
|
||||
'rows': [{'part_number': 'P1'}],
|
||||
}
|
||||
_merge_visual_reservation_into_blind_candidate(
|
||||
datasets_candidate=datasets_candidate,
|
||||
visual_candidate={
|
||||
'order_fields': [{
|
||||
'field_code': 'reservation_id', 'value': '1000144510',
|
||||
'scope': 'header', 'status': 'confirmed', 'field_id': 'f-res',
|
||||
}],
|
||||
'rows': [{'reservation_id': 'LINE-1'}],
|
||||
},
|
||||
)
|
||||
reservation = next(
|
||||
item for item in datasets_candidate['order_fields']
|
||||
if item['field_code'] == 'reservation_id'
|
||||
)
|
||||
assert reservation['value'] == '1000144510'
|
||||
assert datasets_candidate['rows'][0]['reservation_id'] == 'LINE-1'
|
||||
|
||||
|
||||
def test_datasets_success_drops_ocr_parse_strategy_fallback_codes():
|
||||
"""
|
||||
datasets 正式通过后,OCR 行重建 PARSE_STRATEGY 不得留作阻断码。
|
||||
关键断言:PARSE_STRATEGY_* / 无表/坐标证据不可用被剔除;其它码保留。
|
||||
"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_fallback_codes_after_datasets_success,
|
||||
)
|
||||
|
||||
kept = _fallback_codes_after_datasets_success([
|
||||
'PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION',
|
||||
'PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',
|
||||
'business_table_not_found',
|
||||
'coordinate_evidence_unavailable',
|
||||
'reservation_region_needs_review',
|
||||
])
|
||||
assert kept == ['reservation_region_needs_review']
|
||||
|
||||
|
||||
def test_blind_gate_does_not_fail_on_ocr_or_visual_metrics():
|
||||
"""
|
||||
XFA:OCR↔datasets 与 visual/mirror/evidence 指标均不得硬拦盲测(datasets 为正式值)。
|
||||
关键断言:指标 < 1.0 且对照 mismatched 时 failures 为空;抽取失败仍硬拦。
|
||||
"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_blind_candidate_cross_check,
|
||||
blind_gate_failures,
|
||||
)
|
||||
|
||||
visual = {
|
||||
'order_fields': [
|
||||
{'field_code': 'currency', 'value': 'usd', 'scope': 'header'},
|
||||
{'field_code': 'bill_to_customer', 'value': 'Full Block', 'scope': 'header'},
|
||||
],
|
||||
'rows': [{'part_number': 'P1'}],
|
||||
}
|
||||
datasets = {
|
||||
'order_fields': [
|
||||
{'field_code': 'currency', 'value': 'USD', 'scope': 'header'},
|
||||
{'field_code': 'bill_to_customer', 'value': 'Cloud Network', 'scope': 'header'},
|
||||
],
|
||||
'rows': [{'part_number': 'P1'}],
|
||||
}
|
||||
comparison = _blind_candidate_cross_check(
|
||||
visual_candidate=visual, datasets_candidate=datasets,
|
||||
)
|
||||
assert comparison['status'] == 'mismatched'
|
||||
assert {item['field_code'] for item in comparison['mismatches']} == {
|
||||
'currency', 'bill_to_customer',
|
||||
}
|
||||
failures, metrics = blind_gate_failures(
|
||||
candidate={
|
||||
'extraction_status': 'parsed',
|
||||
'reason_codes': [],
|
||||
'visual_coverage_rate': 0.857,
|
||||
'mirror_consistency_rate': 0.5,
|
||||
'evidence_retention_rate': 0.9,
|
||||
'ocr_datasets_cross_check': comparison,
|
||||
},
|
||||
sample_id=44,
|
||||
)
|
||||
assert failures == []
|
||||
assert metrics['visual_coverage_rate'] == 0.857
|
||||
assert 'ocr_datasets_mismatch' not in failures
|
||||
|
||||
extract_failures, _ = blind_gate_failures(
|
||||
candidate={
|
||||
'extraction_status': 'failed',
|
||||
'reason_codes': ['xfa_dataset_missing'],
|
||||
'visual_coverage_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
'evidence_retention_rate': 1.0,
|
||||
},
|
||||
sample_id=45,
|
||||
)
|
||||
assert extract_failures == ['sample:45:extraction:xfa_dataset_missing']
|
||||
|
||||
|
||||
def test_serialize_suite_exposes_soft_diagnostics_without_payload_values():
|
||||
"""执行摘要应带 soft_diagnostics 字段码,且不含对照正文值。"""
|
||||
from app.services.shipping_notice.document_profile_quality_service import serialize_suite
|
||||
|
||||
suite = SimpleNamespace(
|
||||
id=1,
|
||||
profile_id=9,
|
||||
profile_checksum='abc',
|
||||
status='draft',
|
||||
samples=[],
|
||||
approved_at=None,
|
||||
runs=[
|
||||
SimpleNamespace(
|
||||
status='passed',
|
||||
sample_count=1,
|
||||
passed_sample_count=1,
|
||||
failure_codes_json=[],
|
||||
evidence_json={
|
||||
'metrics': {
|
||||
'visual_coverage_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'key_field_accuracy_rate': 1.0,
|
||||
},
|
||||
'soft_diagnostics': [{
|
||||
'sample_id': 44,
|
||||
'code': 'ocr_datasets_mismatch',
|
||||
'mismatch_count': 1,
|
||||
'fields': [{
|
||||
'scope': 'header',
|
||||
'field_code': 'bill_to_customer',
|
||||
'row_index': None,
|
||||
'ocr_value': 'Cloud Network Technology Kft. Full Block',
|
||||
'datasets_value': 'Cloud Network Technology Kft.',
|
||||
}],
|
||||
}],
|
||||
},
|
||||
),
|
||||
],
|
||||
)
|
||||
payload = serialize_suite(suite)
|
||||
assert payload['latest_run']['status'] == 'passed'
|
||||
field = payload['latest_run']['soft_diagnostics'][0]['fields'][0]
|
||||
assert field['field_code'] == 'bill_to_customer'
|
||||
assert field['ocr_value'].startswith('Cloud Network')
|
||||
assert field['datasets_value'] == 'Cloud Network Technology Kft.'
|
||||
dumped = json.dumps(payload['latest_run']['soft_diagnostics'])
|
||||
assert 'normalized_value' not in dumped
|
||||
|
||||
|
||||
def test_xfa_unified_bindings_require_header_blind_truths():
|
||||
"""bindings-only XFA Profile 的 Header 真值不得因 legacy 映射为空而被静默丢弃。"""
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_formal_multiline_extraction.py
|
||||
|
||||
用途:正式提取——多行 MATNR 经已确认 matcher 规则产出 customer_part_number 与 part_number。
|
||||
用途:正式提取——多行 MATNR 经已确认 matcher 规则产出 customer_part_number 与 part_number;
|
||||
Header INVOICED_TO 拆分不得因带 split_rule_ref 的目标 binding 重复读源全文。
|
||||
依赖:xfa_profile_extraction、xfa_split_rule_contract、xfa_dataset、pytest。
|
||||
逻辑:合成多行 datasets XML + 已确认规则集;断言 mapped 字段、evidence_only 与 needs_review 边界。
|
||||
"""
|
||||
@@ -127,7 +128,7 @@ def _confirmed_matnr_rule_set() -> dict:
|
||||
|
||||
|
||||
def _confirmed_header_rule_set() -> dict:
|
||||
"""构造 Header 拆分规则:第 1 行 mapped,其余行 evidence_only。"""
|
||||
"""构造 Header 拆分规则:第 1 行客户,第 2–末行地址。"""
|
||||
return XfaSplitRuleSet(
|
||||
rule_set_id='invoiced-to-v1',
|
||||
rule_version=1,
|
||||
@@ -144,6 +145,14 @@ def _confirmed_header_rule_set() -> dict:
|
||||
handling='mapped', target_field_id='f-bill-customer', target_field_code='bill_to_customer',
|
||||
),
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='bill-address',
|
||||
matcher=XfaSplitMatcher(type='position', line_index=2, line_end=4),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(), segment_code='bill_address', display_name='账款地址',
|
||||
handling='mapped', target_field_id='f-bill-address', target_field_code='bill_to_address',
|
||||
),
|
||||
),
|
||||
],
|
||||
unmatched_line_policy='evidence_only',
|
||||
source='user', status='confirmed', requires_confirmation=False,
|
||||
@@ -158,9 +167,10 @@ def _xfa_binding(
|
||||
scope: str,
|
||||
path_id: str,
|
||||
data_path: str,
|
||||
split_rule_ref: dict | None = None,
|
||||
) -> dict:
|
||||
"""构造最小合法统一 binding。"""
|
||||
return {
|
||||
payload = {
|
||||
'binding_id': binding_id,
|
||||
'field_id': field_id,
|
||||
'field_code': field_code,
|
||||
@@ -178,6 +188,9 @@ def _xfa_binding(
|
||||
'confidence': 0.0,
|
||||
},
|
||||
}
|
||||
if split_rule_ref is not None:
|
||||
payload['split_rule_ref'] = split_rule_ref
|
||||
return payload
|
||||
|
||||
|
||||
def _raw_profile(*, split_rules: list[dict] | None = None) -> dict:
|
||||
@@ -279,7 +292,7 @@ def test_draft_split_rules_fail_closed_needs_review():
|
||||
|
||||
|
||||
def test_confirmed_header_split_rules_extract_customer_line():
|
||||
"""Header 源规则执行一次并产出第 1 行客户名;其余行保留为 evidence。"""
|
||||
"""Header 源规则执行一次并产出客户/地址;不得再附带源全文重复项。"""
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=_raw_profile(split_rules=[_confirmed_header_rule_set()]),
|
||||
@@ -290,4 +303,54 @@ def test_confirmed_header_split_rules_extract_customer_line():
|
||||
)
|
||||
header_values = {item.field_code: item.normalized_value for item in result.header_fields}
|
||||
assert header_values['bill_to_customer'] == 'Cloud Network Technology Kft.'
|
||||
assert header_values['bill_to_address'] == 'Bánki Donát u. 1,\n2900 Komárom,\nHungary'
|
||||
assert sum(item.field_code == 'bill_to_customer' for item in result.header_fields) == 1
|
||||
assert sum(item.field_code == 'bill_to_address' for item in result.header_fields) == 1
|
||||
|
||||
|
||||
def test_header_split_target_bindings_do_not_duplicate_raw_source():
|
||||
"""
|
||||
编辑器形态:账款客户/地址 binding 共享源 path 且带 split_rule_ref。
|
||||
关键断言:表头只保留拆分段,禁止 STEP1 再读源全文导致重复与错误值。
|
||||
"""
|
||||
rule_set = _confirmed_header_rule_set()
|
||||
customer_seg = rule_set['rules'][0]['segment']['segment_id']
|
||||
address_seg = rule_set['rules'][1]['segment']['segment_id']
|
||||
raw = _raw_profile(split_rules=[rule_set])
|
||||
raw['definition']['bindings'].extend([
|
||||
_xfa_binding(
|
||||
binding_id='bind-bill-customer',
|
||||
field_id='f-bill-customer',
|
||||
field_code='bill_to_customer',
|
||||
scope='header',
|
||||
path_id='path-invoiced-to',
|
||||
data_path='/data/HEADER/INVOICED_TO',
|
||||
split_rule_ref={'rule_set_id': 'invoiced-to-v1', 'segment_id': customer_seg},
|
||||
),
|
||||
_xfa_binding(
|
||||
binding_id='bind-bill-address',
|
||||
field_id='f-bill-address',
|
||||
field_code='bill_to_address',
|
||||
scope='header',
|
||||
path_id='path-invoiced-to',
|
||||
data_path='/data/HEADER/INVOICED_TO',
|
||||
split_rule_ref={'rule_set_id': 'invoiced-to-v1', 'segment_id': address_seg},
|
||||
),
|
||||
])
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=raw,
|
||||
dataset_analysis=analysis,
|
||||
schema_definition=_schema_definition(),
|
||||
document_id=1,
|
||||
packet_checksum='pkt-checksum-0123456789abcdef',
|
||||
)
|
||||
customers = [item for item in result.header_fields if item.field_code == 'bill_to_customer']
|
||||
addresses = [item for item in result.header_fields if item.field_code == 'bill_to_address']
|
||||
assert len(customers) == 1
|
||||
assert len(addresses) == 1
|
||||
assert customers[0].normalized_value == 'Cloud Network Technology Kft.'
|
||||
assert addresses[0].normalized_value == 'Bánki Donát u. 1,\n2900 Komárom,\nHungary'
|
||||
# 禁止 STEP1 把源全文挂到目标 field_code。
|
||||
assert 'Cloud Network Technology Kft.\nBánki' not in (customers[0].normalized_value or '')
|
||||
assert customers[0].normalized_value != addresses[0].normalized_value
|
||||
@@ -454,6 +454,30 @@ def test_normalize_definition_freezes_schema_identity_for_visual_header_line_fie
|
||||
assert field['target_fields'] == [{'field_id': 'f-qty', 'field_code': 'quantity', 'scope': 'line'}]
|
||||
|
||||
|
||||
def test_normalize_definition_freezes_schema_identity_for_order_field_layouts():
|
||||
"""订单头视觉框画布常提交空 field_id,XFA 保存必须按 Schema 冻结,禁止盲测读到空串。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
raw, context, _path_id_by_path = _normalization_raw_profile(analysis)
|
||||
assert raw['order_field_layouts'], 'fixture must already contain an order field layout'
|
||||
for layout in raw['order_field_layouts']:
|
||||
layout['field_id'] = ''
|
||||
|
||||
normalized = normalize_definition(
|
||||
raw, schema_version=SimpleNamespace(definition_json=_schema_definition()), path_context=context,
|
||||
)
|
||||
|
||||
# 关键断言:空 field_id 已写成 Schema 主键,持久化定义可直接构造坐标契约。
|
||||
assert all(str(item.get('field_id') or '').strip() for item in normalized['order_field_layouts'])
|
||||
assert all(
|
||||
item['field_id'] == next(
|
||||
field['field_id']
|
||||
for field in _schema_definition()['fields']
|
||||
if field['field_code'] == item['field_code'] and field['scope'] == item['scope']
|
||||
)
|
||||
for item in normalized['order_field_layouts']
|
||||
)
|
||||
|
||||
|
||||
def test_normalize_definition_allows_line_header_inheritance_to_reuse_header_visual_layout():
|
||||
"""行级正式继承可复用同名 Header 视觉框,避免伪造不存在的表格内预约号框。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
|
||||
@@ -107,6 +107,21 @@ def test_position_matcher_accepts_restricted_prefix_post_processor():
|
||||
|
||||
assert matcher.post_processors[0].type == 'prefix'
|
||||
assert matcher.post_processors[0].value == 'MPN'
|
||||
assert matcher.line_end is None
|
||||
assert matcher.join_with is None
|
||||
|
||||
|
||||
def test_position_matcher_accepts_consecutive_line_range():
|
||||
"""连续多行 position:允许 line_end + join_with。"""
|
||||
matcher = XfaSplitMatcher(
|
||||
type='position',
|
||||
line_index=2,
|
||||
line_end=4,
|
||||
join_with='newline',
|
||||
)
|
||||
assert matcher.line_index == 2
|
||||
assert matcher.line_end == 4
|
||||
assert matcher.join_with == 'newline'
|
||||
|
||||
|
||||
def test_rule_set_accepts_rule_id_alias():
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_blind_test.py
|
||||
|
||||
用途:阶段 6 独立盲测指标——视觉/证据率 < 1.0 时失败;所有 adapter 共用 evidence DTO。
|
||||
依赖:document_profile_quality_service serialize / BlindTestRun evidence_json。
|
||||
逻辑:纯单元验证公共 evidence DTO 与阈值语义。
|
||||
用途:阶段 6 独立盲测指标——公共 evidence DTO 序列化;XFA 视觉指标不硬拦通过。
|
||||
依赖:document_profile_quality_service serialize / BlindTestRun evidence_json;
|
||||
xfa_dataset.blind_gate_failures。
|
||||
逻辑:纯单元验证公共 evidence DTO 与 XFA 盲测硬门禁语义。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,6 +14,9 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_profile_quality_service import serialize_suite
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
blind_gate_failures,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
@@ -47,11 +51,17 @@ def test_serialize_suite_reads_shared_adapter_evidence():
|
||||
assert payload['latest_run']['failure_codes'] == ['sample:1:order_field:po:mismatch']
|
||||
|
||||
|
||||
def test_blind_metrics_threshold_requires_full_coverage():
|
||||
"""关键断言:任一统一指标 < 1.0 即视为盲测不合格(契约语义)。"""
|
||||
rates = {
|
||||
'visual_coverage_rate': 0.99,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
}
|
||||
assert any(float(v) < 1.0 for v in rates.values())
|
||||
def test_xfa_blind_gate_keeps_visual_metrics_as_display_only():
|
||||
"""关键断言:XFA 视觉/镜像/留痕 < 1.0 不产生硬失败码,仅回传指标。"""
|
||||
failures, metrics = blind_gate_failures(
|
||||
candidate={
|
||||
'extraction_status': 'parsed',
|
||||
'reason_codes': [],
|
||||
'visual_coverage_rate': 0.99,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
},
|
||||
sample_id=7,
|
||||
)
|
||||
assert failures == []
|
||||
assert metrics['visual_coverage_rate'] == 0.99
|
||||
@@ -296,6 +296,46 @@ def test_xfa_publish_gate_accepts_a_line_binding_with_its_shared_line_visual_lay
|
||||
assert not any(item['key'] == 'xfa_shared_field_label_incomplete' for item in blocking)
|
||||
|
||||
|
||||
def test_xfa_publish_gate_prefers_field_region_id_over_legacy_layout_key():
|
||||
"""有 region_id 时,binding.field_layout_id 必须按 region_id 校验,而不是强制 legacy 键。"""
|
||||
definition = {
|
||||
'order_field_layouts': [],
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'fields': []},
|
||||
'bindings': [{
|
||||
'binding_id': 'line-binding-region',
|
||||
'field_id': 'field-quantity',
|
||||
'field_code': 'quantity',
|
||||
'scope': 'line',
|
||||
'field_layout_id': 'field_qty_box',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-quantity',
|
||||
'data_path': '/datasets/data/data/ITEMS/DATA/MENGE',
|
||||
},
|
||||
}],
|
||||
'table_regions': [{
|
||||
'line_layouts': [{
|
||||
'layout_id': 'line_1',
|
||||
'field_regions': [{
|
||||
'field_code': 'quantity',
|
||||
'scope': 'line',
|
||||
'region_id': 'field_qty_box',
|
||||
'region': {'x0': .2, 'y0': .3, 'x1': .4, 'y1': .4},
|
||||
}],
|
||||
}],
|
||||
}],
|
||||
}
|
||||
|
||||
blocking = _blocking_shared_field_labels(
|
||||
definition=definition,
|
||||
schema_field_ids={'field-quantity'},
|
||||
)
|
||||
|
||||
# 关键断言:region_id 作为 shared layout 主键时,发布门禁应放行。
|
||||
assert not any(item['key'] == 'xfa_shared_field_label_incomplete' for item in blocking)
|
||||
|
||||
|
||||
def test_suggest_split_rules_service_status_draft(app, monkeypatch, _patch_xfa_io):
|
||||
"""拆分建议 service 层 status 必须为 draft/suggested。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -248,6 +248,75 @@ def test_acroform_composite_value_requires_an_explicit_split_binding(monkeypatch
|
||||
assert 'xfa_acroform_mismatch' in result.reason_codes
|
||||
|
||||
|
||||
def test_acroform_skips_header_bindings_with_split_rule_ref(monkeypatch):
|
||||
"""
|
||||
表头拆分目标不得拿源 Widget 全文对账(与明细 split_rule_ref 跳过对齐)。
|
||||
关键断言:即使 datasets 侧与 AcroForm 源全文因换行不同,也不应报 bill_to_* mismatched。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.xfa_profile_extraction import XfaExtractedField
|
||||
|
||||
raw_profile, analysis, extraction = _extract_ok()
|
||||
raw_profile['definition']['bindings'].append({
|
||||
'binding_id': 'bind-bill-customer',
|
||||
'field_id': 'f-bill-customer',
|
||||
'field_code': 'bill_to_customer',
|
||||
'scope': 'header',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-invoiced-to',
|
||||
'data_path': '/data/HEADER/INVOICED_TO',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.0, 'y0': 0.0, 'x1': 0.02, 'y1': 0.02},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.0,
|
||||
},
|
||||
'split_rule_ref': {
|
||||
'rule_set_id': 'invoiced-to-v1',
|
||||
'segment_id': 'seg-bill-customer',
|
||||
},
|
||||
})
|
||||
# 模拟 STEP1 误写的源全文(修复前会按 binding_id 参与 AcroForm 对账)。
|
||||
sample_evidence = extraction.header_fields[0].evidence if extraction.header_fields else {}
|
||||
extraction.header_fields = list(extraction.header_fields) + [
|
||||
XfaExtractedField(
|
||||
mapping_id='bind-bill-customer',
|
||||
field_id='f-bill-customer',
|
||||
field_code='bill_to_customer',
|
||||
data_path='/data/HEADER/INVOICED_TO',
|
||||
raw_value='Cloud Network Technology Kft.\nBánki Donát u.1.',
|
||||
normalized_value='Cloud Network Technology Kft.\nBánki Donát u.1.',
|
||||
quote='Cloud Network Technology Kft.\nBánki Donát u.1.',
|
||||
normalizer_key='trim',
|
||||
evidence=sample_evidence,
|
||||
issues=[],
|
||||
),
|
||||
]
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.xfa_validation.read_acroform_fields',
|
||||
lambda _pdf: [
|
||||
XfaAcroformField(
|
||||
'INVOICED_TO',
|
||||
'INVOICED_TO',
|
||||
'Cloud Network Technology Kft.\r\nBánki Donát u.1.',
|
||||
'Cloud***u.1.',
|
||||
),
|
||||
],
|
||||
)
|
||||
result = validate_xfa_extraction(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
extraction=extraction,
|
||||
pdf_bytes=b'%PDF-fake',
|
||||
)
|
||||
mismatches = result.cross_check_summary.get('acroform_mismatches') or []
|
||||
assert not any(item.get('field_code') == 'bill_to_customer' for item in mismatches)
|
||||
assert 'xfa_acroform_mismatch' not in result.reason_codes
|
||||
|
||||
|
||||
def test_acroform_english_month_date_matches_normalized_dataset_date(monkeypatch):
|
||||
"""AcroForm 的英文月名日期与 datasets ISO 日期一致时不得误判为冲突。"""
|
||||
raw_profile, analysis, extraction = _extract_ok()
|
||||
|
||||
Reference in new issue
Block a user