Merge branch 'dev' into snow

# Conflicts:
#	frontend/package-lock.json
This commit is contained in:
HTEWJ\26070045 committed 2026-09-14 09:23:19 +08:00
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(
+4 -2
View File
@@ -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(