feat(shipping-notice): 收敛复核状态隔离、STP 重试幂等与 XFA 合成预览标注

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-07 02:58:28 +08:00
1 parent 84a881b554
commit 74270adc22
149 files changed
+20111 -3871

No files matched your search

@@ -2,9 +2,9 @@
backend/app/services/shipping_notice/document_layout/lifecycle.py
用途:管理 ShippingOrderDocument 的版面版本、checksum、大小门禁和当前成功快照。
依赖:ShippingDocumentLayoutVersion、ShippingXfaStructureAnalysis、Flask 配置、SQLAlchemy Session、workflow_ledger_service
(claim/complete/recovery 尽力同步 WorkflowItem,缺 Item 不阻断版面收口)。
逻辑:相同内容/parser/checksum 幂等复用;XFA 复用时同步本地化结构分析身份;
依赖:ShippingDocumentLayoutVersion、ShippingXfaStructureAnalysis、Flask 配置、SQLAlchemy Session、
workflow_ledger_service、audit_service(XFA Analysis 复用/拒绝/重排队双写审计)。
逻辑:相同内容/parser/checksum 幂等复用;XFA 复用时同步本地化结构分析身份并写审计;
失败版本保留审计,只有可用终态更新 Document 当前引用。
"""
@@ -294,9 +294,93 @@ def record_inline_layout_snapshot(
return version
def _audit_xfa_analysis_reuse_event(
*,
event_type: str,
document: ShippingOrderDocument,
result: str = 'success',
source_document_id: int | None = None,
source_layout_version_id: int | None = None,
source_analysis_id: int | None = None,
target_layout_version_id: int | None = None,
target_analysis_id: int | None = None,
content_hash: str | None = None,
template_packet_checksum: str | None = None,
datasets_packet_checksum: str | None = None,
dataset_structure_fingerprint: str | None = None,
reject_reason: str | None = None,
job_id: int | None = None,
actor_user_id: int | None = None,
request_id: str | None = None,
operation_id: str | None = None,
before: dict[str, Any] | None = None,
after: dict[str, Any] | None = None,
) -> None:
"""
双写 XFA StructureAnalysis 复用/拒绝/重排队审计(Document 可见流 + 平台账本)。
核心逻辑:actor 固定为 system/worker,并附带触发用户与 Job/request/operation(存在时)。
Args:
event_type: xfa_structure_analysis_reused / reuse_rejected / reparse_queued。
document: 目标 Document。
result: success / failure / degraded。
其余字段:来源/目标身份与 checksum 快照。
"""
try:
from flask import g, has_request_context
from app.services.shipping_notice.audit_service import append_shipping_audit_event
if actor_user_id is None and has_request_context():
actor_user_id = getattr(g, 'current_user_id', None) or getattr(g, 'user_id', None)
if request_id is None and has_request_context():
request_id = getattr(g, 'request_id', None)
payload = {
'source_document_id': source_document_id,
'source_layout_version_id': source_layout_version_id,
'source_analysis_id': source_analysis_id,
'target_document_id': int(document.id),
'target_layout_version_id': target_layout_version_id,
'target_analysis_id': target_analysis_id,
'content_hash': content_hash or str(document.content_hash or '') or None,
'template_packet_checksum': template_packet_checksum,
'datasets_packet_checksum': datasets_packet_checksum,
'dataset_structure_fingerprint': dataset_structure_fingerprint,
'reject_reason': reject_reason,
'job_id': job_id,
'trigger_user_id': int(actor_user_id) if actor_user_id is not None else None,
'request_id': str(request_id) if request_id else None,
'operation_id': str(operation_id) if operation_id else None,
'before': before or {},
'after': after or {},
}
append_shipping_audit_event(
event_type=event_type,
aggregate_type='shipping_order_document',
aggregate_id=str(int(document.id)),
document_id=int(document.id),
actor_type='system',
actor_id=None,
result=result,
action=event_type,
sensitivity_level='internal',
before=before,
after=after or payload,
metadata={
**{k: v for k, v in payload.items() if k not in {'before', 'after'}},
'executor': 'system/worker',
},
)
except Exception: # noqa: BLE001 — 审计失败不得阻断布局复用主路径
_LOGGER.exception('Failed to write XFA analysis reuse audit event=%s', event_type)
def _clone_reusable_layout_for_document(
document: ShippingOrderDocument,
reusable: ShippingDocumentLayoutVersion,
*,
created_by_id: int | None = None,
) -> ShippingDocumentLayoutVersion | None:
"""
将同一所有者的已完成布局快照本地化到目标 Document。
@@ -304,11 +388,12 @@ def _clone_reusable_layout_for_document(
LayoutVersion 的 document_id 是不可跨文档共享的外键语义;相同内容只能复用
已冻结 payload,不能让目标 Document 指向源 Document 的版本记录。XFA 快照还必须
为目标 Document 克隆独立 StructureAnalysis,并重写快照 analysis_id;源证据缺失或
身份不一致时返回 None,让调用方重新排队解析。
身份不一致时写 reuse_rejected 审计并返回 None,让调用方重新排队解析。
Args:
document: 待接收复用结果的目标 Document。
reusable: 同一所有者、同内容且 parser 身份一致的源 LayoutVersion。
created_by_id: 触发用户(若有)。
Returns:
目标 Document 专属 LayoutVersion;无法安全本地化时返回 None。
@@ -324,6 +409,8 @@ def _clone_reusable_layout_for_document(
copied_payload.setdefault('snapshot_version', reusable.contract_version or LAYOUT_CONTRACT_VERSION)
target_analysis: ShippingXfaStructureAnalysis | None = None
source_analysis: ShippingXfaStructureAnalysis | None = None
reject_reason: str | None = None
if str(copied_payload.get('provider') or '') == 'xfa':
capability = (
copied_payload.get('xfa_capability')
@@ -336,20 +423,44 @@ def _clone_reusable_layout_for_document(
if source_analysis_id not in (None, '')
else None
)
if (
source_analysis is None
or int(source_analysis.document_id) != int(reusable.document_id)
or str(source_analysis.analysis_status or '') != 'ready'
or str(source_analysis.source_content_hash or '').lower()
!= str(document.content_hash or '').lower()
or str(source_analysis.template_packet_checksum or '')
!= str(capability.get('template_packet_checksum') or '')
or str(source_analysis.dataset_structure_fingerprint or '')
!= str(capability.get('dataset_structure_fingerprint') or '')
if source_analysis is None:
reject_reason = 'source_analysis_missing'
elif int(source_analysis.document_id) != int(reusable.document_id):
reject_reason = 'source_analysis_document_mismatch'
elif str(source_analysis.analysis_status or '') != 'ready':
reject_reason = 'source_analysis_not_ready'
elif str(source_analysis.source_content_hash or '').lower() != str(document.content_hash or '').lower():
reject_reason = 'content_hash_mismatch'
elif str(source_analysis.template_packet_checksum or '') != str(capability.get('template_packet_checksum') or ''):
reject_reason = 'template_checksum_mismatch'
elif str(source_analysis.dataset_structure_fingerprint or '') != str(
capability.get('dataset_structure_fingerprint') or '',
):
reject_reason = 'structure_fingerprint_mismatch'
if reject_reason is not None:
_audit_xfa_analysis_reuse_event(
event_type='xfa_structure_analysis_reuse_rejected',
document=document,
result='failure',
source_document_id=int(reusable.document_id),
source_layout_version_id=int(reusable.id),
source_analysis_id=int(source_analysis_id) if source_analysis_id not in (None, '') else None,
content_hash=str(document.content_hash or '') or None,
template_packet_checksum=str(capability.get('template_packet_checksum') or '') or None,
dataset_structure_fingerprint=str(capability.get('dataset_structure_fingerprint') or '') or None,
reject_reason=reject_reason,
actor_user_id=created_by_id,
before={
'source_layout_version_id': int(reusable.id),
'source_analysis_id': source_analysis_id,
},
after={},
)
return None
# [STEP 1] Analysis 是 document-scoped 证据;克隆安全摘要并先取得目标主键。
assert source_analysis is not None
target_analysis = ShippingXfaStructureAnalysis(
document_id=int(document.id),
layout_version_id=None,
@@ -386,8 +497,44 @@ def _clone_reusable_layout_for_document(
if target_analysis is not None:
if str(localized.status or '') not in CURRENT_LAYOUT_STATUSES:
db.session.delete(target_analysis)
_audit_xfa_analysis_reuse_event(
event_type='xfa_structure_analysis_reuse_rejected',
document=document,
result='failure',
source_document_id=int(reusable.document_id),
source_layout_version_id=int(reusable.id),
source_analysis_id=int(source_analysis.id) if source_analysis is not None else None,
target_layout_version_id=int(localized.id),
reject_reason='localized_layout_not_ready',
actor_user_id=created_by_id,
)
return None
target_analysis.layout_version_id = int(localized.id)
_audit_xfa_analysis_reuse_event(
event_type='xfa_structure_analysis_reused',
document=document,
result='success',
source_document_id=int(reusable.document_id),
source_layout_version_id=int(reusable.id),
source_analysis_id=int(source_analysis.id) if source_analysis is not None else None,
target_layout_version_id=int(localized.id),
target_analysis_id=int(target_analysis.id),
content_hash=str(document.content_hash or '') or None,
template_packet_checksum=str(target_analysis.template_packet_checksum or '') or None,
datasets_packet_checksum=str(target_analysis.datasets_packet_checksum or '') or None,
dataset_structure_fingerprint=str(target_analysis.dataset_structure_fingerprint or '') or None,
actor_user_id=created_by_id,
before={
'source_document_id': int(reusable.document_id),
'source_layout_version_id': int(reusable.id),
'source_analysis_id': int(source_analysis.id) if source_analysis is not None else None,
},
after={
'target_document_id': int(document.id),
'target_layout_version_id': int(localized.id),
'target_analysis_id': int(target_analysis.id),
},
)
return localized
@@ -435,9 +582,19 @@ def schedule_layout_version(
None,
)
if reusable_from_owner is not None:
localized = _clone_reusable_layout_for_document(document, reusable_from_owner)
localized = _clone_reusable_layout_for_document(
document,
reusable_from_owner,
created_by_id=created_by_id,
)
if localized is not None:
return localized
# 复用被拒绝后继续排队重新解析;下方 enqueue 后写 reparse_queued
reuse_rejected_source = reusable_from_owner
else:
reuse_rejected_source = None
else:
reuse_rejected_source = None
active = ShippingDocumentLayoutVersion.query.filter(
ShippingDocumentLayoutVersion.document_id == int(document.id),
ShippingDocumentLayoutVersion.status.in_({'queued', 'running'}),
@@ -479,6 +636,35 @@ def schedule_layout_version(
commit=False,
)
version.job_id = job_id
# [STEP] 仅在跨文档复用失败后重新 enqueue 时写 reparse_queued(force 重解析不记该事件)
if reuse_rejected_source is not None:
source_cap = (
reuse_rejected_source.payload_json.get('xfa_capability')
if isinstance(reuse_rejected_source.payload_json, dict)
and isinstance(reuse_rejected_source.payload_json.get('xfa_capability'), dict)
else {}
)
_audit_xfa_analysis_reuse_event(
event_type='xfa_structure_analysis_reparse_queued',
document=document,
result='degraded',
source_document_id=int(reuse_rejected_source.document_id),
source_layout_version_id=int(reuse_rejected_source.id),
source_analysis_id=(
int(source_cap['structure_analysis_id'])
if source_cap.get('structure_analysis_id') not in (None, '')
else None
),
target_layout_version_id=int(version.id),
content_hash=source_hash,
job_id=int(job_id) if job_id is not None else None,
actor_user_id=created_by_id,
after={
'queued_layout_version_id': int(version.id),
'job_id': int(job_id) if job_id is not None else None,
'force': bool(force),
},
)
return version
@@ -1,11 +1,13 @@
"""
backend/app/services/shipping_notice/document_layout/xfa_analysis.py
用途:编排 XFA packet 读取、datasets 解析、签名计算与布局快照/持久化。
依赖:xfa_packets、xfa_dataset、xfa_signature、xfa_acroform、xfa_contract、
ShippingXfaStructureAnalysis 模型。
逻辑:由 runtime 与 shipping_document_layout Job 调用;成功时写入结构分析记录并返回
不含 XML/PDF 正文的 capability 快照。
用途:编排 XFA packet 读取、datasets 解析、签名计算与布局快照/持久化;
并提供 Layout 冻结的 StructureAnalysis 精确解析(禁止回退 document 最新)。
依赖:ValidationError、ShippingDocumentLayoutVersion、ShippingOrderDocument、
ShippingXfaStructureAnalysis、xfa_packets、xfa_dataset、xfa_signature、
xfa_acroform、xfa_contract。
逻辑:由 runtime / shipping_document_layout Job 写入分析;Profile 读路径经
resolve_frozen_xfa_structure_analysis 按 Layout.structure_analysis_id 精确读取。
"""
from __future__ import annotations
@@ -14,8 +16,9 @@ from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
from app.core.errors import ValidationError
from app.extensions import db
from app.models import ShippingXfaStructureAnalysis
from app.models import ShippingDocumentLayoutVersion, ShippingOrderDocument, ShippingXfaStructureAnalysis
from app.services.shipping_notice.document_layout.xfa_acroform import (
build_reconciliation_candidates,
read_acroform_fields,
@@ -396,7 +399,7 @@ def project_field_tree(analysis: ShippingXfaStructureAnalysis, *, include_values
def get_latest_analysis_for_document(document_id: int) -> ShippingXfaStructureAnalysis | None:
"""
读取文档最近一次成功的 XFA 结构分析。
读取文档最近一次结构分析(兼容诊断;正式路径请用 resolve_frozen_xfa_structure_analysis)。
Args:
document_id: ShippingOrderDocument 主键。
@@ -411,6 +414,172 @@ def get_latest_analysis_for_document(document_id: int) -> ShippingXfaStructureAn
)
def resolve_layout_version_for_xfa(
document: ShippingOrderDocument,
*,
layout_version: ShippingDocumentLayoutVersion | None = None,
layout_version_id: int | None = None,
) -> ShippingDocumentLayoutVersion:
"""
解析文档应绑定的 LayoutVersion(旧 Revision 传入显式版本,禁止回退“最新”)。
核心逻辑:显式 layout_version / layout_version_id 优先;否则使用 Document.current。
Args:
document: 样本文档。
layout_version: 已加载的 LayoutVersion。
layout_version_id: LayoutVersion 主键。
Returns:
LayoutVersion 实体。
Raises:
ValidationError: Layout 缺失或不属于该 Document。
"""
version = layout_version
if version is None and layout_version_id is not None:
version = db.session.get(ShippingDocumentLayoutVersion, int(layout_version_id))
if version is None:
version = getattr(document, 'current_layout_version', None)
if version is None:
raise ValidationError(
'XFA layout version is missing for structure analysis binding',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_MISSING',
details={'document_id': int(document.id), 'reason': 'layout_missing'},
)
if int(version.document_id) != int(document.id):
raise ValidationError(
'XFA layout version does not belong to the sample document',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_IDENTITY_MISMATCH',
details={
'document_id': int(document.id),
'layout_version_id': int(version.id),
'layout_document_id': int(version.document_id),
},
)
return version
def resolve_frozen_xfa_structure_analysis(
document: ShippingOrderDocument,
*,
layout_version: ShippingDocumentLayoutVersion | None = None,
layout_version_id: int | None = None,
require_ready: bool = True,
) -> tuple[ShippingDocumentLayoutVersion, ShippingXfaStructureAnalysis, dict[str, Any]]:
"""
按 Layout 冻结的 structure_analysis_id 精确读取 Analysis(禁止 document 最新回退)。
核心逻辑:Layout → xfa_capability.structure_analysis_id → 主键读取 →
校验 document_id / layout_version_id / content_hash;缺失、身份不一致、陈旧分码 fail-closed。
Args:
document: 样本文档。
layout_version: 可选已解析 LayoutVersion(旧 Revision / 非 current 必传)。
layout_version_id: 可选 LayoutVersion 主键。
require_ready: True 时要求 analysis_status=ready。
Returns:
(layout_version, analysis, capability_dict)。
Raises:
ValidationError: XFA_ANALYSIS_MISSING / IDENTITY_MISMATCH / STALE。
"""
version = resolve_layout_version_for_xfa(
document,
layout_version=layout_version,
layout_version_id=layout_version_id,
)
payload = version.payload_json if isinstance(version.payload_json, dict) else {}
capability = payload.get('xfa_capability') if isinstance(payload.get('xfa_capability'), dict) else {}
if not capability and isinstance(payload.get('capability'), dict):
capability = payload.get('capability') or {}
raw_id = capability.get('structure_analysis_id')
if raw_id in (None, ''):
raise ValidationError(
'Frozen XFA structure_analysis_id is missing on layout snapshot',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_MISSING',
details={
'document_id': int(document.id),
'layout_version_id': int(version.id),
'reason': 'structure_analysis_id_missing',
},
)
try:
analysis_id = int(raw_id)
except (TypeError, ValueError) as exc:
raise ValidationError(
'Frozen XFA structure_analysis_id is invalid',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_MISSING',
details={
'document_id': int(document.id),
'layout_version_id': int(version.id),
'structure_analysis_id': raw_id,
},
) from exc
analysis = db.session.get(ShippingXfaStructureAnalysis, analysis_id)
if analysis is None:
raise ValidationError(
'Frozen XFA structure analysis record is missing',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_MISSING',
details={
'document_id': int(document.id),
'layout_version_id': int(version.id),
'structure_analysis_id': analysis_id,
},
)
if int(analysis.document_id) != int(document.id):
raise ValidationError(
'XFA structure analysis document identity mismatch',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_IDENTITY_MISMATCH',
details={
'document_id': int(document.id),
'analysis_document_id': int(analysis.document_id),
'structure_analysis_id': analysis_id,
'layout_version_id': int(version.id),
},
)
analysis_layout_id = getattr(analysis, 'layout_version_id', None)
if analysis_layout_id not in (None, '') and int(analysis_layout_id) != int(version.id):
raise ValidationError(
'XFA structure analysis layout identity mismatch',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_IDENTITY_MISMATCH',
details={
'document_id': int(document.id),
'layout_version_id': int(version.id),
'analysis_layout_version_id': int(analysis_layout_id),
'structure_analysis_id': analysis_id,
},
)
doc_hash = str(document.content_hash or '').strip().lower()
analysis_hash = str(analysis.source_content_hash or '').strip().lower()
if doc_hash and analysis_hash and doc_hash != analysis_hash:
raise ValidationError(
'XFA structure analysis content hash is stale relative to the document',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_STALE',
details={
'document_id': int(document.id),
'layout_version_id': int(version.id),
'structure_analysis_id': analysis_id,
'document_content_hash': doc_hash,
'analysis_content_hash': analysis_hash,
},
)
if require_ready and str(analysis.analysis_status or '') != 'ready':
raise ValidationError(
'XFA structure analysis is not ready',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_MISSING',
details={
'document_id': int(document.id),
'layout_version_id': int(version.id),
'structure_analysis_id': analysis_id,
'analysis_status': analysis.analysis_status,
},
)
return version, analysis, dict(capability)
def rebuild_tree_dto_from_analysis(
analysis: ShippingXfaStructureAnalysis,
pdf_bytes: bytes,
@@ -3,9 +3,9 @@ services/shipping_notice/document_layout/xfa_contract.py
用途:冻结 XFA 数据路径 Profile 契约——template_mode、受控路径语法、结构指纹、
统一字段 binding(value_binding + visual_binding)、鉴别联合 definition、
evidence 与安全投影。
evidence 与安全投影、合成预览审计事件与错误码注册。
依赖:Pydantic 2、标准库 hashlib/json/re/unicodedata;被 order_extraction_route_contract、
Profile 校验、拆分契约与后续 xfa_*.py 解析器引用。
Profile 校验、拆分契约、xfa_preview_* 与后续 xfa_*.py 解析器引用。
逻辑:本模块只定义契约与纯函数校验,不读 PDF/XML、不执行脚本、不接正式流量;
禁止混入 coordinate 表区键,但允许 visual_binding 归一化框作为视觉证据。
header_mappings / line_mapping.fields 仅作**迁移输入**解析(order_profile_unified_migration);
@@ -144,6 +144,12 @@ XFA_ERROR_CODES: Final[frozenset[str]] = frozenset({
'XFA_SPLIT_RULE_INVALID',
'XFA_SPLIT_FIELD_CONFLICT',
'XFA_SPLIT_MIRROR_MISMATCH',
# 合成预览(阶段 1 POC)
'XFA_PREVIEW_STALE',
'XFA_PREVIEW_FAILED',
'XFA_PREVIEW_UNAVAILABLE',
'XFA_PREVIEW_PAGE_INCONSISTENT',
'XFA_PREVIEW_VALUE_MISMATCH',
})
XFA_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({
@@ -178,6 +184,14 @@ XFA_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({
'xfa_profile_checksum_mismatch',
'xfa_visual_not_publishable',
'xfa_split_rule_unconfirmed',
# 合成预览发布门禁(阶段 5)
'xfa_synthetic_preview_not_ready',
'xfa_preview_render_checksum_missing',
'xfa_preview_pages_incomplete',
'xfa_preview_page_box_invalid',
'xfa_ocr_unresolved_mismatch',
'xfa_preview_checksum_drift',
'xfa_preview_renderer_version_mismatch',
})
XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
@@ -189,6 +203,9 @@ XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
'xfa_document_kind_detected',
'xfa_packet_parsed',
'xfa_structure_analysis_ready',
'xfa_structure_analysis_reused',
'xfa_structure_analysis_reuse_rejected',
'xfa_structure_analysis_reparse_queued',
'xfa_field_tree_accessed',
'xfa_collections_accessed',
'xfa_sensitive_sample_value_read',
@@ -228,6 +245,16 @@ XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
# 统一 binding 一次性迁移(阶段 7)
'order_profile_unified_migration_dry_run',
'order_profile_unified_migration_executed',
# 合成预览(阶段 1 POC)
'xfa_preview_requested',
'xfa_preview_generated',
'xfa_preview_failed',
'xfa_preview_viewed',
'xfa_preview_stale',
# OCR 自动标记建议(阶段 3)
'xfa_ocr_started',
'xfa_ocr_completed',
'xfa_ocr_failed',
})
# Profile / Run / 分析 DTO 禁止键(大小写不敏感);完整 XML / PDF bytes / 存储地址不得外泄。
@@ -400,6 +427,16 @@ XfaVisualBindingSource = Literal[
]
XfaVisualBindingStatus = Literal['suggested', 'confirmed', 'rejected', 'unavailable']
XfaBindingScope = Literal['header', 'line']
# 画布工具 → 统一 region_kind;xfa_visual 为历史兼容别名(等价 field)
XfaVisualRegionKind = Literal['anchor', 'header', 'line', 'exclude', 'field', 'xfa_visual']
XFA_VISUAL_REGION_KINDS: Final[frozenset[str]] = frozenset({
'anchor',
'header',
'line',
'exclude',
'field',
'xfa_visual',
})
class XfaNormalizedBBox(XfaContractModel):
@@ -448,13 +485,24 @@ class XfaValueBinding(XfaContractModel):
class XfaVisualBinding(XfaContractModel):
"""视觉绑定:页码 + 归一化框 + 确认状态;正式字段发布前须 confirmed。"""
"""视觉绑定:页码 + 归一化框 + 确认状态;正式字段发布前须 confirmed。
合成预览确认证据(阶段 4+):confirmed 时须携带 preview_render_checksum /
render_mode=xfa_dataset_preview / confirmed_on=xfa_dataset_preview。
"""
page_no: int = Field(ge=1, le=500)
normalized_bbox: XfaNormalizedBBox
source: XfaVisualBindingSource
status: XfaVisualBindingStatus
confidence: float = Field(default=1.0, ge=0.0, le=1.0)
# 画布区域语义:anchor|header|line|exclude|field(xfa_visual 历史兼容)
region_kind: XfaVisualRegionKind | None = None
# 合成预览确认证据(可选;confirm 门禁写入,publish 门禁读取)
preview_render_checksum: str | None = None
render_mode: str | None = None
confirmed_on: str | None = None
renderer_version: str | None = None
class XfaSplitRuleRef(XfaContractModel):
@@ -482,21 +530,37 @@ class XfaUnifiedFieldBinding(XfaContractModel):
@model_validator(mode='after')
def validate_xfa_scope_value_type(self) -> 'XfaUnifiedFieldBinding':
"""XFA Profile 内正式绑定必须是 xfa_dataset(由上层 Profile 再强制)。"""
"""同模板允许字段级混合数据源;具体约束由 value_binding / 发布门禁执行。"""
return self
def is_formal_binding_publishable(binding: XfaUnifiedFieldBinding) -> bool:
"""
判断统一绑定是否满足发布门禁的视觉确认要求。
判断统一绑定是否满足发布门禁(字段级混合数据源口径)。
核心逻辑:
- xfa_dataset:正式 path 已配置即可发布(视觉框可选);
- pdf_coordinate / ocr_coordinate:必须视觉 confirmed;
- 旧合成预览确认(confirmed_on/render_mode=xfa_dataset_preview)视为未重确认。
Args:
binding: 统一字段绑定。
Returns:
视觉状态为 confirmed 时为 True。
满足对应类型发布条件时为 True。
"""
return binding.visual_binding.status == 'confirmed'
value_type = binding.value_binding.type
visual = binding.visual_binding
confirmed_on = str(visual.confirmed_on or '').strip()
render_mode = str(visual.render_mode or '').strip()
# 旧 flatten/synthetic 坐标系确认框须在原生 PDF 画布重确认。
if visual.status == 'confirmed' and (
confirmed_on == 'xfa_dataset_preview' or render_mode == 'xfa_dataset_preview'
):
return False
if value_type == 'xfa_dataset':
return bool(binding.value_binding.path_id and binding.value_binding.data_path)
return visual.status == 'confirmed'
def canonical_unified_bindings_payload(
@@ -538,6 +602,10 @@ class OrderXfaDatasetProfile(XfaContractModel):
bindings: list[XfaUnifiedFieldBinding] = Field(default_factory=list)
cross_checks: XfaCrossChecks = Field(default_factory=XfaCrossChecks)
split_rules: list[dict[str, Any]] = Field(default_factory=list)
# 合成预览摘要(可选;发布门禁优先读取 status / preview_render_checksum)
xfa_preview: dict[str, Any] | None = None
# OCR 自动标记摘要(可选;未解决 mismatch 计数供发布门禁读取)
xfa_ocr_automark: dict[str, Any] | None = None
@model_validator(mode='before')
@classmethod
@@ -587,8 +655,12 @@ class OrderXfaDatasetProfile(XfaContractModel):
binding_ids: list[str] = []
binding_field_keys: list[tuple[str, str]] = []
for binding in self.bindings:
if binding.value_binding.type != 'xfa_dataset':
raise ValueError('OrderXfaDatasetProfile bindings must use value_binding.type=xfa_dataset')
# 硬冻结(2026-08-07):同模板允许 xfa_dataset / pdf_coordinate / ocr_coordinate 混用。
if binding.value_binding.type not in {'xfa_dataset', 'pdf_coordinate', 'ocr_coordinate'}:
raise ValueError(
'OrderXfaDatasetProfile bindings must use value_binding.type in '
'xfa_dataset|pdf_coordinate|ocr_coordinate',
)
binding_ids.append(binding.binding_id)
binding_field_keys.append((binding.scope, binding.field_id))
field_ids.append(binding.field_id)
@@ -0,0 +1,133 @@
"""
services/shipping_notice/document_layout/xfa_preview_cache.py
用途:XFA 合成预览进程内缓存(Phase 1 POC);按身份指纹键存取预览结果。
依赖:threading、xfa_preview_contract.build_preview_identity_fingerprint。
逻辑:由预览编排层调用;可选后续替换为 Redis;本模块不做 IO/渲染。
"""
from __future__ import annotations
import threading
import time
from typing import Any
from app.services.shipping_notice.document_layout.xfa_preview_contract import (
PreviewIdentityContext,
build_preview_identity_fingerprint,
)
_LOCK = threading.RLock()
_CACHE: dict[str, tuple[float, dict[str, Any]]] = {}
_DEFAULT_TTL_SECONDS = 30 * 60
def build_preview_cache_key(
*,
structure_analysis_id: int | str | None,
template_packet_checksum: str,
datasets_packet_checksum: str,
dataset_structure_fingerprint: str,
source_content_hash: str,
renderer_version: str,
) -> str:
"""
构造预览缓存键(analysis_id + checksums + renderer_version)。
核心逻辑:委托 PreviewIdentityContext 指纹,page_count/preview_render_checksum 置空
以便在渲染前即可定位缓存槽。
Args:
structure_analysis_id: 冻结结构分析 ID。
template_packet_checksum: template packet 校验和。
datasets_packet_checksum: datasets packet 校验和。
dataset_structure_fingerprint: datasets 结构指纹。
source_content_hash: 源 PDF 内容哈希。
renderer_version: 合成器版本。
Returns:
稳定十六进制缓存键。
"""
ctx = PreviewIdentityContext(
document_id=None,
layout_version_id=None,
structure_analysis_id=structure_analysis_id,
source_content_hash=str(source_content_hash or ''),
template_packet_checksum=str(template_packet_checksum or ''),
datasets_packet_checksum=str(datasets_packet_checksum or ''),
dataset_structure_fingerprint=str(dataset_structure_fingerprint or ''),
preview_render_checksum='',
renderer_version=str(renderer_version or ''),
page_count=0,
)
return build_preview_identity_fingerprint(ctx)
def get_preview_cache(key: str) -> dict[str, Any] | None:
"""
读取预览缓存条目。
核心逻辑:持锁检查 TTL;过期则删除并返回 None。
Args:
key: build_preview_cache_key 结果。
Returns:
缓存的预览结果字典;未命中或过期时为 None。
"""
text = str(key or '').strip()
if not text:
return None
now = time.time()
with _LOCK:
item = _CACHE.get(text)
if item is None:
return None
expires_at, payload = item
if expires_at <= now:
_CACHE.pop(text, None)
return None
return dict(payload)
def set_preview_cache(
key: str,
value: dict[str, Any],
*,
ttl_seconds: int = _DEFAULT_TTL_SECONDS,
) -> None:
"""
写入预览缓存条目。
Args:
key: 缓存键。
value: 可浅拷贝的预览结果字典(调用方勿放入不可序列化巨型对象以外的副作用状态)。
ttl_seconds: 存活秒数;最小 1。
"""
text = str(key or '').strip()
if not text or not isinstance(value, dict):
return
expires_at = time.time() + max(1, int(ttl_seconds))
with _LOCK:
_CACHE[text] = (expires_at, dict(value))
def invalidate_preview_cache(key: str | None = None) -> None:
"""
使预览缓存失效。
核心逻辑:key 为空时清空全部;否则仅删除指定键。
Args:
key: 可选缓存键;None/空串表示清空。
"""
with _LOCK:
if not key:
_CACHE.clear()
return
_CACHE.pop(str(key), None)
def clear_preview_cache() -> None:
"""清空全部预览缓存(测试辅助)。"""
invalidate_preview_cache(None)
@@ -0,0 +1,185 @@
"""
services/shipping_notice/document_layout/xfa_preview_contract.py
用途:冻结 XFA 自研静态合成预览(Phase 1 POC)契约——render_mode、预览状态、
错误码、身份上下文、审计事件名与确定性指纹辅助。
依赖:标准库 dataclasses/hashlib/json;被 xfa_preview_renderer / xfa_preview_cache /
后续预览 API 与审计接线引用。
逻辑:本模块只定义纯数据与纯函数,不读 PDF、不渲染、不落库;身份字段与
preview_render_checksum 必须与合成器输出一致,供 stale 判定与发布证据绑定。
"""
from __future__ import annotations
import hashlib
import json
from dataclasses import asdict, dataclass
from typing import Any, Final, Literal
# ---------------------------------------------------------------------------
# 渲染模式 / 预览状态
# ---------------------------------------------------------------------------
RENDER_MODE: Final[str] = 'xfa_dataset_preview'
XfaPreviewStatus = Literal['ready', 'needs_review', 'failed', 'stale']
XFA_PREVIEW_STATUSES: Final[frozenset[str]] = frozenset({
'ready',
'needs_review',
'failed',
'stale',
})
# ---------------------------------------------------------------------------
# 稳定错误码(短码;AppError 层可映射为 SHIPPING.ORDER_DOCUMENT_PROFILE_*)
# ---------------------------------------------------------------------------
XFA_PREVIEW_STALE: Final[str] = 'XFA_PREVIEW_STALE'
XFA_PREVIEW_FAILED: Final[str] = 'XFA_PREVIEW_FAILED'
XFA_PREVIEW_UNAVAILABLE: Final[str] = 'XFA_PREVIEW_UNAVAILABLE'
XFA_PREVIEW_PAGE_INCONSISTENT: Final[str] = 'XFA_PREVIEW_PAGE_INCONSISTENT'
XFA_PREVIEW_VALUE_MISMATCH: Final[str] = 'XFA_PREVIEW_VALUE_MISMATCH'
XFA_PREVIEW_ERROR_CODES: Final[frozenset[str]] = frozenset({
XFA_PREVIEW_STALE,
XFA_PREVIEW_FAILED,
XFA_PREVIEW_UNAVAILABLE,
XFA_PREVIEW_PAGE_INCONSISTENT,
XFA_PREVIEW_VALUE_MISMATCH,
})
# AppError / i18n 完整码(与 SHIPPING.ORDER_DOCUMENT_PROFILE_* 风格对齐)
SHIPPING_XFA_PREVIEW_STALE: Final[str] = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_STALE'
SHIPPING_XFA_PREVIEW_FAILED: Final[str] = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_FAILED'
SHIPPING_XFA_PREVIEW_UNAVAILABLE: Final[str] = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_UNAVAILABLE'
SHIPPING_XFA_PREVIEW_PAGE_INCONSISTENT: Final[str] = (
'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_PAGE_INCONSISTENT'
)
SHIPPING_XFA_PREVIEW_VALUE_MISMATCH: Final[str] = (
'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_VALUE_MISMATCH'
)
XFA_PREVIEW_SHIPPING_ERROR_BY_CODE: Final[dict[str, str]] = {
XFA_PREVIEW_STALE: SHIPPING_XFA_PREVIEW_STALE,
XFA_PREVIEW_FAILED: SHIPPING_XFA_PREVIEW_FAILED,
XFA_PREVIEW_UNAVAILABLE: SHIPPING_XFA_PREVIEW_UNAVAILABLE,
XFA_PREVIEW_PAGE_INCONSISTENT: SHIPPING_XFA_PREVIEW_PAGE_INCONSISTENT,
XFA_PREVIEW_VALUE_MISMATCH: SHIPPING_XFA_PREVIEW_VALUE_MISMATCH,
}
# ---------------------------------------------------------------------------
# 审计事件(预览生命周期)
# ---------------------------------------------------------------------------
XFA_PREVIEW_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
'xfa_preview_requested',
'xfa_preview_generated',
'xfa_preview_failed',
'xfa_preview_viewed',
'xfa_preview_stale',
})
@dataclass(frozen=True)
class PreviewIdentityContext:
"""
合成预览身份上下文:发布视觉证据与 stale 判定的冻结字段集合。
任一关键校验和/指纹变化即视为预览身份漂移,不得继续当作 ready 证据。
"""
document_id: int | None
layout_version_id: int | None
structure_analysis_id: int | str | None
source_content_hash: str
template_packet_checksum: str
datasets_packet_checksum: str
dataset_structure_fingerprint: str
preview_render_checksum: str
render_mode: str = RENDER_MODE
renderer_version: str = ''
page_count: int = 0
def shipping_error_code_for_preview(error_code: str | None) -> str | None:
"""
将预览短错误码映射为 SHIPPING.ORDER_DOCUMENT_PROFILE_* AppError 码。
核心逻辑:查 XFA_PREVIEW_SHIPPING_ERROR_BY_CODE;未知码原样返回。
Args:
error_code: 预览短错误码或已是完整 SHIPPING.* 码。
Returns:
完整业务错误码;输入为空时返回 None。
"""
text = str(error_code or '').strip()
if not text:
return None
if text.startswith('SHIPPING.'):
return text
return XFA_PREVIEW_SHIPPING_ERROR_BY_CODE.get(text, text)
def preview_identity_to_dict(ctx: PreviewIdentityContext) -> dict[str, Any]:
"""
将 PreviewIdentityContext 序列化为可审计/可缓存的普通字典。
Args:
ctx: 预览身份上下文。
Returns:
字段字典(不含额外派生键)。
"""
return asdict(ctx)
def build_preview_identity_fingerprint(ctx: PreviewIdentityContext) -> str:
"""
计算预览身份指纹(不含 preview_render_checksum 本身,避免循环依赖)。
核心逻辑:对 document/layout/analysis/内容哈希/packet/结构指纹/render_mode/
renderer_version/page_count 做稳定 JSON 序列化后 SHA-256。
Args:
ctx: 预览身份上下文。
Returns:
64 位十六进制指纹字符串。
"""
payload = {
'document_id': ctx.document_id,
'layout_version_id': ctx.layout_version_id,
'structure_analysis_id': ctx.structure_analysis_id,
'source_content_hash': str(ctx.source_content_hash or ''),
'template_packet_checksum': str(ctx.template_packet_checksum or ''),
'datasets_packet_checksum': str(ctx.datasets_packet_checksum or ''),
'dataset_structure_fingerprint': str(ctx.dataset_structure_fingerprint or ''),
'render_mode': str(ctx.render_mode or RENDER_MODE),
'renderer_version': str(ctx.renderer_version or ''),
'page_count': int(ctx.page_count or 0),
}
raw = json.dumps(payload, sort_keys=True, separators=(',', ':'), ensure_ascii=True)
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
def is_preview_identity_stale(
*,
expected: PreviewIdentityContext,
actual: PreviewIdentityContext,
) -> bool:
"""
判断实际预览身份是否相对期望身份已过期(stale)。
核心逻辑:比较身份指纹与 preview_render_checksum;任一不等即 stale。
Args:
expected: 期望/冻结身份(例如绑定证据快照)。
actual: 当前重新计算的身份。
Returns:
True 表示应标记 stale 并重新生成/重确认。
"""
if build_preview_identity_fingerprint(expected) != build_preview_identity_fingerprint(actual):
return True
return str(expected.preview_render_checksum or '') != str(actual.preview_render_checksum or '')
@@ -0,0 +1,200 @@
"""
services/shipping_notice/document_layout/xfa_preview_renderer.py
用途:XFA 离线完整 flatten 入口(硬冻结 §0)。当前未接入可复现 flatten 引擎时
一律 fail-closed 返回 needs_review;禁止静态 overlay / 壳图充当 ready。
依赖:xfa_preview_contract;未来真实引擎须离线、禁不受控脚本、输出可复现 checksum。
逻辑:由预览编排服务调用 compose_xfa_dataset_preview_pages;settings
SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY=true 且引擎实现就绪后才可返回 ready。
"""
from __future__ import annotations
import hashlib
from dataclasses import dataclass, field
from typing import Any
from app.services.shipping_notice.document_layout.xfa_preview_contract import (
RENDER_MODE,
XFA_PREVIEW_FAILED,
XFA_PREVIEW_UNAVAILABLE,
XfaPreviewStatus,
)
# 版本号:v0_pending 表示尚未交付完整 flatten;不得与历史 overlay checksum 混用。
RENDERER_VERSION = 'hxops.xfa_flatten.v0_pending'
@dataclass
class DrawnFieldEcho:
"""单页上 flatten 回显痕迹(完整引擎就绪后使用)。"""
path_id: str
value: str
normalized_bbox: dict[str, float]
page_no: int = 1
@dataclass
class XfaPreviewComposeResult:
"""flatten / 预览文档级结果;status!=ready 时 pages 为空。"""
status: XfaPreviewStatus
error_code: str | None
render_mode: str
renderer_version: str
page_count: int
preview_render_checksum: str | None
pages: list[dict[str, Any]] = field(default_factory=list)
diagnostics: dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> dict[str, Any]:
"""序列化为普通字典。"""
return {
'status': self.status,
'error_code': self.error_code,
'render_mode': self.render_mode,
'renderer_version': self.renderer_version,
'page_count': self.page_count,
'preview_render_checksum': self.preview_render_checksum,
'pages': self.pages,
'diagnostics': self.diagnostics,
}
def compute_preview_render_checksum(
*,
renderer_version: str,
pages: list[dict[str, Any]],
) -> str:
"""
计算可复现的预览渲染校验和。
核心逻辑:串联 renderer_version 与各页宽高/回显指纹/图像哈希后 SHA-256。
Args:
renderer_version: 合成器版本。
pages: 含 width/height/drawn_field_echoes/png_bytes 的页列表。
Returns:
hex digest 字符串。
"""
parts: list[str] = [str(renderer_version or '')]
for page in pages:
page_no = int(page.get('page_no') or 0)
width = float(page.get('width') or 0)
height = float(page.get('height') or 0)
echoes = page.get('drawn_field_echoes') if isinstance(page.get('drawn_field_echoes'), list) else []
echo_fp = '|'.join(
f"{item.get('path_id')}:{item.get('value')}"
for item in echoes
if isinstance(item, dict)
)
png = page.get('png_bytes')
img_hash = ''
if isinstance(png, (bytes, bytearray)) and png:
img_hash = hashlib.sha256(bytes(png)).hexdigest()
parts.append(f'{page_no}:{width}x{height}:{echo_fp}:{img_hash}')
return hashlib.sha256('\n'.join(parts).encode('utf-8')).hexdigest()
def is_xfa_flatten_engine_ready() -> bool:
"""
完整离线 flatten 引擎是否已启用且可对外返回 ready。
核心逻辑:读取 settings.SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY;默认 false。
引擎实现与人眼一致性完成前必须保持关闭。
Returns:
True 仅当显式开启(当前仍无真实引擎实现,开启也不会 ready)。
"""
try:
from app.core.config.settings import Settings
return bool(getattr(Settings, 'SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY', False))
except Exception: # noqa: BLE001
return False
def attempt_offline_xfa_flatten(
*,
pdf_bytes: bytes,
analysis_or_nodes: Any,
page_boxes: list[dict[str, Any]] | None = None,
template_bytes: bytes | None = None,
) -> XfaPreviewComposeResult:
"""
尝试离线完整 XFA flatten(template + datasets → 有效 PDF/PNG)。
核心逻辑:硬冻结要求删除 overlay;真实引擎未交付前一律 needs_review。
不得用 PDFium 壳图或黄框叠加冒充 ready。
Args:
pdf_bytes: 源 XFA PDF 字节。
analysis_or_nodes: datasets 分析或叶子映射(预留)。
page_boxes: 可选期望页框(预留)。
template_bytes: 可选 template packet(预留)。
Returns:
当前恒为 needs_review / failed;未来引擎就绪后返回 ready + pages。
"""
del analysis_or_nodes, page_boxes, template_bytes # 真实引擎接入时启用
if not pdf_bytes:
return XfaPreviewComposeResult(
status='failed',
error_code=XFA_PREVIEW_FAILED,
render_mode=RENDER_MODE,
renderer_version=RENDERER_VERSION,
page_count=0,
preview_render_checksum=None,
pages=[],
diagnostics={'reason': 'empty_pdf_bytes'},
)
# [STEP] 完整 flatten 未交付:fail-closed(禁止 overlay ready)
return XfaPreviewComposeResult(
status='needs_review',
error_code=XFA_PREVIEW_UNAVAILABLE,
render_mode=RENDER_MODE,
renderer_version=RENDERER_VERSION,
page_count=0,
preview_render_checksum=None,
pages=[],
diagnostics={
'reason': 'flatten_engine_unavailable',
'message': (
'Offline reproducible XFA flatten is not available; '
'shell PDF / PDFium shell / overlay must not be used as canvas source'
),
'flatten_engine_ready_flag': is_xfa_flatten_engine_ready(),
'operational_status': 'OPERATIONAL_PENDING',
},
)
def compose_xfa_dataset_preview_pages(
*,
pdf_bytes: bytes,
analysis_or_nodes: Any,
page_boxes: list[dict[str, Any]] | None = None,
template_bytes: bytes | None = None,
) -> XfaPreviewComposeResult:
"""
XFA 标注图源编排入口(对外保持原函数名以兼容调用方)。
核心逻辑:委托 attempt_offline_xfa_flatten;未完成完整 flatten 前不得返回 ready。
Args:
pdf_bytes: 源 PDF 字节。
analysis_or_nodes: datasets 分析或叶子映射。
page_boxes: 可选期望页框。
template_bytes: 可选 template packet。
Returns:
XfaPreviewComposeResult;当前预期 status=needs_review。
"""
return attempt_offline_xfa_flatten(
pdf_bytes=pdf_bytes,
analysis_or_nodes=analysis_or_nodes,
page_boxes=page_boxes,
template_bytes=template_bytes,
)
@@ -2,9 +2,10 @@
services/shipping_notice/document_layout/xfa_split_preview_token.py
用途:签发与校验 XFA 拆分规则预览确认令牌,防止客户端自行声明 confirmed。
依赖:Flask current_app.SECRET_KEY、hmac、hashlib、time、secrets、redis_client(可选)。
依赖:Flask current_app.SECRET_KEY、hmac、hashlib、time、secrets、redis_client。
逻辑:由 preview_xfa_split_rules 签发;save_draft / 确认接口经 verify_and_consume 原子消费 jti;
Redis 不可用时回退进程内 set + threading.Lock(单测与单进程开发友好,非多 Worker 生产语义)。
生产/预发/多 Worker:Redis 不可用时 fail-closed(STORE_UNAVAILABLE);
仅 TESTING 或单进程 development(ALLOW_MEMORY_JTI)允许进程内兜底。
"""
from __future__ import annotations
@@ -12,6 +13,7 @@ from __future__ import annotations
import hashlib
import hmac
import json
import logging
import secrets
import threading
import time
@@ -21,6 +23,8 @@ from flask import current_app
from app.core.errors import ValidationError
_LOGGER = logging.getLogger(__name__)
# 预览确认令牌默认有效期(秒)
DEFAULT_SPLIT_PREVIEW_TOKEN_TTL_SECONDS = 15 * 60
@@ -59,6 +63,40 @@ class _MemoryConsumedJtiStore:
_memory_jti_store = _MemoryConsumedJtiStore()
def _allow_memory_jti_fallback() -> bool:
"""
是否允许进程内 JTI 消费兜底。
核心逻辑:pytest(TESTING)或明确开启 ALLOW_MEMORY_JTI 的单进程 development;
ENV_NAME 为 test/prod/staging 时一律禁止(即使误配开关)。
Returns:
True 仅当允许内存兜底。
"""
if bool(current_app.config.get('TESTING')):
return True
env = str(current_app.config.get('ENV_NAME') or '').strip().lower()
if env in {'test', 'prod', 'production', 'staging', 'pre', 'uat'}:
return False
if env not in {'dev', 'development'}:
return False
return bool(current_app.config.get('XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI'))
def _raise_confirm_store_unavailable(*, reason: str) -> None:
"""
Redis 确认存储不可用时 fail-closed。
Raises:
ValidationError: SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_CONFIRM_STORE_UNAVAILABLE。
"""
raise ValidationError(
'XFA split confirmation store is temporarily unavailable',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_CONFIRM_STORE_UNAVAILABLE',
details={'reason': reason},
)
def _signing_secret() -> bytes:
"""
读取应用级签名密钥。
@@ -102,7 +140,8 @@ def _try_consume_jti(*, jti: str, ttl_seconds: int) -> bool:
"""
原子消费令牌 jti。
核心逻辑:优先 Redis SET NX EX;失败或不可用时回退进程内 set + Lock。
核心逻辑:优先 Redis SET NX EX;Redis 不可用时仅在 testing/单进程 development
回退进程内 store,否则抛 STORE_UNAVAILABLE(禁止多 Worker 不一致消费)。
Args:
jti: 令牌唯一标识。
@@ -110,18 +149,31 @@ def _try_consume_jti(*, jti: str, ttl_seconds: int) -> bool:
Returns:
True 表示首次消费成功;False 表示已被消费。
Raises:
ValidationError: Redis 不可用且当前环境禁止内存兜底。
"""
key = f'{_JTI_REDIS_KEY_PREFIX}{jti}'
ttl = max(1, int(ttl_seconds))
redis_error: Exception | None = None
try:
from app.services.redis_client import get_redis_client
client = get_redis_client()
if client is not None:
return bool(client.set(key, '1', nx=True, ex=ttl))
except Exception:
pass
return _memory_jti_store.try_consume(jti, ttl)
redis_error = RuntimeError('redis_client_unavailable')
except Exception as exc: # noqa: BLE001 — 任意 Redis 故障均需 fail-closed 决策
redis_error = exc
_LOGGER.warning('XFA split preview token Redis consume failed: %s', exc)
if _allow_memory_jti_fallback():
return _memory_jti_store.try_consume(jti, ttl)
_raise_confirm_store_unavailable(
reason='redis_unavailable' if redis_error is not None else 'redis_client_missing',
)
return False # pragma: no cover — raise 已终止
def _validate_token_bindings(
@@ -386,8 +438,8 @@ def verify_and_consume_split_preview_token(
"""
验签并原子消费拆分预览确认令牌。
核心逻辑:验签与绑定校验通过后,以 Redis SET NX EX(或进程内兜底)标记 jti 已消费;
重复消费抛 token_replay。
核心逻辑:验签与绑定校验通过后,以 Redis SET NX EX 标记 jti 已消费;
重复消费抛 token_replay;Redis 不可用且非允许环境抛 STORE_UNAVAILABLE。
Args:
token: 预览接口返回的令牌。
@@ -405,7 +457,7 @@ def verify_and_consume_split_preview_token(
已校验且已消费的 payload dict。
Raises:
ValidationError: 令牌无效、绑定不匹配或已被消费(重放)。
ValidationError: 令牌无效、绑定不匹配、已被消费,或确认存储不可用。
"""
payload = _decode_and_verify_signature(token)
_validate_token_bindings(
@@ -0,0 +1,294 @@
"""
services/shipping_notice/document_layout/xfa_template_parser.py
用途:防御性解析 XFA template packet,提取 field/draw 节点的 bind 引用与近似几何
(x/y/w/h 属性),供自研静态合成预览定位回显文本。
依赖:lxml、xfa_packets.preflight_xml_bytes、xfa_dataset._hardened_parser 模式。
逻辑:由 xfa_preview_renderer 调用;不执行 JS/FormCalc、不联网;解析失败返回空列表。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Any
from lxml import etree
from app.services.shipping_notice.document_layout.xfa_packets import XfaPacketError, preflight_xml_bytes
_DIMENSION_RE = re.compile(
r'^\s*(?P<value>-?\d+(?:\.\d+)?)\s*(?P<unit>pt|mm|in|cm|px)?\s*$',
re.IGNORECASE,
)
# 常见页面参考尺寸(Letter pt),仅用于将绝对单位粗略归一化。
_DEFAULT_PAGE_WIDTH_PT = 612.0
_DEFAULT_PAGE_HEIGHT_PT = 792.0
_FIELD_DRAW_LOCAL_NAMES = frozenset({'field', 'draw'})
@dataclass(frozen=True)
class XfaTemplateFieldGeometry:
"""
template 中可定位的 field/draw 摘要。
坐标为页面相对归一化框(左上原点 0..1);无法可靠归一化时 normalized_bbox 为空。
"""
name: str
bind_ref: str
page_no: int
raw_x: float | None
raw_y: float | None
raw_w: float | None
raw_h: float | None
normalized_bbox: dict[str, float] | None
local_name: str
def _local_name(tag: str) -> str:
"""提取 XML localName,忽略命名空间前缀。"""
return str(tag or '').rsplit('}', 1)[-1].lower()
def _hardened_parser() -> etree.XMLParser:
"""
构造禁用外部实体与 DTD 的 lxml 解析器。
Returns:
与 datasets 解析同策略的安全 XMLParser。
"""
return etree.XMLParser(
resolve_entities=False,
load_dtd=False,
no_network=True,
huge_tree=False,
)
def _parse_dimension(raw: str | None) -> float | None:
"""
解析 XFA 尺寸属性(可带 pt/mm/in/cm/px 后缀)为浮点数。
核心逻辑:无单位时原样返回数值;有单位时统一换算为 pt(近似)。
Args:
raw: 属性字符串,如 ``36pt``、``10mm``、``0.25``。
Returns:
数值(pt 或无单位原值);无法解析时返回 None。
"""
text = str(raw or '').strip()
if not text:
return None
match = _DIMENSION_RE.match(text)
if not match:
return None
try:
value = float(match.group('value'))
except (TypeError, ValueError):
return None
unit = (match.group('unit') or '').lower()
if not unit or unit == 'pt' or unit == 'px':
return value
if unit == 'in':
return value * 72.0
if unit == 'mm':
return value * 72.0 / 25.4
if unit == 'cm':
return value * 72.0 / 2.54
return value
def _attr(element: etree._Element, *names: str) -> str:
"""按候选属性名读取第一个非空值(忽略命名空间前缀)。"""
for name in names:
for key, value in element.attrib.items():
local = str(key).rsplit('}', 1)[-1]
if local.lower() == name.lower() and str(value or '').strip():
return str(value).strip()
return ''
def _extract_bind_ref(element: etree._Element) -> str:
"""
从 field/draw 或其 bind 子节点提取 dataRef。
核心逻辑:优先读子节点 ``bind`` 的 ref/dataRef;否则读自身 bind/ref 属性。
"""
direct = _attr(element, 'bind', 'ref', 'dataRef')
if direct:
return direct
for child in element:
if not isinstance(child.tag, str):
continue
if _local_name(child.tag) != 'bind':
continue
ref = _attr(child, 'ref', 'dataRef', 'match')
if ref and ref.lower() not in {'none', 'dataref', 'once', 'global', 'dataRef'.lower()}:
return ref
# match="dataRef" 时真正路径常在 ref
ref2 = _attr(child, 'ref', 'dataRef')
if ref2:
return ref2
return ''
def _normalize_bbox_from_raw(
*,
x: float | None,
y: float | None,
w: float | None,
h: float | None,
page_width: float,
page_height: float,
) -> dict[str, float] | None:
"""
将 template 原始 x/y/w/h 粗略归一化为左上原点 0..1 框。
核心逻辑:若数值均落在 0..1 则视为已归一化;否则按 page pt 尺寸换算。
XFA 模板常以左下为原点,此处按「y 为距底边」尝试翻转;若翻转后越界则按左上解释。
Args:
x/y/w/h: 原始尺寸(pt 或相对)。
page_width/page_height: 参考页尺寸(pt)。
Returns:
``{x0,y0,x1,y1}``;无法构成有效框时返回 None。
"""
if x is None or y is None or w is None or h is None:
return None
if w <= 0 or h <= 0:
return None
if page_width <= 0 or page_height <= 0:
return None
# [STEP 1] 已是相对坐标
if 0.0 <= x <= 1.0 and 0.0 <= y <= 1.0 and 0.0 < w <= 1.0 and 0.0 < h <= 1.0:
x0, y0, x1, y1 = x, y, x + w, y + h
else:
# [STEP 2] 绝对 pt:优先按 PDF 左下原点翻转
x0 = x / page_width
x1 = (x + w) / page_width
y0_flip = 1.0 - ((y + h) / page_height)
y1_flip = 1.0 - (y / page_height)
y0_top = y / page_height
y1_top = (y + h) / page_height
if 0.0 <= y0_flip <= 1.0 and 0.0 <= y1_flip <= 1.0 and y1_flip > y0_flip:
y0, y1 = y0_flip, y1_flip
else:
y0, y1 = y0_top, y1_top
x0 = max(0.0, min(1.0, x0))
x1 = max(0.0, min(1.0, x1))
y0 = max(0.0, min(1.0, y0))
y1 = max(0.0, min(1.0, y1))
if x1 <= x0 or y1 <= y0:
return None
return {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1}
def _resolve_page_no(element: etree._Element, default_page: int = 1) -> int:
"""从节点或其祖先读取 page/pageNum 属性;非法时回退 default_page。"""
current: etree._Element | None = element
while current is not None:
raw = _attr(current, 'page', 'pageNum', 'page_no')
if raw:
try:
value = int(float(raw))
if value >= 1:
return value
except (TypeError, ValueError):
pass
parent = current.getparent()
current = parent if isinstance(parent, etree._Element) else None
return max(1, int(default_page))
def parse_xfa_template_field_geometries(
template_bytes: bytes,
*,
page_width: float = _DEFAULT_PAGE_WIDTH_PT,
page_height: float = _DEFAULT_PAGE_HEIGHT_PT,
) -> list[XfaTemplateFieldGeometry]:
"""
解析 XFA template packet,提取带 bind 与近似位置的 field/draw 节点。
核心逻辑:preflight → hardened lxml 解析 → 遍历 field/draw;读取 name/bind 与
x/y/w/h;失败或不可解析时返回空列表(不抛给调用方)。
Args:
template_bytes: template packet XML 字节。
page_width: 用于绝对坐标归一化的参考页宽(pt)。
page_height: 用于绝对坐标归一化的参考页高(pt)。
Returns:
几何摘要列表;不可解析时为空列表。
"""
if not template_bytes:
return []
try:
preflight_xml_bytes(template_bytes)
root = etree.fromstring(template_bytes, parser=_hardened_parser())
except (XfaPacketError, etree.XMLSyntaxError, ValueError, TypeError, OSError):
return []
except Exception:
return []
results: list[XfaTemplateFieldGeometry] = []
for element in root.iter():
if not isinstance(element.tag, str):
continue
local = _local_name(element.tag)
if local not in _FIELD_DRAW_LOCAL_NAMES:
continue
name = _attr(element, 'name') or local
bind_ref = _extract_bind_ref(element)
x = _parse_dimension(_attr(element, 'x'))
y = _parse_dimension(_attr(element, 'y'))
w = _parse_dimension(_attr(element, 'w', 'width'))
h = _parse_dimension(_attr(element, 'h', 'height'))
page_no = _resolve_page_no(element)
bbox = _normalize_bbox_from_raw(
x=x, y=y, w=w, h=h, page_width=page_width, page_height=page_height,
)
results.append(XfaTemplateFieldGeometry(
name=name,
bind_ref=bind_ref,
page_no=page_no,
raw_x=x,
raw_y=y,
raw_w=w,
raw_h=h,
normalized_bbox=bbox,
local_name=local,
))
return results
def serialize_template_field_geometries(
items: list[XfaTemplateFieldGeometry],
) -> list[dict[str, Any]]:
"""
将 template 几何摘要序列化为普通字典列表(测试/诊断用)。
Args:
items: parse_xfa_template_field_geometries 结果。
Returns:
可 JSON 化的字典列表。
"""
return [
{
'name': item.name,
'bind_ref': item.bind_ref,
'page_no': item.page_no,
'raw_x': item.raw_x,
'raw_y': item.raw_y,
'raw_w': item.raw_w,
'raw_h': item.raw_h,
'normalized_bbox': item.normalized_bbox,
'local_name': item.local_name,
}
for item in items
]