Merge branch 'dev' into snow
# Conflicts: # frontend/package-lock.json
This commit is contained in:
commit
590a21515a
81 files changed
+7045
-1079
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(
|
||||
|
||||
@@ -553,8 +553,10 @@ class Config:
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder')
|
||||
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>,默认 16)。
|
||||
WECOM_LEAN_TRAINING_JUMP_AGENT_ID = int(os.getenv('WECOM_LEAN_TRAINING_JUMP_AGENT_ID', '16'))
|
||||
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>,默认 27=员工培训)。
|
||||
# 注意:默认值必须指向 content_profile=training 的培训 agent;历史默认 16 实为「通用入口」,
|
||||
# 会导致卡片落地非培训 agent、前端精益页签深链不消费([FIX] 2026-09-11)。
|
||||
WECOM_LEAN_TRAINING_JUMP_AGENT_ID = int(os.getenv('WECOM_LEAN_TRAINING_JUMP_AGENT_ID', '27'))
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED = os.getenv('WECOM_FEEDBACK_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL = os.getenv('WECOM_FEEDBACK_NOTIFY_BASE_URL')
|
||||
WECOM_FEEDBACK_BOT_WEBHOOK = os.getenv('WECOM_FEEDBACK_BOT_WEBHOOK')
|
||||
|
||||
@@ -7,6 +7,7 @@ backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
order_supplement_merge(仅 eml)、order_extraction_ready_document_ids(Unit 级放行)。
|
||||
逻辑:物化附件与排版面 Job 均在主 try 内执行;有 ready PDF 即按 Unit 抽取并下游推进,
|
||||
兄弟文件 layout pending 时 Job 以 partial_units_done 回到 waiting_layout;
|
||||
运行时预算耗尽且仍有 pending Unit 时入队续抽,禁止终态 partially_completed;
|
||||
每个 Unit 按 STP route_decision 直通或落 provisional;needs_review 剥离验收标记;
|
||||
不调用 Dify 主链。阶段 2:direct_pdf 跳过 email_supplements 与 ORDER_EMAIL_ADJUDICATION_*;
|
||||
合并默认 keep_primary_documents_separate(多 PDF 各成 Candidate)。
|
||||
@@ -41,6 +42,7 @@ from app.services.shipping_notice.audit_service import append_shipping_audit_eve
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction_run_result
|
||||
from app.services.shipping_notice.order_extraction_merge import merge_unit_orders
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
_enqueue_ready_order_extraction_job,
|
||||
begin_input_freeze,
|
||||
complete_input_freeze,
|
||||
mark_order_extraction_persistence_started,
|
||||
@@ -50,6 +52,7 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
materialize_order_extraction_run_inputs,
|
||||
ensure_workflow_items_for_run,
|
||||
progress_ready_extraction_unit,
|
||||
revive_layout_prerequisite_failed_units,
|
||||
schedule_order_extraction_layouts,
|
||||
synchronize_order_extraction_expansion_snapshot,
|
||||
transition_order_extraction_run,
|
||||
@@ -774,6 +777,8 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
if code == 'layout_pending'
|
||||
}
|
||||
ready_document_ids = order_extraction_ready_document_ids(run)
|
||||
# 版面已就绪时复活此前因 layout 前置失败的 Unit,避免永久 failed。
|
||||
revive_layout_prerequisite_failed_units(run)
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing')
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
@@ -1170,6 +1175,50 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
# [STEP] 运行时预算耗尽且仍有 pending Unit:保留已抽成果,入队续抽,禁止终态 partially_completed。
|
||||
units = ShippingOrderProcessingUnit.query.filter_by(plan_id=plan.id).order_by(
|
||||
ShippingOrderProcessingUnit.position.asc(),
|
||||
).all()
|
||||
pending_left = any(str(unit.status or '') == 'pending' for unit in units)
|
||||
if runtime_budget_stopped and pending_left:
|
||||
record_run_progress(
|
||||
run=run,
|
||||
event_code='budget_stopped',
|
||||
reason_code='budget_runtime_limit',
|
||||
summary={
|
||||
**_selection_progress_summary(run),
|
||||
'max_runtime_seconds': max_runtime_seconds,
|
||||
'pending_unit_count': sum(
|
||||
1 for unit in units if str(unit.status or '') == 'pending'
|
||||
),
|
||||
'merged_unit_count': len(pending_merge_unit_ids),
|
||||
},
|
||||
job_id=job.id,
|
||||
commit=False,
|
||||
)
|
||||
continue_job_id = _enqueue_ready_order_extraction_job(
|
||||
run, message='运行时预算已用尽,继续识别剩余附件',
|
||||
)
|
||||
run.current_job_id = continue_job_id
|
||||
run.phase = 'waiting_layout'
|
||||
db.session.commit()
|
||||
finish_job(
|
||||
job.id,
|
||||
result={
|
||||
'run_no': run.run_no,
|
||||
'budget_stopped': True,
|
||||
'waiting_continue': True,
|
||||
'handoff_status': 'runtime_budget_continue',
|
||||
'merged_unit_count': len(pending_merge_unit_ids),
|
||||
'pending_unit_count': sum(
|
||||
1 for unit in units if str(unit.status or '') == 'pending'
|
||||
),
|
||||
'continue_job_id': int(continue_job_id),
|
||||
},
|
||||
message='运行时预算已用尽,已排队继续识别剩余附件',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
orders = persisted_orders + merged_orders
|
||||
execution = {
|
||||
'mode': 'deterministic',
|
||||
|
||||
@@ -52,9 +52,10 @@ def _send_reminder(
|
||||
db.session.flush()
|
||||
except IntegrityError:
|
||||
return "skipped"
|
||||
# [STEP] 企微卡片跳转地址:指向员工培训聊天页(agent 16),由前端消费 training_type=lean_management
|
||||
# 自动展开精益页签;agent id 走配置,便于多环境调整,避免硬编码。
|
||||
jump_agent_id = int(current_app.config.get("WECOM_LEAN_TRAINING_JUMP_AGENT_ID") or 16)
|
||||
# [STEP] 企微卡片跳转地址:指向员工培训聊天页(默认 agent 27,content_profile=training),
|
||||
# 由前端 TrainingWorkspacePanel 消费 training_type=lean_management 自动展开精益页签;
|
||||
# agent id 走配置(app_settings/env 覆盖),便于多环境调整,避免硬编码。
|
||||
jump_agent_id = int(current_app.config.get("WECOM_LEAN_TRAINING_JUMP_AGENT_ID") or 27)
|
||||
result = send_wecom_event_message(
|
||||
event_type=event_type,
|
||||
user=recipient,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -866,10 +866,29 @@ def schedule_layout_version(
|
||||
return version
|
||||
|
||||
|
||||
def _document_has_active_or_current_layout(document: ShippingOrderDocument) -> bool:
|
||||
"""
|
||||
判断文档是否已有进行中或可用的版面,从而本轮不必再占配额新建。
|
||||
|
||||
核心逻辑:queued/running 算进行中;current 指向 ready/needs_review 算可用。
|
||||
历史 unsupported(含预算跳过审计)不算可用,允许后续波次重新排程。
|
||||
"""
|
||||
for item in list(getattr(document, 'layout_versions', None) or []):
|
||||
if str(item.status or '') in {'queued', 'running'}:
|
||||
return True
|
||||
current = getattr(document, 'current_layout_version', None)
|
||||
return current is not None and str(current.status or '') in CURRENT_LAYOUT_STATUSES
|
||||
|
||||
|
||||
def schedule_document_layouts(
|
||||
documents: list[ShippingOrderDocument], *, created_by_id: int | None = None,
|
||||
) -> list[ShippingDocumentLayoutVersion]:
|
||||
"""在 Document 持久化事务内为支持附件建立独立布局版本,超量文档保留 skipped 审计。"""
|
||||
"""
|
||||
在 Document 持久化事务内为支持附件建立独立布局版本。
|
||||
|
||||
核心逻辑:只对尚无进行中/可用版面的 PDF 占配额;本轮最多新建 max_documents 个 Job。
|
||||
超出配额的文档本轮不排程、不写 unsupported 伪终态,留给后续 schedule 调用继续排。
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
from app.services.shipping_notice.document_layout.mineru import MINERU_SUPPORTED_EXTENSIONS
|
||||
@@ -882,30 +901,9 @@ def schedule_document_layouts(
|
||||
if item.asset_id is not None
|
||||
and Path(str(item.filename or '')).suffix.lower() in MINERU_SUPPORTED_EXTENSIONS
|
||||
]
|
||||
needing = [item for item in eligible if not _document_has_active_or_current_layout(item)]
|
||||
result: list[ShippingDocumentLayoutVersion] = []
|
||||
for index, document in enumerate(eligible):
|
||||
if index >= max_documents:
|
||||
existing = ShippingDocumentLayoutVersion.query.filter_by(
|
||||
document_id=int(document.id), source_content_hash=str(document.content_hash or ''),
|
||||
parser_key=current_layout_parser_key(), status='unsupported',
|
||||
).first()
|
||||
if existing is None:
|
||||
version_no = int(db.session.query(func.max(ShippingDocumentLayoutVersion.version)).filter_by(
|
||||
document_id=int(document.id),
|
||||
).scalar() or 0) + 1
|
||||
existing = ShippingDocumentLayoutVersion(
|
||||
document_id=int(document.id), version=version_no, status='unsupported',
|
||||
source_content_hash=str(document.content_hash or ''),
|
||||
parser_key=current_layout_parser_key(),
|
||||
parser_name=LAYOUT_PARSER_NAME, backend=LAYOUT_BACKEND,
|
||||
contract_version=LAYOUT_CONTRACT_VERSION,
|
||||
issues_json=['mineru_intake_document_budget_exceeded'], attempt_count=0,
|
||||
finished_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.flush()
|
||||
result.append(existing)
|
||||
continue
|
||||
for document in needing[:max_documents]:
|
||||
version = schedule_layout_version(document, created_by_id=created_by_id)
|
||||
if version is not None:
|
||||
result.append(version)
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -7,7 +7,8 @@ services/shipping_notice/document_layout/order_profile_matcher.py
|
||||
table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column;
|
||||
主表优先按签名表头原子亲和度选择(避免 MinerU 抬头 KV 小表抢主表),并列再比表区重叠;
|
||||
无 hard_valid 时仅当全部候选均坐标结构不可用才抬升 evidence_insufficient;
|
||||
身份表头只读「签名 header_bbox 按主表顶边 deltaY 对齐」后的窗口,禁止表顶宽带兜底;
|
||||
身份表头按各 table_patterns.header_bbox 对齐到对应表区后只读窗口(正确页码),
|
||||
禁止表顶宽带兜底;多 pattern 观测结果并集与签名身份 token 口径一致;
|
||||
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
|
||||
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁;
|
||||
单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。
|
||||
@@ -1352,7 +1353,7 @@ def _observe_layout_features(
|
||||
)
|
||||
|
||||
header_tokens, column_centers, column_width_ratios = _observe_primary_table_header(
|
||||
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
primary_bbox=primary_bbox, signature=signature,
|
||||
)
|
||||
static_text_centers = _observe_static_text_centers(
|
||||
@@ -1722,53 +1723,71 @@ _HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+')
|
||||
def _signature_table_bbox_median(signature: dict[str, Any] | None) -> list[float] | None:
|
||||
"""读取签名首个可用 table_patterns.bbox.median(归一化四点)。"""
|
||||
for pattern in (signature or {}).get('table_patterns') or []:
|
||||
if not isinstance(pattern, dict):
|
||||
continue
|
||||
bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else None
|
||||
if not isinstance(bbox, dict):
|
||||
continue
|
||||
median = bbox.get('median')
|
||||
if isinstance(median, list) and len(median) == 4:
|
||||
try:
|
||||
return [float(item) for item in median]
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
median = _pattern_table_bbox_median(pattern if isinstance(pattern, dict) else None)
|
||||
if median is not None:
|
||||
return median
|
||||
return None
|
||||
|
||||
|
||||
def _align_signature_header_bbox_to_primary(
|
||||
def _pattern_header_bbox(pattern: dict[str, Any] | None) -> list[float] | None:
|
||||
"""读取单个 table_pattern 的 header_bbox。"""
|
||||
if not isinstance(pattern, dict):
|
||||
return None
|
||||
value = pattern.get('header_bbox')
|
||||
if isinstance(value, list) and len(value) == 4:
|
||||
try:
|
||||
return [float(item) for item in value]
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _pattern_table_bbox_median(pattern: dict[str, Any] | None) -> list[float] | None:
|
||||
"""读取单个 table_pattern.bbox.median。"""
|
||||
if not isinstance(pattern, dict):
|
||||
return None
|
||||
bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else None
|
||||
if not isinstance(bbox, dict):
|
||||
return None
|
||||
median = bbox.get('median')
|
||||
if isinstance(median, list) and len(median) == 4:
|
||||
try:
|
||||
return [float(item) for item in median]
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _align_header_bbox_to_table(
|
||||
*,
|
||||
signature: dict[str, Any] | None,
|
||||
primary_bbox: list[float],
|
||||
header_bbox: list[float],
|
||||
signature_table_y0: float | None,
|
||||
table_bbox: list[float],
|
||||
) -> list[float] | None:
|
||||
"""
|
||||
将签名冻结的表头框按当前主表顶边做整体 deltaY 对齐。
|
||||
将签名表头框按目标表顶边做整体 deltaY 对齐并夹在表内。
|
||||
|
||||
核心逻辑:x/高度保持签名 header_bbox;只用 primary_bbox.y0 - signature_table.y0
|
||||
平移;再把 y 夹在主表竖向范围内,避免落到明细数据行。无 header_bbox 时返回 None。
|
||||
核心逻辑:x/高度保持 header_bbox;deltaY = table.y0 - signature_table.y0。
|
||||
"""
|
||||
if not isinstance(primary_bbox, list) or len(primary_bbox) != 4:
|
||||
if not isinstance(table_bbox, list) or len(table_bbox) != 4:
|
||||
return None
|
||||
header_bbox = _signature_header_bbox(signature)
|
||||
if header_bbox is None:
|
||||
if not isinstance(header_bbox, list) or len(header_bbox) != 4:
|
||||
return None
|
||||
table_median = _signature_table_bbox_median(signature)
|
||||
try:
|
||||
hx0, hy0, hx1, hy1 = (float(header_bbox[i]) for i in range(4))
|
||||
py0, py1 = float(primary_bbox[1]), float(primary_bbox[3])
|
||||
py0, py1 = float(table_bbox[1]), float(table_bbox[3])
|
||||
except (TypeError, ValueError, IndexError):
|
||||
return None
|
||||
if hy1 <= hy0 or py1 <= py0:
|
||||
return None
|
||||
delta_y = 0.0
|
||||
if table_median is not None:
|
||||
if signature_table_y0 is not None:
|
||||
try:
|
||||
delta_y = py0 - float(table_median[1])
|
||||
except (TypeError, ValueError, IndexError):
|
||||
delta_y = py0 - float(signature_table_y0)
|
||||
except (TypeError, ValueError):
|
||||
delta_y = 0.0
|
||||
aligned_y0 = hy0 + delta_y
|
||||
aligned_y1 = hy1 + delta_y
|
||||
# [STEP] 夹在主表内;保持最小可读高度。
|
||||
height = max(0.02, aligned_y1 - aligned_y0)
|
||||
clipped_y0 = min(max(aligned_y0, py0), max(py0, py1 - height))
|
||||
clipped_y1 = min(clipped_y0 + height, py1)
|
||||
@@ -1777,51 +1796,106 @@ def _align_signature_header_bbox_to_primary(
|
||||
return [hx0, clipped_y0, hx1, clipped_y1]
|
||||
|
||||
|
||||
def _observe_primary_table_header(
|
||||
def _align_signature_header_bbox_to_primary(
|
||||
*,
|
||||
glyph_tables: dict[str, Any],
|
||||
page_glyphs: dict[str, Any],
|
||||
pages: dict[str, Any],
|
||||
primary_bbox: list[float] | None,
|
||||
signature: dict[str, Any] | None,
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""
|
||||
从对齐身份窗口观测表头,与签名生成保持同一证据口径。
|
||||
|
||||
核心逻辑:有签名 header_bbox 时按主表顶边 deltaY 对齐后只读该窗口;无签名表头框
|
||||
时才用主表顶 18% 保守带(与签名生成兜底一致)。禁止固定带失准后改走表顶多行
|
||||
宽带搜索,避免印刷括号注记污染身份原子。
|
||||
"""
|
||||
if not primary_bbox or len(primary_bbox) != 4:
|
||||
return [], [], []
|
||||
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
|
||||
if not isinstance(glyphs, list):
|
||||
glyphs = []
|
||||
for table_glyphs in glyph_tables.values():
|
||||
if isinstance(table_glyphs, list):
|
||||
glyphs.extend(table_glyphs)
|
||||
page = pages.get('1') or pages.get(1)
|
||||
if not isinstance(glyphs, list) or not glyphs or not isinstance(page, dict):
|
||||
return [], [], []
|
||||
aligned = _align_signature_header_bbox_to_primary(
|
||||
signature=signature, primary_bbox=primary_bbox,
|
||||
primary_bbox: list[float],
|
||||
) -> list[float] | None:
|
||||
"""兼容入口:用签名首个 header_bbox / table median 对齐到主表。"""
|
||||
header_bbox = _signature_header_bbox(signature)
|
||||
if header_bbox is None:
|
||||
return None
|
||||
table_median = _signature_table_bbox_median(signature)
|
||||
signature_table_y0 = float(table_median[1]) if table_median is not None else None
|
||||
return _align_header_bbox_to_table(
|
||||
header_bbox=header_bbox,
|
||||
signature_table_y0=signature_table_y0,
|
||||
table_bbox=primary_bbox,
|
||||
)
|
||||
if aligned is not None:
|
||||
region = {
|
||||
'x0': float(aligned[0]), 'y0': float(aligned[1]),
|
||||
'x1': float(aligned[2]), 'y1': float(aligned[3]),
|
||||
}
|
||||
else:
|
||||
region = {
|
||||
'x0': float(primary_bbox[0]),
|
||||
'y0': float(primary_bbox[1]),
|
||||
'x1': float(primary_bbox[2]),
|
||||
'y1': float(primary_bbox[1]) + max(
|
||||
0.06, (float(primary_bbox[3]) - float(primary_bbox[1])) * 0.18,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _normalized_layout_tables(
|
||||
*,
|
||||
tables: list[dict[str, Any]],
|
||||
pages: dict[str, Any],
|
||||
) -> list[tuple[list[float], Any, dict[str, Any]]]:
|
||||
"""将 layout.tables 规范为 (归一化 bbox, page_no, page)。"""
|
||||
normalized: list[tuple[list[float], Any, dict[str, Any]]] = []
|
||||
for table in tables:
|
||||
page_no = table.get('page_no') or 1
|
||||
page = pages.get(str(page_no)) or pages.get(page_no)
|
||||
bbox = table.get('bbox') if isinstance(table.get('bbox'), dict) else None
|
||||
if not isinstance(page, dict) or not isinstance(bbox, dict):
|
||||
continue
|
||||
try:
|
||||
raw = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')]
|
||||
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if raw[2] <= raw[0] or raw[3] <= raw[1] or width <= 0 or height <= 0:
|
||||
continue
|
||||
norm = raw if max(raw) <= 1 else [
|
||||
raw[0] / width, raw[1] / height, raw[2] / width, raw[3] / height,
|
||||
]
|
||||
normalized.append((norm, page_no, page))
|
||||
return normalized
|
||||
|
||||
|
||||
def _best_table_for_pattern_bbox(
|
||||
*,
|
||||
pattern_bbox: list[float] | None,
|
||||
normalized_tables: list[tuple[list[float], Any, dict[str, Any]]],
|
||||
fallback: list[float] | None,
|
||||
) -> tuple[list[float], Any, dict[str, Any]] | None:
|
||||
"""按与 pattern.bbox.median 的 IoU 选运行时表;无重叠时回退 fallback 及其最近页。"""
|
||||
if pattern_bbox is not None and normalized_tables:
|
||||
best: tuple[float, list[float], Any, dict[str, Any]] | None = None
|
||||
for bbox, page_no, page in normalized_tables:
|
||||
overlap = _bbox_overlap(pattern_bbox, bbox)
|
||||
if best is None or overlap > best[0]:
|
||||
best = (overlap, bbox, page_no, page)
|
||||
if best is not None and best[0] > 0:
|
||||
return best[1], best[2], best[3]
|
||||
if fallback is None or len(fallback) != 4 or not normalized_tables:
|
||||
return None
|
||||
nearest = max(
|
||||
normalized_tables,
|
||||
key=lambda item: _bbox_overlap(fallback, item[0]),
|
||||
)
|
||||
return fallback, nearest[1], nearest[2]
|
||||
|
||||
|
||||
def _glyphs_for_page(
|
||||
*,
|
||||
page_no: Any,
|
||||
page_glyphs: dict[str, Any],
|
||||
glyph_tables: dict[str, Any],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""按页取 glyphs;缺页时回退全部 table glyphs。"""
|
||||
glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no)
|
||||
if isinstance(glyphs, list) and glyphs:
|
||||
return glyphs
|
||||
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
|
||||
if isinstance(glyphs, list) and glyphs:
|
||||
return glyphs
|
||||
merged: list[dict[str, Any]] = []
|
||||
for table_glyphs in glyph_tables.values():
|
||||
if isinstance(table_glyphs, list):
|
||||
merged.extend(table_glyphs)
|
||||
return merged
|
||||
|
||||
|
||||
def _observe_header_region(
|
||||
*,
|
||||
region: dict[str, float],
|
||||
page: dict[str, Any],
|
||||
glyphs: list[dict[str, Any]],
|
||||
table_bbox: list[float],
|
||||
merge_wrap: bool,
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""在指定页的相对区域内读取表头 token/列中心/宽度比。"""
|
||||
width = float(page.get('width') or 0)
|
||||
if width <= 0:
|
||||
if width <= 0 or not glyphs:
|
||||
return [], [], []
|
||||
header_glyphs = _glyphs_in_relative_region(glyphs, page=page, region=region)
|
||||
spans = [
|
||||
@@ -1830,11 +1904,11 @@ def _observe_primary_table_header(
|
||||
][:32]
|
||||
band_tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
|
||||
band_centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans]
|
||||
table_span = max(float(primary_bbox[2]) - float(primary_bbox[0]), 0.0001)
|
||||
table_span = max(float(table_bbox[2]) - float(table_bbox[0]), 0.0001)
|
||||
band_widths = [
|
||||
round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans
|
||||
]
|
||||
if _signature_single_logical_header(signature):
|
||||
if merge_wrap:
|
||||
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
|
||||
band_tokens, band_centers, band_widths,
|
||||
)
|
||||
@@ -1846,6 +1920,97 @@ def _observe_primary_table_header(
|
||||
return band_tokens, band_centers, band_widths
|
||||
|
||||
|
||||
def _observe_primary_table_header(
|
||||
*,
|
||||
tables: list[dict[str, Any]],
|
||||
glyph_tables: dict[str, Any],
|
||||
page_glyphs: dict[str, Any],
|
||||
pages: dict[str, Any],
|
||||
primary_bbox: list[float] | None,
|
||||
signature: dict[str, Any] | None,
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""
|
||||
从对齐身份窗口观测表头,与签名生成保持同一证据口径。
|
||||
|
||||
核心逻辑:对每个带 header_bbox 的 table_pattern,选 IoU 最大的运行时表,按该表
|
||||
所在页做 deltaY 对齐后只读窗口;多 pattern 的 token 并集对应签名身份并集。无
|
||||
header_bbox 时才用主表顶 18% 保守带。禁止表顶多行宽带搜索。
|
||||
"""
|
||||
if not primary_bbox or len(primary_bbox) != 4:
|
||||
return [], [], []
|
||||
|
||||
patterns = [
|
||||
item for item in (signature or {}).get('table_patterns') or []
|
||||
if isinstance(item, dict) and _pattern_header_bbox(item) is not None
|
||||
]
|
||||
normalized_tables = _normalized_layout_tables(tables=tables, pages=pages)
|
||||
observed_tokens: list[str] = []
|
||||
observed_centers: list[float] = []
|
||||
observed_widths: list[float] = []
|
||||
|
||||
if patterns:
|
||||
for pattern in patterns:
|
||||
header_bbox = _pattern_header_bbox(pattern)
|
||||
if header_bbox is None:
|
||||
continue
|
||||
pattern_median = _pattern_table_bbox_median(pattern)
|
||||
matched = _best_table_for_pattern_bbox(
|
||||
pattern_bbox=pattern_median,
|
||||
normalized_tables=normalized_tables,
|
||||
fallback=primary_bbox,
|
||||
)
|
||||
if matched is None:
|
||||
continue
|
||||
table_bbox, page_no, page = matched
|
||||
aligned = _align_header_bbox_to_table(
|
||||
header_bbox=header_bbox,
|
||||
signature_table_y0=(
|
||||
float(pattern_median[1]) if pattern_median is not None else None
|
||||
),
|
||||
table_bbox=table_bbox,
|
||||
)
|
||||
if aligned is None:
|
||||
continue
|
||||
region = {
|
||||
'x0': float(aligned[0]), 'y0': float(aligned[1]),
|
||||
'x1': float(aligned[2]), 'y1': float(aligned[3]),
|
||||
}
|
||||
glyphs = _glyphs_for_page(
|
||||
page_no=page_no, page_glyphs=page_glyphs, glyph_tables=glyph_tables,
|
||||
)
|
||||
tokens, centers, widths = _observe_header_region(
|
||||
region=region, page=page, glyphs=glyphs, table_bbox=table_bbox,
|
||||
merge_wrap=int(pattern.get('header_row_count') or 1) <= 1,
|
||||
)
|
||||
observed_tokens.extend(tokens)
|
||||
observed_centers.extend(centers)
|
||||
observed_widths.extend(widths)
|
||||
if observed_tokens:
|
||||
return observed_tokens, observed_centers, observed_widths
|
||||
|
||||
# 无签名表头框或 pattern 均未读到:主表顶 18% 保守带(与签名生成兜底一致)。
|
||||
page_no, page = _page_for_primary_table_bbox(
|
||||
primary_bbox, tables=tables, pages=pages,
|
||||
)
|
||||
if not isinstance(page, dict):
|
||||
return [], [], []
|
||||
glyphs = _glyphs_for_page(
|
||||
page_no=page_no, page_glyphs=page_glyphs, glyph_tables=glyph_tables,
|
||||
)
|
||||
region = {
|
||||
'x0': float(primary_bbox[0]),
|
||||
'y0': float(primary_bbox[1]),
|
||||
'x1': float(primary_bbox[2]),
|
||||
'y1': float(primary_bbox[1]) + max(
|
||||
0.06, (float(primary_bbox[3]) - float(primary_bbox[1])) * 0.18,
|
||||
),
|
||||
}
|
||||
return _observe_header_region(
|
||||
region=region, page=page, glyphs=glyphs, table_bbox=primary_bbox,
|
||||
merge_wrap=_signature_single_logical_header(signature),
|
||||
)
|
||||
|
||||
|
||||
def _merge_following_wrap_candidate(
|
||||
*,
|
||||
header: dict[str, Any],
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1165,12 +1165,28 @@ def order_extraction_layout_prerequisite_issues(run: ShippingOrderProcessingRun)
|
||||
)
|
||||
version = active_versions[0] if active_versions else document.current_layout_version
|
||||
if version is None:
|
||||
issues[int(document.id)] = 'layout_missing'
|
||||
# 有原件但尚未排到版面(配额延后或历史 budget unsupported 未绑 current):
|
||||
# 记 pending 等待后续 schedule,禁止当成 layout_missing 永久 failed。
|
||||
if document.asset_id:
|
||||
issues[int(document.id)] = 'layout_pending'
|
||||
else:
|
||||
issues[int(document.id)] = 'layout_missing'
|
||||
continue
|
||||
if str(version.status or '') in {'queued', 'running'}:
|
||||
issues[int(document.id)] = 'layout_pending'
|
||||
continue
|
||||
if str(version.status or '') != 'ready':
|
||||
issues_list = [
|
||||
str(item) for item in (version.issues_json or []) if str(item or '').strip()
|
||||
]
|
||||
# 历史预算跳过审计:视为延后排程,不进硬失败。
|
||||
if (
|
||||
str(version.status or '') == 'unsupported'
|
||||
and 'mineru_intake_document_budget_exceeded' in issues_list
|
||||
and bool(document.asset_id)
|
||||
):
|
||||
issues[int(document.id)] = 'layout_pending'
|
||||
continue
|
||||
payload = version.payload_json if isinstance(version.payload_json, dict) else {}
|
||||
# PDF 坐标证据可从原始附件按需恢复;压缩导致的 failed/不完整版本不应
|
||||
# 在正式模板匹配前提前阻断,workflow 会在内存中恢复并继续做确定性匹配。
|
||||
@@ -1204,11 +1220,48 @@ def order_extraction_layouts_pending(run: ShippingOrderProcessingRun) -> bool:
|
||||
_EXTRACT_DONE_UNIT_STATUSES = frozenset({
|
||||
'candidate_ready', 'review_required', 'failed', 'cancelled',
|
||||
})
|
||||
_LAYOUT_PREREQUISITE_FAILED_CODE = 'SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED'
|
||||
# layout 与 extraction 共 shipping 队列且默认 priority=0;resume 抬高后才能插队,
|
||||
# 否则「单文件版式完成」的 extraction 仍排在剩余 layout FIFO 之后。
|
||||
_ORDER_EXTRACTION_READY_PRIORITY = 10
|
||||
|
||||
|
||||
def revive_layout_prerequisite_failed_units(run: ShippingOrderProcessingRun) -> int:
|
||||
"""
|
||||
版面已就绪时,将 layout 前置失败的 Unit 重置为 pending 以便重抽。
|
||||
|
||||
核心逻辑:仅复活 error_code=LAYOUT_PREREQUISITE_FAILED 且 document 现已 ready 的 Unit;
|
||||
同步清掉 Document 上对应的 failed 投影,避免首屏仍显示解析失败。
|
||||
|
||||
Returns:
|
||||
复活的 Unit 数量。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
ready_ids = order_extraction_ready_document_ids(run)
|
||||
if not ready_ids:
|
||||
return 0
|
||||
plan = ShippingOrderProcessingPlan.query.filter_by(run_id=int(run.id)).first()
|
||||
if plan is None:
|
||||
return 0
|
||||
revived = 0
|
||||
for unit in ShippingOrderProcessingUnit.query.filter_by(plan_id=int(plan.id)).all():
|
||||
if str(unit.status or '') != 'failed':
|
||||
continue
|
||||
if str(unit.error_code or '') != _LAYOUT_PREREQUISITE_FAILED_CODE:
|
||||
continue
|
||||
if int(unit.document_id or 0) not in ready_ids:
|
||||
continue
|
||||
transition_order_extraction_unit(unit, target_status='pending')
|
||||
document = db.session.get(ShippingOrderDocument, int(unit.document_id))
|
||||
if document is not None and str(document.order_extraction_status or '') == 'failed':
|
||||
document.order_extraction_status = 'not_started'
|
||||
document.order_extraction_error_code = None
|
||||
document.order_extraction_error_message = None
|
||||
revived += 1
|
||||
return revived
|
||||
|
||||
|
||||
def _enqueue_ready_order_extraction_job(
|
||||
run: ShippingOrderProcessingRun, *, message: str,
|
||||
) -> int:
|
||||
@@ -1265,9 +1318,10 @@ def order_extraction_has_extractable_ready_work(run: ShippingOrderProcessingRun)
|
||||
"""
|
||||
判断是否存在「版式已就绪、Unit 尚未收口」的可抽取工作。
|
||||
|
||||
核心逻辑:有 ready PDF 且(尚无 Plan / Plan 为空 → 需要建计划抽取;或存在对应
|
||||
Unit 未到 candidate_ready/review_required/failed/cancelled)。
|
||||
核心逻辑:先尝试复活 layout 前置失败 Unit;有 ready PDF 且(尚无 Plan / Plan 为空 →
|
||||
需要建计划抽取;或存在对应 Unit 未到 candidate_ready/review_required/failed/cancelled)。
|
||||
"""
|
||||
revive_layout_prerequisite_failed_units(run)
|
||||
ready_ids = order_extraction_ready_document_ids(run)
|
||||
if not ready_ids:
|
||||
return False
|
||||
@@ -1334,13 +1388,11 @@ def schedule_order_extraction_layouts(
|
||||
"""
|
||||
发送后为本 Run 已选附件创建版面任务,并返回是否需要等待其完成。
|
||||
|
||||
核心逻辑:调用 schedule_document_layouts;用返回值与库查询确认每份 PDF 已有布局版本,
|
||||
避免 ORM 关系未刷新导致误报「未创建版面 Job」。
|
||||
核心逻辑:调用 schedule_document_layouts;配额延后的 PDF 本轮可不排程,返回 True 继续等待;
|
||||
已有 queued/running/ready 的不重复占用配额。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.lifecycle import schedule_document_layouts
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
documents = _run_layout_documents(run)
|
||||
scheduled = schedule_document_layouts(documents, created_by_id=created_by_id)
|
||||
# [STEP] 以本轮排程结果与库内版本为准,禁止依赖可能未 refresh 的 layout_versions 关系。
|
||||
@@ -1374,7 +1426,7 @@ def schedule_order_extraction_layouts(
|
||||
for document in documents
|
||||
if document.current_layout_version_id is not None
|
||||
}
|
||||
# 排程函数不能再静默跳过订单 PDF;否则后续路由只能看到空表格并误判业务失败。
|
||||
# 配额延后的 PDF 本轮可不排程;保留 pending,禁止当成排程失败抬 ValidationError。
|
||||
missing = [
|
||||
document_id for document_id in pdf_document_ids
|
||||
if (
|
||||
@@ -1384,11 +1436,7 @@ def schedule_order_extraction_layouts(
|
||||
)
|
||||
]
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
'Order PDF layout job was not created',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_SCHEDULING_FAILED',
|
||||
details={'document_ids': missing},
|
||||
)
|
||||
return True
|
||||
return order_extraction_layouts_pending(run)
|
||||
|
||||
|
||||
@@ -1460,6 +1508,44 @@ def resume_runs_waiting_for_layout(*, document_id: int) -> int:
|
||||
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_FAILED', commit=False,
|
||||
)
|
||||
resumed += 1
|
||||
continue
|
||||
# 无版面 pending、无可抽/可复活工作:收口卡住的 waiting_layout,避免永久 processing。
|
||||
plan = ShippingOrderProcessingPlan.query.filter_by(run_id=int(run.id)).first()
|
||||
units = (
|
||||
ShippingOrderProcessingUnit.query.filter_by(plan_id=int(plan.id)).all()
|
||||
if plan is not None else []
|
||||
)
|
||||
if not units or any(
|
||||
str(unit.status or '') not in _EXTRACT_DONE_UNIT_STATUSES for unit in units
|
||||
):
|
||||
continue
|
||||
deterministic = sum(1 for unit in units if str(unit.status or '') == 'candidate_ready')
|
||||
failed = sum(1 for unit in units if str(unit.status or '') == 'failed')
|
||||
review = sum(1 for unit in units if str(unit.status or '') == 'review_required')
|
||||
if deterministic == 0 and failed > 0 and review == 0:
|
||||
final_status = 'failed'
|
||||
elif deterministic == 0 and review > 0 and failed == 0:
|
||||
final_status = 'review_required'
|
||||
elif review > 0 or failed > 0 or deterministic < len(units):
|
||||
final_status = 'partially_completed'
|
||||
else:
|
||||
final_status = 'completed'
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='processing', phase=final_status)
|
||||
transition_order_extraction_run(run, target_status=final_status, phase=final_status)
|
||||
record_run_progress(
|
||||
run=run,
|
||||
event_code='run_completed',
|
||||
summary={
|
||||
'document_id': int(document_id),
|
||||
'handoff_status': 'waiting_layout_closed',
|
||||
'deterministic_unit_count': deterministic,
|
||||
'failed_unit_count': failed,
|
||||
'review_required_unit_count': review,
|
||||
},
|
||||
commit=False,
|
||||
)
|
||||
resumed += 1
|
||||
if resumed:
|
||||
db.session.commit()
|
||||
return resumed
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -783,8 +783,8 @@ def test_on_demand_evidence_leaves_coordinates_missing_when_native_and_ocr_fail(
|
||||
assert not restored['coordinate_evidence'].get('page_glyphs')
|
||||
|
||||
|
||||
def test_layout_document_budget_creates_unsupported_audit_versions(app):
|
||||
"""超过单 Intake 配额的支持附件必须有 unsupported 审计,不能静默跳过。"""
|
||||
def test_layout_document_budget_defers_unscheduled_pdfs(app):
|
||||
"""超过单 Intake 配额的 PDF 本轮不排程、不写 unsupported;后续 schedule 可继续排上。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE'] = 1
|
||||
with app.app_context():
|
||||
@@ -805,12 +805,23 @@ def test_layout_document_budget_creates_unsupported_audit_versions(app):
|
||||
versions = schedule_document_layouts([first, text, second])
|
||||
db.session.commit()
|
||||
|
||||
assert len(versions) == 2
|
||||
assert len(versions) == 1
|
||||
assert versions[0].status == 'queued'
|
||||
assert versions[1].status == 'unsupported'
|
||||
assert versions[1].issues_json == ['mineru_intake_document_budget_exceeded']
|
||||
assert versions[0].document_id == first.id
|
||||
assert ShippingDocumentLayoutVersion.query.filter_by(document_id=second.id).count() == 0
|
||||
assert ShippingDocumentLayoutVersion.query.filter_by(document_id=text.id).count() == 0
|
||||
|
||||
# 第一份进入可用终态后,第二次 schedule 应排上此前延后的 PDF。
|
||||
versions[0].status = 'ready'
|
||||
first.current_layout_version_id = versions[0].id
|
||||
db.session.commit()
|
||||
|
||||
second_wave = schedule_document_layouts([first, text, second])
|
||||
db.session.commit()
|
||||
assert len(second_wave) == 1
|
||||
assert second_wave[0].document_id == second.id
|
||||
assert second_wave[0].status == 'queued'
|
||||
|
||||
|
||||
def test_deleting_document_cascades_layout_versions(app):
|
||||
"""Document 删除必须先解除 current 引用,并级联清理其全部布局版本。"""
|
||||
|
||||
@@ -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 = [
|
||||
|
||||
@@ -53,6 +53,7 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
reparse_order_extraction_run,
|
||||
retry_order_extraction_run,
|
||||
resume_runs_waiting_for_layout,
|
||||
revive_layout_prerequisite_failed_units,
|
||||
order_extraction_layout_prerequisite_issues,
|
||||
order_extraction_layouts_failed,
|
||||
materialize_order_extraction_run_inputs,
|
||||
@@ -706,6 +707,66 @@ def test_create_run_waits_for_active_document_layout_before_enqueuing_extraction
|
||||
assert ShippingOrderProcessingRun.query.count() == 1
|
||||
|
||||
|
||||
def test_resume_revives_layout_prerequisite_failed_unit_when_layout_ready(app):
|
||||
"""layout 前置失败的 Unit 在版面变 ready 后必须复活为 pending 并入队续抽。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
user, agent, session, intake, document, run, _ = _seed_run_with_plan(suffix='REVIVE-LAYOUT')
|
||||
unit = run.extraction_plan.units[0]
|
||||
transition_order_extraction_unit(unit, target_status='routing')
|
||||
transition_order_extraction_unit(
|
||||
unit,
|
||||
target_status='failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
error_message='layout prerequisite: layout_missing',
|
||||
)
|
||||
document.order_extraction_status = 'failed'
|
||||
document.order_extraction_error_code = unit.error_code
|
||||
run.status = 'processing'
|
||||
run.phase = 'waiting_layout'
|
||||
layout = ShippingDocumentLayoutVersion.query.filter_by(document_id=document.id).order_by(
|
||||
ShippingDocumentLayoutVersion.version.desc(),
|
||||
).first()
|
||||
if layout is None:
|
||||
layout = ShippingDocumentLayoutVersion(
|
||||
document_id=document.id,
|
||||
version=1,
|
||||
status='ready',
|
||||
source_content_hash=document.content_hash,
|
||||
parser_key='mineru:pipeline:shipping_document_table_snapshot.v1:test',
|
||||
parser_name='mineru',
|
||||
contract_version='shipping_document_table_snapshot.v1',
|
||||
issues_json=[],
|
||||
)
|
||||
db.session.add(layout)
|
||||
db.session.flush()
|
||||
layout.status = 'ready'
|
||||
layout.payload_json = {
|
||||
'status': 'ready',
|
||||
'layout_candidate': {'pages': [{'page_no': 1, 'tables': []}]},
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 100, 'height': 100}},
|
||||
'page_glyphs': {'1': [{'text': 'A'}]},
|
||||
},
|
||||
}
|
||||
layout.issues_json = []
|
||||
document.current_layout_version_id = layout.id
|
||||
db.session.commit()
|
||||
|
||||
revived = revive_layout_prerequisite_failed_units(run)
|
||||
assert revived == 1
|
||||
db.session.refresh(unit)
|
||||
db.session.refresh(document)
|
||||
assert unit.status == 'pending'
|
||||
assert unit.error_code is None
|
||||
assert document.order_extraction_status == 'not_started'
|
||||
|
||||
assert resume_runs_waiting_for_layout(document_id=document.id) == 1
|
||||
db.session.refresh(run)
|
||||
assert run.current_job_id is not None
|
||||
assert run.phase in {'queued', 'waiting_layout'}
|
||||
|
||||
|
||||
def test_create_run_accepts_a_reused_layout_from_an_identical_document(app):
|
||||
"""相同内容复用历史布局时,当前 Document 的版本绑定应视为排程成功。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -246,6 +246,128 @@ def test_worker_processes_ready_unit_then_defers_while_sibling_layout_pending(mo
|
||||
assert finished['result']['waiting_layout'] is True
|
||||
|
||||
|
||||
def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeypatch):
|
||||
"""运行时预算耗尽且仍有 pending Unit 时,必须入队续抽,不得终态 partially_completed。"""
|
||||
import app.jobs.handlers.shipping_order_extraction as handler
|
||||
|
||||
events: list[str] = []
|
||||
finished: dict = {}
|
||||
run = SimpleNamespace(
|
||||
id=5, user_id=9, run_no='SNER-WORKER-BUDGET', status='queued', phase='queued',
|
||||
current_job_id=None, attempt_count=0, cancellation_requested_at=None,
|
||||
input_snapshot_json={
|
||||
'attachment_selection': {'max_runtime_seconds': 1},
|
||||
'intakes': [],
|
||||
},
|
||||
execution_result_json=None, extraction_completed_at=None,
|
||||
)
|
||||
job = SimpleNamespace(id=5, attempts=1, business_ref=run.run_no, max_attempts=3)
|
||||
done_unit = SimpleNamespace(
|
||||
id=51, document_id=201, intake_id=1, status='pending', result_json=None, position=1,
|
||||
cancellation_requested_at=None,
|
||||
)
|
||||
pending_unit = SimpleNamespace(
|
||||
id=52, document_id=202, intake_id=1, status='pending', result_json=None, position=2,
|
||||
cancellation_requested_at=None,
|
||||
)
|
||||
plan = SimpleNamespace(id=5, unit_count=2, units=[done_unit, pending_unit])
|
||||
|
||||
monkeypatch.setattr(handler.db.session, 'get', lambda model, _id: job if model is handler.Job else done_unit)
|
||||
monkeypatch.setattr(
|
||||
handler, 'ShippingOrderProcessingRun',
|
||||
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
with_for_update=lambda: SimpleNamespace(first=lambda: run),
|
||||
))),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'ShippingOrderProcessingUnit', SimpleNamespace(
|
||||
position=SimpleNamespace(asc=lambda: None),
|
||||
status=SimpleNamespace(in_=lambda *_a, **_k: True),
|
||||
query=SimpleNamespace(
|
||||
filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(all=lambda: [done_unit, pending_unit]),
|
||||
),
|
||||
),
|
||||
))
|
||||
monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=SimpleNamespace()))
|
||||
monkeypatch.setattr(handler, 'begin_input_freeze', lambda _run: None)
|
||||
monkeypatch.setattr(handler, 'complete_input_freeze', lambda _run: None)
|
||||
monkeypatch.setattr(
|
||||
handler, 'materialize_order_extraction_run_inputs',
|
||||
lambda _run, *, finalize_plan=True: plan if finalize_plan else None,
|
||||
)
|
||||
monkeypatch.setattr(handler, 'ensure_workflow_items_for_run', lambda *_a, **_k: [])
|
||||
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda *_a, **_k: False)
|
||||
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {})
|
||||
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {201, 202})
|
||||
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: False)
|
||||
monkeypatch.setattr(
|
||||
handler, 'transition_order_extraction_run',
|
||||
lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: events.append('budget_progress'))
|
||||
monkeypatch.setattr(handler, 'record_unit_progress', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: [done_unit, pending_unit])
|
||||
monkeypatch.setattr(handler, '_next_existing_batch', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda *_a, **_k: [])
|
||||
monkeypatch.setattr(handler, '_selection_progress_summary', lambda _run: {})
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_plan.transition_order_extraction_unit',
|
||||
lambda unit, *, target_status, **_k: setattr(unit, 'status', target_status),
|
||||
)
|
||||
|
||||
# 第一轮抽完后假装时间已耗尽,禁止启动第二个 Unit。
|
||||
clock = {'now': 100.0}
|
||||
|
||||
def _perf_counter():
|
||||
return clock['now']
|
||||
|
||||
monkeypatch.setattr(handler.time, 'perf_counter', _perf_counter)
|
||||
|
||||
def _process(*, unit, **_kwargs):
|
||||
events.append(f'processed:{unit.id}')
|
||||
unit.status = 'merging_supplement'
|
||||
clock['now'] = 200.0 # 超过 max_runtime_seconds=1
|
||||
return [{'po_number': 'PO-BUDGET', '_hxops_intake_id': 1}]
|
||||
|
||||
monkeypatch.setattr(handler, '_process_unit_with_retries', _process)
|
||||
monkeypatch.setattr(
|
||||
handler, 'merge_unit_orders',
|
||||
lambda *, orders, schema_definition, keep_primary_documents_separate: orders,
|
||||
)
|
||||
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', lambda **_kwargs: {})
|
||||
monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda **_kwargs: events.append('terminalized') or {})
|
||||
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: events.append('persist_started'))
|
||||
monkeypatch.setattr(
|
||||
handler, '_enqueue_ready_order_extraction_job',
|
||||
lambda _run, *, message: events.append(f'enqueue:{message}') or 999,
|
||||
)
|
||||
|
||||
def fake_finish(*_args, **kwargs):
|
||||
events.append('finished')
|
||||
finished.update(kwargs)
|
||||
|
||||
monkeypatch.setattr(handler, 'finish_job', fake_finish)
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(handler.db.session, 'refresh', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None)
|
||||
monkeypatch.setattr(handler, '_intake_source_types', lambda _ids: {1: 'direct_pdf'})
|
||||
|
||||
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 5})
|
||||
|
||||
assert 'processed:51' in events
|
||||
assert 'processed:52' not in events
|
||||
assert any(item.startswith('enqueue:') for item in events)
|
||||
assert 'terminalized' not in events
|
||||
assert 'persist_started' not in events
|
||||
assert run.status == 'processing'
|
||||
assert run.phase == 'waiting_layout'
|
||||
assert run.current_job_id == 999
|
||||
assert finished['result']['budget_stopped'] is True
|
||||
assert finished['result']['waiting_continue'] is True
|
||||
assert finished['result']['handoff_status'] == 'runtime_budget_continue'
|
||||
assert pending_unit.status == 'pending'
|
||||
|
||||
|
||||
def test_worker_marks_run_failed_when_layout_scheduling_fails(monkeypatch):
|
||||
"""版面 Job 创建失败(如 MinerU 关闭)时必须同步收口 Run,禁止仅失败 Job 而留下 queued。"""
|
||||
import app.jobs.handlers.shipping_order_extraction as handler
|
||||
|
||||
@@ -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'
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
tests/test_shipping_order_profile_matcher_replay.py
|
||||
|
||||
用途:回放本地库历史 unique_match 冻结快照,验证收紧表头身份读取不回归已发布模板。
|
||||
依赖:SQLAlchemy、match_frozen_coordinate_profiles、shipping_order_route_decisions 表。
|
||||
逻辑:只读查询 Run 冻结 input_snapshot_json;无 DB/快照时 skip;失败样本按 profile 汇总。
|
||||
用途:回放本地库已发布模板样本,验证表头身份观测改动不回归任一 published profile。
|
||||
依赖:SQLAlchemy / Flask app、match_frozen_coordinate_profiles、profile samples、route decisions。
|
||||
逻辑:① 历史 unique_match 快照仍命中原 profile;② 每个 published 标注样本在全量候选中自匹配;
|
||||
③ 生产件 curated 文档重匹配。无 DB 时 skip。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,10 +27,11 @@ _REPLAY_DB_URL = os.environ.get(
|
||||
os.environ.get('DATABASE_URL', 'postgresql://postgres:postgres@127.0.0.1:5432/hxops_db'),
|
||||
)
|
||||
_MAX_PER_PROFILE = int(os.environ.get('HXOPS_PROFILE_REPLAY_MAX_PER_PROFILE', '20'))
|
||||
_EXTRA_DOC_IDS = {
|
||||
int(item.strip())
|
||||
for item in os.environ.get('HXOPS_PROFILE_REPLAY_DOC_IDS', '194').split(',')
|
||||
if item.strip().isdigit()
|
||||
# 生产件回归:document_id → 期望 profile_code
|
||||
_CURATED_DOC_EXPECTATIONS = {
|
||||
194: 'ODP-20260824-2C542346805B', # FOX MX / 4210012210
|
||||
199: 'ODP-20260825-BE122F0633B6', # INVENTECH TW / 4518814494_524
|
||||
197: 'ODP-20260825-BE122F0633B6', # INVENTECH TW / 4518814838
|
||||
}
|
||||
|
||||
|
||||
@@ -52,6 +54,27 @@ def replay_engine() -> Engine:
|
||||
return create_engine(_REPLAY_DB_URL)
|
||||
|
||||
|
||||
@pytest.fixture(scope='module')
|
||||
def replay_app(replay_engine: Engine):
|
||||
"""
|
||||
绑定回放库的 Flask app,供标注样本 hydrate / published 快照加载。
|
||||
|
||||
核心逻辑:强制 DATABASE_URL 指向回放库后 create_app;测试结束弹出覆盖值。
|
||||
"""
|
||||
previous = os.environ.get('DATABASE_URL')
|
||||
os.environ['DATABASE_URL'] = _REPLAY_DB_URL
|
||||
from app import create_app
|
||||
|
||||
app = create_app('development')
|
||||
try:
|
||||
yield app
|
||||
finally:
|
||||
if previous is None:
|
||||
os.environ.pop('DATABASE_URL', None)
|
||||
else:
|
||||
os.environ['DATABASE_URL'] = previous
|
||||
|
||||
|
||||
def _document_from_snapshot(
|
||||
snapshot: dict[str, Any],
|
||||
*,
|
||||
@@ -95,12 +118,7 @@ def _frozen_profiles(snapshot: dict[str, Any], *, schema_version_id: int) -> lis
|
||||
|
||||
|
||||
def _load_replay_samples(engine: Engine) -> list[dict[str, Any]]:
|
||||
"""
|
||||
拉取 unique_match 路由样本;每个 profile_code 最多保留最近 N 条。
|
||||
|
||||
Returns:
|
||||
含 route/run/unit/document/profile 期望字段的字典列表。
|
||||
"""
|
||||
"""拉取 unique_match 路由样本;每个 profile_code 最多保留最近 N 条。"""
|
||||
query = text("""
|
||||
SELECT
|
||||
r.id AS route_id,
|
||||
@@ -148,11 +166,9 @@ def _load_replay_samples(engine: Engine) -> list[dict[str, Any]]:
|
||||
rows.append({
|
||||
'route_id': int(row['route_id']),
|
||||
'run_id': int(row['run_id']),
|
||||
'unit_id': int(row['unit_id']),
|
||||
'document_id': int(row['document_id']),
|
||||
'expected_profile_code': code,
|
||||
'expected_profile_version': int(row['selected_profile_version'] or 0),
|
||||
'expected_profile_checksum': str(row['selected_profile_checksum'] or ''),
|
||||
'profiles': profiles,
|
||||
'layout': layout,
|
||||
})
|
||||
@@ -160,57 +176,133 @@ def _load_replay_samples(engine: Engine) -> list[dict[str, Any]]:
|
||||
|
||||
|
||||
def test_replay_published_unique_match_snapshots(replay_engine: Engine) -> None:
|
||||
"""历史 unique_match 样本回放后仍应命中同一 profile(收紧表头带回归门禁)。"""
|
||||
"""历史 unique_match 样本回放后仍应命中同一 profile。"""
|
||||
samples = _load_replay_samples(replay_engine)
|
||||
if not samples:
|
||||
pytest.skip('No replayable unique_match snapshots in database')
|
||||
|
||||
failures: list[str] = []
|
||||
summary: dict[str, dict[str, int]] = defaultdict(lambda: {'pass': 0, 'fail': 0})
|
||||
|
||||
for sample in samples:
|
||||
code = sample['expected_profile_code']
|
||||
result = match_frozen_coordinate_profiles(
|
||||
profiles=sample['profiles'],
|
||||
layout=sample['layout'],
|
||||
profiles=sample['profiles'], layout=sample['layout'],
|
||||
)
|
||||
ok = (
|
||||
result.status == 'unique_match'
|
||||
and result.profile_code == sample['expected_profile_code']
|
||||
and result.profile_code == code
|
||||
and (
|
||||
not sample['expected_profile_version']
|
||||
or int(result.version or 0) == int(sample['expected_profile_version'])
|
||||
)
|
||||
)
|
||||
if ok:
|
||||
summary[code]['pass'] += 1
|
||||
else:
|
||||
summary[code]['fail'] += 1
|
||||
summary[code]['pass' if ok else 'fail'] += 1
|
||||
if not ok:
|
||||
failures.append(
|
||||
f"{code} route={sample['route_id']} run={sample['run_id']} "
|
||||
f"doc={sample['document_id']}: expected {sample['expected_profile_code']}"
|
||||
f"/v{sample['expected_profile_version']}, got {result.status}"
|
||||
f"/{result.profile_code}/v{result.version}"
|
||||
f"{code} route={sample['route_id']} doc={sample['document_id']}: "
|
||||
f"got {result.status}/{result.profile_code}"
|
||||
)
|
||||
|
||||
if failures:
|
||||
lines = [
|
||||
'Published unique_match replay failures:',
|
||||
*[f' - {item}' for item in failures[:50]],
|
||||
'Per-profile summary:',
|
||||
]
|
||||
lines = ['unique_match replay failures:', *[f' - {item}' for item in failures[:50]]]
|
||||
for profile_code, counts in sorted(summary.items()):
|
||||
lines.append(f' {profile_code}: pass={counts["pass"]} fail={counts["fail"]}')
|
||||
pytest.fail('\n'.join(lines))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('document_id', sorted(_EXTRA_DOC_IDS))
|
||||
def test_replay_specific_document_rematch_after_header_band(replay_engine: Engine, document_id: int) -> None:
|
||||
def test_replay_all_published_annotation_samples_unique_match(replay_app) -> None:
|
||||
"""
|
||||
对指定 document(默认 194 / 4210012210)用最新 Run 冻结快照重匹配。
|
||||
每个已发布模板的标注样本,在同 Schema 全量 published 候选中须 unique_match 自身。
|
||||
|
||||
历史路由可能失败;本断言验证收紧表头带后应 FOX MX unique_match。
|
||||
覆盖无历史 unique_match 路由的模板(FOX TW / QUANTA / Inventec / WIWYNN CZ 等)。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfileSample
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.order_document_profile_service import (
|
||||
published_snapshots_for_schema,
|
||||
)
|
||||
from app.services.shipping_notice.order_document_profile_validation_service import (
|
||||
_load_sample_layout,
|
||||
)
|
||||
|
||||
with replay_app.app_context():
|
||||
published = (
|
||||
ShippingOrderDocumentProfile.query
|
||||
.filter_by(status='published')
|
||||
.order_by(ShippingOrderDocumentProfile.profile_code.asc())
|
||||
.all()
|
||||
)
|
||||
if not published:
|
||||
pytest.skip('No published profiles in replay database')
|
||||
|
||||
failures: list[str] = []
|
||||
missing: list[str] = []
|
||||
for profile in published:
|
||||
sample = (
|
||||
ShippingOrderDocumentProfileSample.query
|
||||
.filter_by(profile_id=int(profile.id), sample_role='annotation')
|
||||
.order_by(ShippingOrderDocumentProfileSample.id.asc())
|
||||
.first()
|
||||
)
|
||||
if sample is None:
|
||||
missing.append(f'{profile.display_name} ({profile.profile_code}): no annotation sample')
|
||||
continue
|
||||
try:
|
||||
layout = _load_sample_layout(sample)
|
||||
except ValidationError as exc:
|
||||
missing.append(
|
||||
f'{profile.display_name} ({profile.profile_code}): layout unavailable ({exc.code})'
|
||||
)
|
||||
continue
|
||||
if not _layout_ready(layout):
|
||||
from app.models import ShippingOrderDocument
|
||||
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import (
|
||||
ensure_on_demand_coordinate_evidence,
|
||||
)
|
||||
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
|
||||
if document is not None:
|
||||
layout = ensure_on_demand_coordinate_evidence(
|
||||
document=document, layout=dict(layout), page_nos=None,
|
||||
)
|
||||
if not _layout_ready(layout):
|
||||
missing.append(
|
||||
f'{profile.display_name} ({profile.profile_code}): layout evidence incomplete'
|
||||
)
|
||||
continue
|
||||
|
||||
candidates = published_snapshots_for_schema(int(profile.schema_version_id))
|
||||
if not candidates:
|
||||
missing.append(
|
||||
f'{profile.display_name} ({profile.profile_code}): no published snapshots'
|
||||
)
|
||||
continue
|
||||
result = match_frozen_coordinate_profiles(profiles=candidates, layout=layout)
|
||||
if not (
|
||||
result.status == 'unique_match'
|
||||
and result.profile_code == profile.profile_code
|
||||
and int(result.version or 0) == int(profile.version)
|
||||
):
|
||||
failures.append(
|
||||
f'{profile.display_name} ({profile.profile_code}): '
|
||||
f'got {result.status}/{result.profile_code}/v{result.version}'
|
||||
)
|
||||
|
||||
if missing or failures:
|
||||
lines = []
|
||||
if missing:
|
||||
lines.append('Missing fixtures / evidence:')
|
||||
lines.extend(f' - {item}' for item in missing)
|
||||
if failures:
|
||||
lines.append('Annotation self-match failures:')
|
||||
lines.extend(f' - {item}' for item in failures)
|
||||
pytest.fail('\n'.join(lines))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('document_id,expected_profile_code', sorted(_CURATED_DOC_EXPECTATIONS.items()))
|
||||
def test_replay_curated_production_documents(
|
||||
replay_engine: Engine, document_id: int, expected_profile_code: str,
|
||||
) -> None:
|
||||
"""生产回归件(FOX MX / INVENTECH TW 等)用最新 Run 快照重匹配须 unique_match。"""
|
||||
query = text("""
|
||||
SELECT
|
||||
run.id AS run_id,
|
||||
@@ -245,7 +337,4 @@ def test_replay_specific_document_rematch_after_header_band(replay_engine: Engin
|
||||
profiles = _frozen_profiles(snapshot, schema_version_id=int(row['schema_version_id'] or 0))
|
||||
result = match_frozen_coordinate_profiles(profiles=profiles, layout=layout)
|
||||
assert result.status == 'unique_match'
|
||||
if document_id == 194:
|
||||
assert result.profile_code == 'ODP-20260824-2C542346805B'
|
||||
else:
|
||||
assert result.profile_code
|
||||
assert result.profile_code == expected_profile_code
|
||||
@@ -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