feat(shipping-notice): 落地 XFA 统一视觉拆分确认门禁与处理投影收敛
闭合拆分预览令牌单次消费、样本 checksum 绑定与确认审计;正式提取改为 bindings-only。 同步统一标注工作台交互,并补齐进度投影/任务中心与迁移文档。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
d2b3d74def
commit
84a881b554
195 files changed
+20269
-3463
No files matched your search
@@ -194,6 +194,14 @@ SHIPPING_NOTICE_XFA_MAX_XML_NODES=100000
|
||||
SHIPPING_NOTICE_XFA_MAX_LINE_ROWS=2000
|
||||
SHIPPING_NOTICE_XFA_PARSE_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_XFA_MAX_RETRIES=2
|
||||
# XFA 字段拆分规则资源上限(统一方案阶段 1;与 settings.XFA_SPLIT_* 对齐)
|
||||
XFA_SPLIT_MAX_RULES_PER_SET=32
|
||||
XFA_SPLIT_MAX_RULE_SETS=64
|
||||
XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH=128
|
||||
XFA_SPLIT_MAX_REGEX_GROUPS=5
|
||||
XFA_SPLIT_MAX_PREFIX_LENGTH=64
|
||||
XFA_SPLIT_MAX_INPUT_LENGTH=32768
|
||||
XFA_SPLIT_REGEX_TIMEOUT_MS=50
|
||||
# 复核台 Dify 最小证据建议;永不自动冻结。
|
||||
SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true
|
||||
# 全局紧急停止:新 Run 自动冻结立即为 0(进程配置;多 worker 需逐进程/重启生效)。
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/api/admin/shipping_order_document_profiles.py
|
||||
|
||||
用途:提供订单文档模板 Profile 的管理员版本治理 API。
|
||||
依赖:admin blueprint、require_admin、order_document_profile_service。
|
||||
逻辑:路由只转换请求和操作者;版本、Schema、字段及发布门禁全部由服务层执行。
|
||||
依赖:admin blueprint、require_admin、order_document_profile_service、
|
||||
order_document_profile_visual_binding_service、order_profile_unified_migration。
|
||||
逻辑:路由只转换请求和操作者;版本、Schema、字段、统一迁移与发布门禁全部由服务层执行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -29,6 +30,8 @@ from app.services.shipping_notice import order_document_profile_usage_service as
|
||||
from app.services.shipping_notice import order_document_profile_validation_service as validation_service
|
||||
from app.services.shipping_notice import order_document_profile_publish_check_service as publish_check_service
|
||||
from app.services.shipping_notice import order_document_profile_version_service as version_service
|
||||
from app.services.shipping_notice import order_document_profile_visual_binding_service as visual_binding_service
|
||||
from app.services.shipping_notice import order_profile_unified_migration as unified_migration
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
@@ -232,10 +235,13 @@ def update_order_document_profile(profile_id: int):
|
||||
profile_row = _db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
incoming_def = data.get('definition') if isinstance(data.get('definition'), dict) else {}
|
||||
previous_def = (
|
||||
profile_row.definition_json
|
||||
dict(profile_row.definition_json)
|
||||
if profile_row is not None and isinstance(profile_row.definition_json, dict)
|
||||
else {}
|
||||
)
|
||||
# [STEP] 变更 split_rules 强制校验 xfa_split_rule_edit(注释与实现一致)。
|
||||
if service.split_rules_definition_changed(previous_def, incoming_def if isinstance(incoming_def, dict) else {}):
|
||||
_require_xfa_split_edit_permission()
|
||||
return _ok(service.save_draft(
|
||||
data, actor_id=_actor_id(), profile_id=profile_id, **_write_context(data), enforce_lease=True,
|
||||
))
|
||||
@@ -774,15 +780,16 @@ def get_order_document_profile_sample_xfa_collections(document_id: int):
|
||||
)
|
||||
@require_admin
|
||||
def preview_order_document_profile_sample_xfa_value(document_id: int):
|
||||
"""按 path_id 返回分级样本值;完整值读取要求敏感权限并由服务层留痕。"""
|
||||
"""
|
||||
按 path_id 返回样本值投影。
|
||||
|
||||
核心逻辑:默认脱敏;仅当请求 reveal=true 且具备 audit_sensitive_read 时返回完整值,
|
||||
并由服务层写入敏感访问审计。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
reveal = bool(data.get('reveal'))
|
||||
user = getattr(g, 'current_user', None)
|
||||
if reveal and not bool(user and user.has_feature_permission('shipping_notice.audit_sensitive_read')):
|
||||
raise ForbiddenError(
|
||||
'XFA sample full value permission is required',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_VALUE_FORBIDDEN',
|
||||
)
|
||||
if reveal:
|
||||
_require_audit_sensitive_read_permission()
|
||||
return _private_ok(service.preview_xfa_sample_value(
|
||||
document_id,
|
||||
path_id=str(data.get('path_id') or ''),
|
||||
@@ -797,11 +804,19 @@ def preview_order_document_profile_sample_xfa_value(document_id: int):
|
||||
)
|
||||
@require_admin
|
||||
def preview_order_document_profile_sample_xfa_split_rules(document_id: int):
|
||||
"""预览拆分规则执行结果;默认脱敏,完整值需敏感读权限。"""
|
||||
"""
|
||||
预览拆分规则执行结果并签发确认令牌。
|
||||
|
||||
核心逻辑:须 xfa_split_rule_preview;完整 mapped/raw 值另需 audit_sensitive_read,
|
||||
且完整值路径强制写访问审计。
|
||||
"""
|
||||
_require_xfa_split_preview_permission()
|
||||
data = request.get_json(silent=True) or {}
|
||||
reveal = bool(data.get('reveal'))
|
||||
rule_set = data.get('rule_set') if isinstance(data.get('rule_set'), dict) else {}
|
||||
profile_id = data.get('profile_id')
|
||||
reveal = bool(data.get('reveal'))
|
||||
if reveal:
|
||||
_require_audit_sensitive_read_permission()
|
||||
return _private_ok(service.preview_xfa_split_rules(
|
||||
document_id,
|
||||
path_id=str(data.get('path_id') or ''),
|
||||
@@ -809,6 +824,81 @@ def preview_order_document_profile_sample_xfa_split_rules(document_id: int):
|
||||
actor_id=_actor_id(),
|
||||
profile_id=int(profile_id) if profile_id not in (None, '') else None,
|
||||
include_full_values=reveal,
|
||||
write_audit=True if reveal else bool(data.get('write_audit')),
|
||||
))
|
||||
|
||||
|
||||
def _require_audit_sensitive_read_permission() -> None:
|
||||
"""完整 XFA 样本/拆分值读取需 shipping_notice.audit_sensitive_read。"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
if not bool(user and user.has_feature_permission('shipping_notice.audit_sensitive_read')):
|
||||
raise ForbiddenError(
|
||||
'XFA sensitive value read permission is required',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_VALUE_FORBIDDEN',
|
||||
details={'permission': 'shipping_notice.audit_sensitive_read'},
|
||||
)
|
||||
|
||||
|
||||
def _require_xfa_split_preview_permission() -> None:
|
||||
"""拆分规则预览/建议需 xfa_split_rule_preview 权限(admin 默认具备)。"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
if not bool(user and user.has_feature_permission('shipping_notice.xfa_split_rule_preview')):
|
||||
raise ForbiddenError(
|
||||
'XFA split rule preview permission is required',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_VALUE_FORBIDDEN',
|
||||
details={'permission': 'shipping_notice.xfa_split_rule_preview'},
|
||||
)
|
||||
|
||||
|
||||
def _require_xfa_split_edit_permission() -> None:
|
||||
"""变更拆分规则需 shipping_notice.xfa_split_rule_edit。"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
if not bool(user and user.has_feature_permission('shipping_notice.xfa_split_rule_edit')):
|
||||
raise ForbiddenError(
|
||||
'XFA split rule edit permission is required',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_EDIT_FORBIDDEN',
|
||||
details={'permission': 'shipping_notice.xfa_split_rule_edit'},
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/split-rules/suggest',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def suggest_order_document_profile_xfa_split_rules(profile_id: int):
|
||||
"""生成 MATNR 类拆分规则建议;不写 Draft、不 commit。"""
|
||||
_require_xfa_split_preview_permission()
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _private_ok(suggestion_service.suggest_xfa_split_rules(
|
||||
profile_id,
|
||||
document_id=data.get('document_id'),
|
||||
path_id=str(data.get('path_id') or '').strip() or None,
|
||||
actor_id=_actor_id(),
|
||||
write_audit=False,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/unified-mapping/suggest',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def suggest_order_document_profile_xfa_unified_mapping(profile_id: int):
|
||||
"""统一返回视觉 + 拆分规则建议;不写 Draft、不 commit。"""
|
||||
_require_xfa_split_preview_permission()
|
||||
data = request.get_json(silent=True) or {}
|
||||
bbox = data.get('normalized_bbox') if isinstance(data.get('normalized_bbox'), dict) else {}
|
||||
return _private_ok(suggestion_service.suggest_xfa_unified_mapping(
|
||||
profile_id,
|
||||
document_id=data.get('document_id'),
|
||||
page_no=data.get('page_no', 1),
|
||||
normalized_bbox=bbox,
|
||||
path_id=str(data.get('path_id') or '').strip() or None,
|
||||
actor_id=_actor_id(),
|
||||
include_visual=bool(data.get('include_visual', True)),
|
||||
include_split=bool(data.get('include_split', True)),
|
||||
write_audit=False,
|
||||
))
|
||||
|
||||
|
||||
@@ -831,3 +921,131 @@ def validate_order_document_profile_xfa_split_rules(profile_id: int):
|
||||
split_rules=split_rules,
|
||||
actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/visual-bindings/suggest',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def suggest_order_document_profile_xfa_visual_bindings(profile_id: int):
|
||||
"""为页面区域生成 XFA 视觉绑定候选;歧义不自动确认。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
bbox = data.get('normalized_bbox') if isinstance(data.get('normalized_bbox'), dict) else {}
|
||||
return _private_ok(visual_binding_service.suggest_xfa_visual_bindings(
|
||||
profile_id,
|
||||
document_id=data.get('document_id'),
|
||||
page_no=data.get('page_no', 1),
|
||||
normalized_bbox=bbox,
|
||||
actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/visual-bindings/<string:binding_id>/confirm',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def confirm_order_document_profile_xfa_visual_binding(profile_id: int, binding_id: str):
|
||||
"""管理员确认视觉绑定;写 before/after 审计。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
ctx = _write_context(data)
|
||||
visual = data.get('visual_binding') if isinstance(data.get('visual_binding'), dict) else {}
|
||||
return _private_ok(visual_binding_service.confirm_xfa_visual_binding(
|
||||
profile_id,
|
||||
binding_id,
|
||||
visual_binding=visual,
|
||||
path_id=str(data.get('path_id') or '').strip() or None,
|
||||
actor_id=_actor_id(),
|
||||
browser_session_id=ctx.get('browser_session_id'),
|
||||
lease_token=ctx.get('lease_token'),
|
||||
operation_id=ctx.get('operation_id'),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/visual-bindings/<string:binding_id>/reject',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def reject_order_document_profile_xfa_visual_binding(profile_id: int, binding_id: str):
|
||||
"""管理员驳回视觉绑定建议;写 before/after 审计。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
ctx = _write_context(data)
|
||||
return _private_ok(visual_binding_service.reject_xfa_visual_binding(
|
||||
profile_id,
|
||||
binding_id,
|
||||
reason_code=str(data.get('reason_code') or '').strip() or None,
|
||||
actor_id=_actor_id(),
|
||||
browser_session_id=ctx.get('browser_session_id'),
|
||||
lease_token=ctx.get('lease_token'),
|
||||
operation_id=ctx.get('operation_id'),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/unified-migration/dry-run',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def dry_run_order_document_profile_unified_migration(profile_id: int):
|
||||
"""
|
||||
Dry Run 统一 binding 迁移:只产出报告与审计,不改 definition。
|
||||
|
||||
核心逻辑:委托 order_profile_unified_migration.dry_run_unified_migration。
|
||||
"""
|
||||
return _ok(unified_migration.dry_run_unified_migration(
|
||||
profile_id,
|
||||
actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
write_audit=True,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/unified-migration/execute',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def execute_order_document_profile_unified_migration(profile_id: int):
|
||||
"""
|
||||
Execute 统一 binding 迁移:写入 Draft Revision 与 before/after 审计。
|
||||
|
||||
核心逻辑:已发布模板会先 clone 草稿;报告与字段差异写审计 detail。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(unified_migration.execute_unified_migration(
|
||||
profile_id,
|
||||
actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
operation_id=str(data.get('operation_id') or '').strip() or None,
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/unified-migration/scan',
|
||||
methods=['GET'],
|
||||
)
|
||||
@require_admin
|
||||
def scan_order_document_profile_unified_migration():
|
||||
"""
|
||||
扫描全部模板族的统一 binding 迁移状态(内存预览,不写 definition)。
|
||||
|
||||
核心逻辑:每族取 published 优先否则 draft;返回 totals 与逐族 pending_visual 摘要。
|
||||
"""
|
||||
profile_ids = request.args.getlist('profile_id')
|
||||
parsed_ids = [int(item) for item in profile_ids if str(item).strip().isdigit()] or None
|
||||
return _ok(unified_migration.scan_unified_migration_profiles(profile_ids=parsed_ids))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/unified-migration/report',
|
||||
methods=['GET'],
|
||||
)
|
||||
@require_admin
|
||||
def get_order_document_profile_unified_migration_report(profile_id: int):
|
||||
"""读取最近一次统一迁移 Dry Run / Execute 报告(来自审计事件)。"""
|
||||
return _ok(unified_migration.get_unified_migration_report(profile_id))
|
||||
@@ -251,6 +251,7 @@ def _audit_filters_from_request() -> dict:
|
||||
'gate_code', 'node_code', 'result', 'reason_code',
|
||||
'conversation_id', 'workflow_id', 'workflow_item_id', 'review_case_no', 'case_no',
|
||||
'owner_user_id', 'created_from', 'created_to', 'q',
|
||||
'profile_id', 'binding_id', 'revision_no', 'segment_id',
|
||||
)
|
||||
return {key: str(source.get(key) or '').strip() or None for key in keys}
|
||||
|
||||
|
||||
@@ -571,6 +571,14 @@ class Config:
|
||||
SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS', '360')
|
||||
)
|
||||
# XFA 字段拆分规则资源上限(阶段 1:matcher 引擎与 RE2 安全执行)
|
||||
XFA_SPLIT_MAX_RULES_PER_SET = int(os.getenv('XFA_SPLIT_MAX_RULES_PER_SET', '32'))
|
||||
XFA_SPLIT_MAX_RULE_SETS = int(os.getenv('XFA_SPLIT_MAX_RULE_SETS', '64'))
|
||||
XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH = int(os.getenv('XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH', '128'))
|
||||
XFA_SPLIT_MAX_REGEX_GROUPS = int(os.getenv('XFA_SPLIT_MAX_REGEX_GROUPS', '5'))
|
||||
XFA_SPLIT_MAX_PREFIX_LENGTH = int(os.getenv('XFA_SPLIT_MAX_PREFIX_LENGTH', '64'))
|
||||
XFA_SPLIT_MAX_INPUT_LENGTH = int(os.getenv('XFA_SPLIT_MAX_INPUT_LENGTH', '32768'))
|
||||
XFA_SPLIT_REGEX_TIMEOUT_MS = int(os.getenv('XFA_SPLIT_REGEX_TIMEOUT_MS', '50'))
|
||||
# EML 附件提取安全上限(阶段一对齐:只抽取文本,不执行宏/脚本)
|
||||
# parser v6:阶段二附件派生 FileAsset + Document/Candidate;相对 v5 须强制重解析
|
||||
# parser v5:mixed 保留独立 HTML 段 + 附件型 alternative 可提取正文
|
||||
|
||||
@@ -671,7 +671,16 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
run.phase = 'waiting_layout'
|
||||
record_run_progress(run=run, event_code='layout_parsing_started', commit=False)
|
||||
db.session.commit()
|
||||
finish_job(job.id, result={'run_no': run.run_no, 'waiting_layout': True}, message='等待附件版面解析', owned_attempt=owned_attempt)
|
||||
finish_job(
|
||||
job.id,
|
||||
result={
|
||||
'run_no': run.run_no,
|
||||
'waiting_layout': True,
|
||||
'handoff_status': 'deferred_to_layout',
|
||||
},
|
||||
message='已转交附件版面解析,完成后自动创建后继订单识别任务',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
if layout_issues:
|
||||
complete_input_freeze(run)
|
||||
|
||||
@@ -10,6 +10,7 @@ services/shipping_notice/audit_query_service.py
|
||||
任务工作台时间线按 task_no 种子 + 关联键扩张,不另建事件表。
|
||||
敏感 before/after/diff 与 XFA 完整快照仅当调用方具备 shipping_notice.audit_sensitive_read;
|
||||
普通导出仅脱敏摘要,禁止完整密文/明文;支持 event_type_group 与关联键筛选;
|
||||
另支持 XFA 视觉/拆分事件分组、profile_id、binding_id 过滤;
|
||||
PostgreSQL 清理前 set_config purge GUC;XFA 快照到期清理使用独立 GUC。
|
||||
"""
|
||||
|
||||
@@ -21,7 +22,7 @@ import json
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import delete, or_, text
|
||||
from sqlalchemy import String, cast, delete, or_, text
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ServiceUnavailableError, ValidationError
|
||||
@@ -46,6 +47,35 @@ from app.services.shipping_notice.progress_audit_contract import (
|
||||
PROCESS_GATE_AUDIT_EVENT_TYPES,
|
||||
REVIEW_WORKBENCH_AUDIT_EVENT_TYPES,
|
||||
WORKFLOW_NODE_AUDIT_EVENT_TYPES,
|
||||
XFA_PROGRESS_EVENT_CODES,
|
||||
)
|
||||
|
||||
# XFA 视觉绑定 / 拆分 / 统一迁移相关审计事件(管理端筛选分组)。
|
||||
XFA_VISUAL_BINDING_AUDIT_EVENT_TYPES: frozenset[str] = frozenset({
|
||||
'xfa_visual_binding_suggested',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
})
|
||||
XFA_SPLIT_AUDIT_EVENT_TYPES: frozenset[str] = frozenset({
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_split_rule_previewed',
|
||||
'xfa_split_rule_validated',
|
||||
'xfa_split_rule_confirmed',
|
||||
'xfa_split_segment_created',
|
||||
'xfa_split_segment_updated',
|
||||
'xfa_split_segment_deleted',
|
||||
'xfa_segment_mapping_updated',
|
||||
})
|
||||
XFA_UNIFIED_AUDIT_EVENT_TYPES: frozenset[str] = (
|
||||
XFA_VISUAL_BINDING_AUDIT_EVENT_TYPES
|
||||
| XFA_SPLIT_AUDIT_EVENT_TYPES
|
||||
| frozenset({
|
||||
'order_profile_unified_migration_dry_run',
|
||||
'order_profile_unified_migration_executed',
|
||||
'xfa_profile_draft_saved',
|
||||
'xfa_mapping_saved',
|
||||
})
|
||||
)
|
||||
|
||||
# 关联链可追溯的稳定业务键(与前端审计中心筛选对齐)。
|
||||
@@ -325,6 +355,14 @@ def _apply_filters(query, *, filters: dict[str, Any]):
|
||||
query = query.filter(ShippingAuditEvent.event_type.in_(sorted(REVIEW_WORKBENCH_AUDIT_EVENT_TYPES)))
|
||||
elif event_type_group in {'formal_task_edit', 'formal_task'}:
|
||||
query = query.filter(ShippingAuditEvent.event_type.in_(sorted(FORMAL_TASK_EDIT_AUDIT_EVENT_TYPES)))
|
||||
elif event_type_group in {'order_task_progress', 'order_task', 'shipping_order_task'}:
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
ORDER_TASK_PROGRESS_AUDIT_EVENT_TYPES,
|
||||
)
|
||||
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(ORDER_TASK_PROGRESS_AUDIT_EVENT_TYPES))
|
||||
)
|
||||
elif event_type_group in {'chat_workbench', 'chat'}:
|
||||
query = query.filter(ShippingAuditEvent.event_type.in_(sorted(CHAT_WORKBENCH_AUDIT_EVENT_TYPES)))
|
||||
elif event_type_group in {'process_gate', 'process_gates'}:
|
||||
@@ -363,6 +401,21 @@ def _apply_filters(query, *, filters: dict[str, Any]):
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(ORDER_EMAIL_ADJUDICATION_AUDIT_EVENT_TYPES))
|
||||
)
|
||||
elif event_type_group in {'xfa_visual', 'xfa_visual_binding', 'visual_binding'}:
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(XFA_VISUAL_BINDING_AUDIT_EVENT_TYPES))
|
||||
)
|
||||
elif event_type_group in {'xfa_split', 'xfa_split_rule', 'split_rule'}:
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(XFA_SPLIT_AUDIT_EVENT_TYPES))
|
||||
)
|
||||
elif event_type_group in {'xfa_unified', 'xfa_profile', 'xfa'}:
|
||||
# 统一视觉/拆分 + 进度白名单中的 XFA 事件。
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(
|
||||
sorted(set(XFA_UNIFIED_AUDIT_EVENT_TYPES) | set(XFA_PROGRESS_EVENT_CODES))
|
||||
)
|
||||
)
|
||||
if filters.get('event_type'):
|
||||
query = query.filter(ShippingAuditEvent.event_type == str(filters['event_type'])[:64])
|
||||
if filters.get('actor_type'):
|
||||
@@ -383,6 +436,37 @@ def _apply_filters(query, *, filters: dict[str, Any]):
|
||||
query = query.filter(ShippingAuditEvent.aggregate_type == str(filters['aggregate_type'])[:64])
|
||||
if filters.get('aggregate_id'):
|
||||
query = query.filter(ShippingAuditEvent.aggregate_id == str(filters['aggregate_id'])[:128])
|
||||
# Profile / binding:aggregate_id 常为 profile_id;binding_id 落在 metadata/context_refs。
|
||||
profile_id = str(filters.get('profile_id') or '').strip()
|
||||
if profile_id:
|
||||
query = query.filter(ShippingAuditEvent.aggregate_id == profile_id[:128])
|
||||
binding_id = str(filters.get('binding_id') or '').strip()
|
||||
if binding_id:
|
||||
like = f'%{binding_id[:64]}%'
|
||||
query = query.filter(
|
||||
or_(
|
||||
cast(ShippingAuditEvent.metadata_json, String).ilike(like),
|
||||
cast(ShippingAuditEvent.context_refs_json, String).ilike(like),
|
||||
)
|
||||
)
|
||||
revision_no = str(filters.get('revision_no') or '').strip()
|
||||
if revision_no:
|
||||
like = f'%"revision_no": {revision_no}%'
|
||||
query = query.filter(
|
||||
or_(
|
||||
cast(ShippingAuditEvent.metadata_json, String).ilike(like),
|
||||
cast(ShippingAuditEvent.context_refs_json, String).ilike(like),
|
||||
)
|
||||
)
|
||||
segment_id = str(filters.get('segment_id') or '').strip()
|
||||
if segment_id:
|
||||
like = f'%{segment_id[:64]}%'
|
||||
query = query.filter(
|
||||
or_(
|
||||
cast(ShippingAuditEvent.metadata_json, String).ilike(like),
|
||||
cast(ShippingAuditEvent.context_refs_json, String).ilike(like),
|
||||
)
|
||||
)
|
||||
# Candidate 编号写入 aggregate_id(aggregate_type=shipping_notice_candidate)。
|
||||
candidate_no = str(filters.get('candidate_no') or '').strip()
|
||||
if candidate_no:
|
||||
|
||||
@@ -44,6 +44,8 @@ XFA_REDACTED_SUMMARY_KEYS = frozenset({
|
||||
'header_mapping_count',
|
||||
'line_mapping_count',
|
||||
'bound_field_count',
|
||||
'binding_count',
|
||||
'split_rule_count',
|
||||
'mirror_collection_count',
|
||||
'xfa_document_kind',
|
||||
'analysis_id',
|
||||
|
||||
@@ -39,6 +39,7 @@ CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = (
|
||||
'xfa_profile_blind_approved',
|
||||
'xfa_pilot_allowlist',
|
||||
'xfa_evidence_integrity',
|
||||
'xfa_unified_profile_snapshot',
|
||||
)
|
||||
|
||||
# 检查项失败 → 稳定用户原因码(对话 / Process Gate / 复核摘要共用)。
|
||||
@@ -56,6 +57,7 @@ CANDIDATE_QUALIFICATION_GATE_REASON_CODES: Final[dict[str, str]] = {
|
||||
'xfa_profile_blind_approved': 'xfa_profile_not_blind_approved',
|
||||
'xfa_pilot_allowlist': 'xfa_allowlist_unconfigured',
|
||||
'xfa_evidence_integrity': 'xfa_evidence_incomplete',
|
||||
'xfa_unified_profile_snapshot': 'xfa_visual_coverage_insufficient',
|
||||
}
|
||||
|
||||
# 偏向「需人工轻量确认」而非硬阻断的原因码。
|
||||
|
||||
@@ -295,6 +295,7 @@ def evaluate_candidate_qualification(
|
||||
'xfa_profile_blind_approved': bool(xfa_eval['gates']['xfa_profile_blind_approved']),
|
||||
'xfa_pilot_allowlist': bool(xfa_eval['gates']['xfa_pilot_allowlist']),
|
||||
'xfa_evidence_integrity': bool(xfa_eval['gates']['xfa_evidence_integrity']),
|
||||
'xfa_unified_profile_snapshot': bool(xfa_eval['gates'].get('xfa_unified_profile_snapshot', True)),
|
||||
}
|
||||
failed = [key for key in CANDIDATE_QUALIFICATION_GATE_KEYS if not gates.get(key)]
|
||||
|
||||
@@ -500,6 +501,20 @@ def recalculate_candidate_qualification(
|
||||
},
|
||||
source='candidate_qualification',
|
||||
)
|
||||
# [BE-06] 资格重算后同步 OT 统一 stage,避免投影长期停在 candidate_creating。
|
||||
try:
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
sync_order_task_stage_for_candidate,
|
||||
)
|
||||
|
||||
sync_order_task_stage_for_candidate(candidate=candidate, evaluation=evaluation)
|
||||
except Exception as exc: # noqa: BLE001 — 资格主路径不得因 OT 同步失败回滚
|
||||
import logging
|
||||
|
||||
logging.getLogger(__name__).warning(
|
||||
'sync_order_task_stage_for_candidate failed after qualification: %s',
|
||||
exc,
|
||||
)
|
||||
return evaluation
|
||||
|
||||
|
||||
@@ -596,6 +611,7 @@ def _evaluate_xfa_auto_create_gates(
|
||||
'xfa_profile_blind_approved': True,
|
||||
'xfa_pilot_allowlist': True,
|
||||
'xfa_evidence_integrity': True,
|
||||
'xfa_unified_profile_snapshot': True,
|
||||
}
|
||||
if not is_xfa:
|
||||
return {
|
||||
@@ -712,22 +728,64 @@ def _evaluate_xfa_auto_create_gates(
|
||||
evidence_ok = False
|
||||
evidence_reason = 'xfa_cross_check_failed'
|
||||
|
||||
# [STEP 6] 统一 Profile 快照指标:视觉/证据/镜像须 100%,checksum 须与路由一致。
|
||||
# 指标来源优先 route.xfa_unified_metrics,其次 structured / parser_trace 顶层率字段。
|
||||
unified_metrics = route.get('xfa_unified_metrics')
|
||||
if not isinstance(unified_metrics, dict):
|
||||
structured = getattr(candidate, 'structured_result_json', None)
|
||||
if isinstance(structured, dict):
|
||||
nested = structured.get('_hxops_xfa_unified_metrics')
|
||||
unified_metrics = nested if isinstance(nested, dict) else None
|
||||
if not isinstance(unified_metrics, dict):
|
||||
# 兼容 parser_trace 直接携带 visual/evidence 率(阶段 6 契约)。
|
||||
trace_metrics = {
|
||||
key: parser_trace.get(key)
|
||||
for key in (
|
||||
'visual_coverage_rate',
|
||||
'evidence_retention_rate',
|
||||
'mirror_consistency_rate',
|
||||
'profile_checksum',
|
||||
)
|
||||
if parser_trace.get(key) is not None
|
||||
}
|
||||
if any(k.endswith('_rate') for k in trace_metrics):
|
||||
unified_metrics = trace_metrics
|
||||
unified_ok = True
|
||||
unified_reason = None
|
||||
if isinstance(unified_metrics, dict):
|
||||
for metric_key, reason_code in (
|
||||
('visual_coverage_rate', 'xfa_visual_coverage_insufficient'),
|
||||
('evidence_retention_rate', 'xfa_evidence_retention_insufficient'),
|
||||
('mirror_consistency_rate', 'xfa_mirror_consistency_insufficient'),
|
||||
):
|
||||
raw_rate = unified_metrics.get(metric_key)
|
||||
if raw_rate is not None and float(raw_rate) < 1.0:
|
||||
unified_ok = False
|
||||
unified_reason = reason_code
|
||||
break
|
||||
metrics_checksum = str(unified_metrics.get('profile_checksum') or '').strip()
|
||||
if unified_ok and metrics_checksum and checksum and metrics_checksum != checksum:
|
||||
unified_ok = False
|
||||
unified_reason = 'xfa_profile_checksum_mismatch'
|
||||
|
||||
gates = {
|
||||
'xfa_auto_create_policy': policy_ok,
|
||||
'xfa_profile_blind_approved': blind_ok,
|
||||
'xfa_pilot_allowlist': allowlist_ok,
|
||||
'xfa_evidence_integrity': evidence_ok,
|
||||
'xfa_unified_profile_snapshot': unified_ok,
|
||||
}
|
||||
reason_by_gate = {
|
||||
'xfa_auto_create_policy': policy_reason,
|
||||
'xfa_profile_blind_approved': blind_reason,
|
||||
'xfa_pilot_allowlist': allowlist_reason,
|
||||
'xfa_evidence_integrity': evidence_reason,
|
||||
'xfa_unified_profile_snapshot': unified_reason,
|
||||
}
|
||||
|
||||
# shadow:在其余试点门禁(除真实建单开关外)满足时记录 would_auto_create。
|
||||
shadow_base_ok = (
|
||||
blind_ok and allowlist_ok and evidence_ok and not emergency_stop
|
||||
blind_ok and allowlist_ok and evidence_ok and unified_ok and not emergency_stop
|
||||
)
|
||||
shadow_would = bool(shadow and shadow_base_ok)
|
||||
|
||||
@@ -759,6 +817,21 @@ def _evaluate_xfa_auto_create_gates(
|
||||
'xfa_header_field_count': header_count,
|
||||
'xfa_line_row_count': line_count,
|
||||
'xfa_cross_check_keys': sorted(str(k) for k in cross_checks.keys()),
|
||||
'xfa_visual_coverage_rate': (
|
||||
float(unified_metrics.get('visual_coverage_rate'))
|
||||
if isinstance(unified_metrics, dict) and unified_metrics.get('visual_coverage_rate') is not None
|
||||
else None
|
||||
),
|
||||
'xfa_evidence_retention_rate': (
|
||||
float(unified_metrics.get('evidence_retention_rate'))
|
||||
if isinstance(unified_metrics, dict) and unified_metrics.get('evidence_retention_rate') is not None
|
||||
else None
|
||||
),
|
||||
'xfa_mirror_consistency_rate': (
|
||||
float(unified_metrics.get('mirror_consistency_rate'))
|
||||
if isinstance(unified_metrics, dict) and unified_metrics.get('mirror_consistency_rate') is not None
|
||||
else None
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
backend/app/services/shipping_notice/document_layout/lifecycle.py
|
||||
|
||||
用途:管理 ShippingOrderDocument 的版面版本、checksum、大小门禁和当前成功快照。
|
||||
依赖:ShippingDocumentLayoutVersion、Flask 配置、SQLAlchemy Session、workflow_ledger_service
|
||||
依赖:ShippingDocumentLayoutVersion、ShippingXfaStructureAnalysis、Flask 配置、SQLAlchemy Session、workflow_ledger_service
|
||||
(claim/complete/recovery 尽力同步 WorkflowItem,缺 Item 不阻断版面收口)。
|
||||
逻辑:相同内容/parser/checksum 幂等复用;失败版本保留审计,只有可用终态更新 Document 当前引用。
|
||||
逻辑:相同内容/parser/checksum 幂等复用;XFA 复用时同步本地化结构分析身份;
|
||||
失败版本保留审计,只有可用终态更新 Document 当前引用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,7 +21,12 @@ from flask import current_app
|
||||
from sqlalchemy import and_, func, or_, update
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import ShippingDocumentLayoutVersion, ShippingOrderDocument, ShippingOrderIntake
|
||||
from app.models import (
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingXfaStructureAnalysis,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -296,22 +302,93 @@ def _clone_reusable_layout_for_document(
|
||||
将同一所有者的已完成布局快照本地化到目标 Document。
|
||||
|
||||
LayoutVersion 的 document_id 是不可跨文档共享的外键语义;相同内容只能复用
|
||||
已冻结 payload,不能让目标 Document 指向源 Document 的版本记录。
|
||||
已冻结 payload,不能让目标 Document 指向源 Document 的版本记录。XFA 快照还必须
|
||||
为目标 Document 克隆独立 StructureAnalysis,并重写快照 analysis_id;源证据缺失或
|
||||
身份不一致时返回 None,让调用方重新排队解析。
|
||||
|
||||
Args:
|
||||
document: 待接收复用结果的目标 Document。
|
||||
reusable: 同一所有者、同内容且 parser 身份一致的源 LayoutVersion。
|
||||
|
||||
Returns:
|
||||
目标 Document 专属 LayoutVersion;无法安全本地化时返回 None。
|
||||
"""
|
||||
payload = reusable.payload_json
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
copied_payload = dict(payload)
|
||||
copied_payload = json.loads(json.dumps(payload, ensure_ascii=True))
|
||||
copied_payload['status'] = str(reusable.status or copied_payload.get('status') or 'failed')
|
||||
copied_payload.setdefault('provider', reusable.parser_name or LAYOUT_PARSER_NAME)
|
||||
copied_payload.setdefault('provider_version', reusable.parser_version)
|
||||
copied_payload.setdefault('backend', reusable.backend or LAYOUT_BACKEND)
|
||||
copied_payload.setdefault('snapshot_version', reusable.contract_version or LAYOUT_CONTRACT_VERSION)
|
||||
return record_inline_layout_snapshot(
|
||||
|
||||
target_analysis: ShippingXfaStructureAnalysis | None = None
|
||||
if str(copied_payload.get('provider') or '') == 'xfa':
|
||||
capability = (
|
||||
copied_payload.get('xfa_capability')
|
||||
if isinstance(copied_payload.get('xfa_capability'), dict)
|
||||
else {}
|
||||
)
|
||||
source_analysis_id = capability.get('structure_analysis_id')
|
||||
source_analysis = (
|
||||
db.session.get(ShippingXfaStructureAnalysis, int(source_analysis_id))
|
||||
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 '')
|
||||
):
|
||||
return None
|
||||
|
||||
# [STEP 1] Analysis 是 document-scoped 证据;克隆安全摘要并先取得目标主键。
|
||||
target_analysis = ShippingXfaStructureAnalysis(
|
||||
document_id=int(document.id),
|
||||
layout_version_id=None,
|
||||
source_content_hash=str(document.content_hash or '').lower(),
|
||||
document_kind=source_analysis.document_kind,
|
||||
analysis_status='ready',
|
||||
template_packet_checksum=source_analysis.template_packet_checksum,
|
||||
datasets_packet_checksum=source_analysis.datasets_packet_checksum,
|
||||
dataset_structure_fingerprint=source_analysis.dataset_structure_fingerprint,
|
||||
packet_checksums_json=dict(source_analysis.packet_checksums_json or {}),
|
||||
stats_json=dict(source_analysis.stats_json or {}),
|
||||
security_summary_json=dict(source_analysis.security_summary_json or {}),
|
||||
tree_summary_json=dict(source_analysis.tree_summary_json or {}),
|
||||
error_code=None,
|
||||
route_reason=source_analysis.route_reason,
|
||||
encrypted_snapshot_ref=None,
|
||||
parser_identity=source_analysis.parser_identity,
|
||||
contract_version=source_analysis.contract_version,
|
||||
finished_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(target_analysis)
|
||||
db.session.flush()
|
||||
capability['structure_analysis_id'] = int(target_analysis.id)
|
||||
copied_payload['xfa_capability'] = capability
|
||||
if isinstance(copied_payload.get('capability'), dict):
|
||||
copied_payload['capability']['structure_analysis_id'] = int(target_analysis.id)
|
||||
|
||||
# [STEP 2] 先记录目标 Layout,再反向绑定 Analysis,保持两条证据身份一致。
|
||||
localized = record_inline_layout_snapshot(
|
||||
document,
|
||||
copied_payload,
|
||||
parser_key=str(reusable.parser_key or current_layout_parser_key()),
|
||||
)
|
||||
if target_analysis is not None:
|
||||
if str(localized.status or '') not in CURRENT_LAYOUT_STATUSES:
|
||||
db.session.delete(target_analysis)
|
||||
return None
|
||||
target_analysis.layout_version_id = int(localized.id)
|
||||
return localized
|
||||
|
||||
|
||||
def schedule_layout_version(
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_acroform.py
|
||||
|
||||
用途:读取 AcroForm 字段值并生成与 datasets 叶子节点的对账候选。
|
||||
依赖:pypdf、xfa_dataset.XfaDatasetAnalysis。
|
||||
逻辑:由 xfa_analysis / xfa_validation 调用;按短名聚合多实例值供行对齐对账;
|
||||
此处只做候选与分组,不因 display formatting 差异判失败。
|
||||
用途:读取 AcroForm 字段值/Widget 几何,并生成与 datasets 叶子节点的对账与路径候选。
|
||||
依赖:pypdf、xfa_dataset.XfaDatasetAnalysis、xfa_contract.hash_data_path。
|
||||
逻辑:由 xfa_analysis、xfa_visual_binding、xfa_validation 调用;按短名聚合多实例值
|
||||
供行对齐对账;Widget 摘要含页码与归一化 bbox,供统一视觉绑定评分。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
@@ -16,9 +17,14 @@ from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from pypdf import PdfReader
|
||||
from pypdf.generic import ArrayObject
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import hash_data_path
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import XfaDatasetAnalysis, mask_value_for_dto
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import (
|
||||
XfaDatasetAnalysis,
|
||||
_path_id_for,
|
||||
mask_value_for_dto,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -31,6 +37,19 @@ class XfaAcroformField:
|
||||
value_masked: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaAcroformWidget:
|
||||
"""可定位 AcroForm Widget 摘要:页码、归一化 bbox、SOM/短名与展示值。"""
|
||||
|
||||
widget_id: str
|
||||
qualified_name: str
|
||||
short_name: str
|
||||
page_no: int
|
||||
normalized_bbox: dict[str, float]
|
||||
value: str
|
||||
value_masked: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaReconciliationCandidate:
|
||||
"""datasets 叶子与 AcroForm 字段的对账候选。"""
|
||||
@@ -78,6 +97,271 @@ def _normalize_key(value: str) -> str:
|
||||
return re.sub(r'[^a-z0-9]+', '', text)
|
||||
|
||||
|
||||
def _widget_id_for(qualified_name: str, page_no: int) -> str:
|
||||
"""生成 Widget 稳定 ID(不含 SOM 明文外传)。"""
|
||||
digest = hashlib.sha256(f'{qualified_name}:{page_no}'.encode('utf-8')).hexdigest()[:20]
|
||||
return f'wgt-{digest}'
|
||||
|
||||
|
||||
def _pdf_rect_to_normalized_bbox(
|
||||
rect: ArrayObject | list[Any],
|
||||
*,
|
||||
page_width: float,
|
||||
page_height: float,
|
||||
) -> dict[str, float] | None:
|
||||
"""
|
||||
将 PDF /Rect(左下原点)转为页面相对框(左上原点,0..1)。
|
||||
|
||||
Args:
|
||||
rect: PDF Rect 数组 [x0, y0, x1, y1]。
|
||||
page_width: 页宽(pt)。
|
||||
page_height: 页高(pt)。
|
||||
|
||||
Returns:
|
||||
归一化 bbox;非法或零面积时返回 None。
|
||||
"""
|
||||
if page_width <= 0 or page_height <= 0:
|
||||
return None
|
||||
try:
|
||||
x0, y0, x1, y1 = [float(item) for item in rect[:4]]
|
||||
except (TypeError, ValueError, IndexError):
|
||||
return None
|
||||
norm_x0 = max(0.0, min(1.0, x0 / page_width))
|
||||
norm_x1 = max(0.0, min(1.0, x1 / page_width))
|
||||
norm_y0 = max(0.0, min(1.0, 1.0 - (y1 / page_height)))
|
||||
norm_y1 = max(0.0, min(1.0, 1.0 - (y0 / page_height)))
|
||||
if norm_x1 <= norm_x0 or norm_y1 <= norm_y0:
|
||||
return None
|
||||
return {'x0': norm_x0, 'y0': norm_y0, 'x1': norm_x1, 'y1': norm_y1}
|
||||
|
||||
|
||||
def _field_display_value(field_obj: dict[str, Any]) -> str:
|
||||
"""从 AcroForm 字段字典读取 /V 展示值。"""
|
||||
value = field_obj.get('/V')
|
||||
if value is None:
|
||||
return ''
|
||||
return str(getattr(value, 'name', value) or value).strip()
|
||||
|
||||
|
||||
def _resolve_widget_page_no(reader: PdfReader, annot_obj: dict[str, Any], fallback_page_no: int) -> int:
|
||||
"""
|
||||
解析 Widget 所属页码。
|
||||
|
||||
核心逻辑:优先读 /P 页引用;否则使用遍历页码。
|
||||
"""
|
||||
page_ref = annot_obj.get('/P')
|
||||
if page_ref is not None:
|
||||
for index, page in enumerate(reader.pages):
|
||||
if page.indirect_reference == page_ref:
|
||||
return index + 1
|
||||
return int(fallback_page_no)
|
||||
|
||||
|
||||
def read_acroform_widgets(pdf_bytes: bytes) -> list[XfaAcroformWidget]:
|
||||
"""
|
||||
读取 PDF AcroForm Widget 页码、归一化 bbox、SOM/短名与展示值。
|
||||
|
||||
核心逻辑:遍历每页 /Annots 中 /Subtype=/Widget;补充 get_fields 中带 /Rect 的字段;
|
||||
坐标转为 0..1 左上原点,与 PDFium 渲染画布一致。
|
||||
|
||||
Args:
|
||||
pdf_bytes: 原始 PDF 字节。
|
||||
|
||||
Returns:
|
||||
可定位 Widget 列表;无 Widget 或解析失败时返回空列表。
|
||||
"""
|
||||
try:
|
||||
reader = PdfReader(BytesIO(pdf_bytes), strict=False)
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
seen: set[tuple[str, int]] = set()
|
||||
widgets: list[XfaAcroformWidget] = []
|
||||
|
||||
# [STEP 1] 页面 Widget 注解(含几何)
|
||||
for page_index, page in enumerate(reader.pages):
|
||||
page_no = page_index + 1
|
||||
try:
|
||||
width = float(page.mediabox.width)
|
||||
height = float(page.mediabox.height)
|
||||
except (TypeError, ValueError, AttributeError):
|
||||
continue
|
||||
annots = page.get('/Annots')
|
||||
if not annots:
|
||||
continue
|
||||
for annot_ref in annots:
|
||||
try:
|
||||
annot_obj = annot_ref.get_object()
|
||||
except Exception:
|
||||
continue
|
||||
if not isinstance(annot_obj, dict):
|
||||
continue
|
||||
subtype = str(annot_obj.get('/Subtype') or '')
|
||||
if subtype != '/Widget':
|
||||
continue
|
||||
rect = annot_obj.get('/Rect')
|
||||
if rect is None:
|
||||
continue
|
||||
bbox = _pdf_rect_to_normalized_bbox(rect, page_width=width, page_height=height)
|
||||
if bbox is None:
|
||||
continue
|
||||
qualified_name = str(annot_obj.get('/T') or annot_obj.get('/TM') or '').strip()
|
||||
if not qualified_name:
|
||||
parent = annot_obj.get('/Parent')
|
||||
if parent is not None:
|
||||
try:
|
||||
parent_obj = parent.get_object()
|
||||
if isinstance(parent_obj, dict):
|
||||
qualified_name = str(parent_obj.get('/T') or '').strip()
|
||||
except Exception:
|
||||
qualified_name = ''
|
||||
if not qualified_name:
|
||||
qualified_name = f'widget.page{page_no}.{len(widgets)}'
|
||||
short_name = _local_tail(qualified_name)
|
||||
value = _field_display_value(annot_obj)
|
||||
key = (qualified_name, page_no)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
widgets.append(XfaAcroformWidget(
|
||||
widget_id=_widget_id_for(qualified_name, page_no),
|
||||
qualified_name=qualified_name,
|
||||
short_name=short_name,
|
||||
page_no=page_no,
|
||||
normalized_bbox=bbox,
|
||||
value=value,
|
||||
value_masked=mask_value_for_dto(value),
|
||||
))
|
||||
|
||||
# [STEP 2] get_fields 补充(部分 XFA 仅在此暴露 /Rect)
|
||||
try:
|
||||
raw_fields = reader.get_fields() or {}
|
||||
except Exception:
|
||||
raw_fields = {}
|
||||
for qualified_name, field_obj in raw_fields.items():
|
||||
if not isinstance(field_obj, dict):
|
||||
continue
|
||||
rect = field_obj.get('/Rect')
|
||||
if rect is None:
|
||||
continue
|
||||
page_no = _resolve_widget_page_no(reader, field_obj, fallback_page_no=1)
|
||||
try:
|
||||
page = reader.pages[page_no - 1]
|
||||
width = float(page.mediabox.width)
|
||||
height = float(page.mediabox.height)
|
||||
except (IndexError, TypeError, ValueError, AttributeError):
|
||||
continue
|
||||
bbox = _pdf_rect_to_normalized_bbox(rect, page_width=width, page_height=height)
|
||||
if bbox is None:
|
||||
continue
|
||||
qname = str(qualified_name)
|
||||
key = (qname, page_no)
|
||||
if key in seen:
|
||||
continue
|
||||
value = _field_display_value(field_obj)
|
||||
if not value:
|
||||
continue
|
||||
seen.add(key)
|
||||
short_name = _local_tail(qname)
|
||||
widgets.append(XfaAcroformWidget(
|
||||
widget_id=_widget_id_for(qname, page_no),
|
||||
qualified_name=qname,
|
||||
short_name=short_name,
|
||||
page_no=page_no,
|
||||
normalized_bbox=bbox,
|
||||
value=value,
|
||||
value_masked=mask_value_for_dto(value),
|
||||
))
|
||||
|
||||
return widgets
|
||||
|
||||
|
||||
def serialize_locatable_widget_summaries(widgets: list[XfaAcroformWidget]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
序列化可定位 Widget 轻量摘要(分析快照用,不含展示值明文)。
|
||||
|
||||
Args:
|
||||
widgets: Widget 列表。
|
||||
|
||||
Returns:
|
||||
含 widget_id、page_no、bbox、short_name、has_value 的摘要列表。
|
||||
"""
|
||||
return [
|
||||
{
|
||||
'widget_id': item.widget_id,
|
||||
'page_no': int(item.page_no),
|
||||
'short_name': item.short_name,
|
||||
'normalized_bbox': dict(item.normalized_bbox),
|
||||
'has_value': bool(item.value),
|
||||
}
|
||||
for item in widgets
|
||||
]
|
||||
|
||||
|
||||
def build_widget_path_candidates(
|
||||
*,
|
||||
widget: XfaAcroformWidget,
|
||||
dataset_analysis: XfaDatasetAnalysis,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
为单个 Widget 生成 datasets 路径候选(供视觉绑定评分)。
|
||||
|
||||
核心逻辑:按 localName / 规范化短名弱匹配叶子;多命中标记 ambiguous;
|
||||
返回值供内部评分,DTO 仅含 masked 值与 path hash。
|
||||
|
||||
Args:
|
||||
widget: AcroForm Widget 摘要。
|
||||
dataset_analysis: datasets 结构分析。
|
||||
|
||||
Returns:
|
||||
路径候选列表,按 match_hint 质量降序。
|
||||
"""
|
||||
by_short: dict[str, list[tuple[str, str]]] = {}
|
||||
by_norm: dict[str, list[tuple[str, str]]] = {}
|
||||
for data_path, raw_value in dataset_analysis.leaf_values_by_path.items():
|
||||
local_name = data_path.rsplit('/', 1)[-1]
|
||||
by_short.setdefault(local_name.upper(), []).append((data_path, raw_value))
|
||||
by_norm.setdefault(_normalize_key(local_name), []).append((data_path, raw_value))
|
||||
|
||||
matches: list[dict[str, Any]] = []
|
||||
short_key = str(widget.short_name or '').upper()
|
||||
exact = by_short.get(short_key) or []
|
||||
if len(exact) == 1:
|
||||
data_path, raw_value = exact[0]
|
||||
matches.append(_path_candidate_row(data_path, raw_value, match_hint='local_name_exact'))
|
||||
elif len(exact) > 1:
|
||||
for data_path, raw_value in exact:
|
||||
matches.append(_path_candidate_row(data_path, raw_value, match_hint='local_name_ambiguous'))
|
||||
else:
|
||||
fuzzy = by_norm.get(_normalize_key(widget.short_name)) or []
|
||||
if len(fuzzy) == 1:
|
||||
data_path, raw_value = fuzzy[0]
|
||||
matches.append(_path_candidate_row(data_path, raw_value, match_hint='normalized_exact'))
|
||||
elif len(fuzzy) > 1:
|
||||
for data_path, raw_value in fuzzy:
|
||||
matches.append(_path_candidate_row(data_path, raw_value, match_hint='normalized_ambiguous'))
|
||||
|
||||
hint_rank = {
|
||||
'local_name_exact': 4,
|
||||
'normalized_exact': 3,
|
||||
'local_name_ambiguous': 2,
|
||||
'normalized_ambiguous': 1,
|
||||
}
|
||||
matches.sort(key=lambda item: hint_rank.get(str(item.get('match_hint') or ''), 0), reverse=True)
|
||||
return matches
|
||||
|
||||
|
||||
def _path_candidate_row(data_path: str, raw_value: str, *, match_hint: str) -> dict[str, Any]:
|
||||
"""构造单条路径候选内部行。"""
|
||||
return {
|
||||
'path_id': _path_id_for(data_path),
|
||||
'data_path_hash': hash_data_path(data_path),
|
||||
'dataset_value_masked': mask_value_for_dto(raw_value),
|
||||
'raw_value': raw_value,
|
||||
'match_hint': match_hint,
|
||||
}
|
||||
|
||||
|
||||
def read_acroform_fields(pdf_bytes: bytes) -> list[XfaAcroformField]:
|
||||
"""
|
||||
读取 PDF AcroForm 字段值。
|
||||
|
||||
@@ -19,7 +19,9 @@ from app.models import ShippingXfaStructureAnalysis
|
||||
from app.services.shipping_notice.document_layout.xfa_acroform import (
|
||||
build_reconciliation_candidates,
|
||||
read_acroform_fields,
|
||||
read_acroform_widgets,
|
||||
serialize_acroform_fields,
|
||||
serialize_locatable_widget_summaries,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_CONTRACT_VERSION,
|
||||
@@ -157,10 +159,12 @@ def analyze_xfa_pdf(
|
||||
dataset_nodes=dataset_analysis.nodes,
|
||||
)
|
||||
acroform_fields = read_acroform_fields(pdf_bytes)
|
||||
acroform_widgets = read_acroform_widgets(pdf_bytes)
|
||||
reconciliation = build_reconciliation_candidates(
|
||||
dataset_analysis=dataset_analysis,
|
||||
acroform_fields=acroform_fields,
|
||||
)
|
||||
widget_summaries = serialize_locatable_widget_summaries(acroform_widgets)
|
||||
packet_checksums = {item.name: item.checksum for item in packet_result.packets}
|
||||
capability = {
|
||||
'parser_identity': XFA_PARSER_IDENTITY,
|
||||
@@ -180,6 +184,8 @@ def analyze_xfa_pdf(
|
||||
'header_candidate_count': len(dataset_analysis.header_candidates),
|
||||
'collection_candidate_count': len(dataset_analysis.collection_candidates),
|
||||
'acroform_field_count': len(acroform_fields),
|
||||
'locatable_widget_count': len(acroform_widgets),
|
||||
'widget_summaries': widget_summaries[:200],
|
||||
'reconciliation_candidate_count': len(reconciliation),
|
||||
'issues': [],
|
||||
}
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_contract.py
|
||||
|
||||
用途:冻结 XFA 数据路径 Profile 的阶段 0 契约——template_mode、受控路径语法、
|
||||
结构指纹算法、资源上限、支持/拒绝矩阵、鉴别联合 definition、evidence 与安全投影。
|
||||
用途:冻结 XFA 数据路径 Profile 契约——template_mode、受控路径语法、结构指纹、
|
||||
统一字段 binding(value_binding + visual_binding)、鉴别联合 definition、
|
||||
evidence 与安全投影。
|
||||
依赖:Pydantic 2、标准库 hashlib/json/re/unicodedata;被 order_extraction_route_contract、
|
||||
error_explainability_contract、Profile 校验与后续 xfa_*.py 解析器引用。
|
||||
Profile 校验、拆分契约与后续 xfa_*.py 解析器引用。
|
||||
逻辑:本模块只定义契约与纯函数校验,不读 PDF/XML、不执行脚本、不接正式流量;
|
||||
coordinate 行为保持不变,xfa_dataset 定义不得混入坐标 region。
|
||||
禁止混入 coordinate 表区键,但允许 visual_binding 归一化框作为视觉证据。
|
||||
header_mappings / line_mapping.fields 仅作**迁移输入**解析(order_profile_unified_migration);
|
||||
正式 validate/save/extract 须 bindings-only,legacy-only 或 dual-source 均 fail-closed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
@@ -167,6 +169,15 @@ XFA_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_split_rule_invalid',
|
||||
'xfa_split_field_conflict',
|
||||
'xfa_split_mirror_mismatch',
|
||||
# 统一视觉绑定 / 发布门禁 / 运行时再验(阶段 5–6)
|
||||
'xfa_visual_bindings_required',
|
||||
'xfa_visual_binding_incomplete',
|
||||
'xfa_visual_coverage_insufficient',
|
||||
'xfa_evidence_retention_insufficient',
|
||||
'xfa_mirror_consistency_insufficient',
|
||||
'xfa_profile_checksum_mismatch',
|
||||
'xfa_visual_not_publishable',
|
||||
'xfa_split_rule_unconfirmed',
|
||||
})
|
||||
|
||||
XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
@@ -193,10 +204,16 @@ XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_cross_check_completed',
|
||||
'xfa_structure_signature_frozen',
|
||||
'xfa_audit_snapshot_viewed',
|
||||
# 统一视觉绑定(阶段 2)
|
||||
'xfa_visual_binding_suggested',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
# 字段拆分映射审计(阶段 3/7)
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_split_rule_previewed',
|
||||
'xfa_split_rule_validated',
|
||||
'xfa_split_rule_confirmed',
|
||||
'xfa_split_segment_created',
|
||||
'xfa_split_segment_updated',
|
||||
'xfa_split_segment_deleted',
|
||||
@@ -208,6 +225,9 @@ XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_profile_published',
|
||||
'xfa_profile_formal_extracted',
|
||||
'xfa_profile_needs_review',
|
||||
# 统一 binding 一次性迁移(阶段 7)
|
||||
'order_profile_unified_migration_dry_run',
|
||||
'order_profile_unified_migration_executed',
|
||||
})
|
||||
|
||||
# Profile / Run / 分析 DTO 禁止键(大小写不敏感);完整 XML / PDF bytes / 存储地址不得外泄。
|
||||
@@ -294,7 +314,12 @@ class XfaSourceContract(XfaContractModel):
|
||||
|
||||
|
||||
class XfaHeaderMapping(XfaContractModel):
|
||||
"""Header 字段:Schema field ↔ 受控 datasets 路径。"""
|
||||
"""
|
||||
Header 字段:Schema field ↔ 受控 datasets 路径。
|
||||
|
||||
**迁移输入兼容**:仅供 unified migration 读取旧 definition;正式 save/validate/extract
|
||||
禁止单独依赖本结构,须先 Execute 迁移为 bindings[]。
|
||||
"""
|
||||
|
||||
mapping_id: str = Field(min_length=1, max_length=64)
|
||||
field_id: str = Field(min_length=1, max_length=64)
|
||||
@@ -313,7 +338,11 @@ class XfaHeaderMapping(XfaContractModel):
|
||||
|
||||
|
||||
class XfaLineFieldMapping(XfaContractModel):
|
||||
"""明细行字段映射。"""
|
||||
"""
|
||||
明细行字段映射。
|
||||
|
||||
**迁移输入兼容**:见 XfaHeaderMapping;正式路径禁止 legacy-only。
|
||||
"""
|
||||
|
||||
mapping_id: str = Field(min_length=1, max_length=64)
|
||||
field_id: str = Field(min_length=1, max_length=64)
|
||||
@@ -332,7 +361,12 @@ class XfaLineFieldMapping(XfaContractModel):
|
||||
|
||||
|
||||
class XfaLineMapping(XfaContractModel):
|
||||
"""权威明细集合路径及行内字段映射。"""
|
||||
"""
|
||||
权威明细集合路径及行内字段映射。
|
||||
|
||||
row_path 为正式契约必填;fields 列表为**迁移输入兼容**(同 header_mappings),
|
||||
Execute 后须为空,正式值绑定仅经 bindings[]。
|
||||
"""
|
||||
|
||||
row_path: str = Field(min_length=1, max_length=512)
|
||||
fields: list[XfaLineFieldMapping] = Field(default_factory=list)
|
||||
@@ -353,25 +387,166 @@ class XfaCrossChecks(XfaContractModel):
|
||||
total_amount_policy: XfaTotalAmountPolicy = 'must_equal_line_sum'
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 统一字段绑定(value_binding + visual_binding)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
XfaValueBindingType = Literal['xfa_dataset', 'pdf_coordinate', 'ocr_coordinate']
|
||||
XfaVisualBindingSource = Literal[
|
||||
'acroform_widget',
|
||||
'manual_draw',
|
||||
'migrated_coordinate',
|
||||
'suggested',
|
||||
]
|
||||
XfaVisualBindingStatus = Literal['suggested', 'confirmed', 'rejected', 'unavailable']
|
||||
XfaBindingScope = Literal['header', 'line']
|
||||
|
||||
|
||||
class XfaNormalizedBBox(XfaContractModel):
|
||||
"""页面相对坐标框(0..1);仅作视觉证据,不作 XFA 正式取值来源。"""
|
||||
|
||||
x0: float = Field(ge=0.0, le=1.0)
|
||||
y0: float = Field(ge=0.0, le=1.0)
|
||||
x1: float = Field(ge=0.0, le=1.0)
|
||||
y1: float = Field(ge=0.0, le=1.0)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_positive_area(self) -> 'XfaNormalizedBBox':
|
||||
"""框必须正面积且不倒置。"""
|
||||
if self.x1 <= self.x0 or self.y1 <= self.y0:
|
||||
raise ValueError('normalized_bbox must have positive area')
|
||||
return self
|
||||
|
||||
|
||||
class XfaValueBinding(XfaContractModel):
|
||||
"""正式值绑定:XFA 仅允许 datasets 路径;普通 PDF 允许坐标/OCR。"""
|
||||
|
||||
type: XfaValueBindingType
|
||||
path_id: str | None = Field(default=None, max_length=128)
|
||||
data_path: str | None = Field(default=None, max_length=512)
|
||||
region_id: str | None = Field(default=None, max_length=64)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_by_type(self) -> 'XfaValueBinding':
|
||||
"""
|
||||
按类型校验必填字段。
|
||||
|
||||
XFA:必须 path_id + data_path;坐标类:必须 region_id。
|
||||
"""
|
||||
if self.type == 'xfa_dataset':
|
||||
if not self.path_id or not self.data_path:
|
||||
raise ValueError('xfa_dataset value_binding requires path_id and data_path')
|
||||
validate_controlled_data_path(self.data_path)
|
||||
if self.region_id:
|
||||
raise ValueError('xfa_dataset value_binding must not set region_id')
|
||||
else:
|
||||
if not self.region_id:
|
||||
raise ValueError(f'{self.type} value_binding requires region_id')
|
||||
if self.path_id or self.data_path:
|
||||
raise ValueError(f'{self.type} value_binding must not set XFA path fields')
|
||||
return self
|
||||
|
||||
|
||||
class XfaVisualBinding(XfaContractModel):
|
||||
"""视觉绑定:页码 + 归一化框 + 确认状态;正式字段发布前须 confirmed。"""
|
||||
|
||||
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)
|
||||
|
||||
|
||||
class XfaSplitRuleRef(XfaContractModel):
|
||||
"""字段对拆分段的引用;未拆分字段可省略。"""
|
||||
|
||||
rule_set_id: str = Field(min_length=8, max_length=64)
|
||||
segment_id: str = Field(min_length=8, max_length=64)
|
||||
|
||||
|
||||
class XfaUnifiedFieldBinding(XfaContractModel):
|
||||
"""
|
||||
统一字段绑定:同一 Schema 字段在同一作用域最多一个正式来源。
|
||||
|
||||
核心逻辑:value_binding 决定正式取值;visual_binding 决定页面证据;
|
||||
split_rule_ref 可选指向已确认拆分段。
|
||||
"""
|
||||
|
||||
binding_id: str = Field(min_length=8, max_length=64)
|
||||
field_id: str = Field(min_length=1, max_length=64)
|
||||
field_code: str = Field(min_length=1, max_length=128)
|
||||
scope: XfaBindingScope
|
||||
value_binding: XfaValueBinding
|
||||
visual_binding: XfaVisualBinding
|
||||
split_rule_ref: XfaSplitRuleRef | None = None
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_xfa_scope_value_type(self) -> 'XfaUnifiedFieldBinding':
|
||||
"""XFA Profile 内正式绑定必须是 xfa_dataset(由上层 Profile 再强制)。"""
|
||||
return self
|
||||
|
||||
|
||||
def is_formal_binding_publishable(binding: XfaUnifiedFieldBinding) -> bool:
|
||||
"""
|
||||
判断统一绑定是否满足发布门禁的视觉确认要求。
|
||||
|
||||
Args:
|
||||
binding: 统一字段绑定。
|
||||
|
||||
Returns:
|
||||
视觉状态为 confirmed 时为 True。
|
||||
"""
|
||||
return binding.visual_binding.status == 'confirmed'
|
||||
|
||||
|
||||
def canonical_unified_bindings_payload(
|
||||
bindings: list[XfaUnifiedFieldBinding] | list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
生成统一 binding 的 canonical JSON 列表(供 checksum)。
|
||||
|
||||
Args:
|
||||
bindings: 模型列表或已 dump 的字典列表。
|
||||
|
||||
Returns:
|
||||
按 binding_id 排序的稳定字典列表。
|
||||
"""
|
||||
items: list[dict[str, Any]] = []
|
||||
for raw in bindings or []:
|
||||
if isinstance(raw, XfaUnifiedFieldBinding):
|
||||
items.append(raw.model_dump(mode='json'))
|
||||
elif isinstance(raw, dict):
|
||||
items.append(XfaUnifiedFieldBinding.model_validate(raw).model_dump(mode='json'))
|
||||
else:
|
||||
raise ValueError('bindings must be XfaUnifiedFieldBinding or dict')
|
||||
return sorted(items, key=lambda item: str(item.get('binding_id') or ''))
|
||||
|
||||
|
||||
class OrderXfaDatasetProfile(XfaContractModel):
|
||||
"""
|
||||
xfa_dataset 模式的鉴别联合 definition。
|
||||
|
||||
核心逻辑:仅允许 XFA 映射字段;显式拒绝 coordinate 的 table_regions /
|
||||
order_field_layouts 等键混入;可选 split_rules 声明式多行拆分。
|
||||
核心逻辑:header_mappings / line_mapping.fields 仅迁移输入(须 bindings-only 正式运行);
|
||||
validate 拒绝 legacy-only 与 dual-source;拒绝 coordinate 表区键;可选 split_rules。
|
||||
"""
|
||||
|
||||
template_mode: Literal['xfa_dataset'] = 'xfa_dataset'
|
||||
source_contract: XfaSourceContract
|
||||
# 迁移输入兼容:禁止正式运行时单独携带非空 legacy mappings(须 bindings-only)。
|
||||
header_mappings: list[XfaHeaderMapping] = Field(default_factory=list)
|
||||
line_mapping: XfaLineMapping
|
||||
bindings: list[XfaUnifiedFieldBinding] = Field(default_factory=list)
|
||||
cross_checks: XfaCrossChecks = Field(default_factory=XfaCrossChecks)
|
||||
split_rules: list[dict[str, Any]] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='before')
|
||||
@classmethod
|
||||
def reject_coordinate_keys(cls, data: Any) -> Any:
|
||||
"""拒绝 coordinate region / layout 键混入 XFA definition。"""
|
||||
"""
|
||||
拒绝 coordinate 表区 / layout 键混入 XFA definition。
|
||||
|
||||
注意:不拒绝 visual_binding / normalized_bbox(统一绑定的视觉证据)。
|
||||
"""
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
forbidden = {
|
||||
@@ -396,7 +571,7 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_unique_bindings(self) -> 'OrderXfaDatasetProfile':
|
||||
"""同一 Schema 字段与同一 mapping_id 不得重复绑定;校验 split_rules 契约。"""
|
||||
"""同一 Schema 字段与同一 mapping/binding id 不得重复;校验 split_rules 与 bindings。"""
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
parse_split_rule_sets,
|
||||
)
|
||||
@@ -409,18 +584,40 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
for item in self.line_mapping.fields:
|
||||
field_ids.append(item.field_id)
|
||||
mapping_ids.append(item.mapping_id)
|
||||
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')
|
||||
binding_ids.append(binding.binding_id)
|
||||
binding_field_keys.append((binding.scope, binding.field_id))
|
||||
field_ids.append(binding.field_id)
|
||||
if len(binding_ids) != len(set(binding_ids)):
|
||||
raise ValueError('duplicate binding_id values are not allowed')
|
||||
if len(binding_field_keys) != len(set(binding_field_keys)):
|
||||
raise ValueError('duplicate Schema field_id bindings in the same scope are not allowed')
|
||||
rule_sets = parse_split_rule_sets(self.split_rules)
|
||||
for rule_set in rule_sets:
|
||||
for rule in rule_set.rules:
|
||||
if rule.segment.handling == 'mapped' and rule.segment.target_field_id:
|
||||
field_ids.append(rule.segment.target_field_id)
|
||||
has_legacy_mappings = bool(self.header_mappings) or bool(self.line_mapping.fields)
|
||||
if self.bindings and has_legacy_mappings:
|
||||
raise ValueError(
|
||||
'xfa_dual_binding_source: bindings cannot coexist with '
|
||||
'header_mappings or line_mapping.fields',
|
||||
)
|
||||
if has_legacy_mappings and not self.bindings:
|
||||
raise ValueError(
|
||||
'xfa_legacy_mappings_forbidden: header_mappings / line_mapping.fields are '
|
||||
'migration input only; formal runtime requires bindings[] — run unified migration first',
|
||||
)
|
||||
if len(field_ids) != len(set(field_ids)):
|
||||
raise ValueError('duplicate Schema field_id bindings are not allowed')
|
||||
if len(mapping_ids) != len(set(mapping_ids)):
|
||||
raise ValueError('duplicate mapping_id values are not allowed')
|
||||
if self.line_mapping.row_path != self.source_contract.authoritative_line_collection_path:
|
||||
raise ValueError('line_mapping.row_path must equal authoritative_line_collection_path')
|
||||
# 回写规范化后的 split_rules(model_dump 形状)。
|
||||
object.__setattr__(
|
||||
self,
|
||||
'split_rules',
|
||||
@@ -603,7 +800,11 @@ def compute_dataset_structure_fingerprint(
|
||||
|
||||
def validate_xfa_dataset_definition(payload: dict[str, Any] | OrderXfaDatasetProfile) -> OrderXfaDatasetProfile:
|
||||
"""
|
||||
将字典校验为 OrderXfaDatasetProfile。
|
||||
将字典校验为 OrderXfaDatasetProfile(正式路径:bindings-only)。
|
||||
|
||||
核心逻辑:normalize 后若仅有 legacy mappings 无 bindings → ValidationError
|
||||
(xfa_legacy_mappings_forbidden);与提取 fail-closed 一致。迁移读入旧字段请直接用
|
||||
dict + order_profile_unified_migration,勿经本函数校验 legacy-only 输入。
|
||||
|
||||
Args:
|
||||
payload: 原始 definition 或已构造模型。
|
||||
@@ -612,7 +813,7 @@ def validate_xfa_dataset_definition(payload: dict[str, Any] | OrderXfaDatasetPro
|
||||
通过鉴别联合与路径语法校验的模型。
|
||||
|
||||
Raises:
|
||||
pydantic.ValidationError / ValueError: 契约不合法。
|
||||
pydantic.ValidationError / ValueError: 契约不合法或 legacy-only。
|
||||
"""
|
||||
if isinstance(payload, OrderXfaDatasetProfile):
|
||||
return OrderXfaDatasetProfile.model_validate(payload.model_dump(mode='json'))
|
||||
|
||||
@@ -565,7 +565,7 @@ def serialize_tree_node(node: XfaDatasetNode, *, include_values: bool = False) -
|
||||
|
||||
Args:
|
||||
node: 数据集树节点。
|
||||
include_values: 是否包含脱敏样本值。
|
||||
include_values: 是否包含当前管理端使用的完整样本值。
|
||||
|
||||
Returns:
|
||||
安全 DTO 字典。
|
||||
@@ -583,11 +583,10 @@ def serialize_tree_node(node: XfaDatasetNode, *, include_values: bool = False) -
|
||||
'children': [serialize_tree_node(child, include_values=include_values) for child in node.children],
|
||||
}
|
||||
if include_values and node.is_leaf:
|
||||
payload['sample_value_masked'] = node.sample_value_masked or ''
|
||||
payload['sample_value_display'] = node.sample_value_display or ''
|
||||
payload['display_policy'] = node.display_policy
|
||||
payload['can_reveal'] = bool(node.can_reveal)
|
||||
# 仅暴露行数,不返回 lines 原文(完整值走受控 reveal)。
|
||||
payload['sample_value_masked'] = str(node.raw_value or '')
|
||||
payload['sample_value_display'] = str(node.raw_value or '')
|
||||
payload['display_policy'] = 'full'
|
||||
payload['can_reveal'] = False
|
||||
payload['line_count'] = len(node.lines or [])
|
||||
return payload
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_profile_extraction.py
|
||||
|
||||
用途:按冻结 published XFA Profile 路径映射提取 Header/Lines,并产出安全 evidence refs。
|
||||
依赖:xfa_contract、xfa_dataset、xfa_split_rule_contract、xfa_split_rule_engine、
|
||||
order_schema.field_rules、order_profile_extractors、XfaProfileMatchResult。
|
||||
逻辑:由 order_extraction_workflow XFA 分支在精确命中后调用;失败由上层回退坐标/OCR/通用;
|
||||
普通结果不含完整 XML / 明文路径;NETPR ``单价 / 价格单位`` 确定性拆分为 unit_price + price_unit;
|
||||
多行源字段经已确认 split_rules 引擎产出 mapped 字段与 evidence_only 段(非 Schema 字段)。
|
||||
用途:按冻结 published XFA Profile 统一 bindings[] 提取 Header/Lines,并产出安全 evidence refs。
|
||||
依赖:xfa_contract(OrderXfaDatasetProfile / XfaUnifiedFieldBinding)、xfa_dataset、
|
||||
xfa_split_rule_contract、xfa_split_rule_engine、order_schema.field_rules、
|
||||
order_profile_extractors。
|
||||
逻辑:由 order_extraction_workflow XFA 分支在精确命中后调用;正式提取仅读 bindings[],
|
||||
无 bindings 或仍含 header_mappings/line_mapping.fields 时 fail-closed;
|
||||
类型/normalizer/validator 取自 schema_fields;失败由上层回退坐标/OCR/通用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,6 +24,7 @@ from app.services.shipping_notice.document_layout.order_profile_extractors impor
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
OrderXfaDatasetProfile,
|
||||
XfaFieldEvidenceRef,
|
||||
XfaUnifiedFieldBinding,
|
||||
XFA_PARSER_IDENTITY,
|
||||
hash_data_path,
|
||||
sanitize_xfa_dto,
|
||||
@@ -76,6 +78,43 @@ class XfaExtractionResult:
|
||||
evidence_summary: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
def _schema_metadata_for_field(
|
||||
*,
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
field_id: str,
|
||||
field_code: str,
|
||||
) -> tuple[str, str | None, str | None]:
|
||||
"""
|
||||
从 schema_fields 读取 value_type / normalizer / validator。
|
||||
|
||||
核心逻辑:bindings 不含类型元数据时,以 Schema 为唯一来源;缺省 string + trim。
|
||||
|
||||
Args:
|
||||
schema_fields: Run 冻结 Schema field_id → 配置。
|
||||
field_id: Schema 字段 ID。
|
||||
field_code: 业务 field_code(仅用于缺省回退)。
|
||||
|
||||
Returns:
|
||||
(value_type, normalizer_key, validator_key)。
|
||||
"""
|
||||
cfg = schema_fields.get(field_id) or {}
|
||||
value_type = str(cfg.get('value_type') or 'string')
|
||||
normalizer_key = str(cfg.get('normalizer_key') or 'trim') or None
|
||||
validator_keys = list(cfg.get('validator_keys') or [])
|
||||
validator_key = str(validator_keys[0]) if validator_keys else None
|
||||
if not cfg and field_code:
|
||||
_ = field_code
|
||||
return value_type, normalizer_key, validator_key
|
||||
|
||||
|
||||
def _bindings_for_scope(
|
||||
profile: OrderXfaDatasetProfile,
|
||||
scope: str,
|
||||
) -> list[XfaUnifiedFieldBinding]:
|
||||
"""按 scope 过滤统一 bindings(header / line)。"""
|
||||
return [item for item in profile.bindings if str(item.scope) == scope]
|
||||
|
||||
|
||||
def _schema_field_config(
|
||||
*,
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
@@ -239,39 +278,45 @@ def _is_formal_ready_split_rule_set(rule_set: XfaSplitRuleSet) -> bool:
|
||||
|
||||
|
||||
def _build_path_id_to_data_path(profile: OrderXfaDatasetProfile) -> dict[str, str]:
|
||||
"""从 Header/Line 映射构建 path_id → data_path 索引。"""
|
||||
"""
|
||||
从 bindings[].value_binding 构建 path_id → data_path 索引。
|
||||
|
||||
核心逻辑:正式提取与 split_rules 源路径解析均只读统一 bindings。
|
||||
"""
|
||||
mapping: dict[str, str] = {}
|
||||
for item in profile.header_mappings:
|
||||
if item.path_id and item.data_path:
|
||||
mapping[str(item.path_id)] = str(item.data_path)
|
||||
for item in profile.line_mapping.fields:
|
||||
if item.path_id and item.data_path:
|
||||
mapping[str(item.path_id)] = str(item.data_path)
|
||||
for binding in profile.bindings:
|
||||
path_id = str(binding.value_binding.path_id or '').strip()
|
||||
data_path = str(binding.value_binding.data_path or '').strip()
|
||||
if path_id and data_path:
|
||||
mapping[path_id] = data_path
|
||||
return mapping
|
||||
|
||||
|
||||
def _resolve_split_source_data_path(
|
||||
rule_set: XfaSplitRuleSet,
|
||||
*,
|
||||
line_fields: list[Any],
|
||||
line_bindings: list[XfaUnifiedFieldBinding],
|
||||
path_id_to_data_path: dict[str, str],
|
||||
) -> str | None:
|
||||
"""
|
||||
解析拆分规则集源字段 data_path。
|
||||
|
||||
核心逻辑:优先使用服务端冻结的 source_data_path,其次按 source_path_id 命中映射;
|
||||
旧定义最后按 data_path 后缀兼容匹配 source_field_code。
|
||||
核心逻辑:优先使用服务端冻结的 source_data_path,其次按 source_path_id 命中 bindings;
|
||||
最后按 data_path 后缀兼容匹配 source_field_code。
|
||||
"""
|
||||
if rule_set.source_data_path:
|
||||
return str(rule_set.source_data_path)
|
||||
path_id = str(rule_set.source_path_id or '')
|
||||
if path_id in path_id_to_data_path:
|
||||
return path_id_to_data_path[path_id]
|
||||
suffix = f'/{rule_set.source_field_code}'
|
||||
for mapping in line_fields:
|
||||
data_path = str(getattr(mapping, 'data_path', '') or '')
|
||||
mapping_path_id = str(getattr(mapping, 'path_id', '') or '')
|
||||
if mapping_path_id == path_id or data_path.endswith(suffix):
|
||||
field_code = str(rule_set.source_field_code or '').strip()
|
||||
if not field_code:
|
||||
return None
|
||||
suffix = f'/{field_code}'
|
||||
for binding in line_bindings:
|
||||
data_path = str(binding.value_binding.data_path or '')
|
||||
binding_path_id = str(binding.value_binding.path_id or '')
|
||||
if binding_path_id == path_id or data_path.endswith(suffix):
|
||||
return data_path or None
|
||||
return None
|
||||
|
||||
@@ -299,7 +344,7 @@ def _apply_split_rules_for_header(
|
||||
for rule_set in rule_sets:
|
||||
data_path = _resolve_split_source_data_path(
|
||||
rule_set,
|
||||
line_fields=[],
|
||||
line_bindings=[],
|
||||
path_id_to_data_path=path_id_to_data_path,
|
||||
)
|
||||
if not data_path:
|
||||
@@ -360,7 +405,7 @@ def _apply_split_rules_for_row(
|
||||
*,
|
||||
row_values: dict[str, str],
|
||||
rule_sets: list[XfaSplitRuleSet],
|
||||
line_fields: list[Any],
|
||||
line_bindings: list[XfaUnifiedFieldBinding],
|
||||
path_id_to_data_path: dict[str, str],
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
schema_by_code: dict[str, dict[str, Any]],
|
||||
@@ -371,6 +416,9 @@ def _apply_split_rules_for_row(
|
||||
"""
|
||||
对单行执行已确认拆分规则并产出 Schema 字段值与 evidence_only 段。
|
||||
|
||||
Args:
|
||||
line_bindings: scope=line 的统一 bindings,供源路径后缀回退。
|
||||
|
||||
Returns:
|
||||
(values, split_evidence, produced_field_codes, issues, required_missing)
|
||||
"""
|
||||
@@ -383,7 +431,7 @@ def _apply_split_rules_for_row(
|
||||
for rule_set in rule_sets:
|
||||
data_path = _resolve_split_source_data_path(
|
||||
rule_set,
|
||||
line_fields=line_fields,
|
||||
line_bindings=line_bindings,
|
||||
path_id_to_data_path=path_id_to_data_path,
|
||||
)
|
||||
if not data_path:
|
||||
@@ -455,10 +503,11 @@ def extract_xfa_profile(
|
||||
dataset_structure_fingerprint: str | None = None,
|
||||
) -> XfaExtractionResult:
|
||||
"""
|
||||
按冻结 XFA Profile 提取 Header 与权威明细行。
|
||||
按冻结 XFA Profile 统一 bindings[] 提取 Header 与权威明细行。
|
||||
|
||||
核心逻辑:校验 definition → 读 Header 叶子 → 读权威集合行 → Schema 标准化;
|
||||
权威集合缺失时 fail-closed(reason=xfa_authoritative_collection_missing)。
|
||||
核心逻辑:校验 definition → 要求 bindings-only(拒绝 legacy mappings)→
|
||||
按 scope 迭代 bindings → 读权威集合行 → 从 schema_fields 标准化;
|
||||
无 bindings → xfa_visual_bindings_required;双源 → xfa_dual_binding_source。
|
||||
|
||||
Args:
|
||||
raw_profile: 冻结 Profile 快照(含 definition / checksum)。
|
||||
@@ -472,6 +521,30 @@ def extract_xfa_profile(
|
||||
XfaExtractionResult:含 rows(对齐坐标路径)与安全 evidence_summary。
|
||||
"""
|
||||
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
|
||||
header_mappings = definition.get('header_mappings') if isinstance(definition.get('header_mappings'), list) else []
|
||||
line_mapping = definition.get('line_mapping') if isinstance(definition.get('line_mapping'), dict) else {}
|
||||
line_fields = line_mapping.get('fields') if isinstance(line_mapping.get('fields'), list) else []
|
||||
bindings_raw = definition.get('bindings') if isinstance(definition.get('bindings'), list) else []
|
||||
has_bindings = bool(bindings_raw)
|
||||
has_legacy_mappings = bool(header_mappings) or bool(line_fields)
|
||||
|
||||
if not has_bindings:
|
||||
return XfaExtractionResult(
|
||||
status='failed',
|
||||
reason_codes=['xfa_visual_bindings_required'],
|
||||
packet_checksum=packet_checksum,
|
||||
dataset_structure_fingerprint=dataset_structure_fingerprint,
|
||||
profile_checksum=str(raw_profile.get('checksum') or '') or None,
|
||||
)
|
||||
if has_legacy_mappings:
|
||||
return XfaExtractionResult(
|
||||
status='failed',
|
||||
reason_codes=['xfa_dual_binding_source'],
|
||||
packet_checksum=packet_checksum,
|
||||
dataset_structure_fingerprint=dataset_structure_fingerprint,
|
||||
profile_checksum=str(raw_profile.get('checksum') or '') or None,
|
||||
)
|
||||
|
||||
try:
|
||||
profile = OrderXfaDatasetProfile.model_validate(definition)
|
||||
except (TypeError, ValueError):
|
||||
@@ -489,20 +562,30 @@ def extract_xfa_profile(
|
||||
if isinstance(item, dict) and item.get('enabled', True) and item.get('field_id')
|
||||
}
|
||||
|
||||
# [STEP 1] Header 映射
|
||||
# [STEP 0] 正式提取仅允许 bindings-only(已在 model_validate 前 fail-closed)
|
||||
header_bindings = _bindings_for_scope(profile, 'header')
|
||||
line_bindings = _bindings_for_scope(profile, 'line')
|
||||
|
||||
# [STEP 1] Header bindings
|
||||
header_fields: list[XfaExtractedField] = []
|
||||
header_issues: list[str] = []
|
||||
for mapping in profile.header_mappings:
|
||||
raw_value = read_dataset_value(dataset_analysis, mapping.data_path)
|
||||
for binding in header_bindings:
|
||||
data_path = str(binding.value_binding.data_path or '')
|
||||
value_type, normalizer_key, validator_key = _schema_metadata_for_field(
|
||||
schema_fields=schema_fields,
|
||||
field_id=binding.field_id,
|
||||
field_code=binding.field_code,
|
||||
)
|
||||
raw_value = read_dataset_value(dataset_analysis, data_path)
|
||||
extracted = _extract_one_field(
|
||||
raw_value=raw_value,
|
||||
mapping_id=mapping.mapping_id,
|
||||
field_id=mapping.field_id,
|
||||
field_code=mapping.field_code,
|
||||
data_path=mapping.data_path,
|
||||
value_type=mapping.value_type,
|
||||
normalizer_key=mapping.normalizer_key,
|
||||
validator_key=mapping.validator_key,
|
||||
mapping_id=binding.binding_id,
|
||||
field_id=binding.field_id,
|
||||
field_code=binding.field_code,
|
||||
data_path=data_path,
|
||||
value_type=value_type,
|
||||
normalizer_key=normalizer_key,
|
||||
validator_key=validator_key,
|
||||
schema_fields=schema_fields,
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
@@ -580,7 +663,7 @@ def extract_xfa_profile(
|
||||
_apply_split_rules_for_row(
|
||||
row_values=row_values,
|
||||
rule_sets=line_split_rule_sets,
|
||||
line_fields=list(profile.line_mapping.fields),
|
||||
line_bindings=line_bindings,
|
||||
path_id_to_data_path=path_id_to_data_path,
|
||||
schema_fields=schema_fields,
|
||||
schema_by_code=schema_by_code,
|
||||
@@ -609,38 +692,44 @@ def extract_xfa_profile(
|
||||
})
|
||||
pending_price_unit_raw: str | None = None
|
||||
pending_price_unit_path: str | None = None
|
||||
for mapping in profile.line_mapping.fields:
|
||||
if str(mapping.field_code or '') in split_produced_codes:
|
||||
for binding in line_bindings:
|
||||
if str(binding.field_code or '') in split_produced_codes:
|
||||
continue
|
||||
if str(mapping.path_id or '') in split_source_path_ids:
|
||||
if str(binding.value_binding.path_id or '') in split_source_path_ids:
|
||||
continue
|
||||
raw_value = row_values.get(mapping.data_path)
|
||||
data_path = str(binding.value_binding.data_path or '')
|
||||
raw_value = row_values.get(data_path)
|
||||
extract_raw = raw_value
|
||||
# [STEP] NETPR 复合值:拆出单价;价格单位若无独立映射则稍后补齐。
|
||||
if str(mapping.field_code or '') == 'unit_price':
|
||||
value_type, normalizer_key, validator_key = _schema_metadata_for_field(
|
||||
schema_fields=schema_fields,
|
||||
field_id=binding.field_id,
|
||||
field_code=binding.field_code,
|
||||
)
|
||||
# [STEP] NETPR 复合值:拆出单价;价格单位若无独立 binding 则稍后补齐。
|
||||
if str(binding.field_code or '') == 'unit_price':
|
||||
composite = parse_unit_price_with_price_unit(
|
||||
None if raw_value is None else str(raw_value)
|
||||
)
|
||||
if composite:
|
||||
extract_raw = composite['unit_price']
|
||||
pending_price_unit_raw = composite['price_unit']
|
||||
pending_price_unit_path = mapping.data_path
|
||||
pending_price_unit_path = data_path
|
||||
extracted = _extract_one_field(
|
||||
raw_value=extract_raw if extract_raw is not None else raw_value,
|
||||
mapping_id=mapping.mapping_id,
|
||||
field_id=mapping.field_id,
|
||||
field_code=mapping.field_code,
|
||||
data_path=mapping.data_path,
|
||||
value_type=mapping.value_type,
|
||||
normalizer_key=mapping.normalizer_key,
|
||||
validator_key=mapping.validator_key,
|
||||
mapping_id=binding.binding_id,
|
||||
field_id=binding.field_id,
|
||||
field_code=binding.field_code,
|
||||
data_path=data_path,
|
||||
value_type=value_type,
|
||||
normalizer_key=normalizer_key,
|
||||
validator_key=validator_key,
|
||||
schema_fields=schema_fields,
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
)
|
||||
# 保留原文 quote(含 ``898.72 / 1``)便于审计对账。
|
||||
if (
|
||||
str(mapping.field_code or '') == 'unit_price'
|
||||
str(binding.field_code or '') == 'unit_price'
|
||||
and raw_value not in (None, '')
|
||||
and extract_raw != raw_value
|
||||
):
|
||||
@@ -727,7 +816,7 @@ def extract_xfa_profile(
|
||||
reason_codes: list[str] = []
|
||||
if has_unconfirmed_split_rules:
|
||||
reason_codes.append('xfa_split_rule_unconfirmed')
|
||||
if required_missing or any(row.get('status') != 'parsed' for row in rows):
|
||||
if required_missing:
|
||||
reason_codes.append('xfa_required_field_missing')
|
||||
|
||||
evidence_summary = sanitize_xfa_dto({
|
||||
|
||||
@@ -0,0 +1,387 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_safe_regex.py
|
||||
|
||||
用途:XFA 拆分规则的安全正则编译与搜索——优先 RE2 线性时间语义,失败时回退受限子集。
|
||||
依赖:可选 google-re2;标准库 re、multiprocessing、concurrent.futures;backend/xfa_regex_worker(spawn 隔离)。
|
||||
逻辑:由 xfa_split_rule_contract 校验入口与 xfa_split_rule_engine 执行路径调用;
|
||||
禁止无限制 Python re 执行用户正则;restricted_re 在独立子进程(xfa_regex_worker)执行;
|
||||
不访问网络或文件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import multiprocessing as mp
|
||||
import re
|
||||
import threading
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from concurrent.futures import TimeoutError as FuturesTimeoutError
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Final
|
||||
|
||||
import xfa_regex_worker
|
||||
|
||||
try:
|
||||
import re2 as _re2 # type: ignore[import-untyped]
|
||||
|
||||
_HAS_RE2: Final[bool] = True
|
||||
except ImportError: # pragma: no cover - CI/本地未装 google-re2 时走 fallback
|
||||
_re2 = None # type: ignore[assignment]
|
||||
_HAS_RE2 = False
|
||||
|
||||
_REGEX_FORBIDDEN: Final[tuple[str, ...]] = (
|
||||
'(?P',
|
||||
'(?R',
|
||||
'(?&',
|
||||
'\\g',
|
||||
'(?<',
|
||||
'(?<=',
|
||||
'(?<!',
|
||||
'(?=',
|
||||
'(?!',
|
||||
)
|
||||
_REGEX_CATASTROPHIC: Final[tuple[re.Pattern[str], ...]] = (
|
||||
re.compile(r'\([^)]*[+*][^)]*\)[+*]'),
|
||||
re.compile(r'\([^)]*[+*][^)]*\)\{'),
|
||||
re.compile(r'\(\?\:.*[+*].*\)[+*]'),
|
||||
)
|
||||
_WORKER_JOIN_GRACE_S: Final[float] = 1.0
|
||||
_restricted_pool: ProcessPoolExecutor | None = None
|
||||
_restricted_pool_lock = threading.Lock()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SafeRegexCompiled:
|
||||
"""安全正则编译结果:携带引擎标识供诊断。"""
|
||||
|
||||
pattern: str
|
||||
engine: str # re2 | restricted_re
|
||||
flags: int
|
||||
_re2_obj: Any = None
|
||||
_re_obj: re.Pattern[str] | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _MatchSnapshot:
|
||||
"""父进程侧重导出 xfa_regex_worker.MatchSnapshot 类型别名。"""
|
||||
|
||||
groups: tuple[str, ...]
|
||||
lastindex: int | None
|
||||
|
||||
|
||||
class SafeRegexError(ValueError):
|
||||
"""安全正则编译或执行失败。"""
|
||||
|
||||
|
||||
class _MatchSnapshotAdapter:
|
||||
"""
|
||||
将子进程序列化的分组快照适配为 re.Match 最小接口(group / lastindex)。
|
||||
|
||||
核心逻辑:仅暴露 search_safe 消费方所需的 group、lastindex、groupdict。
|
||||
"""
|
||||
|
||||
def __init__(self, snapshot: _MatchSnapshot) -> None:
|
||||
self._snapshot = snapshot
|
||||
|
||||
@property
|
||||
def lastindex(self) -> int | None:
|
||||
return self._snapshot.lastindex
|
||||
|
||||
def group(self, index: int = 0) -> str:
|
||||
groups = self._snapshot.groups
|
||||
if index < 0 or index >= len(groups):
|
||||
raise IndexError(f'no such group: {index}')
|
||||
return groups[index]
|
||||
|
||||
def groupdict(self) -> dict[str, str]:
|
||||
return {}
|
||||
|
||||
|
||||
def validate_restricted_regex_pattern(pattern: str, *, max_length: int, max_groups: int) -> None:
|
||||
"""
|
||||
校验受限子集正则是否可接受(不执行匹配)。
|
||||
|
||||
核心逻辑:长度、捕获组、禁止 token、灾难回溯启发式;为 RE2 预留相同接口。
|
||||
|
||||
Args:
|
||||
pattern: 正则表达式。
|
||||
max_length: 最大模式长度。
|
||||
max_groups: 最大捕获组数。
|
||||
|
||||
Raises:
|
||||
SafeRegexError: 模式非法或高风险。
|
||||
"""
|
||||
text = str(pattern or '')
|
||||
if not text:
|
||||
raise SafeRegexError('regex pattern is empty')
|
||||
if len(text) > max_length:
|
||||
raise SafeRegexError('regex pattern exceeds max length')
|
||||
for token in _REGEX_FORBIDDEN:
|
||||
if token in text:
|
||||
raise SafeRegexError(f'regex pattern contains forbidden construct: {token}')
|
||||
for probe in _REGEX_CATASTROPHIC:
|
||||
if probe.search(text):
|
||||
raise SafeRegexError('regex pattern looks catastrophic (nested quantifiers)')
|
||||
try:
|
||||
compiled = re.compile(text)
|
||||
except re.error as exc:
|
||||
raise SafeRegexError(f'invalid regex pattern: {exc}') from exc
|
||||
if compiled.groups > max_groups:
|
||||
raise SafeRegexError('regex capture groups exceed limit')
|
||||
|
||||
|
||||
def compile_safe_regex(
|
||||
pattern: str,
|
||||
*,
|
||||
case_sensitive: bool = True,
|
||||
max_length: int = 128,
|
||||
max_groups: int = 5,
|
||||
) -> SafeRegexCompiled:
|
||||
"""
|
||||
编译安全正则:优先 RE2,失败或未安装时使用受限 Python re 子集。
|
||||
|
||||
Args:
|
||||
pattern: 正则表达式。
|
||||
case_sensitive: 是否区分大小写。
|
||||
max_length: 最大模式长度。
|
||||
max_groups: 最大捕获组数。
|
||||
|
||||
Returns:
|
||||
SafeRegexCompiled。
|
||||
|
||||
Raises:
|
||||
SafeRegexError: 模式非法或 RE2 拒绝。
|
||||
"""
|
||||
validate_restricted_regex_pattern(pattern, max_length=max_length, max_groups=max_groups)
|
||||
flags = 0 if case_sensitive else re.IGNORECASE
|
||||
if _HAS_RE2 and _re2 is not None:
|
||||
try:
|
||||
re2_flags = _re2.Flags(0)
|
||||
if not case_sensitive:
|
||||
re2_flags = _re2.Flags.CASE_INSENSITIVE # type: ignore[attr-defined]
|
||||
compiled_re2 = _re2.compile(str(pattern), re2_flags)
|
||||
group_count = compiled_re2.groups if hasattr(compiled_re2, 'groups') else 0
|
||||
if int(group_count or 0) > max_groups:
|
||||
raise SafeRegexError('regex capture groups exceed limit')
|
||||
return SafeRegexCompiled(
|
||||
pattern=str(pattern),
|
||||
engine='re2',
|
||||
flags=flags,
|
||||
_re2_obj=compiled_re2,
|
||||
)
|
||||
except SafeRegexError:
|
||||
raise
|
||||
except Exception as exc: # pragma: no cover - RE2 运行时拒绝
|
||||
raise SafeRegexError(f're2 compile failed: {exc}') from exc
|
||||
compiled = re.compile(str(pattern), flags)
|
||||
return SafeRegexCompiled(
|
||||
pattern=str(pattern),
|
||||
engine='restricted_re',
|
||||
flags=flags,
|
||||
_re_obj=compiled,
|
||||
)
|
||||
|
||||
|
||||
def _terminate_process(process: mp.Process) -> None:
|
||||
"""
|
||||
强制终止子进程(Windows/Linux 兼容)。
|
||||
|
||||
核心逻辑:先 terminate,宽限期后仍存活则 kill。
|
||||
|
||||
Args:
|
||||
process: 待终止的 multiprocessing.Process。
|
||||
"""
|
||||
if not process.is_alive():
|
||||
return
|
||||
process.terminate()
|
||||
process.join(timeout=_WORKER_JOIN_GRACE_S)
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
process.join()
|
||||
|
||||
|
||||
def _destroy_restricted_pool() -> None:
|
||||
"""
|
||||
销毁 restricted_re 进程池并在超时后 terminate/kill 仍在运行的 worker。
|
||||
|
||||
核心逻辑:shutdown(cancel_futures=True) 后逐个 terminate/kill 残留进程,避免灾难回溯拖死 worker。
|
||||
"""
|
||||
global _restricted_pool
|
||||
with _restricted_pool_lock:
|
||||
pool = _restricted_pool
|
||||
if pool is None:
|
||||
return
|
||||
processes = dict(getattr(pool, '_processes', {}) or {})
|
||||
pool.shutdown(wait=False, cancel_futures=True)
|
||||
for process in processes.values():
|
||||
_terminate_process(process)
|
||||
_restricted_pool = None
|
||||
|
||||
|
||||
def _get_restricted_pool() -> ProcessPoolExecutor:
|
||||
"""
|
||||
获取或创建 restricted_re 专用 ProcessPoolExecutor(spawn,单 worker)。
|
||||
|
||||
核心逻辑:worker 仅导入 xfa_regex_worker;首次创建时提交空匹配预热 spawn 开销。
|
||||
|
||||
Returns:
|
||||
可复用的 ProcessPoolExecutor(max_workers=1)。
|
||||
"""
|
||||
global _restricted_pool
|
||||
with _restricted_pool_lock:
|
||||
if _restricted_pool is None:
|
||||
pool = ProcessPoolExecutor(
|
||||
max_workers=1,
|
||||
mp_context=mp.get_context('spawn'),
|
||||
)
|
||||
warm_future = pool.submit(xfa_regex_worker.run_restricted_search, '^$', 0, '')
|
||||
warm_future.result(timeout=30.0)
|
||||
_restricted_pool = pool
|
||||
return _restricted_pool
|
||||
|
||||
|
||||
def _search_restricted_re_in_subprocess(
|
||||
pattern: str,
|
||||
flags: int,
|
||||
haystack: str,
|
||||
*,
|
||||
timeout_s: float,
|
||||
) -> re.Match[str] | None:
|
||||
"""
|
||||
在可 kill 的子进程池中执行 restricted re.search,超时立即销毁池并抛 TimeoutError。
|
||||
|
||||
核心逻辑:ProcessPoolExecutor 复用 worker;future.result(timeout) 超时则 terminate/kill 全部 worker。
|
||||
|
||||
Args:
|
||||
pattern: 已校验的正则 pattern。
|
||||
flags: re 编译 flags。
|
||||
haystack: 待搜索文本。
|
||||
timeout_s: 超时秒数(仅计匹配执行,不含首次 pool 预热)。
|
||||
|
||||
Returns:
|
||||
匹配快照适配器;无匹配时 None。
|
||||
|
||||
Raises:
|
||||
TimeoutError: 超时且 worker 进程已被终止。
|
||||
SafeRegexError: 子进程报告执行错误或异常退出。
|
||||
"""
|
||||
pool = _get_restricted_pool()
|
||||
future = pool.submit(xfa_regex_worker.run_restricted_search, pattern, flags, haystack)
|
||||
try:
|
||||
payload = future.result(timeout=timeout_s)
|
||||
except FuturesTimeoutError as exc:
|
||||
_destroy_restricted_pool()
|
||||
raise TimeoutError('regex execution timed out') from exc
|
||||
except Exception as exc:
|
||||
_destroy_restricted_pool()
|
||||
raise SafeRegexError(f'restricted regex worker failed: {exc}') from exc
|
||||
|
||||
if payload is None:
|
||||
return None
|
||||
snapshot = _MatchSnapshot(groups=payload.groups, lastindex=payload.lastindex)
|
||||
return _MatchSnapshotAdapter(snapshot)
|
||||
|
||||
|
||||
def search_safe(
|
||||
compiled: SafeRegexCompiled | str,
|
||||
text: str,
|
||||
*,
|
||||
timeout_ms: int = 50,
|
||||
case_sensitive: bool = True,
|
||||
max_length: int = 128,
|
||||
max_groups: int = 5,
|
||||
) -> re.Match[str] | None:
|
||||
"""
|
||||
对文本执行安全正则搜索(带超时)。
|
||||
|
||||
核心逻辑:RE2 路径在线程池执行(线性时间,线程超时即可);
|
||||
restricted_re 路径在 ProcessPoolExecutor spawn worker 中执行,超时 destroy pool 并 kill worker。
|
||||
|
||||
Args:
|
||||
compiled: 已编译对象或原始 pattern(将临时编译)。
|
||||
text: 待搜索文本。
|
||||
timeout_ms: 超时毫秒。
|
||||
case_sensitive: 当 compiled 为 str 时传给 compile_safe_regex。
|
||||
max_length: 当 compiled 为 str 时的模式长度上限。
|
||||
max_groups: 当 compiled 为 str 时的捕获组上限。
|
||||
|
||||
Returns:
|
||||
匹配对象;无匹配时 None。
|
||||
|
||||
Raises:
|
||||
SafeRegexError: 编译失败或 restricted 子进程执行失败。
|
||||
TimeoutError: 执行超时(restricted 路径保证子进程已被终止)。
|
||||
"""
|
||||
obj = (
|
||||
compiled
|
||||
if isinstance(compiled, SafeRegexCompiled)
|
||||
else compile_safe_regex(
|
||||
str(compiled),
|
||||
case_sensitive=case_sensitive,
|
||||
max_length=max_length,
|
||||
max_groups=max_groups,
|
||||
)
|
||||
)
|
||||
haystack = str(text or '')
|
||||
timeout_s = max(int(timeout_ms), 1) / 1000.0
|
||||
|
||||
if obj.engine == 're2' and obj._re2_obj is not None:
|
||||
def _run_re2() -> Any:
|
||||
assert obj._re2_obj is not None
|
||||
return obj._re2_obj.search(haystack)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
future = pool.submit(_run_re2)
|
||||
try:
|
||||
matched = future.result(timeout=timeout_s)
|
||||
except FuturesTimeoutError as exc:
|
||||
future.cancel()
|
||||
raise TimeoutError('regex execution timed out') from exc
|
||||
if matched is None:
|
||||
return None
|
||||
return _Re2MatchAdapter(matched)
|
||||
|
||||
return _search_restricted_re_in_subprocess(
|
||||
obj.pattern,
|
||||
obj.flags,
|
||||
haystack,
|
||||
timeout_s=timeout_s,
|
||||
)
|
||||
|
||||
|
||||
class _Re2MatchAdapter:
|
||||
"""
|
||||
将 RE2 Match 适配为类似 re.Match 的最小接口(group / lastindex)。
|
||||
"""
|
||||
|
||||
def __init__(self, raw: Any) -> None:
|
||||
self._raw = raw
|
||||
|
||||
@property
|
||||
def lastindex(self) -> int | None:
|
||||
try:
|
||||
count = int(self._raw.groups())
|
||||
return count if count > 0 else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def group(self, index: int = 0) -> str:
|
||||
try:
|
||||
if index == 0:
|
||||
return str(self._raw.group() or '')
|
||||
return str(self._raw.group(index) or '')
|
||||
except Exception as exc:
|
||||
raise IndexError(str(exc)) from exc
|
||||
|
||||
def groupdict(self) -> dict[str, str]:
|
||||
return {}
|
||||
|
||||
|
||||
def has_re2_engine() -> bool:
|
||||
"""
|
||||
当前进程是否可用 RE2 引擎。
|
||||
|
||||
Returns:
|
||||
True 表示 google-re2 已安装且可导入。
|
||||
"""
|
||||
return _HAS_RE2
|
||||
@@ -1,10 +1,11 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_signature.py
|
||||
|
||||
用途:计算 XFA template packet checksum、datasets 结构指纹与治理用 structure signature。
|
||||
用途:计算 XFA template packet checksum、datasets 结构指纹、统一 binding/拆分
|
||||
内容指纹与治理用 structure signature。
|
||||
依赖:xfa_contract、xfa_dataset.XfaDatasetNode、标准库 hashlib/json。
|
||||
逻辑:由 xfa_analysis / 验证服务调用;指纹忽略业务值与行数;structure signature
|
||||
冻结 analysis 与 packet 身份供发布门禁引用。
|
||||
与 definition checksum 覆盖视觉绑定与拆分规则业务字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,6 +17,8 @@ from typing import Any
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_STRUCTURE_SIGNATURE_ID,
|
||||
XfaStructureNodeSpec,
|
||||
XfaUnifiedFieldBinding,
|
||||
canonical_unified_bindings_payload,
|
||||
compute_dataset_structure_fingerprint,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import XfaDatasetNode
|
||||
@@ -145,3 +148,43 @@ def build_xfa_structure_signature(
|
||||
'has_structure_fingerprint': bool(dataset_structure_fingerprint),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def compute_unified_bindings_checksum(
|
||||
bindings: list[XfaUnifiedFieldBinding] | list[dict[str, Any]],
|
||||
) -> str:
|
||||
"""
|
||||
计算统一 binding(含 visual_binding / split_rule_ref)的稳定 checksum。
|
||||
|
||||
Args:
|
||||
bindings: 统一字段绑定列表。
|
||||
|
||||
Returns:
|
||||
`sha256:<hex>`。
|
||||
"""
|
||||
payload = {
|
||||
'kind': 'xfa-unified-bindings.v1',
|
||||
'bindings': canonical_unified_bindings_payload(bindings),
|
||||
}
|
||||
encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
return f'sha256:{hashlib.sha256(encoded).hexdigest()}'
|
||||
|
||||
|
||||
def compute_definition_business_checksum(definition: dict[str, Any]) -> str:
|
||||
"""
|
||||
计算 XFA definition 业务字段 checksum(含 bindings 与 split_rules)。
|
||||
|
||||
核心逻辑:对 definition 做 canonical JSON 哈希;调用方须传入已通过契约校验的对象。
|
||||
|
||||
Args:
|
||||
definition: Profile definition 字典。
|
||||
|
||||
Returns:
|
||||
`sha256:<hex>`。
|
||||
"""
|
||||
payload = {
|
||||
'kind': 'xfa-definition-business.v1',
|
||||
'definition': definition or {},
|
||||
}
|
||||
encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
return f'sha256:{hashlib.sha256(encoded).hexdigest()}'
|
||||
@@ -0,0 +1,437 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_split_preview_token.py
|
||||
|
||||
用途:签发与校验 XFA 拆分规则预览确认令牌,防止客户端自行声明 confirmed。
|
||||
依赖: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 生产语义)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
# 预览确认令牌默认有效期(秒)
|
||||
DEFAULT_SPLIT_PREVIEW_TOKEN_TTL_SECONDS = 15 * 60
|
||||
|
||||
# Redis 消费键前缀;不可用时由 _MemoryConsumedJtiStore 兜底。
|
||||
_JTI_REDIS_KEY_PREFIX = 'shipping:xfa_split_preview_token:'
|
||||
|
||||
|
||||
class _MemoryConsumedJtiStore:
|
||||
"""进程内 jti 一次性消费存储(Redis 不可用时的测试/单进程兜底)。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.Lock()
|
||||
self._consumed: dict[str, float] = {}
|
||||
|
||||
def try_consume(self, jti: str, ttl_seconds: int) -> bool:
|
||||
"""
|
||||
尝试标记 jti 为已消费。
|
||||
|
||||
核心逻辑:持锁清理过期项后,若 jti 已存在则拒绝(重放),否则写入过期时间。
|
||||
|
||||
Returns:
|
||||
True 表示首次消费成功;False 表示已消费或仍在有效期内。
|
||||
"""
|
||||
now = time.time()
|
||||
expires_at = now + max(1, int(ttl_seconds))
|
||||
with self._lock:
|
||||
expired = [key for key, exp in self._consumed.items() if exp <= now]
|
||||
for key in expired:
|
||||
del self._consumed[key]
|
||||
if jti in self._consumed:
|
||||
return False
|
||||
self._consumed[jti] = expires_at
|
||||
return True
|
||||
|
||||
|
||||
_memory_jti_store = _MemoryConsumedJtiStore()
|
||||
|
||||
|
||||
def _signing_secret() -> bytes:
|
||||
"""
|
||||
读取应用级签名密钥。
|
||||
|
||||
Returns:
|
||||
SECRET_KEY 的 UTF-8 字节。
|
||||
|
||||
Raises:
|
||||
ValidationError: SECRET_KEY 未配置。
|
||||
"""
|
||||
secret = str(current_app.config.get('SECRET_KEY') or '').strip()
|
||||
if not secret:
|
||||
raise ValidationError(
|
||||
'SECRET_KEY is required for XFA split preview tokens',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
details={'reason': 'secret_key_missing'},
|
||||
)
|
||||
return secret.encode('utf-8')
|
||||
|
||||
|
||||
def split_rule_preview_fingerprint(rule_set: dict[str, Any] | Any) -> str:
|
||||
"""
|
||||
计算规则集内容指纹(与确认令牌绑定)。
|
||||
|
||||
核心逻辑:委托 split_rule_content_fingerprint,保证预览与保存比对一致。
|
||||
|
||||
Args:
|
||||
rule_set: 规则集 dict 或已校验模型。
|
||||
|
||||
Returns:
|
||||
内容指纹字符串。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
split_rule_content_fingerprint,
|
||||
)
|
||||
|
||||
return split_rule_content_fingerprint(rule_set)
|
||||
|
||||
|
||||
def _try_consume_jti(*, jti: str, ttl_seconds: int) -> bool:
|
||||
"""
|
||||
原子消费令牌 jti。
|
||||
|
||||
核心逻辑:优先 Redis SET NX EX;失败或不可用时回退进程内 set + Lock。
|
||||
|
||||
Args:
|
||||
jti: 令牌唯一标识。
|
||||
ttl_seconds: 剩余有效秒数(与令牌 exp 对齐)。
|
||||
|
||||
Returns:
|
||||
True 表示首次消费成功;False 表示已被消费。
|
||||
"""
|
||||
key = f'{_JTI_REDIS_KEY_PREFIX}{jti}'
|
||||
ttl = max(1, int(ttl_seconds))
|
||||
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)
|
||||
|
||||
|
||||
def _validate_token_bindings(
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
actor_id: int,
|
||||
profile_id: int | None,
|
||||
document_id: int | None,
|
||||
path_id: str,
|
||||
rule_fingerprint: str,
|
||||
sample_checksum: str,
|
||||
analysis_id: int | None = None,
|
||||
template_packet_checksum: str | None = None,
|
||||
dataset_structure_fingerprint: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
校验令牌 payload 与当前请求上下文绑定一致(不含 jti 消费)。
|
||||
|
||||
Raises:
|
||||
ValidationError: 任一绑定字段不匹配。
|
||||
"""
|
||||
if int(payload.get('exp') or 0) < int(time.time()):
|
||||
raise ValidationError(
|
||||
'XFA split preview confirmation token expired',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
|
||||
details={'reason': 'expired'},
|
||||
)
|
||||
if int(payload.get('actor_id') or 0) != int(actor_id):
|
||||
raise ValidationError(
|
||||
'XFA split preview confirmation token actor mismatch',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
|
||||
details={'reason': 'actor_mismatch'},
|
||||
)
|
||||
if str(payload.get('path_id') or '') != str(path_id):
|
||||
raise ValidationError(
|
||||
'XFA split preview confirmation token path mismatch',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
|
||||
details={'reason': 'path_mismatch'},
|
||||
)
|
||||
if str(payload.get('rule_fp') or '') != str(rule_fingerprint):
|
||||
raise ValidationError(
|
||||
'XFA split preview confirmation token rule fingerprint mismatch',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
|
||||
details={'reason': 'rule_mismatch'},
|
||||
)
|
||||
token_sample = str(payload.get('sample_checksum') or '').strip()
|
||||
if not token_sample or token_sample != str(sample_checksum or '').strip():
|
||||
raise ValidationError(
|
||||
'XFA split preview confirmation token sample checksum mismatch',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
|
||||
details={'reason': 'sample_checksum_mismatch'},
|
||||
)
|
||||
token_profile = payload.get('profile_id')
|
||||
if token_profile is not None and profile_id is not None and int(token_profile) != int(profile_id):
|
||||
raise ValidationError(
|
||||
'XFA split preview confirmation token profile mismatch',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
|
||||
details={'reason': 'profile_mismatch'},
|
||||
)
|
||||
token_document = payload.get('document_id')
|
||||
if document_id is not None and token_document is not None and int(token_document) != int(document_id):
|
||||
raise ValidationError(
|
||||
'XFA split preview confirmation token document mismatch',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
|
||||
details={'reason': 'document_mismatch'},
|
||||
)
|
||||
token_analysis = payload.get('analysis_id')
|
||||
if analysis_id is not None and token_analysis is not None and int(token_analysis) != int(analysis_id):
|
||||
raise ValidationError(
|
||||
'XFA split preview confirmation token analysis mismatch',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
|
||||
details={'reason': 'analysis_mismatch'},
|
||||
)
|
||||
token_template = str(payload.get('template_packet_checksum') or '').strip()
|
||||
expected_template = str(template_packet_checksum or '').strip()
|
||||
if token_template and expected_template and token_template != expected_template:
|
||||
raise ValidationError(
|
||||
'XFA split preview confirmation token template checksum mismatch',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
|
||||
details={'reason': 'template_checksum_mismatch'},
|
||||
)
|
||||
token_fp = str(payload.get('dataset_structure_fingerprint') or '').strip()
|
||||
expected_fp = str(dataset_structure_fingerprint or '').strip()
|
||||
if token_fp and expected_fp and token_fp != expected_fp:
|
||||
raise ValidationError(
|
||||
'XFA split preview confirmation token structure fingerprint mismatch',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
|
||||
details={'reason': 'structure_fingerprint_mismatch'},
|
||||
)
|
||||
|
||||
|
||||
def _decode_and_verify_signature(token: str) -> dict[str, Any]:
|
||||
"""
|
||||
解码并验签令牌,返回 payload。
|
||||
|
||||
Raises:
|
||||
ValidationError: 令牌缺失、伪造或 payload 非法。
|
||||
"""
|
||||
text = str(token or '').strip()
|
||||
if not text or '.' not in text:
|
||||
raise ValidationError(
|
||||
'XFA split preview confirmation token is required',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
|
||||
details={'reason': 'token_missing'},
|
||||
)
|
||||
payload_hex, _, sig = text.partition('.')
|
||||
try:
|
||||
raw = bytes.fromhex(payload_hex)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(
|
||||
'XFA split preview confirmation token is invalid',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
|
||||
details={'reason': 'token_malformed'},
|
||||
) from exc
|
||||
expected = hmac.new(_signing_secret(), raw, hashlib.sha256).hexdigest()
|
||||
if not hmac.compare_digest(expected, sig):
|
||||
raise ValidationError(
|
||||
'XFA split preview confirmation token signature mismatch',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
|
||||
details={'reason': 'bad_signature'},
|
||||
)
|
||||
try:
|
||||
payload = json.loads(raw.decode('utf-8'))
|
||||
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
raise ValidationError(
|
||||
'XFA split preview confirmation token payload is invalid',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
|
||||
details={'reason': 'bad_payload'},
|
||||
) from exc
|
||||
if not isinstance(payload, dict):
|
||||
raise ValidationError(
|
||||
'XFA split preview confirmation token payload is invalid',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
|
||||
details={'reason': 'bad_payload'},
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def issue_split_preview_token(
|
||||
*,
|
||||
actor_id: int,
|
||||
profile_id: int | None,
|
||||
document_id: int,
|
||||
path_id: str,
|
||||
rule_fingerprint: str,
|
||||
sample_checksum: str,
|
||||
analysis_id: int | None = None,
|
||||
template_packet_checksum: str | None = None,
|
||||
dataset_structure_fingerprint: str | None = None,
|
||||
ttl_seconds: int = DEFAULT_SPLIT_PREVIEW_TOKEN_TTL_SECONDS,
|
||||
) -> str:
|
||||
"""
|
||||
签发可验证的拆分预览确认令牌。
|
||||
|
||||
核心逻辑:payload 含 jti、actor/profile/document/path/规则指纹/样本 checksum 与
|
||||
可选 analysis/template/structure 绑定;HMAC-SHA256 签名后以 hex 拼接。
|
||||
|
||||
Args:
|
||||
actor_id: 预览操作者。
|
||||
profile_id: Profile 主键(可空,保存时须与请求一致)。
|
||||
document_id: 样本文档 ID。
|
||||
path_id: 源字段 path_id。
|
||||
rule_fingerprint: 规则内容指纹。
|
||||
sample_checksum: 源叶子 raw_value 的 SHA256 前 32 位 hex(必填)。
|
||||
analysis_id: 结构分析 ID(可空;有则保存时校验)。
|
||||
template_packet_checksum: 模板包 checksum(可空;有则校验)。
|
||||
dataset_structure_fingerprint: 数据集结构指纹(可空;有则校验)。
|
||||
ttl_seconds: 有效期秒数。
|
||||
|
||||
Returns:
|
||||
令牌字符串。
|
||||
"""
|
||||
exp = int(time.time()) + max(60, int(ttl_seconds))
|
||||
payload: dict[str, Any] = {
|
||||
'v': 2,
|
||||
'jti': secrets.token_hex(16),
|
||||
'actor_id': int(actor_id),
|
||||
'profile_id': int(profile_id) if profile_id is not None else None,
|
||||
'document_id': int(document_id),
|
||||
'path_id': str(path_id),
|
||||
'rule_fp': str(rule_fingerprint),
|
||||
'sample_checksum': str(sample_checksum).strip(),
|
||||
'exp': exp,
|
||||
}
|
||||
if analysis_id is not None:
|
||||
payload['analysis_id'] = int(analysis_id)
|
||||
if template_packet_checksum:
|
||||
payload['template_packet_checksum'] = str(template_packet_checksum).strip()
|
||||
if dataset_structure_fingerprint:
|
||||
payload['dataset_structure_fingerprint'] = str(dataset_structure_fingerprint).strip()
|
||||
raw = json.dumps(payload, sort_keys=True, separators=(',', ':')).encode('utf-8')
|
||||
payload_hex = raw.hex()
|
||||
sig = hmac.new(_signing_secret(), raw, hashlib.sha256).hexdigest()
|
||||
return f'{payload_hex}.{sig}'
|
||||
|
||||
|
||||
def verify_split_preview_token(
|
||||
token: str,
|
||||
*,
|
||||
actor_id: int,
|
||||
profile_id: int | None,
|
||||
document_id: int | None,
|
||||
path_id: str,
|
||||
rule_fingerprint: str,
|
||||
sample_checksum: str,
|
||||
analysis_id: int | None = None,
|
||||
template_packet_checksum: str | None = None,
|
||||
dataset_structure_fingerprint: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
纯验签校验拆分预览确认令牌并返回 payload(不消费 jti)。
|
||||
|
||||
核心逻辑:验签 → 绑定字段比对;保存路径须改用 verify_and_consume_split_preview_token。
|
||||
|
||||
Args:
|
||||
token: 预览接口返回的令牌。
|
||||
actor_id: 当前操作者(须与签发者相同)。
|
||||
profile_id: 当前 Profile。
|
||||
document_id: 可选样本文档;提供时须匹配。
|
||||
path_id: 规则源 path_id。
|
||||
rule_fingerprint: 待确认规则内容指纹。
|
||||
sample_checksum: 当前样本源叶子 checksum。
|
||||
analysis_id: 当前结构分析 ID(可选)。
|
||||
template_packet_checksum: 当前模板包 checksum(可选)。
|
||||
dataset_structure_fingerprint: 当前结构指纹(可选)。
|
||||
|
||||
Returns:
|
||||
已校验 payload dict。
|
||||
|
||||
Raises:
|
||||
ValidationError: 令牌缺失、伪造、过期或绑定不匹配。
|
||||
"""
|
||||
payload = _decode_and_verify_signature(token)
|
||||
_validate_token_bindings(
|
||||
payload,
|
||||
actor_id=actor_id,
|
||||
profile_id=profile_id,
|
||||
document_id=document_id,
|
||||
path_id=path_id,
|
||||
rule_fingerprint=rule_fingerprint,
|
||||
sample_checksum=sample_checksum,
|
||||
analysis_id=analysis_id,
|
||||
template_packet_checksum=template_packet_checksum,
|
||||
dataset_structure_fingerprint=dataset_structure_fingerprint,
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def verify_and_consume_split_preview_token(
|
||||
token: str,
|
||||
*,
|
||||
actor_id: int,
|
||||
profile_id: int | None,
|
||||
document_id: int | None,
|
||||
path_id: str,
|
||||
rule_fingerprint: str,
|
||||
sample_checksum: str,
|
||||
analysis_id: int | None = None,
|
||||
template_packet_checksum: str | None = None,
|
||||
dataset_structure_fingerprint: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
验签并原子消费拆分预览确认令牌。
|
||||
|
||||
核心逻辑:验签与绑定校验通过后,以 Redis SET NX EX(或进程内兜底)标记 jti 已消费;
|
||||
重复消费抛 token_replay。
|
||||
|
||||
Args:
|
||||
token: 预览接口返回的令牌。
|
||||
actor_id: 当前操作者。
|
||||
profile_id: 当前 Profile。
|
||||
document_id: 样本文档 ID。
|
||||
path_id: 规则源 path_id。
|
||||
rule_fingerprint: 待确认规则内容指纹。
|
||||
sample_checksum: 当前样本源叶子 checksum。
|
||||
analysis_id: 当前结构分析 ID(可选)。
|
||||
template_packet_checksum: 当前模板包 checksum(可选)。
|
||||
dataset_structure_fingerprint: 当前结构指纹(可选)。
|
||||
|
||||
Returns:
|
||||
已校验且已消费的 payload dict。
|
||||
|
||||
Raises:
|
||||
ValidationError: 令牌无效、绑定不匹配或已被消费(重放)。
|
||||
"""
|
||||
payload = _decode_and_verify_signature(token)
|
||||
_validate_token_bindings(
|
||||
payload,
|
||||
actor_id=actor_id,
|
||||
profile_id=profile_id,
|
||||
document_id=document_id,
|
||||
path_id=path_id,
|
||||
rule_fingerprint=rule_fingerprint,
|
||||
sample_checksum=sample_checksum,
|
||||
analysis_id=analysis_id,
|
||||
template_packet_checksum=template_packet_checksum,
|
||||
dataset_structure_fingerprint=dataset_structure_fingerprint,
|
||||
)
|
||||
jti = str(payload.get('jti') or '').strip()
|
||||
if not jti:
|
||||
raise ValidationError(
|
||||
'XFA split preview confirmation token is invalid',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
|
||||
details={'reason': 'jti_missing'},
|
||||
)
|
||||
remaining_ttl = max(1, int(payload.get('exp') or 0) - int(time.time()))
|
||||
if not _try_consume_jti(jti=jti, ttl_seconds=remaining_ttl):
|
||||
raise ValidationError(
|
||||
'XFA split preview confirmation token was already used',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
|
||||
details={'reason': 'token_replay'},
|
||||
)
|
||||
return payload
|
||||
@@ -1,71 +1,123 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_split_rule_contract.py
|
||||
|
||||
用途:冻结 XFA 字段拆分规则契约——自定义 segment、多阶段 stages 白名单、
|
||||
Schema 映射限制、evidence_only 边界与正则资源上限。
|
||||
依赖:Pydantic 2、标准库 re/uuid;被 xfa_split_rule_engine、
|
||||
order_document_profile_service 与正式提取路径引用。
|
||||
用途:冻结 XFA 字段拆分规则契约——matcher 优先级模型、segment 映射、
|
||||
evidence_only 边界、正则资源上限与 Schema 校验入口。
|
||||
依赖:Pydantic 2、xfa_contract、xfa_safe_regex、Flask settings(可选)。
|
||||
逻辑:仅声明式校验,不执行规则、不读 PDF、不接网络;非法契约以 ValidationError
|
||||
或 ValueError 拒绝;不提供系统推荐;若残留 source=system_suggestion 必须 draft。
|
||||
或 ValueError 拒绝;匹配优先级由引擎固定 prefix > regex > position > unmatched。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from typing import Any, Final, Literal
|
||||
|
||||
from pydantic import Field, field_validator, model_validator
|
||||
from pydantic import AliasChoices, Field, field_validator, model_validator
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XfaContractModel,
|
||||
validate_controlled_data_path,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_safe_regex import (
|
||||
SafeRegexError,
|
||||
validate_restricted_regex_pattern,
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 资源上限(防止灾难性回溯与规则爆炸)
|
||||
# 资源上限默认值(可被 settings / 环境变量覆盖)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
XFA_SPLIT_MAX_RULES_PER_SET: Final[int] = 32
|
||||
XFA_SPLIT_MAX_RULE_SETS: Final[int] = 64
|
||||
XFA_SPLIT_MAX_STAGES_PER_RULE: Final[int] = 16
|
||||
XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH: Final[int] = 128
|
||||
XFA_SPLIT_MAX_REGEX_GROUPS: Final[int] = 5
|
||||
XFA_SPLIT_MAX_PREFIX_LENGTH: Final[int] = 64
|
||||
XFA_SPLIT_MAX_SEGMENT_CODE_LENGTH: Final[int] = 64
|
||||
XFA_SPLIT_MAX_DISPLAY_NAME_LENGTH: Final[int] = 128
|
||||
XFA_SPLIT_MAX_REPLACE_LENGTH: Final[int] = 128
|
||||
XFA_SPLIT_MAX_INPUT_LENGTH: Final[int] = 32_768
|
||||
XFA_SPLIT_REGEX_TIMEOUT_MS: Final[int] = 50
|
||||
|
||||
# 引擎固定匹配优先级(数值越小优先级越高)
|
||||
XFA_SPLIT_MATCHER_PRIORITY: Final[dict[str, int]] = {
|
||||
'prefix': 0,
|
||||
'regex': 1,
|
||||
'position': 2,
|
||||
}
|
||||
XFA_SPLIT_UNMATCHED_PRIORITY: Final[int] = 3
|
||||
|
||||
XfaSplitHandling = Literal['mapped', 'evidence_only']
|
||||
XfaSplitStageType = Literal[
|
||||
'split_lines',
|
||||
'select_line',
|
||||
'select_line_range',
|
||||
'extract_prefix',
|
||||
'regex_capture',
|
||||
'replace',
|
||||
'substring',
|
||||
'normalize',
|
||||
]
|
||||
XfaSplitStrategy = Literal['pipeline']
|
||||
XfaSplitMatcherType = Literal['position', 'prefix', 'regex']
|
||||
XfaSplitSourceScope = Literal['header', 'line']
|
||||
XfaSplitUnmatchedPolicy = Literal['evidence_only', 'needs_review']
|
||||
XfaSplitDuplicatePolicy = Literal['needs_review']
|
||||
XfaSplitRuleStatus = Literal['draft', 'confirmed', 'published']
|
||||
XfaSplitRuleSource = Literal['system_suggestion', 'user', 'imported']
|
||||
|
||||
_SEGMENT_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,63}$')
|
||||
_REGEX_FORBIDDEN = (
|
||||
'(?P', # named groups
|
||||
'(?R', # recursive
|
||||
'(?&',
|
||||
'\\g',
|
||||
)
|
||||
# 常见灾难性回溯形态(启发式,不保证穷尽)
|
||||
_REGEX_CATASTROPHIC = (
|
||||
re.compile(r'\([^)]*[+*][^)]*\)[+*]'),
|
||||
re.compile(r'\([^)]*[+*][^)]*\)\{'),
|
||||
)
|
||||
|
||||
|
||||
def _config_int(key: str, default: int) -> int:
|
||||
"""
|
||||
从 Flask config 或环境变量读取整型配置。
|
||||
|
||||
Args:
|
||||
key: 配置键名。
|
||||
default: 缺失时的默认值。
|
||||
|
||||
Returns:
|
||||
解析后的正整数。
|
||||
"""
|
||||
try:
|
||||
from flask import has_app_context, current_app
|
||||
|
||||
if has_app_context():
|
||||
raw = current_app.config.get(key)
|
||||
if raw is not None:
|
||||
return max(1, int(raw))
|
||||
except Exception:
|
||||
pass
|
||||
raw_env = os.getenv(key)
|
||||
if raw_env is not None and str(raw_env).strip():
|
||||
return max(1, int(raw_env))
|
||||
return default
|
||||
|
||||
|
||||
def get_xfa_split_max_rules_per_set() -> int:
|
||||
"""单规则集最大 rules 条数。"""
|
||||
return _config_int('XFA_SPLIT_MAX_RULES_PER_SET', XFA_SPLIT_MAX_RULES_PER_SET)
|
||||
|
||||
|
||||
def get_xfa_split_max_rule_sets() -> int:
|
||||
"""Profile 最大 split_rules 规则集数。"""
|
||||
return _config_int('XFA_SPLIT_MAX_RULE_SETS', XFA_SPLIT_MAX_RULE_SETS)
|
||||
|
||||
|
||||
def get_xfa_split_max_regex_pattern_length() -> int:
|
||||
"""单条正则模式最大长度。"""
|
||||
return _config_int('XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH', XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH)
|
||||
|
||||
|
||||
def get_xfa_split_max_regex_groups() -> int:
|
||||
"""正则最大捕获组数。"""
|
||||
return _config_int('XFA_SPLIT_MAX_REGEX_GROUPS', XFA_SPLIT_MAX_REGEX_GROUPS)
|
||||
|
||||
|
||||
def get_xfa_split_max_prefix_length() -> int:
|
||||
"""前缀标签最大长度。"""
|
||||
return _config_int('XFA_SPLIT_MAX_PREFIX_LENGTH', XFA_SPLIT_MAX_PREFIX_LENGTH)
|
||||
|
||||
|
||||
def get_xfa_split_max_input_length() -> int:
|
||||
"""拆分源字段最大输入长度。"""
|
||||
return _config_int('XFA_SPLIT_MAX_INPUT_LENGTH', XFA_SPLIT_MAX_INPUT_LENGTH)
|
||||
|
||||
|
||||
def get_xfa_split_regex_timeout_ms() -> int:
|
||||
"""正则执行超时(毫秒)。"""
|
||||
return _config_int('XFA_SPLIT_REGEX_TIMEOUT_MS', XFA_SPLIT_REGEX_TIMEOUT_MS)
|
||||
|
||||
|
||||
class XfaSplitSegment(XfaContractModel):
|
||||
@@ -102,125 +154,73 @@ class XfaSplitSegment(XfaContractModel):
|
||||
return self
|
||||
|
||||
|
||||
class XfaSplitStage(XfaContractModel):
|
||||
class XfaSplitMatcher(XfaContractModel):
|
||||
"""
|
||||
单阶段处理步骤(声明式流水线节点)。
|
||||
单行匹配器:position / prefix / regex。
|
||||
|
||||
状态机:split_lines 产出行列表;select_line/select_line_range 产出标量并记录行号范围;
|
||||
其余阶段在标量文本上变换。
|
||||
优先级由引擎固定为 prefix > regex > position;契约仅声明字段形状。
|
||||
"""
|
||||
|
||||
stage_id: str = Field(min_length=1, max_length=64)
|
||||
type: XfaSplitStageType
|
||||
# split_lines / normalize
|
||||
trim: bool = True
|
||||
remove_empty_lines: bool = True
|
||||
line_breaks: list[str] = Field(default_factory=lambda: ['\r\n', '\r', '\n'])
|
||||
# select_line
|
||||
type: XfaSplitMatcherType
|
||||
line_index: int | None = Field(default=None, ge=1, le=1000)
|
||||
# select_line_range
|
||||
line_start: 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'] = 'newline'
|
||||
# extract_prefix
|
||||
value: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_PREFIX_LENGTH)
|
||||
case_sensitive: bool = False
|
||||
separators: list[str] = Field(default_factory=lambda: [':', ':'])
|
||||
# regex_capture
|
||||
case_sensitive: bool = False
|
||||
pattern: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH)
|
||||
capture_group: int | None = Field(default=None, ge=0, le=XFA_SPLIT_MAX_REGEX_GROUPS)
|
||||
# replace
|
||||
find: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_REPLACE_LENGTH)
|
||||
replace_with: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_REPLACE_LENGTH)
|
||||
# substring(0-based,end 不含)
|
||||
start: int | None = Field(default=None, ge=0, le=10_000)
|
||||
end: int | None = Field(default=None, ge=0, le=10_000)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_stage_shape(self) -> 'XfaSplitStage':
|
||||
"""按 type 校验必填字段与正则安全边界。"""
|
||||
if self.type == 'split_lines':
|
||||
breaks = [str(item) for item in (self.line_breaks or []) if str(item)]
|
||||
if not breaks:
|
||||
raise ValueError('split_lines requires at least one line_break')
|
||||
object.__setattr__(self, 'line_breaks', breaks)
|
||||
elif self.type == 'select_line':
|
||||
def validate_matcher_shape(self) -> 'XfaSplitMatcher':
|
||||
"""按 type 校验必填字段、前缀与正则安全边界。"""
|
||||
max_prefix = get_xfa_split_max_prefix_length()
|
||||
max_pattern_len = get_xfa_split_max_regex_pattern_length()
|
||||
max_groups = get_xfa_split_max_regex_groups()
|
||||
|
||||
if self.type == 'position':
|
||||
if self.line_index is None:
|
||||
raise ValueError('select_line requires line_index (1-based)')
|
||||
elif self.type == 'select_line_range':
|
||||
if self.line_start is None or self.line_end is None:
|
||||
raise ValueError('select_line_range requires line_start and line_end (1-based)')
|
||||
if self.line_end < self.line_start:
|
||||
raise ValueError('select_line_range requires line_end >= line_start')
|
||||
elif self.type == 'extract_prefix':
|
||||
raise ValueError('position matcher requires line_index (1-based)')
|
||||
elif self.type == 'prefix':
|
||||
label = str(self.value or '').strip()
|
||||
if not label:
|
||||
raise ValueError('extract_prefix requires non-empty value')
|
||||
raise ValueError('prefix matcher requires non-empty value')
|
||||
if len(label) > max_prefix:
|
||||
raise ValueError('prefix value exceeds max length')
|
||||
seps = [str(item) for item in (self.separators or []) if str(item)]
|
||||
if not seps:
|
||||
raise ValueError('extract_prefix requires at least one separator')
|
||||
raise ValueError('prefix matcher requires at least one separator')
|
||||
object.__setattr__(self, 'separators', seps)
|
||||
object.__setattr__(self, 'value', label)
|
||||
elif self.type == 'regex_capture':
|
||||
elif self.type == 'regex':
|
||||
pattern = str(self.pattern or '')
|
||||
if not pattern:
|
||||
raise ValueError('regex_capture requires pattern')
|
||||
if len(pattern) > XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH:
|
||||
raise ValueError('regex matcher requires pattern')
|
||||
if len(pattern) > max_pattern_len:
|
||||
raise ValueError('regex pattern exceeds max length')
|
||||
for token in _REGEX_FORBIDDEN:
|
||||
if token in pattern:
|
||||
raise ValueError(f'regex pattern contains forbidden construct: {token}')
|
||||
for probe in _REGEX_CATASTROPHIC:
|
||||
if probe.search(pattern):
|
||||
raise ValueError('regex pattern looks catastrophic (nested quantifiers)')
|
||||
try:
|
||||
compiled = re.compile(pattern)
|
||||
except re.error as exc:
|
||||
raise ValueError(f'invalid regex pattern: {exc}') from exc
|
||||
if compiled.groups > XFA_SPLIT_MAX_REGEX_GROUPS:
|
||||
raise ValueError('regex capture groups exceed limit')
|
||||
if self.capture_group is not None and self.capture_group > compiled.groups:
|
||||
raise ValueError('capture_group exceeds pattern groups')
|
||||
elif self.type == 'replace':
|
||||
if self.find is None or str(self.find) == '':
|
||||
raise ValueError('replace requires non-empty find')
|
||||
if self.replace_with is None:
|
||||
object.__setattr__(self, 'replace_with', '')
|
||||
elif self.type == 'substring':
|
||||
if self.start is None:
|
||||
raise ValueError('substring requires start')
|
||||
if self.end is not None and self.end < self.start:
|
||||
raise ValueError('substring end must be >= start')
|
||||
elif self.type == 'normalize':
|
||||
pass
|
||||
validate_restricted_regex_pattern(
|
||||
pattern,
|
||||
max_length=max_pattern_len,
|
||||
max_groups=max_groups,
|
||||
)
|
||||
except SafeRegexError as exc:
|
||||
raise ValueError(str(exc)) from exc
|
||||
if self.capture_group is not None and self.capture_group > max_groups:
|
||||
raise ValueError('capture_group exceeds pattern groups limit')
|
||||
else:
|
||||
raise ValueError(f'unsupported matcher type: {self.type}')
|
||||
return self
|
||||
|
||||
|
||||
class XfaSplitRule(XfaContractModel):
|
||||
"""单条输出流水线:显式 order + stages[] + segment。"""
|
||||
"""单条拆分规则:rule_id + matcher + segment(无 stages[])。"""
|
||||
|
||||
rule_id: str = Field(min_length=1, max_length=64)
|
||||
order: int = Field(ge=1, le=10_000)
|
||||
matcher: XfaSplitMatcher
|
||||
segment: XfaSplitSegment
|
||||
stages: list[XfaSplitStage] = Field(min_length=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_pipeline(self) -> 'XfaSplitRule':
|
||||
"""校验 stages 数量与 stage_id 唯一。"""
|
||||
if len(self.stages) > XFA_SPLIT_MAX_STAGES_PER_RULE:
|
||||
raise ValueError(f'stages exceed max {XFA_SPLIT_MAX_STAGES_PER_RULE}')
|
||||
stage_ids = [item.stage_id for item in self.stages]
|
||||
if len(stage_ids) != len(set(stage_ids)):
|
||||
raise ValueError('duplicate stage_id within split rule')
|
||||
return self
|
||||
|
||||
|
||||
class XfaSplitNormalization(XfaContractModel):
|
||||
"""
|
||||
规则集级默认换行策略:用于未匹配行盘点与无 split_lines 时的行清单。
|
||||
|
||||
流水线内仍以 stages.split_lines 为准。
|
||||
"""
|
||||
"""规则集级换行与 trim 策略:引擎按 line_breaks 拆行后再逐行匹配。"""
|
||||
|
||||
trim: bool = True
|
||||
remove_empty_lines: bool = True
|
||||
@@ -244,12 +244,16 @@ class XfaSplitRuleSet(XfaContractModel):
|
||||
必须保持 draft + requires_confirmation,且不得进入正式提取/发布。
|
||||
"""
|
||||
|
||||
rule_id: str = Field(min_length=1, max_length=128)
|
||||
rule_set_id: str = Field(
|
||||
min_length=1,
|
||||
max_length=128,
|
||||
validation_alias=AliasChoices('rule_set_id', 'rule_id'),
|
||||
)
|
||||
rule_version: int = Field(ge=1, le=10_000)
|
||||
source_path_id: str = Field(min_length=1, max_length=128)
|
||||
source_field_code: str = Field(min_length=1, max_length=128)
|
||||
source_scope: XfaSplitSourceScope = 'line'
|
||||
source_field_code: str | None = Field(default=None, max_length=128)
|
||||
source_data_path: str | None = Field(default=None, min_length=1, max_length=512)
|
||||
strategy: XfaSplitStrategy = 'pipeline'
|
||||
normalization: XfaSplitNormalization = Field(default_factory=XfaSplitNormalization)
|
||||
rules: list[XfaSplitRule] = Field(default_factory=list)
|
||||
unmatched_line_policy: XfaSplitUnmatchedPolicy = 'evidence_only'
|
||||
@@ -259,6 +263,11 @@ class XfaSplitRuleSet(XfaContractModel):
|
||||
status: XfaSplitRuleStatus = 'draft'
|
||||
requires_confirmation: bool = False
|
||||
|
||||
@property
|
||||
def rule_id(self) -> str:
|
||||
"""兼容旧字段名 rule_id(等同 rule_set_id)。"""
|
||||
return self.rule_set_id
|
||||
|
||||
@field_validator('source_data_path', mode='before')
|
||||
@classmethod
|
||||
def validate_source_data_path(cls, value: Any) -> str | None:
|
||||
@@ -270,14 +279,12 @@ class XfaSplitRuleSet(XfaContractModel):
|
||||
@model_validator(mode='after')
|
||||
def validate_rule_set_invariants(self) -> 'XfaSplitRuleSet':
|
||||
"""规则集内唯一性与数量上限。"""
|
||||
if len(self.rules) > XFA_SPLIT_MAX_RULES_PER_SET:
|
||||
raise ValueError(f'rules exceed max {XFA_SPLIT_MAX_RULES_PER_SET}')
|
||||
max_rules = get_xfa_split_max_rules_per_set()
|
||||
if len(self.rules) > max_rules:
|
||||
raise ValueError(f'rules exceed max {max_rules}')
|
||||
rule_ids = [item.rule_id for item in self.rules]
|
||||
if len(rule_ids) != len(set(rule_ids)):
|
||||
raise ValueError('duplicate rule_id within split rule set')
|
||||
orders = [item.order for item in self.rules]
|
||||
if len(orders) != len(set(orders)):
|
||||
raise ValueError('duplicate order within split rule set')
|
||||
segment_ids = [item.segment.segment_id for item in self.rules]
|
||||
if len(segment_ids) != len(set(segment_ids)):
|
||||
raise ValueError('duplicate segment_id within split rule set')
|
||||
@@ -316,25 +323,12 @@ def new_rule_id(prefix: str = 'rule') -> str:
|
||||
return f'{safe}-{uuid.uuid4().hex[:12]}'
|
||||
|
||||
|
||||
def new_stage_id(prefix: str = 'stage') -> str:
|
||||
"""
|
||||
生成 stage_id。
|
||||
|
||||
Args:
|
||||
prefix: ID 前缀。
|
||||
|
||||
Returns:
|
||||
形如 ``{prefix}-<hex>`` 的标识。
|
||||
"""
|
||||
safe = re.sub(r'[^a-z0-9_]+', '_', str(prefix or 'stage').strip().lower()) or 'stage'
|
||||
return f'{safe}-{uuid.uuid4().hex[:10]}'
|
||||
|
||||
|
||||
def split_rule_content_fingerprint(rule_set: XfaSplitRuleSet | dict[str, Any]) -> str:
|
||||
"""
|
||||
计算规则集内容指纹(排除 status / requires_confirmation / rule_version)。
|
||||
|
||||
核心逻辑:用于判断 confirmed 规则内容是否被篡改,需强制回退 Draft。
|
||||
核心逻辑:只冻结 matcher 与 normalization;segment 的 Schema 映射字段不属于拆分逻辑,
|
||||
后续绑定或解绑目标字段不得取消已确认状态。
|
||||
|
||||
Args:
|
||||
rule_set: 模型或 dict。
|
||||
@@ -345,12 +339,22 @@ def split_rule_content_fingerprint(rule_set: XfaSplitRuleSet | dict[str, Any]) -
|
||||
import json
|
||||
|
||||
if isinstance(rule_set, XfaSplitRuleSet):
|
||||
payload = rule_set.model_dump(mode='json')
|
||||
payload = rule_set.model_dump(mode='json', by_alias=True)
|
||||
else:
|
||||
payload = dict(rule_set or {})
|
||||
if 'rule_set_id' not in payload and payload.get('rule_id'):
|
||||
payload['rule_set_id'] = payload['rule_id']
|
||||
payload.pop('status', None)
|
||||
payload.pop('requires_confirmation', None)
|
||||
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(segment, dict):
|
||||
continue
|
||||
segment.pop('handling', None)
|
||||
segment.pop('target_field_id', None)
|
||||
segment.pop('target_field_code', None)
|
||||
return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
|
||||
|
||||
|
||||
@@ -365,13 +369,13 @@ def validate_split_rules_against_schema(
|
||||
相对冻结 Schema 与已知 path_id 校验拆分规则集。
|
||||
|
||||
核心逻辑:目标字段必须存在、启用且与拆分源节点 scope 一致;
|
||||
source_path_id 必须已知(若提供集合)。
|
||||
source_path_id 必须已知(若提供集合);优先使用 rule_set.source_scope。
|
||||
|
||||
Args:
|
||||
rule_sets: 待校验规则集。
|
||||
known_schema_fields: field_code → Schema 字段配置(仅 enabled)。
|
||||
known_path_ids: 分析记录合法 path_id;None 时跳过路径存在性检查。
|
||||
source_scopes: source_path_id → header/line;未提供时仅校验字段存在性。
|
||||
source_scopes: source_path_id → header/line;未提供时使用 rule_set.source_scope。
|
||||
|
||||
Returns:
|
||||
校验通过的同一列表。
|
||||
@@ -379,13 +383,18 @@ def validate_split_rules_against_schema(
|
||||
Raises:
|
||||
ValueError: 契约或 Schema 引用非法。
|
||||
"""
|
||||
if len(rule_sets) > XFA_SPLIT_MAX_RULE_SETS:
|
||||
raise ValueError(f'split_rules exceed max {XFA_SPLIT_MAX_RULE_SETS}')
|
||||
max_sets = get_xfa_split_max_rule_sets()
|
||||
if len(rule_sets) > max_sets:
|
||||
raise ValueError(f'split_rules exceed max {max_sets}')
|
||||
all_codes: list[str] = []
|
||||
all_segment_ids: list[str] = []
|
||||
for rule_set in rule_sets:
|
||||
if known_path_ids is not None and rule_set.source_path_id not in known_path_ids:
|
||||
raise ValueError(f'unknown source_path_id: {rule_set.source_path_id}')
|
||||
expected_scope = str(rule_set.source_scope or '').strip().lower()
|
||||
scoped = str((source_scopes or {}).get(rule_set.source_path_id) or '').strip().lower()
|
||||
if scoped:
|
||||
expected_scope = scoped
|
||||
for rule in rule_set.rules:
|
||||
all_codes.append(rule.segment.segment_code)
|
||||
all_segment_ids.append(rule.segment.segment_id)
|
||||
@@ -396,7 +405,6 @@ def validate_split_rules_against_schema(
|
||||
if field is None:
|
||||
raise ValueError(f'target Schema field not found or disabled: {code}')
|
||||
scope = str(field.get('scope') or '').strip().lower()
|
||||
expected_scope = str((source_scopes or {}).get(rule_set.source_path_id) or '').strip().lower()
|
||||
if expected_scope and scope != expected_scope:
|
||||
raise ValueError(
|
||||
f'target Schema field {code} must have scope={expected_scope}; got {scope or "missing"}',
|
||||
|
||||
@@ -1,27 +1,34 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_split_rule_engine.py
|
||||
|
||||
用途:声明式执行 XFA 多阶段拆分流水线,产出 mapped Schema 值与 evidence_only 段。
|
||||
依赖:xfa_split_rule_contract、concurrent.futures(正则超时)。
|
||||
用途:按冻结优先级执行 XFA 字段拆分——prefix > regex > position > unmatched。
|
||||
依赖:xfa_split_rule_contract、xfa_safe_regex、concurrent.futures。
|
||||
逻辑:由预览 API 与正式提取调用;无网络、无脚本、无 LLM;
|
||||
每条 rule 按 stages[] 顺序独立变换;显式 order 决定冲突判定次序;
|
||||
同一行被多条流水线 select_line/select_line_range 认领 → needs_review;正式字段冲突 → needs_review。
|
||||
逐行收集命中规则后按优先级决出唯一 segment;同优先级多个 mapped 命中 → needs_review;
|
||||
全部候选命中写入 diagnostics;evidence_only 不写 Schema。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from concurrent.futures import TimeoutError as FuturesTimeoutError
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import XfaLeafValue
|
||||
from app.services.shipping_notice.document_layout.xfa_safe_regex import (
|
||||
SafeRegexError,
|
||||
compile_safe_regex,
|
||||
search_safe,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
XFA_SPLIT_REGEX_TIMEOUT_MS,
|
||||
XFA_SPLIT_MATCHER_PRIORITY,
|
||||
XfaSplitMatcher,
|
||||
XfaSplitRule,
|
||||
XfaSplitRuleSet,
|
||||
XfaSplitStage,
|
||||
get_xfa_split_max_input_length,
|
||||
get_xfa_split_max_regex_groups,
|
||||
get_xfa_split_max_regex_pattern_length,
|
||||
get_xfa_split_regex_timeout_ms,
|
||||
)
|
||||
|
||||
|
||||
@@ -41,7 +48,7 @@ class XfaSplitSegmentResult:
|
||||
target_field_code: str | None
|
||||
rule_id: str
|
||||
status: str
|
||||
matcher_type: str # 兼容预览字段名:末级 stage type 或 unmatched
|
||||
matcher_type: str
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -68,6 +75,18 @@ class XfaSplitEngineResult:
|
||||
rule_version: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class _LineMatch:
|
||||
"""单行候选命中。"""
|
||||
|
||||
rule: XfaSplitRule
|
||||
matcher_type: str
|
||||
priority: int
|
||||
line_text: str
|
||||
normalized_text: str
|
||||
raw_line: str
|
||||
|
||||
|
||||
def _split_text_by_breaks(text: str, line_breaks: list[str]) -> list[str]:
|
||||
"""
|
||||
按声明的 line_breaks 切分文本(长分隔符优先)。
|
||||
@@ -104,9 +123,9 @@ def _apply_line_normalization(
|
||||
|
||||
def _inventory_lines(raw_value: str, rule_set: XfaSplitRuleSet) -> list[str]:
|
||||
"""
|
||||
用规则集级 normalization 生成未匹配行盘点用的行清单。
|
||||
用规则集级 normalization 生成行清单。
|
||||
|
||||
核心逻辑:尊重 normalization.line_breaks(不再忽略配置)。
|
||||
核心逻辑:按 normalization.line_breaks 拆行并应用 trim / 去空行。
|
||||
"""
|
||||
norm = rule_set.normalization
|
||||
lines = _split_text_by_breaks(raw_value or '', list(norm.line_breaks))
|
||||
@@ -117,15 +136,20 @@ def _inventory_lines(raw_value: str, rule_set: XfaSplitRuleSet) -> list[str]:
|
||||
)
|
||||
|
||||
|
||||
def _extract_prefix(text: str, stage: XfaSplitStage) -> str | None:
|
||||
"""前缀提取:标签 + 分隔符后的值。"""
|
||||
label = str(stage.value or '')
|
||||
hay = text if stage.case_sensitive else text.casefold()
|
||||
needle = label if stage.case_sensitive else label.casefold()
|
||||
def _extract_prefix_value(line: str, matcher: XfaSplitMatcher) -> str | None:
|
||||
"""
|
||||
前缀匹配:标签 + 分隔符后的值。
|
||||
|
||||
Returns:
|
||||
提取值;无法匹配时 None。
|
||||
"""
|
||||
label = str(matcher.value or '')
|
||||
hay = line if matcher.case_sensitive else line.casefold()
|
||||
needle = label if matcher.case_sensitive else label.casefold()
|
||||
if not hay.startswith(needle):
|
||||
return None
|
||||
rest = text[len(label):]
|
||||
for sep in stage.separators:
|
||||
rest = line[len(label):]
|
||||
for sep in matcher.separators:
|
||||
if rest.startswith(sep):
|
||||
return rest[len(sep):].strip()
|
||||
stripped = rest.lstrip()
|
||||
@@ -134,50 +158,32 @@ def _extract_prefix(text: str, stage: XfaSplitStage) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def _regex_search(text: str, pattern: str, *, case_sensitive: bool) -> re.Match[str] | None:
|
||||
def _regex_extract_value(line: str, matcher: XfaSplitMatcher) -> tuple[str | None, str | None]:
|
||||
"""
|
||||
带超时的正则搜索。
|
||||
|
||||
Raises:
|
||||
TimeoutError: 超过 XFA_SPLIT_REGEX_TIMEOUT_MS。
|
||||
re.error: 编译失败。
|
||||
"""
|
||||
flags = 0 if case_sensitive else re.IGNORECASE
|
||||
compiled = re.compile(pattern, flags)
|
||||
timeout_s = max(XFA_SPLIT_REGEX_TIMEOUT_MS, 1) / 1000.0
|
||||
|
||||
def _run() -> re.Match[str] | None:
|
||||
return compiled.search(text)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
future = pool.submit(_run)
|
||||
try:
|
||||
return future.result(timeout=timeout_s)
|
||||
except FuturesTimeoutError as exc:
|
||||
future.cancel()
|
||||
raise TimeoutError('regex execution timed out') from exc
|
||||
|
||||
|
||||
def _regex_capture(text: str, stage: XfaSplitStage) -> tuple[str | None, str | None]:
|
||||
"""
|
||||
正则捕获。
|
||||
正则捕获单行文本。
|
||||
|
||||
Returns:
|
||||
(value, error_code);成功时 error_code 为 None。
|
||||
"""
|
||||
pattern = str(matcher.pattern or '')
|
||||
timeout_ms = get_xfa_split_regex_timeout_ms()
|
||||
max_len = get_xfa_split_max_regex_pattern_length()
|
||||
max_groups = get_xfa_split_max_regex_groups()
|
||||
try:
|
||||
matched = _regex_search(
|
||||
text,
|
||||
str(stage.pattern or ''),
|
||||
case_sensitive=bool(stage.case_sensitive),
|
||||
compiled = compile_safe_regex(
|
||||
pattern,
|
||||
case_sensitive=bool(matcher.case_sensitive),
|
||||
max_length=max_len,
|
||||
max_groups=max_groups,
|
||||
)
|
||||
matched = search_safe(compiled, line, timeout_ms=timeout_ms)
|
||||
except SafeRegexError:
|
||||
return None, 'regex_failed'
|
||||
except TimeoutError:
|
||||
return None, 'regex_timeout'
|
||||
except re.error:
|
||||
return None, 'regex_failed'
|
||||
if not matched:
|
||||
return None, 'regex_not_matched'
|
||||
group = stage.capture_group
|
||||
group = matcher.capture_group
|
||||
try:
|
||||
if group is None:
|
||||
if matched.lastindex:
|
||||
@@ -188,81 +194,104 @@ def _regex_capture(text: str, stage: XfaSplitStage) -> tuple[str | None, str | N
|
||||
return None, 'regex_failed'
|
||||
|
||||
|
||||
def _run_pipeline(
|
||||
*,
|
||||
raw_value: str,
|
||||
rule: XfaSplitRule,
|
||||
) -> tuple[str | None, set[int], str, str | None]:
|
||||
def _match_line(line_no: int, line: str, rule: XfaSplitRule) -> tuple[_LineMatch | None, str | None]:
|
||||
"""
|
||||
执行单条规则的 stages 流水线。
|
||||
判断单条规则是否命中指定行。
|
||||
|
||||
Returns:
|
||||
(output_text, claimed_line_numbers, last_stage_type, error_code)
|
||||
error_code 非空表示流水线失败。
|
||||
(match, error_code):命中时 error_code 为 None;未命中时 match 为 None。
|
||||
"""
|
||||
state: str | list[str] = raw_value or ''
|
||||
claimed_lines: set[int] = set()
|
||||
last_type = 'pipeline'
|
||||
for stage in rule.stages:
|
||||
last_type = stage.type
|
||||
if stage.type == 'split_lines':
|
||||
if not isinstance(state, str):
|
||||
return None, claimed_lines, last_type, 'stage_type_mismatch'
|
||||
lines = _split_text_by_breaks(state, list(stage.line_breaks))
|
||||
state = _apply_line_normalization(
|
||||
lines,
|
||||
trim=bool(stage.trim),
|
||||
remove_empty_lines=bool(stage.remove_empty_lines),
|
||||
)
|
||||
continue
|
||||
if stage.type == 'select_line':
|
||||
if not isinstance(state, list):
|
||||
return None, claimed_lines, last_type, 'stage_type_mismatch'
|
||||
idx = int(stage.line_index or 0)
|
||||
if idx < 1 or idx > len(state):
|
||||
return None, claimed_lines, last_type, 'select_line_out_of_range'
|
||||
claimed_lines = {idx}
|
||||
state = state[idx - 1]
|
||||
continue
|
||||
if stage.type == 'select_line_range':
|
||||
if not isinstance(state, list):
|
||||
return None, claimed_lines, last_type, 'stage_type_mismatch'
|
||||
start = int(stage.line_start or 0)
|
||||
end = int(stage.line_end or 0)
|
||||
if start < 1 or end < start or end > len(state):
|
||||
return None, claimed_lines, last_type, 'select_line_range_out_of_range'
|
||||
claimed_lines = set(range(start, end + 1))
|
||||
separator = {'newline': '\n', 'space': ' ', 'comma': ', '}.get(stage.join_with, '\n')
|
||||
state = separator.join(state[start - 1:end])
|
||||
continue
|
||||
if not isinstance(state, str):
|
||||
return None, claimed_lines, last_type, 'stage_type_mismatch'
|
||||
if stage.type == 'extract_prefix':
|
||||
value = _extract_prefix(state, stage)
|
||||
if value is None:
|
||||
return None, claimed_lines, last_type, 'prefix_not_matched'
|
||||
state = value
|
||||
elif stage.type == 'regex_capture':
|
||||
value, err = _regex_capture(state, stage)
|
||||
if err:
|
||||
return None, claimed_lines, last_type, err
|
||||
state = str(value or '')
|
||||
elif stage.type == 'replace':
|
||||
state = state.replace(str(stage.find or ''), str(stage.replace_with or ''))
|
||||
elif stage.type == 'substring':
|
||||
start = int(stage.start or 0)
|
||||
end = len(state) if stage.end is None else int(stage.end)
|
||||
state = state[start:end]
|
||||
elif stage.type == 'normalize':
|
||||
text = state.strip() if stage.trim else state
|
||||
if stage.remove_empty_lines:
|
||||
text = re.sub(r'\s+', ' ', text).strip()
|
||||
state = text
|
||||
else:
|
||||
return None, claimed_lines, last_type, 'unknown_stage'
|
||||
if not isinstance(state, str):
|
||||
return None, claimed_lines, last_type, 'pipeline_ended_on_lines'
|
||||
return state, claimed_lines, last_type, None
|
||||
matcher = rule.matcher
|
||||
priority = XFA_SPLIT_MATCHER_PRIORITY.get(matcher.type)
|
||||
if priority is None:
|
||||
return None, 'unknown_matcher'
|
||||
|
||||
if matcher.type == 'position':
|
||||
if int(matcher.line_index or 0) != line_no:
|
||||
return None, None
|
||||
normalized = line.strip() if line else ''
|
||||
return _LineMatch(
|
||||
rule=rule,
|
||||
matcher_type='position',
|
||||
priority=priority,
|
||||
line_text=line,
|
||||
normalized_text=normalized,
|
||||
raw_line=line,
|
||||
), None
|
||||
|
||||
if matcher.type == 'prefix':
|
||||
extracted = _extract_prefix_value(line, matcher)
|
||||
if extracted is None:
|
||||
return None, None
|
||||
return _LineMatch(
|
||||
rule=rule,
|
||||
matcher_type='prefix',
|
||||
priority=priority,
|
||||
line_text=line,
|
||||
normalized_text=extracted,
|
||||
raw_line=line,
|
||||
), None
|
||||
|
||||
if matcher.type == 'regex':
|
||||
value, err = _regex_extract_value(line, matcher)
|
||||
if err:
|
||||
return None, err
|
||||
if value is None:
|
||||
return None, None
|
||||
return _LineMatch(
|
||||
rule=rule,
|
||||
matcher_type='regex',
|
||||
priority=priority,
|
||||
line_text=line,
|
||||
normalized_text=value,
|
||||
raw_line=line,
|
||||
), None
|
||||
|
||||
return None, 'unknown_matcher'
|
||||
|
||||
|
||||
def _pick_line_winner(
|
||||
line_no: int,
|
||||
matches: list[_LineMatch],
|
||||
diagnostics: list[XfaSplitDiagnostic],
|
||||
) -> _LineMatch | None:
|
||||
"""
|
||||
按 prefix > regex > position 决出单行唯一胜出规则。
|
||||
|
||||
核心逻辑:同优先级多个 mapped 命中 → duplicate_line_match;不同优先级取最高优先级。
|
||||
"""
|
||||
if not matches:
|
||||
return None
|
||||
|
||||
diagnostics.append(XfaSplitDiagnostic(
|
||||
code='line_match_candidates',
|
||||
message='All matcher hits for line recorded',
|
||||
line_no=line_no,
|
||||
rule_ids=[item.rule.rule_id for item in matches],
|
||||
))
|
||||
|
||||
best_priority = min(item.priority for item in matches)
|
||||
tier = [item for item in matches if item.priority == best_priority]
|
||||
mapped_tier = [item for item in tier if item.rule.segment.handling == 'mapped']
|
||||
|
||||
if len(mapped_tier) >= 2:
|
||||
diagnostics.append(XfaSplitDiagnostic(
|
||||
code='duplicate_line_match',
|
||||
message='Multiple mapped rules matched the same line at the same priority',
|
||||
line_no=line_no,
|
||||
rule_ids=[item.rule.rule_id for item in mapped_tier],
|
||||
))
|
||||
|
||||
if len(tier) == 1:
|
||||
return tier[0]
|
||||
|
||||
if len(mapped_tier) == 1:
|
||||
return mapped_tier[0]
|
||||
|
||||
if len(mapped_tier) >= 2:
|
||||
return sorted(mapped_tier, key=lambda item: item.rule.rule_id)[0]
|
||||
|
||||
return sorted(tier, key=lambda item: item.rule.rule_id)[0]
|
||||
|
||||
|
||||
def execute_split_rule_set(
|
||||
@@ -272,87 +301,89 @@ def execute_split_rule_set(
|
||||
lines: list[str] | None = None,
|
||||
) -> XfaSplitEngineResult:
|
||||
"""
|
||||
对单个源字段原值执行多阶段拆分规则集。
|
||||
对单个源字段原值执行拆分规则集。
|
||||
|
||||
核心逻辑:
|
||||
1. 按 order 升序执行每条输出流水线;
|
||||
2. select_line/select_line_range 认领行号;范围重叠 → duplicate_line_match;
|
||||
3. 未认领行按 unmatched_line_policy;
|
||||
4. 同一正式字段多段命中 → needs_review;
|
||||
1. normalization.line_breaks 拆行;
|
||||
2. 逐行收集命中规则,按 prefix > regex > position 决出唯一 segment;
|
||||
3. 同优先级多个 mapped 命中 → duplicate_line_match / needs_review;
|
||||
4. 未认领行按 unmatched_line_policy;
|
||||
5. evidence_only 全部保留。
|
||||
|
||||
Args:
|
||||
raw_value: 保留换行的原始叶子值。
|
||||
rule_set: 已校验规则集。
|
||||
lines: 可选预切分行(仅覆盖未匹配盘点;流水线仍从 raw 起步)。
|
||||
lines: 可选预切分行(覆盖 normalization 结果)。
|
||||
|
||||
Returns:
|
||||
XfaSplitEngineResult。
|
||||
"""
|
||||
if len(raw_value or '') > get_xfa_split_max_input_length():
|
||||
return XfaSplitEngineResult(
|
||||
status='needs_review',
|
||||
diagnostics=[XfaSplitDiagnostic(
|
||||
code='input_too_long',
|
||||
message='Split source value exceeds max input length',
|
||||
)],
|
||||
rule_id=rule_set.rule_set_id,
|
||||
rule_version=rule_set.rule_version,
|
||||
)
|
||||
|
||||
inventory = list(lines) if lines is not None else _inventory_lines(raw_value, rule_set)
|
||||
diagnostics: list[XfaSplitDiagnostic] = []
|
||||
segments: list[XfaSplitSegmentResult] = []
|
||||
line_claims: dict[int, list[str]] = {}
|
||||
claimed_lines: set[int] = set()
|
||||
|
||||
ordered_rules = sorted(rule_set.rules, key=lambda item: (item.order, item.rule_id))
|
||||
# [STEP 1] 逐行匹配并按优先级决出胜出规则。
|
||||
for line_no, line in enumerate(inventory, start=1):
|
||||
matches: list[_LineMatch] = []
|
||||
for rule in rule_set.rules:
|
||||
outcome, error = _match_line(line_no, line, rule)
|
||||
if error:
|
||||
diagnostics.append(XfaSplitDiagnostic(
|
||||
code=error,
|
||||
message=f'Rule {rule.rule_id} regex failed on line {line_no}',
|
||||
line_no=line_no,
|
||||
field_code=rule.segment.target_field_code,
|
||||
rule_ids=[rule.rule_id],
|
||||
))
|
||||
continue
|
||||
if outcome is not None:
|
||||
matches.append(outcome)
|
||||
|
||||
# [STEP 1] 独立执行各输出流水线。
|
||||
for rule in ordered_rules:
|
||||
text, claimed_lines, last_type, error = _run_pipeline(raw_value=raw_value, rule=rule)
|
||||
claimed_start = min(claimed_lines) if claimed_lines else None
|
||||
claimed_end = max(claimed_lines) if claimed_lines else None
|
||||
seg = rule.segment
|
||||
if error:
|
||||
diagnostics.append(XfaSplitDiagnostic(
|
||||
code=error,
|
||||
message=f'Pipeline {rule.rule_id} failed at stage type={last_type}: {error}',
|
||||
line_no=claimed_start,
|
||||
field_code=seg.target_field_code,
|
||||
rule_ids=[rule.rule_id],
|
||||
))
|
||||
winner = _pick_line_winner(line_no, matches, diagnostics)
|
||||
if winner is None:
|
||||
continue
|
||||
assert text is not None
|
||||
for claimed_line in claimed_lines:
|
||||
line_claims.setdefault(claimed_line, []).append(rule.rule_id)
|
||||
|
||||
claimed_lines.add(line_no)
|
||||
seg = winner.rule.segment
|
||||
status = 'parsed'
|
||||
if not str(text).strip() and seg.handling == 'mapped':
|
||||
if not str(winner.normalized_text).strip() and seg.handling == 'mapped':
|
||||
status = 'needs_review'
|
||||
diagnostics.append(XfaSplitDiagnostic(
|
||||
code='mapped_value_empty',
|
||||
message=f'Mapped segment {seg.segment_code} extracted empty value',
|
||||
line_no=claimed_start,
|
||||
line_no=line_no,
|
||||
field_code=seg.target_field_code,
|
||||
rule_ids=[rule.rule_id],
|
||||
rule_ids=[winner.rule.rule_id],
|
||||
))
|
||||
segments.append(XfaSplitSegmentResult(
|
||||
segment_id=seg.segment_id,
|
||||
segment_code=seg.segment_code,
|
||||
display_name=seg.display_name,
|
||||
line_no=claimed_start,
|
||||
line_end_no=claimed_end,
|
||||
raw_text=str(text),
|
||||
normalized_text=str(text).strip(),
|
||||
line_no=line_no,
|
||||
line_end_no=line_no,
|
||||
raw_text=winner.raw_line,
|
||||
normalized_text=winner.normalized_text,
|
||||
handling=seg.handling,
|
||||
target_field_id=seg.target_field_id,
|
||||
target_field_code=seg.target_field_code,
|
||||
rule_id=rule.rule_id,
|
||||
rule_id=winner.rule.rule_id,
|
||||
status=status,
|
||||
matcher_type=last_type,
|
||||
matcher_type=winner.matcher_type,
|
||||
))
|
||||
|
||||
# [STEP 2] 同行多规则认领冲突(不再 break 短路)。
|
||||
for line_no, rule_ids in sorted(line_claims.items()):
|
||||
if len(rule_ids) > 1:
|
||||
diagnostics.append(XfaSplitDiagnostic(
|
||||
code='duplicate_line_match',
|
||||
message='Multiple pipelines claimed the same line',
|
||||
line_no=line_no,
|
||||
rule_ids=list(rule_ids),
|
||||
))
|
||||
|
||||
claimed_lines = set(line_claims)
|
||||
|
||||
# [STEP 3] 未匹配行。
|
||||
# [STEP 2] 未匹配行。
|
||||
for line_index, line in enumerate(inventory, start=1):
|
||||
if line_index in claimed_lines:
|
||||
continue
|
||||
@@ -379,7 +410,7 @@ def execute_split_rule_set(
|
||||
matcher_type='unmatched',
|
||||
))
|
||||
|
||||
# [STEP 4] 聚合正式字段。
|
||||
# [STEP 3] 聚合正式字段。
|
||||
mapped_fields: dict[str, str] = {}
|
||||
field_sources: dict[str, list[str]] = {}
|
||||
overall = 'parsed'
|
||||
@@ -410,9 +441,7 @@ def execute_split_rule_set(
|
||||
overall = 'needs_review'
|
||||
|
||||
if any(d.code in {
|
||||
'prefix_not_matched', 'regex_not_matched', 'regex_timeout', 'regex_failed',
|
||||
'select_line_out_of_range', 'select_line_range_out_of_range',
|
||||
'stage_type_mismatch', 'pipeline_ended_on_lines',
|
||||
'regex_timeout', 'regex_failed', 'mapped_value_empty', 'input_too_long',
|
||||
} for d in diagnostics):
|
||||
overall = 'needs_review'
|
||||
|
||||
@@ -423,7 +452,7 @@ def execute_split_rule_set(
|
||||
mapped_fields=mapped_fields,
|
||||
evidence_only_segments=evidence_only,
|
||||
diagnostics=diagnostics,
|
||||
rule_id=rule_set.rule_id,
|
||||
rule_id=rule_set.rule_set_id,
|
||||
rule_version=rule_set.rule_version,
|
||||
)
|
||||
|
||||
@@ -456,7 +485,7 @@ def project_split_result_safe(
|
||||
|
||||
核心逻辑:默认脱敏 mapped/segment 文本;仅当调用方已通过敏感读权限且
|
||||
include_full_values=True 时返回 raw_text / 完整 mapped 值。
|
||||
evidence_only_segments 仅作兼容字段;完整列表以 segments 为准。
|
||||
evidence_only_segments 避免与 segments 重复展示(置空列表)。
|
||||
|
||||
Args:
|
||||
result: 引擎输出。
|
||||
@@ -498,7 +527,7 @@ def project_split_result_safe(
|
||||
}
|
||||
for item in result.segments
|
||||
],
|
||||
'evidence_only_segments': [], # 避免与 segments 重复展示;兼容字段置空
|
||||
'evidence_only_segments': [],
|
||||
'diagnostics': [
|
||||
{
|
||||
'code': item.code,
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_validation.py
|
||||
|
||||
用途:XFA 正式提取后的 AcroForm / 镜像集合 / 金额恒等式业务校验。
|
||||
依赖:Decimal、xfa_contract、xfa_dataset、xfa_acroform、field_rules。
|
||||
逻辑:由 order_extraction_workflow 在提取成功后调用;硬失败(mismatched/公式失败)
|
||||
写入稳定 reason_code 进入 needs_review;AcroForm 状态区分
|
||||
matched/partial/unavailable/skipped/mismatched,避免“缺字段却记 matched”。
|
||||
用途:XFA 正式提取后的 AcroForm / 镜像集合 / 金额恒等式业务校验,以及统一视觉/证据指标。
|
||||
依赖:Decimal、xfa_contract、xfa_dataset、xfa_acroform、split_rule_*。
|
||||
逻辑:由 order_extraction_workflow / validation_service 在提取成功后调用;硬失败
|
||||
(mismatched/公式失败)写入稳定 reason_code 进入 needs_review;AcroForm 状态区分
|
||||
matched/partial/unavailable/skipped/mismatched;阶段 5 附加 visual/mirror/evidence 指标。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,6 +22,8 @@ from app.services.shipping_notice.document_layout.xfa_acroform import (
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
OrderXfaDatasetProfile,
|
||||
XfaUnifiedFieldBinding,
|
||||
is_formal_binding_publishable,
|
||||
sanitize_xfa_dto,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import (
|
||||
@@ -147,6 +149,38 @@ def _validate_line_amount_formula(line_maps: list[dict[str, Any]]) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _line_amount_failures(line_maps: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""返回明细金额校验失败的具体行和值,供模板管理员定位映射或数据问题。"""
|
||||
failures: list[dict[str, Any]] = []
|
||||
for row_index, mapping in enumerate(line_maps, start=1):
|
||||
quantity = _to_decimal(mapping.get('quantity'))
|
||||
unit_price = _to_decimal(mapping.get('unit_price'))
|
||||
amount = _to_decimal(mapping.get('amount'))
|
||||
price_unit = _to_decimal(mapping.get('price_unit')) or Decimal('1')
|
||||
if quantity is None or unit_price is None or amount is None or price_unit == 0:
|
||||
failures.append({
|
||||
'row_index': row_index,
|
||||
'quantity': mapping.get('quantity'),
|
||||
'unit_price': mapping.get('unit_price'),
|
||||
'price_unit': mapping.get('price_unit'),
|
||||
'amount': mapping.get('amount'),
|
||||
'reason': 'missing_or_invalid_operand',
|
||||
})
|
||||
continue
|
||||
expected = (quantity * unit_price) / price_unit
|
||||
if expected.quantize(Decimal('0.01')) != amount.quantize(Decimal('0.01')) and expected != amount:
|
||||
failures.append({
|
||||
'row_index': row_index,
|
||||
'quantity': str(quantity),
|
||||
'unit_price': str(unit_price),
|
||||
'price_unit': str(price_unit),
|
||||
'amount': str(amount),
|
||||
'expected_amount': str(expected),
|
||||
'reason': 'amount_mismatch',
|
||||
})
|
||||
return failures
|
||||
|
||||
|
||||
def _validate_total_equals_line_sum(
|
||||
*,
|
||||
header_fields: list[Any],
|
||||
@@ -190,17 +224,17 @@ def _split_mirror_compare_plan(
|
||||
)
|
||||
]
|
||||
path_id_to_data_path = {
|
||||
str(item.path_id): str(item.data_path)
|
||||
for item in profile.line_mapping.fields
|
||||
if item.path_id and item.data_path
|
||||
str(binding.value_binding.path_id): str(binding.value_binding.data_path)
|
||||
for binding in profile.bindings
|
||||
if binding.value_binding.path_id and binding.value_binding.data_path
|
||||
}
|
||||
split_source_paths: set[str] = set()
|
||||
split_field_codes: set[str] = set()
|
||||
line_fields = list(profile.line_mapping.fields)
|
||||
line_bindings = [item for item in profile.bindings if item.scope == 'line']
|
||||
for rule_set in rule_sets:
|
||||
data_path = _resolve_split_source_data_path(
|
||||
rule_set,
|
||||
line_fields=line_fields,
|
||||
line_bindings=line_bindings,
|
||||
path_id_to_data_path=path_id_to_data_path,
|
||||
)
|
||||
if data_path:
|
||||
@@ -244,7 +278,7 @@ def _validate_mirror_collections(
|
||||
formal_rule_sets, split_source_paths, split_field_codes, path_id_to_data_path = (
|
||||
_split_mirror_compare_plan(profile)
|
||||
)
|
||||
line_fields = list(profile.line_mapping.fields)
|
||||
line_bindings = [item for item in profile.bindings if item.scope == 'line']
|
||||
present_count = 0
|
||||
for mirror_path in mirrors:
|
||||
mirror_rows = read_collection_rows(dataset_analysis, mirror_path)
|
||||
@@ -267,7 +301,7 @@ def _validate_mirror_collections(
|
||||
for rule_set in formal_rule_sets:
|
||||
auth_source_path = _resolve_split_source_data_path(
|
||||
rule_set,
|
||||
line_fields=line_fields,
|
||||
line_bindings=line_bindings,
|
||||
path_id_to_data_path=path_id_to_data_path,
|
||||
)
|
||||
if not auth_source_path:
|
||||
@@ -319,7 +353,7 @@ def _validate_acroform(
|
||||
profile: OrderXfaDatasetProfile,
|
||||
extraction: XfaExtractionResult,
|
||||
pdf_bytes: bytes | None,
|
||||
) -> tuple[bool, str]:
|
||||
) -> tuple[bool, str, list[dict[str, Any]]]:
|
||||
"""
|
||||
对账 datasets 标准化值与 AcroForm 展示值(表头单值 + 明细按行对齐)。
|
||||
|
||||
@@ -329,50 +363,61 @@ def _validate_acroform(
|
||||
- 无 Fields / 无重叠字段 → unavailable;仅部分字段可对 → partial;冲突 → mismatched。
|
||||
|
||||
Returns:
|
||||
(hard_ok, status):hard_ok=False 仅 mismatched;其余状态不阻断正式提取硬失败,
|
||||
(hard_ok, status, mismatches):hard_ok=False 仅 mismatched;其余状态不阻断正式提取硬失败,
|
||||
由 CQ 决定是否允许自动建单。
|
||||
"""
|
||||
if not profile.cross_checks.acroform_enabled:
|
||||
return True, 'skipped'
|
||||
return True, 'skipped', []
|
||||
if not pdf_bytes:
|
||||
return True, 'unavailable'
|
||||
return True, 'unavailable', []
|
||||
acro_fields = read_acroform_fields(pdf_bytes)
|
||||
if not acro_fields:
|
||||
return True, 'unavailable'
|
||||
return True, 'unavailable', []
|
||||
|
||||
by_name = _acroform_values_by_local_name(acro_fields)
|
||||
compared = 0
|
||||
mismatched = 0
|
||||
missing_counterpart = 0
|
||||
mismatches: list[dict[str, Any]] = []
|
||||
|
||||
# [STEP 1] Header:每个映射对应短名的首个 AcroForm 实例。
|
||||
for mapping in profile.header_mappings:
|
||||
local = mapping.data_path.rsplit('/', 1)[-1].upper()
|
||||
# [STEP 1] Header:每个 binding 对应短名的首个 AcroForm 实例。
|
||||
for binding in profile.bindings:
|
||||
if binding.scope != 'header':
|
||||
continue
|
||||
data_path = str(binding.value_binding.data_path or '')
|
||||
local = data_path.rsplit('/', 1)[-1].upper()
|
||||
acro_values = by_name.get(local) or []
|
||||
if not acro_values:
|
||||
missing_counterpart += 1
|
||||
continue
|
||||
dataset_value = None
|
||||
for header in extraction.header_fields:
|
||||
if header.mapping_id == mapping.mapping_id:
|
||||
if header.mapping_id == binding.binding_id:
|
||||
dataset_value = header.normalized_value
|
||||
break
|
||||
left = _normalize_comparable(dataset_value, value_type=mapping.value_type)
|
||||
right = _normalize_comparable(acro_values[0], value_type=mapping.value_type)
|
||||
left = _normalize_comparable(dataset_value)
|
||||
right = _normalize_comparable(acro_values[0])
|
||||
if left is None or right is None:
|
||||
missing_counterpart += 1
|
||||
continue
|
||||
compared += 1
|
||||
if left != right:
|
||||
mismatched += 1
|
||||
mismatches.append({
|
||||
'scope': 'header', 'field_code': binding.field_code,
|
||||
'dataset_value': left, 'acroform_value': right,
|
||||
})
|
||||
|
||||
# [STEP 2] Line:按行索引对齐同名多实例 Widget。
|
||||
for mapping in profile.line_mapping.fields:
|
||||
local = mapping.data_path.rsplit('/', 1)[-1].upper()
|
||||
for binding in profile.bindings:
|
||||
if binding.scope != 'line':
|
||||
continue
|
||||
data_path = str(binding.value_binding.data_path or '')
|
||||
local = data_path.rsplit('/', 1)[-1].upper()
|
||||
acro_values = by_name.get(local) or []
|
||||
dataset_values = _dataset_line_values_by_mapping(
|
||||
extraction=extraction,
|
||||
mapping_field_code=mapping.field_code,
|
||||
mapping_field_code=binding.field_code,
|
||||
)
|
||||
if not dataset_values:
|
||||
continue
|
||||
@@ -383,22 +428,221 @@ def _validate_acroform(
|
||||
if row_index >= len(acro_values):
|
||||
missing_counterpart += 1
|
||||
continue
|
||||
left = _normalize_comparable(dataset_value, value_type=mapping.value_type)
|
||||
right = _normalize_comparable(acro_values[row_index], value_type=mapping.value_type)
|
||||
left = _normalize_comparable(dataset_value)
|
||||
right = _normalize_comparable(acro_values[row_index])
|
||||
if left is None or right is None:
|
||||
missing_counterpart += 1
|
||||
continue
|
||||
compared += 1
|
||||
if left != right:
|
||||
mismatched += 1
|
||||
mismatches.append({
|
||||
'scope': 'line', 'row_index': row_index + 1,
|
||||
'field_code': binding.field_code,
|
||||
'dataset_value': left, 'acroform_value': right,
|
||||
})
|
||||
|
||||
if mismatched > 0:
|
||||
return False, 'mismatched'
|
||||
return False, 'mismatched', mismatches
|
||||
if compared == 0:
|
||||
return True, 'unavailable'
|
||||
return True, 'unavailable', []
|
||||
if missing_counterpart > 0:
|
||||
return True, 'partial'
|
||||
return True, 'matched'
|
||||
return True, 'partial', []
|
||||
return True, 'matched', []
|
||||
|
||||
|
||||
def collect_formal_schema_field_ids(
|
||||
definition: dict[str, Any],
|
||||
*,
|
||||
schema_field_ids: set[str] | None = None,
|
||||
) -> set[str]:
|
||||
"""
|
||||
收集正式 Schema 映射字段 ID(Header + Line + mapped split segments)。
|
||||
|
||||
核心逻辑:union bindings / header_mappings / line_mapping.fields / 已确认拆分 mapped 段的
|
||||
target_field_id;若提供 schema_field_ids 则仅保留其中启用字段。
|
||||
|
||||
Args:
|
||||
definition: XFA definition 字典。
|
||||
schema_field_ids: 可选 Schema 启用字段 ID 集合;None 表示不过滤。
|
||||
|
||||
Returns:
|
||||
正式字段 field_id 集合。
|
||||
"""
|
||||
formal: set[str] = set()
|
||||
for item in definition.get('bindings') or []:
|
||||
if isinstance(item, dict) and item.get('field_id'):
|
||||
formal.add(str(item['field_id']))
|
||||
for item in definition.get('header_mappings') or []:
|
||||
if isinstance(item, dict) and item.get('field_id'):
|
||||
formal.add(str(item['field_id']))
|
||||
line_mapping = definition.get('line_mapping') if isinstance(definition.get('line_mapping'), dict) else {}
|
||||
for item in line_mapping.get('fields') or []:
|
||||
if isinstance(item, dict) and item.get('field_id'):
|
||||
formal.add(str(item['field_id']))
|
||||
for raw_rule in definition.get('split_rules') or []:
|
||||
if not isinstance(raw_rule, dict):
|
||||
continue
|
||||
for rule in raw_rule.get('rules') or []:
|
||||
if not isinstance(rule, dict):
|
||||
continue
|
||||
segment = rule.get('segment') if isinstance(rule.get('segment'), dict) else {}
|
||||
if str(segment.get('handling') or '') != 'mapped':
|
||||
continue
|
||||
target_id = str(segment.get('target_field_id') or '').strip()
|
||||
if target_id:
|
||||
formal.add(target_id)
|
||||
if schema_field_ids is not None:
|
||||
formal &= set(schema_field_ids)
|
||||
return {item for item in formal if item}
|
||||
|
||||
|
||||
def compute_visual_coverage_rate(
|
||||
definition: dict[str, Any],
|
||||
*,
|
||||
schema_field_ids: set[str] | None = None,
|
||||
) -> float:
|
||||
"""
|
||||
计算正式字段视觉确认覆盖率。
|
||||
|
||||
核心逻辑:每个正式 Schema 字段须有一条 is_formal_binding_publishable 的统一绑定;
|
||||
无正式字段时返回 1.0。
|
||||
|
||||
Args:
|
||||
definition: XFA definition。
|
||||
schema_field_ids: 可选 Schema 字段过滤。
|
||||
|
||||
Returns:
|
||||
[0.0, 1.0] 覆盖率。
|
||||
"""
|
||||
formal_ids = collect_formal_schema_field_ids(definition, schema_field_ids=schema_field_ids)
|
||||
if not formal_ids:
|
||||
return 1.0
|
||||
publishable_by_field: set[str] = set()
|
||||
for raw in definition.get('bindings') or []:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
try:
|
||||
binding = XfaUnifiedFieldBinding.model_validate(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if is_formal_binding_publishable(binding):
|
||||
publishable_by_field.add(str(binding.field_id))
|
||||
covered = len(formal_ids & publishable_by_field)
|
||||
return round(covered / len(formal_ids), 6)
|
||||
|
||||
|
||||
def compute_mirror_consistency_rate(cross_check_summary: dict[str, Any] | None) -> float:
|
||||
"""
|
||||
由镜像对账摘要派生一致率。
|
||||
|
||||
核心逻辑:matched/skipped/unavailable → 1.0;mismatched → 0.0;未知 → 0.0。
|
||||
|
||||
Args:
|
||||
cross_check_summary: validate_xfa_extraction 的 cross_check_summary。
|
||||
|
||||
Returns:
|
||||
[0.0, 1.0] 一致率。
|
||||
"""
|
||||
summary = cross_check_summary if isinstance(cross_check_summary, dict) else {}
|
||||
status = str(summary.get('mirror_status') or '').strip().lower()
|
||||
if status in {'matched', 'skipped', 'unavailable'}:
|
||||
return 1.0
|
||||
if status == 'mismatched':
|
||||
return 0.0
|
||||
return 0.0
|
||||
|
||||
|
||||
def compute_evidence_retention_rate(
|
||||
*,
|
||||
extraction: XfaExtractionResult | None = None,
|
||||
evidence_segments: list[dict[str, Any]] | None = None,
|
||||
expected_line_nos: set[int] | None = None,
|
||||
) -> float:
|
||||
"""
|
||||
计算 evidence_only 行保留率。
|
||||
|
||||
核心逻辑:
|
||||
1. 若给出 expected_line_nos,以提取结果中实际保留的 line_no 求交占比;
|
||||
2. 否则从 extraction 的 split_evidence / evidence_summary.header_split_evidence 统计,
|
||||
有拆分证据时视为 1.0(引擎已产出即保留),无拆分时 1.0。
|
||||
|
||||
Args:
|
||||
extraction: 正式提取结果(可含 split_evidence)。
|
||||
evidence_segments: 可选显式证据段列表。
|
||||
expected_line_nos: 期望保留的行号集合(如 {2,4,5})。
|
||||
|
||||
Returns:
|
||||
[0.0, 1.0] 保留率。
|
||||
"""
|
||||
segments: list[dict[str, Any]] = list(evidence_segments or [])
|
||||
if extraction is not None and not segments:
|
||||
for row in getattr(extraction, 'rows', None) or []:
|
||||
if isinstance(row, dict):
|
||||
segments.extend(
|
||||
item for item in (row.get('split_evidence') or []) if isinstance(item, dict)
|
||||
)
|
||||
summary = getattr(extraction, 'evidence_summary', None) or {}
|
||||
if isinstance(summary, dict):
|
||||
segments.extend(
|
||||
item for item in (summary.get('header_split_evidence') or []) if isinstance(item, dict)
|
||||
)
|
||||
|
||||
if expected_line_nos is not None:
|
||||
if not expected_line_nos:
|
||||
return 1.0
|
||||
retained: set[int] = set()
|
||||
for item in segments:
|
||||
raw_line = item.get('line_no')
|
||||
if raw_line is None:
|
||||
continue
|
||||
try:
|
||||
retained.add(int(raw_line))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return round(len(expected_line_nos & retained) / len(expected_line_nos), 6)
|
||||
|
||||
# 无期望行号:拆分引擎已写入的 evidence 视为完整保留。
|
||||
return 1.0
|
||||
|
||||
|
||||
def build_xfa_validation_metrics(
|
||||
*,
|
||||
definition: dict[str, Any],
|
||||
extraction: XfaExtractionResult | None = None,
|
||||
cross_check_summary: dict[str, Any] | None = None,
|
||||
schema_field_ids: set[str] | None = None,
|
||||
expected_evidence_line_nos: set[int] | None = None,
|
||||
) -> dict[str, float]:
|
||||
"""
|
||||
组装统一验证指标(视觉覆盖 / 镜像一致 / 证据保留)。
|
||||
|
||||
Args:
|
||||
definition: XFA definition。
|
||||
extraction: 可选提取结果(证据保留率)。
|
||||
cross_check_summary: 可选对账摘要(镜像一致率)。
|
||||
schema_field_ids: 可选 Schema 字段过滤。
|
||||
expected_evidence_line_nos: 可选期望 evidence_only 行号。
|
||||
|
||||
Returns:
|
||||
含 visual_coverage_rate / mirror_consistency_rate / evidence_retention_rate 的字典。
|
||||
"""
|
||||
return {
|
||||
'visual_coverage_rate': compute_visual_coverage_rate(
|
||||
definition, schema_field_ids=schema_field_ids,
|
||||
),
|
||||
'mirror_consistency_rate': compute_mirror_consistency_rate(cross_check_summary),
|
||||
'evidence_retention_rate': compute_evidence_retention_rate(
|
||||
extraction=extraction,
|
||||
expected_line_nos=expected_evidence_line_nos,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def definition_has_unified_bindings(definition: dict[str, Any]) -> bool:
|
||||
"""判断 definition 是否已进入统一 bindings 模式(非空 bindings 列表)。"""
|
||||
bindings = definition.get('bindings')
|
||||
return isinstance(bindings, list) and len(bindings) > 0
|
||||
|
||||
|
||||
def validate_xfa_extraction(
|
||||
@@ -407,6 +651,8 @@ def validate_xfa_extraction(
|
||||
dataset_analysis: XfaDatasetAnalysis,
|
||||
extraction: XfaExtractionResult,
|
||||
pdf_bytes: bytes | None = None,
|
||||
schema_field_ids: set[str] | None = None,
|
||||
expected_evidence_line_nos: set[int] | None = None,
|
||||
) -> XfaValidationResult:
|
||||
"""
|
||||
执行 XFA 提取后的确定性业务校验。
|
||||
@@ -415,13 +661,16 @@ def validate_xfa_extraction(
|
||||
1. 镜像集合标准化一致性;
|
||||
2. AcroForm 关键字段标准化一致性;
|
||||
3. 明细金额公式 quantity×unit_price;
|
||||
4. Header 总金额与明细合计。
|
||||
4. Header 总金额与明细合计;
|
||||
5. 附加 visual/mirror/evidence 指标(不直接因指标失败,由发布门禁消费)。
|
||||
|
||||
Args:
|
||||
raw_profile: 冻结 Profile 快照。
|
||||
dataset_analysis: datasets 分析。
|
||||
extraction: 提取结果。
|
||||
pdf_bytes: 可选原始 PDF,用于 AcroForm 对账。
|
||||
schema_field_ids: 可选 Schema 字段过滤(视觉覆盖率)。
|
||||
expected_evidence_line_nos: 可选期望 evidence_only 行号。
|
||||
|
||||
Returns:
|
||||
XfaValidationResult。
|
||||
@@ -438,7 +687,9 @@ def validate_xfa_extraction(
|
||||
|
||||
reason_codes: list[str] = []
|
||||
line_field_paths = {
|
||||
item.field_code: item.data_path for item in profile.line_mapping.fields
|
||||
binding.field_code: str(binding.value_binding.data_path or '')
|
||||
for binding in profile.bindings
|
||||
if binding.scope == 'line' and binding.value_binding.data_path
|
||||
}
|
||||
summary: dict[str, Any] = {
|
||||
'mirror_collection_policy': profile.cross_checks.mirror_collection_policy,
|
||||
@@ -458,7 +709,7 @@ def validate_xfa_extraction(
|
||||
summary['mirror_status'] = mirror_status
|
||||
|
||||
# [STEP 2] AcroForm(按行对齐;状态含 matched/partial/unavailable)
|
||||
acro_ok, acro_status = _validate_acroform(
|
||||
acro_ok, acro_status, acro_mismatches = _validate_acroform(
|
||||
profile=profile,
|
||||
extraction=extraction,
|
||||
pdf_bytes=pdf_bytes,
|
||||
@@ -466,16 +717,20 @@ def validate_xfa_extraction(
|
||||
if not acro_ok:
|
||||
reason_codes.append('xfa_acroform_mismatch')
|
||||
summary['acroform_status'] = acro_status
|
||||
summary['acroform_mismatches'] = acro_mismatches
|
||||
|
||||
line_maps = _field_map_from_rows(extraction.rows)
|
||||
|
||||
# [STEP 3] 明细金额公式
|
||||
if profile.cross_checks.line_amount_formula == 'quantity_times_unit_price':
|
||||
if not _validate_line_amount_formula(line_maps):
|
||||
line_amount_failures = _line_amount_failures(line_maps)
|
||||
if line_amount_failures:
|
||||
reason_codes.append('xfa_business_validation_failed')
|
||||
summary['line_amount_status'] = 'failed'
|
||||
summary['line_amount_failures'] = line_amount_failures
|
||||
else:
|
||||
summary['line_amount_status'] = 'passed'
|
||||
summary['line_amount_failures'] = []
|
||||
else:
|
||||
summary['line_amount_status'] = 'skipped'
|
||||
|
||||
@@ -493,6 +748,16 @@ def validate_xfa_extraction(
|
||||
else:
|
||||
summary['total_amount_status'] = 'skipped'
|
||||
|
||||
# [STEP 5] 统一验证指标(发布门禁消费;此处不直接 fail)
|
||||
metrics = build_xfa_validation_metrics(
|
||||
definition=definition,
|
||||
extraction=extraction,
|
||||
cross_check_summary=summary,
|
||||
schema_field_ids=schema_field_ids,
|
||||
expected_evidence_line_nos=expected_evidence_line_nos,
|
||||
)
|
||||
summary.update(metrics)
|
||||
|
||||
return XfaValidationResult(
|
||||
passed=not reason_codes,
|
||||
reason_codes=reason_codes,
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_visual_binding.py
|
||||
|
||||
用途:XFA 统一视觉绑定的候选评分、歧义诊断与建议结果组装(纯函数,不写数据库)。
|
||||
依赖:xfa_acroform、xfa_dataset、xfa_contract(归一化框与 path 哈希)。
|
||||
逻辑:由 order_document_profile_visual_binding_service 调用;画框或 Widget 命中后
|
||||
返回 suggested 候选列表与 diagnostics;高置信也不得自动 confirmed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Literal
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_acroform import (
|
||||
XfaAcroformWidget,
|
||||
build_widget_path_candidates,
|
||||
read_acroform_widgets,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import hash_data_path
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import XfaDatasetAnalysis
|
||||
|
||||
|
||||
VisualCandidateStatus = Literal['suggested']
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VisualPathCandidate:
|
||||
"""datasets 路径候选摘要(不含完整 XPath 明文时可仅含 hash)。"""
|
||||
|
||||
path_id: str
|
||||
data_path_hash: str
|
||||
dataset_value_masked: str
|
||||
match_hint: str
|
||||
confidence: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class VisualBindingCandidate:
|
||||
"""单个 Widget/区域视觉绑定候选;status 恒为 suggested,禁止自动 confirmed。"""
|
||||
|
||||
candidate_id: str
|
||||
widget_id: str
|
||||
page_no: int
|
||||
normalized_bbox: dict[str, float]
|
||||
acroform_field_name_tail: str
|
||||
display_value_masked: str
|
||||
path_candidates: list[VisualPathCandidate] = field(default_factory=list)
|
||||
overlap_score: float = 0.0
|
||||
value_match_score: float = 0.0
|
||||
confidence: float = 0.0
|
||||
status: VisualCandidateStatus = 'suggested'
|
||||
|
||||
|
||||
@dataclass
|
||||
class VisualBindingDiagnostics:
|
||||
"""歧义与覆盖诊断;供管理员确认前展示。"""
|
||||
|
||||
candidate_count: int = 0
|
||||
ambiguous: bool = False
|
||||
ambiguity_reason: str | None = None
|
||||
top_confidence: float = 0.0
|
||||
second_confidence: float = 0.0
|
||||
auto_confirm_blocked: bool = True
|
||||
notes: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def _bbox_area(bbox: dict[str, float]) -> float:
|
||||
"""计算归一化框面积;非法框返回 0。"""
|
||||
x0 = float(bbox.get('x0') or 0)
|
||||
y0 = float(bbox.get('y0') or 0)
|
||||
x1 = float(bbox.get('x1') or 0)
|
||||
y1 = float(bbox.get('y1') or 0)
|
||||
if x1 <= x0 or y1 <= y0:
|
||||
return 0.0
|
||||
return (x1 - x0) * (y1 - y0)
|
||||
|
||||
|
||||
def _bbox_intersection_area(a: dict[str, float], b: dict[str, float]) -> float:
|
||||
"""两框交集面积。"""
|
||||
x0 = max(float(a.get('x0') or 0), float(b.get('x0') or 0))
|
||||
y0 = max(float(a.get('y0') or 0), float(b.get('y0') or 0))
|
||||
x1 = min(float(a.get('x1') or 0), float(b.get('x1') or 0))
|
||||
y1 = min(float(a.get('y1') or 0), float(b.get('y1') or 0))
|
||||
if x1 <= x0 or y1 <= y0:
|
||||
return 0.0
|
||||
return (x1 - x0) * (y1 - y0)
|
||||
|
||||
|
||||
def _bbox_overlap_score(region: dict[str, float], widget_bbox: dict[str, float]) -> float:
|
||||
"""
|
||||
区域与 Widget 框重叠得分(IoU 优先,退化时为交集占区域面积比)。
|
||||
|
||||
Args:
|
||||
region: 用户画框或查询区域(0..1)。
|
||||
widget_bbox: AcroForm Widget 归一化框。
|
||||
|
||||
Returns:
|
||||
0..1 重叠得分。
|
||||
"""
|
||||
intersection = _bbox_intersection_area(region, widget_bbox)
|
||||
if intersection <= 0:
|
||||
return 0.0
|
||||
region_area = _bbox_area(region)
|
||||
widget_area = _bbox_area(widget_bbox)
|
||||
union = region_area + widget_area - intersection
|
||||
if union > 0:
|
||||
return intersection / union
|
||||
return intersection / region_area if region_area > 0 else 0.0
|
||||
|
||||
|
||||
def _normalize_compare_value(value: str) -> str:
|
||||
"""值对账用的空白无关规范化。"""
|
||||
return ''.join(str(value or '').casefold().split())
|
||||
|
||||
|
||||
def _value_match_score(display_value: str, dataset_value: str) -> float:
|
||||
"""
|
||||
页面展示值与 datasets 叶子值的标准化匹配分。
|
||||
|
||||
Returns:
|
||||
1.0 精确匹配;0.5 包含关系;0 不匹配。
|
||||
"""
|
||||
left = _normalize_compare_value(display_value)
|
||||
right = _normalize_compare_value(dataset_value)
|
||||
if not left or not right:
|
||||
return 0.0
|
||||
if left == right:
|
||||
return 1.0
|
||||
if left in right or right in left:
|
||||
return 0.5
|
||||
return 0.0
|
||||
|
||||
|
||||
def _candidate_id(widget_id: str, path_id: str) -> str:
|
||||
"""生成稳定的候选 ID(不含敏感明文)。"""
|
||||
digest = hashlib.sha256(f'{widget_id}:{path_id}'.encode('utf-8')).hexdigest()[:16]
|
||||
return f'vbc-{digest}'
|
||||
|
||||
|
||||
def _diagnose_ambiguity(candidates: list[VisualBindingCandidate]) -> VisualBindingDiagnostics:
|
||||
"""
|
||||
诊断候选歧义;同分或接近时标记 ambiguous,且始终阻断自动确认。
|
||||
|
||||
Args:
|
||||
candidates: 已按 confidence 降序排列的候选。
|
||||
|
||||
Returns:
|
||||
诊断摘要。
|
||||
"""
|
||||
diagnostics = VisualBindingDiagnostics(candidate_count=len(candidates))
|
||||
if not candidates:
|
||||
diagnostics.notes.append('no_widget_overlap')
|
||||
return diagnostics
|
||||
diagnostics.top_confidence = float(candidates[0].confidence)
|
||||
if len(candidates) > 1:
|
||||
diagnostics.second_confidence = float(candidates[1].confidence)
|
||||
# [STEP 1] 高置信接近时视为歧义,禁止自动确认
|
||||
if len(candidates) >= 2 and abs(diagnostics.top_confidence - diagnostics.second_confidence) < 0.05:
|
||||
diagnostics.ambiguous = True
|
||||
diagnostics.ambiguity_reason = 'top_candidates_too_close'
|
||||
elif len(candidates) >= 2 and diagnostics.top_confidence >= 0.85 and diagnostics.second_confidence >= 0.75:
|
||||
diagnostics.ambiguous = True
|
||||
diagnostics.ambiguity_reason = 'multiple_high_confidence'
|
||||
top_paths = candidates[0].path_candidates
|
||||
if len(top_paths) > 1:
|
||||
diagnostics.ambiguous = True
|
||||
diagnostics.ambiguity_reason = diagnostics.ambiguity_reason or 'multiple_path_candidates'
|
||||
diagnostics.auto_confirm_blocked = True
|
||||
return diagnostics
|
||||
|
||||
|
||||
def suggest_visual_binding_candidates(
|
||||
*,
|
||||
page_no: int,
|
||||
normalized_bbox: dict[str, float],
|
||||
dataset_analysis: XfaDatasetAnalysis,
|
||||
pdf_bytes: bytes | None = None,
|
||||
widgets: list[XfaAcroformWidget] | None = None,
|
||||
min_overlap: float = 0.05,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为指定页面区域生成 AcroForm Widget → datasets 路径的视觉绑定候选。
|
||||
|
||||
核心逻辑:按框重叠筛选 Widget → 为每个 Widget 生成路径候选 → 综合重叠与值匹配
|
||||
评分;所有候选 status 恒为 suggested,歧义写入 diagnostics。
|
||||
|
||||
Args:
|
||||
page_no: 目标 PDF 页码(1-based)。
|
||||
normalized_bbox: 用户画框或查询区域(0..1,左上原点)。
|
||||
dataset_analysis: 已解析的 datasets 结构。
|
||||
pdf_bytes: 原始 PDF;widgets 未传入时用于读取 AcroForm Widget。
|
||||
widgets: 可选预读 Widget 列表(测试/mock 用)。
|
||||
min_overlap: 最小 IoU/重叠阈值。
|
||||
|
||||
Returns:
|
||||
{candidates, diagnostics, page_no, normalized_bbox} 安全 DTO。
|
||||
"""
|
||||
region = {
|
||||
'x0': float(normalized_bbox.get('x0') or 0),
|
||||
'y0': float(normalized_bbox.get('y0') or 0),
|
||||
'x1': float(normalized_bbox.get('x1') or 0),
|
||||
'y1': float(normalized_bbox.get('y1') or 0),
|
||||
}
|
||||
if _bbox_area(region) <= 0:
|
||||
return {
|
||||
'page_no': int(page_no),
|
||||
'normalized_bbox': region,
|
||||
'candidates': [],
|
||||
'diagnostics': VisualBindingDiagnostics(
|
||||
candidate_count=0,
|
||||
notes=['invalid_region_bbox'],
|
||||
).__dict__,
|
||||
}
|
||||
|
||||
widget_list = list(widgets or [])
|
||||
if not widget_list and pdf_bytes:
|
||||
widget_list = read_acroform_widgets(pdf_bytes)
|
||||
|
||||
candidates: list[VisualBindingCandidate] = []
|
||||
for widget in widget_list:
|
||||
if int(widget.page_no) != int(page_no):
|
||||
continue
|
||||
overlap = _bbox_overlap_score(region, widget.normalized_bbox)
|
||||
if overlap < float(min_overlap):
|
||||
continue
|
||||
path_items = build_widget_path_candidates(
|
||||
widget=widget,
|
||||
dataset_analysis=dataset_analysis,
|
||||
)
|
||||
path_candidates: list[VisualPathCandidate] = []
|
||||
best_value_score = 0.0
|
||||
for item in path_items:
|
||||
value_score = _value_match_score(widget.value, item.get('raw_value') or '')
|
||||
best_value_score = max(best_value_score, value_score)
|
||||
path_candidates.append(VisualPathCandidate(
|
||||
path_id=str(item.get('path_id') or ''),
|
||||
data_path_hash=str(item.get('data_path_hash') or ''),
|
||||
dataset_value_masked=str(item.get('dataset_value_masked') or ''),
|
||||
match_hint=str(item.get('match_hint') or 'unmatched'),
|
||||
confidence=round(min(1.0, overlap * 0.6 + value_score * 0.4), 4),
|
||||
))
|
||||
confidence = round(min(1.0, overlap * 0.55 + best_value_score * 0.45), 4)
|
||||
top_path_id = path_candidates[0].path_id if path_candidates else ''
|
||||
candidates.append(VisualBindingCandidate(
|
||||
candidate_id=_candidate_id(widget.widget_id, top_path_id or widget.widget_id),
|
||||
widget_id=widget.widget_id,
|
||||
page_no=int(widget.page_no),
|
||||
normalized_bbox=dict(widget.normalized_bbox),
|
||||
acroform_field_name_tail=widget.short_name,
|
||||
display_value_masked=widget.value_masked,
|
||||
path_candidates=path_candidates,
|
||||
overlap_score=round(overlap, 4),
|
||||
value_match_score=round(best_value_score, 4),
|
||||
confidence=confidence,
|
||||
status='suggested',
|
||||
))
|
||||
|
||||
candidates.sort(key=lambda item: (-item.confidence, item.widget_id))
|
||||
diagnostics = _diagnose_ambiguity(candidates)
|
||||
|
||||
return {
|
||||
'page_no': int(page_no),
|
||||
'normalized_bbox': region,
|
||||
'candidates': [
|
||||
{
|
||||
'candidate_id': item.candidate_id,
|
||||
'widget_id': item.widget_id,
|
||||
'page_no': item.page_no,
|
||||
'normalized_bbox': item.normalized_bbox,
|
||||
'acroform_field_name_tail': item.acroform_field_name_tail,
|
||||
'display_value_masked': item.display_value_masked,
|
||||
'path_candidates': [
|
||||
{
|
||||
'path_id': path.path_id,
|
||||
'data_path_hash': path.data_path_hash,
|
||||
'dataset_value_masked': path.dataset_value_masked,
|
||||
'match_hint': path.match_hint,
|
||||
'confidence': path.confidence,
|
||||
}
|
||||
for path in item.path_candidates
|
||||
],
|
||||
'overlap_score': item.overlap_score,
|
||||
'value_match_score': item.value_match_score,
|
||||
'confidence': item.confidence,
|
||||
'status': item.status,
|
||||
}
|
||||
for item in candidates
|
||||
],
|
||||
'diagnostics': {
|
||||
'candidate_count': diagnostics.candidate_count,
|
||||
'ambiguous': diagnostics.ambiguous,
|
||||
'ambiguity_reason': diagnostics.ambiguity_reason,
|
||||
'top_confidence': diagnostics.top_confidence,
|
||||
'second_confidence': diagnostics.second_confidence,
|
||||
'auto_confirm_blocked': diagnostics.auto_confirm_blocked,
|
||||
'notes': list(diagnostics.notes),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def visual_binding_audit_snapshot(binding: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
"""
|
||||
提取视觉绑定审计摘要(before/after 用),不含 datasets 明文路径。
|
||||
|
||||
Args:
|
||||
binding: 统一 binding 字典或 None。
|
||||
|
||||
Returns:
|
||||
含 status、bbox、page_no、confidence 的摘要;None 表示无绑定。
|
||||
"""
|
||||
if not isinstance(binding, dict):
|
||||
return None
|
||||
visual = binding.get('visual_binding') if isinstance(binding.get('visual_binding'), dict) else {}
|
||||
if not visual:
|
||||
return None
|
||||
bbox = visual.get('normalized_bbox') if isinstance(visual.get('normalized_bbox'), dict) else {}
|
||||
value = binding.get('value_binding') if isinstance(binding.get('value_binding'), dict) else {}
|
||||
return {
|
||||
'binding_id': binding.get('binding_id'),
|
||||
'field_id': binding.get('field_id'),
|
||||
'field_code': binding.get('field_code'),
|
||||
'status': visual.get('status'),
|
||||
'page_no': visual.get('page_no'),
|
||||
'normalized_bbox': {
|
||||
'x0': bbox.get('x0'),
|
||||
'y0': bbox.get('y0'),
|
||||
'x1': bbox.get('x1'),
|
||||
'y1': bbox.get('y1'),
|
||||
},
|
||||
'source': visual.get('source'),
|
||||
'confidence': visual.get('confidence'),
|
||||
'path_id': value.get('path_id'),
|
||||
'data_path_hash': hash_data_path(str(value.get('data_path') or '')) if value.get('data_path') else None,
|
||||
}
|
||||
@@ -2,9 +2,10 @@
|
||||
services/shipping_notice/document_profile_quality_service.py
|
||||
|
||||
用途:治理订单文档 Profile 的盲测候选、样本、执行结果和确定性自动建单资格。
|
||||
依赖:Profile 服务、MinerU 当前布局快照、XFA 结构分析、Profile 纯解析器与质量 ORM 模型。
|
||||
依赖:Profile 服务、MinerU 当前布局快照、XFA 结构分析、xfa_validation 指标、Profile 纯解析器与质量 ORM 模型。
|
||||
逻辑:管理员先固化一份独立样本的期望行,服务按冻结 Profile 执行比对;
|
||||
coordinate 走表格坐标回放,xfa_dataset 走文档级结构分析与路径提取;样本通过并批准后才放行自动建单。
|
||||
coordinate 走表格坐标回放,xfa_dataset 走文档级结构分析与路径提取;
|
||||
盲测执行附加 visual/split/evidence 指标,XFA 任一指标 < 1.0 即失败;样本通过并批准后才放行自动建单。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -53,6 +54,8 @@ from app.services.shipping_notice.order_schema.field_rules import normalize_orde
|
||||
MINIMUM_BLIND_SAMPLES = 1
|
||||
HEADERLESS_MINIMUM_BLIND_SAMPLES = 1
|
||||
DOCUMENT_CANDIDATE_TABLE_ID = '__document_candidate__'
|
||||
# 盲测指标哨兵:写入 failure_codes_json,serialize 时剥离为 metrics DTO 字段。
|
||||
_XFA_BLIND_METRICS_PREFIX = '__xfa_blind_metrics__:'
|
||||
_BUSINESS_SCENARIO_PATTERN = re.compile(r'^[a-z0-9_:-]{1,64}$')
|
||||
|
||||
|
||||
@@ -427,6 +430,29 @@ def _candidate_for_xfa_sample(
|
||||
packet_checksum=str(datasets_checksum or ''),
|
||||
dataset_structure_fingerprint=str(capability.get('dataset_structure_fingerprint') or '') or None,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_validation import (
|
||||
build_xfa_validation_metrics,
|
||||
validate_xfa_extraction,
|
||||
)
|
||||
schema_definition = dict((profile.schema_version.definition_json if profile.schema_version else None) or {})
|
||||
schema_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=schema_field_ids,
|
||||
)
|
||||
metrics = build_xfa_validation_metrics(
|
||||
definition=dict(profile.definition_json or {}),
|
||||
extraction=extraction,
|
||||
cross_check_summary=validation.cross_check_summary,
|
||||
schema_field_ids=schema_field_ids,
|
||||
)
|
||||
order_fields = [
|
||||
{
|
||||
'field_code': item.field_code,
|
||||
@@ -453,8 +479,12 @@ def _candidate_for_xfa_sample(
|
||||
'rows': rows,
|
||||
'order_fields': order_fields,
|
||||
'extraction_status': extraction.status,
|
||||
'reason_codes': list(extraction.reason_codes or []),
|
||||
'reason_codes': list(extraction.reason_codes or []) + list(validation.reason_codes or []),
|
||||
'line_row_count': len(rows),
|
||||
'visual_coverage_rate': float(metrics.get('visual_coverage_rate') or 0.0),
|
||||
'mirror_consistency_rate': float(metrics.get('mirror_consistency_rate') or 0.0),
|
||||
'evidence_retention_rate': float(metrics.get('evidence_retention_rate') or 0.0),
|
||||
'cross_checks': dict(validation.cross_check_summary or {}),
|
||||
}
|
||||
|
||||
|
||||
@@ -796,6 +826,7 @@ def list_independent_samples(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
1 for item in tables[:tables.index(table) + 1]
|
||||
if isinstance(item, dict) and int(item.get('page_no') or 1) == int(table.get('page_no') or 1)
|
||||
)
|
||||
coordinate_evidence_ready = _coordinate_table_available(document.id, table_id)
|
||||
# 同内容重复上传会产生不同 document_id/table_id;表格在文件内的位置与结构才是选择身份。
|
||||
content_identity = str(document.content_hash or '').strip().lower() or f'document:{document.id}'
|
||||
candidate_key = (
|
||||
@@ -811,12 +842,15 @@ def list_independent_samples(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
'table_index': table_index,
|
||||
'row_count': grid.row_count, 'column_count': grid.column_count,
|
||||
'header_preview': header_preview,
|
||||
'review_mode': 'formal_review', 'confirmable': True,
|
||||
# HTML 摘要可用不代表复核所需的冻结坐标证据可用;缺失时保持准备态,
|
||||
# 避免前端把必然返回 SAMPLE_INVALID 的样本送入正式复核接口。
|
||||
'review_mode': 'formal_review' if coordinate_evidence_ready else 'preparing',
|
||||
'confirmable': coordinate_evidence_ready,
|
||||
'layout_version_id': layout_version.id,
|
||||
'layout_payload_checksum': layout_version.payload_checksum,
|
||||
'layout_parser_key': layout_version.parser_key,
|
||||
'layout_parser_version': layout_version.parser_version,
|
||||
'layout_issue_codes': [],
|
||||
'layout_issue_codes': [] if coordinate_evidence_ready else ['coordinate_evidence_missing'],
|
||||
})
|
||||
return {'samples': result}
|
||||
|
||||
@@ -1088,6 +1122,14 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
}
|
||||
failures: list[str] = []
|
||||
passed = 0
|
||||
# 阶段 6:盲测聚合统一指标(XFA);坐标路径保持原语义。
|
||||
metrics_agg = {
|
||||
'visual_coverage_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'key_field_accuracy_rate': 1.0,
|
||||
}
|
||||
metrics_samples = 0
|
||||
for sample in suite.samples:
|
||||
if is_xfa:
|
||||
try:
|
||||
@@ -1095,10 +1137,25 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
except (NotFoundError, ValidationError):
|
||||
failures.append(f'sample:{sample.id}:xfa_evidence_missing')
|
||||
continue
|
||||
visual_rate = float(candidate.get('visual_coverage_rate') or 0.0)
|
||||
mirror_rate = float(candidate.get('mirror_consistency_rate') or 0.0)
|
||||
evidence_rate = float(candidate.get('evidence_retention_rate') or 0.0)
|
||||
metrics_agg['visual_coverage_rate'] = min(metrics_agg['visual_coverage_rate'], visual_rate)
|
||||
metrics_agg['mirror_consistency_rate'] = min(metrics_agg['mirror_consistency_rate'], mirror_rate)
|
||||
metrics_agg['evidence_retention_rate'] = min(metrics_agg['evidence_retention_rate'], evidence_rate)
|
||||
metrics_samples += 1
|
||||
if visual_rate < 1.0:
|
||||
failures.append(f'sample:{sample.id}:visual_coverage_insufficient')
|
||||
if mirror_rate < 1.0:
|
||||
failures.append(f'sample:{sample.id}:mirror_consistency_insufficient')
|
||||
if evidence_rate < 1.0:
|
||||
failures.append(f'sample:{sample.id}:evidence_retention_insufficient')
|
||||
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]}")
|
||||
continue
|
||||
field_failed = False
|
||||
key_total = 0
|
||||
key_matched = 0
|
||||
for field in candidate['order_fields']:
|
||||
review_key = _order_field_review_key(scope='header', field_code=field['field_code'])
|
||||
values_match = _order_field_values_match(
|
||||
@@ -1106,6 +1163,9 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
expected=(sample.expected_order_fields_json or {}).get(review_key),
|
||||
config=schema_fields.get(field['field_id']) or {},
|
||||
)
|
||||
key_total += 1
|
||||
if field['status'] == 'confirmed' and values_match:
|
||||
key_matched += 1
|
||||
if field['status'] != 'confirmed' or not values_match:
|
||||
reason = field['status'] if field['status'] != 'confirmed' else 'mismatch'
|
||||
failures.append(f"sample:{sample.id}:order_field:{field['field_code']}:{reason}")
|
||||
@@ -1123,14 +1183,25 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
for idx, (actual_row, expected_row) in enumerate(zip(actual_rows, expected_rows)):
|
||||
for field_code, expected_value in expected_row.items():
|
||||
config = line_schema_by_code.get(str(field_code)) or {}
|
||||
if not _order_field_values_match(
|
||||
key_total += 1
|
||||
matched = _order_field_values_match(
|
||||
actual=actual_row.get(field_code),
|
||||
expected=expected_value,
|
||||
config=config,
|
||||
):
|
||||
)
|
||||
if matched:
|
||||
key_matched += 1
|
||||
else:
|
||||
failures.append(f'sample:{sample.id}:line:{idx}:{field_code}:mismatch')
|
||||
field_failed = True
|
||||
if not field_failed:
|
||||
if key_total > 0:
|
||||
accuracy = key_matched / key_total
|
||||
metrics_agg['key_field_accuracy_rate'] = min(
|
||||
metrics_agg['key_field_accuracy_rate'], accuracy,
|
||||
)
|
||||
if accuracy < 1.0:
|
||||
failures.append(f'sample:{sample.id}:key_field_accuracy_insufficient')
|
||||
if not field_failed and visual_rate >= 1.0 and mirror_rate >= 1.0 and evidence_rate >= 1.0:
|
||||
passed += 1
|
||||
continue
|
||||
if isinstance(parser, OrderCoordinateProfile):
|
||||
@@ -1164,6 +1235,13 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
continue
|
||||
failures.append(f'sample:{sample.id}:profile_contract_invalid')
|
||||
sample_count = len(suite.samples)
|
||||
# 将指标摘要编码进 failure_codes(哨兵前缀),serialize 时剥离并暴露为 metrics。
|
||||
if is_xfa and metrics_samples > 0:
|
||||
import json as _json
|
||||
failures = [
|
||||
f"{_XFA_BLIND_METRICS_PREFIX}{_json.dumps(metrics_agg, sort_keys=True, separators=(',', ':'))}",
|
||||
*failures,
|
||||
]
|
||||
run = ShippingDocumentProfileTestRun(
|
||||
suite_id=suite.id, profile_checksum=_quality_checksum(profile),
|
||||
status='passed' if sample_count >= MINIMUM_BLIND_SAMPLES and passed == sample_count else 'failed',
|
||||
@@ -1175,6 +1253,7 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
'suite_id': suite.id, 'status': run.status, 'sample_count': sample_count,
|
||||
'passed_sample_count': passed,
|
||||
'template_mode': 'xfa_dataset' if is_xfa else 'coordinate',
|
||||
'metrics': metrics_agg if is_xfa else None,
|
||||
})
|
||||
db.session.commit()
|
||||
return serialize_suite(suite)
|
||||
@@ -1488,15 +1567,29 @@ def serialize_suite(suite: ShippingDocumentProfileTestSuite) -> dict[str, Any]:
|
||||
"""返回不含订单正文及真值的盲测治理摘要,供管理端维护与确认发布状态。
|
||||
|
||||
核心逻辑:保留运行门禁汇总,并附带可删除样本的最小定位信息;真值仍只在
|
||||
服务端保存,避免通过摘要接口泄露订单内容。
|
||||
服务端保存,避免通过摘要接口泄露订单内容。XFA 盲测指标从哨兵码剥离。
|
||||
|
||||
Args:
|
||||
suite: 当前 Profile checksum 对应的盲测集。
|
||||
|
||||
Returns:
|
||||
含样本清单、执行摘要与批准状态的管理端 DTO。
|
||||
含样本清单、执行摘要、可选 metrics 与批准状态的管理端 DTO。
|
||||
"""
|
||||
import json as _json
|
||||
|
||||
latest = suite.runs[-1] if suite.runs else None
|
||||
metrics: dict[str, Any] | None = None
|
||||
failure_codes: list[str] = []
|
||||
if latest is not None:
|
||||
for code in list(latest.failure_codes_json or []):
|
||||
text = str(code or '')
|
||||
if text.startswith(_XFA_BLIND_METRICS_PREFIX):
|
||||
try:
|
||||
metrics = _json.loads(text[len(_XFA_BLIND_METRICS_PREFIX):])
|
||||
except (TypeError, ValueError):
|
||||
metrics = None
|
||||
continue
|
||||
failure_codes.append(text)
|
||||
return {
|
||||
'id': suite.id, 'profile_id': suite.profile_id, 'profile_checksum': suite.profile_checksum,
|
||||
'status': suite.status, 'sample_count': len(suite.samples),
|
||||
@@ -1505,6 +1598,7 @@ def serialize_suite(suite: ShippingDocumentProfileTestSuite) -> dict[str, Any]:
|
||||
'latest_run': None if latest is None else {
|
||||
'status': latest.status, 'sample_count': latest.sample_count,
|
||||
'passed_sample_count': latest.passed_sample_count,
|
||||
'failure_codes': list(latest.failure_codes_json or []),
|
||||
'failure_codes': failure_codes,
|
||||
'metrics': metrics,
|
||||
},
|
||||
}
|
||||
@@ -4,14 +4,16 @@ services/shipping_notice/fulfillment_workflow.py
|
||||
用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传(RPA/人工)与自动串联编排。
|
||||
依赖:customer_identity_gate、reservation_gate、match、export、query_service、inventory_workflow、
|
||||
inventory_mapping_workflow、stp_line_inventory_match、upload_attempt_service、rpa.write_upload_trigger、
|
||||
tool_common、tool_response、fulfillment_audit。
|
||||
tool_common、tool_response、fulfillment_audit、task_workflow(Excel 就绪清失效)、
|
||||
order_task_stage_machine。
|
||||
逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match;
|
||||
STP 多候选:跨文件匹配后仅全部 ok 记 completed+100% 并自动 Excel;partial/冲突记 needs_human;
|
||||
AUTO_UPLOAD 默认 false(须环境显式 true;缺失键 fail-closed 并告警);
|
||||
开启时 Excel 后先做货代 RPA 就绪校验再触发(stage=upload_rpa_pending);关闭时停于人工上传;
|
||||
工作台操作人经 operator_id / actor_id / _trusted_user_id 写入匹配与审计事件;
|
||||
upload_to_freight 支持 mode=auto|retry_upload(RPA)与 manual_confirm(人工凭据);
|
||||
RPA 成功须带白名单 kind + page_url + dom_snippet/dom_sha256,并尽量落 evidence_asset。
|
||||
RPA 成功须带白名单 kind + page_url + dom_snippet/dom_sha256,并尽量落 evidence_asset;
|
||||
Excel 生成成功写路径清除 invalidated_from_stage(BE-02,禁止投影 GET 清库)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -1218,7 +1220,27 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
task.export_file_path = path
|
||||
task.export_file_name = filename
|
||||
# 绑定导出时的 order_data_version,供 formal edit Excel 冻结指纹校验。
|
||||
export_payload = dict(task.step_payload_json or {})
|
||||
export_payload['export_meta'] = {
|
||||
'order_data_version': int(task.order_data_version or 1),
|
||||
'artifact_no': getattr(artifact, 'artifact_no', None),
|
||||
'file_name': filename,
|
||||
}
|
||||
task.step_payload_json = export_payload
|
||||
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
|
||||
# [BE-06] Excel 就绪后 OT 进入货代上传段(waiting_upload → freight_uploading)。
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
sync_order_task_stage_for_notice,
|
||||
)
|
||||
|
||||
sync_order_task_stage_for_notice(task)
|
||||
# [BE-02] Excel 就绪写路径清除改单失效起点,并与 OT 进度同步;禁止投影 GET 清库。
|
||||
from app.services.shipping_notice.task_workflow import (
|
||||
_clear_notice_invalidated_from_stage,
|
||||
)
|
||||
|
||||
_clear_notice_invalidated_from_stage(task)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step6_generate_file",
|
||||
@@ -1522,6 +1544,11 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
# 重复 callback 由 Attempt 的持久化结果决定,不能按本次请求值重写 UI 状态。
|
||||
if completed.status == 'succeeded':
|
||||
apply_task_transition(task, TaskTransition.UPLOADED)
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
sync_order_task_stage_for_notice,
|
||||
)
|
||||
|
||||
sync_order_task_stage_for_notice(task)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step7_upload_freight",
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_audit_service.py
|
||||
|
||||
用途:提供订单模板版本中心的审计时间线查询与只读访问留痕。
|
||||
依赖:ShippingOrderDocumentProfile、ShippingOrderDocumentProfileAudit、User ORM 与 profile service 审计助手。
|
||||
逻辑:审计列表使用游标分页避免新增事件导致翻页重复;读接口返回安全摘要,不暴露 PDF、正文或盲测真值。
|
||||
用途:提供订单模板版本中心的审计时间线查询与只读访问留痕;视觉绑定变更双写 Profile 审计与统一平台快照。
|
||||
依赖:ShippingOrderDocumentProfile、ShippingOrderDocumentProfileAudit、User ORM、profile service 审计助手、
|
||||
audit_service.append_shipping_audit_event、audit_service.project_audit_snapshot。
|
||||
逻辑:审计列表使用游标分页避免新增事件导致翻页重复;读接口返回安全摘要,不暴露 PDF、正文或盲测真值;
|
||||
confirm/reject/suggest/updated 路径在 Profile _audit 后追加 append_shipping_audit_event(含加密 full 快照)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,6 +23,331 @@ from app.services.shipping_notice import order_document_profile_service as profi
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
XFA_VISUAL_BINDING_AUDIT_EVENTS: frozenset[str] = frozenset({
|
||||
'xfa_visual_binding_suggested',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
})
|
||||
|
||||
_VISUAL_BINDING_PLATFORM_ACTIONS: dict[str, str] = {
|
||||
'xfa_visual_binding_suggested': 'suggest_visual_binding',
|
||||
'xfa_visual_binding_confirmed': 'confirm_visual_binding',
|
||||
'xfa_visual_binding_rejected': 'reject_visual_binding',
|
||||
'xfa_visual_binding_updated': 'update_visual_binding',
|
||||
}
|
||||
|
||||
|
||||
def build_profile_audit_context(profile: ShippingOrderDocumentProfile | dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
组装 Profile 上下文供统一审计 full 快照与白名单投影使用。
|
||||
|
||||
核心逻辑:从 ORM 或调用方 dict 提取 profile_code/version/checksum/revision/template_mode。
|
||||
|
||||
Args:
|
||||
profile: Profile ORM 或已投影的上下文字典。
|
||||
|
||||
Returns:
|
||||
非敏感 Profile 上下文字典;profile 为空时返回空 dict。
|
||||
"""
|
||||
if profile is None:
|
||||
return {}
|
||||
if isinstance(profile, dict):
|
||||
return {
|
||||
key: profile[key]
|
||||
for key in (
|
||||
'profile_code',
|
||||
'profile_version',
|
||||
'definition_checksum',
|
||||
'revision_no',
|
||||
'template_mode',
|
||||
)
|
||||
if key in profile and profile[key] is not None
|
||||
}
|
||||
definition = profile.definition_json if isinstance(getattr(profile, 'definition_json', None), dict) else {}
|
||||
profile_code = getattr(profile, 'profile_code', None)
|
||||
version = getattr(profile, 'version', None)
|
||||
structure_fingerprint = getattr(profile, 'structure_fingerprint', None)
|
||||
lock_version = getattr(profile, 'lock_version', None)
|
||||
template_mode = getattr(profile, 'template_mode', None)
|
||||
return {
|
||||
key: value
|
||||
for key, value in {
|
||||
'profile_code': profile_code,
|
||||
'profile_version': int(version) if version is not None else None,
|
||||
'definition_checksum': structure_fingerprint,
|
||||
'revision_no': int(lock_version) if lock_version is not None else None,
|
||||
'template_mode': str(template_mode or definition.get('template_mode') or 'xfa_dataset'),
|
||||
}.items()
|
||||
if value is not None
|
||||
}
|
||||
|
||||
|
||||
def _project_visual_binding_whitelist_snapshot(
|
||||
*,
|
||||
binding_summary: dict[str, Any] | None,
|
||||
profile_context: dict[str, Any] | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
将 binding 摘要与 Profile 上下文投影为统一审计白名单快照。
|
||||
|
||||
核心逻辑:合并 profile 上下文与 field_code/status,委托 project_audit_snapshot 过滤。
|
||||
|
||||
Args:
|
||||
binding_summary: visual_binding_audit_snapshot 或 _binding_audit_snapshot 输出。
|
||||
profile_context: build_profile_audit_context 返回值。
|
||||
|
||||
Returns:
|
||||
白名单 before/after 快照,或 None。
|
||||
"""
|
||||
if binding_summary is None and not profile_context:
|
||||
return None
|
||||
from app.services.shipping_notice.audit_service import project_audit_snapshot
|
||||
|
||||
merged: dict[str, Any] = dict(profile_context or {})
|
||||
if isinstance(binding_summary, dict):
|
||||
field_code = binding_summary.get('field_code')
|
||||
if field_code:
|
||||
merged['field_code'] = field_code
|
||||
status = binding_summary.get('status') or binding_summary.get('visual_status')
|
||||
if status:
|
||||
merged['status'] = status
|
||||
projected = project_audit_snapshot(merged)
|
||||
return projected or None
|
||||
|
||||
|
||||
def _build_visual_binding_full_snapshot(
|
||||
*,
|
||||
binding: dict[str, Any] | None,
|
||||
binding_summary: dict[str, Any] | None,
|
||||
profile_context: dict[str, Any],
|
||||
extra: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
组装视觉绑定加密完整快照载荷(binding 摘要 + Profile 上下文)。
|
||||
|
||||
核心逻辑:优先使用 raw binding;缺失时降级 binding_summary;可附加 suggest 等区域元数据。
|
||||
|
||||
Args:
|
||||
binding: 原始 binding dict(可为 None)。
|
||||
binding_summary: 审计摘要(可为 None)。
|
||||
profile_context: Profile 上下文。
|
||||
extra: 可选附加非敏感字段(如 page_no、candidate_count)。
|
||||
|
||||
Returns:
|
||||
full_before/full_after 载荷;两者皆空且无 extra 时返回 None。
|
||||
"""
|
||||
if binding is None and binding_summary is None and not extra:
|
||||
return None
|
||||
payload: dict[str, Any] = dict(profile_context or {})
|
||||
if binding is not None:
|
||||
payload['binding'] = binding
|
||||
elif binding_summary is not None:
|
||||
payload['binding_summary'] = binding_summary
|
||||
if extra:
|
||||
payload.update(extra)
|
||||
return payload
|
||||
|
||||
|
||||
def _append_visual_binding_platform_audit_event(
|
||||
*,
|
||||
profile_id: int,
|
||||
document_id: int | None,
|
||||
event_type: str,
|
||||
actor_id: int | None,
|
||||
request_id: str | None,
|
||||
operation_id: str | None,
|
||||
action: str | None,
|
||||
binding_id: str | None,
|
||||
page_no: int | None,
|
||||
before_summary: dict[str, Any] | None,
|
||||
after_summary: dict[str, Any] | None,
|
||||
raw_binding_before: dict[str, Any] | None,
|
||||
raw_binding_after: dict[str, Any] | None,
|
||||
profile_context: dict[str, Any],
|
||||
metadata_extra: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
双写统一货代审计事件(含白名单 before/after 与加密 full 快照)。
|
||||
|
||||
核心逻辑:投影白名单 → 组装 full 载荷 → append_shipping_audit_event;
|
||||
context_refs/metadata 携带 binding_id、action、page_no。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
document_id: 可选样本文档 ID。
|
||||
event_type: 与 Profile 审计同名的事件码。
|
||||
actor_id: 操作者 ID。
|
||||
request_id: HTTP request_id。
|
||||
operation_id: 幂等 operation_id。
|
||||
action: 业务动作(confirm/reject/suggest/created/deleted/updated)。
|
||||
binding_id: 目标 binding_id。
|
||||
page_no: 页码(可选)。
|
||||
before_summary: 变更前 binding 审计摘要。
|
||||
after_summary: 变更后 binding 审计摘要。
|
||||
raw_binding_before: 变更前 raw binding。
|
||||
raw_binding_after: 变更后 raw binding。
|
||||
profile_context: Profile 上下文。
|
||||
metadata_extra: 附加 metadata(须已脱敏)。
|
||||
|
||||
Returns:
|
||||
None;由调用方与业务在同一事务提交。
|
||||
"""
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
safe_action = str(action or _VISUAL_BINDING_PLATFORM_ACTIONS.get(event_type) or event_type)[:64]
|
||||
safe_binding_id = str(binding_id or '').strip() or None
|
||||
context_refs: dict[str, Any] = {}
|
||||
if safe_binding_id:
|
||||
context_refs['binding_id'] = safe_binding_id
|
||||
if safe_action:
|
||||
context_refs['action'] = safe_action
|
||||
if page_no is not None:
|
||||
context_refs['page_no'] = int(page_no)
|
||||
|
||||
metadata: dict[str, Any] = dict(metadata_extra or {})
|
||||
if safe_binding_id:
|
||||
metadata.setdefault('binding_id', safe_binding_id)
|
||||
if safe_action:
|
||||
metadata.setdefault('action', safe_action)
|
||||
if page_no is not None:
|
||||
metadata.setdefault('page_no', int(page_no))
|
||||
|
||||
whitelist_before = _project_visual_binding_whitelist_snapshot(
|
||||
binding_summary=before_summary,
|
||||
profile_context=profile_context if before_summary is not None else None,
|
||||
)
|
||||
whitelist_after = _project_visual_binding_whitelist_snapshot(
|
||||
binding_summary=after_summary,
|
||||
profile_context=profile_context if after_summary is not None else profile_context or None,
|
||||
)
|
||||
full_before = _build_visual_binding_full_snapshot(
|
||||
binding=raw_binding_before,
|
||||
binding_summary=before_summary,
|
||||
profile_context=profile_context,
|
||||
)
|
||||
full_after = _build_visual_binding_full_snapshot(
|
||||
binding=raw_binding_after,
|
||||
binding_summary=after_summary,
|
||||
profile_context=profile_context,
|
||||
extra=dict(metadata_extra or {}) if event_type == 'xfa_visual_binding_suggested' and after_summary else None,
|
||||
)
|
||||
|
||||
append_shipping_audit_event(
|
||||
event_type=event_type,
|
||||
aggregate_type='shipping_order_document_profile',
|
||||
aggregate_id=str(int(profile_id)),
|
||||
document_id=document_id,
|
||||
actor_type='admin',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
result='success',
|
||||
action=safe_action,
|
||||
sensitivity_level='sensitive',
|
||||
before=whitelist_before,
|
||||
after=whitelist_after,
|
||||
full_before=full_before,
|
||||
full_after=full_after,
|
||||
context_refs=context_refs or None,
|
||||
metadata=metadata or None,
|
||||
)
|
||||
|
||||
|
||||
def record_visual_binding_audit(
|
||||
*,
|
||||
profile_id: int,
|
||||
document_id: int | None,
|
||||
event_type: str,
|
||||
actor_id: int | None,
|
||||
before: dict[str, Any] | None,
|
||||
after: dict[str, Any] | None,
|
||||
detail: dict[str, Any] | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
raw_binding_before: dict[str, Any] | None = None,
|
||||
raw_binding_after: dict[str, Any] | None = None,
|
||||
profile_context: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
写入 XFA 视觉绑定审计事件(含 before/after bbox 摘要)。
|
||||
|
||||
核心逻辑:委托 profile_service._audit 写 Profile 时间线;再双写 append_shipping_audit_event
|
||||
(白名单 before/after + 加密 full 快照)。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
document_id: 可选样本文档 ID。
|
||||
event_type: suggested|confirmed|rejected|updated。
|
||||
actor_id: 操作者 ID。
|
||||
before: 变更前 visual 摘要。
|
||||
after: 变更后 visual 摘要。
|
||||
detail: 附加非敏感 detail。
|
||||
request_id: HTTP request_id。
|
||||
operation_id: 幂等 operation_id。
|
||||
raw_binding_before: 变更前完整 binding(供 full_before)。
|
||||
raw_binding_after: 变更后完整 binding(供 full_after)。
|
||||
profile_context: Profile 上下文;省略时按 profile_id 加载。
|
||||
|
||||
Raises:
|
||||
ValidationError: event_type 未注册。
|
||||
"""
|
||||
safe_event = str(event_type or '').strip()
|
||||
if safe_event not in XFA_VISUAL_BINDING_AUDIT_EVENTS:
|
||||
raise ValidationError(
|
||||
'visual binding audit event_type is invalid',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
safe_detail = dict(detail or {})
|
||||
profile_service._audit(
|
||||
profile_id=int(profile_id),
|
||||
document_id=document_id,
|
||||
event_type=safe_event,
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
detail={
|
||||
**safe_detail,
|
||||
'before_visual_binding': before,
|
||||
'after_visual_binding': after,
|
||||
},
|
||||
)
|
||||
|
||||
resolved_context = dict(profile_context or {})
|
||||
if not resolved_context:
|
||||
profile_row = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
resolved_context = build_profile_audit_context(profile_row)
|
||||
|
||||
binding_id = str(safe_detail.get('binding_id') or (after or {}).get('binding_id') or (before or {}).get('binding_id') or '').strip() or None
|
||||
page_no_raw = safe_detail.get('page_no')
|
||||
if page_no_raw is None and isinstance(after, dict):
|
||||
page_no_raw = after.get('page_no')
|
||||
if page_no_raw is None and isinstance(before, dict):
|
||||
page_no_raw = before.get('page_no')
|
||||
page_no = int(page_no_raw) if page_no_raw is not None else None
|
||||
|
||||
_append_visual_binding_platform_audit_event(
|
||||
profile_id=int(profile_id),
|
||||
document_id=document_id,
|
||||
event_type=safe_event,
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
action=str(safe_detail.get('action') or '').strip() or None,
|
||||
binding_id=binding_id,
|
||||
page_no=page_no,
|
||||
before_summary=before,
|
||||
after_summary=after,
|
||||
raw_binding_before=raw_binding_before,
|
||||
raw_binding_after=raw_binding_after,
|
||||
profile_context=resolved_context,
|
||||
metadata_extra={
|
||||
key: safe_detail[key]
|
||||
for key in ('reason_code', 'candidate_count', 'normalized_bbox')
|
||||
if key in safe_detail
|
||||
} or None,
|
||||
)
|
||||
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取当前模板版本;不存在时复用版本中心统一 not-found 契约。"""
|
||||
|
||||
@@ -34,6 +34,10 @@ _ENTITY_ORDER = {
|
||||
'xfa_source_contract': 15,
|
||||
'xfa_header_mapping': 45,
|
||||
'xfa_line_mapping': 55,
|
||||
'xfa_unified_binding': 46,
|
||||
'xfa_split_rule_set': 47,
|
||||
'xfa_split_segment': 48,
|
||||
'xfa_split_matcher': 49,
|
||||
}
|
||||
|
||||
|
||||
@@ -822,6 +826,191 @@ def _compare_xfa_definitions(before_def: dict[str, Any] | None, after_def: dict[
|
||||
changes=changes,
|
||||
sort_key=f'{sort_prefix}:{mapping_id}',
|
||||
))
|
||||
items.extend(_compare_xfa_bindings(before_def, after_def))
|
||||
items.extend(_compare_xfa_split_rules(before_def, after_def))
|
||||
return items
|
||||
|
||||
|
||||
def _compare_xfa_bindings(
|
||||
before_def: dict[str, Any] | None,
|
||||
after_def: dict[str, Any],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
比较统一 bindings:visual_binding 框、value_binding 映射与 split_rule_ref。
|
||||
|
||||
Args:
|
||||
before_def: 基线 definition。
|
||||
after_def: 当前 definition。
|
||||
|
||||
Returns:
|
||||
按 binding_id 稳定的 diff 项列表。
|
||||
"""
|
||||
items: list[dict[str, Any]] = []
|
||||
|
||||
def _binding_map(defn: dict[str, Any] | None) -> dict[str, dict[str, Any]]:
|
||||
result: dict[str, dict[str, Any]] = {}
|
||||
for index, item in enumerate(list((defn or {}).get('bindings') or [])):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
key = str(item.get('binding_id') or f'index:{index}')
|
||||
result[key] = item
|
||||
return result
|
||||
|
||||
previous_map = _binding_map(before_def)
|
||||
current_map = _binding_map(after_def)
|
||||
for binding_id in sorted(set(previous_map) | set(current_map)):
|
||||
previous = previous_map.get(binding_id)
|
||||
current = current_map.get(binding_id)
|
||||
previous_body = previous or {}
|
||||
current_body = current or {}
|
||||
prev_value = previous_body.get('value_binding') if isinstance(previous_body.get('value_binding'), dict) else {}
|
||||
curr_value = current_body.get('value_binding') if isinstance(current_body.get('value_binding'), dict) else {}
|
||||
prev_visual = previous_body.get('visual_binding') if isinstance(previous_body.get('visual_binding'), dict) else {}
|
||||
curr_visual = current_body.get('visual_binding') if isinstance(current_body.get('visual_binding'), dict) else {}
|
||||
changes = _scalar_changes(
|
||||
{
|
||||
'field_id': previous_body.get('field_id'),
|
||||
'field_code': previous_body.get('field_code'),
|
||||
'scope': previous_body.get('scope'),
|
||||
'path_id': prev_value.get('path_id'),
|
||||
'visual_status': prev_visual.get('status'),
|
||||
'visual_source': prev_visual.get('source'),
|
||||
},
|
||||
{
|
||||
'field_id': current_body.get('field_id'),
|
||||
'field_code': current_body.get('field_code'),
|
||||
'scope': current_body.get('scope'),
|
||||
'path_id': curr_value.get('path_id'),
|
||||
'visual_status': curr_visual.get('status'),
|
||||
'visual_source': curr_visual.get('source'),
|
||||
},
|
||||
('field_id', 'field_code', 'scope', 'path_id', 'visual_status', 'visual_source'),
|
||||
)
|
||||
visual_region = _region_change(
|
||||
'visual_binding.normalized_bbox',
|
||||
prev_visual.get('normalized_bbox'),
|
||||
curr_visual.get('normalized_bbox'),
|
||||
)
|
||||
if visual_region:
|
||||
changes.append(visual_region)
|
||||
split_change = _change(
|
||||
'split_rule_ref',
|
||||
'json',
|
||||
previous_body.get('split_rule_ref'),
|
||||
current_body.get('split_rule_ref'),
|
||||
) if previous_body.get('split_rule_ref') != current_body.get('split_rule_ref') else None
|
||||
if split_change:
|
||||
changes.append(split_change)
|
||||
field_code = current_body.get('field_code') or previous_body.get('field_code') or binding_id
|
||||
items.append(_item(
|
||||
entity_type='xfa_unified_binding',
|
||||
entity_id=binding_id,
|
||||
parent_id=None,
|
||||
label=f'Binding {field_code}',
|
||||
before=previous,
|
||||
after=current,
|
||||
changes=changes,
|
||||
sort_key=f'046:{binding_id}',
|
||||
))
|
||||
return items
|
||||
|
||||
|
||||
def _compare_xfa_split_rules(
|
||||
before_def: dict[str, Any] | None,
|
||||
after_def: dict[str, Any],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
比较 split_rules:rule_set 元数据、segment 映射与 matcher 语义。
|
||||
|
||||
Args:
|
||||
before_def: 基线 definition。
|
||||
after_def: 当前 definition。
|
||||
|
||||
Returns:
|
||||
segment_id / rule_id 稳定的 diff 项列表。
|
||||
"""
|
||||
|
||||
def _segment_index(defn: dict[str, Any] | None) -> dict[str, dict[str, Any]]:
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
for rule_set in list((defn or {}).get('split_rules') or []):
|
||||
if not isinstance(rule_set, dict):
|
||||
continue
|
||||
for rule in rule_set.get('rules') or []:
|
||||
if not isinstance(rule, dict):
|
||||
continue
|
||||
segment = rule.get('segment') if isinstance(rule.get('segment'), dict) else {}
|
||||
segment_id = str(segment.get('segment_id') or '').strip()
|
||||
if not segment_id:
|
||||
continue
|
||||
matcher = rule.get('matcher') if isinstance(rule.get('matcher'), dict) else {}
|
||||
out[segment_id] = {
|
||||
'segment_id': segment_id,
|
||||
'segment_code': segment.get('segment_code'),
|
||||
'display_name': segment.get('display_name'),
|
||||
'handling': segment.get('handling'),
|
||||
'target_field_code': segment.get('target_field_code'),
|
||||
'target_field_id': segment.get('target_field_id'),
|
||||
'matcher': matcher,
|
||||
'rule_id': rule.get('rule_id'),
|
||||
'rule_set_id': rule_set.get('rule_set_id') or rule_set.get('rule_id'),
|
||||
'rule_version': rule_set.get('rule_version'),
|
||||
'status': rule_set.get('status'),
|
||||
}
|
||||
return out
|
||||
|
||||
items: list[dict[str, Any]] = []
|
||||
before_segments = _segment_index(before_def)
|
||||
after_segments = _segment_index(after_def)
|
||||
for segment_id in sorted(set(before_segments) | set(after_segments)):
|
||||
previous = before_segments.get(segment_id)
|
||||
current = after_segments.get(segment_id)
|
||||
previous_body = previous or {}
|
||||
current_body = current or {}
|
||||
changes = _scalar_changes(
|
||||
{
|
||||
'segment_code': previous_body.get('segment_code'),
|
||||
'display_name': previous_body.get('display_name'),
|
||||
'handling': previous_body.get('handling'),
|
||||
'target_field_code': previous_body.get('target_field_code'),
|
||||
'rule_id': previous_body.get('rule_id'),
|
||||
'rule_version': previous_body.get('rule_version'),
|
||||
'status': previous_body.get('status'),
|
||||
},
|
||||
{
|
||||
'segment_code': current_body.get('segment_code'),
|
||||
'display_name': current_body.get('display_name'),
|
||||
'handling': current_body.get('handling'),
|
||||
'target_field_code': current_body.get('target_field_code'),
|
||||
'rule_id': current_body.get('rule_id'),
|
||||
'rule_version': current_body.get('rule_version'),
|
||||
'status': current_body.get('status'),
|
||||
},
|
||||
(
|
||||
'segment_code', 'display_name', 'handling', 'target_field_code',
|
||||
'rule_id', 'rule_version', 'status',
|
||||
),
|
||||
)
|
||||
prev_matcher = previous_body.get('matcher') if isinstance(previous_body.get('matcher'), dict) else {}
|
||||
curr_matcher = current_body.get('matcher') if isinstance(current_body.get('matcher'), dict) else {}
|
||||
matcher_change = _change(
|
||||
'matcher',
|
||||
'json',
|
||||
prev_matcher,
|
||||
curr_matcher,
|
||||
) if prev_matcher != curr_matcher else None
|
||||
if matcher_change:
|
||||
changes.append(matcher_change)
|
||||
label = current_body.get('display_name') or previous_body.get('display_name') or segment_id
|
||||
items.append(_item(
|
||||
entity_type='xfa_split_segment',
|
||||
entity_id=segment_id,
|
||||
parent_id=str(current_body.get('rule_set_id') or previous_body.get('rule_set_id') or ''),
|
||||
label=f'Split segment {label}',
|
||||
before=previous,
|
||||
after=current,
|
||||
changes=changes,
|
||||
sort_key=f'048:{segment_id}',
|
||||
))
|
||||
return items
|
||||
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_preview_service.py
|
||||
|
||||
用途:提供订单模板版本中心的冻结样本只读预览链路。
|
||||
依赖:Profile/Sample/Layout 模型、preview_grant_store、PDF 渲染能力、XFA 只读映射 DTO。
|
||||
逻辑:预览必须绑定 profile sample,并校验冻结的 document/layout/hash/checksum 后才签发一次性 token;
|
||||
XFA 模式禁止空白 PDF 页预览,改为返回只读映射证据。
|
||||
用途:提供订单模板版本中心与 XFA 编辑器的 PDF 页面预览链路(含冻结样本只读画布)。
|
||||
依赖:Profile/Sample/Layout 模型、preview_grant_store、PDFium PNG 渲染、XFA 只读映射 DTO。
|
||||
逻辑:预览绑定 profile sample 或冻结证据,校验 document/hash/checksum 后签发短期一次性 token;
|
||||
XFA 与 coordinate 模式均允许 PDFium 页图预览;令牌绑定 actor/profile/样本/页且不可重放。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -105,7 +105,7 @@ def build_xfa_readonly_mapping_evidence(profile: ShippingOrderDocumentProfile) -
|
||||
})
|
||||
return {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'pdf_preview_available': False,
|
||||
'pdf_preview_available': True,
|
||||
'source_contract': {
|
||||
'template_packet_checksum': source.get('template_packet_checksum'),
|
||||
'dataset_structure_fingerprint': source.get('dataset_structure_fingerprint'),
|
||||
@@ -179,6 +179,55 @@ def _sample_frozen_evidence_ready(sample: ShippingOrderDocumentProfileSample) ->
|
||||
return all(required)
|
||||
|
||||
|
||||
def _is_xfa_frozen_sample(sample: ShippingOrderDocumentProfileSample) -> bool:
|
||||
"""判断样本是否以 XFA 结构身份冻结(非 coordinate 表格)。"""
|
||||
identity = sample.table_identity_snapshot if isinstance(sample.table_identity_snapshot, dict) else {}
|
||||
return str(identity.get('kind') or '') == 'xfa_structure'
|
||||
|
||||
|
||||
def _validate_frozen_xfa_layout_identity(
|
||||
sample: ShippingOrderDocumentProfileSample,
|
||||
layout_version: ShippingDocumentLayoutVersion,
|
||||
) -> None:
|
||||
"""
|
||||
校验 XFA 冻结样本的 layout/结构身份,不依赖 table_regions。
|
||||
|
||||
核心逻辑:比对 datasets/structure fingerprint 与 structure_analysis_id 快照。
|
||||
"""
|
||||
identity = dict(sample.table_identity_snapshot or {})
|
||||
expected_analysis_id = identity.get('structure_analysis_id')
|
||||
capability = (
|
||||
layout_version.payload_json.get('xfa_capability')
|
||||
if isinstance(layout_version.payload_json, dict)
|
||||
else {}
|
||||
)
|
||||
if not isinstance(capability, dict):
|
||||
capability = (
|
||||
layout_version.payload_json.get('capability')
|
||||
if isinstance(layout_version.payload_json, dict)
|
||||
else {}
|
||||
)
|
||||
if expected_analysis_id is not None and capability.get('structure_analysis_id') not in (None, expected_analysis_id):
|
||||
raise ValidationError(
|
||||
'Frozen XFA structure analysis no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
expected_fingerprint = str(identity.get('dataset_structure_fingerprint') or '').strip().lower()
|
||||
actual_fingerprint = str(capability.get('dataset_structure_fingerprint') or '').strip().lower()
|
||||
if expected_fingerprint and actual_fingerprint and expected_fingerprint != actual_fingerprint:
|
||||
raise ValidationError(
|
||||
'Frozen XFA dataset fingerprint no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
expected_template = str(identity.get('template_packet_checksum') or '').strip().lower()
|
||||
actual_template = str(capability.get('template_packet_checksum') or '').strip().lower()
|
||||
if expected_template and actual_template and expected_template != actual_template:
|
||||
raise ValidationError(
|
||||
'Frozen XFA template checksum no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
|
||||
|
||||
def _frozen_table_identity_ready(
|
||||
sample: ShippingOrderDocumentProfileSample,
|
||||
*,
|
||||
@@ -274,16 +323,21 @@ def _frozen_sample_context(
|
||||
'Frozen layout source hash no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
actual_checksum, _ = canonical_layout_payload(layout_version.payload_json)
|
||||
expected_checksum = str(sample.layout_payload_checksum or '').strip().lower()
|
||||
if (
|
||||
actual_checksum != expected_checksum
|
||||
or str(layout_version.payload_checksum or '').strip().lower() != expected_checksum
|
||||
):
|
||||
raise ValidationError(
|
||||
'Frozen layout checksum no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
if _is_xfa_frozen_sample(sample):
|
||||
# [STEP 1] XFA 冻结样本以 structure identity 为准,不用 coordinate layout checksum。
|
||||
_validate_frozen_xfa_layout_identity(sample, layout_version)
|
||||
else:
|
||||
actual_checksum, _ = canonical_layout_payload(layout_version.payload_json)
|
||||
expected_checksum = str(sample.layout_payload_checksum or '').strip().lower()
|
||||
if (
|
||||
actual_checksum != expected_checksum
|
||||
or str(layout_version.payload_checksum or '').strip().lower() != expected_checksum
|
||||
):
|
||||
raise ValidationError(
|
||||
'Frozen layout checksum no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
_frozen_table_identity_ready(sample, layout_payload=layout_version.payload_json)
|
||||
if str(layout_version.contract_version or '').strip() != str(sample.layout_contract_version or '').strip():
|
||||
raise ValidationError(
|
||||
'Frozen layout contract version no longer matches the published evidence',
|
||||
@@ -305,7 +359,6 @@ def _frozen_sample_context(
|
||||
'Frozen parser version no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
_frozen_table_identity_ready(sample, layout_payload=layout_version.payload_json)
|
||||
return profile, sample, document, layout_version, asset
|
||||
|
||||
|
||||
@@ -329,7 +382,11 @@ def authorize_frozen_sample_preview_pages(
|
||||
sample_binding_id: int,
|
||||
actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""按冻结样本绑定签发一次性页预览 token,禁止 document_id 枚举读取。"""
|
||||
"""
|
||||
按冻结样本绑定签发一次性页预览 token,禁止 document_id 枚举读取。
|
||||
|
||||
核心逻辑:XFA 与 coordinate 样本均走 PDFium PNG;令牌绑定 actor/profile/样本/页。
|
||||
"""
|
||||
if actor_id is None:
|
||||
raise NotFoundError(
|
||||
'Order profile sample not found',
|
||||
@@ -338,11 +395,6 @@ def authorize_frozen_sample_preview_pages(
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if profile is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
if _is_xfa_profile(profile):
|
||||
raise ValidationError(
|
||||
'XFA profiles do not support blank PDF page preview',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
_, sample, document, _layout_version, asset = _frozen_sample_context(
|
||||
profile_id=int(profile_id), sample_binding_id=int(sample_binding_id),
|
||||
)
|
||||
@@ -376,7 +428,12 @@ def authorize_frozen_sample_preview_pages(
|
||||
sample_binding_id=int(sample.id),
|
||||
event_type='preview_pages_authorized',
|
||||
actor_id=actor_id,
|
||||
detail={'page_count': len(pages), 'ttl_seconds': PREVIEW_GRANT_TTL_SECONDS, 'mode': 'frozen_sample'},
|
||||
detail={
|
||||
'page_count': len(pages),
|
||||
'ttl_seconds': PREVIEW_GRANT_TTL_SECONDS,
|
||||
'mode': 'frozen_sample',
|
||||
'template_mode': 'xfa_dataset' if _is_xfa_profile(profile) else 'coordinate',
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return {
|
||||
|
||||
+192
-9
@@ -2,9 +2,11 @@
|
||||
services/shipping_notice/order_document_profile_publish_check_service.py
|
||||
|
||||
用途:生成、确认和消费订单模板不可变发布检查报告。
|
||||
依赖:草稿 Revision、验证运行、版面/XFA 结构签名、跨模板重叠验证、语义差异、发布服务和编辑租约服务。
|
||||
逻辑:报告冻结当前草稿身份与签名/重叠引用;XFA 模式使用结构签名与路径/集合/对账阻断;
|
||||
消费时在同一事务再次校验并发布,草稿或签名变化只能令报告失效。
|
||||
依赖:草稿 Revision、验证运行、版面/XFA 结构签名、跨模板重叠验证、语义差异、发布服务、
|
||||
编辑租约服务、xfa_validation 视觉指标与统一 bindings。
|
||||
逻辑:报告冻结当前草稿身份与签名/重叠引用;XFA 模式使用结构签名、路径/集合/对账阻断,
|
||||
以及视觉绑定完整性与 visual/evidence 100% 阈值;消费时在同一事务再次校验并发布,
|
||||
草稿或签名变化只能令报告失效;编辑人不得批准自己的 Revision。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -117,15 +119,19 @@ def _signature_status(profile: ShippingOrderDocumentProfile, revision: ShippingO
|
||||
|
||||
def _find_last_profile_editor_id(profile_id: int) -> int | None:
|
||||
"""
|
||||
查找最近一次编辑 Profile 映射/拆分规则的管理员 ID。
|
||||
查找最近一次编辑 Profile 映射/视觉绑定/拆分规则的管理员 ID。
|
||||
|
||||
核心逻辑:优先审计事件;回退至最新 DraftRevision.created_by_id。
|
||||
核心逻辑:优先审计事件(含视觉确认/驳回/更新);回退至最新 DraftRevision.created_by_id。
|
||||
"""
|
||||
editor_events = (
|
||||
'xfa_mapping_saved',
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_segment_mapping_updated',
|
||||
'xfa_profile_draft_saved',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
'xfa_visual_binding_suggested',
|
||||
)
|
||||
audit = (
|
||||
db.session.query(ShippingOrderDocumentProfileAudit)
|
||||
@@ -154,9 +160,10 @@ def _blocking_xfa_definition(
|
||||
validation: ShippingOrderDocumentProfileValidationRun | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
汇总 XFA 发布阻断项:缺失路径、集合歧义、对账失败、stale 验证。
|
||||
汇总 XFA 发布阻断项:缺失路径、集合歧义、对账失败、视觉绑定与验证指标。
|
||||
|
||||
核心逻辑:检查 source_contract / 映射覆盖 / current_sample 摘要中的对账失败码。
|
||||
核心逻辑:检查 source_contract / 映射覆盖 / 统一 bindings 视觉确认 /
|
||||
current_sample 摘要中的对账失败码与 visual/evidence 阈值(要求 100%)。
|
||||
"""
|
||||
blocking: list[dict[str, Any]] = []
|
||||
definition = dict(profile.definition_json or {})
|
||||
@@ -176,7 +183,32 @@ def _blocking_xfa_definition(
|
||||
header_mappings = [item for item in (definition.get('header_mappings') or []) if isinstance(item, dict)]
|
||||
line_mapping = definition.get('line_mapping') if isinstance(definition.get('line_mapping'), dict) else {}
|
||||
line_fields = [item for item in (line_mapping.get('fields') or []) if isinstance(item, dict)]
|
||||
if any(not item.get('data_path') or not item.get('field_id') for item in header_mappings + line_fields):
|
||||
bindings_list = [item for item in (definition.get('bindings') or []) if isinstance(item, dict)]
|
||||
has_legacy_mappings = bool(header_mappings or line_fields)
|
||||
has_bindings = bool(bindings_list)
|
||||
|
||||
if has_bindings and has_legacy_mappings:
|
||||
blocking.append({
|
||||
'key': 'xfa_dual_binding_source',
|
||||
'message': 'XFA profile must not mix unified bindings with legacy header_mappings or line_mapping.fields.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'reason_code': 'xfa_dual_binding_source',
|
||||
})
|
||||
|
||||
if has_bindings:
|
||||
if any(
|
||||
not (item.get('value_binding') or {}).get('data_path') or not item.get('field_id')
|
||||
for item in bindings_list
|
||||
if isinstance(item.get('value_binding'), dict)
|
||||
):
|
||||
blocking.append({
|
||||
'key': 'xfa_mapping_path_missing',
|
||||
'message': 'Every XFA binding must bind a known data path.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
})
|
||||
elif has_legacy_mappings and any(
|
||||
not item.get('data_path') or not item.get('field_id') for item in header_mappings + line_fields
|
||||
):
|
||||
blocking.append({
|
||||
'key': 'xfa_mapping_path_missing',
|
||||
'message': 'Every XFA mapping must bind a known data path.',
|
||||
@@ -189,7 +221,7 @@ def _blocking_xfa_definition(
|
||||
}
|
||||
mapped_ids = {
|
||||
str(item.get('field_id') or '')
|
||||
for item in header_mappings + line_fields
|
||||
for item in (bindings_list if has_bindings else header_mappings + line_fields)
|
||||
if item.get('field_id')
|
||||
}
|
||||
split_rules_raw = definition.get('split_rules') or []
|
||||
@@ -199,6 +231,10 @@ def _blocking_xfa_definition(
|
||||
validate_split_rules_against_schema,
|
||||
)
|
||||
known_path_ids = {
|
||||
str((item.get('value_binding') or {}).get('path_id') or '')
|
||||
for item in bindings_list
|
||||
if has_bindings and isinstance(item.get('value_binding'), dict) and (item.get('value_binding') or {}).get('path_id')
|
||||
} if has_bindings else {
|
||||
str(item.get('path_id') or '')
|
||||
for item in header_mappings + line_fields
|
||||
if item.get('path_id')
|
||||
@@ -272,6 +308,13 @@ def _blocking_xfa_definition(
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'field_codes': missing_required[:20],
|
||||
})
|
||||
|
||||
# [STEP] 统一视觉绑定发布门禁:XFA 须 bindings-only 且视觉已确认。
|
||||
blocking.extend(_blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids=set(schema_fields.keys()),
|
||||
))
|
||||
|
||||
if validation is not None:
|
||||
summary = dict(validation.summary_json or {})
|
||||
if validation.definition_checksum != profile.structure_fingerprint or validation.status != 'passed':
|
||||
@@ -318,6 +361,146 @@ def _blocking_xfa_definition(
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'failure_codes': failures[:10],
|
||||
})
|
||||
# 指标阈值:存在时视觉/证据须 100%。
|
||||
blocking.extend(_blocking_xfa_validation_metrics(summary))
|
||||
return blocking
|
||||
|
||||
|
||||
def _blocking_xfa_visual_bindings(
|
||||
*,
|
||||
definition: dict[str, Any],
|
||||
schema_field_ids: set[str],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
校验统一视觉绑定是否满足发布门禁。
|
||||
|
||||
核心逻辑:XFA 无 bindings 一律阻断;bindings 与 legacy mappings 共存 →
|
||||
xfa_dual_binding_source;已有 bindings 时每个正式 Schema 字段须 is_formal_binding_publishable。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XfaUnifiedFieldBinding,
|
||||
is_formal_binding_publishable,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_validation import (
|
||||
collect_formal_schema_field_ids,
|
||||
compute_visual_coverage_rate,
|
||||
)
|
||||
|
||||
blocking: list[dict[str, Any]] = []
|
||||
bindings_raw = definition.get('bindings')
|
||||
bindings_list = bindings_raw if isinstance(bindings_raw, list) else []
|
||||
header_mappings = [item for item in (definition.get('header_mappings') or []) if isinstance(item, dict)]
|
||||
line_mapping = definition.get('line_mapping') if isinstance(definition.get('line_mapping'), dict) else {}
|
||||
line_fields = [item for item in (line_mapping.get('fields') or []) if isinstance(item, dict)]
|
||||
has_legacy_mappings = bool(header_mappings or line_fields)
|
||||
has_xfa_dataset = isinstance(definition.get('source_contract'), dict) and bool(
|
||||
(definition.get('source_contract') or {}).get('dataset_structure_fingerprint')
|
||||
)
|
||||
|
||||
if bindings_list and has_legacy_mappings:
|
||||
blocking.append({
|
||||
'key': 'xfa_dual_binding_source',
|
||||
'message': 'XFA profile must not mix unified bindings with legacy header_mappings or line_mapping.fields.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'reason_code': 'xfa_dual_binding_source',
|
||||
})
|
||||
return blocking
|
||||
|
||||
if has_xfa_dataset and not bindings_list:
|
||||
blocking.append({
|
||||
'key': 'xfa_visual_bindings_required',
|
||||
'message': 'Unified visual bindings are required before publishing an XFA profile.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'reason_code': 'xfa_visual_bindings_required',
|
||||
})
|
||||
return blocking
|
||||
|
||||
if not bindings_list:
|
||||
return blocking
|
||||
|
||||
formal_ids = collect_formal_schema_field_ids(
|
||||
definition,
|
||||
schema_field_ids=schema_field_ids or None,
|
||||
)
|
||||
publishable_by_field: dict[str, bool] = {}
|
||||
for raw in bindings_list:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
try:
|
||||
binding = XfaUnifiedFieldBinding.model_validate(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
field_id = str(binding.field_id)
|
||||
publishable_by_field[field_id] = (
|
||||
publishable_by_field.get(field_id, False) or is_formal_binding_publishable(binding)
|
||||
)
|
||||
incomplete = sorted(
|
||||
field_id for field_id in formal_ids if not publishable_by_field.get(field_id)
|
||||
)
|
||||
if incomplete:
|
||||
blocking.append({
|
||||
'key': 'xfa_visual_binding_incomplete',
|
||||
'message': 'Every formal Schema-mapped field must have a confirmed visual binding.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'reason_code': 'xfa_visual_binding_incomplete',
|
||||
'field_ids': incomplete[:20],
|
||||
})
|
||||
coverage = compute_visual_coverage_rate(definition, schema_field_ids=schema_field_ids or None)
|
||||
if coverage < 1.0 and 'xfa_visual_binding_incomplete' not in {item.get('key') for item in blocking}:
|
||||
blocking.append({
|
||||
'key': 'xfa_visual_coverage_insufficient',
|
||||
'message': 'Visual binding coverage must be 100% before publish.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'reason_code': 'xfa_visual_coverage_insufficient',
|
||||
'visual_coverage_rate': coverage,
|
||||
})
|
||||
return blocking
|
||||
|
||||
|
||||
def _blocking_xfa_validation_metrics(summary: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
当 current-sample 摘要含统一指标时,要求视觉/证据覆盖率均为 100%。
|
||||
|
||||
Args:
|
||||
summary: validation.run.summary_json。
|
||||
|
||||
Returns:
|
||||
阻断项列表。
|
||||
"""
|
||||
blocking: list[dict[str, Any]] = []
|
||||
has_metrics = any(
|
||||
key in summary
|
||||
for key in ('visual_coverage_rate', 'evidence_retention_rate', 'mirror_consistency_rate')
|
||||
)
|
||||
if not has_metrics:
|
||||
return blocking
|
||||
visual = summary.get('visual_coverage_rate')
|
||||
if visual is not None and float(visual) < 1.0:
|
||||
blocking.append({
|
||||
'key': 'xfa_visual_coverage_insufficient',
|
||||
'message': 'Visual coverage rate must be 100% on the current sample.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'reason_code': 'xfa_visual_coverage_insufficient',
|
||||
'visual_coverage_rate': float(visual),
|
||||
})
|
||||
evidence = summary.get('evidence_retention_rate')
|
||||
if evidence is not None and float(evidence) < 1.0:
|
||||
blocking.append({
|
||||
'key': 'xfa_evidence_retention_insufficient',
|
||||
'message': 'evidence_only retention rate must be 100% on the current sample.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'reason_code': 'xfa_evidence_retention_insufficient',
|
||||
'evidence_retention_rate': float(evidence),
|
||||
})
|
||||
mirror = summary.get('mirror_consistency_rate')
|
||||
if mirror is not None and float(mirror) < 1.0:
|
||||
blocking.append({
|
||||
'key': 'xfa_mirror_consistency_insufficient',
|
||||
'message': 'Mirror consistency rate must be 100% on the current sample.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'reason_code': 'xfa_mirror_consistency_insufficient',
|
||||
'mirror_consistency_rate': float(mirror),
|
||||
})
|
||||
return blocking
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,8 @@ backend/app/services/shipping_notice/order_document_profile_revision_service.py
|
||||
用途:提供订单模板草稿 Revision 的查询与恢复(coordinate / xfa_dataset 共用)。
|
||||
依赖:Profile、DraftRevision、Profile 保存服务和编辑租约服务。
|
||||
逻辑:恢复只读取旧快照并作为新的有效保存写入,历史 Revision 绝不覆盖或删除;
|
||||
XFA 快照的 definition checksum 与语义摘要由 save_draft / change_summary_json 承载。
|
||||
XFA 快照的 definition_snapshot_json 冻结含 bindings[] 与 split_rules[] 的新格式 definition,
|
||||
checksum 与 change_summary_json(binding_count/split_rule_count)由 save_draft 承载。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,20 +1,24 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_suggestion_service.py
|
||||
|
||||
用途:冻结订单模板算法建议的接受、调整接受或拒绝决定。
|
||||
依赖:Profile 草稿、Revision、编辑租约、SuggestionDecision ORM 与统一错误。
|
||||
逻辑:编辑器先呈现本地建议,再以建议摘要 checksum 写入不可变决定;服务端只记录决定事实,不替换 Profile 定义。
|
||||
用途:XFA 统一映射建议(视觉 + 拆分规则)与算法建议决定冻结。
|
||||
依赖:order_document_profile_service、order_document_profile_visual_binding_service、
|
||||
xfa_analysis、xfa_split_rule_contract、Profile 草稿与 SuggestionDecision ORM。
|
||||
逻辑:suggest/preview 路径只读不写 Draft/业务表;决定写入走 decide() 且需租约;
|
||||
拆分建议 status 固定 draft/suggested,禁止直接 confirmed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
@@ -22,15 +26,427 @@ from app.models import (
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice.document_layout.xfa_analysis import analyze_xfa_pdf
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import sanitize_xfa_dto
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
XfaSplitMatcher,
|
||||
XfaSplitRule,
|
||||
XfaSplitRuleSet,
|
||||
XfaSplitSegment,
|
||||
new_rule_id,
|
||||
new_segment_id,
|
||||
split_rule_content_fingerprint,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_visual_binding import (
|
||||
suggest_visual_binding_candidates,
|
||||
)
|
||||
|
||||
|
||||
def suggestion_identity(summary: dict[str, Any]) -> dict[str, str]:
|
||||
"""根据无敏感建议摘要生成稳定身份;相同算法输出可幂等记录同一决定。"""
|
||||
"""
|
||||
根据无敏感建议摘要生成稳定身份;相同算法输出可幂等记录同一决定。
|
||||
|
||||
Args:
|
||||
summary: 不含敏感正文的建议摘要 dict。
|
||||
|
||||
Returns:
|
||||
suggestion_id 与 suggestion_checksum。
|
||||
"""
|
||||
encoded = json.dumps(summary, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
checksum = hashlib.sha256(encoded).hexdigest()
|
||||
return {'suggestion_id': checksum[:32], 'suggestion_checksum': checksum}
|
||||
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取 Profile;不存在时统一 not-found。"""
|
||||
row = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if row is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
return row
|
||||
|
||||
|
||||
def _require_xfa_draft(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
"""校验 XFA 草稿并返回 definition 副本(只读)。"""
|
||||
if str(profile.status or '') != 'draft':
|
||||
raise ValidationError(
|
||||
'Suggestions require a draft profile',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
mode = str(profile.template_mode or (profile.definition_json or {}).get('template_mode') or '')
|
||||
if mode != 'xfa_dataset':
|
||||
raise ValidationError(
|
||||
'Unified mapping suggestions are only available for XFA profiles',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
return dict(profile.definition_json or {})
|
||||
|
||||
|
||||
def _sample_pdf_bytes(document_id: int) -> bytes:
|
||||
"""读取样本文档 PDF 字节。"""
|
||||
from app.models import ShippingOrderDocument
|
||||
from app.models import FileAsset
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
if document is None or not document.asset_id:
|
||||
raise ValidationError(
|
||||
'Profile sample document is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
asset = db.session.get(FileAsset, int(document.asset_id))
|
||||
if asset is None:
|
||||
raise ValidationError(
|
||||
'Profile sample file is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
return read_asset_bytes(asset)
|
||||
|
||||
|
||||
def _resolve_matnr_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 优先;否则在权威行集合下查找 local_name=MATNR 的路径。
|
||||
|
||||
Args:
|
||||
definition: 当前 Profile definition。
|
||||
path_context: resolve_xfa_path_context 结果。
|
||||
path_id: 可选显式 path_id。
|
||||
|
||||
Returns:
|
||||
(path_id, data_path) 元组。
|
||||
|
||||
Raises:
|
||||
ValidationError: 无法定位 MATNR 路径。
|
||||
"""
|
||||
path_map: dict[str, str] = dict(path_context.get('path_map') or {})
|
||||
if path_id:
|
||||
resolved = path_map.get(str(path_id))
|
||||
if not resolved:
|
||||
raise ValidationError(
|
||||
'XFA path_id cannot be resolved',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
|
||||
details={'path_id': path_id},
|
||||
)
|
||||
return str(path_id), resolved
|
||||
|
||||
source = definition.get('source_contract') if isinstance(definition.get('source_contract'), dict) else {}
|
||||
auth_path = str(source.get('authoritative_line_collection_path') or '').rstrip('/')
|
||||
candidates = [
|
||||
(pid, data_path)
|
||||
for pid, data_path in path_map.items()
|
||||
if data_path.endswith('/MATNR') or data_path == f'{auth_path}/MATNR'
|
||||
]
|
||||
if not candidates:
|
||||
raise ValidationError(
|
||||
'MATNR source path is not available for split rule suggestion',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
|
||||
details={'reason': 'matnr_path_missing'},
|
||||
)
|
||||
if len(candidates) > 1:
|
||||
candidates.sort(key=lambda item: item[1])
|
||||
return candidates[0]
|
||||
|
||||
|
||||
def _schema_field_ids(profile_id: int) -> dict[str, dict[str, Any]]:
|
||||
"""
|
||||
读取 Profile 绑定 Schema 的 field_code → 字段定义。
|
||||
|
||||
Args:
|
||||
profile_id: Profile 主键。
|
||||
|
||||
Returns:
|
||||
field_code 索引的 Schema 字段 dict。
|
||||
"""
|
||||
return profile_service._resolve_schema_fields_for_split(profile_id=profile_id)
|
||||
|
||||
|
||||
def build_matnr_split_rule_suggestion(
|
||||
*,
|
||||
path_id: str,
|
||||
data_path: str,
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
生成 MATNR 类五行样本的拆分规则建议(matcher 模型)。
|
||||
|
||||
核心逻辑: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)。
|
||||
schema_fields: Schema field_code 索引。
|
||||
|
||||
Returns:
|
||||
可预览/校验的 rule_set dict;status 必为 draft,requires_confirmation=true。
|
||||
"""
|
||||
cpn_field = schema_fields.get('customer_part_number') or {}
|
||||
pn_field = schema_fields.get('part_number') or {}
|
||||
rule_set_id = f'rs-{secrets.token_hex(8)}'
|
||||
segment_cpn = new_segment_id()
|
||||
segment_mpn = new_segment_id()
|
||||
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_data_path=str(data_path),
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id=new_rule_id('position1'),
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=segment_cpn,
|
||||
segment_code='customer_material_candidate',
|
||||
display_name='客户料号候选',
|
||||
handling='mapped',
|
||||
target_field_id=str(cpn_field.get('field_id') or 'f-cpn-placeholder'),
|
||||
target_field_code='customer_part_number',
|
||||
),
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id=new_rule_id('mpn_prefix'),
|
||||
matcher=XfaSplitMatcher(
|
||||
type='prefix',
|
||||
value='MPN',
|
||||
separators=[':', ':'],
|
||||
case_sensitive=False,
|
||||
),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=segment_mpn,
|
||||
segment_code='mpn_candidate',
|
||||
display_name='MPN 料号',
|
||||
handling='mapped',
|
||||
target_field_id=str(pn_field.get('field_id') or 'f-pn-placeholder'),
|
||||
target_field_code='part_number',
|
||||
),
|
||||
),
|
||||
],
|
||||
unmatched_line_policy='evidence_only',
|
||||
duplicate_match_policy='needs_review',
|
||||
same_field_multiple_segment_policy='needs_review',
|
||||
source='system_suggestion',
|
||||
status='draft',
|
||||
requires_confirmation=True,
|
||||
)
|
||||
dumped = rule_set.model_dump(mode='json')
|
||||
dumped['source_data_path'] = str(data_path)
|
||||
dumped['suggestion_status'] = 'suggested'
|
||||
assert dumped['status'] == 'draft'
|
||||
assert dumped['status'] != 'confirmed'
|
||||
return dumped
|
||||
|
||||
|
||||
def suggest_xfa_split_rules(
|
||||
profile_id: int,
|
||||
*,
|
||||
document_id: int,
|
||||
path_id: str | None = None,
|
||||
actor_id: int | None,
|
||||
write_audit: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为 MATNR 类字段生成拆分规则建议(不写 Draft、不 commit)。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
document_id: 绑定样本 document ID。
|
||||
path_id: 可选显式源 path_id;省略时自动定位 MATNR。
|
||||
actor_id: 管理员 ID。
|
||||
write_audit: 为 True 时写只读建议审计(默认 False,零写库)。
|
||||
|
||||
Returns:
|
||||
含 rule_set、suggestion_checksum、path_id 的 DTO;rule_set.status=draft。
|
||||
|
||||
Raises:
|
||||
ValidationError: 非 XFA 草稿或无法定位源路径。
|
||||
"""
|
||||
if actor_id is None:
|
||||
raise ValidationError(
|
||||
'actor_id is required for split rule suggestion',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
details={'reason': 'actor_required'},
|
||||
)
|
||||
profile = _profile(profile_id)
|
||||
definition = _require_xfa_draft(profile)
|
||||
profile_service._bound_sample_document(int(profile_id), int(document_id))
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
path_context = profile_service.resolve_xfa_path_context(document)
|
||||
resolved_path_id, data_path = _resolve_matnr_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(
|
||||
path_id=resolved_path_id,
|
||||
data_path=data_path,
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
suggestion_checksum = hashlib.sha256(
|
||||
split_rule_content_fingerprint(rule_set).encode('utf-8'),
|
||||
).hexdigest()
|
||||
if write_audit:
|
||||
profile_service._audit(
|
||||
profile_id=int(profile.id),
|
||||
document_id=int(document_id),
|
||||
event_type='xfa_split_rule_suggested',
|
||||
actor_id=actor_id,
|
||||
detail={
|
||||
'path_id': resolved_path_id,
|
||||
'rule_set_id': rule_set.get('rule_set_id'),
|
||||
'suggestion_checksum': suggestion_checksum,
|
||||
'status': rule_set.get('status'),
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return sanitize_xfa_dto({
|
||||
'profile_id': int(profile.id),
|
||||
'document_id': int(document_id),
|
||||
'path_id': resolved_path_id,
|
||||
'suggestion_checksum': suggestion_checksum,
|
||||
'suggestion_status': 'suggested',
|
||||
'rule_set': rule_set,
|
||||
})
|
||||
|
||||
|
||||
def suggest_xfa_visual_bindings_readonly(
|
||||
profile_id: int,
|
||||
*,
|
||||
document_id: int,
|
||||
page_no: int,
|
||||
normalized_bbox: dict[str, Any],
|
||||
actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为页面区域生成视觉绑定候选(纯内存,不写 Draft/审计)。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
document_id: 样本 document ID。
|
||||
page_no: 页码。
|
||||
normalized_bbox: 归一化查询区域。
|
||||
actor_id: 管理员 ID。
|
||||
|
||||
Returns:
|
||||
候选与 diagnostics;候选 status 均为 suggested。
|
||||
"""
|
||||
if actor_id is None:
|
||||
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
profile = _profile(profile_id)
|
||||
_require_xfa_draft(profile)
|
||||
profile_service._bound_sample_document(int(profile_id), int(document_id))
|
||||
pdf_bytes = _sample_pdf_bytes(int(document_id))
|
||||
outcome = analyze_xfa_pdf(pdf_bytes)
|
||||
if outcome.dataset_analysis is None:
|
||||
raise ValidationError(
|
||||
'XFA dataset analysis is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
bbox = {
|
||||
'x0': float(normalized_bbox.get('x0') or 0),
|
||||
'y0': float(normalized_bbox.get('y0') or 0),
|
||||
'x1': float(normalized_bbox.get('x1') or 0),
|
||||
'y1': float(normalized_bbox.get('y1') or 0),
|
||||
}
|
||||
result = suggest_visual_binding_candidates(
|
||||
page_no=int(page_no),
|
||||
normalized_bbox=bbox,
|
||||
dataset_analysis=outcome.dataset_analysis,
|
||||
pdf_bytes=pdf_bytes,
|
||||
)
|
||||
for candidate in result.get('candidates') or []:
|
||||
if isinstance(candidate, dict):
|
||||
candidate['status'] = 'suggested'
|
||||
return {
|
||||
'profile_id': int(profile.id),
|
||||
'document_id': int(document_id),
|
||||
**result,
|
||||
}
|
||||
|
||||
|
||||
def suggest_xfa_unified_mapping(
|
||||
profile_id: int,
|
||||
*,
|
||||
document_id: int,
|
||||
page_no: int,
|
||||
normalized_bbox: dict[str, Any],
|
||||
actor_id: int | None,
|
||||
path_id: str | None = None,
|
||||
include_visual: bool = True,
|
||||
include_split: bool = True,
|
||||
write_audit: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
统一入口:返回视觉建议 + 拆分规则建议(不写 Draft)。
|
||||
|
||||
核心逻辑:分别调用只读视觉候选与 MATNR 拆分建议;默认零写库。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
document_id: 样本 document ID。
|
||||
page_no: 页码(视觉建议)。
|
||||
normalized_bbox: 查询区域(视觉建议)。
|
||||
actor_id: 管理员 ID。
|
||||
path_id: 可选拆分源 path_id。
|
||||
include_visual: 是否包含视觉候选。
|
||||
include_split: 是否包含拆分规则建议。
|
||||
write_audit: 是否写只读审计(默认 False)。
|
||||
|
||||
Returns:
|
||||
visual_suggestion、split_rule_suggestion 与 suggestion_status=suggested。
|
||||
"""
|
||||
if actor_id is None:
|
||||
raise ValidationError(
|
||||
'actor_id is required for unified mapping suggestion',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
details={'reason': 'actor_required'},
|
||||
)
|
||||
visual_payload: dict[str, Any] | None = None
|
||||
split_payload: dict[str, Any] | None = None
|
||||
if include_visual:
|
||||
visual_payload = suggest_xfa_visual_bindings_readonly(
|
||||
profile_id,
|
||||
document_id=int(document_id),
|
||||
page_no=int(page_no),
|
||||
normalized_bbox=normalized_bbox,
|
||||
actor_id=actor_id,
|
||||
)
|
||||
if include_split:
|
||||
split_payload = suggest_xfa_split_rules(
|
||||
profile_id,
|
||||
document_id=int(document_id),
|
||||
path_id=path_id,
|
||||
actor_id=actor_id,
|
||||
write_audit=write_audit,
|
||||
)
|
||||
summary = {
|
||||
'kind': 'xfa_unified_mapping_suggestion',
|
||||
'algorithm_version': 'xfa-unified-suggest-v1',
|
||||
'include_visual': bool(include_visual),
|
||||
'include_split': bool(include_split),
|
||||
'visual_candidate_count': len((visual_payload or {}).get('candidates') or []),
|
||||
'split_rule_set_id': (split_payload or {}).get('rule_set', {}).get('rule_set_id'),
|
||||
}
|
||||
identity = suggestion_identity(summary)
|
||||
return sanitize_xfa_dto({
|
||||
'profile_id': int(profile_id),
|
||||
'document_id': int(document_id),
|
||||
'suggestion_status': 'suggested',
|
||||
'suggestion_id': identity['suggestion_id'],
|
||||
'suggestion_checksum': identity['suggestion_checksum'],
|
||||
'visual_suggestion': visual_payload,
|
||||
'split_rule_suggestion': split_payload,
|
||||
})
|
||||
|
||||
|
||||
def decide(
|
||||
profile_id: int, *, data: dict[str, Any], actor_id: int | None,
|
||||
browser_session_id: str | None, lease_token: str | None, operation_id: str,
|
||||
|
||||
@@ -37,7 +37,6 @@ from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_PARSER_IDENTITY,
|
||||
XFA_STRUCTURE_SIGNATURE_ID,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import mask_value_for_dto
|
||||
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
@@ -315,9 +314,9 @@ def _build_xfa_field_preview_rows(
|
||||
validation: Any,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
组装验证页可用的脱敏字段级结果(不含明文路径 / 完整 XML)。
|
||||
组装验证页可用的完整字段级结果(不含明文路径 / 完整 XML)。
|
||||
|
||||
核心逻辑:Header/Line 返回 masked_raw + normalized;cross_checks 透传摘要状态。
|
||||
核心逻辑:Header/Line 返回 raw + normalized;cross_checks 透传摘要状态。
|
||||
"""
|
||||
header_fields: list[dict[str, Any]] = []
|
||||
for item in getattr(extraction, 'header_fields', None) or []:
|
||||
@@ -327,7 +326,7 @@ def _build_xfa_field_preview_rows(
|
||||
header_fields.append({
|
||||
'field_id': item.field_id,
|
||||
'field_code': item.field_code,
|
||||
'masked_raw_value': mask_value_for_dto(item.raw_value) if item.raw_value not in (None, '') else None,
|
||||
'raw_value': str(item.raw_value) if item.raw_value not in (None, '') else None,
|
||||
'normalized_value': _serialize_normalized_for_dto(item.normalized_value),
|
||||
'status': status,
|
||||
'issues': list(item.issues or []),
|
||||
@@ -355,7 +354,7 @@ def _build_xfa_field_preview_rows(
|
||||
fields_out.append({
|
||||
'field_id': str(field.get('field_id') or ''),
|
||||
'field_code': code,
|
||||
'masked_raw_value': mask_value_for_dto(raw) if raw not in (None, '') else None,
|
||||
'raw_value': str(raw) if raw not in (None, '') else None,
|
||||
'normalized_value': _serialize_normalized_for_dto(value),
|
||||
'status': status,
|
||||
'issues': issues,
|
||||
@@ -379,7 +378,7 @@ def _extract_xfa_current_sample(
|
||||
对绑定样本按草稿 XFA definition 试提取;仅返回计数与对账摘要。
|
||||
|
||||
核心逻辑:读 PDF → analyze → extract_xfa_profile → validate_xfa_extraction;
|
||||
覆盖 required / auto_create_key 映射与值;明文路径与原值不落库。
|
||||
当前模板只验证已配置提取与确定性对账;订单 Schema 必填由多来源合并后的业务 Gate 判断。
|
||||
"""
|
||||
from app.models import FileAsset
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
@@ -440,42 +439,14 @@ def _extract_xfa_current_sample(
|
||||
dataset_analysis=outcome.dataset_analysis,
|
||||
extraction=extraction,
|
||||
pdf_bytes=pdf_bytes,
|
||||
schema_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')
|
||||
},
|
||||
)
|
||||
|
||||
required_ids, auto_key_ids = _schema_gate_field_ids(profile)
|
||||
mapped_header_ids = {
|
||||
str(item.get('field_id') or '')
|
||||
for item in (definition.get('header_mappings') or [])
|
||||
if isinstance(item, dict) and item.get('field_id')
|
||||
}
|
||||
line_mapping = definition.get('line_mapping') if isinstance(definition.get('line_mapping'), dict) else {}
|
||||
mapped_line_ids = {
|
||||
str(item.get('field_id') or '')
|
||||
for item in (line_mapping.get('fields') or [])
|
||||
if isinstance(item, dict) and item.get('field_id')
|
||||
}
|
||||
mapped_ids = mapped_header_ids | mapped_line_ids
|
||||
header_required_missing = len((required_ids & mapped_ids) - {
|
||||
f.field_id for f in extraction.header_fields if f.normalized_value not in (None, '')
|
||||
} - {
|
||||
str(field.get('field_id') or '')
|
||||
for row in extraction.rows
|
||||
for field in (row.get('fields') or [])
|
||||
if isinstance(field, dict) and field.get('value') not in (None, '')
|
||||
})
|
||||
# 未映射的 required / auto_create_key 也计为缺失。
|
||||
unmapped_required = len(required_ids - mapped_ids)
|
||||
unmapped_auto = len(auto_key_ids - mapped_ids)
|
||||
readable_ids = {
|
||||
f.field_id for f in extraction.header_fields if f.normalized_value not in (None, '')
|
||||
} | {
|
||||
str(field.get('field_id') or '')
|
||||
for row in extraction.rows
|
||||
for field in (row.get('fields') or [])
|
||||
if isinstance(field, dict) and field.get('value') not in (None, '') and field.get('field_id')
|
||||
}
|
||||
auto_create_missing = len((auto_key_ids & mapped_ids) - readable_ids) + unmapped_auto
|
||||
header_required_missing_count = header_required_missing + unmapped_required
|
||||
|
||||
line_field_count = len(line_mapping.get('fields') or [])
|
||||
line_value_count = sum(
|
||||
@@ -493,8 +464,8 @@ def _extract_xfa_current_sample(
|
||||
line_value_count=line_value_count,
|
||||
header_field_count=header_field_count,
|
||||
header_value_count=header_value_count,
|
||||
header_required_missing_count=header_required_missing_count,
|
||||
auto_create_key_missing_count=auto_create_missing,
|
||||
header_required_missing_count=0,
|
||||
auto_create_key_missing_count=0,
|
||||
cross_check_failures=cross_failures,
|
||||
sample_role=sample.sample_role,
|
||||
template_mode='xfa_dataset',
|
||||
@@ -502,7 +473,12 @@ def _extract_xfa_current_sample(
|
||||
summary['cross_checks'] = validation.cross_check_summary
|
||||
summary['authoritative_collection_present'] = 'xfa_authoritative_collection_missing' not in cross_failures
|
||||
summary['line_row_count'] = len(extraction.rows)
|
||||
# 字段级脱敏预览:供验证页核验业务值,不含明文路径。
|
||||
# 阶段 5:统一验证指标写入 summary,供发布门禁阈值消费。
|
||||
cross_summary = validation.cross_check_summary if isinstance(validation.cross_check_summary, dict) else {}
|
||||
summary['visual_coverage_rate'] = float(cross_summary.get('visual_coverage_rate') or 0.0)
|
||||
summary['mirror_consistency_rate'] = float(cross_summary.get('mirror_consistency_rate') or 0.0)
|
||||
summary['evidence_retention_rate'] = float(cross_summary.get('evidence_retention_rate') or 0.0)
|
||||
# 字段级完整预览:供当前模板管理员直接核验,不含明文路径或完整 XML。
|
||||
field_preview = _build_xfa_field_preview_rows(extraction=extraction, validation=validation)
|
||||
summary['header_fields'] = field_preview['header_fields']
|
||||
summary['lines'] = field_preview['lines']
|
||||
|
||||
@@ -19,6 +19,9 @@ from app.models import (
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice.order_profile_unified_migration import (
|
||||
summarize_unified_migration_status,
|
||||
)
|
||||
|
||||
|
||||
def _profile_event_time(profile: ShippingOrderDocumentProfile) -> datetime:
|
||||
@@ -179,6 +182,12 @@ def list_profile_families() -> list[dict[str, Any]]:
|
||||
default = published or draft or retired or versions[0]
|
||||
latest = versions[0]
|
||||
updated = max((_profile_event_time(item) for item in versions), default=latest.created_at)
|
||||
migration_target = published or draft or default
|
||||
migration_definition = dict(migration_target.definition_json or {})
|
||||
migration_summary = summarize_unified_migration_status(
|
||||
migration_definition,
|
||||
template_mode=str(migration_target.template_mode or migration_definition.get('template_mode') or 'coordinate'),
|
||||
)
|
||||
result.append({
|
||||
'profile_code': profile_code,
|
||||
'display_name': default.display_name,
|
||||
@@ -196,6 +205,11 @@ def list_profile_families() -> list[dict[str, Any]]:
|
||||
'default_version': default.version,
|
||||
'version_count': len(versions),
|
||||
'updated_at': updated.isoformat(),
|
||||
'template_mode': migration_summary.get('template_mode'),
|
||||
'unified_binding_status': migration_summary.get('unified_binding_status'),
|
||||
'unified_binding_count': migration_summary.get('binding_count'),
|
||||
'unified_pending_visual_count': migration_summary.get('pending_visual_count'),
|
||||
'unified_needs_migration': migration_summary.get('needs_migration'),
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
+388
@@ -0,0 +1,388 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_visual_binding_service.py
|
||||
|
||||
用途:XFA 统一视觉绑定的建议、确认、驳回编排(Lease、definition 更新与审计)。
|
||||
依赖:xfa_visual_binding、xfa_analysis、order_document_profile_service、lease_service、
|
||||
order_document_profile_audit_service(双写 Profile + 平台快照)。
|
||||
逻辑:admin API 调用本模块;建议只读不写 Draft;确认/驳回需租约并写 before/after 审计及加密 full 快照。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingOrderDocument, ShippingOrderDocumentProfile
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice.document_layout.xfa_analysis import analyze_xfa_pdf
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
OrderXfaDatasetProfile,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_visual_binding import (
|
||||
suggest_visual_binding_candidates,
|
||||
visual_binding_audit_snapshot,
|
||||
)
|
||||
from app.services.shipping_notice.order_document_profile_audit_service import (
|
||||
build_profile_audit_context,
|
||||
record_visual_binding_audit,
|
||||
)
|
||||
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取 Profile;不存在时统一 not-found。"""
|
||||
row = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if row is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
return row
|
||||
|
||||
|
||||
def _require_xfa_draft(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
"""校验 XFA 草稿 definition 并返回可变副本。"""
|
||||
if str(profile.status or '') != 'draft':
|
||||
raise ValidationError(
|
||||
'Visual binding changes require a draft profile',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
mode = str(profile.template_mode or (profile.definition_json or {}).get('template_mode') or '')
|
||||
if mode != 'xfa_dataset':
|
||||
raise ValidationError(
|
||||
'Visual binding is only available for XFA profiles',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
return dict(profile.definition_json or {})
|
||||
|
||||
|
||||
def _sample_pdf_bytes(document_id: int) -> bytes:
|
||||
"""读取样本文档 PDF 字节。"""
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
if document is None or not document.asset_id:
|
||||
raise ValidationError(
|
||||
'Profile sample document is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
from app.models import FileAsset
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
|
||||
asset = db.session.get(FileAsset, int(document.asset_id))
|
||||
if asset is None:
|
||||
raise ValidationError(
|
||||
'Profile sample file is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
return read_asset_bytes(asset)
|
||||
|
||||
|
||||
def _resolve_path_from_definition(definition: dict[str, Any], path_id: str) -> str | None:
|
||||
"""从 header/line mappings 或 bindings 反查 data_path。"""
|
||||
for item in definition.get('header_mappings') or []:
|
||||
if isinstance(item, dict) and str(item.get('path_id') or '') == path_id:
|
||||
return str(item.get('data_path') or '').strip() or None
|
||||
line_mapping = definition.get('line_mapping') if isinstance(definition.get('line_mapping'), dict) else {}
|
||||
for item in line_mapping.get('fields') or []:
|
||||
if isinstance(item, dict) and str(item.get('path_id') or '') == path_id:
|
||||
return str(item.get('data_path') or '').strip() or None
|
||||
for item in definition.get('bindings') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
value = item.get('value_binding') if isinstance(item.get('value_binding'), dict) else {}
|
||||
if str(value.get('path_id') or '') == path_id:
|
||||
return str(value.get('data_path') or '').strip() or None
|
||||
return None
|
||||
|
||||
|
||||
def suggest_xfa_visual_bindings(
|
||||
profile_id: int,
|
||||
*,
|
||||
document_id: int,
|
||||
page_no: int,
|
||||
normalized_bbox: dict[str, Any],
|
||||
actor_id: int | None,
|
||||
request_id: str | None = None,
|
||||
write_audit: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为页面区域生成 XFA 视觉绑定候选(默认不写 Draft、不 commit)。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
document_id: 绑定样本 document ID。
|
||||
page_no: 页码。
|
||||
normalized_bbox: 归一化查询区域。
|
||||
actor_id: 管理员 ID。
|
||||
request_id: HTTP request_id。
|
||||
write_audit: 为 True 时写只读建议审计并 commit(默认 False)。
|
||||
|
||||
Returns:
|
||||
候选列表与 diagnostics;所有候选 status=suggested。
|
||||
"""
|
||||
from app.services.shipping_notice import order_document_profile_suggestion_service as suggestion_service
|
||||
|
||||
result = suggestion_service.suggest_xfa_visual_bindings_readonly(
|
||||
profile_id,
|
||||
document_id=int(document_id),
|
||||
page_no=int(page_no),
|
||||
normalized_bbox=normalized_bbox,
|
||||
actor_id=actor_id,
|
||||
)
|
||||
if write_audit:
|
||||
profile = _profile(profile_id)
|
||||
record_visual_binding_audit(
|
||||
profile_id=int(profile_id),
|
||||
document_id=int(document_id),
|
||||
event_type='xfa_visual_binding_suggested',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
before=None,
|
||||
after={'page_no': int(page_no), 'candidate_count': len(result.get('candidates') or [])},
|
||||
detail={
|
||||
'page_no': int(page_no),
|
||||
'normalized_bbox': normalized_bbox,
|
||||
'diagnostics': result.get('diagnostics'),
|
||||
'candidate_count': len(result.get('candidates') or []),
|
||||
'action': 'suggest',
|
||||
},
|
||||
profile_context=build_profile_audit_context(profile),
|
||||
)
|
||||
db.session.commit()
|
||||
return result
|
||||
|
||||
|
||||
def _find_binding(definition: dict[str, Any], binding_id: str) -> tuple[int, dict[str, Any]]:
|
||||
"""在 definition.bindings 中定位 binding 索引。"""
|
||||
bindings = definition.get('bindings') if isinstance(definition.get('bindings'), list) else []
|
||||
for index, item in enumerate(bindings):
|
||||
if isinstance(item, dict) and str(item.get('binding_id') or '') == str(binding_id):
|
||||
return index, item
|
||||
raise NotFoundError(
|
||||
'Visual binding not found',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_BINDING_NOT_FOUND',
|
||||
)
|
||||
|
||||
|
||||
def confirm_xfa_visual_binding(
|
||||
profile_id: int,
|
||||
binding_id: str,
|
||||
*,
|
||||
visual_binding: dict[str, Any],
|
||||
path_id: str | None,
|
||||
actor_id: int | None,
|
||||
browser_session_id: str | None,
|
||||
lease_token: str | None,
|
||||
operation_id: str | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
管理员确认视觉绑定;写 definition 与 before/after 审计。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
binding_id: 目标 binding_id。
|
||||
visual_binding: 确认的 visual_binding(须含 page_no、normalized_bbox)。
|
||||
path_id: 可选 value path_id;省略时保留既有 value_binding。
|
||||
actor_id: 管理员 ID。
|
||||
browser_session_id: 浏览器会话。
|
||||
lease_token: 编辑租约令牌。
|
||||
operation_id: 幂等操作 ID。
|
||||
request_id: HTTP request_id。
|
||||
|
||||
Returns:
|
||||
更新后的 binding 摘要。
|
||||
"""
|
||||
if actor_id is None:
|
||||
raise ConflictError('Edit lease is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED')
|
||||
profile = _profile(profile_id)
|
||||
lease_service.require_active_lease(
|
||||
profile.id,
|
||||
actor_id=actor_id,
|
||||
browser_session_id=browser_session_id,
|
||||
lease_token=lease_token,
|
||||
)
|
||||
definition = _require_xfa_draft(profile)
|
||||
index, binding = _find_binding(definition, binding_id)
|
||||
before = visual_binding_audit_snapshot(binding)
|
||||
|
||||
next_visual = dict(visual_binding or {})
|
||||
next_visual['status'] = 'confirmed'
|
||||
next_visual.setdefault('source', 'manual_draw')
|
||||
next_visual.setdefault('confidence', 1.0)
|
||||
|
||||
updated = deepcopy(binding)
|
||||
updated['visual_binding'] = next_visual
|
||||
if path_id:
|
||||
data_path = _resolve_path_from_definition(definition, str(path_id))
|
||||
if not data_path:
|
||||
raise ValidationError(
|
||||
'path_id is unknown for this profile',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
value = updated.get('value_binding') if isinstance(updated.get('value_binding'), dict) else {}
|
||||
value.update({'type': 'xfa_dataset', 'path_id': str(path_id), 'data_path': data_path})
|
||||
updated['value_binding'] = value
|
||||
|
||||
bindings = list(definition.get('bindings') or [])
|
||||
bindings[index] = updated
|
||||
definition['bindings'] = bindings
|
||||
OrderXfaDatasetProfile.model_validate(definition)
|
||||
|
||||
profile.definition_json = definition
|
||||
db.session.flush()
|
||||
after = visual_binding_audit_snapshot(updated)
|
||||
record_visual_binding_audit(
|
||||
profile_id=int(profile.id),
|
||||
document_id=None,
|
||||
event_type='xfa_visual_binding_confirmed',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
before=before,
|
||||
after=after,
|
||||
detail={'binding_id': binding_id, 'action': 'confirm'},
|
||||
raw_binding_before=binding,
|
||||
raw_binding_after=updated,
|
||||
profile_context=build_profile_audit_context(profile),
|
||||
)
|
||||
db.session.commit()
|
||||
return {'binding_id': binding_id, 'visual_binding': next_visual, 'status': 'confirmed'}
|
||||
|
||||
|
||||
def reject_xfa_visual_binding(
|
||||
profile_id: int,
|
||||
binding_id: str,
|
||||
*,
|
||||
reason_code: str | None,
|
||||
actor_id: int | None,
|
||||
browser_session_id: str | None,
|
||||
lease_token: str | None,
|
||||
operation_id: str | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
管理员驳回视觉绑定建议;写 before/after 审计。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
binding_id: 目标 binding_id。
|
||||
reason_code: 可选驳回原因码。
|
||||
actor_id: 管理员 ID。
|
||||
browser_session_id: 浏览器会话。
|
||||
lease_token: 编辑租约令牌。
|
||||
operation_id: 幂等操作 ID。
|
||||
request_id: HTTP request_id。
|
||||
|
||||
Returns:
|
||||
驳回后的 binding 摘要。
|
||||
"""
|
||||
if actor_id is None:
|
||||
raise ConflictError('Edit lease is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED')
|
||||
profile = _profile(profile_id)
|
||||
lease_service.require_active_lease(
|
||||
profile.id,
|
||||
actor_id=actor_id,
|
||||
browser_session_id=browser_session_id,
|
||||
lease_token=lease_token,
|
||||
)
|
||||
definition = _require_xfa_draft(profile)
|
||||
index, binding = _find_binding(definition, binding_id)
|
||||
before = visual_binding_audit_snapshot(binding)
|
||||
|
||||
updated = deepcopy(binding)
|
||||
visual = updated.get('visual_binding') if isinstance(updated.get('visual_binding'), dict) else {}
|
||||
visual['status'] = 'rejected'
|
||||
visual.setdefault('source', 'suggested')
|
||||
updated['visual_binding'] = visual
|
||||
|
||||
bindings = list(definition.get('bindings') or [])
|
||||
bindings[index] = updated
|
||||
definition['bindings'] = bindings
|
||||
OrderXfaDatasetProfile.model_validate(definition)
|
||||
|
||||
profile.definition_json = definition
|
||||
db.session.flush()
|
||||
after = visual_binding_audit_snapshot(updated)
|
||||
record_visual_binding_audit(
|
||||
profile_id=int(profile.id),
|
||||
document_id=None,
|
||||
event_type='xfa_visual_binding_rejected',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
before=before,
|
||||
after=after,
|
||||
detail={'binding_id': binding_id, 'action': 'reject', 'reason_code': reason_code},
|
||||
raw_binding_before=binding,
|
||||
raw_binding_after=updated,
|
||||
profile_context=build_profile_audit_context(profile),
|
||||
)
|
||||
db.session.commit()
|
||||
return {'binding_id': binding_id, 'visual_binding': visual, 'status': 'rejected'}
|
||||
|
||||
|
||||
def ensure_binding_stub(
|
||||
profile_id: int,
|
||||
*,
|
||||
field_id: str,
|
||||
field_code: str,
|
||||
scope: str,
|
||||
path_id: str,
|
||||
data_path: str,
|
||||
actor_id: int | None,
|
||||
browser_session_id: str | None,
|
||||
lease_token: str | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为字段创建带 suggested 视觉状态的 binding 占位(供测试/编辑器初始化)。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
field_id: Schema field_id。
|
||||
field_code: 字段编码。
|
||||
scope: header|line。
|
||||
path_id: datasets path_id。
|
||||
data_path: datasets 路径。
|
||||
actor_id: 管理员 ID。
|
||||
browser_session_id: 浏览器会话。
|
||||
lease_token: 租约令牌。
|
||||
|
||||
Returns:
|
||||
新建 binding 摘要。
|
||||
"""
|
||||
if actor_id is None:
|
||||
raise ConflictError('Edit lease is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED')
|
||||
profile = _profile(profile_id)
|
||||
lease_service.require_active_lease(
|
||||
profile.id,
|
||||
actor_id=actor_id,
|
||||
browser_session_id=browser_session_id,
|
||||
lease_token=lease_token,
|
||||
)
|
||||
definition = _require_xfa_draft(profile)
|
||||
bindings = list(definition.get('bindings') or [])
|
||||
binding_id = f'bind-{secrets.token_hex(8)}'
|
||||
binding = {
|
||||
'binding_id': binding_id,
|
||||
'field_id': field_id,
|
||||
'field_code': field_code,
|
||||
'scope': scope,
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': path_id,
|
||||
'data_path': data_path,
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.0, 'y0': 0.0, 'x1': 0.01, 'y1': 0.01},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.0,
|
||||
},
|
||||
}
|
||||
bindings.append(binding)
|
||||
definition['bindings'] = bindings
|
||||
OrderXfaDatasetProfile.model_validate(definition)
|
||||
profile.definition_json = definition
|
||||
db.session.commit()
|
||||
return binding
|
||||
@@ -841,9 +841,18 @@ def persist_order_extraction_result(
|
||||
if candidate_intake is not None
|
||||
else None
|
||||
),
|
||||
stage='waiting_review'
|
||||
if str(getattr(run, 'status', None) or '') == 'review_required'
|
||||
else 'candidate_creating',
|
||||
stage='candidate_creating',
|
||||
)
|
||||
# [BE-06] Candidate 形成后立即按资格推进 OT stage(客户/查重/库存源/复核)。
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
sync_order_task_stage_for_candidate,
|
||||
)
|
||||
|
||||
sync_order_task_stage_for_candidate(
|
||||
candidate=candidate,
|
||||
prefer_waiting_review=(
|
||||
str(getattr(run, 'status', None) or '') == 'review_required'
|
||||
),
|
||||
)
|
||||
|
||||
auto_candidate_nos = [row.candidate_no for row in auto_candidates]
|
||||
@@ -1261,8 +1270,8 @@ def submit_order_extraction_unit_result(
|
||||
'idempotent_replay': True,
|
||||
'unit_id': int(unit.id),
|
||||
}
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
ensure_run_review_cases(run=run)
|
||||
from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit
|
||||
ensure_review_case_for_unit(run=run, unit=unit)
|
||||
return result
|
||||
|
||||
session = _runtime_session_for_run(run)
|
||||
@@ -1331,8 +1340,8 @@ def submit_order_extraction_unit_result(
|
||||
allow_same_run_consumed_continuation=is_same_run_consumed_continuation,
|
||||
)
|
||||
result['unit_id'] = int(unit.id)
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
ensure_run_review_cases(run=run)
|
||||
from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit
|
||||
ensure_review_case_for_unit(run=run, unit=unit)
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import maybe_stp_auto_create_for_run
|
||||
|
||||
result['stp_auto_create'] = maybe_stp_auto_create_for_run(run=run)
|
||||
|
||||
@@ -3,10 +3,13 @@ services/shipping_notice/order_extraction_progress.py
|
||||
|
||||
用途:记录订单抽取 Run/Unit 的确定性业务事件,作为用户态进度与管理员诊断的共同事实源。
|
||||
依赖:ShippingOrderProcessingRun/Unit/ProgressEvent ORM、统一数据库会话、progress_audit_contract、
|
||||
order_task_stage_machine(统一 processing_stage 写路径)、
|
||||
workflow_ledger_service(进度事件尽力同步 Workflow 状态,缺 Item 不阻断进度写入)。
|
||||
逻辑:调用方只能写入受控 event_code;服务负责幂等、顺序号、终态保护和最小化 Run 投影。
|
||||
投影更新时同步写入 progress_summary_json.processing_stage(15 阶早期事实)。
|
||||
Run 终态默认拒绝新事件,但允许复核/LLM 生命周期事件(发生在 review_required 之后)。
|
||||
commit=False 且处于 Savepoint 时,flush 异常回滚嵌套事务,避免污染外层业务 Session。
|
||||
summary.audit 写入 actor/request_id/前后 Run 快照(BE-06);同事务失败 fail-closed(BE-07)。
|
||||
独立 commit 失败时标记 progress_event_loss 供对账。
|
||||
阶段 0 冻结 cancellation_* 事件码与 mapping v3;写入取消事实在阶段 1 与 Worker 检查点实现。
|
||||
"""
|
||||
|
||||
@@ -193,11 +196,35 @@ def _should_update_projection(run: ShippingOrderProcessingRun, event_code: str)
|
||||
|
||||
|
||||
def _apply_run_projection(run: ShippingOrderProcessingRun, *, event_code: str, occurred_at: datetime) -> None:
|
||||
"""维持最小 Run 投影,供阶段一验证恢复性与轮询版本控制。"""
|
||||
"""
|
||||
维持最小 Run 投影,并写入统一 processing_stage 事实。
|
||||
|
||||
核心逻辑:更新 current_stage_code / 完成集 / progress_version;
|
||||
同步将事件映射为 15 阶 processing_stage 写入 progress_summary_json,
|
||||
供投影优先读取(Candidate 前早期阶段写路径)。
|
||||
"""
|
||||
if run.status in TERMINAL_RUN_STATUSES:
|
||||
return
|
||||
if _should_update_projection(run, event_code):
|
||||
run.current_stage_code = event_code
|
||||
# [STEP] Candidate 前:把进度事件落成统一 15 阶事实,避免投影纯启发式。
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
resolve_processing_stage_for_progress_event,
|
||||
source_type_hint_from_run,
|
||||
write_run_unified_processing_stage,
|
||||
)
|
||||
|
||||
source_type = source_type_hint_from_run(run)
|
||||
unified_stage = resolve_processing_stage_for_progress_event(
|
||||
event_code,
|
||||
source_type=source_type,
|
||||
)
|
||||
if unified_stage:
|
||||
write_run_unified_processing_stage(
|
||||
run,
|
||||
unified_stage,
|
||||
source_type=source_type,
|
||||
)
|
||||
run.active_stage_codes_json = [] if event_code in {
|
||||
'candidate_ready', 'review_required', 'technical_failed', 'budget_stopped', 'run_completed',
|
||||
} else [event_code]
|
||||
@@ -338,6 +365,37 @@ def record_order_extraction_progress_event(
|
||||
unit_id = int(event['unit_id']) if event.get('unit_id') is not None else None
|
||||
document_id = int(event['document_id']) if event.get('document_id') is not None else None
|
||||
attempt_count = int(event['attempt_count']) if event.get('attempt_count') is not None else None
|
||||
# [BE-06] 写入前后 Run 进度快照 + request/operation 关联,对齐 OT 进度审计契约。
|
||||
before_snapshot = {
|
||||
'status': str(getattr(run, 'status', None) or '') or None,
|
||||
'current_stage_code': str(getattr(run, 'current_stage_code', None) or '') or None,
|
||||
'progress_version': int(getattr(run, 'progress_version', None) or 0),
|
||||
'processing_stage': (
|
||||
(run.progress_summary_json or {}).get('processing_stage')
|
||||
if isinstance(run.progress_summary_json, dict)
|
||||
else None
|
||||
),
|
||||
}
|
||||
from flask import g, has_request_context
|
||||
|
||||
audit_request_id = event.get('request_id')
|
||||
audit_operation_id = event.get('operation_id')
|
||||
audit_actor_type = event.get('actor_type') or 'system'
|
||||
audit_actor_id = event.get('actor_id')
|
||||
if has_request_context():
|
||||
if not audit_request_id:
|
||||
audit_request_id = getattr(g, 'request_id', None)
|
||||
if not audit_actor_id and getattr(g, 'user_id', None) is not None:
|
||||
audit_actor_type = 'user'
|
||||
audit_actor_id = str(g.user_id)
|
||||
enriched_summary = dict(summary or {})
|
||||
enriched_summary['audit'] = {
|
||||
'actor_type': str(audit_actor_type or 'system'),
|
||||
'actor_id': str(audit_actor_id) if audit_actor_id is not None else None,
|
||||
'request_id': str(audit_request_id or '') or None,
|
||||
'operation_id': str(audit_operation_id or '') or None,
|
||||
'before': before_snapshot,
|
||||
}
|
||||
key = _event_key(
|
||||
run_id=int(run.id),
|
||||
unit_id=unit_id,
|
||||
@@ -347,6 +405,7 @@ def record_order_extraction_progress_event(
|
||||
visibility=visibility,
|
||||
reason_code=reason_code,
|
||||
attempt_count=attempt_count,
|
||||
# [BE-06] 幂等键仍基于业务 summary,排除 audit 快照避免同事件重复写入。
|
||||
summary=summary,
|
||||
)
|
||||
if ShippingOrderExtractionProgressEvent.query.filter_by(idempotency_key=key).first() is not None:
|
||||
@@ -364,13 +423,29 @@ def record_order_extraction_progress_event(
|
||||
occurred_at=occurred_at,
|
||||
reason_code=reason_code,
|
||||
received_at=datetime.utcnow(),
|
||||
summary_json=summary,
|
||||
summary_json=_safe_summary(enriched_summary),
|
||||
idempotency_key=key,
|
||||
mapping_version=MAPPING_VERSION,
|
||||
expires_at=occurred_at + timedelta(days=EVENT_RETENTION_DAYS),
|
||||
)
|
||||
db.session.add(row)
|
||||
_apply_run_projection(run, event_code=event_code, occurred_at=occurred_at)
|
||||
# [BE-06] 写后快照补进 summary.audit.after(flush 后 progress_version 已递增)。
|
||||
after_snapshot = {
|
||||
'status': str(getattr(run, 'status', None) or '') or None,
|
||||
'current_stage_code': str(getattr(run, 'current_stage_code', None) or '') or None,
|
||||
'progress_version': int(getattr(run, 'progress_version', None) or 0),
|
||||
'processing_stage': (
|
||||
(run.progress_summary_json or {}).get('processing_stage')
|
||||
if isinstance(run.progress_summary_json, dict)
|
||||
else None
|
||||
),
|
||||
}
|
||||
final_summary = dict(row.summary_json or {})
|
||||
audit_block = dict(final_summary.get('audit') or {})
|
||||
audit_block['after'] = after_snapshot
|
||||
final_summary['audit'] = audit_block
|
||||
row.summary_json = _safe_summary(final_summary)
|
||||
# [STEP] 进度事实尽力驱动 WorkflowItem;Item 缺失不回滚进度写入。
|
||||
_sync_workflow_from_progress_event(
|
||||
run=run,
|
||||
@@ -383,9 +458,8 @@ def record_order_extraction_progress_event(
|
||||
db.session.flush()
|
||||
return True
|
||||
except Exception as exc:
|
||||
# [STEP] commit 路径整事务回滚;commit=False 时优先回滚 Savepoint。
|
||||
# Flask-SQLAlchemy 的 scoped_session 可能未代理 in_nested_transaction,
|
||||
# 故使用 get_nested_transaction;无法探测时向上抛出,由旁路桥接 rollback。
|
||||
# [BE-07] 同事务(commit=False)写入失败必须向上抛,禁止主业务继续而进度静默丢失。
|
||||
# 独立 commit=True 路径仍回滚本函数事务并标记 Run 供对账告警。
|
||||
if commit:
|
||||
db.session.rollback()
|
||||
_LOGGER.exception(
|
||||
@@ -393,6 +467,27 @@ def record_order_extraction_progress_event(
|
||||
normalized_no,
|
||||
event_code,
|
||||
)
|
||||
try:
|
||||
run_for_flag = ShippingOrderProcessingRun.query.filter_by(run_no=normalized_no).first()
|
||||
if run_for_flag is not None:
|
||||
summary_payload = (
|
||||
dict(run_for_flag.progress_summary_json)
|
||||
if isinstance(run_for_flag.progress_summary_json, dict)
|
||||
else {}
|
||||
)
|
||||
summary_payload['progress_event_loss'] = {
|
||||
'event_code': event_code,
|
||||
'at': datetime.utcnow().isoformat(timespec='seconds') + 'Z',
|
||||
}
|
||||
run_for_flag.progress_summary_json = summary_payload
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
_LOGGER.exception(
|
||||
'failed to flag progress_event_loss run_no=%s event_code=%s',
|
||||
normalized_no,
|
||||
event_code,
|
||||
)
|
||||
return False
|
||||
nested_tx = None
|
||||
get_nested = getattr(db.session, 'get_nested_transaction', None)
|
||||
@@ -406,14 +501,8 @@ def record_order_extraction_progress_event(
|
||||
nested_tx.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
_LOGGER.exception(
|
||||
'order extraction progress recording failed run_no=%s event_code=%s',
|
||||
normalized_no,
|
||||
event_code,
|
||||
)
|
||||
return False
|
||||
_LOGGER.exception(
|
||||
'order extraction progress recording failed run_no=%s event_code=%s',
|
||||
'order extraction progress recording failed run_no=%s event_code=%s (fail-closed)',
|
||||
normalized_no,
|
||||
event_code,
|
||||
)
|
||||
|
||||
@@ -1435,6 +1435,17 @@ def _route_xfa_deterministic_unit(
|
||||
pdf_bytes=pdf_bytes,
|
||||
)
|
||||
decision['xfa_cross_checks'] = validation.cross_check_summary
|
||||
from app.services.shipping_notice.document_layout.xfa_validation import build_xfa_validation_metrics
|
||||
definition_payload = (
|
||||
selected.get('definition') if isinstance(selected.get('definition'), dict) else {}
|
||||
)
|
||||
unified_metrics = build_xfa_validation_metrics(
|
||||
definition=definition_payload,
|
||||
extraction=extraction,
|
||||
cross_check_summary=validation.cross_check_summary,
|
||||
)
|
||||
unified_metrics['profile_checksum'] = str(selected.get('checksum') or '')
|
||||
decision['xfa_unified_metrics'] = unified_metrics
|
||||
if not validation.passed:
|
||||
decision['fallback_reason_codes'] = list(validation.reason_codes or ['xfa_business_validation_failed'])
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
|
||||
@@ -0,0 +1,933 @@
|
||||
"""
|
||||
services/shipping_notice/order_profile_unified_migration.py
|
||||
|
||||
用途:将现有订单文档模板一次性迁移为统一 bindings[](value_binding + visual_binding)。
|
||||
依赖:xfa_contract、xfa_acroform、order_document_profile_service、SQLAlchemy ORM。
|
||||
逻辑:CLI / Admin API 调用本模块;Dry Run 只产出报告与审计;Execute 生成新 Draft Revision
|
||||
并写入 before/after 审计。报告存审计 detail,不新增表字段(无 Alembic)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XfaUnifiedFieldBinding,
|
||||
validate_controlled_data_path,
|
||||
)
|
||||
|
||||
UNIFIED_MIGRATION_DRY_RUN_EVENT = 'order_profile_unified_migration_dry_run'
|
||||
UNIFIED_MIGRATION_EXECUTED_EVENT = 'order_profile_unified_migration_executed'
|
||||
UNIFIED_MIGRATION_AUDIT_EVENTS = frozenset({
|
||||
UNIFIED_MIGRATION_DRY_RUN_EVENT,
|
||||
UNIFIED_MIGRATION_EXECUTED_EVENT,
|
||||
})
|
||||
|
||||
|
||||
def _stable_binding_id(*parts: str) -> str:
|
||||
"""
|
||||
由稳定业务键生成 binding_id(≥8 字符)。
|
||||
|
||||
Args:
|
||||
parts: 参与哈希的业务片段(scope、mapping_id、field_id 等)。
|
||||
|
||||
Returns:
|
||||
形如 bind-<hex> 的稳定 ID。
|
||||
"""
|
||||
seed = '|'.join(str(item or '').strip() for item in parts)
|
||||
digest = hashlib.sha256(seed.encode('utf-8')).hexdigest()[:20]
|
||||
return f'bind-{digest}'
|
||||
|
||||
|
||||
def _region_dict(raw: Any) -> dict[str, float] | None:
|
||||
"""将相对矩形 dict 归一为 x0/y0/x1/y1;非法时返回 None。"""
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
try:
|
||||
box = {
|
||||
'x0': float(raw['x0']),
|
||||
'y0': float(raw['y0']),
|
||||
'x1': float(raw['x1']),
|
||||
'y1': float(raw['y1']),
|
||||
}
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
if box['x1'] <= box['x0'] or box['y1'] <= box['y0']:
|
||||
return None
|
||||
if any(value < 0.0 or value > 1.0 for value in box.values()):
|
||||
return None
|
||||
return box
|
||||
|
||||
|
||||
def _placeholder_bbox() -> dict[str, float]:
|
||||
"""无视觉证据时的占位框(status=suggested,不可发布)。"""
|
||||
return {'x0': 0.0, 'y0': 0.0, 'x1': 0.02, 'y1': 0.02}
|
||||
|
||||
|
||||
def _formal_field_keys_from_definition(definition: dict[str, Any]) -> set[tuple[str, str]]:
|
||||
"""
|
||||
抽取 definition 中正式 Schema 字段键集合 (scope, field_id)。
|
||||
|
||||
核心逻辑:XFA 读 header/line mappings;坐标读 order_field_layouts;
|
||||
若已有 bindings 则一并计入(迁移前后字段差异比较)。
|
||||
"""
|
||||
keys: set[tuple[str, str]] = set()
|
||||
mode = str(definition.get('template_mode') or 'coordinate').strip()
|
||||
if mode == 'xfa_dataset':
|
||||
for item in definition.get('header_mappings') or []:
|
||||
if isinstance(item, dict) and item.get('field_id'):
|
||||
keys.add(('header', str(item['field_id'])))
|
||||
line = definition.get('line_mapping') if isinstance(definition.get('line_mapping'), dict) else {}
|
||||
for item in line.get('fields') or []:
|
||||
if isinstance(item, dict) and item.get('field_id'):
|
||||
keys.add(('line', str(item['field_id'])))
|
||||
else:
|
||||
for item in definition.get('order_field_layouts') or []:
|
||||
if isinstance(item, dict) and item.get('field_id'):
|
||||
scope = str(item.get('scope') or 'header')
|
||||
keys.add((scope, str(item['field_id'])))
|
||||
for table in definition.get('table_regions') or []:
|
||||
if not isinstance(table, dict):
|
||||
continue
|
||||
for layout_key, scope in (('header_layouts', 'header'), ('line_layouts', 'line')):
|
||||
for layout in table.get(layout_key) or []:
|
||||
if not isinstance(layout, dict):
|
||||
continue
|
||||
for field in layout.get('field_regions') or []:
|
||||
if isinstance(field, dict) and field.get('field_id'):
|
||||
keys.add((scope, str(field['field_id'])))
|
||||
for item in definition.get('bindings') or []:
|
||||
if isinstance(item, dict) and item.get('field_id'):
|
||||
keys.add((str(item.get('scope') or 'header'), str(item['field_id'])))
|
||||
return keys
|
||||
|
||||
|
||||
def _xfa_path_keys(definition: dict[str, Any]) -> set[str]:
|
||||
"""抽取 XFA path_id 集合(用于路径保留率)。"""
|
||||
paths: set[str] = set()
|
||||
for item in definition.get('header_mappings') or []:
|
||||
if isinstance(item, dict) and item.get('path_id'):
|
||||
paths.add(str(item['path_id']))
|
||||
line = definition.get('line_mapping') if isinstance(definition.get('line_mapping'), dict) else {}
|
||||
for item in line.get('fields') or []:
|
||||
if isinstance(item, dict) and item.get('path_id'):
|
||||
paths.add(str(item['path_id']))
|
||||
for item in definition.get('bindings') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
value = item.get('value_binding') if isinstance(item.get('value_binding'), dict) else {}
|
||||
if value.get('path_id'):
|
||||
paths.add(str(value['path_id']))
|
||||
return paths
|
||||
|
||||
|
||||
def _match_acroform_widget(
|
||||
*,
|
||||
path_id: str,
|
||||
data_path: str,
|
||||
widgets: list[Any],
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
尝试用 path 短名匹配 AcroForm Widget,返回 page_no + normalized_bbox。
|
||||
|
||||
Args:
|
||||
path_id: datasets 路径身份。
|
||||
data_path: 受控 data_path。
|
||||
widgets: XfaAcroformWidget 列表。
|
||||
|
||||
Returns:
|
||||
匹配到的视觉框摘要;无匹配时 None。
|
||||
"""
|
||||
if not widgets:
|
||||
return None
|
||||
leaf = str(data_path or '').rsplit('/', 1)[-1].strip().upper()
|
||||
path_key = str(path_id or '').strip().upper()
|
||||
for widget in widgets:
|
||||
short = str(getattr(widget, 'short_name', '') or '').strip().upper()
|
||||
if not short:
|
||||
continue
|
||||
if short == leaf or short == path_key or leaf.endswith(short) or short in leaf:
|
||||
bbox = dict(getattr(widget, 'normalized_bbox', None) or {})
|
||||
page_no = int(getattr(widget, 'page_no', 1) or 1)
|
||||
if _region_dict(bbox) is None:
|
||||
continue
|
||||
return {
|
||||
'page_no': page_no,
|
||||
'normalized_bbox': _region_dict(bbox),
|
||||
'source': 'acroform_widget',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.6,
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
def convert_coordinate_definition_to_unified_bindings(
|
||||
definition: dict[str, Any],
|
||||
) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
"""
|
||||
将坐标模板 definition 转为带 bindings[] 的副本。
|
||||
|
||||
核心逻辑:order_field_layouts 与表区 field_regions → pdf_coordinate/ocr_coordinate
|
||||
value_binding + migrated_coordinate visual;保留原 coordinate 键以便过渡。
|
||||
|
||||
Args:
|
||||
definition: 原始 coordinate definition。
|
||||
|
||||
Returns:
|
||||
(after_definition, stats) stats 含 pending_visual_count 等。
|
||||
"""
|
||||
after = deepcopy(definition if isinstance(definition, dict) else {})
|
||||
after.setdefault('template_mode', 'coordinate')
|
||||
bindings: list[dict[str, Any]] = []
|
||||
pending = 0
|
||||
seen: set[tuple[str, str]] = set()
|
||||
|
||||
def _append_layout_binding(
|
||||
*,
|
||||
scope: str,
|
||||
field_id: str,
|
||||
field_code: str,
|
||||
region_id: str,
|
||||
page_no: int | None,
|
||||
absolute_region: Any,
|
||||
fallback_region: Any,
|
||||
evidence: str,
|
||||
) -> None:
|
||||
nonlocal pending
|
||||
key = (scope, field_id)
|
||||
if not field_id or key in seen:
|
||||
return
|
||||
seen.add(key)
|
||||
bbox = _region_dict(absolute_region) or _region_dict(fallback_region)
|
||||
status = 'confirmed'
|
||||
source = 'migrated_coordinate'
|
||||
confidence = 1.0
|
||||
if bbox is None:
|
||||
bbox = _placeholder_bbox()
|
||||
status = 'suggested'
|
||||
source = 'suggested'
|
||||
confidence = 0.0
|
||||
pending += 1
|
||||
value_type = 'ocr_coordinate' if evidence == 'ocr_coordinate' else 'pdf_coordinate'
|
||||
binding = {
|
||||
'binding_id': _stable_binding_id('coordinate', scope, field_id, region_id),
|
||||
'field_id': field_id,
|
||||
'field_code': field_code or field_id,
|
||||
'scope': scope,
|
||||
'value_binding': {
|
||||
'type': value_type,
|
||||
'region_id': region_id[:64] if region_id else f'region-{field_id}'[:64],
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': int(page_no or 1),
|
||||
'normalized_bbox': bbox,
|
||||
'source': source,
|
||||
'status': status,
|
||||
'confidence': confidence,
|
||||
},
|
||||
}
|
||||
XfaUnifiedFieldBinding.model_validate(binding)
|
||||
bindings.append(binding)
|
||||
|
||||
for item in after.get('order_field_layouts') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
_append_layout_binding(
|
||||
scope=str(item.get('scope') or 'header'),
|
||||
field_id=str(item.get('field_id') or '').strip(),
|
||||
field_code=str(item.get('field_code') or '').strip(),
|
||||
region_id=str(item.get('layout_id') or item.get('field_id') or 'layout'),
|
||||
page_no=item.get('page_no') if item.get('page_no') is not None else 1,
|
||||
absolute_region=item.get('absolute_value_region'),
|
||||
fallback_region=item.get('fallback_value_region'),
|
||||
evidence=str(item.get('minimum_evidence_level') or 'coordinate'),
|
||||
)
|
||||
|
||||
for table in after.get('table_regions') or []:
|
||||
if not isinstance(table, dict):
|
||||
continue
|
||||
table_page = table.get('page_no')
|
||||
for layout_key, scope in (('header_layouts', 'header'), ('line_layouts', 'line')):
|
||||
for layout in table.get(layout_key) or []:
|
||||
if not isinstance(layout, dict):
|
||||
continue
|
||||
for field in layout.get('field_regions') or []:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
region = field.get('region') or field.get('absolute_value_region')
|
||||
_append_layout_binding(
|
||||
scope=scope,
|
||||
field_id=str(field.get('field_id') or '').strip(),
|
||||
field_code=str(field.get('field_code') or '').strip(),
|
||||
region_id=str(field.get('region_id') or field.get('field_id') or 'region'),
|
||||
page_no=table_page if table_page is not None else 1,
|
||||
absolute_region=region,
|
||||
fallback_region=None,
|
||||
evidence=str(field.get('minimum_evidence_level') or 'coordinate'),
|
||||
)
|
||||
|
||||
after['bindings'] = bindings
|
||||
stats = {
|
||||
'binding_count': len(bindings),
|
||||
'pending_visual_count': pending,
|
||||
'template_mode': 'coordinate',
|
||||
}
|
||||
return after, stats
|
||||
|
||||
|
||||
def _clear_xfa_legacy_mappings(definition: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
迁移 Execute 后清除 legacy header_mappings / line_mapping.fields,仅保留 bindings[]。
|
||||
|
||||
核心逻辑:row_path 仍与 authoritative_line_collection_path 对齐供契约校验;
|
||||
before 快照已保留审计对比。
|
||||
|
||||
Args:
|
||||
definition: 已写入 bindings 的 xfa_dataset definition。
|
||||
|
||||
Returns:
|
||||
清除 legacy 映射后的 definition 副本。
|
||||
"""
|
||||
cleared = dict(definition)
|
||||
cleared['header_mappings'] = []
|
||||
line_mapping = dict(cleared.get('line_mapping') or {})
|
||||
source = cleared.get('source_contract') if isinstance(cleared.get('source_contract'), dict) else {}
|
||||
auth_path = str(source.get('authoritative_line_collection_path') or line_mapping.get('row_path') or '').strip()
|
||||
line_mapping['fields'] = []
|
||||
if auth_path:
|
||||
line_mapping['row_path'] = auth_path
|
||||
cleared['line_mapping'] = line_mapping
|
||||
return cleared
|
||||
|
||||
|
||||
def convert_xfa_definition_to_unified_bindings(
|
||||
definition: dict[str, Any],
|
||||
*,
|
||||
widgets: list[Any] | None = None,
|
||||
) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
"""
|
||||
将 XFA definition 转为带 bindings[] 的副本(convert 阶段仍读 legacy mappings 作输入)。
|
||||
|
||||
核心逻辑:header_mappings + line_mapping.fields → xfa_dataset value_binding;
|
||||
Execute 写入 Draft 后由 _clear_xfa_legacy_mappings 清除 legacy 映射,仅保留 bindings。
|
||||
|
||||
Args:
|
||||
definition: 原始 xfa_dataset definition。
|
||||
widgets: 可选 AcroForm Widget 列表。
|
||||
|
||||
Returns:
|
||||
(after_definition, stats)。
|
||||
"""
|
||||
after = deepcopy(definition if isinstance(definition, dict) else {})
|
||||
after['template_mode'] = 'xfa_dataset'
|
||||
# convert 阶段读取 legacy mappings 作迁移输入;Execute 写入 Draft 后清除 legacy
|
||||
after.setdefault('header_mappings', list(definition.get('header_mappings') or []))
|
||||
after.setdefault('line_mapping', dict(definition.get('line_mapping') or {}))
|
||||
after.setdefault('source_contract', dict(definition.get('source_contract') or {}))
|
||||
after.setdefault('split_rules', list(definition.get('split_rules') or []))
|
||||
|
||||
bindings: list[dict[str, Any]] = []
|
||||
pending = 0
|
||||
preserved_paths = 0
|
||||
total_paths = 0
|
||||
seen: set[tuple[str, str]] = set()
|
||||
|
||||
def _append_mapping(item: dict[str, Any], *, scope: str) -> None:
|
||||
nonlocal pending, preserved_paths, total_paths
|
||||
field_id = str(item.get('field_id') or '').strip()
|
||||
if not field_id or (scope, field_id) in seen:
|
||||
return
|
||||
seen.add((scope, field_id))
|
||||
path_id = str(item.get('path_id') or '').strip()
|
||||
data_path = str(item.get('data_path') or '').strip()
|
||||
total_paths += 1
|
||||
if path_id and data_path:
|
||||
validate_controlled_data_path(data_path)
|
||||
preserved_paths += 1
|
||||
visual = _match_acroform_widget(
|
||||
path_id=path_id,
|
||||
data_path=data_path,
|
||||
widgets=list(widgets or []),
|
||||
)
|
||||
if visual is None:
|
||||
visual = {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': _placeholder_bbox(),
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.0,
|
||||
}
|
||||
pending += 1
|
||||
else:
|
||||
pending += 1 # AcroForm 候选仍须人工确认
|
||||
mapping_id = str(item.get('mapping_id') or path_id or field_id)
|
||||
binding = {
|
||||
'binding_id': _stable_binding_id('xfa', scope, mapping_id, field_id),
|
||||
'field_id': field_id,
|
||||
'field_code': str(item.get('field_code') or field_id),
|
||||
'scope': scope,
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': path_id,
|
||||
'data_path': data_path,
|
||||
},
|
||||
'visual_binding': visual,
|
||||
}
|
||||
XfaUnifiedFieldBinding.model_validate(binding)
|
||||
bindings.append(binding)
|
||||
|
||||
for item in after.get('header_mappings') or []:
|
||||
if isinstance(item, dict):
|
||||
_append_mapping(item, scope='header')
|
||||
line = after.get('line_mapping') if isinstance(after.get('line_mapping'), dict) else {}
|
||||
for item in line.get('fields') or []:
|
||||
if isinstance(item, dict):
|
||||
_append_mapping(item, scope='line')
|
||||
|
||||
after['bindings'] = bindings
|
||||
path_preserve_rate = 100.0 if total_paths == 0 else round(100.0 * preserved_paths / total_paths, 4)
|
||||
stats = {
|
||||
'binding_count': len(bindings),
|
||||
'pending_visual_count': pending,
|
||||
'template_mode': 'xfa_dataset',
|
||||
'path_preserve_rate': path_preserve_rate,
|
||||
'preserved_path_count': preserved_paths,
|
||||
'total_path_count': total_paths,
|
||||
}
|
||||
return after, stats
|
||||
|
||||
|
||||
def build_migration_report(
|
||||
*,
|
||||
before: dict[str, Any],
|
||||
after: dict[str, Any],
|
||||
stats: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
汇总迁移报告(path_preserve_rate / field_diff_count / pending_visual_count)。
|
||||
|
||||
Args:
|
||||
before: 迁移前 definition。
|
||||
after: 迁移后 definition。
|
||||
stats: convert_* 返回的统计。
|
||||
|
||||
Returns:
|
||||
可序列化报告 dict。
|
||||
"""
|
||||
before_fields = _formal_field_keys_from_definition(before)
|
||||
after_fields = _formal_field_keys_from_definition(after)
|
||||
# 正式字段差异:仅比较原 mappings/layouts 与迁移后 bindings 对应字段集合
|
||||
after_binding_fields = {
|
||||
(str(item.get('scope') or 'header'), str(item.get('field_id')))
|
||||
for item in (after.get('bindings') or [])
|
||||
if isinstance(item, dict) and item.get('field_id')
|
||||
}
|
||||
source_fields = before_fields or after_binding_fields
|
||||
field_diff = sorted(source_fields.symmetric_difference(after_binding_fields))
|
||||
mode = str(stats.get('template_mode') or before.get('template_mode') or 'coordinate')
|
||||
legacy_header_count = len([
|
||||
item for item in (before.get('header_mappings') or []) if isinstance(item, dict)
|
||||
])
|
||||
line_before = before.get('line_mapping') if isinstance(before.get('line_mapping'), dict) else {}
|
||||
legacy_line_count = len([
|
||||
item for item in (line_before.get('fields') or []) if isinstance(item, dict)
|
||||
])
|
||||
legacy_will_be_cleared = (
|
||||
mode == 'xfa_dataset'
|
||||
and (legacy_header_count > 0 or legacy_line_count > 0)
|
||||
)
|
||||
if mode == 'xfa_dataset':
|
||||
path_rate = float(stats.get('path_preserve_rate') or 0.0)
|
||||
before_paths = _xfa_path_keys(before)
|
||||
after_paths = _xfa_path_keys(after)
|
||||
if before_paths and before_paths <= after_paths:
|
||||
path_rate = 100.0
|
||||
else:
|
||||
# 坐标模板无 datasets 路径;区域绑定保留率按 binding 覆盖率计
|
||||
path_rate = 100.0 if not field_diff else 0.0
|
||||
return {
|
||||
'template_mode': mode,
|
||||
'path_preserve_rate': path_rate,
|
||||
'field_diff_count': len(field_diff),
|
||||
'field_diff_keys': [
|
||||
{'scope': scope, 'field_id': field_id} for scope, field_id in field_diff
|
||||
],
|
||||
'pending_visual_count': int(stats.get('pending_visual_count') or 0),
|
||||
'binding_count': int(stats.get('binding_count') or len(after.get('bindings') or [])),
|
||||
'already_unified': bool(before.get('bindings')),
|
||||
'legacy_will_be_cleared': legacy_will_be_cleared,
|
||||
'legacy_mapping_counts': {
|
||||
'header': legacy_header_count,
|
||||
'line': legacy_line_count,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _profile_or_raise(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取 Profile;不存在时统一 not-found。"""
|
||||
row = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if row is None:
|
||||
raise NotFoundError(
|
||||
'Order document profile not found',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND',
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def _load_acroform_widgets(profile: ShippingOrderDocumentProfile) -> list[Any]:
|
||||
"""尽力从标注样本 PDF 读取 AcroForm Widget;失败返回空列表。"""
|
||||
sample = (
|
||||
ShippingOrderDocumentProfileSample.query.filter_by(
|
||||
profile_id=profile.id, sample_role='annotation',
|
||||
).order_by(ShippingOrderDocumentProfileSample.id.asc()).first()
|
||||
)
|
||||
if sample is None:
|
||||
return []
|
||||
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
|
||||
if document is None or not document.asset_id:
|
||||
return []
|
||||
try:
|
||||
from app.models import FileAsset
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.document_layout.xfa_acroform import read_acroform_widgets
|
||||
|
||||
asset = db.session.get(FileAsset, int(document.asset_id))
|
||||
if asset is None:
|
||||
return []
|
||||
return read_acroform_widgets(read_asset_bytes(asset))
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def convert_profile_definition(
|
||||
profile: ShippingOrderDocumentProfile,
|
||||
*,
|
||||
include_acroform: bool = True,
|
||||
) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]:
|
||||
"""
|
||||
按模板模式转换 definition 并生成报告。
|
||||
|
||||
Args:
|
||||
profile: ORM Profile。
|
||||
include_acroform: XFA 时是否尝试读取 Widget。
|
||||
|
||||
Returns:
|
||||
(before, after, report)。
|
||||
"""
|
||||
before = dict(profile.definition_json or {})
|
||||
mode = str(profile.template_mode or before.get('template_mode') or 'coordinate').strip()
|
||||
if mode == 'xfa_dataset':
|
||||
widgets = _load_acroform_widgets(profile) if include_acroform else []
|
||||
after, stats = convert_xfa_definition_to_unified_bindings(before, widgets=widgets)
|
||||
else:
|
||||
after, stats = convert_coordinate_definition_to_unified_bindings(before)
|
||||
report = build_migration_report(before=before, after=after, stats=stats)
|
||||
return before, after, report
|
||||
|
||||
|
||||
def _write_profile_audit(
|
||||
*,
|
||||
profile_id: int,
|
||||
event_type: str,
|
||||
actor_id: int | None,
|
||||
detail: dict[str, Any],
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
revision_no: int | None = None,
|
||||
) -> None:
|
||||
"""写入订单模板审计表(含迁移报告)。"""
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
profile_service._audit(
|
||||
profile_id=int(profile_id),
|
||||
event_type=event_type,
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
revision_no=revision_no,
|
||||
detail=detail,
|
||||
)
|
||||
|
||||
|
||||
def dry_run_unified_migration(
|
||||
profile_id: int,
|
||||
*,
|
||||
actor_id: int | None = None,
|
||||
request_id: str | None = None,
|
||||
write_audit: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Dry Run:转换并返回报告,不修改 definition。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
actor_id: 操作者。
|
||||
request_id: HTTP request_id。
|
||||
write_audit: 是否写入 dry-run 审计。
|
||||
|
||||
Returns:
|
||||
{profile_id, report, binding_preview_count, dry_run: True}。
|
||||
"""
|
||||
profile = _profile_or_raise(profile_id)
|
||||
before, after, report = convert_profile_definition(profile)
|
||||
payload = {
|
||||
'profile_id': int(profile.id),
|
||||
'profile_code': profile.profile_code,
|
||||
'version': int(profile.version),
|
||||
'status': profile.status,
|
||||
'dry_run': True,
|
||||
'report': report,
|
||||
'binding_preview_count': len(after.get('bindings') or []),
|
||||
}
|
||||
if write_audit:
|
||||
_write_profile_audit(
|
||||
profile_id=int(profile.id),
|
||||
event_type=UNIFIED_MIGRATION_DRY_RUN_EVENT,
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
detail={
|
||||
'report': report,
|
||||
'before_binding_count': len(before.get('bindings') or []),
|
||||
'after_binding_count': len(after.get('bindings') or []),
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return payload
|
||||
|
||||
|
||||
def _ensure_draft_for_execute(
|
||||
source: ShippingOrderDocumentProfile,
|
||||
*,
|
||||
actor_id: int | None,
|
||||
) -> ShippingOrderDocumentProfile:
|
||||
"""
|
||||
Execute 时确保有可写 Draft:已发布则 clone;已是草稿则复用。
|
||||
|
||||
Raises:
|
||||
ConflictError: 已发布且同族已有其它草稿。
|
||||
"""
|
||||
if source.status == 'draft':
|
||||
return source
|
||||
if source.status not in {'published', 'retired'}:
|
||||
raise ValidationError(
|
||||
'Only draft or published profiles can be migrated',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_INVALID',
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
cloned = profile_service.clone_draft(int(source.id), actor_id=actor_id)
|
||||
draft = db.session.get(ShippingOrderDocumentProfile, int(cloned['id']))
|
||||
if draft is None:
|
||||
raise ConflictError(
|
||||
'Failed to create migration draft',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_INVALID',
|
||||
)
|
||||
return draft
|
||||
|
||||
|
||||
def execute_unified_migration(
|
||||
profile_id: int,
|
||||
*,
|
||||
actor_id: int | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Execute:写入统一 bindings 到新/现有 Draft Revision,并记 before/after 审计。
|
||||
|
||||
核心逻辑:转换 definition → 确保 Draft → 更新 definition_json + DraftRevision →
|
||||
审计事件含报告与 before/after binding 摘要。
|
||||
|
||||
Args:
|
||||
profile_id: 源模板 ID(发布版或草稿)。
|
||||
actor_id: 操作者。
|
||||
request_id: HTTP request_id。
|
||||
operation_id: 幂等操作 ID。
|
||||
|
||||
Returns:
|
||||
含 draft_profile_id、revision_no、report 的结果。
|
||||
"""
|
||||
source = _profile_or_raise(profile_id)
|
||||
before, after, report = convert_profile_definition(source)
|
||||
if report.get('already_unified') and after.get('bindings') and before.get('bindings'):
|
||||
# 已有 bindings 时仍允许再跑,覆盖重建建议框
|
||||
pass
|
||||
|
||||
draft = _ensure_draft_for_execute(source, actor_id=actor_id)
|
||||
# clone 后需在草稿上再次转换(定义已复制)
|
||||
if draft.id != source.id:
|
||||
before, after, report = convert_profile_definition(draft)
|
||||
|
||||
previous_definition = dict(draft.definition_json or {})
|
||||
next_definition = dict(after)
|
||||
if next_definition.get('template_mode') == 'xfa_dataset':
|
||||
next_definition = _clear_xfa_legacy_mappings(next_definition)
|
||||
# Execute 后 legacy header_mappings / line_mapping.fields 须已清空
|
||||
assert next_definition.get('header_mappings') == []
|
||||
line_after = next_definition.get('line_mapping') if isinstance(next_definition.get('line_mapping'), dict) else {}
|
||||
assert line_after.get('fields') == []
|
||||
# 保留 template_mode 列与 definition 一致
|
||||
if draft.template_mode == 'xfa_dataset' or next_definition.get('template_mode') == 'xfa_dataset':
|
||||
next_definition['template_mode'] = 'xfa_dataset'
|
||||
else:
|
||||
next_definition['template_mode'] = 'coordinate'
|
||||
|
||||
draft.definition_json = next_definition
|
||||
draft.lock_version = int(draft.lock_version or 0) + 1
|
||||
db.session.flush()
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
next_revision_no = int(
|
||||
db.session.query(func.max(ShippingOrderDocumentProfileDraftRevision.revision_no))
|
||||
.filter_by(profile_id=draft.id)
|
||||
.scalar()
|
||||
or 0,
|
||||
) + 1
|
||||
op = str(operation_id or secrets.token_hex(16)).strip()
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
revision = ShippingOrderDocumentProfileDraftRevision(
|
||||
profile_id=draft.id,
|
||||
revision_no=next_revision_no,
|
||||
base_lock_version=int(draft.lock_version) - 1,
|
||||
result_lock_version=int(draft.lock_version),
|
||||
definition_checksum=getattr(draft, 'structure_fingerprint', None) or secrets.token_hex(16),
|
||||
change_source='unified_binding_migration',
|
||||
actor_id=actor_id,
|
||||
browser_session_id=None,
|
||||
operation_id=op,
|
||||
change_summary_json={
|
||||
**profile_service._definition_audit_summary(next_definition),
|
||||
'unified_migration_report': report,
|
||||
},
|
||||
definition_snapshot_json=dict(next_definition),
|
||||
)
|
||||
db.session.add(revision)
|
||||
before_summary = {
|
||||
'binding_count': len(previous_definition.get('bindings') or []),
|
||||
'formal_field_count': len(_formal_field_keys_from_definition(previous_definition)),
|
||||
'template_mode': previous_definition.get('template_mode') or draft.template_mode,
|
||||
}
|
||||
after_summary = {
|
||||
'binding_count': len(next_definition.get('bindings') or []),
|
||||
'formal_field_count': len(_formal_field_keys_from_definition(next_definition)),
|
||||
'template_mode': next_definition.get('template_mode'),
|
||||
'pending_visual_count': report.get('pending_visual_count'),
|
||||
}
|
||||
_write_profile_audit(
|
||||
profile_id=int(draft.id),
|
||||
event_type=UNIFIED_MIGRATION_EXECUTED_EVENT,
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=op,
|
||||
revision_no=next_revision_no,
|
||||
detail={
|
||||
'report': report,
|
||||
'before': before_summary,
|
||||
'after': after_summary,
|
||||
'source_profile_id': int(source.id),
|
||||
'draft_profile_id': int(draft.id),
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return {
|
||||
'profile_id': int(source.id),
|
||||
'draft_profile_id': int(draft.id),
|
||||
'profile_code': draft.profile_code,
|
||||
'version': int(draft.version),
|
||||
'revision_no': next_revision_no,
|
||||
'operation_id': op,
|
||||
'dry_run': False,
|
||||
'report': report,
|
||||
}
|
||||
|
||||
|
||||
def get_unified_migration_report(profile_id: int) -> dict[str, Any]:
|
||||
"""
|
||||
读取最近一次统一迁移 Dry Run / Execute 报告(来自审计 detail)。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
|
||||
Returns:
|
||||
最近报告;无记录时 report=None。
|
||||
|
||||
Raises:
|
||||
NotFoundError: Profile 不存在。
|
||||
"""
|
||||
profile = _profile_or_raise(profile_id)
|
||||
# 同族草稿/发布均可查:先本 profile,再 source / 同 code 草稿
|
||||
candidate_ids = {int(profile.id)}
|
||||
if profile.source_profile_id:
|
||||
candidate_ids.add(int(profile.source_profile_id))
|
||||
siblings = (
|
||||
ShippingOrderDocumentProfile.query.filter_by(profile_code=profile.profile_code)
|
||||
.with_entities(ShippingOrderDocumentProfile.id)
|
||||
.all()
|
||||
)
|
||||
for row in siblings:
|
||||
candidate_ids.add(int(row[0]))
|
||||
|
||||
event = (
|
||||
ShippingOrderDocumentProfileAudit.query.filter(
|
||||
ShippingOrderDocumentProfileAudit.profile_id.in_(sorted(candidate_ids)),
|
||||
ShippingOrderDocumentProfileAudit.event_type.in_(sorted(UNIFIED_MIGRATION_AUDIT_EVENTS)),
|
||||
)
|
||||
.order_by(
|
||||
ShippingOrderDocumentProfileAudit.id.desc(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if event is None:
|
||||
return {
|
||||
'profile_id': int(profile.id),
|
||||
'report': None,
|
||||
'event_type': None,
|
||||
'created_at': None,
|
||||
}
|
||||
detail = event.detail_json if isinstance(event.detail_json, dict) else {}
|
||||
return {
|
||||
'profile_id': int(profile.id),
|
||||
'report': detail.get('report'),
|
||||
'event_type': event.event_type,
|
||||
'created_at': event.created_at.isoformat() + 'Z' if event.created_at else None,
|
||||
'detail': {
|
||||
'before': detail.get('before'),
|
||||
'after': detail.get('after'),
|
||||
'draft_profile_id': detail.get('draft_profile_id'),
|
||||
'source_profile_id': detail.get('source_profile_id'),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def summarize_unified_migration_status(
|
||||
definition: dict[str, Any],
|
||||
*,
|
||||
template_mode: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
轻量汇总模板统一 binding 迁移状态(不读 PDF / AcroForm)。
|
||||
|
||||
核心逻辑:已有 bindings[] 时统计未确认视觉框;否则对 definition 做内存转换预览
|
||||
needs_migration / pending_visual / field_diff,不写库。
|
||||
|
||||
Args:
|
||||
definition: Profile definition_json。
|
||||
template_mode: ORM template_mode;缺省时读 definition。
|
||||
|
||||
Returns:
|
||||
unified_binding_status、pending_visual_count、needs_migration 等摘要。
|
||||
"""
|
||||
safe_definition = dict(definition if isinstance(definition, dict) else {})
|
||||
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:
|
||||
pending = sum(
|
||||
1
|
||||
for item in bindings
|
||||
if str((item.get('visual_binding') or {}).get('status') or '').strip() != 'confirmed'
|
||||
)
|
||||
status = 'ready' if pending == 0 else 'pending_visual'
|
||||
return {
|
||||
'template_mode': mode,
|
||||
'unified_binding_status': status,
|
||||
'already_unified': True,
|
||||
'needs_migration': False,
|
||||
'binding_count': len(bindings),
|
||||
'pending_visual_count': pending,
|
||||
'field_diff_count': 0,
|
||||
'path_preserve_rate': 100.0,
|
||||
}
|
||||
if mode == 'xfa_dataset':
|
||||
after, stats = convert_xfa_definition_to_unified_bindings(safe_definition, widgets=[])
|
||||
else:
|
||||
after, stats = convert_coordinate_definition_to_unified_bindings(safe_definition)
|
||||
report = build_migration_report(before=safe_definition, after=after, stats=stats)
|
||||
pending = int(report.get('pending_visual_count') or 0)
|
||||
return {
|
||||
'template_mode': mode,
|
||||
'unified_binding_status': 'needs_migration',
|
||||
'already_unified': False,
|
||||
'needs_migration': True,
|
||||
'binding_count': int(report.get('binding_count') or 0),
|
||||
'pending_visual_count': pending,
|
||||
'field_diff_count': int(report.get('field_diff_count') or 0),
|
||||
'path_preserve_rate': float(report.get('path_preserve_rate') or 0.0),
|
||||
}
|
||||
|
||||
|
||||
def scan_unified_migration_profiles(
|
||||
*,
|
||||
profile_ids: list[int] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
扫描全部(或指定)模板族的统一 binding 迁移状态;Dry Run 预览,不写 definition。
|
||||
|
||||
核心逻辑:每 profile_code 取 published 优先、否则 draft;委托 summarize_unified_migration_status。
|
||||
|
||||
Args:
|
||||
profile_ids: 可选 Profile ID 白名单;缺省扫描全部族代表版本。
|
||||
|
||||
Returns:
|
||||
totals 汇总与 items 逐族明细(含 target_profile_id 供后续 Dry Run / Execute)。
|
||||
"""
|
||||
query = ShippingOrderDocumentProfile.query.order_by(
|
||||
ShippingOrderDocumentProfile.profile_code.asc(),
|
||||
ShippingOrderDocumentProfile.version.desc(),
|
||||
)
|
||||
if profile_ids:
|
||||
query = query.filter(ShippingOrderDocumentProfile.id.in_([int(item) for item in profile_ids]))
|
||||
rows = query.all()
|
||||
families: dict[str, list[ShippingOrderDocumentProfile]] = {}
|
||||
for row in rows:
|
||||
families.setdefault(str(row.profile_code), []).append(row)
|
||||
|
||||
items: list[dict[str, Any]] = []
|
||||
totals = {
|
||||
'total_families': 0,
|
||||
'needs_migration': 0,
|
||||
'pending_visual': 0,
|
||||
'ready': 0,
|
||||
'pending_visual_bindings': 0,
|
||||
}
|
||||
for profile_code, versions in sorted(families.items()):
|
||||
published = next((item for item in versions if item.status == 'published'), None)
|
||||
draft = next((item for item in versions if item.status == 'draft'), None)
|
||||
target = published or draft or versions[0]
|
||||
definition = dict(target.definition_json or {})
|
||||
summary = summarize_unified_migration_status(
|
||||
definition,
|
||||
template_mode=str(target.template_mode or definition.get('template_mode') or 'coordinate'),
|
||||
)
|
||||
status = str(summary.get('unified_binding_status') or 'needs_migration')
|
||||
totals['total_families'] += 1
|
||||
if status == 'needs_migration':
|
||||
totals['needs_migration'] += 1
|
||||
elif status == 'pending_visual':
|
||||
totals['pending_visual'] += 1
|
||||
else:
|
||||
totals['ready'] += 1
|
||||
pending_count = int(summary.get('pending_visual_count') or 0)
|
||||
totals['pending_visual_bindings'] += pending_count
|
||||
items.append({
|
||||
'profile_code': profile_code,
|
||||
'display_name': target.display_name,
|
||||
'target_profile_id': int(target.id),
|
||||
'target_version': int(target.version),
|
||||
'target_status': target.status,
|
||||
**summary,
|
||||
})
|
||||
return {'totals': totals, 'items': items}
|
||||
@@ -10,7 +10,8 @@ backend/app/services/shipping_notice/order_review_confirmation_service.py
|
||||
逻辑:确认在单事务内分别锁定 Case 与 Draft,重跑资格门禁,冻结行级库存源候选与
|
||||
可自动确认的客户;库存源未唯一确定时按硬门禁拒绝建单并回写 OT stage=
|
||||
inventory_source_resolving;物化人工 Candidate 时先写入客户已确认事实再执行履约门禁;
|
||||
确认建单前锁定 case.candidate_id 对应 OT,人工 Candidate 仅受控替换该 OT 的 candidate_id;
|
||||
确认建单前锁定 case.candidate_id 对应 OT:未消费 OT 受控换绑人工 Candidate;
|
||||
已消费 OT 保留历史并为后续波次创建稳定子 OT;同步 Case 当前 Candidate;
|
||||
缺 OT 则 fail-closed 回滚;禁止 upsert 到 Run 根号串单;
|
||||
物化 accepted Extraction(保留派生 field_lineage);建单前再次校验客户确认并
|
||||
持久化 Candidate Qualification 快照;客户未确认拒绝建单;同 Case 既有波次 Task
|
||||
@@ -1257,7 +1258,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
)
|
||||
# [BE-01/BE-02] 复用锁定 OT;无原 Candidate 时才按人工 Candidate 新建 OT。
|
||||
try:
|
||||
if locked_order_task is not None:
|
||||
if locked_order_task is not None and locked_order_task.shipping_notice_id is None:
|
||||
order_task = replace_order_task_candidate_after_review(
|
||||
order_task=locked_order_task,
|
||||
previous_candidate_id=source_candidate_id,
|
||||
@@ -1266,6 +1267,9 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
actor_id=int(user_id),
|
||||
stage='order_creating',
|
||||
)
|
||||
# [BE-01] OT 已受控换绑到人工 Candidate;Case 必须同步当前绑定,
|
||||
# 否则同一 PDF 下一波次仍按旧机器 Candidate 查 OT 并错误 fail-closed。
|
||||
case.candidate_id = int(candidate.id)
|
||||
source_candidate = (
|
||||
db.session.get(ShippingOrderCandidate, int(source_candidate_id))
|
||||
if source_candidate_id is not None
|
||||
@@ -1281,14 +1285,24 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
source_candidate.candidate_status = 'expired'
|
||||
source_candidate.is_current_version = False
|
||||
else:
|
||||
# [BE-01] 同一 PDF 后续履约波次不能改写已挂 Notice 的历史 OT;
|
||||
# 新人工 Candidate 使用稳定子号,保持一 Candidate 一 OT 与波次审计完整。
|
||||
root_task_no = str(case.run.user_task_no or '').strip()
|
||||
wave_task_no = (
|
||||
f'{root_task_no}-C{int(candidate.id)}'
|
||||
if root_task_no and locked_order_task is not None
|
||||
else None
|
||||
)
|
||||
upsert_order_task_from_run(
|
||||
case.run,
|
||||
intake_id=int(intake.id),
|
||||
candidate_id=int(candidate.id),
|
||||
source_type=str(getattr(intake, 'source_type', None) or 'direct_pdf').strip() or 'direct_pdf',
|
||||
stage='order_creating',
|
||||
task_no=wave_task_no,
|
||||
)
|
||||
order_task = resolve_order_task_for_candidate(int(candidate.id))
|
||||
case.candidate_id = int(candidate.id)
|
||||
except AppError as err:
|
||||
_reject_confirmation(
|
||||
case,
|
||||
|
||||
@@ -262,7 +262,10 @@ def _allowed_actions(case: ShippingOrderReviewCase) -> list[str]:
|
||||
|
||||
def serialize_review_case(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
"""返回一个 Case 的安全详情,用于阶段 1 只读工作台与后续编辑基线。"""
|
||||
from app.services.shipping_notice.schema_edit_policy import list_editable_formal_field_ids
|
||||
from app.services.shipping_notice.schema_edit_policy import (
|
||||
is_excel_ready_for_task,
|
||||
list_editable_formal_field_ids,
|
||||
)
|
||||
|
||||
run = case.run
|
||||
draft = case.current_draft
|
||||
@@ -368,6 +371,7 @@ def serialize_review_case(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
order_data_version = None
|
||||
confirmed_notice = None
|
||||
if str(case.status or '') == 'confirmed' and case.confirmed_task_id:
|
||||
from app.models import ShippingNotice
|
||||
|
||||
@@ -402,9 +406,12 @@ def serialize_review_case(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
'draft': projected_draft,
|
||||
'llm_suggestions': llm_suggestions,
|
||||
'available_actions': _allowed_actions(case),
|
||||
# 正式任务可编辑字段(默认空;仅 Schema task_edit_policy 放行)。
|
||||
# 正式任务可编辑字段(默认空;仅 Schema task_edit_policy 放行;Excel ready 后全空)。
|
||||
'formal_editable_field_ids': (
|
||||
list_editable_formal_field_ids(schema_fields)
|
||||
list_editable_formal_field_ids(
|
||||
schema_fields,
|
||||
excel_ready=is_excel_ready_for_task(confirmed_notice) if confirmed_notice is not None else False,
|
||||
)
|
||||
if str(case.status or '') == 'confirmed'
|
||||
else []
|
||||
),
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
"""
|
||||
建单前订单复核 Case 的初始化与只读加载服务。
|
||||
services/shipping_notice/order_review_service.py
|
||||
|
||||
依赖:冻结 Run/Unit、机器 Candidate、Review Case/Draft 模型、冻结 Schema 快照、
|
||||
用途:建单前订单复核 Case 的初始化与只读加载服务。
|
||||
依赖:冻结 Run/Unit、机器 Candidate、Review Case/Draft、order_task_service、
|
||||
workflow_ledger_service.bind_cases_for_run。
|
||||
逻辑:每个 PDF Unit 幂等创建一个 Case;只有该 PDF 恰有一个本 Run Candidate
|
||||
时才把它作为只读机器来源。Draft 从 Unit 的冻结结果初始化,绝不回写 Candidate;
|
||||
逻辑:Candidate 落库后按单个已就绪 PDF Unit 幂等创建/修复 Case;Run 级入口仅做
|
||||
已就绪 Unit 对账,禁止一个 PDF 提前创建其余 PDF 的空 Case。只有该 PDF
|
||||
恰有一个本 Run 当前 Candidate 时才把它作为只读机器来源。Draft 从 Unit 的冻结结果
|
||||
初始化,绝不回写 Candidate;
|
||||
Case 初始化/回填时为已关联 Candidate 幂等预建 OT(确认前必须有 OT);
|
||||
Case 初始化后绑定/创建对应 WorkflowItem。
|
||||
"""
|
||||
|
||||
@@ -19,6 +23,7 @@ from app import db
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderProcessingUnit,
|
||||
ShippingOrderReviewCase,
|
||||
@@ -27,6 +32,10 @@ from app.models import (
|
||||
)
|
||||
|
||||
|
||||
_REVIEW_CASE_READY_UNIT_STATUSES = frozenset({'candidate_ready', 'review_required'})
|
||||
_REPAIRABLE_CASE_STATUSES = frozenset({'unreviewed', 'draft', 'ready'})
|
||||
|
||||
|
||||
def _restore_machine_field_source_case(field: Any) -> bool:
|
||||
"""以坐标证据的原始引文修正机器文本大小写,不改写人工值或类型化字段。
|
||||
|
||||
@@ -78,13 +87,85 @@ def _is_pdf_unit(run: ShippingOrderProcessingRun, unit: ShippingOrderProcessingU
|
||||
|
||||
|
||||
def _single_candidate_id(run: ShippingOrderProcessingRun, unit: ShippingOrderProcessingUnit) -> int | None:
|
||||
"""只关联唯一机器 Candidate;旧多 Candidate 结果必须留空并由后续清理处理。"""
|
||||
"""只关联唯一当前机器 Candidate;旧版或多 Candidate 结果必须保持显式歧义。"""
|
||||
rows = ShippingOrderCandidate.query.filter_by(
|
||||
order_extraction_run_id=int(run.id), primary_document_id=int(unit.document_id),
|
||||
order_extraction_run_id=int(run.id),
|
||||
primary_document_id=int(unit.document_id),
|
||||
is_current_version=True,
|
||||
).order_by(ShippingOrderCandidate.id.asc()).all()
|
||||
return int(rows[0].id) if len(rows) == 1 else None
|
||||
|
||||
|
||||
def _ensure_order_task_for_case_candidate(
|
||||
run: ShippingOrderProcessingRun,
|
||||
*,
|
||||
candidate_id: int | None,
|
||||
) -> None:
|
||||
"""
|
||||
为 Case 已关联的 Candidate 幂等预建 OT,保证进入复核/确认前已有聚合根。
|
||||
|
||||
核心逻辑:已有 OT 则跳过;否则按 Candidate 的 Intake/Submission 调用
|
||||
upsert_order_task_for_candidate_formation,stage 置 waiting_review。
|
||||
无 candidate_id 时不建 OT(确认路径仍 fail-closed)。
|
||||
|
||||
Args:
|
||||
run: 当前抽取 Run。
|
||||
candidate_id: Case 关联的 Candidate 主键;空则跳过。
|
||||
"""
|
||||
if candidate_id is None:
|
||||
return
|
||||
from app.services.shipping_notice.order_task_service import (
|
||||
allocate_user_task_no_for_run,
|
||||
resolve_order_task_for_candidate,
|
||||
upsert_order_task_for_candidate_formation,
|
||||
)
|
||||
|
||||
if resolve_order_task_for_candidate(int(candidate_id)) is not None:
|
||||
return
|
||||
from app.models import ShippingOrderTask
|
||||
|
||||
candidate = db.session.get(ShippingOrderCandidate, int(candidate_id))
|
||||
if candidate is None:
|
||||
return
|
||||
intake = (
|
||||
db.session.get(ShippingOrderIntake, int(candidate.intake_id))
|
||||
if candidate.intake_id
|
||||
else None
|
||||
)
|
||||
root_task_no = allocate_user_task_no_for_run(run)
|
||||
root_task = ShippingOrderTask.query.filter_by(task_no=root_task_no).one_or_none()
|
||||
# [STEP] 首个 Candidate 占用根 OT;任意后续兄弟 Candidate 使用稳定子号,
|
||||
# 禁止 N 个 PDF 依次通过 upsert 抢占同一个 candidate_id。
|
||||
candidate_task_no = (
|
||||
root_task_no
|
||||
if root_task is None or int(root_task.candidate_id or 0) == int(candidate.id)
|
||||
else f'{root_task_no}-C{int(candidate.id)}'
|
||||
)
|
||||
upsert_order_task_for_candidate_formation(
|
||||
run,
|
||||
intake_id=int(intake.id) if intake is not None else None,
|
||||
candidate_id=int(candidate.id),
|
||||
submission_id=(
|
||||
getattr(intake, 'order_submission_id', None) if intake is not None else None
|
||||
),
|
||||
source_type=(
|
||||
str(getattr(intake, 'source_type', None) or '').strip() or None
|
||||
if intake is not None
|
||||
else None
|
||||
),
|
||||
stage='waiting_review',
|
||||
task_no=candidate_task_no,
|
||||
)
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
sync_order_task_stage_for_candidate,
|
||||
)
|
||||
|
||||
sync_order_task_stage_for_candidate(
|
||||
candidate=candidate,
|
||||
prefer_waiting_review=True,
|
||||
)
|
||||
|
||||
|
||||
def _machine_orders_for_unit(
|
||||
run: ShippingOrderProcessingRun, unit: ShippingOrderProcessingUnit,
|
||||
) -> list[dict[str, Any]]:
|
||||
@@ -128,76 +209,150 @@ def _initial_draft_payload(
|
||||
|
||||
|
||||
def _can_backfill_machine_draft(case: ShippingOrderReviewCase) -> bool:
|
||||
"""仅回填从旧中间结果生成的空白草稿,绝不覆盖人工编辑。"""
|
||||
"""仅回填未被人工编辑的机器初始化空草稿,不依赖可能被校验替换的问题码。"""
|
||||
draft = case.current_draft
|
||||
if draft is None or draft.header_values_json or draft.lines_json:
|
||||
if (
|
||||
draft is None
|
||||
or case.status not in _REPAIRABLE_CASE_STATUSES
|
||||
or int(draft.draft_version or 0) != 1
|
||||
or draft.header_values_json
|
||||
or draft.lines_json
|
||||
):
|
||||
return False
|
||||
issues = list(draft.issue_summary_json or [])
|
||||
return any(str(item.get('code') or '') == 'machine_order_unavailable' for item in issues if isinstance(item, dict))
|
||||
reason = draft.change_reason_json if isinstance(draft.change_reason_json, dict) else {}
|
||||
return str(reason.get('source') or '') in {'machine_initialization', 'machine_result_backfill'}
|
||||
|
||||
|
||||
def _backfill_existing_case_from_ready_unit(
|
||||
*,
|
||||
run: ShippingOrderProcessingRun,
|
||||
unit: ShippingOrderProcessingUnit,
|
||||
case: ShippingOrderReviewCase,
|
||||
) -> None:
|
||||
"""
|
||||
在 Unit 最终结果与唯一 Candidate 到齐后修复历史/竞态空 Case,保护人工草稿。
|
||||
|
||||
核心逻辑:仅可给未终态 Case 补唯一当前 Candidate;机器 Draft 仅在版本 1、
|
||||
来源仍为机器初始化且内容为空时覆盖。Candidate 与 Draft 的修复分别审计。
|
||||
|
||||
Args:
|
||||
run: Case 所属 Run。
|
||||
unit: 已进入 candidate_ready/review_required 的当前 PDF Unit。
|
||||
case: 按 unit_id 唯一定位并锁定语义的既有 Case。
|
||||
"""
|
||||
candidate_id = _single_candidate_id(run, unit)
|
||||
if (
|
||||
case.candidate_id is None
|
||||
and candidate_id is not None
|
||||
and case.status in _REPAIRABLE_CASE_STATUSES
|
||||
):
|
||||
case.candidate_id = candidate_id
|
||||
db.session.add(ShippingOrderReviewCaseEvent(
|
||||
case_id=int(case.id), event_type='candidate_linked_after_unit_persist',
|
||||
draft_version=int(case.current_draft.draft_version) if case.current_draft is not None else None,
|
||||
actor_user_id=None,
|
||||
operation_json={'document_id': int(unit.document_id), 'candidate_id': candidate_id},
|
||||
))
|
||||
if _can_backfill_machine_draft(case):
|
||||
header, lines, issues = _initial_draft_payload(run, unit)
|
||||
if header or lines:
|
||||
case.current_draft.header_values_json = header
|
||||
case.current_draft.lines_json = lines
|
||||
case.current_draft.issue_summary_json = issues
|
||||
case.current_draft.change_reason_json = {'source': 'machine_result_backfill'}
|
||||
db.session.add(ShippingOrderReviewCaseEvent(
|
||||
case_id=int(case.id), event_type='machine_result_backfilled',
|
||||
draft_version=int(case.current_draft.draft_version), actor_user_id=None,
|
||||
operation_json={'document_id': int(unit.document_id)},
|
||||
))
|
||||
elif case.current_draft is not None and _restore_machine_source_case(
|
||||
case.current_draft.header_values_json or {}, list(case.current_draft.lines_json or []),
|
||||
):
|
||||
# JSON columns do not detect nested dict mutations automatically.
|
||||
flag_modified(case.current_draft, 'header_values_json')
|
||||
flag_modified(case.current_draft, 'lines_json')
|
||||
db.session.add(ShippingOrderReviewCaseEvent(
|
||||
case_id=int(case.id), event_type='machine_source_case_restored',
|
||||
draft_version=int(case.current_draft.draft_version), actor_user_id=None,
|
||||
operation_json={'document_id': int(unit.document_id)},
|
||||
))
|
||||
_ensure_order_task_for_case_candidate(run, candidate_id=case.candidate_id)
|
||||
|
||||
|
||||
def ensure_review_case_for_unit(
|
||||
*,
|
||||
run: ShippingOrderProcessingRun,
|
||||
unit: ShippingOrderProcessingUnit,
|
||||
) -> ShippingOrderReviewCase | None:
|
||||
"""
|
||||
为一个已就绪 PDF Unit 幂等创建或修复唯一复核 Case。
|
||||
|
||||
核心逻辑:pending/routing/extracting 等未收敛 Unit 直接跳过;Candidate 持久化
|
||||
调用方只推进当前 Unit,避免任意 N 个并行 PDF 相互提前创建空 Case。
|
||||
|
||||
Args:
|
||||
run: Unit 所属订单抽取 Run。
|
||||
unit: 当前完成落库的 PDF Unit,必须属于 run.extraction_plan。
|
||||
|
||||
Returns:
|
||||
已创建/修复的 Case;Unit 未就绪或不是 PDF 时返回 None。
|
||||
"""
|
||||
if (
|
||||
run.extraction_plan is None
|
||||
or int(unit.plan_id) != int(run.extraction_plan.id)
|
||||
or str(unit.status or '') not in _REVIEW_CASE_READY_UNIT_STATUSES
|
||||
or not _is_pdf_unit(run, unit)
|
||||
):
|
||||
return None
|
||||
case = ShippingOrderReviewCase.query.filter_by(unit_id=int(unit.id)).first()
|
||||
if case is not None:
|
||||
_backfill_existing_case_from_ready_unit(run=run, unit=unit, case=case)
|
||||
db.session.flush()
|
||||
return case
|
||||
|
||||
header, lines, issues = _initial_draft_payload(run, unit)
|
||||
candidate_id = _single_candidate_id(run, unit)
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no=f'SORC-{uuid.uuid4().hex[:16].upper()}',
|
||||
run_id=int(run.id), unit_id=int(unit.id), document_id=int(unit.document_id),
|
||||
candidate_id=candidate_id, owner_user_id=int(run.user_id), status='unreviewed',
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
draft = ShippingOrderReviewDraft(
|
||||
case_id=int(case.id), schema_version_id=int(run.schema_version_id),
|
||||
header_values_json=header, lines_json=lines, issue_summary_json=issues,
|
||||
validation_result_json={'status': 'not_validated'},
|
||||
change_reason_json={'source': 'machine_initialization'},
|
||||
)
|
||||
db.session.add(draft)
|
||||
db.session.flush()
|
||||
case.current_draft_id = int(draft.id)
|
||||
db.session.add(ShippingOrderReviewCaseEvent(
|
||||
case_id=int(case.id), event_type='case_initialized', draft_version=1,
|
||||
actor_user_id=None,
|
||||
operation_json={'candidate_linked': candidate_id is not None, 'issue_count': len(issues)},
|
||||
))
|
||||
_ensure_order_task_for_case_candidate(run, candidate_id=candidate_id)
|
||||
db.session.flush()
|
||||
return case
|
||||
|
||||
|
||||
def ensure_run_review_cases(*, run: ShippingOrderProcessingRun) -> list[ShippingOrderReviewCase]:
|
||||
"""为 Run 的每个 PDF Unit 幂等初始化唯一 Case 和 Draft,供 Worker 结果持久化后调用。"""
|
||||
"""
|
||||
为 Run 的每个 PDF Unit 幂等初始化唯一 Case 和 Draft,供 Worker 结果持久化后调用。
|
||||
|
||||
核心逻辑:仅对 candidate_ready/review_required Unit 调用单 Unit 入口;新建/已有
|
||||
Case 在关联 Candidate 后幂等预建 OT,再统一绑定 WorkflowItem。未完成 PDF 必须跳过。
|
||||
"""
|
||||
plan = run.extraction_plan
|
||||
if plan is None:
|
||||
return []
|
||||
cases: list[ShippingOrderReviewCase] = []
|
||||
for unit in plan.units:
|
||||
if not _is_pdf_unit(run, unit):
|
||||
continue
|
||||
case = ShippingOrderReviewCase.query.filter_by(unit_id=int(unit.id)).first()
|
||||
case = ensure_review_case_for_unit(run=run, unit=unit)
|
||||
if case is not None:
|
||||
if _can_backfill_machine_draft(case):
|
||||
header, lines, issues = _initial_draft_payload(run, unit)
|
||||
if header or lines:
|
||||
# 旧 Case 在 Unit 尚未写入最终结果时已初始化;只修复这种空白机器草稿。
|
||||
case.current_draft.header_values_json = header
|
||||
case.current_draft.lines_json = lines
|
||||
case.current_draft.issue_summary_json = issues
|
||||
case.current_draft.change_reason_json = {
|
||||
'source': 'machine_result_backfill',
|
||||
}
|
||||
db.session.add(ShippingOrderReviewCaseEvent(
|
||||
case_id=int(case.id), event_type='machine_result_backfilled',
|
||||
draft_version=int(case.current_draft.draft_version), actor_user_id=None,
|
||||
operation_json={'document_id': int(unit.document_id)},
|
||||
))
|
||||
elif _restore_machine_source_case(
|
||||
case.current_draft.header_values_json or {}, list(case.current_draft.lines_json or []),
|
||||
):
|
||||
# JSON columns do not detect nested dict mutations automatically.
|
||||
flag_modified(case.current_draft, 'header_values_json')
|
||||
flag_modified(case.current_draft, 'lines_json')
|
||||
db.session.add(ShippingOrderReviewCaseEvent(
|
||||
case_id=int(case.id), event_type='machine_source_case_restored',
|
||||
draft_version=int(case.current_draft.draft_version), actor_user_id=None,
|
||||
operation_json={'document_id': int(unit.document_id)},
|
||||
))
|
||||
cases.append(case)
|
||||
continue
|
||||
header, lines, issues = _initial_draft_payload(run, unit)
|
||||
candidate_id = _single_candidate_id(run, unit)
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no=f'SORC-{uuid.uuid4().hex[:16].upper()}',
|
||||
run_id=int(run.id), unit_id=int(unit.id), document_id=int(unit.document_id),
|
||||
candidate_id=candidate_id, owner_user_id=int(run.user_id),
|
||||
status='unreviewed',
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
draft = ShippingOrderReviewDraft(
|
||||
case_id=int(case.id), schema_version_id=int(run.schema_version_id),
|
||||
header_values_json=header, lines_json=lines, issue_summary_json=issues,
|
||||
validation_result_json={'status': 'not_validated'}, change_reason_json={'source': 'machine_initialization'},
|
||||
)
|
||||
db.session.add(draft)
|
||||
db.session.flush()
|
||||
case.current_draft_id = int(draft.id)
|
||||
db.session.add(ShippingOrderReviewCaseEvent(
|
||||
case_id=int(case.id), event_type='case_initialized', draft_version=1,
|
||||
actor_user_id=None, operation_json={'candidate_linked': candidate_id is not None, 'issue_count': len(issues)},
|
||||
))
|
||||
cases.append(case)
|
||||
db.session.flush()
|
||||
# [STEP] WorkflowItem 绑定:同会话多 PDF 各一条;重识别复用并切换当前版本。
|
||||
from app.services.shipping_notice.workflow_ledger_service import bind_cases_for_run
|
||||
|
||||
@@ -4,12 +4,11 @@ services/shipping_notice/order_stp_auto_create_service.py
|
||||
用途:对未人工改脏且 Candidate Qualification 合格的复核 Case 执行幂等 STP 自动建单。
|
||||
依赖:order_review_confirmation_service、draft 资格校验(含 can_auto_create)、
|
||||
candidate_qualification_service、tool_common(紧急停止 / XFA shadow)、
|
||||
fulfillment_audit。
|
||||
fulfillment_audit、xfa_validation(发布后视觉可发布性再验)。
|
||||
逻辑:由抽取单元提交 / Run 收尾在 ensure_run_review_cases 之后调用;
|
||||
先持久化资格快照;有人工字段覆盖、资格未 ready 或 can_auto_create=false 则跳过;
|
||||
XFA 与坐标路径共用 Schema/CQ 自动建单总开关;STP 入口再校验 shadow、盲测、白名单与证据;
|
||||
每单成功后与建单同事务入队 shipping_notice_run,再 commit;成功/失败审计均 strict;
|
||||
幂等重试不重复创建 Task;紧急停止只阻断新建,不删除审计事实。
|
||||
XFA 与坐标路径共用 Schema/CQ 自动建单总开关;STP 入口再校验 shadow、盲测、白名单、
|
||||
证据,以及已发布 Profile checksum + 视觉绑定可发布性;失败一律 needs_review。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -120,6 +119,77 @@ def _is_xfa_case(*, candidate: ShippingOrderCandidate | None, validation: dict[s
|
||||
return str(getattr(candidate, 'extraction_source', '') or '').lower() in {'xfa', 'xfa_dataset'}
|
||||
|
||||
|
||||
def _revalidate_published_xfa_profile(*, validation: dict[str, Any]) -> tuple[bool, str | None]:
|
||||
"""
|
||||
自动建单前重验已发布 XFA Profile 的 checksum 与视觉可发布性。
|
||||
|
||||
核心逻辑:从资格 parser_trace 读取 profile_id/checksum → 加载 published 行 →
|
||||
比对 structure_fingerprint/checksum → 对 definition.bindings 执行正式字段视觉门禁。
|
||||
|
||||
Args:
|
||||
validation: Case draft 资格校验结果。
|
||||
|
||||
Returns:
|
||||
(允许?, 阻断原因码);非 XFA 或缺 profile 引用时放行由上层其它门禁负责。
|
||||
"""
|
||||
qualification = (
|
||||
validation.get('qualification')
|
||||
if isinstance(validation.get('qualification'), dict)
|
||||
else {}
|
||||
)
|
||||
trace = qualification.get('parser_trace') if isinstance(qualification.get('parser_trace'), dict) else {}
|
||||
profile_id = trace.get('profile_id')
|
||||
expected_checksum = str(trace.get('profile_checksum') or '').strip()
|
||||
if profile_id is None or not expected_checksum:
|
||||
return True, None
|
||||
|
||||
from app.models import ShippingOrderDocumentProfile
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XfaUnifiedFieldBinding,
|
||||
is_formal_binding_publishable,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_validation import (
|
||||
collect_formal_schema_field_ids,
|
||||
compute_visual_coverage_rate,
|
||||
)
|
||||
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if profile is None or str(profile.status or '') != 'published':
|
||||
return False, 'xfa_profile_checksum_mismatch'
|
||||
actual = str(profile.checksum or profile.structure_fingerprint or '').strip()
|
||||
if actual != expected_checksum:
|
||||
return False, 'xfa_profile_checksum_mismatch'
|
||||
|
||||
definition = dict(profile.definition_json or {})
|
||||
if str(definition.get('template_mode') or profile.template_mode or '') != 'xfa_dataset':
|
||||
return True, None
|
||||
|
||||
schema_field_ids = {
|
||||
str(item.get('field_id') or '')
|
||||
for item in ((profile.schema_version.definition_json or {}).get('fields') or [])
|
||||
if isinstance(item, dict) and item.get('enabled', True) and item.get('field_id')
|
||||
}
|
||||
formal_ids = collect_formal_schema_field_ids(definition, schema_field_ids=schema_field_ids or None)
|
||||
bindings = definition.get('bindings') if isinstance(definition.get('bindings'), list) else []
|
||||
if formal_ids and not bindings:
|
||||
return False, 'xfa_visual_not_publishable'
|
||||
publishable: set[str] = set()
|
||||
for raw in bindings:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
try:
|
||||
binding = XfaUnifiedFieldBinding.model_validate(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if is_formal_binding_publishable(binding):
|
||||
publishable.add(str(binding.field_id))
|
||||
if formal_ids - publishable:
|
||||
return False, 'xfa_visual_not_publishable'
|
||||
if compute_visual_coverage_rate(definition, schema_field_ids=schema_field_ids or None) < 1.0:
|
||||
return False, 'xfa_visual_not_publishable'
|
||||
return True, None
|
||||
|
||||
|
||||
def _xfa_stp_precheck(*, validation: dict[str, Any]) -> tuple[bool, str | None]:
|
||||
"""
|
||||
XFA 路径建单前再次执行试点硬门禁(防御 CQ 快照与配置漂移)。
|
||||
@@ -190,6 +260,18 @@ def _xfa_stp_precheck(*, validation: dict[str, Any]) -> tuple[bool, str | None]:
|
||||
return False, _first_matching(allowlist_reasons, 'xfa_allowlist_unconfigured')
|
||||
if gates.get('xfa_evidence_integrity') is False:
|
||||
return False, _first_matching(evidence_reasons, 'xfa_evidence_incomplete')
|
||||
if gates.get('xfa_unified_profile_snapshot') is False:
|
||||
return False, _first_matching({
|
||||
'xfa_visual_coverage_insufficient',
|
||||
'xfa_evidence_retention_insufficient',
|
||||
'xfa_mirror_consistency_insufficient',
|
||||
'xfa_profile_checksum_mismatch',
|
||||
'xfa_visual_not_publishable',
|
||||
}, 'xfa_visual_not_publishable')
|
||||
|
||||
profile_ok, profile_reason = _revalidate_published_xfa_profile(validation=validation)
|
||||
if not profile_ok:
|
||||
return False, profile_reason
|
||||
return True, None
|
||||
|
||||
|
||||
|
||||
@@ -7,7 +7,8 @@ backend/app/services/shipping_notice/order_task_service.py
|
||||
逻辑:Candidate 形成后按显式 task_no / Run.user_task_no 幂等 upsert OT(创建写 order_task_created);
|
||||
upsert 禁止跨 Candidate 覆盖 candidate_id;复核确认走 replace_order_task_candidate_after_review;
|
||||
局部重识别走 replace_order_task_candidate_after_reparse(专用审计);
|
||||
sync_order_task_processing_state 统一写入 stage/status 并递增 progress_version;
|
||||
sync_order_task_processing_state 统一写入 stage/status、递增 progress_version,
|
||||
并强制写 order_task_progress_changed 审计;
|
||||
建单成功后按 candidate_id 定位 OT 再挂 shipping_notice_id(禁止误用 Run 根号串单);
|
||||
GET 投影只读本表,禁止读路径创建。
|
||||
"""
|
||||
@@ -26,17 +27,17 @@ if TYPE_CHECKING:
|
||||
|
||||
|
||||
def _status_from_run(run: ShippingOrderProcessingRun) -> str:
|
||||
"""将 Extraction Run 状态映射为 OT 投影状态。"""
|
||||
status = str(getattr(run, 'status', None) or '').strip()
|
||||
if status in {'completed', 'partially_completed'}:
|
||||
return 'completed'
|
||||
if status == 'failed':
|
||||
return 'failed'
|
||||
if status == 'cancelled':
|
||||
return 'cancelled'
|
||||
if status == 'review_required':
|
||||
return 'waiting_review'
|
||||
return 'processing'
|
||||
"""
|
||||
将 Extraction Run 状态映射为 OT 投影状态。
|
||||
|
||||
核心逻辑:识别 Run completed ≠ 全流程 completed;review_required → waiting_review。
|
||||
"""
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
derivation_status_for_extraction_run,
|
||||
)
|
||||
|
||||
stage = str(getattr(run, 'current_stage_code', None) or getattr(run, 'phase', None) or '').strip()
|
||||
return derivation_status_for_extraction_run(str(getattr(run, 'status', None) or ''), stage=stage or None)
|
||||
|
||||
|
||||
def sync_order_task_processing_state(
|
||||
@@ -45,38 +46,110 @@ def sync_order_task_processing_state(
|
||||
stage: str | None = None,
|
||||
status: str | None = None,
|
||||
bump_progress: bool = True,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
reason_code: str | None = None,
|
||||
reason: str | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
source: str | None = None,
|
||||
correlation_id: str | None = None,
|
||||
) -> ShippingOrderTask:
|
||||
"""
|
||||
同步 OT 上的统一进度 stage/status,并可选递增 progress_version。
|
||||
|
||||
【触发时机】候选形成、库存源阻断、确认建单、履约阶段回退等写路径。
|
||||
|
||||
核心逻辑:仅在值变化时写入;bump_progress=True 时 progress_version+1,
|
||||
保证四页面刷新后看到同一版本。
|
||||
核心逻辑:仅在值变化时写入;bump_progress=True 时 progress_version+1;
|
||||
每次真实变更强制写入 order_task_progress_changed 审计(前后 stage/status、
|
||||
操作主体、原因码、progress_version、request_id)。
|
||||
|
||||
Args:
|
||||
order_task: 正式任务聚合根。
|
||||
stage: 统一 ShippingProcessingStage;None 表示不改。
|
||||
status: OT 投影 status;None 表示不改。
|
||||
bump_progress: 是否递增乐观并发版本。
|
||||
actor_type/actor_id: 操作主体(默认 system)。
|
||||
reason_code/reason: 变更原因(码 + 可选说明)。
|
||||
request_id/operation_id/correlation_id: 请求与幂等关联键。
|
||||
source: 写路径来源模块标识。
|
||||
|
||||
Returns:
|
||||
同一 order_task 引用(已 flush)。
|
||||
"""
|
||||
from flask import g, has_request_context
|
||||
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
changed = False
|
||||
before_stage = str(order_task.stage or '').strip() or None
|
||||
before_status = str(order_task.status or '').strip() or None
|
||||
before_version = int(order_task.progress_version or 1)
|
||||
next_stage = str(stage or '').strip() or None
|
||||
next_status = str(status or '').strip() or None
|
||||
if next_stage is not None and str(order_task.stage or '') != next_stage:
|
||||
if next_stage is not None and before_stage != next_stage:
|
||||
order_task.stage = next_stage
|
||||
changed = True
|
||||
if next_status is not None and str(order_task.status or '') != next_status:
|
||||
if next_status is not None and before_status != next_status:
|
||||
order_task.status = next_status
|
||||
changed = True
|
||||
if changed and bump_progress:
|
||||
order_task.progress_version = int(order_task.progress_version or 1) + 1
|
||||
order_task.progress_version = before_version + 1
|
||||
if changed:
|
||||
order_task.updated_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
# [BE-06] 中央写入口强制审计,禁止静默推进 stage/status。
|
||||
resolved_request_id = request_id
|
||||
if resolved_request_id is None and has_request_context():
|
||||
resolved_request_id = getattr(g, 'request_id', None)
|
||||
# [BE-01] 审计 after 附带当次 stage_nodes 快照,形成进度变更可追溯账本;
|
||||
# 节点仍由权威 stage/status 推导,但每次写路径变更均落库审计。
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
build_stage_nodes,
|
||||
)
|
||||
|
||||
after_stage = str(order_task.stage or '').strip() or None
|
||||
after_status = str(order_task.status or '').strip() or None
|
||||
stage_nodes_snapshot = build_stage_nodes(
|
||||
stage=after_stage or 'upload_received',
|
||||
status=after_status or 'processing',
|
||||
source_type=str(getattr(order_task, 'source_type', None) or '') or None,
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type='order_task_progress_changed',
|
||||
aggregate_type='shipping_order_task',
|
||||
aggregate_id=str(order_task.task_no),
|
||||
task_no=str(order_task.task_no),
|
||||
actor_type=str(actor_type or 'system'),
|
||||
actor_id=actor_id,
|
||||
owner_user_id=getattr(order_task, 'user_id', None),
|
||||
conversation_id=str(getattr(order_task, 'conversation_id', None) or '') or None,
|
||||
request_id=str(resolved_request_id or '') or None,
|
||||
operation_id=str(operation_id or '') or None,
|
||||
correlation_id=str(correlation_id or '') or None,
|
||||
action='sync_order_task_processing_state',
|
||||
reason_code=str(reason_code or 'progress_sync').strip() or 'progress_sync',
|
||||
reason=reason,
|
||||
before={
|
||||
'stage': before_stage,
|
||||
'status': before_status,
|
||||
'progress_version': before_version,
|
||||
},
|
||||
after={
|
||||
'stage': after_stage,
|
||||
'status': after_status,
|
||||
'progress_version': int(order_task.progress_version or 1),
|
||||
'stage_nodes': stage_nodes_snapshot,
|
||||
},
|
||||
metadata={
|
||||
'extraction_run_id': getattr(order_task, 'extraction_run_id', None),
|
||||
'shipping_notice_id': getattr(order_task, 'shipping_notice_id', None),
|
||||
'candidate_id': getattr(order_task, 'candidate_id', None),
|
||||
},
|
||||
source=str(source or 'order_task_service'),
|
||||
result='success',
|
||||
sensitivity_level='normal',
|
||||
)
|
||||
return order_task
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
"""
|
||||
services/shipping_notice/order_task_stage_machine.py
|
||||
|
||||
用途:在写路径上推进统一 15 阶 stage/status,使进度成为业务事实而非仅投影启发式。
|
||||
依赖:order_task_service.sync_order_task_processing_state、progress_audit_contract、
|
||||
ShippingOrderTask / ShippingOrderCandidate / ShippingNotice /
|
||||
ShippingOrderProcessingRun.progress_summary_json。
|
||||
逻辑:Candidate 前写入 Run.progress_summary_json.processing_stage;
|
||||
Candidate 后写入 OT.stage;履约期按 Notice 回写 OT。
|
||||
投影层优先读已写入事实,禁止再靠启发式猜早期阶段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.order_task_service import (
|
||||
resolve_order_task_for_candidate,
|
||||
sync_order_task_processing_state,
|
||||
)
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
DIRECT_PDF_ALLOWED_STAGES,
|
||||
EML_ONLY_PROCESSING_STAGES,
|
||||
ORDER_INTAKE_SOURCE_TYPES,
|
||||
SHIPPING_PROCESSING_STAGES,
|
||||
)
|
||||
|
||||
# 抽取进度事件 → 统一早期/候选阶段(Candidate 形成前写在 Run 上)。
|
||||
_PROGRESS_EVENT_TO_PROCESSING_STAGE: dict[str, str] = {
|
||||
'plan_created': 'upload_received',
|
||||
'document_queued': 'document_parsing',
|
||||
'layout_parsing_started': 'document_parsing',
|
||||
'layout_parsing_completed': 'document_parsing',
|
||||
'initial_wave_started': 'document_parsing',
|
||||
'expansion_wave_started': 'document_parsing',
|
||||
'profile_matching': 'document_parsing',
|
||||
'profile_candidates_scored': 'document_parsing',
|
||||
'profile_auto_selected': 'document_parsing',
|
||||
'profile_ambiguous': 'document_parsing',
|
||||
'profile_drift_detected': 'document_parsing',
|
||||
'profile_matched': 'document_parsing',
|
||||
'table_reconstructed': 'document_parsing',
|
||||
'generic_extraction_completed': 'document_parsing',
|
||||
'generic_gate_evaluated': 'document_parsing',
|
||||
'order_fields_extracted': 'document_parsing',
|
||||
'email_supplement_merged': 'email_adjudicating',
|
||||
'llm_review_requested': 'document_parsing',
|
||||
'llm_review_received': 'document_parsing',
|
||||
'llm_suggestion_validated': 'document_parsing',
|
||||
'technical_retrying': 'document_parsing',
|
||||
'candidate_ready': 'candidate_creating',
|
||||
'review_required': 'waiting_review',
|
||||
'review_confirmed': 'order_creating',
|
||||
'order_auto_frozen': 'order_creating',
|
||||
'run_completed': 'candidate_creating',
|
||||
}
|
||||
|
||||
|
||||
def _clamp_early_stage(stage: str, *, source_type: str | None) -> str:
|
||||
"""
|
||||
将早期 stage 约束到冻结词典;direct_pdf 禁止 email_*。
|
||||
|
||||
Args:
|
||||
stage: 候选统一 stage。
|
||||
source_type: eml / direct_pdf / None。
|
||||
|
||||
Returns:
|
||||
合法 SHIPPING_PROCESSING_STAGES 成员。
|
||||
"""
|
||||
normalized = str(stage or '').strip().lower()
|
||||
if normalized not in SHIPPING_PROCESSING_STAGES:
|
||||
normalized = 'document_parsing'
|
||||
source = str(source_type or '').strip().lower() or None
|
||||
if source and source not in ORDER_INTAKE_SOURCE_TYPES:
|
||||
source = None
|
||||
if source == 'direct_pdf':
|
||||
if normalized in EML_ONLY_PROCESSING_STAGES:
|
||||
normalized = 'document_parsing'
|
||||
if normalized not in DIRECT_PDF_ALLOWED_STAGES:
|
||||
normalized = 'document_parsing'
|
||||
return normalized
|
||||
|
||||
|
||||
def resolve_processing_stage_for_progress_event(
|
||||
event_code: str,
|
||||
*,
|
||||
source_type: str | None = None,
|
||||
) -> str | None:
|
||||
"""
|
||||
将抽取进度事件码映射为统一 ShippingProcessingStage。
|
||||
|
||||
【触发时机】record_order_extraction_progress_event 更新 Run 投影时。
|
||||
|
||||
核心逻辑:查事件→阶段表;email_supplement_merged 对 eml 为 email_adjudicating,
|
||||
对 direct_pdf 折叠为 candidate_creating;未知事件返回 None(不覆盖已有写入)。
|
||||
|
||||
Args:
|
||||
event_code: WORKSPACE 进度事件码。
|
||||
source_type: Intake 来源 eml|direct_pdf。
|
||||
|
||||
Returns:
|
||||
统一 stage;事件无映射时 None。
|
||||
"""
|
||||
code = str(event_code or '').strip().lower()
|
||||
if not code:
|
||||
return None
|
||||
mapped = _PROGRESS_EVENT_TO_PROCESSING_STAGE.get(code)
|
||||
if not mapped:
|
||||
return None
|
||||
source = str(source_type or '').strip().lower() or None
|
||||
if code == 'email_supplement_merged' and source == 'direct_pdf':
|
||||
mapped = 'candidate_creating'
|
||||
if code == 'plan_created' and source == 'eml':
|
||||
# 邮件接入刚建计划时优先标 email_parsing,随后 layout 事件推进到 document_parsing。
|
||||
mapped = 'email_parsing'
|
||||
return _clamp_early_stage(mapped, source_type=source)
|
||||
|
||||
|
||||
def read_run_unified_processing_stage(run: Any) -> str | None:
|
||||
"""
|
||||
读取 Run 上已写入的统一 processing_stage 事实。
|
||||
|
||||
核心逻辑:仅认 progress_summary_json.processing_stage;非法码视为未写入。
|
||||
|
||||
Args:
|
||||
run: ShippingOrderProcessingRun 或兼容对象。
|
||||
|
||||
Returns:
|
||||
合法 stage;无写入时 None。
|
||||
"""
|
||||
summary = getattr(run, 'progress_summary_json', None)
|
||||
if not isinstance(summary, dict):
|
||||
return None
|
||||
stage = str(summary.get('processing_stage') or '').strip().lower()
|
||||
if stage in SHIPPING_PROCESSING_STAGES:
|
||||
return stage
|
||||
return None
|
||||
|
||||
|
||||
def write_run_unified_processing_stage(
|
||||
run: ShippingOrderProcessingRun,
|
||||
stage: str,
|
||||
*,
|
||||
source_type: str | None = None,
|
||||
) -> str:
|
||||
"""
|
||||
将统一 stage 写入 Run.progress_summary_json(Candidate 前权威事实)。
|
||||
|
||||
【触发时机】进度事件投影更新;迟到事件不得回退更后的 stage(由调用方保证)。
|
||||
|
||||
Args:
|
||||
run: 抽取 Run。
|
||||
stage: 统一 stage 码。
|
||||
source_type: 用于 direct_pdf clamp。
|
||||
|
||||
Returns:
|
||||
实际写入的 stage。
|
||||
"""
|
||||
clamped = _clamp_early_stage(stage, source_type=source_type)
|
||||
summary = (
|
||||
dict(run.progress_summary_json)
|
||||
if isinstance(run.progress_summary_json, dict)
|
||||
else {}
|
||||
)
|
||||
summary['processing_stage'] = clamped
|
||||
run.progress_summary_json = summary
|
||||
return clamped
|
||||
|
||||
|
||||
def source_type_hint_from_run(run: Any) -> str | None:
|
||||
"""
|
||||
从 Run 快照轻量推断 source_type(避免写路径额外查库)。
|
||||
|
||||
Args:
|
||||
run: ShippingOrderProcessingRun。
|
||||
|
||||
Returns:
|
||||
eml|direct_pdf|None。
|
||||
"""
|
||||
snapshot = getattr(run, 'input_snapshot_json', None)
|
||||
if not isinstance(snapshot, dict):
|
||||
return None
|
||||
for row in snapshot.get('intakes') or []:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
source = str(row.get('source_type') or '').strip().lower() or None
|
||||
if source in ORDER_INTAKE_SOURCE_TYPES:
|
||||
return source
|
||||
return None
|
||||
|
||||
|
||||
def resolve_pre_confirm_stage(
|
||||
*,
|
||||
candidate: ShippingOrderCandidate | None = None,
|
||||
evaluation: dict[str, Any] | None = None,
|
||||
prefer_waiting_review: bool = False,
|
||||
) -> tuple[str, str]:
|
||||
"""
|
||||
根据 Candidate 资格评估结果解析确认建单前的 OT (stage, status)。
|
||||
|
||||
核心逻辑:客户未确认 → customer_resolving;查重未清 → duplicate_checking;
|
||||
库存源阻断 → inventory_source_resolving;否则 waiting_review。
|
||||
prefer_waiting_review 仅在无阻断时抬升到 waiting_review,不得覆盖前置业务阻断。
|
||||
|
||||
Args:
|
||||
candidate: 可选 Candidate(读 structured_result / duplicate 字段兜底)。
|
||||
evaluation: evaluate/recalculate 返回的评估 dict。
|
||||
prefer_waiting_review: True 时,在资格无阻断时落到 waiting_review(复核 Case 场景)。
|
||||
|
||||
Returns:
|
||||
(stage, status) 均属统一词典。
|
||||
"""
|
||||
eval_payload = dict(evaluation or {})
|
||||
blocking = {
|
||||
str(code).strip().lower()
|
||||
for code in (eval_payload.get('blocking_reason_codes') or [])
|
||||
if str(code).strip()
|
||||
}
|
||||
gates = eval_payload.get('gates') if isinstance(eval_payload.get('gates'), dict) else {}
|
||||
|
||||
customer_ok = bool(gates.get('customer_confirmed'))
|
||||
if eval_payload and 'customer_confirmed' not in gates:
|
||||
# 无 gates 时看 blocking 码。
|
||||
customer_ok = not any('customer' in code for code in blocking)
|
||||
if candidate is not None and not eval_payload:
|
||||
structured = dict(getattr(candidate, 'structured_result_json', None) or {})
|
||||
customer = structured.get('customer') if isinstance(structured.get('customer'), dict) else {}
|
||||
customer_ok = str(customer.get('resolution_status') or '').strip().lower() == 'confirmed'
|
||||
if not customer_ok or any(code.startswith('customer') for code in blocking):
|
||||
return 'customer_resolving', 'waiting_review'
|
||||
|
||||
duplicate_ok = bool(gates.get('duplicate_resolved', True))
|
||||
if candidate is not None and not eval_payload:
|
||||
dup = str(getattr(candidate, 'duplicate_status', '') or '').strip().lower()
|
||||
duplicate_ok = dup in {'', 'none', 'not_duplicate', 'clear', 'resolved'}
|
||||
if not duplicate_ok or any('duplicate' in code for code in blocking):
|
||||
return 'duplicate_checking', 'waiting_review'
|
||||
|
||||
if any('inventory' in code for code in blocking):
|
||||
return 'inventory_source_resolving', 'waiting_review'
|
||||
|
||||
# [BE-02] prefer_waiting_review 不得跳过客户/查重/库存源阻断;无阻断时才落到复核。
|
||||
return 'waiting_review', 'waiting_review'
|
||||
|
||||
|
||||
def sync_order_task_stage_for_candidate(
|
||||
*,
|
||||
candidate: ShippingOrderCandidate,
|
||||
evaluation: dict[str, Any] | None = None,
|
||||
prefer_waiting_review: bool = False,
|
||||
order_task: ShippingOrderTask | None = None,
|
||||
) -> ShippingOrderTask | None:
|
||||
"""
|
||||
将 Candidate 对应 OT 推进到确认前正确 stage。
|
||||
|
||||
【触发时机】Candidate 形成后、资格重算后、Case 预建 OT 后。
|
||||
|
||||
Args:
|
||||
candidate: 已落库 Candidate。
|
||||
evaluation: 可选资格评估结果。
|
||||
prefer_waiting_review: 复核 Case 场景。
|
||||
order_task: 可选已加载 OT;缺省按 candidate_id 解析。
|
||||
|
||||
Returns:
|
||||
更新后的 OT;无 OT 时 None。
|
||||
"""
|
||||
ot = order_task or resolve_order_task_for_candidate(
|
||||
int(candidate.id) if getattr(candidate, 'id', None) else None
|
||||
)
|
||||
if ot is None:
|
||||
return None
|
||||
stage, status = resolve_pre_confirm_stage(
|
||||
candidate=candidate,
|
||||
evaluation=evaluation,
|
||||
prefer_waiting_review=prefer_waiting_review,
|
||||
)
|
||||
if stage not in SHIPPING_PROCESSING_STAGES:
|
||||
stage = 'waiting_review'
|
||||
return sync_order_task_processing_state(
|
||||
ot,
|
||||
stage=stage,
|
||||
status=status,
|
||||
reason_code='candidate_pre_confirm_sync',
|
||||
source='order_task_stage_machine',
|
||||
)
|
||||
|
||||
|
||||
def sync_order_task_stage_for_notice(
|
||||
notice: ShippingNotice,
|
||||
*,
|
||||
order_task: ShippingOrderTask | None = None,
|
||||
) -> ShippingOrderTask | None:
|
||||
"""
|
||||
按正式 Notice 履约态回写挂接 OT 的 stage/status。
|
||||
|
||||
【触发时机】Excel 生成、货代上传触发/成功、履约状态迁移后。
|
||||
|
||||
核心逻辑:使用领域映射 map_notice_to_processing_status_stage(非投影私有函数),
|
||||
写入 OT 成为权威事实。
|
||||
|
||||
Args:
|
||||
notice: 正式发货通知。
|
||||
order_task: 可选;缺省按 notice.order_task_id / ShippingOrderTask.shipping_notice_id。
|
||||
|
||||
Returns:
|
||||
更新后的 OT;找不到时 None。
|
||||
"""
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
map_notice_to_processing_status_stage,
|
||||
)
|
||||
|
||||
ot = order_task
|
||||
if ot is None and getattr(notice, 'order_task_id', None):
|
||||
ot = db.session.get(ShippingOrderTask, int(notice.order_task_id))
|
||||
if ot is None and getattr(notice, 'id', None):
|
||||
ot = (
|
||||
ShippingOrderTask.query.filter_by(shipping_notice_id=int(notice.id))
|
||||
.order_by(ShippingOrderTask.id.desc())
|
||||
.first()
|
||||
)
|
||||
if ot is None:
|
||||
return None
|
||||
status, stage = map_notice_to_processing_status_stage(notice)
|
||||
if stage not in SHIPPING_PROCESSING_STAGES:
|
||||
stage = 'inventory_matching'
|
||||
return sync_order_task_processing_state(
|
||||
ot,
|
||||
stage=stage,
|
||||
status=status,
|
||||
reason_code='notice_fulfillment_sync',
|
||||
source='order_task_stage_machine',
|
||||
)
|
||||
@@ -477,6 +477,13 @@ PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_scenario_not_allowlisted',
|
||||
'xfa_evidence_incomplete',
|
||||
'xfa_cross_check_failed',
|
||||
'xfa_visual_coverage_insufficient',
|
||||
'xfa_evidence_retention_insufficient',
|
||||
'xfa_mirror_consistency_insufficient',
|
||||
'xfa_profile_checksum_mismatch',
|
||||
'xfa_visual_not_publishable',
|
||||
'xfa_visual_bindings_required',
|
||||
'xfa_visual_binding_incomplete',
|
||||
# 跨门禁技术重试耗尽(不绑定唯一 owning_gate,由当前 Gate 承载)
|
||||
'technical_retry_exhausted',
|
||||
})
|
||||
@@ -546,6 +553,13 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = {
|
||||
'xfa_scenario_not_allowlisted': 'order_freeze_readiness',
|
||||
'xfa_evidence_incomplete': 'order_field_extraction',
|
||||
'xfa_cross_check_failed': 'order_field_extraction',
|
||||
'xfa_visual_coverage_insufficient': 'order_field_extraction',
|
||||
'xfa_evidence_retention_insufficient': 'order_field_extraction',
|
||||
'xfa_mirror_consistency_insufficient': 'order_field_extraction',
|
||||
'xfa_profile_checksum_mismatch': 'order_freeze_readiness',
|
||||
'xfa_visual_not_publishable': 'order_freeze_readiness',
|
||||
'xfa_visual_bindings_required': 'order_freeze_readiness',
|
||||
'xfa_visual_binding_incomplete': 'order_freeze_readiness',
|
||||
'classification_low_confidence': 'order_field_extraction',
|
||||
'field_low_confidence': 'order_field_extraction',
|
||||
'technical_failure_present': 'order_freeze_readiness',
|
||||
@@ -597,6 +611,7 @@ AUTO_BUILD_LEGACY_GATE_OWNING_MAP: Final[dict[str, str]] = {
|
||||
'xfa_profile_blind_approved': 'order_freeze_readiness',
|
||||
'xfa_pilot_allowlist': 'order_freeze_readiness',
|
||||
'xfa_evidence_integrity': 'order_field_extraction',
|
||||
'xfa_unified_profile_snapshot': 'order_field_extraction',
|
||||
# 兼容旧五门键名(历史测试 / 投影)
|
||||
'approved_template': 'order_freeze_readiness',
|
||||
'fields_complete': 'field_completeness',
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
"""
|
||||
services/shipping_notice/processing_projection_invariants.py
|
||||
|
||||
用途:统一 ShippingProcessingProjection 输出前的 status/stage/gate/action 不变量与
|
||||
15 阶节点事实,避免四页面各自推导互相矛盾的进度。
|
||||
依赖:progress_audit_contract(15 阶 / 节点态 / 动作意图词典)。
|
||||
逻辑:由 shipping_processing_projection 与 order_task_stage_machine 共用;不读写数据库;
|
||||
Notice→(status,stage) 领域映射供写/读两侧;Extraction Run 完成 ≠ 全流程 completed;
|
||||
Gate 要求复核时强制 waiting_review;download_excel 依赖 excel_ready;
|
||||
stage_nodes 可表达 invalidated_from_stage 失效。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
EML_ONLY_PROCESSING_STAGES,
|
||||
SHIPPING_PROCESSING_ACTION_INTENTS,
|
||||
SHIPPING_PROCESSING_STAGE_NODE_STATUSES,
|
||||
SHIPPING_PROCESSING_STAGES,
|
||||
SHIPPING_PROCESSING_STATUSES,
|
||||
shipping_processing_stage_index,
|
||||
)
|
||||
|
||||
# 写操作动作:status=completed 时必须剔除。
|
||||
_WRITE_ACTION_CODES = frozenset({
|
||||
'open_order_review',
|
||||
'open_review',
|
||||
'edit_formal_task',
|
||||
'open_inventory_source_review',
|
||||
'open_inventory_match_review',
|
||||
'open_shortage_review',
|
||||
'upload_inventory_file',
|
||||
'retry',
|
||||
'retry_parse',
|
||||
'retry_failed_documents',
|
||||
'regenerate_excel',
|
||||
'open_manual_upload',
|
||||
'wait_manual_upload',
|
||||
'mark_manual_uploaded',
|
||||
'regenerate_manual_upload_todo',
|
||||
'open_fulfillment',
|
||||
})
|
||||
|
||||
# 后端可能发出、需映射到契约意图的别名。
|
||||
_ACTION_CODE_ALIASES: dict[str, str] = {
|
||||
'open_review': 'open_order_review',
|
||||
'open_order_processing': 'open_order_review',
|
||||
'retry_parse': 'retry',
|
||||
'retry_failed_documents': 'retry',
|
||||
'open_fulfillment': 'view_result',
|
||||
'view_details': 'view_result',
|
||||
'wait_manual_upload': 'open_manual_upload',
|
||||
'mark_manual_uploaded': 'open_manual_upload',
|
||||
'regenerate_manual_upload_todo': 'open_manual_upload',
|
||||
# [BE-05] Notice ui_state / Gate 业务动作收口到统一契约意图。
|
||||
'confirm_inventory_source': 'open_inventory_source_review',
|
||||
'retry_resolve_inventory_source': 'open_inventory_source_review',
|
||||
'rematch': 'open_inventory_match_review',
|
||||
'match_inventory': 'open_inventory_match_review',
|
||||
'generate_excel': 'regenerate_excel',
|
||||
'confirm_customer': 'open_order_review',
|
||||
'freeze_order': 'edit_formal_task',
|
||||
}
|
||||
|
||||
|
||||
def normalize_action_code(code: str | None) -> str | None:
|
||||
"""
|
||||
将原始动作码规范为 SHIPPING_PROCESSING_ACTION_INTENTS 可识别的契约码。
|
||||
|
||||
Args:
|
||||
code: Gate / legacy available_actions 原始码。
|
||||
|
||||
Returns:
|
||||
契约动作码;无法映射时返回 None(禁止泄漏未知码)。
|
||||
"""
|
||||
raw = str(code or '').strip().lower()
|
||||
if not raw:
|
||||
return None
|
||||
mapped = _ACTION_CODE_ALIASES.get(raw, raw)
|
||||
if mapped in SHIPPING_PROCESSING_ACTION_INTENTS and mapped != 'none':
|
||||
return mapped
|
||||
return None
|
||||
|
||||
|
||||
def _gate_next_action(gate: dict[str, Any] | None) -> str | None:
|
||||
"""读取 Gate.next_action_code 并规范化。"""
|
||||
if not isinstance(gate, dict):
|
||||
return None
|
||||
return normalize_action_code(
|
||||
str(gate.get('next_action_code') or gate.get('nextActionCode') or '').strip()
|
||||
or None
|
||||
)
|
||||
|
||||
|
||||
def derivation_status_for_extraction_run(run_status: str, *, stage: str | None) -> str:
|
||||
"""
|
||||
将 Extraction Run.status 映射为 OT 业务进度 status。
|
||||
|
||||
核心逻辑:Run completed/partially_completed 仅表示识别结束,不等于履约 completed;
|
||||
若 stage 未到 completed,折叠为 processing / waiting_review。
|
||||
|
||||
Args:
|
||||
run_status: ShippingOrderProcessingRun.status。
|
||||
stage: 已判定的统一 stage(可空)。
|
||||
|
||||
Returns:
|
||||
SHIPPING_PROCESSING_STATUSES 成员。
|
||||
"""
|
||||
status = str(run_status or '').strip().lower()
|
||||
stage_code = str(stage or '').strip().lower()
|
||||
if status == 'failed':
|
||||
return 'failed'
|
||||
if status == 'cancelled':
|
||||
return 'cancelled'
|
||||
if status == 'review_required':
|
||||
return 'waiting_review'
|
||||
if status in {'completed', 'partially_completed'}:
|
||||
if stage_code == 'completed':
|
||||
return 'completed'
|
||||
if stage_code == 'waiting_review':
|
||||
return 'waiting_review'
|
||||
# [BE-03] 识别完成 ≠ 全流程完成。
|
||||
return 'processing'
|
||||
if status in {'queued', 'processing'}:
|
||||
return 'processing'
|
||||
return 'processing' if status not in SHIPPING_PROCESSING_STATUSES else status
|
||||
|
||||
|
||||
def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
|
||||
"""
|
||||
将正式 Notice 履约态映射为统一 (status, stage)。
|
||||
|
||||
【触发时机】写状态机回写 OT、投影组装 order_task 工作项。
|
||||
|
||||
核心逻辑:上传完成 → completed;上传中/待上传 → freight_uploading;
|
||||
导出/Excel → excel_generating;匹配 → inventory_matching;建单/拉库存细分。
|
||||
领域映射唯一来源,禁止写状态机反向依赖投影私有函数。
|
||||
|
||||
Args:
|
||||
notice: ShippingNotice 或具备 process_status/current_step/upload_status 的对象。
|
||||
|
||||
Returns:
|
||||
(ShippingProcessingStatus, ShippingProcessingStage)。
|
||||
"""
|
||||
ps = str(getattr(notice, 'process_status', None) or '').strip().lower()
|
||||
step = str(getattr(notice, 'current_step', None) or '').strip().lower()
|
||||
upload_st = str(getattr(notice, 'upload_status', None) or '').strip().lower()
|
||||
export_path = str(getattr(notice, 'export_file_path', None) or '').strip()
|
||||
|
||||
if ps in {'uploaded', 'closed', 'completed'}:
|
||||
return ('completed', 'completed')
|
||||
if ps in {'waiting_upload', 'upload_failed', 'uploading'} or upload_st == 'uploading':
|
||||
return ('automating', 'freight_uploading')
|
||||
if 'upload' in step or step.startswith('step7'):
|
||||
return ('automating', 'freight_uploading')
|
||||
|
||||
if ps in {'export', 'excel', 'generating_excel'} or 'generate' in step or step.startswith('step6'):
|
||||
return ('automating', 'excel_generating')
|
||||
if ps == 'matched' and export_path:
|
||||
return ('automating', 'excel_generating')
|
||||
|
||||
if ps in {'matching', 'inventory_ready', 'waiting_inventory', 'matched', 'parsed'} or 'match' in step:
|
||||
return ('automating', 'inventory_matching')
|
||||
|
||||
if ps == 'pending_review':
|
||||
return ('waiting_review', 'waiting_review')
|
||||
|
||||
if ps in {'creating', 'order_creating', 'confirming'} or 'create' in step or step.startswith('step3'):
|
||||
return ('automating', 'order_creating')
|
||||
if ps in {'fetching_inventory', 'inventory_fetching'} or 'fetch' in step or step.startswith('step4'):
|
||||
return ('automating', 'inventory_fetching')
|
||||
if ps in {'parsing', 'parsed_pending'}:
|
||||
return ('automating', 'order_creating')
|
||||
# [BE-03] 未知状态 fail-closed:禁止猜测为正常「创建订单中」。
|
||||
return ('blocked', 'waiting_review')
|
||||
|
||||
|
||||
def build_stage_nodes(
|
||||
*,
|
||||
stage: str,
|
||||
status: str,
|
||||
source_type: str | None,
|
||||
invalidated_from_stage: str | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
为 15 阶构建后端权威节点事实(passed/running/blocked/failed/skipped/pending)。
|
||||
|
||||
核心逻辑:direct_pdf 邮件专属阶 → skipped;当前阶前 → passed(失效点之后可 pending);
|
||||
当前阶按投影 status 映射;之后 → pending。
|
||||
[BE-01] 本函数输出为「当前态便捷投影」,依赖权威 stage/status + invalidate;
|
||||
完整时序(开始/完成时间、重试次数)由 OT 进度审计 after.stage_nodes 快照补齐。
|
||||
|
||||
Args:
|
||||
stage: 当前统一 stage。
|
||||
status: 当前统一 status。
|
||||
source_type: eml | direct_pdf | None。
|
||||
invalidated_from_stage: 可选;该阶及之后不得标记 passed(改单失效)。
|
||||
|
||||
Returns:
|
||||
[{stage, absolute_index, status}] 列表,长度恒为 15。
|
||||
"""
|
||||
current_idx = shipping_processing_stage_index(stage)
|
||||
if current_idx is None:
|
||||
current_idx = 0
|
||||
invalidate_idx = shipping_processing_stage_index(invalidated_from_stage)
|
||||
source = str(source_type or '').strip().lower() or None
|
||||
status_norm = str(status or '').strip().lower()
|
||||
nodes: list[dict[str, Any]] = []
|
||||
for idx, code in enumerate(SHIPPING_PROCESSING_STAGES):
|
||||
if source == 'direct_pdf' and code in EML_ONLY_PROCESSING_STAGES:
|
||||
node_status = 'skipped'
|
||||
elif idx < current_idx:
|
||||
if invalidate_idx is not None and idx >= invalidate_idx:
|
||||
node_status = 'pending'
|
||||
else:
|
||||
node_status = 'passed'
|
||||
elif idx > current_idx:
|
||||
node_status = 'pending'
|
||||
else:
|
||||
if status_norm in {'failed', 'cancelled'}:
|
||||
node_status = 'failed'
|
||||
elif status_norm in {'blocked', 'waiting_review'}:
|
||||
node_status = 'blocked'
|
||||
elif status_norm == 'completed' and code == 'completed':
|
||||
node_status = 'passed'
|
||||
elif status_norm in {'automating', 'processing', 'queued'}:
|
||||
node_status = 'running'
|
||||
else:
|
||||
node_status = 'running'
|
||||
if node_status not in SHIPPING_PROCESSING_STAGE_NODE_STATUSES:
|
||||
node_status = 'pending'
|
||||
nodes.append({
|
||||
'stage': code,
|
||||
'absolute_index': idx,
|
||||
'status': node_status,
|
||||
})
|
||||
return nodes
|
||||
|
||||
|
||||
def derive_available_actions(
|
||||
*,
|
||||
status: str,
|
||||
stage: str,
|
||||
gate: dict[str, Any] | None,
|
||||
legacy_actions: list[str] | None = None,
|
||||
excel_ready: bool = False,
|
||||
) -> list[str]:
|
||||
"""
|
||||
由 Gate / Artifact 等业务事实推导 available_actions,禁止仅凭 stage 猜测可下载。
|
||||
|
||||
核心逻辑:Gate next_action 优先;download_excel 仅当 excel_ready;
|
||||
regenerate_excel 仅当处于 excel_generating 且非 automating 且 Excel 未就绪;
|
||||
open_manual_upload 仅当 Gate 或 legacy 明确给出;completed → view_result。
|
||||
|
||||
Args:
|
||||
status: 统一 status。
|
||||
stage: 统一 stage。
|
||||
gate: current_gate 摘要。
|
||||
legacy_actions: 可选旧会话卡动作,仅保留可映射项。
|
||||
excel_ready: 是否存在 ready 的发货 Excel Artifact。
|
||||
|
||||
Returns:
|
||||
契约动作码列表(去重、保序)。
|
||||
"""
|
||||
status_norm = str(status or '').strip().lower()
|
||||
stage_norm = str(stage or '').strip().lower()
|
||||
actions: list[str] = []
|
||||
seen: set[str] = set()
|
||||
gate_action = _gate_next_action(gate)
|
||||
|
||||
def _push(raw: str | None) -> None:
|
||||
code = normalize_action_code(raw)
|
||||
if not code or code in seen:
|
||||
return
|
||||
if status_norm == 'completed' and code in _WRITE_ACTION_CODES:
|
||||
return
|
||||
# [BE-04] download_excel 必须有 ready Artifact,禁止仅因 stage 猜测。
|
||||
if code == 'download_excel' and not excel_ready:
|
||||
return
|
||||
seen.add(code)
|
||||
actions.append(code)
|
||||
|
||||
_push(gate_action)
|
||||
|
||||
# [BE-04] 仅技术失败允许默认 retry;业务 blocked 只保留 Gate next_action。
|
||||
if status_norm == 'failed' and 'retry' not in seen:
|
||||
_push('retry')
|
||||
elif status_norm == 'blocked' and gate_action in {
|
||||
'retry', 'retry_parse', 'retry_failed_documents', 'retry_failed_attachments',
|
||||
}:
|
||||
_push('retry')
|
||||
if status_norm == 'completed':
|
||||
_push('view_result')
|
||||
elif (
|
||||
stage_norm == 'excel_generating'
|
||||
and status_norm != 'automating'
|
||||
and not excel_ready
|
||||
):
|
||||
_push('regenerate_excel')
|
||||
# [BE-04] 人工上传入口:仅 Gate/动作事实,不得因 freight_uploading 阶段就猜测。
|
||||
if gate_action in {'open_manual_upload', 'wait_manual_upload', 'mark_manual_uploaded'}:
|
||||
_push('open_manual_upload')
|
||||
|
||||
if excel_ready:
|
||||
_push('download_excel')
|
||||
|
||||
for item in legacy_actions or []:
|
||||
mapped = normalize_action_code(item)
|
||||
# [BE-07] legacy 只补充只读类动作,禁止用旧卡覆盖 Gate 写意图。
|
||||
if mapped in {'view_result', 'view_record', 'refresh', 'download_excel'}:
|
||||
_push(mapped)
|
||||
elif mapped == 'open_manual_upload':
|
||||
_push(mapped)
|
||||
|
||||
if not actions:
|
||||
actions = ['view_result'] if status_norm in {'completed', 'failed', 'cancelled'} else []
|
||||
return actions
|
||||
|
||||
|
||||
def reconcile_processing_projection_facts(
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
legacy_actions: list[str] | None = None,
|
||||
invalidated_from_stage: str | None = None,
|
||||
excel_ready: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
在投影输出前强制 status/stage/gate/action 不变量,并写入 stage_nodes。
|
||||
|
||||
核心逻辑:
|
||||
1. Gate open_order_review → status/stage = waiting_review;
|
||||
2. status=completed ⇒ stage=completed 且清空写动作与 current_gate;
|
||||
3. stage=freight_uploading 时剔除 open_order_review;
|
||||
4. Extraction 完成但 stage 未 completed 时不得保持 status=completed;
|
||||
5. 规范化 available_actions(结合 excel_ready)与 stage_nodes(结合失效起点)。
|
||||
|
||||
Args:
|
||||
payload: 即将返回的 ShippingProcessingProjection dict(snake_case)。
|
||||
legacy_actions: 可选旧动作列表。
|
||||
invalidated_from_stage: 可选失效起点 stage。
|
||||
excel_ready: 是否存在 ready Excel Artifact。
|
||||
|
||||
Returns:
|
||||
就地修正后的 payload(同一对象)。
|
||||
"""
|
||||
status = str(payload.get('status') or '').strip().lower()
|
||||
stage = str(payload.get('stage') or '').strip().lower()
|
||||
source_type = str(payload.get('source_type') or '').strip().lower() or None
|
||||
gate = payload.get('current_gate') if isinstance(payload.get('current_gate'), dict) else None
|
||||
gate_action = _gate_next_action(gate)
|
||||
stage_idx = shipping_processing_stage_index(stage)
|
||||
waiting_idx = shipping_processing_stage_index('waiting_review') or 8
|
||||
|
||||
# [BE-03] Extraction Run 完成误标为全流程 completed:早期 stage 时回退 status。
|
||||
if status == 'completed' and stage and stage != 'completed':
|
||||
if stage_idx is not None and stage_idx <= waiting_idx:
|
||||
status = derivation_status_for_extraction_run('completed', stage=stage)
|
||||
elif gate_action == 'open_order_review':
|
||||
# 履约后半段不得被陈旧复核 Gate 拉回;清除 Gate,保留 completed。
|
||||
gate = None
|
||||
gate_action = None
|
||||
|
||||
# [BE-04] Gate 要求进入复核 ⇒ 进度必须停在 waiting_review(不得被 completed 误伤)。
|
||||
if gate_action == 'open_order_review' and status != 'completed':
|
||||
status = 'waiting_review' if status not in {'failed', 'cancelled'} else status
|
||||
stage = 'waiting_review'
|
||||
if isinstance(gate, dict):
|
||||
gate = {**gate, 'next_action_code': 'open_order_review'}
|
||||
|
||||
if stage == 'freight_uploading' and gate_action == 'open_order_review':
|
||||
gate = None
|
||||
gate_action = None
|
||||
|
||||
if status == 'completed':
|
||||
stage = 'completed'
|
||||
gate = None
|
||||
gate_action = None
|
||||
|
||||
if status not in SHIPPING_PROCESSING_STATUSES:
|
||||
status = 'processing'
|
||||
if stage not in SHIPPING_PROCESSING_STAGES:
|
||||
stage = 'document_parsing'
|
||||
|
||||
payload['status'] = status
|
||||
payload['stage'] = stage
|
||||
payload['current_gate'] = gate
|
||||
payload['available_actions'] = derive_available_actions(
|
||||
status=status,
|
||||
stage=stage,
|
||||
gate=gate,
|
||||
legacy_actions=legacy_actions if legacy_actions is not None else list(
|
||||
payload.get('available_actions') or []
|
||||
),
|
||||
excel_ready=excel_ready,
|
||||
)
|
||||
payload['stage_nodes'] = build_stage_nodes(
|
||||
stage=stage,
|
||||
status=status,
|
||||
source_type=source_type,
|
||||
invalidated_from_stage=invalidated_from_stage,
|
||||
)
|
||||
return payload
|
||||
@@ -91,6 +91,13 @@ FORMAL_TASK_EDIT_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'excel_export_invalidated',
|
||||
})
|
||||
|
||||
# OT 统一进度写路径审计(BE-06);由 sync_order_task_processing_state 中央强制写入。
|
||||
ORDER_TASK_PROGRESS_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'order_task_created',
|
||||
'order_task_updated',
|
||||
'order_task_progress_changed',
|
||||
})
|
||||
|
||||
# 复核工作台布局重构(2026-08-01)业务写 / 敏感读稳定事件字典。
|
||||
# 普通 UI 折叠不写服务端审计;访问类经 record_access_audit 映射 action,见 REVIEW_WORKBENCH_ACCESS_ACTIONS。
|
||||
REVIEW_WORKBENCH_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
@@ -132,7 +139,7 @@ REVIEW_WORKBENCH_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'llm_suggestion_modified',
|
||||
'llm_suggestion_rejected',
|
||||
'sensitive_evidence_viewed',
|
||||
}) | FORMAL_TASK_EDIT_AUDIT_EVENT_TYPES
|
||||
}) | FORMAL_TASK_EDIT_AUDIT_EVENT_TYPES | ORDER_TASK_PROGRESS_AUDIT_EVENT_TYPES
|
||||
|
||||
# 对话工作台轻量操作 / 聚焦 / 恢复(阶段 5–6);禁止前端私自发明事件名。
|
||||
CHAT_WORKBENCH_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
@@ -661,9 +668,14 @@ XFA_PROGRESS_EVENT_CODES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_cross_check_completed',
|
||||
'xfa_structure_signature_frozen',
|
||||
'xfa_audit_snapshot_viewed',
|
||||
'xfa_visual_binding_suggested',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_split_rule_previewed',
|
||||
'xfa_split_rule_validated',
|
||||
'xfa_split_rule_confirmed',
|
||||
'xfa_split_segment_created',
|
||||
'xfa_split_segment_updated',
|
||||
'xfa_split_segment_deleted',
|
||||
@@ -675,6 +687,8 @@ XFA_PROGRESS_EVENT_CODES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_profile_published',
|
||||
'xfa_profile_formal_extracted',
|
||||
'xfa_profile_needs_review',
|
||||
'order_profile_unified_migration_dry_run',
|
||||
'order_profile_unified_migration_executed',
|
||||
})
|
||||
|
||||
# 工作台可用动作扩展(阶段 1/2 下发);既有动作保持兼容。
|
||||
@@ -786,6 +800,7 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
|
||||
'workflow_no',
|
||||
'workflow_item_no',
|
||||
'current_stage',
|
||||
'stage',
|
||||
'version_status',
|
||||
'owner_user_id',
|
||||
'conversation_id',
|
||||
@@ -890,6 +905,8 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
|
||||
'header_mapping_count',
|
||||
'line_mapping_count',
|
||||
'bound_field_count',
|
||||
'binding_count',
|
||||
'split_rule_count',
|
||||
'mirror_collection_count',
|
||||
'xfa_document_kind',
|
||||
'analysis_id',
|
||||
|
||||
@@ -9,7 +9,8 @@ services/shipping_notice/query_service.py
|
||||
co8 起 shipping_batches 已删除,批次 list API 返回空、按 batch_no 查询返回 None;
|
||||
tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉;
|
||||
SUMMARY 经 _enrich_task_center_fields 附带 todo_category / can_handle / ui_state / recent_event,
|
||||
以及统一 shipping_processing_status / progress_version / order_task_no(BE-02);
|
||||
以及统一 shipping_processing_status / progress_version / order_task_no(BE-02),
|
||||
并注入 review_run_no 供任务中心深链订单处理工作台(UI-04);
|
||||
list_my_todos / count_my_todos 合并建单前 Review Case、未建 OT Intake 与 Task 待办;
|
||||
客户关键字 SQL 同时过滤 Review Case / Intake(文件名)与 Task(客户快照/来源文件名);
|
||||
待办 todo_category 下推为与状态机同序的 SQL CASE;list 用 UNION ALL + COUNT/OFFSET/LIMIT,
|
||||
@@ -936,18 +937,19 @@ def _artifact_summary_for_task(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
|
||||
def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]) -> None:
|
||||
"""
|
||||
将 Notice 关联 OT 的统一进度写入任务中心字段(BE-02)。
|
||||
将 Notice 关联 OT 的统一进度写入任务中心字段(BE-02 / UI-04)。
|
||||
|
||||
核心逻辑:优先 Notice.order_task_id → ShippingOrderTask;有 OT 时用 Notice 履约
|
||||
process_status 映射为 shipping_processing_status(与 shipping_processing_projection 同源),
|
||||
并注入 shipping_processing_stage / progress_version / order_task_no;
|
||||
无 OT 时仍按 Notice.process_status 映射,保证列表/详情轮询可读同一字段。
|
||||
另附带 review_run_no / owner_agent_id / conversation_id(经 OT.extraction_run),
|
||||
供任务中心「进入订单处理」深链;无 OT 时仍按 Notice.process_status 映射。
|
||||
|
||||
Args:
|
||||
task: ShippingNotice(正式发货任务)。
|
||||
data: 就地写入的序列化字典。
|
||||
"""
|
||||
from app.models import ShippingOrderTask
|
||||
from app.models import ShippingOrderProcessingRun, ShippingOrderTask
|
||||
from app.services.shipping_notice.shipping_processing_projection import (
|
||||
_notice_processing_status_stage,
|
||||
)
|
||||
@@ -978,6 +980,19 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]
|
||||
data['order_task_no'] = (
|
||||
str(getattr(order_task, 'task_no', None) or '').strip() or None
|
||||
)
|
||||
# [UI-04] 任务中心仅作列表入口;深链订单处理工作台需要 Run 编号与 Agent。
|
||||
if order_task is not None and getattr(order_task, 'extraction_run_id', None):
|
||||
run = db.session.get(ShippingOrderProcessingRun, int(order_task.extraction_run_id))
|
||||
if run is not None:
|
||||
run_no = str(getattr(run, 'run_no', None) or '').strip() or None
|
||||
if run_no:
|
||||
data['review_run_no'] = run_no
|
||||
if not str(data.get('conversation_id') or '').strip():
|
||||
cid = str(getattr(run, 'conversation_id', None) or '').strip() or None
|
||||
if cid:
|
||||
data['conversation_id'] = cid
|
||||
if data.get('owner_agent_id') is None and getattr(run, 'owner_agent_id', None) is not None:
|
||||
data['owner_agent_id'] = int(run.owner_agent_id)
|
||||
|
||||
|
||||
def _enrich_task_center_fields(
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"""
|
||||
services/shipping_notice/schema_edit_policy.py
|
||||
|
||||
用途:正式任务字段编辑策略(Schema 冻结策略优先;无策略时回退安全默认只读)。
|
||||
依赖:task_order_field_editor(锁定 Schema)、ConflictError;被 task_workflow /
|
||||
复核 formal patch / 投影 formal_editable_field_ids 引用。
|
||||
逻辑:默认 editable_after_task_creation=False;显式 editable=True 或 legacy 白名单
|
||||
(且无 editable=false)方可写;change_effect 供 task_workflow 下游失效编排消费。
|
||||
用途:正式任务字段编辑策略(Schema 显式放行;无策略默认只读;Excel ready 硬冻结)。
|
||||
依赖:task_order_field_editor(锁定 Schema)、ShippingExportArtifact、ConflictError;
|
||||
被 task_workflow / 复核 formal patch / 投影 formal_editable_field_ids 引用。
|
||||
逻辑:默认 editable_after_task_creation=False;仅 Schema editable=True 可写;
|
||||
Excel ready = ready Artifact 匹配路径 + 可选 order_data_version 指纹;
|
||||
change_effect 供 task_workflow 下游失效编排消费。不考虑 legacy 白名单兼容绕过。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,10 +18,10 @@ from app.core.errors import ConflictError
|
||||
if TYPE_CHECKING:
|
||||
from app.models import ShippingNotice
|
||||
|
||||
# 默认:创建正式任务后字段不可编辑(阶段 3 契约)。
|
||||
# 默认:创建正式任务后字段不可编辑。
|
||||
DEFAULT_EDITABLE_AFTER_TASK_CREATION: Final[bool] = False
|
||||
|
||||
# 允许的 change_effect(阶段 4 消费;阶段 3 仅校验白名单)。
|
||||
# 允许的 change_effect。
|
||||
ALLOWED_CHANGE_EFFECTS: Final[frozenset[str]] = frozenset({
|
||||
'none',
|
||||
'rerun_inventory_source_resolution',
|
||||
@@ -29,6 +30,9 @@ ALLOWED_CHANGE_EFFECTS: Final[frozenset[str]] = frozenset({
|
||||
'require_revision',
|
||||
})
|
||||
|
||||
# 审计 Diff 中标量值最大字符数(防塞入正文)。
|
||||
_AUDIT_VALUE_MAX_CHARS: Final[int] = 256
|
||||
|
||||
|
||||
def field_task_edit_policy(field_config: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
@@ -58,6 +62,57 @@ def field_task_edit_policy(field_config: dict[str, Any] | None) -> dict[str, Any
|
||||
}
|
||||
|
||||
|
||||
def is_excel_ready_for_task(task: ShippingNotice) -> bool:
|
||||
"""
|
||||
判断发货 Excel 是否已成功生成并仍绑定当前订单数据版本。
|
||||
|
||||
核心逻辑:须存在 export_file_path,且 shipping_notice_export_artifacts 中有
|
||||
status=ready 且 file_path 匹配的 Artifact;若 step_payload.export_meta 记录了
|
||||
order_data_version,则须与当前 order_data_version 一致,否则视为 stale。
|
||||
|
||||
Args:
|
||||
task: 目标 ShippingNotice。
|
||||
|
||||
Returns:
|
||||
True 表示正式字段应全局冻结。
|
||||
"""
|
||||
path = str(getattr(task, 'export_file_path', None) or '').strip()
|
||||
if not path:
|
||||
return False
|
||||
task_id = getattr(task, 'id', None)
|
||||
if task_id is None:
|
||||
return False
|
||||
# [BE-09] 路径 alone 不足;必须存在当前 ready Artifact。
|
||||
from app.models import ShippingExportArtifact
|
||||
|
||||
artifact = (
|
||||
ShippingExportArtifact.query.filter_by(
|
||||
task_id=int(task_id),
|
||||
status='ready',
|
||||
file_path=path,
|
||||
)
|
||||
.order_by(
|
||||
ShippingExportArtifact.created_at.desc(),
|
||||
ShippingExportArtifact.id.desc(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if artifact is None:
|
||||
return False
|
||||
step_payload = dict(getattr(task, 'step_payload_json', None) or {})
|
||||
export_meta = step_payload.get('export_meta') if isinstance(step_payload.get('export_meta'), dict) else {}
|
||||
raw_version = export_meta.get('order_data_version')
|
||||
if raw_version is None or raw_version == '':
|
||||
# 有 ready Artifact 但无版本指纹:仍冻结(fail-closed)。
|
||||
return True
|
||||
try:
|
||||
exported_version = int(raw_version)
|
||||
except (TypeError, ValueError):
|
||||
return True
|
||||
current_version = int(getattr(task, 'order_data_version', None) or 1)
|
||||
return exported_version == current_version
|
||||
|
||||
|
||||
def is_field_editable_for_formal_task(
|
||||
field_config: dict[str, Any] | None,
|
||||
*,
|
||||
@@ -66,8 +121,8 @@ def is_field_editable_for_formal_task(
|
||||
"""
|
||||
判断正式任务下该字段是否可编辑。
|
||||
|
||||
核心逻辑:必须 Schema 显式 editable=True;若 editable_until=excel_ready 且 Excel
|
||||
已就绪则关闭编辑。
|
||||
核心逻辑:Excel ready 时一律不可编辑;否则必须 Schema 显式 editable=True;
|
||||
若 editable_until=excel_ready 且 Excel 已就绪则关闭(与全局冻结一致)。
|
||||
|
||||
Args:
|
||||
field_config: Schema 字段配置。
|
||||
@@ -76,6 +131,8 @@ def is_field_editable_for_formal_task(
|
||||
Returns:
|
||||
True 表示允许写路径修改。
|
||||
"""
|
||||
if excel_ready:
|
||||
return False
|
||||
policy = field_task_edit_policy(field_config)
|
||||
if not policy['editable']:
|
||||
return False
|
||||
@@ -108,11 +165,6 @@ def locked_schema_field_configs(task: ShippingNotice) -> list[dict[str, Any]]:
|
||||
]
|
||||
|
||||
|
||||
def _excel_ready_for_task(task: ShippingNotice) -> bool:
|
||||
"""Excel 导出路径已就绪时,editable_until=excel_ready 的字段应关闭编辑。"""
|
||||
return bool(str(getattr(task, 'export_file_path', None) or '').strip())
|
||||
|
||||
|
||||
def _locked_field_config(
|
||||
task: ShippingNotice,
|
||||
field_code: str,
|
||||
@@ -130,40 +182,48 @@ def _locked_field_config(
|
||||
return None
|
||||
|
||||
|
||||
def assert_formal_task_not_excel_frozen(task: ShippingNotice) -> None:
|
||||
"""
|
||||
Excel 成功生成后拒绝一切正式字段写路径。
|
||||
|
||||
Raises:
|
||||
ConflictError: code=SHIPPING.ORDER_EXCEL_FROZEN。
|
||||
"""
|
||||
if is_excel_ready_for_task(task):
|
||||
raise ConflictError(
|
||||
'Excel already generated; formal task fields are frozen',
|
||||
code='SHIPPING.ORDER_EXCEL_FROZEN',
|
||||
)
|
||||
|
||||
|
||||
def is_formal_field_code_editable(
|
||||
task: ShippingNotice,
|
||||
field_code: str,
|
||||
*,
|
||||
scope: str,
|
||||
legacy_whitelist: frozenset[str],
|
||||
) -> bool:
|
||||
"""
|
||||
判断正式任务下 field_code 是否允许写入。
|
||||
|
||||
核心逻辑:显式 editable=false 一律拒绝;Schema editable=true 放行;
|
||||
否则 legacy 白名单字段在无显式策略时保持向后兼容。
|
||||
核心逻辑:仅 Schema 显式 editable=True 且未 Excel 冻结时放行;无 legacy 白名单。
|
||||
|
||||
Args:
|
||||
task: 目标 ShippingNotice。
|
||||
field_code: Schema field_code。
|
||||
scope: header 或 line。
|
||||
legacy_whitelist: EDITABLE_NOTICE_* 常量。
|
||||
|
||||
Returns:
|
||||
True 表示 update_notice_* 可接受该字段。
|
||||
"""
|
||||
if is_excel_ready_for_task(task):
|
||||
return False
|
||||
config = _locked_field_config(task, field_code, scope=scope)
|
||||
if config is None:
|
||||
return False
|
||||
policy_raw = config.get('task_edit_policy') if isinstance(config, dict) else None
|
||||
if isinstance(policy_raw, dict) and policy_raw.get('editable') is False:
|
||||
return False
|
||||
if is_field_editable_for_formal_task(config, excel_ready=_excel_ready_for_task(task)):
|
||||
return True
|
||||
if field_code in legacy_whitelist:
|
||||
if not isinstance(policy_raw, dict) or 'editable' not in policy_raw:
|
||||
return True
|
||||
return False
|
||||
return is_field_editable_for_formal_task(
|
||||
config,
|
||||
excel_ready=is_excel_ready_for_task(task),
|
||||
)
|
||||
|
||||
|
||||
def assert_formal_field_editable(
|
||||
@@ -171,7 +231,6 @@ def assert_formal_field_editable(
|
||||
field_codes: list[str],
|
||||
*,
|
||||
scope: str,
|
||||
legacy_whitelist: frozenset[str],
|
||||
) -> None:
|
||||
"""
|
||||
批量校验正式任务字段可写;任一不可写则抛 ConflictError。
|
||||
@@ -180,16 +239,14 @@ def assert_formal_field_editable(
|
||||
task: 目标 ShippingNotice。
|
||||
field_codes: 待写入 field_code 列表。
|
||||
scope: header 或 line。
|
||||
legacy_whitelist: legacy 白名单常量。
|
||||
|
||||
Raises:
|
||||
ConflictError: code=SHIPPING.ORDER_FIELD_EDIT_FORBIDDEN。
|
||||
ConflictError: code=SHIPPING.ORDER_EXCEL_FROZEN 或 ORDER_FIELD_EDIT_FORBIDDEN。
|
||||
"""
|
||||
assert_formal_task_not_excel_frozen(task)
|
||||
forbidden = [
|
||||
code for code in field_codes
|
||||
if not is_formal_field_code_editable(
|
||||
task, code, scope=scope, legacy_whitelist=legacy_whitelist,
|
||||
)
|
||||
if not is_formal_field_code_editable(task, code, scope=scope)
|
||||
]
|
||||
if forbidden:
|
||||
raise ConflictError(
|
||||
@@ -204,9 +261,9 @@ def collect_change_effects_for_fields(
|
||||
field_codes: list[str],
|
||||
*,
|
||||
scope: str,
|
||||
) -> tuple[set[str], bool]:
|
||||
) -> set[str]:
|
||||
"""
|
||||
汇总被编辑字段的 change_effect;识别是否含 legacy 无策略字段。
|
||||
汇总被编辑字段的 change_effect(仅 Schema 策略;无 legacy 全量 reset)。
|
||||
|
||||
Args:
|
||||
task: 目标 ShippingNotice。
|
||||
@@ -214,22 +271,17 @@ def collect_change_effects_for_fields(
|
||||
scope: header 或 line。
|
||||
|
||||
Returns:
|
||||
(change_effect 集合, 是否含 legacy 无 task_edit_policy 字段)。
|
||||
change_effect 集合(不含 none)。
|
||||
"""
|
||||
effects: set[str] = set()
|
||||
has_legacy_unpolicy = False
|
||||
for code in field_codes:
|
||||
config = _locked_field_config(task, code, scope=scope)
|
||||
if config is None:
|
||||
continue
|
||||
policy_raw = config.get('task_edit_policy')
|
||||
if not isinstance(policy_raw, dict):
|
||||
has_legacy_unpolicy = True
|
||||
continue
|
||||
effect = field_task_edit_policy(config)['change_effect']
|
||||
if effect and effect != 'none':
|
||||
effects.add(str(effect))
|
||||
return effects, has_legacy_unpolicy
|
||||
return effects
|
||||
|
||||
|
||||
def list_editable_formal_field_ids(
|
||||
@@ -257,3 +309,21 @@ def list_editable_formal_field_ids(
|
||||
if field_id:
|
||||
result.append(field_id)
|
||||
return result
|
||||
|
||||
|
||||
def sanitize_audit_field_value(value: Any) -> Any:
|
||||
"""
|
||||
将字段前后值压缩为可进审计 metadata 的标量摘要。
|
||||
|
||||
Args:
|
||||
value: 原始业务值。
|
||||
|
||||
Returns:
|
||||
str/int/float/bool/None;过长字符串截断。
|
||||
"""
|
||||
if value is None or isinstance(value, (bool, int, float)):
|
||||
return value
|
||||
text = str(value)
|
||||
if len(text) > _AUDIT_VALUE_MAX_CHARS:
|
||||
return text[:_AUDIT_VALUE_MAX_CHARS] + '…'
|
||||
return text
|
||||
@@ -1,15 +1,17 @@
|
||||
"""
|
||||
services/shipping_notice/shipping_processing_projection.py
|
||||
|
||||
用途:统一 ShippingProcessingProjection 阶段 4 适配器——将会话 processing 与尚未建 OT
|
||||
的 Intake 投影为四页面共用的 work_item 列表。
|
||||
依赖:progress_audit_contract、conversation_processing_projection、
|
||||
用途:统一 ShippingProcessingProjection 适配器——将会话 processing 与尚未建 OT
|
||||
的 Intake 投影为四页面共用的 work_item 列表(统一事实,非统一 UI)。
|
||||
依赖:progress_audit_contract、processing_projection_invariants、
|
||||
ShippingOrderIntake / ShippingOrderSubmission / ShippingOrderProcessingRun /
|
||||
ShippingOrderTask / ShippingOrderCandidate / ShippingOrderReviewCase /
|
||||
ShippingProcessExecution / FileAsset / Job。
|
||||
逻辑:由 GET /shipping-processing/conversations/{id} 与 work-items 路由调用;
|
||||
复用 project_conversation_processing 作 order_task 来源,Stage 1 Intake 作 order_intake;
|
||||
直接以 ShippingOrderTask 为 order_task 来源,Stage 1 Intake 作 order_intake;
|
||||
Intake/OT 均填充 current_gate(优先真实 ProcessExecution)与 source_summary;
|
||||
输出前 reconcile status/stage/gate/action,并结合 Notice 失效起点 / Excel Artifact
|
||||
写入 stage_nodes 与 available_actions;stage/status 以 OT 已写入值为准(BE-07,禁止 Notice 覆盖);
|
||||
**只读加载**已有 shipping_order_tasks(禁止 GET 路径 upsert);已建 Notice 时填 shipping_notice_no;
|
||||
work_items 构建后由 _conversation_processing_from_work_items 重建兼容 conversation_processing。
|
||||
"""
|
||||
@@ -34,8 +36,9 @@ from app.models import (
|
||||
ShippingOrderSubmission,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.conversation_processing_projection import (
|
||||
project_conversation_processing,
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
derivation_status_for_extraction_run,
|
||||
reconcile_processing_projection_facts,
|
||||
)
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
DIRECT_PDF_ALLOWED_STAGES,
|
||||
@@ -96,7 +99,8 @@ def map_run_status_to_processing_status(run_status: str) -> str:
|
||||
"""
|
||||
将 Run.status 映射为统一 ShippingProcessingStatus。
|
||||
|
||||
核心逻辑:按阶段 0 冻结词典折叠;未知状态回退 processing,保证前端可 i18n。
|
||||
核心逻辑:按冻结词典折叠;识别 Run completed ≠ 全流程 completed(回退 processing);
|
||||
未知状态回退 processing,保证前端可 i18n。
|
||||
|
||||
Args:
|
||||
run_status: ShippingOrderProcessingRun.status。
|
||||
@@ -104,19 +108,8 @@ def map_run_status_to_processing_status(run_status: str) -> str:
|
||||
Returns:
|
||||
SHIPPING_PROCESSING_STATUSES 中的码。
|
||||
"""
|
||||
status = str(run_status or '').strip().lower()
|
||||
if status in {'queued', 'processing'}:
|
||||
mapped = 'processing'
|
||||
elif status == 'review_required':
|
||||
mapped = 'waiting_review'
|
||||
elif status == 'failed':
|
||||
mapped = 'failed'
|
||||
elif status == 'cancelled':
|
||||
mapped = 'cancelled'
|
||||
elif status in {'completed', 'partially_completed'}:
|
||||
mapped = 'completed'
|
||||
else:
|
||||
mapped = 'processing'
|
||||
# [BE-03] 无 stage 上下文时,completed 仅表示识别结束,投影为 processing。
|
||||
mapped = derivation_status_for_extraction_run(run_status, stage=None)
|
||||
return mapped if mapped in SHIPPING_PROCESSING_STATUSES else 'processing'
|
||||
|
||||
|
||||
@@ -184,11 +177,10 @@ def map_run_to_processing_stage(run: Any, *, source_type: str | None) -> str:
|
||||
将 Extraction Run 投影为统一 ShippingProcessingStage。
|
||||
|
||||
核心逻辑:
|
||||
1. 终态优先(completed / review_required / cancelled);
|
||||
2. EML 在 merging_supplement 时进入 email_adjudicating;
|
||||
3. direct_pdf 永不返回 email_parsing / email_adjudicating;
|
||||
4. extracting → document_parsing(direct_pdf 亦可候选 creating);
|
||||
5. 其余按 phase/activity 启发式映射。
|
||||
1. 终态优先(cancelled / review_required);
|
||||
2. 优先读写路径写入的 progress_summary_json.processing_stage;
|
||||
3. 无写入时:EML merging → email_adjudicating;activity 启发式兜底;
|
||||
4. direct_pdf 永不返回 email_parsing / email_adjudicating。
|
||||
|
||||
Args:
|
||||
run: ShippingOrderProcessingRun 或具备 status/phase 的兼容对象。
|
||||
@@ -197,6 +189,10 @@ def map_run_to_processing_stage(run: Any, *, source_type: str | None) -> str:
|
||||
Returns:
|
||||
SHIPPING_PROCESSING_STAGES 中的码。
|
||||
"""
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
read_run_unified_processing_stage,
|
||||
)
|
||||
|
||||
status = str(getattr(run, 'status', '') or '').strip().lower()
|
||||
hint = _activity_hint_from_run(run)
|
||||
unit_statuses = _unit_statuses_for_run(run)
|
||||
@@ -204,17 +200,35 @@ def map_run_to_processing_stage(run: Any, *, source_type: str | None) -> str:
|
||||
if source and source not in ORDER_INTAKE_SOURCE_TYPES:
|
||||
source = None
|
||||
|
||||
# [STEP 1] 明确终态
|
||||
if status in {'completed', 'partially_completed'}:
|
||||
return _clamp_processing_stage('completed', source_type=source)
|
||||
# [STEP 1] 明确终态(识别 Run completed ≠ 全流程 completed)
|
||||
if status == 'cancelled':
|
||||
return _clamp_processing_stage('completed', source_type=source)
|
||||
if status == 'review_required':
|
||||
return _clamp_processing_stage('waiting_review', source_type=source)
|
||||
|
||||
# [STEP 2] 写路径事实优先(进度事件已落 processing_stage)
|
||||
written = read_run_unified_processing_stage(run)
|
||||
if written:
|
||||
if status in {'completed', 'partially_completed'} and written in {
|
||||
'upload_received', 'email_parsing', 'document_parsing', 'email_adjudicating',
|
||||
}:
|
||||
# 识别已结束但写入仍停在解析早期时,抬升到候选态。
|
||||
return _clamp_processing_stage('candidate_creating', source_type=source)
|
||||
return _clamp_processing_stage(written, source_type=source)
|
||||
|
||||
if status in {'completed', 'partially_completed'}:
|
||||
# [BE-03] 识别完成时若仍有活动提示,按活动映射;否则停在候选/待复核而非 completed。
|
||||
if hint in _ACTIVITY_TO_PROCESSING_STAGE:
|
||||
return _clamp_processing_stage(
|
||||
_ACTIVITY_TO_PROCESSING_STAGE[hint], source_type=source,
|
||||
)
|
||||
if 'review_required' in unit_statuses or 'candidate_ready' in unit_statuses:
|
||||
return _clamp_processing_stage('waiting_review', source_type=source)
|
||||
return _clamp_processing_stage('candidate_creating', source_type=source)
|
||||
if status == 'failed':
|
||||
return _clamp_processing_stage('document_parsing', source_type=source)
|
||||
|
||||
# [STEP 2] EML 裁决:单元或 Run 处于 merging_supplement
|
||||
# [STEP 3] EML 裁决:单元或 Run 处于 merging_supplement
|
||||
merging = (
|
||||
hint == 'merging_supplement'
|
||||
or 'merging_supplement' in unit_statuses
|
||||
@@ -222,24 +236,22 @@ def map_run_to_processing_stage(run: Any, *, source_type: str | None) -> str:
|
||||
if source == 'eml' and merging:
|
||||
return _clamp_processing_stage('email_adjudicating', source_type=source)
|
||||
|
||||
# [STEP 3] extracting / merging 对 direct_pdf 的专用映射
|
||||
# [STEP 4] extracting / merging 对 direct_pdf 的专用映射
|
||||
if hint == 'extracting' or 'extracting' in unit_statuses:
|
||||
if source == 'direct_pdf':
|
||||
return _clamp_processing_stage('document_parsing', source_type=source)
|
||||
return _clamp_processing_stage('document_parsing', source_type=source)
|
||||
if hint == 'merging_supplement' or merging:
|
||||
if source == 'direct_pdf':
|
||||
return _clamp_processing_stage('candidate_creating', source_type=source)
|
||||
return _clamp_processing_stage('candidate_creating', source_type=source)
|
||||
|
||||
# [STEP 4] 活动码表映射
|
||||
# [STEP 5] 活动码表映射
|
||||
if hint and hint in _ACTIVITY_TO_PROCESSING_STAGE:
|
||||
return _clamp_processing_stage(
|
||||
_ACTIVITY_TO_PROCESSING_STAGE[hint],
|
||||
source_type=source,
|
||||
)
|
||||
|
||||
# [STEP 5] 默认:处理中→文档解析;排队同解析前
|
||||
# [STEP 6] 默认:处理中→文档解析;排队同解析前
|
||||
if status in {'queued', 'processing'}:
|
||||
return _clamp_processing_stage('document_parsing', source_type=source)
|
||||
return _clamp_processing_stage('document_parsing', source_type=source)
|
||||
@@ -464,24 +476,28 @@ def project_intake_work_item(
|
||||
getattr(intake, 'updated_at', None)
|
||||
or getattr(intake, 'created_at', None)
|
||||
)
|
||||
return {
|
||||
'work_item_type': 'order_intake',
|
||||
'work_item_no': str(intake.intake_no),
|
||||
'source_type': source_type,
|
||||
'root_order_task_no': None,
|
||||
'shipping_notice_no': None,
|
||||
'conversation_id': str(intake.conversation_id or '').strip() or None,
|
||||
'submission_no': str(submission.submission_no) if submission is not None else '',
|
||||
'intake_no': str(intake.intake_no),
|
||||
'status': _intake_processing_status(intake),
|
||||
'stage': _intake_processing_stage(intake),
|
||||
'progress_version': progress_version,
|
||||
'last_activity_at': _iso(last_activity) or '',
|
||||
'current_gate': _intake_current_gate(intake, asset=asset),
|
||||
'available_actions': _intake_available_actions(intake),
|
||||
'source_summary': _intake_source_summary(intake, asset=asset),
|
||||
'child_order_tasks': [],
|
||||
}
|
||||
legacy_actions = _intake_available_actions(intake)
|
||||
return reconcile_processing_projection_facts(
|
||||
{
|
||||
'work_item_type': 'order_intake',
|
||||
'work_item_no': str(intake.intake_no),
|
||||
'source_type': source_type,
|
||||
'root_order_task_no': None,
|
||||
'shipping_notice_no': None,
|
||||
'conversation_id': str(intake.conversation_id or '').strip() or None,
|
||||
'submission_no': str(submission.submission_no) if submission is not None else '',
|
||||
'intake_no': str(intake.intake_no),
|
||||
'status': _intake_processing_status(intake),
|
||||
'stage': _intake_processing_stage(intake),
|
||||
'progress_version': progress_version,
|
||||
'last_activity_at': _iso(last_activity) or '',
|
||||
'current_gate': _intake_current_gate(intake, asset=asset),
|
||||
'available_actions': legacy_actions,
|
||||
'source_summary': _intake_source_summary(intake, asset=asset),
|
||||
'child_order_tasks': [],
|
||||
},
|
||||
legacy_actions=legacy_actions,
|
||||
)
|
||||
|
||||
|
||||
def _source_type_for_run(run: ShippingOrderProcessingRun) -> str | None:
|
||||
@@ -625,10 +641,11 @@ def _order_task_source_summary(
|
||||
"""
|
||||
构建 order_task 的 source_summary(候选数 / PO / 客户)。
|
||||
|
||||
核心逻辑:按 run_id 计数 Candidate;优先 OT.candidate_id,否则取当前版本候选填 PO/客户;
|
||||
parsed_document_count 按 Run 关联 Intake 下 Document.parse_status=parsed 实计,禁止等于 document_count。
|
||||
核心逻辑:优先 OT.candidate_id 定位当前订单候选及其 primary_document_id;
|
||||
OT 摘要只统计本票关联 PDF,禁止把整个 Run 的文档数复制到每个兄弟 OT;
|
||||
仅在旧数据缺少 Candidate 关联时回退 Run 级摘要。
|
||||
"""
|
||||
candidate_count = (
|
||||
run_candidate_count = (
|
||||
db.session.query(ShippingOrderCandidate.id)
|
||||
.filter(ShippingOrderCandidate.order_extraction_run_id == int(run.id))
|
||||
.count()
|
||||
@@ -668,22 +685,41 @@ def _order_task_source_summary(
|
||||
)
|
||||
if link.intake_id
|
||||
]
|
||||
parsed_document_count = 0
|
||||
if intake_ids:
|
||||
parsed_document_count = (
|
||||
db.session.query(ShippingOrderDocument.id)
|
||||
.filter(
|
||||
ShippingOrderDocument.intake_id.in_(intake_ids),
|
||||
ShippingOrderDocument.parse_status == 'parsed',
|
||||
ShippingOrderDocument.document_type != 'email_body',
|
||||
)
|
||||
.count()
|
||||
task_document: ShippingOrderDocument | None = None
|
||||
if candidate is not None and getattr(candidate, 'primary_document_id', None):
|
||||
task_document = db.session.get(
|
||||
ShippingOrderDocument,
|
||||
int(candidate.primary_document_id),
|
||||
)
|
||||
|
||||
# [STEP 2] Candidate 已明确绑定主 PDF 时,所有计数与文件名必须保持 OT 粒度。
|
||||
if task_document is not None:
|
||||
filename = str(task_document.filename or '').strip() or filename
|
||||
task_document_count = 1
|
||||
parsed_document_count = 1 if str(task_document.parse_status or '') == 'parsed' else 0
|
||||
candidate_count = 1
|
||||
document_id = int(task_document.id)
|
||||
else:
|
||||
parsed_document_count = 0
|
||||
if intake_ids:
|
||||
parsed_document_count = (
|
||||
db.session.query(ShippingOrderDocument.id)
|
||||
.filter(
|
||||
ShippingOrderDocument.intake_id.in_(intake_ids),
|
||||
ShippingOrderDocument.parse_status == 'parsed',
|
||||
ShippingOrderDocument.document_type != 'email_body',
|
||||
)
|
||||
.count()
|
||||
)
|
||||
task_document_count = int(document_count)
|
||||
candidate_count = int(run_candidate_count)
|
||||
document_id = None
|
||||
|
||||
return {
|
||||
'email_subject': None,
|
||||
'filename': filename,
|
||||
'document_count': int(document_count),
|
||||
'document_id': document_id,
|
||||
'document_count': task_document_count,
|
||||
'parsed_document_count': int(parsed_document_count),
|
||||
'candidate_count': int(candidate_count),
|
||||
'customer_name': _customer_name_from_candidate(candidate),
|
||||
@@ -695,38 +731,13 @@ def _notice_processing_status_stage(notice: ShippingNotice) -> tuple[str, str]:
|
||||
"""
|
||||
将正式 Notice 履约 process_status 映射为统一投影 (status, stage)。
|
||||
|
||||
核心逻辑:uploading/uploaded → freight_uploading/completed;matching → inventory_matching;
|
||||
export/excel → excel_generating;优先于 OT 上可能过期的 stage。
|
||||
|
||||
Args:
|
||||
notice: 已建单的 ShippingNotice。
|
||||
|
||||
Returns:
|
||||
(ShippingProcessingStatus, ShippingProcessingStage) 元组。
|
||||
核心逻辑:委托领域映射 map_notice_to_processing_status_stage,投影不再私有维护规则。
|
||||
"""
|
||||
ps = str(notice.process_status or '').strip().lower()
|
||||
step = str(notice.current_step or '').strip().lower()
|
||||
upload_st = str(notice.upload_status or '').strip().lower()
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
map_notice_to_processing_status_stage,
|
||||
)
|
||||
|
||||
if ps in {'uploaded', 'closed', 'completed'}:
|
||||
return ('completed', 'completed')
|
||||
if ps in {'waiting_upload', 'upload_failed', 'uploading'} or upload_st == 'uploading':
|
||||
return ('automating', 'freight_uploading')
|
||||
if 'upload' in step or step.startswith('step7'):
|
||||
return ('automating', 'freight_uploading')
|
||||
|
||||
if ps in {'export', 'excel', 'generating_excel'} or 'generate' in step or step.startswith('step6'):
|
||||
return ('automating', 'excel_generating')
|
||||
if ps == 'matched' and notice.export_file_path:
|
||||
return ('automating', 'excel_generating')
|
||||
|
||||
if ps in {'matching', 'inventory_ready', 'waiting_inventory', 'matched', 'parsed'} or 'match' in step:
|
||||
return ('automating', 'inventory_matching')
|
||||
|
||||
if ps == 'pending_review':
|
||||
return ('waiting_review', 'waiting_review')
|
||||
|
||||
return ('automating', 'inventory_matching')
|
||||
return map_notice_to_processing_status_stage(notice)
|
||||
|
||||
|
||||
def _order_task_current_gate(
|
||||
@@ -935,9 +946,7 @@ def _project_order_task_work_item(
|
||||
user_task_no = str(getattr(order_task, 'task_no', None) or '').strip()
|
||||
if not user_task_no:
|
||||
return None
|
||||
available_actions = list((task_row or {}).get('available_actions') or [])
|
||||
if not available_actions:
|
||||
available_actions = ['view_details']
|
||||
legacy_actions = list((task_row or {}).get('available_actions') or [])
|
||||
documents = []
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
for intake_row in snapshot.get('intakes') or []:
|
||||
@@ -949,36 +958,87 @@ def _project_order_task_work_item(
|
||||
filename = None
|
||||
if len(documents) == 1:
|
||||
filename = str(documents[0].get('filename') or '').strip() or None
|
||||
status = (
|
||||
str(getattr(order_task, 'status', None) or '').strip()
|
||||
or map_run_status_to_processing_status(str(run.status or ''))
|
||||
)
|
||||
if status not in SHIPPING_PROCESSING_STATUSES:
|
||||
status = map_run_status_to_processing_status(str(run.status or ''))
|
||||
stage = (
|
||||
str(getattr(order_task, 'stage', None) or '').strip()
|
||||
or map_run_to_processing_stage(run, source_type=source_type)
|
||||
)
|
||||
if stage not in SHIPPING_PROCESSING_STAGES:
|
||||
stage = map_run_to_processing_stage(run, source_type=source_type)
|
||||
raw_status = str(getattr(order_task, 'status', None) or '').strip().lower()
|
||||
if raw_status in SHIPPING_PROCESSING_STATUSES:
|
||||
status = raw_status
|
||||
else:
|
||||
status = derivation_status_for_extraction_run(
|
||||
str(run.status or ''),
|
||||
stage=stage,
|
||||
)
|
||||
# [BE-03] OT 上残留的 completed + 早期 stage 组合在输出前再折叠。
|
||||
if status == 'completed' and stage != 'completed':
|
||||
status = derivation_status_for_extraction_run('completed', stage=stage)
|
||||
|
||||
# [BE-07] 已挂 Notice 时以履约 process_status 为准,避免 OT.stage 滞后。
|
||||
# [BE-07] stage/status 以 OT 已写入事实为准,禁止读路径用 Notice 覆盖 OT。
|
||||
# 履约态须经 sync_order_task_stage_for_notice 回写 OT;此处仅读改单失效与 Excel ready。
|
||||
# [BE-01] 读取改单失效起点与 Excel Artifact ready 事实。
|
||||
notice = None
|
||||
invalidated_from_stage = None
|
||||
excel_ready = False
|
||||
if order_task.shipping_notice_id:
|
||||
notice = db.session.get(ShippingNotice, int(order_task.shipping_notice_id))
|
||||
if notice is not None:
|
||||
notice_status, notice_stage = _notice_processing_status_stage(notice)
|
||||
status = notice_status
|
||||
stage = notice_stage
|
||||
from app.services.shipping_notice.task_workflow import (
|
||||
read_notice_invalidated_from_stage,
|
||||
)
|
||||
from app.services.shipping_notice.schema_edit_policy import (
|
||||
is_excel_ready_for_task,
|
||||
)
|
||||
|
||||
invalidated_from_stage = read_notice_invalidated_from_stage(notice)
|
||||
excel_ready = is_excel_ready_for_task(notice)
|
||||
# [BE-02] 投影只读:不得在 GET 路径清库。
|
||||
# 若写路径尚未清掉失效标记,但 Excel 已就绪且履约已越过失效点,仅对展示折叠失效。
|
||||
if (
|
||||
invalidated_from_stage
|
||||
and excel_ready
|
||||
and stage in {'freight_uploading', 'completed'}
|
||||
):
|
||||
invalidated_from_stage = None
|
||||
|
||||
root_task_no = str(getattr(run, 'user_task_no', None) or '').strip() or user_task_no
|
||||
is_root = user_task_no == root_task_no
|
||||
# [P0] 深链订单处理工作台需要 run_no / case_no;禁止前端合成 OT 时丢失。
|
||||
run_no = str(getattr(run, 'run_no', None) or '').strip() or None
|
||||
case_no = None
|
||||
open_case = (
|
||||
ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.run_id == int(run.id),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
|
||||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||||
)
|
||||
.order_by(ShippingOrderReviewCase.id.desc())
|
||||
.first()
|
||||
)
|
||||
if open_case is not None:
|
||||
case_no = str(getattr(open_case, 'case_no', None) or '').strip() or None
|
||||
elif order_task is not None and getattr(order_task, 'candidate_id', None):
|
||||
linked_case = (
|
||||
ShippingOrderReviewCase.query.filter_by(
|
||||
candidate_id=int(order_task.candidate_id),
|
||||
)
|
||||
.order_by(ShippingOrderReviewCase.id.desc())
|
||||
.first()
|
||||
)
|
||||
if linked_case is not None:
|
||||
case_no = str(getattr(linked_case, 'case_no', None) or '').strip() or None
|
||||
|
||||
return {
|
||||
return reconcile_processing_projection_facts(
|
||||
{
|
||||
'work_item_type': 'order_task',
|
||||
'work_item_no': user_task_no,
|
||||
'source_type': source_type,
|
||||
'root_order_task_no': root_task_no,
|
||||
'shipping_notice_no': _notice_no_for_order_task(order_task),
|
||||
'run_no': run_no,
|
||||
'case_no': case_no,
|
||||
'conversation_id': str(run.conversation_id or '').strip() or None,
|
||||
'submission_no': _submission_no_for_run(run),
|
||||
'intake_no': _first_intake_no_for_run(run),
|
||||
@@ -995,7 +1055,7 @@ def _project_order_task_work_item(
|
||||
or getattr(run, 'updated_at', None)
|
||||
) or '',
|
||||
'current_gate': _order_task_current_gate(run, order_task),
|
||||
'available_actions': available_actions,
|
||||
'available_actions': legacy_actions,
|
||||
'source_summary': _order_task_source_summary(
|
||||
run,
|
||||
order_task,
|
||||
@@ -1005,7 +1065,11 @@ def _project_order_task_work_item(
|
||||
'child_order_tasks': (
|
||||
_child_order_tasks_for_run(run, root_task_no=root_task_no) if is_root else []
|
||||
),
|
||||
}
|
||||
},
|
||||
legacy_actions=legacy_actions,
|
||||
invalidated_from_stage=invalidated_from_stage,
|
||||
excel_ready=excel_ready,
|
||||
)
|
||||
|
||||
|
||||
def _intake_ids_linked_to_active_ot(*, user_id: int, conversation_id: str) -> set[int]:
|
||||
@@ -1194,7 +1258,8 @@ def _conversation_processing_from_work_items(
|
||||
"""
|
||||
由最终 work_items 重建 conversation_processing 兼容块(含兄弟 OT)。
|
||||
|
||||
核心逻辑:仅消费 order_task 项;按 status/stage 分组并汇总 summary;
|
||||
核心逻辑:仅消费 order_task 项;按 status/stage 分组;文件总数优先按
|
||||
source_summary.document_id 去重,避免异常兄弟 OT 重复累计同一 PDF;
|
||||
保留调用方传入的 focused_task_no / recent_task_no。
|
||||
|
||||
Args:
|
||||
@@ -1234,7 +1299,19 @@ def _conversation_processing_from_work_items(
|
||||
processing.sort(key=_sort_key, reverse=True)
|
||||
completed.sort(key=_sort_key, reverse=True)
|
||||
total = len(needs_action) + len(processing) + len(completed)
|
||||
total_files = sum(int(row.get('file_count') or 0) for row in needs_action + processing + completed)
|
||||
# [STEP 2] 会话文件数是业务 PDF 去重数,不是各任务 Run 文档数的简单求和。
|
||||
document_ids = {
|
||||
int(summary.get('document_id'))
|
||||
for item in work_items
|
||||
if isinstance(item, dict) and str(item.get('work_item_type') or '') == 'order_task'
|
||||
for summary in [item.get('source_summary')]
|
||||
if isinstance(summary, dict) and int(summary.get('document_id') or 0) > 0
|
||||
}
|
||||
total_files = (
|
||||
len(document_ids)
|
||||
if document_ids
|
||||
else sum(int(row.get('file_count') or 0) for row in needs_action + processing + completed)
|
||||
)
|
||||
return {
|
||||
'summary': {
|
||||
'total_tasks': total,
|
||||
@@ -1267,8 +1344,8 @@ def project_conversation_processing_items(
|
||||
投影会话级统一 ShippingProcessingProjection 列表。
|
||||
|
||||
核心逻辑:
|
||||
1. 复用 project_conversation_processing 得到 OT 分组与兼容载荷;
|
||||
2. 将会话任务卡映射为 order_task work_items;
|
||||
1. 直接批量加载会话 ShippingOrderTask 与关联 Run;
|
||||
2. 将每个真实 OT 映射为 order_task work_item;
|
||||
3. 加载尚未建 OT / 仍在解析的 Intake,映射为 order_intake;
|
||||
4. 返回 work_items + conversation_processing 兼容块。
|
||||
|
||||
@@ -1289,66 +1366,81 @@ def project_conversation_processing_items(
|
||||
if not normalized:
|
||||
raise ValidationError('conversation_id is required')
|
||||
|
||||
conversation_processing = project_conversation_processing(
|
||||
user_id=int(user_id),
|
||||
conversation_id=normalized,
|
||||
focused_task_no=focused_task_no,
|
||||
recent_task_no=recent_task_no,
|
||||
recent_decision=recent_decision,
|
||||
recent_append_count=recent_append_count,
|
||||
)
|
||||
# 仅恢复最近焦点元数据;不再执行旧 Run 级会话投影。
|
||||
focused_override = str(focused_task_no or '').strip() or None
|
||||
if not focused_override:
|
||||
from app.services.shipping_notice.conversation_processing_projection import (
|
||||
_latest_focused_task_no,
|
||||
)
|
||||
|
||||
focused_override = _latest_focused_task_no(
|
||||
user_id=int(user_id),
|
||||
conversation_id=normalized,
|
||||
)
|
||||
|
||||
work_items: list[dict[str, Any]] = []
|
||||
seen_task_nos: set[str] = set()
|
||||
for group in ('needs_action', 'processing', 'completed', 'history'):
|
||||
for task_row in conversation_processing.get(group) or []:
|
||||
if not isinstance(task_row, dict):
|
||||
continue
|
||||
task_no = str(task_row.get('user_task_no') or '').strip()
|
||||
run_no = str(task_row.get('run_no') or '').strip()
|
||||
if not task_no or task_no in seen_task_nos:
|
||||
continue
|
||||
run = None
|
||||
if run_no:
|
||||
run = ShippingOrderProcessingRun.query.filter_by(
|
||||
run_no=run_no,
|
||||
user_id=int(user_id),
|
||||
).first()
|
||||
if run is None:
|
||||
run = (
|
||||
ShippingOrderProcessingRun.query.filter_by(
|
||||
user_task_no=task_no,
|
||||
user_id=int(user_id),
|
||||
conversation_id=normalized,
|
||||
)
|
||||
.order_by(
|
||||
ShippingOrderProcessingRun.last_activity_at.desc().nullslast(),
|
||||
ShippingOrderProcessingRun.created_at.desc(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if run is None:
|
||||
continue
|
||||
projected = _project_order_task_work_item(run, task_row=task_row)
|
||||
if projected is None:
|
||||
continue
|
||||
# [STEP 1] OT 是统一进度聚合根;禁止为构造统一投影先执行旧 Run 级会话投影。
|
||||
order_tasks = (
|
||||
ShippingOrderTask.query.filter(
|
||||
ShippingOrderTask.user_id == int(user_id),
|
||||
ShippingOrderTask.conversation_id == normalized,
|
||||
)
|
||||
.order_by(ShippingOrderTask.updated_at.desc(), ShippingOrderTask.id.desc())
|
||||
.limit(200)
|
||||
.all()
|
||||
)
|
||||
run_ids = {
|
||||
int(task.extraction_run_id)
|
||||
for task in order_tasks
|
||||
if task.extraction_run_id
|
||||
}
|
||||
runs_by_id = {
|
||||
int(run.id): run
|
||||
for run in (
|
||||
ShippingOrderProcessingRun.query.filter(
|
||||
ShippingOrderProcessingRun.id.in_(run_ids),
|
||||
ShippingOrderProcessingRun.user_id == int(user_id),
|
||||
).all()
|
||||
if run_ids
|
||||
else []
|
||||
)
|
||||
}
|
||||
missing_task_nos = [
|
||||
str(task.task_no or '').strip()
|
||||
for task in order_tasks
|
||||
if not task.extraction_run_id and str(task.task_no or '').strip()
|
||||
]
|
||||
latest_run_by_task: dict[str, ShippingOrderProcessingRun] = {}
|
||||
if missing_task_nos:
|
||||
fallback_runs = (
|
||||
ShippingOrderProcessingRun.query.filter(
|
||||
ShippingOrderProcessingRun.user_id == int(user_id),
|
||||
ShippingOrderProcessingRun.conversation_id == normalized,
|
||||
ShippingOrderProcessingRun.user_task_no.in_(missing_task_nos),
|
||||
)
|
||||
.order_by(
|
||||
ShippingOrderProcessingRun.last_activity_at.desc().nullslast(),
|
||||
ShippingOrderProcessingRun.created_at.desc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for fallback_run in fallback_runs:
|
||||
task_no = str(fallback_run.user_task_no or '').strip()
|
||||
if task_no and task_no not in latest_run_by_task:
|
||||
latest_run_by_task[task_no] = fallback_run
|
||||
|
||||
for order_task in order_tasks:
|
||||
task_no = str(order_task.task_no or '').strip()
|
||||
run = (
|
||||
runs_by_id.get(int(order_task.extraction_run_id))
|
||||
if order_task.extraction_run_id
|
||||
else latest_run_by_task.get(task_no)
|
||||
)
|
||||
if run is None:
|
||||
continue
|
||||
projected = _project_order_task_work_item(run, order_task=order_task)
|
||||
if projected is not None:
|
||||
work_items.append(projected)
|
||||
seen_task_nos.add(task_no)
|
||||
# [BE-04] 同 Run 兄弟 OT 各自独立成为 work_item,可按自身 task_no 拉取详情。
|
||||
for sibling in ShippingOrderTask.query.filter(
|
||||
ShippingOrderTask.extraction_run_id == int(run.id),
|
||||
ShippingOrderTask.task_no != task_no,
|
||||
).order_by(ShippingOrderTask.id.asc()).all():
|
||||
sibling_no = str(sibling.task_no or '').strip()
|
||||
if not sibling_no or sibling_no in seen_task_nos:
|
||||
continue
|
||||
sibling_item = _project_order_task_work_item(
|
||||
run, task_row=task_row, order_task=sibling,
|
||||
)
|
||||
if sibling_item is None:
|
||||
continue
|
||||
work_items.append(sibling_item)
|
||||
seen_task_nos.add(sibling_no)
|
||||
|
||||
linked_intake_ids = _intake_ids_linked_to_active_ot(
|
||||
user_id=int(user_id),
|
||||
@@ -1387,8 +1479,7 @@ def project_conversation_processing_items(
|
||||
project_intake_work_item(intake, submission=submission, asset=asset)
|
||||
)
|
||||
|
||||
focused_override = str(focused_task_no or '').strip() or conversation_processing.get('focused_task_no')
|
||||
recent_override = str(recent_task_no or '').strip() or conversation_processing.get('recent_task_no')
|
||||
recent_override = str(recent_task_no or '').strip() or None
|
||||
rebuilt = _conversation_processing_from_work_items(
|
||||
work_items,
|
||||
focused_task_no=focused_override,
|
||||
@@ -1397,12 +1488,8 @@ def project_conversation_processing_items(
|
||||
# 写路径元数据:保留提交决策与追加计数,供前端卡片提示。
|
||||
if recent_decision is not None:
|
||||
rebuilt['recent_decision'] = recent_decision
|
||||
elif conversation_processing.get('recent_decision') is not None:
|
||||
rebuilt['recent_decision'] = conversation_processing.get('recent_decision')
|
||||
if recent_append_count is not None:
|
||||
rebuilt['recent_append_count'] = recent_append_count
|
||||
elif conversation_processing.get('recent_append_count') is not None:
|
||||
rebuilt['recent_append_count'] = conversation_processing.get('recent_append_count')
|
||||
|
||||
return {
|
||||
'conversation_id': normalized,
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
services/shipping_notice/task_order_field_editor.py
|
||||
|
||||
用途:在人工复核时更新任务当前订单解析的已裁决 FieldValue。
|
||||
依赖:订单 Schema 运行模型、ShippingTaskFieldConflict、SQLAlchemy db。
|
||||
逻辑:按当前发布契约的 field_code 找到稳定 field_id,仅修改当前 accepted Extraction 对应行的 Decision/FieldValue,不回写旧任务行投影。
|
||||
依赖:订单 Schema 运行模型、schema_edit_policy(Excel 冻结)、SQLAlchemy db。
|
||||
逻辑:按当前发布契约的 field_code 找到稳定 field_id,仅修改当前 accepted Extraction 对应行的
|
||||
Decision/FieldValue;正式 Schema 字段写入以 Excel ready 冻结,不再被 order_snapshot_id 拦截。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,6 +22,7 @@ from app.models import (
|
||||
ShippingNotice,
|
||||
)
|
||||
from app.services.shipping_notice.order_freeze_service import assert_task_order_is_editable
|
||||
from app.services.shipping_notice.schema_edit_policy import assert_formal_task_not_excel_frozen
|
||||
|
||||
|
||||
def current_line_field_values(task: ShippingNotice) -> list[dict[str, Any]]:
|
||||
@@ -187,8 +189,12 @@ def _field_value_columns(value: Any, value_type: str) -> dict[str, Any]:
|
||||
|
||||
|
||||
def replace_current_line_field_value(*, task: ShippingNotice, position: int, field_code: str, value: Any) -> None:
|
||||
"""将人工确认值写入当前 accepted Extraction 的稳定字段,缺少值投影时补建 FieldValue。"""
|
||||
assert_task_order_is_editable(task)
|
||||
"""
|
||||
将人工确认值写入当前 accepted Extraction 的稳定字段,缺少值投影时补建 FieldValue。
|
||||
|
||||
核心逻辑:Excel ready 时拒绝写入;有 order_snapshot_id 但 Excel 未 ready 时仍允许 Schema 行字段编辑。
|
||||
"""
|
||||
assert_formal_task_not_excel_frozen(task)
|
||||
extraction = _current_extraction(task)
|
||||
config = next(
|
||||
(
|
||||
@@ -231,8 +237,12 @@ def replace_current_line_field_value(*, task: ShippingNotice, position: int, fie
|
||||
|
||||
|
||||
def replace_current_header_field_value(*, task: ShippingNotice, field_code: str, value: Any) -> None:
|
||||
"""将人工确认值写入当前 accepted Extraction 的单头 FieldValue。"""
|
||||
assert_task_order_is_editable(task)
|
||||
"""
|
||||
将人工确认值写入当前 accepted Extraction 的单头 FieldValue。
|
||||
|
||||
核心逻辑:与行字段一致,正式 Schema 写入以 Excel ready 冻结,不因 snapshot 阻断。
|
||||
"""
|
||||
assert_formal_task_not_excel_frozen(task)
|
||||
extraction = _current_extraction(task)
|
||||
config = next(
|
||||
(
|
||||
@@ -268,8 +278,12 @@ def replace_current_header_field_value(*, task: ShippingNotice, field_code: str,
|
||||
|
||||
|
||||
def replace_current_line_fields(*, task: ShippingNotice, lines: list[dict[str, Any]]) -> None:
|
||||
"""以人工确认的完整行集创建新的已接受 Extraction,供新增或删除订单行使用。"""
|
||||
assert_task_order_is_editable(task)
|
||||
"""
|
||||
以人工确认的完整行集创建新的已接受 Extraction,供新增或删除订单行使用。
|
||||
|
||||
核心逻辑:整行替换同属正式 Schema 编辑路径,Excel ready 时冻结;snapshot 不单独拦截。
|
||||
"""
|
||||
assert_formal_task_not_excel_frozen(task)
|
||||
extraction = _current_extraction(task)
|
||||
configs = [
|
||||
item for item in (extraction.schema_version.definition_json or {}).get('fields') or []
|
||||
|
||||
@@ -74,7 +74,6 @@ from app.services.shipping_notice.tool_common import (
|
||||
set_task_step_progress,
|
||||
task_lifecycle_audit_snapshot,
|
||||
)
|
||||
from app.services.shipping_notice.order_freeze_service import assert_task_order_is_editable
|
||||
from app.models import ShippingOrderCandidate, ShippingOrderReviewEvent
|
||||
|
||||
EDITABLE_NOTICE_FIELDS = frozenset({"customer_name", "customer_code", "ship_to", "po_number", "required_date"})
|
||||
@@ -296,7 +295,7 @@ def _notice_header_snapshot(task: ShippingNotice) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _reset_notice_edit_downstream(task: ShippingNotice) -> None:
|
||||
"""清空匹配/导出/上传等派生结果,供 legacy 改单或 rerun_inventory 类 change_effect 使用。"""
|
||||
"""清空匹配/导出/上传等派生结果,供 require_revision / 库存重算类 change_effect 使用。"""
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
task.line_results_json = None
|
||||
@@ -312,6 +311,9 @@ def _reset_notice_edit_downstream(task: ShippingNotice) -> None:
|
||||
task.upload_error_message = None
|
||||
task.upload_receipt_json = None
|
||||
task.idempotency_key = None
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
step_payload.pop('export_meta', None)
|
||||
task.step_payload_json = step_payload
|
||||
|
||||
|
||||
def _reset_notice_export_downstream(task: ShippingNotice) -> None:
|
||||
@@ -328,6 +330,9 @@ def _reset_notice_export_downstream(task: ShippingNotice) -> None:
|
||||
task.upload_error_message = None
|
||||
task.upload_receipt_json = None
|
||||
task.idempotency_key = None
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
step_payload.pop('export_meta', None)
|
||||
task.step_payload_json = step_payload
|
||||
|
||||
|
||||
def _resolve_order_task_for_notice(task: ShippingNotice):
|
||||
@@ -345,26 +350,101 @@ def _resolve_order_task_for_notice(task: ShippingNotice):
|
||||
)
|
||||
|
||||
|
||||
def _set_notice_invalidated_from_stage(task: ShippingNotice, stage: str) -> None:
|
||||
"""
|
||||
将改单失效起点写入 Notice.step_payload_json,供投影 stage_nodes 消费。
|
||||
|
||||
[BE-08] 写入时追加 invalidated_from_stage_history,降低无历史可追溯风险;
|
||||
完整列级约束与乐观锁仍待显式字段迁移。
|
||||
|
||||
Args:
|
||||
task: 被编辑的正式任务。
|
||||
stage: 失效起点统一 stage。
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from app.services.shipping_notice.progress_audit_contract import SHIPPING_PROCESSING_STAGES
|
||||
|
||||
code = str(stage or '').strip().lower()
|
||||
if code not in SHIPPING_PROCESSING_STAGES:
|
||||
return
|
||||
payload = dict(task.step_payload_json or {}) if isinstance(task.step_payload_json, dict) else {}
|
||||
history = payload.get('invalidated_from_stage_history')
|
||||
if not isinstance(history, list):
|
||||
history = []
|
||||
history.append({
|
||||
'stage': code,
|
||||
'at': datetime.utcnow().isoformat(timespec='seconds') + 'Z',
|
||||
'progress_version': int(getattr(task, 'progress_version', None) or 0),
|
||||
})
|
||||
payload['invalidated_from_stage'] = code
|
||||
payload['invalidated_from_stage_history'] = history[-20:]
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def _clear_notice_invalidated_from_stage(task: ShippingNotice) -> None:
|
||||
"""
|
||||
清除 Notice 上的改单失效起点(下游已成功重跑后)。
|
||||
|
||||
[BE-08] 清除仅移除当前起点;历史列表保留供审计追溯。
|
||||
"""
|
||||
if not isinstance(task.step_payload_json, dict):
|
||||
return
|
||||
if 'invalidated_from_stage' not in task.step_payload_json:
|
||||
return
|
||||
payload = dict(task.step_payload_json)
|
||||
payload.pop('invalidated_from_stage', None)
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def read_notice_invalidated_from_stage(task: ShippingNotice | None) -> str | None:
|
||||
"""
|
||||
读取正式任务上的改单失效起点 stage。
|
||||
|
||||
Args:
|
||||
task: ShippingNotice;可空。
|
||||
|
||||
Returns:
|
||||
合法统一 stage;无则 None。
|
||||
"""
|
||||
from app.services.shipping_notice.progress_audit_contract import SHIPPING_PROCESSING_STAGES
|
||||
|
||||
if task is None:
|
||||
return None
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
code = str(payload.get('invalidated_from_stage') or '').strip().lower()
|
||||
return code if code in SHIPPING_PROCESSING_STAGES else None
|
||||
|
||||
|
||||
def _apply_notice_edit_change_effects(
|
||||
task: ShippingNotice,
|
||||
edited_field_scopes: list[tuple[str, str]],
|
||||
) -> set[str]:
|
||||
"""
|
||||
按 Schema change_effect 选择性失效下游;legacy 无策略字段保持全量 reset。
|
||||
按 Schema change_effect 选择性失效下游;无 legacy 全量 reset。
|
||||
|
||||
核心逻辑:rerun_inventory_matching → 清空匹配+导出并同步 OT inventory_matching;
|
||||
regenerate_excel → 仅清空导出并同步 OT excel_generating;
|
||||
全部显式 none → 跳过重型 reset(快照冻结仍由 assert_task_order_is_editable 拦截)。
|
||||
核心逻辑:
|
||||
rerun_inventory_source_resolution → 清匹配/导出、重裁库存源、OT inventory_source_resolving;
|
||||
rerun_inventory_matching → 清匹配/导出、OT inventory_matching;
|
||||
regenerate_excel → 仅清导出、OT excel_generating;
|
||||
require_revision → 全量下游 reset;
|
||||
none → 跳过重型 reset(Excel 冻结由 assert_formal_task_not_excel_frozen 拦截)。
|
||||
同时写入 invalidated_from_stage,供四页面 stage_nodes 表达“曾通过现已失效”。
|
||||
|
||||
Args:
|
||||
task: 被编辑的 ShippingNotice。
|
||||
edited_field_scopes: (scope, field_code) 列表。
|
||||
|
||||
Returns:
|
||||
实际应用的 effect 集合(含 legacy_full_reset);无下游失效时为空集。
|
||||
实际应用的 effect 集合;无下游失效时为空集。
|
||||
"""
|
||||
from app.services.shipping_notice.schema_edit_policy import collect_change_effects_for_fields
|
||||
from app.services.shipping_notice.order_task_service import sync_order_task_processing_state
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
STABLE_INVENTORY_SOURCE_STATUSES,
|
||||
adjudicate_and_apply_inventory_source,
|
||||
clear_inventory_source_confirmation,
|
||||
)
|
||||
|
||||
if not edited_field_scopes:
|
||||
return set()
|
||||
@@ -374,56 +454,82 @@ def _apply_notice_edit_change_effects(
|
||||
grouped.setdefault(str(scope), []).append(str(code))
|
||||
|
||||
effects: set[str] = set()
|
||||
has_legacy = False
|
||||
for scope, codes in grouped.items():
|
||||
scope_effects, legacy = collect_change_effects_for_fields(task, codes, scope=scope)
|
||||
effects |= scope_effects
|
||||
has_legacy = has_legacy or legacy
|
||||
|
||||
if has_legacy:
|
||||
_reset_notice_edit_downstream(task)
|
||||
return {'legacy_full_reset'}
|
||||
effects |= collect_change_effects_for_fields(task, codes, scope=scope)
|
||||
|
||||
if not effects:
|
||||
return set()
|
||||
|
||||
order_task = _resolve_order_task_for_notice(task)
|
||||
if 'rerun_inventory_matching' in effects or 'rerun_inventory_source_resolution' in effects:
|
||||
applied: set[str] = set()
|
||||
|
||||
# [STEP] 库存源重算优先于匹配重算:不得跳过 inventory_source_resolving。
|
||||
if 'rerun_inventory_source_resolution' in effects:
|
||||
clear_inventory_source_confirmation(task)
|
||||
task.inventory_source_status = 'unresolved'
|
||||
task.inventory_source_code = None
|
||||
task.inventory_connector_type = None
|
||||
task.inventory_warehouse_id = None
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
task.line_results_json = None
|
||||
task.inventory_lines_json = None
|
||||
_reset_notice_export_downstream(task)
|
||||
_set_notice_invalidated_from_stage(task, 'inventory_source_resolving')
|
||||
adjudication = adjudicate_and_apply_inventory_source(task)
|
||||
stable = str(adjudication.status or '').strip() in STABLE_INVENTORY_SOURCE_STATUSES
|
||||
if order_task is not None:
|
||||
if stable:
|
||||
sync_order_task_processing_state(
|
||||
order_task,
|
||||
stage='inventory_fetching',
|
||||
status='processing',
|
||||
)
|
||||
_clear_notice_invalidated_from_stage(task)
|
||||
else:
|
||||
sync_order_task_processing_state(
|
||||
order_task,
|
||||
stage='inventory_source_resolving',
|
||||
status='blocked',
|
||||
)
|
||||
applied.add('rerun_inventory_source_resolution')
|
||||
return applied
|
||||
|
||||
if 'rerun_inventory_matching' in effects:
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
task.line_results_json = None
|
||||
task.inventory_lines_json = None
|
||||
_reset_notice_export_downstream(task)
|
||||
_set_notice_invalidated_from_stage(task, 'inventory_matching')
|
||||
if order_task is not None:
|
||||
sync_order_task_processing_state(
|
||||
order_task,
|
||||
stage='inventory_matching',
|
||||
status='processing',
|
||||
)
|
||||
return {
|
||||
effect for effect in effects
|
||||
if effect in {
|
||||
'rerun_inventory_matching',
|
||||
'rerun_inventory_source_resolution',
|
||||
'regenerate_excel',
|
||||
}
|
||||
} or {'rerun_inventory_matching'}
|
||||
applied.add('rerun_inventory_matching')
|
||||
return applied
|
||||
|
||||
if 'regenerate_excel' in effects:
|
||||
_reset_notice_export_downstream(task)
|
||||
_set_notice_invalidated_from_stage(task, 'excel_generating')
|
||||
if order_task is not None:
|
||||
sync_order_task_processing_state(
|
||||
order_task,
|
||||
stage='excel_generating',
|
||||
status='processing',
|
||||
)
|
||||
return {'regenerate_excel'}
|
||||
applied.add('regenerate_excel')
|
||||
return applied
|
||||
|
||||
if 'require_revision' in effects:
|
||||
_reset_notice_edit_downstream(task)
|
||||
return {'require_revision'}
|
||||
_set_notice_invalidated_from_stage(task, 'waiting_review')
|
||||
applied.add('require_revision')
|
||||
return applied
|
||||
|
||||
return set()
|
||||
return applied
|
||||
|
||||
|
||||
def _formal_edit_field_diff_summary(
|
||||
@@ -434,20 +540,28 @@ def _formal_edit_field_diff_summary(
|
||||
after_lines: list[dict[str, Any]] | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
生成正式编辑字段 Diff 摘要(仅字段码与行号,不含大段原文)。
|
||||
生成正式编辑字段 Diff 摘要(含脱敏前后值)。
|
||||
|
||||
Args:
|
||||
before_header/after_header: 单头前后快照。
|
||||
before_lines/after_lines: 行前后快照。
|
||||
|
||||
Returns:
|
||||
变更条目列表(scope/field/line_index)。
|
||||
变更条目列表(scope/field/line_index/previous_value/new_value)。
|
||||
"""
|
||||
from app.services.shipping_notice.schema_edit_policy import sanitize_audit_field_value
|
||||
|
||||
changes: list[dict[str, Any]] = []
|
||||
for field, before in (before_header or {}).items():
|
||||
after = (after_header or {}).get(field)
|
||||
if before != after:
|
||||
changes.append({'scope': 'header', 'field': field, 'line_index': None})
|
||||
changes.append({
|
||||
'scope': 'header',
|
||||
'field': field,
|
||||
'line_index': None,
|
||||
'previous_value': sanitize_audit_field_value(before),
|
||||
'new_value': sanitize_audit_field_value(after),
|
||||
})
|
||||
before_line_rows = before_lines or []
|
||||
after_line_rows = after_lines or []
|
||||
for position in range(max(len(before_line_rows), len(after_line_rows))):
|
||||
@@ -455,7 +569,13 @@ def _formal_edit_field_diff_summary(
|
||||
after = after_line_rows[position] if position < len(after_line_rows) else {}
|
||||
for field in sorted(set(before) | set(after)):
|
||||
if before.get(field) != after.get(field):
|
||||
changes.append({'scope': 'line', 'field': field, 'line_index': position})
|
||||
changes.append({
|
||||
'scope': 'line',
|
||||
'field': field,
|
||||
'line_index': position,
|
||||
'previous_value': sanitize_audit_field_value(before.get(field)),
|
||||
'new_value': sanitize_audit_field_value(after.get(field)),
|
||||
})
|
||||
return changes[:64]
|
||||
|
||||
|
||||
@@ -539,7 +659,6 @@ def _record_formal_task_edit_audits(
|
||||
if applied_effects & {
|
||||
'rerun_inventory_matching',
|
||||
'rerun_inventory_source_resolution',
|
||||
'legacy_full_reset',
|
||||
'require_revision',
|
||||
}:
|
||||
record_fulfillment_audit(
|
||||
@@ -562,7 +681,6 @@ def _record_formal_task_edit_audits(
|
||||
'regenerate_excel',
|
||||
'rerun_inventory_matching',
|
||||
'rerun_inventory_source_resolution',
|
||||
'legacy_full_reset',
|
||||
'require_revision',
|
||||
}:
|
||||
record_fulfillment_audit(
|
||||
@@ -824,8 +942,11 @@ def _commit_notice_edit(
|
||||
idempotency_key: str | None = None,
|
||||
edited_field_scopes: list[tuple[str, str]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""提交冻结前的人工复核,记录证据审计并使旧库存/导出派生结果失效。"""
|
||||
assert_task_order_is_editable(task)
|
||||
"""提交正式任务字段编辑,记录证据审计并按 change_effect 失效下游。"""
|
||||
from app.services.shipping_notice.schema_edit_policy import assert_formal_task_not_excel_frozen
|
||||
|
||||
# Formal Schema 编辑以 Excel ready 为硬冻结,不再用 order_snapshot_id 阻断。
|
||||
assert_formal_task_not_excel_frozen(task)
|
||||
reviewed_by_id = None
|
||||
evidence_ref = ''
|
||||
reason = ''
|
||||
@@ -855,20 +976,23 @@ def _commit_notice_edit(
|
||||
step_payload.pop('process_field_gate', None)
|
||||
task.step_payload_json = step_payload
|
||||
|
||||
# [STEP 2] 解析编辑后按 change_effect 重置下游结果并进入重新确认,避免旧匹配真相继续生效。
|
||||
apply_task_transition(
|
||||
task,
|
||||
TaskTransition.RSV_REQUIRED if validation_issues else TaskTransition.PARSE_NEEDS_REVIEW,
|
||||
)
|
||||
# 失效前快照:供 ShippingAuditEvent before 使用(不含敏感正文)。
|
||||
# [STEP 2] 先按 change_effect 失效下游;仅缺字段或 require_revision 才回旧复核态。
|
||||
before_match_status = task.match_status
|
||||
before_export_file_name = task.export_file_name
|
||||
before_order_data_version = task.order_data_version
|
||||
applied_effects = _apply_notice_edit_change_effects(task, edited_field_scopes or [])
|
||||
if validation_issues:
|
||||
apply_task_transition(task, TaskTransition.RSV_REQUIRED)
|
||||
elif 'require_revision' in applied_effects:
|
||||
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
|
||||
message = (
|
||||
"已更新订单字段,但仍有后续处理必需字段待补充。"
|
||||
if validation_issues
|
||||
else "已更新解析结果,请重新确认。"
|
||||
else (
|
||||
"已更新正式任务字段,下游结果已按策略失效。"
|
||||
if applied_effects
|
||||
else "已更新正式任务字段。"
|
||||
)
|
||||
)
|
||||
_remember_notice_edit_idempotency(task, key=idempotency_key, message=message)
|
||||
log_task_event(
|
||||
@@ -937,8 +1061,18 @@ def _commit_notice_edit(
|
||||
|
||||
|
||||
def _prepare_review_context(task: ShippingNotice, payload: dict[str, Any]) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
|
||||
"""校验冻结前纠错的操作者、证据和原因,禁止 Dify 或无证据路径直接改订单。"""
|
||||
assert_task_order_is_editable(task)
|
||||
"""校验正式编辑的操作者、证据和原因;Excel ready 后拒绝写入。"""
|
||||
from app.services.shipping_notice.schema_edit_policy import assert_formal_task_not_excel_frozen
|
||||
|
||||
try:
|
||||
assert_formal_task_not_excel_frozen(task)
|
||||
except ConflictError as exc:
|
||||
return None, tool_response(
|
||||
status='failed',
|
||||
task=task,
|
||||
message=str(exc),
|
||||
data={'error_code': exc.code, **(exc.details or {})},
|
||||
)
|
||||
if str(payload.get('event_source') or '').strip() != 'workspace_api':
|
||||
return None, tool_response(
|
||||
status='failed', task=task, message='订单纠错只能由工作台人工复核提交',
|
||||
@@ -989,7 +1123,12 @@ def update_notice_fields(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not isinstance(fields, dict) or not fields:
|
||||
return tool_response(status="failed", task=task, message="fields 不能为空")
|
||||
|
||||
patch = {key: value for key, value in fields.items() if key in EDITABLE_NOTICE_FIELDS}
|
||||
# 仅 Schema 策略决定可写字段;不再用 legacy EDITABLE_NOTICE_FIELDS 绕过。
|
||||
patch = {
|
||||
str(key).strip(): value
|
||||
for key, value in fields.items()
|
||||
if str(key).strip()
|
||||
}
|
||||
if not patch:
|
||||
return tool_response(status="failed", task=task, message="没有可更新的单头字段")
|
||||
|
||||
@@ -1000,7 +1139,6 @@ def update_notice_fields(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task,
|
||||
list(patch.keys()),
|
||||
scope='header',
|
||||
legacy_whitelist=EDITABLE_NOTICE_FIELDS,
|
||||
)
|
||||
except ConflictError as exc:
|
||||
_record_formal_task_edit_rejection(
|
||||
@@ -1085,7 +1223,11 @@ def update_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if line_index < 0 or line_index >= len(lines):
|
||||
return tool_response(status="failed", task=task, message="line_index 超出范围")
|
||||
|
||||
normalized_patch = {key: value for key, value in patch.items() if key in EDITABLE_NOTICE_LINE_FIELDS}
|
||||
normalized_patch = {
|
||||
str(key).strip(): value
|
||||
for key, value in patch.items()
|
||||
if str(key).strip()
|
||||
}
|
||||
if not normalized_patch:
|
||||
return tool_response(status="failed", task=task, message="没有可更新的行字段")
|
||||
|
||||
@@ -1108,7 +1250,6 @@ def update_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task,
|
||||
list(normalized_patch.keys()),
|
||||
scope='line',
|
||||
legacy_whitelist=EDITABLE_NOTICE_LINE_FIELDS,
|
||||
)
|
||||
except ConflictError as exc:
|
||||
_record_formal_task_edit_rejection(
|
||||
|
||||
@@ -38,3 +38,4 @@ croniter
|
||||
tzdata
|
||||
pyyaml
|
||||
minio==7.2.20
|
||||
google-re2>=1.1.20240702
|
||||
@@ -0,0 +1,118 @@
|
||||
"""
|
||||
backend/scripts/migrate_order_profiles_to_unified_bindings.py
|
||||
|
||||
用途:将订单文档模板 Dry Run / Execute 迁移到统一 bindings[]。
|
||||
依赖:Flask create_app、order_profile_unified_migration。
|
||||
逻辑:默认 Dry Run;--execute 才写 Draft Revision;可用 --profile-id 限定单个模板。
|
||||
|
||||
用法:
|
||||
cd backend
|
||||
python scripts/migrate_order_profiles_to_unified_bindings.py --dry-run
|
||||
python scripts/migrate_order_profiles_to_unified_bindings.py --profile-id 12 --dry-run
|
||||
python scripts/migrate_order_profiles_to_unified_bindings.py --profile-id 12 --execute
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||
_REPO_ROOT = _BACKEND_ROOT.parent
|
||||
if str(_BACKEND_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_BACKEND_ROOT))
|
||||
|
||||
|
||||
def _prepare_env() -> None:
|
||||
"""导入 app 前固定 ENV_NAME=dev,并允许 .env.local 覆盖 DATABASE_URL。"""
|
||||
os.environ.setdefault('ENV_NAME', 'dev')
|
||||
try:
|
||||
from dotenv import dotenv_values
|
||||
except ImportError:
|
||||
return
|
||||
local_file = _REPO_ROOT / '.env.local'
|
||||
if not local_file.exists():
|
||||
return
|
||||
values = {k: v for k, v in dotenv_values(local_file).items() if v is not None}
|
||||
if values.get('DATABASE_URL'):
|
||||
os.environ['DATABASE_URL'] = str(values['DATABASE_URL'])
|
||||
|
||||
|
||||
def _parse_args() -> argparse.Namespace:
|
||||
"""解析 --dry-run / --execute / --profile-id。"""
|
||||
parser = argparse.ArgumentParser(description='Migrate order profiles to unified bindings')
|
||||
mode = parser.add_mutually_exclusive_group()
|
||||
mode.add_argument('--dry-run', action='store_true', help='Only convert and print report (default)')
|
||||
mode.add_argument('--execute', action='store_true', help='Write Draft revision with bindings')
|
||||
parser.add_argument('--profile-id', type=int, action='append', default=[], help='Limit to profile id')
|
||||
parser.add_argument('--actor-id', type=int, default=None, help='Optional actor id for audits')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""批量 Dry Run 或 Execute;任一失败返回 1。"""
|
||||
_prepare_env()
|
||||
args = _parse_args()
|
||||
execute = bool(args.execute)
|
||||
dry_run = not execute
|
||||
|
||||
from app import create_app
|
||||
from app.models import ShippingOrderDocumentProfile
|
||||
from app.services.shipping_notice import order_profile_unified_migration as migration
|
||||
|
||||
app = create_app()
|
||||
failures = 0
|
||||
with app.app_context():
|
||||
query = ShippingOrderDocumentProfile.query
|
||||
if args.profile_id:
|
||||
query = query.filter(ShippingOrderDocumentProfile.id.in_(args.profile_id))
|
||||
rows = query.order_by(
|
||||
ShippingOrderDocumentProfile.profile_code.asc(),
|
||||
ShippingOrderDocumentProfile.version.desc(),
|
||||
).all()
|
||||
# 同族只处理最新 published 或 draft,避免重复
|
||||
seen_codes: set[str] = set()
|
||||
targets: list[ShippingOrderDocumentProfile] = []
|
||||
for row in rows:
|
||||
key = str(row.profile_code)
|
||||
if key in seen_codes:
|
||||
continue
|
||||
if row.status not in {'draft', 'published'}:
|
||||
continue
|
||||
seen_codes.add(key)
|
||||
targets.append(row)
|
||||
|
||||
print(json.dumps({
|
||||
'mode': 'execute' if execute else 'dry_run',
|
||||
'target_count': len(targets),
|
||||
}, ensure_ascii=False))
|
||||
|
||||
for profile in targets:
|
||||
try:
|
||||
if dry_run:
|
||||
result = migration.dry_run_unified_migration(
|
||||
int(profile.id),
|
||||
actor_id=args.actor_id,
|
||||
write_audit=True,
|
||||
)
|
||||
else:
|
||||
result = migration.execute_unified_migration(
|
||||
int(profile.id),
|
||||
actor_id=args.actor_id,
|
||||
)
|
||||
print(json.dumps(result, ensure_ascii=False, default=str))
|
||||
except Exception as exc:
|
||||
failures += 1
|
||||
print(json.dumps({
|
||||
'profile_id': int(profile.id),
|
||||
'error': str(exc),
|
||||
}, ensure_ascii=False), file=sys.stderr)
|
||||
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,64 @@
|
||||
"""
|
||||
backend/tests/performance/test_shipping_xfa_visual_mapping_load.py
|
||||
|
||||
用途:阶段 8 统一视觉映射建议/转换负载冒烟(合成数据,软阈值,非 flaky)。
|
||||
依赖:order_profile_unified_migration、time。
|
||||
逻辑:批量转换合成 XFA definition;断言在本地冒烟预算内完成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from app.services.shipping_notice.order_profile_unified_migration import (
|
||||
convert_xfa_definition_to_unified_bindings,
|
||||
)
|
||||
|
||||
|
||||
def _synthetic_xfa_definition(*, field_count: int = 40) -> dict:
|
||||
"""生成含多 Header/Line 映射的合成 XFA definition。"""
|
||||
headers = []
|
||||
lines = []
|
||||
for index in range(field_count // 2):
|
||||
headers.append({
|
||||
'mapping_id': f'map-h-{index}',
|
||||
'field_id': f'fld-h-{index}',
|
||||
'field_code': f'header_field_{index}',
|
||||
'data_path': f'/data/HEADER/F{index}',
|
||||
'path_id': f'path-h-{index}',
|
||||
'value_type': 'string',
|
||||
})
|
||||
lines.append({
|
||||
'mapping_id': f'map-l-{index}',
|
||||
'field_id': f'fld-l-{index}',
|
||||
'field_code': f'line_field_{index}',
|
||||
'data_path': f'/data/ITEMS/DATA/C{index}',
|
||||
'path_id': f'path-l-{index}',
|
||||
'value_type': 'string',
|
||||
})
|
||||
return {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
'mirror_collection_paths': [],
|
||||
},
|
||||
'header_mappings': headers,
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': lines},
|
||||
'bindings': [],
|
||||
'split_rules': [],
|
||||
}
|
||||
|
||||
|
||||
def test_visual_mapping_conversion_under_soft_latency_budget():
|
||||
"""40 字段统一转换应在软阈值(2s)内完成;失败才视为回归。"""
|
||||
definition = _synthetic_xfa_definition(field_count=40)
|
||||
started = time.perf_counter()
|
||||
after, stats = convert_xfa_definition_to_unified_bindings(definition, widgets=[])
|
||||
elapsed = time.perf_counter() - started
|
||||
assert stats['binding_count'] == 40
|
||||
assert len(after['bindings']) == 40
|
||||
# 软阈值:本地合成转换远快于 2s;避免偶发 GC 抖动用宽松上限。
|
||||
assert elapsed < 2.0
|
||||
@@ -120,8 +120,8 @@ def _create_mapped_draft(*, user: User, schema: ShippingOrderSchemaVersion) -> t
|
||||
return saved, paths, lease['lease_token']
|
||||
|
||||
|
||||
def test_xfa_current_sample_summary_rejects_auto_create_missing():
|
||||
"""关键断言:auto_create_key 缺值时当前样本摘要必须失败。"""
|
||||
def test_current_sample_summary_still_supports_coordinate_schema_gate():
|
||||
"""通用摘要保留坐标模板的 Schema 门禁;XFA 调用方固定传零。"""
|
||||
status, summary, _ = validation_service._current_sample_summary(
|
||||
line_field_count=2, line_value_count=2, header_field_count=1, header_value_count=1,
|
||||
header_required_missing_count=0, auto_create_key_missing_count=1,
|
||||
|
||||
@@ -43,8 +43,8 @@ def test_xfa_definition_scale_and_identity_summary():
|
||||
assert 'blind' not in str(identity).lower()
|
||||
|
||||
|
||||
def test_xfa_readonly_mapping_evidence_has_no_pdf_preview():
|
||||
"""关键断言:只读映射 DTO 明确禁用 PDF 预览且不含盲测真值键。"""
|
||||
def test_xfa_readonly_mapping_evidence_allows_pdf_preview():
|
||||
"""关键断言:只读映射 DTO 声明 PDF 预览可用(阶段 2)。"""
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
id=1,
|
||||
profile_code='XFA_RO',
|
||||
@@ -80,7 +80,7 @@ def test_xfa_readonly_mapping_evidence_has_no_pdf_preview():
|
||||
},
|
||||
)
|
||||
evidence = build_xfa_readonly_mapping_evidence(profile)
|
||||
assert evidence['pdf_preview_available'] is False
|
||||
assert evidence['pdf_preview_available'] is True
|
||||
assert evidence['template_mode'] == 'xfa_dataset'
|
||||
assert 'expected_rows' not in evidence
|
||||
assert 'expected_order_fields' not in evidence
|
||||
|
||||
@@ -123,3 +123,28 @@ def test_hash_verify_detects_tampered_chain(app):
|
||||
# 关键断言:篡改链被日检检出。
|
||||
assert int(result['hash_verify']['failed_chains']) >= 1
|
||||
assert result['hash_verify']['failures_sample']
|
||||
|
||||
|
||||
def test_retention_job_includes_xfa_snapshot_purge_key(app):
|
||||
"""shipping-audit-retention 必须覆盖 XFA 快照清理(阶段 8)。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED'] = False
|
||||
result = run_shipping_audit_retention_schedule(
|
||||
_task(limit=10, dry_run=True, hash_sample_limit=10, xfa_snapshot_limit=50),
|
||||
SimpleNamespace(),
|
||||
)
|
||||
# 关键断言:结果含 xfa_snapshots 清理统计,证明 Job 仍覆盖 XFA 快照。
|
||||
assert 'xfa_snapshots' in result
|
||||
assert 'scanned' in result['xfa_snapshots']
|
||||
assert 'deleted' in result['xfa_snapshots']
|
||||
retention = get_platform_job('shipping-audit-retention')
|
||||
assert retention is not None
|
||||
schema_keys = {field['key'] for field in retention.params_schema}
|
||||
assert 'xfa_snapshot_limit' in schema_keys or 'limit' in schema_keys
|
||||
|
||||
|
||||
def test_retention_days_default_is_1095(app):
|
||||
"""审计保留期默认 1095 天(3 年),阶段 8 运营验收。"""
|
||||
with app.app_context():
|
||||
days = int(app.config.get('SHIPPING_NOTICE_AUDIT_RETENTION_DAYS') or 0)
|
||||
assert days == 1095
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_lifecycle.py
|
||||
|
||||
用途:验证 L1 版面快照 checksum、版本幂等、容量门禁和当前成功版本保护。
|
||||
依赖:ShippingOrderDocument/LayoutVersion、document_layout.lifecycle、Flask 测试库。
|
||||
逻辑:相同快照复用;新失败/超限版本保留审计但不覆盖旧成功引用。
|
||||
用途:验证 L1 版面快照 checksum、版本幂等、XFA 证据本地化、容量门禁和当前成功版本保护。
|
||||
依赖:ShippingOrderDocument/LayoutVersion/XfaStructureAnalysis、document_layout.lifecycle、Flask 测试库。
|
||||
逻辑:相同快照复用;XFA 复用同步克隆 document-scoped 分析;失败版本不覆盖旧成功引用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,7 +11,15 @@ from __future__ import annotations
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app import db
|
||||
from app.models import Job, ShippingDocumentLayoutVersion, ShippingOrderDocument, ShippingOrderIntake, FileAsset, User
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
Job,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingXfaStructureAnalysis,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.lifecycle import (
|
||||
canonical_layout_payload,
|
||||
claim_layout_version,
|
||||
@@ -190,6 +198,123 @@ def test_recoverable_ready_layout_is_reused_for_duplicate_document(app):
|
||||
assert scheduled.id != incomplete.id
|
||||
|
||||
|
||||
def test_xfa_layout_reuse_localizes_structure_analysis_for_duplicate_document(app):
|
||||
"""相同 XFA 文件复用时,目标 Document 必须获得独立 Analysis 并重写快照身份。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
with app.app_context():
|
||||
original = _document()
|
||||
source_analysis = ShippingXfaStructureAnalysis(
|
||||
document_id=original.id,
|
||||
layout_version_id=None,
|
||||
source_content_hash=original.content_hash,
|
||||
document_kind='xfa_hybrid',
|
||||
analysis_status='ready',
|
||||
template_packet_checksum='sha256:template',
|
||||
datasets_packet_checksum='sha256:datasets',
|
||||
dataset_structure_fingerprint='sha256:structure',
|
||||
packet_checksums_json={'datasets': 'sha256:datasets'},
|
||||
stats_json={'leaf_count': 8},
|
||||
security_summary_json={'scripts_executed': False},
|
||||
tree_summary_json={'known_path_ids': ['path-1']},
|
||||
parser_identity='xfa-parser.v1',
|
||||
contract_version='xfa-contract.v1',
|
||||
)
|
||||
db.session.add(source_analysis)
|
||||
db.session.flush()
|
||||
source_layout = record_inline_layout_snapshot(original, {
|
||||
'status': 'ready',
|
||||
'provider': 'xfa',
|
||||
'provider_version': 'xfa-parser.v1',
|
||||
'backend': 'pypdf',
|
||||
'snapshot_version': 'shipping_document_layout.v1',
|
||||
'tables': [],
|
||||
'xfa_capability': {
|
||||
'structure_analysis_ready': True,
|
||||
'structure_analysis_id': source_analysis.id,
|
||||
'template_packet_checksum': source_analysis.template_packet_checksum,
|
||||
'dataset_structure_fingerprint': source_analysis.dataset_structure_fingerprint,
|
||||
},
|
||||
'capability': {
|
||||
'structure_analysis_ready': True,
|
||||
'structure_analysis_id': source_analysis.id,
|
||||
},
|
||||
})
|
||||
source_analysis.layout_version_id = source_layout.id
|
||||
|
||||
duplicate_intake = ShippingOrderIntake(
|
||||
intake_no='SNI-LAYOUT-XFA-DUPLICATE', asset_id=original.asset_id,
|
||||
user_id=db.session.get(ShippingOrderIntake, original.intake_id).user_id,
|
||||
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v6',
|
||||
)
|
||||
db.session.add(duplicate_intake)
|
||||
db.session.flush()
|
||||
duplicate = ShippingOrderDocument(
|
||||
intake_id=duplicate_intake.id, asset_id=original.asset_id, document_type='attachment',
|
||||
attachment_key='duplicate-xfa.pdf', filename='duplicate-xfa.pdf',
|
||||
content_hash=original.content_hash, classification='order_notice', parse_status='parsed',
|
||||
)
|
||||
db.session.add(duplicate)
|
||||
db.session.flush()
|
||||
|
||||
localized = schedule_layout_version(duplicate)
|
||||
db.session.commit()
|
||||
|
||||
target_analysis = ShippingXfaStructureAnalysis.query.filter_by(document_id=duplicate.id).one()
|
||||
target_capability = localized.payload_json['xfa_capability']
|
||||
assert localized.document_id == duplicate.id
|
||||
assert localized.id != source_layout.id
|
||||
assert target_analysis.id != source_analysis.id
|
||||
assert target_analysis.layout_version_id == localized.id
|
||||
assert target_analysis.source_content_hash == duplicate.content_hash
|
||||
assert target_analysis.dataset_structure_fingerprint == source_analysis.dataset_structure_fingerprint
|
||||
assert target_capability['structure_analysis_id'] == target_analysis.id
|
||||
assert localized.payload_json['capability']['structure_analysis_id'] == target_analysis.id
|
||||
|
||||
|
||||
def test_xfa_layout_without_source_analysis_is_not_reused(app):
|
||||
"""XFA 快照声明 ready 但源 Analysis 缺失时必须重新排队,禁止复制伪 ready 状态。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
with app.app_context():
|
||||
original = _document()
|
||||
source_layout = record_inline_layout_snapshot(original, {
|
||||
'status': 'ready',
|
||||
'provider': 'xfa',
|
||||
'provider_version': 'xfa-parser.v1',
|
||||
'backend': 'pypdf',
|
||||
'snapshot_version': 'shipping_document_layout.v1',
|
||||
'tables': [],
|
||||
'xfa_capability': {
|
||||
'structure_analysis_ready': True,
|
||||
'structure_analysis_id': 999999,
|
||||
'template_packet_checksum': 'sha256:template',
|
||||
'dataset_structure_fingerprint': 'sha256:structure',
|
||||
},
|
||||
})
|
||||
duplicate_intake = ShippingOrderIntake(
|
||||
intake_no='SNI-LAYOUT-XFA-MISSING-ANALYSIS', asset_id=original.asset_id,
|
||||
user_id=db.session.get(ShippingOrderIntake, original.intake_id).user_id,
|
||||
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v6',
|
||||
)
|
||||
db.session.add(duplicate_intake)
|
||||
db.session.flush()
|
||||
duplicate = ShippingOrderDocument(
|
||||
intake_id=duplicate_intake.id, asset_id=original.asset_id, document_type='attachment',
|
||||
attachment_key='duplicate-xfa-missing.pdf', filename='duplicate-xfa-missing.pdf',
|
||||
content_hash=original.content_hash, classification='order_notice', parse_status='parsed',
|
||||
)
|
||||
db.session.add(duplicate)
|
||||
db.session.flush()
|
||||
|
||||
scheduled = schedule_layout_version(duplicate)
|
||||
db.session.commit()
|
||||
|
||||
assert source_layout.status == 'ready'
|
||||
assert scheduled.document_id == duplicate.id
|
||||
assert scheduled.status == 'queued'
|
||||
assert duplicate.current_layout_version_id is None
|
||||
assert ShippingXfaStructureAnalysis.query.filter_by(document_id=duplicate.id).count() == 0
|
||||
|
||||
|
||||
def test_layout_parser_fingerprint_change_creates_new_version_without_force(app, monkeypatch):
|
||||
"""布局实现指纹变化后自动创建新版本,不依赖人工修改环境变量。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
|
||||
@@ -304,6 +304,34 @@ def test_independent_sample_review_reuses_existing_truth_and_excludes_training_i
|
||||
assert executed['latest_run']['status'] == 'passed'
|
||||
|
||||
|
||||
def test_independent_sample_without_coordinate_evidence_stays_preparing(app):
|
||||
"""关键断言:HTML 表格存在但坐标证据缺失时,不得进入会必然失败的正式复核。"""
|
||||
with app.app_context():
|
||||
profile, user, documents = _published_profile_with_samples()
|
||||
for document in documents:
|
||||
db.session.get(ShippingOrderIntake, document.intake_id).purpose = 'order_document_profile_sample'
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile.id, document_id=documents[0].id, table_id='table-1',
|
||||
sample_role='training', created_by_id=user.id,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
layout_version = documents[1].current_layout_version
|
||||
payload = dict(layout_version.payload_json)
|
||||
payload['coordinate_evidence'] = {'tables': {}, 'pages': {}, 'page_glyphs': {}}
|
||||
layout_version.payload_json = payload
|
||||
db.session.commit()
|
||||
|
||||
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
||||
candidate = next(
|
||||
item for item in quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
|
||||
if item['document_id'] == documents[1].id
|
||||
)
|
||||
assert candidate['review_mode'] == 'preparing'
|
||||
assert candidate['confirmable'] is False
|
||||
assert candidate['layout_issue_codes'] == ['coordinate_evidence_missing']
|
||||
|
||||
|
||||
def test_layout_failed_document_is_diagnostic_only(app, monkeypatch):
|
||||
"""关键断言:失败 Layout 可从原 PDF 诊断,但不能确认成盲测真值。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -104,3 +104,9 @@ def test_inventory_invalidation_writes_formal_edit_audit_chain(app):
|
||||
assert edited.after_snapshot_json.get('match_status') is None
|
||||
meta = edited.metadata_json or {}
|
||||
assert 'rerun_inventory_matching' in (meta.get('applied_effects') or [])
|
||||
field_changes = meta.get('field_changes') or []
|
||||
assert field_changes
|
||||
assert 'previous_value' in field_changes[0]
|
||||
assert 'new_value' in field_changes[0]
|
||||
assert field_changes[0]['previous_value'] == '3000000001'
|
||||
assert field_changes[0]['new_value'] == '3000092917'
|
||||
@@ -86,10 +86,11 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
|
||||
|
||||
|
||||
def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch):
|
||||
"""物化后新出现的 PDF 必须先排布局 Job;布局运行中禁止进入模板路由。"""
|
||||
"""物化后新出现的 PDF 必须转交布局 Job,并明确当前 Job 只是成功完成交接。"""
|
||||
import app.jobs.handlers.shipping_order_extraction as handler
|
||||
|
||||
events: list[str] = []
|
||||
finished: dict = {}
|
||||
run = SimpleNamespace(
|
||||
id=2, user_id=9, run_no='SNER-WORKER-WAIT-LAYOUT', status='queued', phase='queued',
|
||||
current_job_id=None, attempt_count=0, input_snapshot_json={'attachment_selection': {}},
|
||||
@@ -112,7 +113,11 @@ def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch)
|
||||
)
|
||||
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {357: 'layout_pending'})
|
||||
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: events.append('waiting'))
|
||||
monkeypatch.setattr(handler, 'finish_job', lambda *_args, **_kwargs: events.append('finished'))
|
||||
def fake_finish_job(*_args, **kwargs):
|
||||
events.append('finished')
|
||||
finished.update(kwargs)
|
||||
|
||||
monkeypatch.setattr(handler, 'finish_job', fake_finish_job)
|
||||
monkeypatch.setattr(handler, 'route_deterministic_unit', lambda *_args, **_kwargs: events.append('routed'))
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
|
||||
@@ -120,6 +125,12 @@ def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch)
|
||||
|
||||
assert events == ['materialize', 'schedule', 'waiting', 'finished']
|
||||
assert run.phase == 'waiting_layout'
|
||||
assert finished['result'] == {
|
||||
'run_no': run.run_no,
|
||||
'waiting_layout': True,
|
||||
'handoff_status': 'deferred_to_layout',
|
||||
}
|
||||
assert finished['message'] == '已转交附件版面解析,完成后自动创建后继订单识别任务'
|
||||
|
||||
|
||||
def test_worker_marks_run_failed_when_layout_scheduling_fails(monkeypatch):
|
||||
|
||||
@@ -15,6 +15,7 @@ import pytest
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
ShippingOrderDocument,
|
||||
ShippingInventoryRoutingRule,
|
||||
ShippingInventoryRoutingRuleCondition,
|
||||
ShippingOrderCandidate,
|
||||
@@ -28,6 +29,7 @@ from app.models import (
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case, serialize_review_run
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run
|
||||
from app.services.shipping_notice.order_review_service import (
|
||||
ensure_review_case_for_unit,
|
||||
ensure_run_review_cases,
|
||||
get_review_case_visible_to_user,
|
||||
get_review_run_visible_to_user,
|
||||
@@ -61,11 +63,13 @@ from app.services.shipping_notice.order_extraction_plan import ensure_order_extr
|
||||
|
||||
|
||||
def _materialized_run(*, user, agent, session, intake):
|
||||
"""测试中显式物化延迟创建的 Plan/Unit,保持与 Worker 的生产时序一致。"""
|
||||
"""测试中显式物化 Plan,并把 Review 测试默认 Unit 推进到可建 Case 的就绪态。"""
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
ensure_order_extraction_plan(run)
|
||||
for unit in run.extraction_plan.units:
|
||||
unit.status = 'candidate_ready'
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
@@ -122,24 +126,110 @@ def test_review_case_initialization_is_pdf_unit_unique_and_keeps_machine_candida
|
||||
assert db.session.get(ShippingOrderCandidate, candidate.id).structured_result_json == {'machine': 'unchanged'}
|
||||
|
||||
|
||||
def test_review_cases_follow_each_ready_unit_for_any_pdf_count_and_completion_order(app):
|
||||
"""任意数量 PDF 乱序完成时,只能为当前已就绪 Unit 建 Case,兄弟 PDF 不得被提前初始化。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, first_document = _seed_run_input(suffix='REVIEW-N-PDF')
|
||||
documents = [first_document]
|
||||
for index in range(2, 6):
|
||||
document = ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=first_document.asset_id,
|
||||
document_type='attachment',
|
||||
attachment_key=f'orders-review-n-pdf-{index}.pdf',
|
||||
filename=f'orders-review-n-pdf-{index}.pdf',
|
||||
content_hash=(str(index) * 64)[:64],
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text=f'PO-N-{index}',
|
||||
)
|
||||
db.session.add(document)
|
||||
documents.append(document)
|
||||
db.session.commit()
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
units_by_document = {
|
||||
int(unit.document_id): unit for unit in run.extraction_plan.units
|
||||
}
|
||||
assert len(units_by_document) == 5
|
||||
for unit in units_by_document.values():
|
||||
unit.status = 'pending'
|
||||
unit.result_json = None
|
||||
db.session.commit()
|
||||
|
||||
completion_order = [3, 0, 4, 1, 2]
|
||||
completed_document_ids: set[int] = set()
|
||||
for step, document_index in enumerate(completion_order, start=1):
|
||||
document = documents[document_index]
|
||||
unit = units_by_document[int(document.id)]
|
||||
unit.status = 'candidate_ready'
|
||||
unit.result_json = {'orders': [{
|
||||
'primary_document_id': int(document.id),
|
||||
'header_fields': [{
|
||||
'field_id': 'po',
|
||||
'observations': [{'value': f'PO-N-{document_index + 1}'}],
|
||||
}],
|
||||
'lines': [],
|
||||
}]}
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=f'CAND-REVIEW-N-{document_index + 1}',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=int(document.id),
|
||||
candidate_key=f'review-n-{document_index + 1}',
|
||||
order_extraction_run_id=run.id,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
|
||||
case = ensure_review_case_for_unit(run=run, unit=unit)
|
||||
db.session.commit()
|
||||
completed_document_ids.add(int(document.id))
|
||||
|
||||
# 关键断言:每一步仅增长一个 Case,未完成的任意兄弟 PDF 始终没有空 Case。
|
||||
assert case is not None
|
||||
assert case.candidate_id == candidate.id
|
||||
assert ShippingOrderReviewCase.query.filter_by(run_id=run.id).count() == step
|
||||
actual_document_ids = {
|
||||
int(row.document_id)
|
||||
for row in ShippingOrderReviewCase.query.filter_by(run_id=run.id).all()
|
||||
}
|
||||
assert actual_document_ids == completed_document_ids
|
||||
|
||||
reconciled = ensure_run_review_cases(run=run)
|
||||
db.session.commit()
|
||||
assert len(reconciled) == 5
|
||||
assert ShippingOrderReviewCase.query.filter_by(run_id=run.id).count() == 5
|
||||
|
||||
|
||||
def test_review_case_backfills_final_run_order_for_an_empty_legacy_draft(app):
|
||||
"""最终合并订单可回填旧空草稿,复核页不得把成功 PDF 显示为机器订单不可用。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-FINAL-ORDER')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
# 先模拟 Worker 在最终合并结果写入前创建的空白旧 Case。
|
||||
# 先模拟历史 Worker 在最终结果与 Candidate 写入前创建的空白旧 Case。
|
||||
unit.status = 'review_required'
|
||||
legacy_case = ensure_run_review_cases(run=run)[0]
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-FINAL-ORDER', intake_id=intake.id,
|
||||
primary_document_id=unit.document_id, candidate_key='review-final-order',
|
||||
order_extraction_run_id=run.id,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
run.execution_result_json = {'orders': [{
|
||||
'primary_document_id': unit.document_id,
|
||||
'header_fields': [{'field_id': 'po', 'observations': [{'value': 'PO-FINAL'}]}],
|
||||
'lines': [{'fields': [{'field_id': 'part', 'observations': [{'value': 'A001'}]}]}],
|
||||
}]}
|
||||
unit.status = 'candidate_ready'
|
||||
# 后续校验可能已替换 machine_order_unavailable,修复不能依赖单一问题码。
|
||||
legacy_case.current_draft.issue_summary_json = [{'code': 'customer_unresolved', 'severity': 'blocking'}]
|
||||
|
||||
refreshed = ensure_run_review_cases(run=run)[0]
|
||||
refreshed = ensure_review_case_for_unit(run=run, unit=unit)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:按当前 PDF 的 primary_document_id 回填,不依赖旧 Unit 中间结果。
|
||||
# 关键断言:补回唯一 Candidate 和机器 Draft,不依赖已被校验替换的问题码。
|
||||
assert refreshed.id == legacy_case.id
|
||||
assert refreshed.candidate_id == candidate.id
|
||||
assert refreshed.current_draft.header_values_json['machine_fields'][0]['observations'][0]['value'] == 'PO-FINAL'
|
||||
assert refreshed.current_draft.lines_json[0]['machine_fields'][0]['observations'][0]['value'] == 'A001'
|
||||
assert not any(item['code'] == 'machine_order_unavailable' for item in refreshed.current_draft.issue_summary_json)
|
||||
|
||||
@@ -365,10 +365,11 @@ def test_confirm_sibling_candidate_reuses_locked_ot_not_root(app):
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 仅给 document_b 对应 Unit 写入可确认机器结果。
|
||||
# 仅给 document_b 对应 Unit 写入可确认机器结果,并标记为复核就绪。
|
||||
for unit in run.extraction_plan.units:
|
||||
if int(unit.document_id) != int(document_b.id):
|
||||
continue
|
||||
unit.status = 'candidate_ready'
|
||||
unit.result_json = {
|
||||
'orders': [{
|
||||
'primary_document_id': int(document_b.id),
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_task_progress_audit.py
|
||||
|
||||
用途:验收 OT 统一进度中央写入口强制写入 order_task_progress_changed 审计。
|
||||
依赖:order_task_service.sync_order_task_processing_state、ShippingAuditEvent、pytest。
|
||||
逻辑:stage/status 变更必须落审计前后值与 reason_code;无变更不写事件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent, ShippingOrderTask, User
|
||||
from app.services.shipping_notice.order_task_service import sync_order_task_processing_state
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
ORDER_TASK_PROGRESS_AUDIT_EVENT_TYPES,
|
||||
)
|
||||
|
||||
|
||||
def test_order_task_progress_audit_event_types_frozen():
|
||||
"""契约冻结:OT 进度三类事件码齐全。"""
|
||||
assert ORDER_TASK_PROGRESS_AUDIT_EVENT_TYPES == frozenset({
|
||||
'order_task_created',
|
||||
'order_task_updated',
|
||||
'order_task_progress_changed',
|
||||
})
|
||||
|
||||
|
||||
def _seed_user_and_task(task_no: str = 'OT-PROGRESS-AUDIT-1') -> ShippingOrderTask:
|
||||
"""最小 OT 行,供中央进度写入口测试。"""
|
||||
user = User(
|
||||
username=f'ot-progress-{task_no[-4:]}',
|
||||
email=f'{task_no.lower()}@example.com',
|
||||
password_hash='x',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
now = datetime.utcnow()
|
||||
ot = ShippingOrderTask(
|
||||
task_no=task_no,
|
||||
user_id=int(user.id),
|
||||
status='processing',
|
||||
stage='candidate_creating',
|
||||
progress_version=1,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
db.session.add(ot)
|
||||
db.session.commit()
|
||||
return ot
|
||||
|
||||
|
||||
def test_sync_order_task_processing_state_writes_progress_audit(app):
|
||||
"""BE-06:stage 变更强制写 order_task_progress_changed,含前后值。"""
|
||||
with app.app_context():
|
||||
ot = _seed_user_and_task()
|
||||
sync_order_task_processing_state(
|
||||
ot,
|
||||
stage='waiting_review',
|
||||
status='waiting_review',
|
||||
reason_code='candidate_pre_confirm_sync',
|
||||
source='test',
|
||||
request_id='req-progress-1',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
events = (
|
||||
ShippingAuditEvent.query.filter_by(
|
||||
event_type='order_task_progress_changed',
|
||||
aggregate_id=ot.task_no,
|
||||
)
|
||||
.order_by(ShippingAuditEvent.id.desc())
|
||||
.all()
|
||||
)
|
||||
assert len(events) >= 1
|
||||
event = events[0]
|
||||
assert event.reason_code == 'candidate_pre_confirm_sync'
|
||||
assert event.request_id == 'req-progress-1'
|
||||
assert event.action == 'sync_order_task_processing_state'
|
||||
before = event.before_snapshot_json if isinstance(event.before_snapshot_json, dict) else {}
|
||||
after = event.after_snapshot_json if isinstance(event.after_snapshot_json, dict) else {}
|
||||
# 白名单快照须保留 stage/status/progress_version,禁止静默丢字段。
|
||||
assert before.get('stage') == 'candidate_creating'
|
||||
assert before.get('status') == 'processing'
|
||||
assert before.get('progress_version') == 1
|
||||
assert after.get('stage') == 'waiting_review'
|
||||
assert after.get('status') == 'waiting_review'
|
||||
assert after.get('progress_version') == 2
|
||||
assert int(ot.progress_version or 1) == 2
|
||||
|
||||
|
||||
def test_sync_order_task_processing_state_noop_skips_audit(app):
|
||||
"""值未变化时不得刷审计与 progress_version。"""
|
||||
with app.app_context():
|
||||
ot = _seed_user_and_task('OT-PROGRESS-AUDIT-2')
|
||||
version = int(ot.progress_version or 1)
|
||||
before_count = ShippingAuditEvent.query.filter_by(
|
||||
event_type='order_task_progress_changed',
|
||||
aggregate_id=ot.task_no,
|
||||
).count()
|
||||
sync_order_task_processing_state(
|
||||
ot,
|
||||
stage='candidate_creating',
|
||||
status='processing',
|
||||
reason_code='noop',
|
||||
)
|
||||
db.session.commit()
|
||||
after_count = ShippingAuditEvent.query.filter_by(
|
||||
event_type='order_task_progress_changed',
|
||||
aggregate_id=ot.task_no,
|
||||
).count()
|
||||
assert after_count == before_count
|
||||
assert int(ot.progress_version or 1) == version
|
||||
@@ -0,0 +1,130 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_task_stage_machine.py
|
||||
|
||||
用途:验收确认前 OT stage 与 Candidate 前 Run 早期 stage 由写路径推进。
|
||||
依赖:order_task_stage_machine、shipping_processing_projection、pytest。
|
||||
逻辑:客户未确认 → customer_resolving;查重未清 → duplicate_checking;
|
||||
否则 waiting_review;进度事件写入 processing_stage 后投影优先读事实。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
resolve_pre_confirm_stage,
|
||||
resolve_processing_stage_for_progress_event,
|
||||
write_run_unified_processing_stage,
|
||||
)
|
||||
from app.services.shipping_notice.shipping_processing_projection import (
|
||||
map_run_to_processing_stage,
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_pre_confirm_stage_customer_blocking():
|
||||
"""客户未确认时 stage=customer_resolving。"""
|
||||
stage, status = resolve_pre_confirm_stage(
|
||||
evaluation={
|
||||
'gates': {'customer_confirmed': False, 'duplicate_resolved': True},
|
||||
'blocking_reason_codes': ['customer_unresolved'],
|
||||
},
|
||||
)
|
||||
assert stage == 'customer_resolving'
|
||||
assert status == 'waiting_review'
|
||||
|
||||
|
||||
def test_resolve_pre_confirm_stage_duplicate_blocking():
|
||||
"""查重未清时 stage=duplicate_checking。"""
|
||||
stage, status = resolve_pre_confirm_stage(
|
||||
evaluation={
|
||||
'gates': {'customer_confirmed': True, 'duplicate_resolved': False},
|
||||
'blocking_reason_codes': ['duplicate_unresolved'],
|
||||
},
|
||||
)
|
||||
assert stage == 'duplicate_checking'
|
||||
assert status == 'waiting_review'
|
||||
|
||||
|
||||
def test_resolve_pre_confirm_stage_waiting_review_default():
|
||||
"""资格无阻断时落到 waiting_review。"""
|
||||
stage, status = resolve_pre_confirm_stage(
|
||||
evaluation={
|
||||
'gates': {'customer_confirmed': True, 'duplicate_resolved': True},
|
||||
'blocking_reason_codes': [],
|
||||
'can_auto_create': False,
|
||||
},
|
||||
)
|
||||
assert stage == 'waiting_review'
|
||||
assert status == 'waiting_review'
|
||||
|
||||
|
||||
def test_prefer_waiting_review_still_respects_customer_blocker():
|
||||
"""BE-02:prefer_waiting_review 不得覆盖客户未确认阻断。"""
|
||||
stage, status = resolve_pre_confirm_stage(
|
||||
evaluation={
|
||||
'gates': {'customer_confirmed': False, 'duplicate_resolved': True},
|
||||
'blocking_reason_codes': ['customer_unresolved'],
|
||||
},
|
||||
prefer_waiting_review=True,
|
||||
)
|
||||
assert stage == 'customer_resolving'
|
||||
assert status == 'waiting_review'
|
||||
|
||||
|
||||
def test_prefer_waiting_review_when_gates_clear():
|
||||
"""无阻断时 prefer_waiting_review 落到 waiting_review。"""
|
||||
stage, status = resolve_pre_confirm_stage(
|
||||
evaluation={
|
||||
'gates': {'customer_confirmed': True, 'duplicate_resolved': True},
|
||||
'blocking_reason_codes': [],
|
||||
},
|
||||
prefer_waiting_review=True,
|
||||
)
|
||||
assert stage == 'waiting_review'
|
||||
assert status == 'waiting_review'
|
||||
|
||||
|
||||
def test_progress_event_maps_early_stages_for_eml():
|
||||
"""EML:plan_created→email_parsing;layout→document_parsing;merge→email_adjudicating。"""
|
||||
assert resolve_processing_stage_for_progress_event(
|
||||
'plan_created', source_type='eml',
|
||||
) == 'email_parsing'
|
||||
assert resolve_processing_stage_for_progress_event(
|
||||
'layout_parsing_started', source_type='eml',
|
||||
) == 'document_parsing'
|
||||
assert resolve_processing_stage_for_progress_event(
|
||||
'email_supplement_merged', source_type='eml',
|
||||
) == 'email_adjudicating'
|
||||
|
||||
|
||||
def test_progress_event_direct_pdf_never_email_stages():
|
||||
"""direct_pdf:禁止 email_*;merge 折叠为 candidate_creating。"""
|
||||
assert resolve_processing_stage_for_progress_event(
|
||||
'plan_created', source_type='direct_pdf',
|
||||
) == 'upload_received'
|
||||
assert resolve_processing_stage_for_progress_event(
|
||||
'email_supplement_merged', source_type='direct_pdf',
|
||||
) == 'candidate_creating'
|
||||
assert resolve_processing_stage_for_progress_event(
|
||||
'layout_parsing_started', source_type='direct_pdf',
|
||||
) == 'document_parsing'
|
||||
|
||||
|
||||
def test_map_run_prefers_written_processing_stage():
|
||||
"""投影优先读 Run.progress_summary_json.processing_stage 写路径事实。"""
|
||||
run = SimpleNamespace(
|
||||
status='processing',
|
||||
phase='extracting',
|
||||
current_stage_code='profile_matching',
|
||||
progress_summary_json=None,
|
||||
extraction_plan=None,
|
||||
)
|
||||
write_run_unified_processing_stage(run, 'document_parsing', source_type='eml')
|
||||
assert map_run_to_processing_stage(run, source_type='eml') == 'document_parsing'
|
||||
|
||||
write_run_unified_processing_stage(run, 'email_adjudicating', source_type='eml')
|
||||
assert map_run_to_processing_stage(run, source_type='eml') == 'email_adjudicating'
|
||||
|
||||
# direct_pdf 即便误写入 email_* 也须 clamp。
|
||||
write_run_unified_processing_stage(run, 'email_adjudicating', source_type='direct_pdf')
|
||||
assert map_run_to_processing_stage(run, source_type='direct_pdf') == 'document_parsing'
|
||||
@@ -0,0 +1,209 @@
|
||||
"""
|
||||
backend/tests/test_shipping_processing_projection_invariants.py
|
||||
|
||||
用途:验收统一投影 status/stage/gate/action 不变量与 15 阶节点事实。
|
||||
依赖:processing_projection_invariants、pytest。
|
||||
逻辑:不连库;断言 Gate 复核强制 waiting_review、Run completed 非全流程完成、
|
||||
动作契约映射与 stage_nodes 权威输出。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
build_stage_nodes,
|
||||
derivation_status_for_extraction_run,
|
||||
normalize_action_code,
|
||||
reconcile_processing_projection_facts,
|
||||
)
|
||||
|
||||
|
||||
def test_run_completed_is_not_workflow_completed_before_review():
|
||||
"""识别 Run completed + candidate_creating 不得映射为全流程 completed。"""
|
||||
assert derivation_status_for_extraction_run('completed', stage='candidate_creating') == 'processing'
|
||||
assert derivation_status_for_extraction_run('completed', stage='waiting_review') == 'waiting_review'
|
||||
assert derivation_status_for_extraction_run('completed', stage='completed') == 'completed'
|
||||
|
||||
|
||||
def test_open_order_review_gate_forces_waiting_review_stage():
|
||||
"""Gate 要求进入复核时,stage/status 必须对齐 waiting_review。"""
|
||||
payload = reconcile_processing_projection_facts({
|
||||
'status': 'processing',
|
||||
'stage': 'candidate_creating',
|
||||
'source_type': 'direct_pdf',
|
||||
'current_gate': {
|
||||
'gate_code': 'order_freeze_readiness',
|
||||
'status': 'blocked',
|
||||
'next_action_code': 'open_order_review',
|
||||
'blocking_reason_code': 'waiting_review',
|
||||
'attempt_no': 0,
|
||||
},
|
||||
'available_actions': ['view_details', 'open_order_review'],
|
||||
})
|
||||
assert payload['status'] == 'waiting_review'
|
||||
assert payload['stage'] == 'waiting_review'
|
||||
assert payload['available_actions'][0] == 'open_order_review'
|
||||
current = next(n for n in payload['stage_nodes'] if n['stage'] == 'waiting_review')
|
||||
assert current['status'] == 'blocked'
|
||||
assert next(n for n in payload['stage_nodes'] if n['stage'] == 'email_parsing')['status'] == 'skipped'
|
||||
|
||||
|
||||
def test_completed_clears_write_actions_and_gate():
|
||||
"""status=completed 时 stage 必须 completed,且不得残留写操作。"""
|
||||
payload = reconcile_processing_projection_facts({
|
||||
'status': 'completed',
|
||||
'stage': 'excel_generating',
|
||||
'source_type': 'eml',
|
||||
'current_gate': {
|
||||
'gate_code': 'x',
|
||||
'status': 'blocked',
|
||||
'next_action_code': 'open_order_review',
|
||||
},
|
||||
'available_actions': ['open_order_review', 'retry'],
|
||||
})
|
||||
assert payload['stage'] == 'completed'
|
||||
assert payload['current_gate'] is None
|
||||
assert 'open_order_review' not in payload['available_actions']
|
||||
assert payload['available_actions'] == ['view_result']
|
||||
|
||||
|
||||
def test_normalize_unknown_action_codes():
|
||||
"""未知 / 别名动作码映射到契约或丢弃。"""
|
||||
assert normalize_action_code('retry_failed_documents') == 'retry'
|
||||
assert normalize_action_code('open_fulfillment') == 'view_result'
|
||||
assert normalize_action_code('not_a_real_action') is None
|
||||
|
||||
|
||||
def test_stage_nodes_length_is_fifteen():
|
||||
"""stage_nodes 恒为 15 阶权威事实。"""
|
||||
nodes = build_stage_nodes(
|
||||
stage='inventory_matching',
|
||||
status='automating',
|
||||
source_type='eml',
|
||||
)
|
||||
assert len(nodes) == 15
|
||||
assert nodes[11]['stage'] == 'inventory_matching'
|
||||
assert nodes[11]['status'] == 'running'
|
||||
assert nodes[10]['status'] == 'passed'
|
||||
assert nodes[12]['status'] == 'pending'
|
||||
|
||||
|
||||
def test_invalidated_from_stage_marks_nodes_pending():
|
||||
"""BE-01:改单失效起点及之后(当前游标之前)不得再标 passed。"""
|
||||
nodes = build_stage_nodes(
|
||||
stage='inventory_matching',
|
||||
status='processing',
|
||||
source_type='eml',
|
||||
invalidated_from_stage='inventory_source_resolving',
|
||||
)
|
||||
# inventory_source_resolving 在当前游标之前且位于失效起点,应标 pending。
|
||||
inv_node = next(n for n in nodes if n['stage'] == 'inventory_source_resolving')
|
||||
assert inv_node['status'] == 'pending'
|
||||
waiting = next(n for n in nodes if n['stage'] == 'waiting_review')
|
||||
assert waiting['status'] == 'pending'
|
||||
# 失效起点之前仍可为 passed。
|
||||
dup_node = next(n for n in nodes if n['stage'] == 'duplicate_checking')
|
||||
assert dup_node['status'] == 'passed'
|
||||
current = next(n for n in nodes if n['stage'] == 'inventory_matching')
|
||||
assert current['status'] == 'running'
|
||||
|
||||
|
||||
def test_download_excel_requires_excel_ready_fact():
|
||||
"""BE-04:仅 stage=excel_generating 不得推出 download_excel。"""
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
derive_available_actions,
|
||||
)
|
||||
|
||||
without_ready = derive_available_actions(
|
||||
status='blocked',
|
||||
stage='excel_generating',
|
||||
gate=None,
|
||||
excel_ready=False,
|
||||
)
|
||||
assert 'download_excel' not in without_ready
|
||||
assert 'regenerate_excel' in without_ready
|
||||
|
||||
with_ready = derive_available_actions(
|
||||
status='blocked',
|
||||
stage='freight_uploading',
|
||||
gate={'next_action_code': 'wait_manual_upload'},
|
||||
excel_ready=True,
|
||||
)
|
||||
assert 'download_excel' in with_ready
|
||||
assert 'open_manual_upload' in with_ready
|
||||
assert 'regenerate_excel' not in with_ready
|
||||
|
||||
|
||||
def test_map_notice_to_processing_status_stage_domain_mapping():
|
||||
"""BE-05:Notice 履约态映射属领域层,写/读共用。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
map_notice_to_processing_status_stage,
|
||||
)
|
||||
|
||||
uploaded = SimpleNamespace(
|
||||
process_status='uploaded', current_step='', upload_status='', export_file_path=None,
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(uploaded) == ('completed', 'completed')
|
||||
|
||||
waiting = SimpleNamespace(
|
||||
process_status='waiting_upload', current_step='', upload_status='', export_file_path='/x.xlsx',
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(waiting) == ('automating', 'freight_uploading')
|
||||
|
||||
matching = SimpleNamespace(
|
||||
process_status='matching', current_step='step5_match', upload_status='', export_file_path=None,
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(matching) == ('automating', 'inventory_matching')
|
||||
|
||||
|
||||
def test_map_notice_unknown_status_fail_closed():
|
||||
"""BE-03: unknown Notice status must fail-closed, not order_creating."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
map_notice_to_processing_status_stage,
|
||||
)
|
||||
|
||||
unknown = SimpleNamespace(
|
||||
process_status='totally_unknown_xyz',
|
||||
current_step='',
|
||||
upload_status='',
|
||||
export_file_path=None,
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(unknown) == ('blocked', 'waiting_review')
|
||||
|
||||
|
||||
def test_derive_available_actions_blocked_without_retry_gate():
|
||||
"""BE-04: business blocked without retry Gate must not append retry."""
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
derive_available_actions,
|
||||
)
|
||||
|
||||
actions = derive_available_actions(
|
||||
status='blocked',
|
||||
stage='inventory_source_resolving',
|
||||
gate={
|
||||
'gate_code': 'inventory_source',
|
||||
'status': 'blocked',
|
||||
'next_action_code': 'confirm_inventory_source',
|
||||
},
|
||||
excel_ready=False,
|
||||
)
|
||||
assert 'retry' not in actions
|
||||
assert 'open_inventory_source_review' in actions
|
||||
|
||||
|
||||
def test_derive_available_actions_failed_adds_retry():
|
||||
"""BE-04: technical failed should allow retry by default."""
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
derive_available_actions,
|
||||
)
|
||||
|
||||
actions = derive_available_actions(
|
||||
status='failed',
|
||||
stage='document_parsing',
|
||||
gate=None,
|
||||
excel_ready=False,
|
||||
)
|
||||
assert 'retry' in actions
|
||||
@@ -64,14 +64,15 @@ def _upload_ready_asset(user_id: int, *, filename: str, content: bytes) -> str:
|
||||
|
||||
|
||||
def test_map_run_status_to_processing_status() -> None:
|
||||
"""Run.status 折叠到统一 ShippingProcessingStatus。"""
|
||||
"""Run.status 折叠到统一 ShippingProcessingStatus;识别完成 ≠ 全流程 completed。"""
|
||||
assert map_run_status_to_processing_status('queued') == 'processing'
|
||||
assert map_run_status_to_processing_status('processing') == 'processing'
|
||||
assert map_run_status_to_processing_status('review_required') == 'waiting_review'
|
||||
assert map_run_status_to_processing_status('failed') == 'failed'
|
||||
assert map_run_status_to_processing_status('cancelled') == 'cancelled'
|
||||
assert map_run_status_to_processing_status('completed') == 'completed'
|
||||
assert map_run_status_to_processing_status('partially_completed') == 'completed'
|
||||
# [BE-03] 无 stage 上下文时 completed/partially_completed → processing。
|
||||
assert map_run_status_to_processing_status('completed') == 'processing'
|
||||
assert map_run_status_to_processing_status('partially_completed') == 'processing'
|
||||
assert map_run_status_to_processing_status('unknown') == 'processing'
|
||||
|
||||
|
||||
@@ -186,7 +187,7 @@ def test_project_intake_work_item_parse_failed_exposes_gate_and_failure(app, shi
|
||||
"""
|
||||
解析失败 Intake 必须投影 blocked Gate、失败原因码与 retry_parse。
|
||||
|
||||
断言:current_gate.status=blocked;failure_reason_code;available_actions 含 retry_parse。
|
||||
断言:current_gate.status=blocked;failure_reason_code;available_actions 含 retry(契约码)。
|
||||
"""
|
||||
with app.app_context():
|
||||
with patch('app.services.shipping_notice.intake_service.enqueue', return_value=9409):
|
||||
@@ -228,7 +229,7 @@ def test_project_intake_work_item_parse_failed_exposes_gate_and_failure(app, shi
|
||||
assert item['current_gate']['attempt_no'] == 2
|
||||
assert item['source_summary']['failure_reason_code'] == 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED'
|
||||
assert item['source_summary']['parse_attempt_count'] == 2
|
||||
assert 'retry_parse' in item['available_actions']
|
||||
assert 'retry' in item['available_actions']
|
||||
|
||||
|
||||
def test_project_conversation_processing_items_includes_work_items(app, shipping_user):
|
||||
@@ -351,17 +352,25 @@ def test_project_order_task_work_item_fills_gate_and_candidate_summary(app, ship
|
||||
assert item['source_summary']['candidate_count'] >= 1
|
||||
assert item['source_summary']['po_number'] == 'PO-OT-1'
|
||||
assert item['source_summary']['customer_name'] == 'ACME Co'
|
||||
# 每个 OT 只统计自身主 PDF,禁止把整个 Run 的文档数复制到兄弟 OT。
|
||||
assert item['source_summary']['document_id'] == int(document.id)
|
||||
assert item['source_summary']['document_count'] == 1
|
||||
assert item['source_summary']['filename'] == document.filename
|
||||
|
||||
|
||||
def test_project_order_task_prefers_notice_fulfillment_stage(app, shipping_user):
|
||||
def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_user):
|
||||
"""
|
||||
OT 已挂 Notice 时,投影 stage/status 须跟随 Notice.process_status,而非过期 OT.stage。
|
||||
BE-07:投影 stage/status 以 OT 已写入值为准,禁止读路径用 Notice 覆盖。
|
||||
|
||||
断言:waiting_upload → automating + freight_uploading。
|
||||
断言:Notice 已是 waiting_upload,但 OT 仍为 candidate_creating 时投影不得偷偷改成 freight_uploading;
|
||||
经 sync_order_task_stage_for_notice 回写后投影才反映履约态。
|
||||
"""
|
||||
del shipping_user
|
||||
with app.app_context():
|
||||
from app.models import ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
sync_order_task_stage_for_notice,
|
||||
)
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
@@ -391,7 +400,13 @@ def test_project_order_task_prefers_notice_fulfillment_stage(app, shipping_user)
|
||||
run.user_task_no = order_task.task_no
|
||||
db.session.commit()
|
||||
|
||||
item = _project_order_task_work_item(run)
|
||||
assert item['status'] == 'automating'
|
||||
assert item['stage'] == 'freight_uploading'
|
||||
assert item['shipping_notice_no'] == notice.task_no
|
||||
stale = _project_order_task_work_item(run)
|
||||
assert stale['stage'] == 'candidate_creating'
|
||||
assert stale['status'] == 'processing'
|
||||
assert stale['shipping_notice_no'] == notice.task_no
|
||||
|
||||
sync_order_task_stage_for_notice(notice, order_task=order_task)
|
||||
db.session.commit()
|
||||
synced = _project_order_task_work_item(run)
|
||||
assert synced['status'] == 'automating'
|
||||
assert synced['stage'] == 'freight_uploading'
|
||||
@@ -11,6 +11,7 @@ from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExportArtifact,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
@@ -157,8 +158,8 @@ def _task(**kwargs) -> ShippingNotice:
|
||||
po_number=kwargs.pop('po_number', 'PO-FORMAL-001'),
|
||||
match_status=kwargs.pop('match_status', 'matched'),
|
||||
line_results_json=kwargs.pop('line_results_json', [{'part_number': 'A001'}]),
|
||||
export_file_path=kwargs.pop('export_file_path', '/tmp/formal.xlsx'),
|
||||
export_file_name=kwargs.pop('export_file_name', 'formal.xlsx'),
|
||||
export_file_path=kwargs.pop('export_file_path', None),
|
||||
export_file_name=kwargs.pop('export_file_name', None),
|
||||
order_data_version=kwargs.pop('order_data_version', 1),
|
||||
order_lines_migration_status='pending',
|
||||
**kwargs,
|
||||
@@ -184,6 +185,73 @@ def _link_order_task(task: ShippingNotice, *, stage: str = 'inventory_matching')
|
||||
return order_task
|
||||
|
||||
|
||||
def _seed_ready_export_artifact(task: ShippingNotice, *, path: str | None = None) -> ShippingExportArtifact:
|
||||
"""为 Excel 冻结测试植入 status=ready 的 Artifact(BE-09)。"""
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
|
||||
file_path = str(path or task.export_file_path or '/tmp/formal.xlsx')
|
||||
template = ShippingExcelTemplate(
|
||||
template_code=f'TPL-{task.task_no}',
|
||||
display_name='Formal Edit',
|
||||
version=1,
|
||||
status='published',
|
||||
storage_bucket='test',
|
||||
storage_key='test/template.xlsx',
|
||||
original_filename='template.xlsx',
|
||||
file_checksum='a' * 64,
|
||||
definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code=f'PRF-{task.task_no}',
|
||||
display_name='Formal Edit',
|
||||
version=1,
|
||||
status='published',
|
||||
file_format='xlsx',
|
||||
definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code=f'SCH-{task.task_no}', display_name='Formal')
|
||||
db.session.add_all([template, profile, schema])
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction_id = getattr(task, 'current_order_extraction_id', None)
|
||||
if extraction_id is None:
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=version.id,
|
||||
input_snapshot_hash='e' * 64,
|
||||
status='accepted',
|
||||
task_id=int(task.id),
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
extraction_id = extraction.id
|
||||
artifact = ShippingExportArtifact(
|
||||
artifact_no=f'ART-{task.task_no}',
|
||||
task_id=int(task.id),
|
||||
template_id=int(template.id),
|
||||
order_schema_version_id=int(version.id),
|
||||
order_extraction_id=int(extraction_id),
|
||||
inventory_parsing_profile_id=int(profile.id),
|
||||
input_checksum='b' * 64,
|
||||
file_path=file_path,
|
||||
file_name=str(task.export_file_name or 'formal.xlsx'),
|
||||
file_checksum='c' * 64,
|
||||
file_size=10,
|
||||
status='ready',
|
||||
)
|
||||
db.session.add(artifact)
|
||||
db.session.flush()
|
||||
return artifact
|
||||
|
||||
|
||||
def test_formal_edit_rejects_default_readonly_field(app):
|
||||
"""Schema 显式 editable=false 时拒绝,即使字段在 legacy 白名单内。"""
|
||||
with app.app_context():
|
||||
@@ -210,7 +278,7 @@ def test_formal_edit_rejects_default_readonly_field(app):
|
||||
def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app):
|
||||
"""Schema editable=True 时允许写入并递增 order_data_version。"""
|
||||
with app.app_context():
|
||||
task = _task()
|
||||
task = _task(export_file_path='/tmp/formal.xlsx', export_file_name='formal.xlsx')
|
||||
_attach_extraction(
|
||||
task,
|
||||
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
@@ -221,6 +289,22 @@ def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app):
|
||||
},
|
||||
},
|
||||
)
|
||||
_seed_ready_export_artifact(task)
|
||||
db.session.commit()
|
||||
|
||||
# Excel ready(ready Artifact)时即使 Schema editable 也必须冻结。
|
||||
frozen = update_notice_line({
|
||||
'task_no': task.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {'reservation_id': '3000092917'},
|
||||
**_review_payload(version=1),
|
||||
})
|
||||
assert frozen['status'] == 'failed'
|
||||
assert frozen['data']['error_code'] == 'SHIPPING.ORDER_EXCEL_FROZEN'
|
||||
|
||||
# 清除导出后允许 Schema 放行字段写入。
|
||||
task.export_file_path = None
|
||||
task.export_file_name = None
|
||||
db.session.commit()
|
||||
|
||||
response = update_notice_line({
|
||||
@@ -232,15 +316,14 @@ def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app):
|
||||
assert response['status'] == 'ok'
|
||||
refreshed = db.session.get(ShippingNotice, task.id)
|
||||
assert int(refreshed.order_data_version) == 2
|
||||
# change_effect=none 时不应清空已有匹配/导出派生结果。
|
||||
# change_effect=none 时不应清空已有匹配结果。
|
||||
assert refreshed.match_status == 'matched'
|
||||
assert refreshed.export_file_path == '/tmp/formal.xlsx'
|
||||
|
||||
|
||||
def test_change_effect_rerun_inventory_matching_invalidates_match_and_syncs_ot(app):
|
||||
"""rerun_inventory_matching 清空匹配并同步 OT inventory_matching stage。"""
|
||||
with app.app_context():
|
||||
task = _task()
|
||||
task = _task(export_file_path='/tmp/formal.xlsx', export_file_name='formal.xlsx')
|
||||
_attach_extraction(
|
||||
task,
|
||||
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
@@ -252,13 +335,16 @@ def test_change_effect_rerun_inventory_matching_invalidates_match_and_syncs_ot(a
|
||||
},
|
||||
)
|
||||
order_task = _link_order_task(task, stage='excel_generating')
|
||||
# 测试编辑路径:先去掉 Excel 冻结。
|
||||
task.export_file_path = None
|
||||
task.export_file_name = None
|
||||
db.session.commit()
|
||||
|
||||
response = update_notice_line({
|
||||
'task_no': task.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {'reservation_id': '3000092917'},
|
||||
**_review_payload(),
|
||||
**_review_payload(version=1),
|
||||
})
|
||||
assert response['status'] == 'ok'
|
||||
refreshed = db.session.get(ShippingNotice, task.id)
|
||||
@@ -285,6 +371,13 @@ def test_change_effect_regenerate_excel_only_clears_export(app):
|
||||
},
|
||||
)
|
||||
order_task = _link_order_task(task, stage='inventory_matching')
|
||||
# 版本不匹配的导出视为 stale,不触发 Excel 冻结,便于测 regenerate_excel。
|
||||
task.export_file_path = '/tmp/stale.xlsx'
|
||||
task.export_file_name = 'stale.xlsx'
|
||||
task.step_payload_json = {
|
||||
**dict(task.step_payload_json or {}),
|
||||
'export_meta': {'order_data_version': 999},
|
||||
}
|
||||
db.session.commit()
|
||||
|
||||
response = update_notice_fields({
|
||||
@@ -300,3 +393,31 @@ def test_change_effect_regenerate_excel_only_clears_export(app):
|
||||
ot = db.session.get(ShippingOrderTask, order_task.id)
|
||||
assert ot.stage == 'excel_generating'
|
||||
assert int(ot.progress_version) == 2
|
||||
|
||||
|
||||
def test_formal_edit_allowed_with_order_snapshot_when_excel_not_ready(app):
|
||||
"""有 order_snapshot_id 但 Excel 未 ready 时,Schema editable 字段仍可写。"""
|
||||
with app.app_context():
|
||||
task = _task(order_snapshot_id=12345)
|
||||
_attach_extraction(
|
||||
task,
|
||||
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
field_policies={
|
||||
'reservation_id': {
|
||||
'editable': True,
|
||||
'change_effect': 'none',
|
||||
},
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
response = update_notice_line({
|
||||
'task_no': task.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {'reservation_id': '3000092917'},
|
||||
**_review_payload(version=1),
|
||||
})
|
||||
assert response['status'] == 'ok'
|
||||
refreshed = db.session.get(ShippingNotice, task.id)
|
||||
assert int(refreshed.order_data_version) == 2
|
||||
assert int(refreshed.order_snapshot_id) == 12345
|
||||
@@ -1,18 +1,20 @@
|
||||
"""
|
||||
backend/tests/test_shipping_schema_edit_policy.py
|
||||
|
||||
用途:验收正式任务 Schema 编辑策略默认只读与显式放行。
|
||||
用途:验收正式任务 Schema 编辑策略默认只读与显式放行(无 legacy 绕过)。
|
||||
依赖:schema_edit_policy、pytest。
|
||||
逻辑:无 task_edit_policy → 不可编辑;显式 editable=True → 可编辑;
|
||||
excel_ready 截止后关闭。
|
||||
excel_ready 后全局关闭。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.schema_edit_policy import (
|
||||
DEFAULT_EDITABLE_AFTER_TASK_CREATION,
|
||||
is_excel_ready_for_task,
|
||||
is_field_editable_for_formal_task,
|
||||
list_editable_formal_field_ids,
|
||||
sanitize_audit_field_value,
|
||||
)
|
||||
|
||||
|
||||
@@ -26,7 +28,7 @@ def test_default_formal_fields_are_readonly() -> None:
|
||||
|
||||
|
||||
def test_schema_explicit_editable_is_honored_until_excel_ready() -> None:
|
||||
"""Schema 显式放行字段在 Excel 就绪前可编辑。"""
|
||||
"""Schema 显式放行字段在 Excel 就绪前可编辑;就绪后全局关闭。"""
|
||||
field = {
|
||||
'field_id': 'reservation-id',
|
||||
'task_edit_policy': {
|
||||
@@ -38,3 +40,84 @@ def test_schema_explicit_editable_is_honored_until_excel_ready() -> None:
|
||||
assert is_field_editable_for_formal_task(field, excel_ready=False) is True
|
||||
assert is_field_editable_for_formal_task(field, excel_ready=True) is False
|
||||
assert list_editable_formal_field_ids([field], excel_ready=False) == ['reservation-id']
|
||||
assert list_editable_formal_field_ids([field], excel_ready=True) == []
|
||||
|
||||
|
||||
def test_excel_ready_freezes_even_without_editable_until() -> None:
|
||||
"""Excel ready 时即使未声明 editable_until 也全局禁写。"""
|
||||
field = {
|
||||
'field_id': 'po-id',
|
||||
'task_edit_policy': {'editable': True, 'change_effect': 'none'},
|
||||
}
|
||||
assert is_field_editable_for_formal_task(field, excel_ready=False) is True
|
||||
assert is_field_editable_for_formal_task(field, excel_ready=True) is False
|
||||
|
||||
|
||||
def test_sanitize_audit_field_value_truncates_long_text() -> None:
|
||||
"""审计前后值过长时截断。"""
|
||||
long_text = 'x' * 400
|
||||
sanitized = sanitize_audit_field_value(long_text)
|
||||
assert isinstance(sanitized, str)
|
||||
assert len(sanitized) < 400
|
||||
assert sanitized.endswith('…')
|
||||
|
||||
|
||||
def test_excel_ready_requires_ready_artifact(app) -> None:
|
||||
"""仅有 export_file_path、无 ready Artifact 时不得冻结(BE-09)。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingExportArtifact,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingNotice,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='SN-EXCEL-READY-BE09',
|
||||
source_type='manual',
|
||||
process_status='matched',
|
||||
export_file_path='/tmp/be09.xlsx',
|
||||
export_file_name='be09.xlsx',
|
||||
order_data_version=1,
|
||||
order_lines_migration_status='pending',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
assert is_excel_ready_for_task(task) is False
|
||||
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='BE09', display_name='BE09', version=1, status='published',
|
||||
storage_bucket='test', storage_key='t.xlsx', original_filename='t.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code='BE09', display_name='BE09', version=1, status='published',
|
||||
file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code='BE09', display_name='BE09')
|
||||
db.session.add_all([template, profile, schema])
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id, schema_version_id=version.id,
|
||||
input_snapshot_hash='b' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingExportArtifact(
|
||||
artifact_no='ART-BE09', task_id=task.id, template_id=template.id,
|
||||
order_schema_version_id=version.id, order_extraction_id=extraction.id,
|
||||
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
|
||||
file_path='/tmp/be09.xlsx', file_name='be09.xlsx',
|
||||
file_checksum='d' * 64, file_size=1, status='ready',
|
||||
))
|
||||
db.session.commit()
|
||||
assert is_excel_ready_for_task(task) is True
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
backend/tests/test_shipping_task_center_review_run_deep_link.py
|
||||
|
||||
用途:验收任务中心 Notice 摘要注入 review_run_no,供 UI-04 深链订单处理工作台。
|
||||
依赖:query_service._inject_unified_processing_fields、ShippingOrderTask、pytest。
|
||||
逻辑:OT 挂 extraction_run 时 SUMMARY 必含 review_run_no / owner_agent_id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.query_service import serialize_task_summary
|
||||
|
||||
|
||||
def test_serialize_task_summary_injects_review_run_no_for_order_processing_deeplink(app):
|
||||
"""UI-04:建单后任务摘要须带 review_run_no,任务中心才能深链 order-review。"""
|
||||
with app.app_context():
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='TC-DEEPLINK')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-TC-DEEPLINK-1',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
source_type='manual',
|
||||
process_status='waiting_upload',
|
||||
current_step='step7_upload_freight',
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
order_task = ShippingOrderTask(
|
||||
task_no='OT-TC-DEEPLINK-1',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=int(run.id),
|
||||
shipping_notice_id=int(notice.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
status='automating',
|
||||
stage='freight_uploading',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(order_task)
|
||||
db.session.flush()
|
||||
notice.order_task_id = int(order_task.id)
|
||||
run.user_task_no = order_task.task_no
|
||||
# 深链 Agent:优先 Run.owner_agent_id(注入逻辑读 Run)。
|
||||
run.owner_agent_id = int(agent.id)
|
||||
db.session.commit()
|
||||
|
||||
data = serialize_task_summary(notice, viewer_user_id=user.id)
|
||||
assert data['order_task_no'] == 'OT-TC-DEEPLINK-1'
|
||||
assert data['review_run_no'] == run.run_no
|
||||
assert int(data.get('owner_agent_id') or 0) == int(agent.id)
|
||||
@@ -60,8 +60,72 @@ from app.services.shipping_notice.progress_audit_contract import (
|
||||
FIXTURE_ROOT = Path(__file__).resolve().parent / 'fixtures' / 'shipping_xfa'
|
||||
|
||||
|
||||
def _confirmed_visual_binding() -> dict[str, object]:
|
||||
"""最小已确认 visual_binding。"""
|
||||
return {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.15},
|
||||
'source': 'manual_draw',
|
||||
'status': 'confirmed',
|
||||
'confidence': 1.0,
|
||||
}
|
||||
|
||||
|
||||
def _sample_xfa_definition(**overrides):
|
||||
"""构造合法 xfa_dataset definition 基线。"""
|
||||
"""构造合法 xfa_dataset definition 基线(bindings-only 正式路径)。"""
|
||||
payload = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
'mirror_collection_paths': ['/data/ITEMS1/DATA'],
|
||||
},
|
||||
'header_mappings': [],
|
||||
'line_mapping': {
|
||||
'row_path': '/data/ITEMS/DATA',
|
||||
'fields': [],
|
||||
},
|
||||
'bindings': [
|
||||
{
|
||||
'binding_id': 'bind-header-po',
|
||||
'field_id': 'f-po',
|
||||
'field_code': 'customer_po_no',
|
||||
'scope': 'header',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-header-ebeln',
|
||||
'data_path': '/data/HEADER/EBELN',
|
||||
},
|
||||
'visual_binding': _confirmed_visual_binding(),
|
||||
},
|
||||
{
|
||||
'binding_id': 'bind-line-mat',
|
||||
'field_id': 'f-mat',
|
||||
'field_code': 'material_no',
|
||||
'scope': 'line',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-line-matnr',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
},
|
||||
'visual_binding': _confirmed_visual_binding(),
|
||||
},
|
||||
],
|
||||
'cross_checks': {
|
||||
'acroform_enabled': True,
|
||||
'mirror_collection_policy': 'must_match_when_present',
|
||||
'line_amount_formula': 'quantity_times_unit_price',
|
||||
'total_amount_policy': 'must_equal_line_sum',
|
||||
},
|
||||
}
|
||||
payload.update(overrides)
|
||||
return payload
|
||||
|
||||
|
||||
def _legacy_only_xfa_definition(**overrides):
|
||||
"""构造仅含 legacy mappings 的迁移输入(不可经正式 validate)。"""
|
||||
payload = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
@@ -96,6 +160,7 @@ def _sample_xfa_definition(**overrides):
|
||||
},
|
||||
],
|
||||
},
|
||||
'bindings': [],
|
||||
'cross_checks': {
|
||||
'acroform_enabled': True,
|
||||
'mirror_collection_policy': 'must_match_when_present',
|
||||
@@ -131,6 +196,12 @@ def test_xfa_definition_rejects_coordinate_region_keys():
|
||||
assert model.source_contract.authoritative_line_collection_path == '/data/ITEMS/DATA'
|
||||
|
||||
|
||||
def test_xfa_definition_rejects_legacy_only_without_bindings():
|
||||
"""关键断言:仅 legacy mappings 无 bindings 时正式 validate fail-closed。"""
|
||||
with pytest.raises(ValidationError, match='xfa_legacy_mappings_forbidden'):
|
||||
validate_xfa_dataset_definition(_legacy_only_xfa_definition())
|
||||
|
||||
|
||||
def test_controlled_data_path_rejects_wildcard_function_parent_escape_and_script():
|
||||
"""数据路径语法拒绝通配符、函数、父级逃逸、脚本。"""
|
||||
assert validate_controlled_data_path('/data/HEADER/EBELN') == '/data/HEADER/EBELN'
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_evidence_retention.py
|
||||
|
||||
用途:阶段 5 evidence_only 保留率——MATNR 第 2/4/5 行 100%。
|
||||
依赖:xfa_validation.compute_evidence_retention_rate、formal_multiline helpers。
|
||||
逻辑:正式提取后断言期望行号全部保留;人为缺行时保留率 < 1.0。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import parse_xfa_datasets
|
||||
from app.services.shipping_notice.document_layout.xfa_profile_extraction import extract_xfa_profile
|
||||
from app.services.shipping_notice.document_layout.xfa_validation import (
|
||||
compute_evidence_retention_rate,
|
||||
)
|
||||
from tests.test_shipping_xfa_formal_multiline_extraction import (
|
||||
_confirmed_matnr_rule_set,
|
||||
_multiline_datasets_xml,
|
||||
_raw_profile,
|
||||
_schema_definition,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
EXPECTED_EVIDENCE_LINES = {2, 4, 5}
|
||||
|
||||
|
||||
def test_matnr_lines_2_4_5_evidence_retention_100_percent():
|
||||
"""关键断言:第 2/4/5 行 evidence_only 保留率 100%。"""
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=_raw_profile(split_rules=[_confirmed_matnr_rule_set()]),
|
||||
dataset_analysis=analysis,
|
||||
schema_definition=_schema_definition(),
|
||||
document_id=1,
|
||||
packet_checksum='pkt-evidence-retain',
|
||||
)
|
||||
rate = compute_evidence_retention_rate(
|
||||
extraction=result,
|
||||
expected_line_nos=EXPECTED_EVIDENCE_LINES,
|
||||
)
|
||||
assert rate == 1.0
|
||||
|
||||
|
||||
def test_missing_evidence_line_lowers_retention_rate():
|
||||
"""关键断言:缺少期望证据行时保留率低于 100%。"""
|
||||
rate = compute_evidence_retention_rate(
|
||||
evidence_segments=[
|
||||
{'line_no': 2, 'normalized_text': 'CAB'},
|
||||
{'line_no': 4, 'normalized_text': 'Cust'},
|
||||
# 故意缺少第 5 行
|
||||
],
|
||||
expected_line_nos=EXPECTED_EVIDENCE_LINES,
|
||||
)
|
||||
assert rate < 1.0
|
||||
assert abs(rate - (2 / 3)) < 1e-6
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_formal_multiline_extraction.py
|
||||
|
||||
用途:正式提取——多行 MATNR 经已确认 stages 流水线产出 customer_part_number 与 part_number。
|
||||
用途:正式提取——多行 MATNR 经已确认 matcher 规则产出 customer_part_number 与 part_number。
|
||||
依赖:xfa_profile_extraction、xfa_split_rule_contract、xfa_dataset、pytest。
|
||||
逻辑:合成多行 datasets XML + 已确认规则集;断言 mapped 字段、evidence_only 与 needs_review 边界。
|
||||
"""
|
||||
@@ -14,12 +14,11 @@ from app.services.shipping_notice.document_layout.xfa_dataset import parse_xfa_d
|
||||
from app.services.shipping_notice.document_layout.xfa_profile_extraction import extract_xfa_profile
|
||||
from app.services.shipping_notice.document_layout.xfa_signature import build_signature_summary
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
XfaSplitMatcher,
|
||||
XfaSplitRule,
|
||||
XfaSplitRuleSet,
|
||||
XfaSplitSegment,
|
||||
XfaSplitStage,
|
||||
new_segment_id,
|
||||
new_stage_id,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
@@ -35,13 +34,6 @@ MATNR_RAW = (
|
||||
AUTH_PATH = '/data/ITEMS/DATA'
|
||||
|
||||
|
||||
def _stage(**kwargs) -> XfaSplitStage:
|
||||
"""构造 stage。"""
|
||||
payload = {'stage_id': new_stage_id()}
|
||||
payload.update(kwargs)
|
||||
return XfaSplitStage.model_validate(payload)
|
||||
|
||||
|
||||
def _multiline_datasets_xml() -> bytes:
|
||||
"""构造含多行 MATNR 的最小 datasets XML。"""
|
||||
return f"""<?xml version="1.0" encoding="UTF-8"?>
|
||||
@@ -91,17 +83,17 @@ def _schema_definition() -> dict:
|
||||
|
||||
|
||||
def _confirmed_matnr_rule_set() -> dict:
|
||||
"""构造已确认、可正式提取的用户配置 MATNR 流水线。"""
|
||||
"""构造已确认、可正式提取的用户配置 MATNR matcher 规则集。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='matnr-multiline-v1',
|
||||
rule_set_id='matnr-multiline-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_scope='line',
|
||||
source_field_code='MATNR',
|
||||
strategy='pipeline',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='cpn',
|
||||
order=1,
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='customer_material_candidate',
|
||||
@@ -110,22 +102,12 @@ def _confirmed_matnr_rule_set() -> dict:
|
||||
target_field_id='f-cpn',
|
||||
target_field_code='customer_part_number',
|
||||
),
|
||||
stages=[_stage(type='split_lines'), _stage(type='select_line', line_index=1)],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='desc',
|
||||
order=2,
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='material_description',
|
||||
display_name='品名规格',
|
||||
handling='evidence_only',
|
||||
),
|
||||
stages=[_stage(type='split_lines'), _stage(type='select_line', line_index=2)],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='mpn',
|
||||
order=3,
|
||||
matcher=XfaSplitMatcher(
|
||||
type='prefix', value='MPN', separators=[':', ':'], case_sensitive=False,
|
||||
),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='mpn_candidate',
|
||||
@@ -134,26 +116,6 @@ def _confirmed_matnr_rule_set() -> dict:
|
||||
target_field_id='f-pn',
|
||||
target_field_code='part_number',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line', line_index=3),
|
||||
_stage(type='extract_prefix', value='MPN', separators=[':', ':'], case_sensitive=False),
|
||||
],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='cust',
|
||||
order=4,
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='customer_number_evidence',
|
||||
display_name='客户编号',
|
||||
handling='evidence_only',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line', line_index=4),
|
||||
_stage(type='extract_prefix', value='Cust nr', separators=[':', ':'], case_sensitive=False),
|
||||
],
|
||||
),
|
||||
],
|
||||
unmatched_line_policy='evidence_only',
|
||||
@@ -161,44 +123,65 @@ def _confirmed_matnr_rule_set() -> dict:
|
||||
status='confirmed',
|
||||
requires_confirmation=False,
|
||||
)
|
||||
return rule_set.model_dump(mode='json')
|
||||
return rule_set.model_dump(mode='json', by_alias=True)
|
||||
|
||||
|
||||
def _confirmed_header_rule_set() -> dict:
|
||||
"""构造 Header 多行账款信息拆分规则。"""
|
||||
"""构造 Header 拆分规则:第 1 行 mapped,其余行 evidence_only。"""
|
||||
return XfaSplitRuleSet(
|
||||
rule_id='invoiced-to-v1',
|
||||
rule_set_id='invoiced-to-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-invoiced-to',
|
||||
source_scope='header',
|
||||
source_field_code='INVOICED_TO',
|
||||
source_data_path='/data/HEADER/INVOICED_TO',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='bill-customer', order=1,
|
||||
rule_id='bill-customer',
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(), segment_code='bill_customer', display_name='账款客户',
|
||||
handling='mapped', target_field_id='f-bill-customer', target_field_code='bill_to_customer',
|
||||
),
|
||||
stages=[_stage(type='split_lines'), _stage(type='select_line', line_index=1)],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='bill-address', order=2,
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(), segment_code='bill_address', display_name='账款地址',
|
||||
handling='mapped', target_field_id='f-bill-address', target_field_code='bill_to_address',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line_range', line_start=2, line_end=4, join_with='newline'),
|
||||
],
|
||||
),
|
||||
],
|
||||
unmatched_line_policy='evidence_only',
|
||||
source='user', status='confirmed', requires_confirmation=False,
|
||||
).model_dump(mode='json')
|
||||
).model_dump(mode='json', by_alias=True)
|
||||
|
||||
|
||||
def _xfa_binding(
|
||||
*,
|
||||
binding_id: str,
|
||||
field_id: str,
|
||||
field_code: str,
|
||||
scope: str,
|
||||
path_id: str,
|
||||
data_path: str,
|
||||
) -> dict:
|
||||
"""构造最小合法统一 binding。"""
|
||||
return {
|
||||
'binding_id': binding_id,
|
||||
'field_id': field_id,
|
||||
'field_code': field_code,
|
||||
'scope': scope,
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': path_id,
|
||||
'data_path': data_path,
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.0, 'y0': 0.0, 'x1': 0.02, 'y1': 0.02},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.0,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _raw_profile(*, split_rules: list[dict] | None = None) -> dict:
|
||||
"""构造含 split_rules 的冻结 XFA Profile。"""
|
||||
"""构造含 split_rules 的冻结 XFA Profile(bindings-only)。"""
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
summary = build_signature_summary(
|
||||
template_bytes=b'<template><subform name="form"/></template>',
|
||||
@@ -215,26 +198,25 @@ def _raw_profile(*, split_rules: list[dict] | None = None) -> dict:
|
||||
'authoritative_line_collection_path': AUTH_PATH,
|
||||
'mirror_collection_paths': ['/data/ITEMS1/DATA'],
|
||||
},
|
||||
'header_mappings': [{
|
||||
'mapping_id': 'm-po', 'field_id': 'f-po', 'field_code': 'customer_po_no',
|
||||
'data_path': '/data/HEADER/EBELN', 'path_id': 'path-po',
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
}],
|
||||
'header_mappings': [],
|
||||
'line_mapping': {
|
||||
'row_path': AUTH_PATH,
|
||||
'fields': [
|
||||
{
|
||||
'mapping_id': 'm-matnr', 'field_id': 'f-matnr', 'field_code': 'material_no',
|
||||
'data_path': f'{AUTH_PATH}/MATNR', 'path_id': 'path-matnr',
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
},
|
||||
{
|
||||
'mapping_id': 'm-qty', 'field_id': 'f-qty', 'field_code': 'quantity',
|
||||
'data_path': f'{AUTH_PATH}/MENGE', 'path_id': 'path-qty',
|
||||
'value_type': 'decimal', 'normalizer_key': 'trim',
|
||||
},
|
||||
],
|
||||
'fields': [],
|
||||
},
|
||||
'bindings': [
|
||||
_xfa_binding(
|
||||
binding_id='bind-m-po', field_id='f-po', field_code='customer_po_no',
|
||||
scope='header', path_id='path-po', data_path='/data/HEADER/EBELN',
|
||||
),
|
||||
_xfa_binding(
|
||||
binding_id='bind-m-matnr', field_id='f-matnr', field_code='material_no',
|
||||
scope='line', path_id='path-matnr', data_path=f'{AUTH_PATH}/MATNR',
|
||||
),
|
||||
_xfa_binding(
|
||||
binding_id='bind-m-qty', field_id='f-qty', field_code='quantity',
|
||||
scope='line', path_id='path-qty', data_path=f'{AUTH_PATH}/MENGE',
|
||||
),
|
||||
],
|
||||
'cross_checks': {
|
||||
'acroform_enabled': False,
|
||||
'mirror_collection_policy': 'must_match_when_present',
|
||||
@@ -247,7 +229,7 @@ def _raw_profile(*, split_rules: list[dict] | None = None) -> dict:
|
||||
|
||||
|
||||
def test_confirmed_split_rules_extract_mapped_fields():
|
||||
"""已确认流水线正式提取产出客户料号与料号。"""
|
||||
"""已确认 matcher 规则正式提取产出客户料号与料号。"""
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=_raw_profile(split_rules=[_confirmed_matnr_rule_set()]),
|
||||
@@ -296,8 +278,8 @@ def test_draft_split_rules_fail_closed_needs_review():
|
||||
assert 'part_number' not in field_codes
|
||||
|
||||
|
||||
def test_confirmed_header_split_rules_extract_once_into_header_fields():
|
||||
"""Header 源规则执行一次并产出客户与连续多行地址。"""
|
||||
def test_confirmed_header_split_rules_extract_customer_line():
|
||||
"""Header 源规则执行一次并产出第 1 行客户名;其余行保留为 evidence。"""
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=_raw_profile(split_rules=[_confirmed_header_rule_set()]),
|
||||
@@ -308,6 +290,4 @@ def test_confirmed_header_split_rules_extract_once_into_header_fields():
|
||||
)
|
||||
header_values = {item.field_code: item.normalized_value for item in result.header_fields}
|
||||
assert header_values['bill_to_customer'] == 'Cloud Network Technology Kft.'
|
||||
assert header_values['bill_to_address'] == 'Bánki Donát u. 1,\n2900 Komárom,\nHungary'
|
||||
assert sum(item.field_code == 'bill_to_customer' for item in result.header_fields) == 1
|
||||
assert result.evidence_summary['header_split_evidence'] == []
|
||||
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_formal_split_extraction.py
|
||||
|
||||
用途:阶段 5 正式拆分提取黄金用例——customer_part_number / part_number。
|
||||
依赖:复用 test_shipping_xfa_formal_multiline_extraction 助手、xfa_profile_extraction。
|
||||
逻辑:断言 TEMP-S000218922 与 D4-A08AR12000001;evidence_only 行保留。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import parse_xfa_datasets
|
||||
from app.services.shipping_notice.document_layout.xfa_profile_extraction import extract_xfa_profile
|
||||
from tests.test_shipping_xfa_formal_multiline_extraction import (
|
||||
_confirmed_matnr_rule_set,
|
||||
_multiline_datasets_xml,
|
||||
_raw_profile,
|
||||
_schema_definition,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_golden_matnr_split_produces_customer_part_and_mpn():
|
||||
"""关键断言:正式拆分产出 TEMP-S000218922 与 D4-A08AR12000001。"""
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=_raw_profile(split_rules=[_confirmed_matnr_rule_set()]),
|
||||
dataset_analysis=analysis,
|
||||
schema_definition=_schema_definition(),
|
||||
document_id=1,
|
||||
packet_checksum='pkt-checksum-formal-split-01234567',
|
||||
)
|
||||
assert result.rows
|
||||
values = {
|
||||
str(item.get('field_code') or ''): item.get('value')
|
||||
for item in (result.rows[0].get('fields') or [])
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
assert values.get('customer_part_number') == 'TEMP-S000218922'
|
||||
assert values.get('part_number') == 'D4-A08AR12000001'
|
||||
evidence = result.rows[0].get('split_evidence') or []
|
||||
line_nos = {int(item['line_no']) for item in evidence if isinstance(item, dict) and item.get('line_no') is not None}
|
||||
# 第 2/4/5 行须保留为 evidence_only。
|
||||
assert {2, 4, 5}.issubset(line_nos)
|
||||
@@ -0,0 +1,202 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_mapping_concurrency.py
|
||||
|
||||
用途:验收 bindings/split_rules 保存的 operation_id 幂等与 lock_version 409。
|
||||
依赖:Flask test client、phase2/multiline XFA 夹具、profile_service。
|
||||
逻辑:重复 operation_id 返回同一 revision;旧 lock_version 稳定 409。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.extensions import db
|
||||
from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfileDraftRevision, User
|
||||
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from tests.conftest import parse_api_error
|
||||
from tests.test_shipping_xfa_formal_multiline_extraction import _schema_definition
|
||||
from tests.test_shipping_xfa_unified_mapping_api import _multiline_sample, _schema_version_id
|
||||
|
||||
|
||||
def _admin_headers(app, username: str) -> dict[str, str]:
|
||||
"""生成 admin JWT。"""
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if not user:
|
||||
user = User(username=username, email=f'{username}@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {'Authorization': f'Bearer {token}'}
|
||||
|
||||
|
||||
def _draft_with_binding(app, monkeypatch):
|
||||
"""创建含 bindings-only(无 line_mapping.fields)与租约的 XFA 草稿。"""
|
||||
with app.app_context():
|
||||
user = User(username='conc-user', email='conc-user@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
schema_id = _schema_version_id(app)
|
||||
document_id, paths = _multiline_sample(app, monkeypatch, user=user)
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'Concurrency',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'conc-tab',
|
||||
'operation_id': 'conc-wizard',
|
||||
}, actor_id=user.id)
|
||||
profile_id = created['id']
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
definition = dict(profile.definition_json)
|
||||
definition['line_mapping'] = {
|
||||
'row_path': definition['source_contract']['authoritative_line_collection_path'],
|
||||
}
|
||||
definition['split_rules'] = []
|
||||
definition['bindings'] = [{
|
||||
'binding_id': 'bind-conc-001',
|
||||
'field_id': 'f-qty',
|
||||
'field_code': 'quantity',
|
||||
'scope': 'line',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': paths['MENGE'],
|
||||
'data_path': '/data/ITEMS/DATA/MENGE',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.6, 'x1': 0.4, 'y1': 0.75},
|
||||
'source': 'manual_draw',
|
||||
'status': 'confirmed',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
}]
|
||||
return int(user.id), schema_id, document_id, created, profile_id, definition, paths
|
||||
|
||||
|
||||
def test_duplicate_operation_id_is_idempotent(app, monkeypatch):
|
||||
"""相同 operation_id + 已落库 snapshot 须幂等,不产生冲突 revision。"""
|
||||
user_id, schema_id, document_id, created, profile_id, definition, _paths = _draft_with_binding(app, monkeypatch)
|
||||
with app.app_context():
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
first = profile_service.save_draft(
|
||||
{
|
||||
'profile_code': profile.profile_code,
|
||||
'display_name': profile.display_name,
|
||||
'schema_version_id': schema_id,
|
||||
'definition': definition,
|
||||
'expected_lock_version': profile.lock_version,
|
||||
'sample_document_id': document_id,
|
||||
},
|
||||
actor_id=user_id,
|
||||
profile_id=profile_id,
|
||||
browser_session_id='conc-tab',
|
||||
lease_token=created['edit_lease']['lease_token'],
|
||||
operation_id='conc-op-idempotent',
|
||||
enforce_lease=True,
|
||||
)
|
||||
rev = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=profile_id, operation_id='conc-op-idempotent',
|
||||
).one()
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
# 重放必须携带已规范化 snapshot,与 Revision 冻结内容一致。
|
||||
second = profile_service.save_draft(
|
||||
{
|
||||
'profile_code': profile.profile_code,
|
||||
'display_name': profile.display_name,
|
||||
'schema_version_id': schema_id,
|
||||
'definition': dict(rev.definition_snapshot_json or {}),
|
||||
'expected_lock_version': profile.lock_version,
|
||||
'sample_document_id': document_id,
|
||||
},
|
||||
actor_id=user_id,
|
||||
profile_id=profile_id,
|
||||
browser_session_id='conc-tab',
|
||||
lease_token=created['edit_lease']['lease_token'],
|
||||
operation_id='conc-op-idempotent',
|
||||
enforce_lease=True,
|
||||
)
|
||||
assert first['draft_revision']['revision_no'] == second['draft_revision']['revision_no']
|
||||
assert first['draft_revision']['operation_id'] == 'conc-op-idempotent'
|
||||
assert ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=profile_id, operation_id='conc-op-idempotent',
|
||||
).count() == 1
|
||||
|
||||
|
||||
def test_stale_lock_version_returns_409_via_api(app, monkeypatch):
|
||||
"""旧 expected_lock_version 经 PUT API 须返回稳定 409。"""
|
||||
_user_id, schema_id, document_id, created, profile_id, definition, _paths = _draft_with_binding(app, monkeypatch)
|
||||
with app.app_context():
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
stale_lock = max(profile.lock_version - 1, 0)
|
||||
profile_code = profile.profile_code
|
||||
display_name = profile.display_name
|
||||
|
||||
client = app.test_client()
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}',
|
||||
json={
|
||||
'profile_code': profile_code,
|
||||
'display_name': display_name,
|
||||
'schema_version_id': schema_id,
|
||||
'definition': definition,
|
||||
'expected_lock_version': stale_lock,
|
||||
'sample_document_id': document_id,
|
||||
'browser_session_id': 'conc-tab',
|
||||
'lease_token': created['edit_lease']['lease_token'],
|
||||
'operation_id': 'conc-stale-lock',
|
||||
},
|
||||
headers=_admin_headers(app, 'conc-user'),
|
||||
)
|
||||
assert response.status_code == 409
|
||||
error = parse_api_error(response.get_json())
|
||||
assert error['code'] in {
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT',
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_LOCK_VERSION_REQUIRED',
|
||||
}
|
||||
|
||||
|
||||
def test_operation_id_conflict_on_different_definition(app, monkeypatch):
|
||||
"""相同 operation_id 但 definition 不同须 409。"""
|
||||
user_id, schema_id, document_id, created, profile_id, definition, _paths = _draft_with_binding(app, monkeypatch)
|
||||
with app.app_context():
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
profile_service.save_draft(
|
||||
{
|
||||
'profile_code': profile.profile_code,
|
||||
'display_name': profile.display_name,
|
||||
'schema_version_id': schema_id,
|
||||
'definition': definition,
|
||||
'expected_lock_version': profile.lock_version,
|
||||
'sample_document_id': document_id,
|
||||
},
|
||||
actor_id=user_id,
|
||||
profile_id=profile_id,
|
||||
browser_session_id='conc-tab',
|
||||
lease_token=created['edit_lease']['lease_token'],
|
||||
operation_id='conc-op-conflict',
|
||||
enforce_lease=True,
|
||||
)
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
mutated = dict(definition)
|
||||
mutated['bindings'] = []
|
||||
with pytest.raises(Exception) as caught:
|
||||
profile_service.save_draft(
|
||||
{
|
||||
'profile_code': profile.profile_code,
|
||||
'display_name': profile.display_name,
|
||||
'schema_version_id': schema_id,
|
||||
'definition': mutated,
|
||||
'expected_lock_version': profile.lock_version,
|
||||
'sample_document_id': document_id,
|
||||
},
|
||||
actor_id=user_id,
|
||||
profile_id=profile_id,
|
||||
browser_session_id='conc-tab',
|
||||
lease_token=created['edit_lease']['lease_token'],
|
||||
operation_id='conc-op-conflict',
|
||||
enforce_lease=True,
|
||||
)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT'
|
||||
@@ -0,0 +1,90 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_mirror_split_consistency.py
|
||||
|
||||
用途:阶段 5 镜像集合在拆分规则下正式字段一致率验收。
|
||||
依赖:xfa_validation、formal_multiline helpers、pytest。
|
||||
逻辑:权威/镜像同 MATNR 多行拆分后 mapped 值一致 → mirror_consistency_rate=1.0;
|
||||
篡改镜像 → mismatched / 0.0。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import parse_xfa_datasets
|
||||
from app.services.shipping_notice.document_layout.xfa_profile_extraction import extract_xfa_profile
|
||||
from app.services.shipping_notice.document_layout.xfa_validation import (
|
||||
compute_mirror_consistency_rate,
|
||||
validate_xfa_extraction,
|
||||
)
|
||||
from tests.test_shipping_xfa_formal_multiline_extraction import (
|
||||
_confirmed_matnr_rule_set,
|
||||
_multiline_datasets_xml,
|
||||
_raw_profile,
|
||||
_schema_definition,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_mirror_split_mapped_fields_consistent():
|
||||
"""关键断言:拆分后镜像正式字段一致 → mirror_consistency_rate=1.0。"""
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
raw_profile = _raw_profile(split_rules=[_confirmed_matnr_rule_set()])
|
||||
extraction = extract_xfa_profile(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
schema_definition=_schema_definition(),
|
||||
document_id=1,
|
||||
packet_checksum='pkt-mirror-split-ok',
|
||||
dataset_structure_fingerprint=raw_profile['definition']['source_contract']['dataset_structure_fingerprint'],
|
||||
)
|
||||
result = validate_xfa_extraction(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
extraction=extraction,
|
||||
pdf_bytes=None,
|
||||
)
|
||||
assert result.passed is True
|
||||
assert result.cross_check_summary['mirror_status'] == 'matched'
|
||||
assert compute_mirror_consistency_rate(result.cross_check_summary) == 1.0
|
||||
|
||||
|
||||
def test_mirror_split_mismatch_rate_zero(monkeypatch):
|
||||
"""关键断言:镜像拆分后 mapped 值不同 → mismatched / rate=0。"""
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
raw_profile = _raw_profile(split_rules=[_confirmed_matnr_rule_set()])
|
||||
extraction = extract_xfa_profile(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
schema_definition=_schema_definition(),
|
||||
document_id=1,
|
||||
packet_checksum='pkt-mirror-split-bad',
|
||||
dataset_structure_fingerprint=raw_profile['definition']['source_contract']['dataset_structure_fingerprint'],
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import read_collection_rows as real_read
|
||||
|
||||
def _fake_rows(dataset_analysis, collection_path):
|
||||
rows = real_read(dataset_analysis, collection_path)
|
||||
if str(collection_path).endswith('ITEMS1/DATA') and rows:
|
||||
mutated = deepcopy(rows)
|
||||
key = '/data/ITEMS1/DATA/MATNR'
|
||||
mutated[0][key] = 'TEMP-OTHER\nCAB\nMPN:OTHER-PN\nCust\nS-ENC'
|
||||
return mutated
|
||||
return rows
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.xfa_validation.read_collection_rows',
|
||||
_fake_rows,
|
||||
)
|
||||
result = validate_xfa_extraction(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
extraction=extraction,
|
||||
pdf_bytes=None,
|
||||
)
|
||||
assert result.passed is False
|
||||
assert 'xfa_mirror_collection_mismatch' in result.reason_codes
|
||||
assert compute_mirror_consistency_rate(result.cross_check_summary) == 0.0
|
||||
@@ -0,0 +1,131 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_page_preview.py
|
||||
|
||||
用途:验收阶段 2 XFA PDF 页面预览不再被禁令阻断,且令牌绑定 actor/profile/页。
|
||||
依赖:preview_service、pytest app fixture、XFA phase2 helpers。
|
||||
逻辑:mock PDFium 渲染;断言 authorize 不抛 XFA 禁令;令牌跨 actor/样本隔离。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice import order_document_profile_preview_service as preview_service
|
||||
from tests.test_order_document_profile_preview_service import _PreviewStore
|
||||
|
||||
|
||||
def test_xfa_profile_frozen_preview_no_longer_raises_blank_pdf_ban(app, monkeypatch):
|
||||
"""关键断言:XFA Profile 签发冻结样本预览时不得再抛 blank PDF 禁令。"""
|
||||
profile = SimpleNamespace(id=1, template_mode='xfa_dataset', definition_json={'template_mode': 'xfa_dataset'})
|
||||
sample = SimpleNamespace(id=2, page_count_snapshot=None)
|
||||
document = SimpleNamespace(id=3)
|
||||
asset = SimpleNamespace()
|
||||
layout = SimpleNamespace()
|
||||
|
||||
monkeypatch.setattr(
|
||||
preview_service,
|
||||
'_frozen_sample_context',
|
||||
lambda **_kwargs: (profile, sample, document, layout, asset),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
preview_service,
|
||||
'_render_pdf_pages',
|
||||
lambda _asset: [
|
||||
SimpleNamespace(page_no=1, image=np.zeros((8, 8, 3), dtype=np.uint8)),
|
||||
SimpleNamespace(page_no=2, image=np.zeros((8, 8, 3), dtype=np.uint8)),
|
||||
SimpleNamespace(page_no=3, image=np.zeros((8, 8, 3), dtype=np.uint8)),
|
||||
],
|
||||
)
|
||||
store = _PreviewStore()
|
||||
monkeypatch.setattr(preview_service, '_preview_grant_store', lambda: store)
|
||||
monkeypatch.setattr(preview_service, '_audit', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(preview_service.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(
|
||||
preview_service.db.session,
|
||||
'get',
|
||||
lambda model, pk: profile if pk == 1 else None,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
payload = preview_service.authorize_frozen_sample_preview_pages(
|
||||
1, sample_binding_id=2, actor_id=99,
|
||||
)
|
||||
|
||||
assert payload['page_count'] == 3
|
||||
assert len(payload['pages']) == 3
|
||||
assert all(item.get('preview_token') for item in payload['pages'])
|
||||
|
||||
|
||||
def test_xfa_readonly_mapping_evidence_allows_pdf_preview():
|
||||
"""只读映射 DTO 应声明 PDF 预览可用(阶段 2)。"""
|
||||
from app.models import ShippingOrderDocumentProfile
|
||||
from app.services.shipping_notice.order_document_profile_preview_service import (
|
||||
build_xfa_readonly_mapping_evidence,
|
||||
)
|
||||
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
id=1,
|
||||
profile_code='XFA',
|
||||
display_name='XFA',
|
||||
version=1,
|
||||
status='published',
|
||||
schema_version_id=1,
|
||||
structure_fingerprint='c' * 64,
|
||||
template_mode='xfa_dataset',
|
||||
definition_json={'template_mode': 'xfa_dataset', 'source_contract': {}, 'header_mappings': [], 'line_mapping': {'fields': []}},
|
||||
)
|
||||
evidence = build_xfa_readonly_mapping_evidence(profile)
|
||||
assert evidence['pdf_preview_available'] is True
|
||||
|
||||
|
||||
def test_preview_token_binds_actor_profile_page(app, monkeypatch):
|
||||
"""render 消费 token 时必须匹配 actor_id、profile_id、sample_binding_id、page_no。"""
|
||||
store = _PreviewStore()
|
||||
monkeypatch.setattr(preview_service, '_preview_grant_store', lambda: store)
|
||||
store.setex(
|
||||
'shipping:order-profile-frozen-preview:tok-1',
|
||||
120,
|
||||
'{"profile_id":1,"sample_binding_id":2,"actor_id":5,"page_no":1}',
|
||||
)
|
||||
profile = SimpleNamespace(id=1)
|
||||
sample = SimpleNamespace(id=2)
|
||||
document = SimpleNamespace(id=3)
|
||||
layout = SimpleNamespace()
|
||||
asset = SimpleNamespace()
|
||||
monkeypatch.setattr(
|
||||
preview_service,
|
||||
'_frozen_sample_context',
|
||||
lambda **_kwargs: (profile, sample, document, layout, asset),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
preview_service,
|
||||
'_render_pdf_pages',
|
||||
lambda _asset: [SimpleNamespace(page_no=1, image=np.zeros((4, 4, 3), dtype=np.uint8))],
|
||||
)
|
||||
monkeypatch.setattr(preview_service, '_audit', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(preview_service.db.session, 'commit', lambda: None)
|
||||
|
||||
with app.app_context():
|
||||
png = preview_service.render_frozen_sample_preview_page(
|
||||
profile_id=1,
|
||||
sample_binding_id=2,
|
||||
token='tok-1',
|
||||
page_no=1,
|
||||
actor_id=5,
|
||||
)
|
||||
assert isinstance(png, bytes) and len(png) > 0
|
||||
|
||||
from app.core.errors import NotFoundError
|
||||
|
||||
with app.app_context():
|
||||
with pytest.raises(NotFoundError):
|
||||
preview_service.render_frozen_sample_preview_page(
|
||||
profile_id=1,
|
||||
sample_binding_id=2,
|
||||
token='tok-1',
|
||||
page_no=1,
|
||||
actor_id=6,
|
||||
)
|
||||
@@ -50,13 +50,77 @@ def _schema_definition() -> dict:
|
||||
return {'fields': fields}
|
||||
|
||||
|
||||
def _xfa_binding(
|
||||
*,
|
||||
binding_id: str,
|
||||
field_id: str,
|
||||
field_code: str,
|
||||
scope: str,
|
||||
path_id: str,
|
||||
data_path: str,
|
||||
) -> dict:
|
||||
"""构造最小合法统一 binding(正式提取 bindings-only)。"""
|
||||
return {
|
||||
'binding_id': binding_id,
|
||||
'field_id': field_id,
|
||||
'field_code': field_code,
|
||||
'scope': scope,
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': path_id,
|
||||
'data_path': data_path,
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.0, 'y0': 0.0, 'x1': 0.02, 'y1': 0.02},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.0,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _raw_profile(*, authoritative: str = '/data/ITEMS/DATA') -> dict:
|
||||
"""构造冻结 XFA Profile。"""
|
||||
"""构造冻结 XFA Profile(bindings-only,无 legacy mappings)。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
summary = build_signature_summary(
|
||||
template_bytes=b'<template><subform name="form"/></template>',
|
||||
dataset_nodes=analysis.nodes,
|
||||
)
|
||||
bindings = [
|
||||
_xfa_binding(
|
||||
binding_id='bind-m-po', field_id='f-po', field_code='customer_po_no',
|
||||
scope='header', path_id='path-po', data_path='/data/HEADER/EBELN',
|
||||
),
|
||||
_xfa_binding(
|
||||
binding_id='bind-m-total', field_id='f-total', field_code='total_amount',
|
||||
scope='header', path_id='path-total', data_path='/data/HEADER/TOTAL_AMOUNT',
|
||||
),
|
||||
_xfa_binding(
|
||||
binding_id='bind-m-mat', field_id='f-mat', field_code='material_no',
|
||||
scope='line', path_id='path-mat', data_path=f'{authoritative}/MATNR',
|
||||
),
|
||||
_xfa_binding(
|
||||
binding_id='bind-m-qty', field_id='f-qty', field_code='quantity',
|
||||
scope='line', path_id='path-qty', data_path=f'{authoritative}/MENGE',
|
||||
),
|
||||
_xfa_binding(
|
||||
binding_id='bind-m-price', field_id='f-price', field_code='unit_price',
|
||||
scope='line', path_id='path-price', data_path=f'{authoritative}/NETPR',
|
||||
),
|
||||
_xfa_binding(
|
||||
binding_id='bind-m-pu', field_id='f-pu', field_code='price_unit',
|
||||
scope='line', path_id='path-pu', data_path=f'{authoritative}/PEINH',
|
||||
),
|
||||
_xfa_binding(
|
||||
binding_id='bind-m-amt', field_id='f-amt', field_code='amount',
|
||||
scope='line', path_id='path-amt', data_path=f'{authoritative}/AMOUNT',
|
||||
),
|
||||
_xfa_binding(
|
||||
binding_id='bind-m-date', field_id='f-date', field_code='delivery_date',
|
||||
scope='line', path_id='path-date', data_path=f'{authoritative}/EINDT',
|
||||
),
|
||||
]
|
||||
return {
|
||||
'profile_id': 7,
|
||||
'profile_code': 'XFA_GOLDEN',
|
||||
@@ -73,53 +137,12 @@ def _raw_profile(*, authoritative: str = '/data/ITEMS/DATA') -> dict:
|
||||
'authoritative_line_collection_path': authoritative,
|
||||
'mirror_collection_paths': ['/data/ITEMS1/DATA'],
|
||||
},
|
||||
'header_mappings': [
|
||||
{
|
||||
'mapping_id': 'm-po', 'field_id': 'f-po', 'field_code': 'customer_po_no',
|
||||
'data_path': '/data/HEADER/EBELN', 'path_id': 'path-po',
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
},
|
||||
{
|
||||
'mapping_id': 'm-total', 'field_id': 'f-total', 'field_code': 'total_amount',
|
||||
'data_path': '/data/HEADER/TOTAL_AMOUNT', 'path_id': 'path-total',
|
||||
'value_type': 'decimal', 'normalizer_key': 'trim',
|
||||
},
|
||||
],
|
||||
'header_mappings': [],
|
||||
'line_mapping': {
|
||||
'row_path': authoritative,
|
||||
'fields': [
|
||||
{
|
||||
'mapping_id': 'm-mat', 'field_id': 'f-mat', 'field_code': 'material_no',
|
||||
'data_path': f'{authoritative}/MATNR', 'path_id': 'path-mat',
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
},
|
||||
{
|
||||
'mapping_id': 'm-qty', 'field_id': 'f-qty', 'field_code': 'quantity',
|
||||
'data_path': f'{authoritative}/MENGE', 'path_id': 'path-qty',
|
||||
'value_type': 'decimal', 'normalizer_key': 'trim',
|
||||
},
|
||||
{
|
||||
'mapping_id': 'm-price', 'field_id': 'f-price', 'field_code': 'unit_price',
|
||||
'data_path': f'{authoritative}/NETPR', 'path_id': 'path-price',
|
||||
'value_type': 'decimal', 'normalizer_key': 'trim',
|
||||
},
|
||||
{
|
||||
'mapping_id': 'm-pu', 'field_id': 'f-pu', 'field_code': 'price_unit',
|
||||
'data_path': f'{authoritative}/PEINH', 'path_id': 'path-pu',
|
||||
'value_type': 'integer', 'normalizer_key': 'trim',
|
||||
},
|
||||
{
|
||||
'mapping_id': 'm-amt', 'field_id': 'f-amt', 'field_code': 'amount',
|
||||
'data_path': f'{authoritative}/AMOUNT', 'path_id': 'path-amt',
|
||||
'value_type': 'decimal', 'normalizer_key': 'trim',
|
||||
},
|
||||
{
|
||||
'mapping_id': 'm-date', 'field_id': 'f-date', 'field_code': 'delivery_date',
|
||||
'data_path': f'{authoritative}/EINDT', 'path_id': 'path-date',
|
||||
'value_type': 'date', 'normalizer_key': 'trim',
|
||||
},
|
||||
],
|
||||
'fields': [],
|
||||
},
|
||||
'bindings': bindings,
|
||||
'cross_checks': {
|
||||
'acroform_enabled': True,
|
||||
'mirror_collection_policy': 'must_match_when_present',
|
||||
@@ -179,11 +202,13 @@ def test_authoritative_collection_missing_fails_closed():
|
||||
"""关键断言:权威集合缺失 → needs_review reason。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
raw_profile = _raw_profile(authoritative='/data/ITEMS/MISSING')
|
||||
# row_path 必须等于 authoritative;手工破坏集合路径以模拟缺失。
|
||||
raw_profile['definition']['source_contract']['authoritative_line_collection_path'] = '/data/ITEMS/MISSING'
|
||||
raw_profile['definition']['line_mapping']['row_path'] = '/data/ITEMS/MISSING'
|
||||
for item in raw_profile['definition']['line_mapping']['fields']:
|
||||
item['data_path'] = item['data_path'].replace('/data/ITEMS/DATA', '/data/ITEMS/MISSING')
|
||||
for item in raw_profile['definition']['bindings']:
|
||||
if item.get('scope') == 'line':
|
||||
item['value_binding']['data_path'] = str(item['value_binding']['data_path']).replace(
|
||||
'/data/ITEMS/DATA', '/data/ITEMS/MISSING',
|
||||
)
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
@@ -216,12 +241,11 @@ def test_netpr_composite_splits_unit_price_and_price_unit():
|
||||
)
|
||||
assert typed == Decimal('898.72')
|
||||
|
||||
# 正式提取:去掉 PEINH 映射后仍应由 NETPR 复合值补齐 price_unit。
|
||||
# 正式提取:去掉 price_unit binding 后仍应由 NETPR 复合值补齐 price_unit。
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
raw_profile = _raw_profile()
|
||||
raw_profile['definition']['line_mapping']['fields'] = [
|
||||
item
|
||||
for item in raw_profile['definition']['line_mapping']['fields']
|
||||
raw_profile['definition']['bindings'] = [
|
||||
item for item in raw_profile['definition']['bindings']
|
||||
if item.get('field_code') != 'price_unit'
|
||||
]
|
||||
result = extract_xfa_profile(
|
||||
@@ -241,3 +265,39 @@ def test_netpr_composite_splits_unit_price_and_price_unit():
|
||||
if item.get('field_code') == 'unit_price'
|
||||
)
|
||||
assert '898.72 / 1' in str(unit_item.get('quote') or '')
|
||||
|
||||
|
||||
def test_missing_bindings_fails_closed():
|
||||
"""关键断言:无 bindings → xfa_visual_bindings_required。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
raw_profile = _raw_profile()
|
||||
raw_profile['definition']['bindings'] = []
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
schema_definition=_schema_definition(),
|
||||
document_id=85,
|
||||
packet_checksum='sha256:' + ('a' * 64),
|
||||
)
|
||||
assert result.status == 'failed'
|
||||
assert 'xfa_visual_bindings_required' in result.reason_codes
|
||||
|
||||
|
||||
def test_dual_binding_source_fails_closed():
|
||||
"""关键断言:bindings 与 legacy mappings 共存 → xfa_dual_binding_source。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
raw_profile = _raw_profile()
|
||||
raw_profile['definition']['header_mappings'] = [{
|
||||
'mapping_id': 'm-po', 'field_id': 'f-po', 'field_code': 'customer_po_no',
|
||||
'data_path': '/data/HEADER/EBELN', 'path_id': 'path-po',
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
}]
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
schema_definition=_schema_definition(),
|
||||
document_id=85,
|
||||
packet_checksum='sha256:' + ('a' * 64),
|
||||
)
|
||||
assert result.status == 'failed'
|
||||
assert 'xfa_dual_binding_source' in result.reason_codes
|
||||
@@ -200,11 +200,26 @@ def test_xfa_save_mapping_creates_revision_and_clears_signature(app, _patch_xfa_
|
||||
before_checksum = profile.structure_fingerprint
|
||||
definition = dict(profile.definition_json)
|
||||
definition['authoritative_collection_path_id'] = paths['ITEMS_DATA']
|
||||
definition['header_mappings'] = [{
|
||||
'mapping_id': 'm-po', 'field_id': 'ignored', 'field_code': 'customer_po_no',
|
||||
'data_path': '/data/HEADER/EBELN', 'path_id': paths['EBELN'], 'value_type': 'string',
|
||||
}]
|
||||
definition['header_mappings'] = []
|
||||
definition['line_mapping'] = {'row_path': '/data/ITEMS/DATA', 'fields': []}
|
||||
definition['bindings'] = [{
|
||||
'binding_id': 'bind-po-001',
|
||||
'field_id': 'ignored',
|
||||
'field_code': 'customer_po_no',
|
||||
'scope': 'header',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': paths['EBELN'],
|
||||
'data_path': '/data/HEADER/EBELN',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.4, 'y1': 0.2},
|
||||
'source': 'manual_draw',
|
||||
'status': 'confirmed',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
}]
|
||||
saved = profile_service.save_draft(
|
||||
{
|
||||
'profile_code': profile.profile_code,
|
||||
@@ -225,7 +240,7 @@ def test_xfa_save_mapping_creates_revision_and_clears_signature(app, _patch_xfa_
|
||||
assert refreshed.structure_fingerprint != before_checksum
|
||||
assert refreshed.matching_signature_run_id is None
|
||||
assert ShippingOrderDocumentProfileDraftRevision.query.filter_by(profile_id=profile_id).count() >= 2
|
||||
assert saved['definition']['header_mappings'][0]['field_id'] == 'f-po'
|
||||
assert saved['definition']['bindings'][0]['field_id'] == 'f-po'
|
||||
# 关键断言:Schema 必填明细字段可由 EML 等其他来源补充,不得成为 XFA 模板映射问题。
|
||||
assert 'mapping_issues' not in saved
|
||||
assert ShippingOrderDocumentProfileAudit.query.filter_by(
|
||||
@@ -252,9 +267,25 @@ def test_xfa_unknown_path_id_blocked(app, _patch_xfa_io):
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, created['id'])
|
||||
bad = dict(profile.definition_json)
|
||||
bad['authoritative_collection_path_id'] = paths['ITEMS_DATA']
|
||||
bad['header_mappings'] = [{
|
||||
'mapping_id': 'm1', 'field_code': 'customer_po_no', 'path_id': 'path-unknown-xxx',
|
||||
'data_path': '/data/HEADER/EBELN', 'value_type': 'string', 'field_id': 'x',
|
||||
bad['header_mappings'] = []
|
||||
bad['line_mapping'] = {'row_path': '/data/ITEMS/DATA', 'fields': []}
|
||||
bad['bindings'] = [{
|
||||
'binding_id': 'bind-bad-001',
|
||||
'field_id': 'x',
|
||||
'field_code': 'customer_po_no',
|
||||
'scope': 'header',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-unknown-xxx',
|
||||
'data_path': '/data/HEADER/EBELN',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.2, 'y1': 0.2},
|
||||
'source': 'manual_draw',
|
||||
'status': 'confirmed',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
}]
|
||||
with pytest.raises(Exception) as caught:
|
||||
profile_service.save_draft(
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_publish_separation_of_duties.py
|
||||
|
||||
用途:阶段 6 发布职责分离契约——编辑人不得批准自己的 Revision。
|
||||
依赖:publish_check_service 已有 consume 阻断键;本文件固化原因码与审计事件集合。
|
||||
逻辑:纯单元断言职责分离键与编辑审计事件白名单稳定。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice import order_document_profile_publish_check_service as checks
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_editor_self_approval_reason_key_is_stable():
|
||||
"""关键断言:职责分离失败键稳定为 editor_cannot_approve_own_version。"""
|
||||
source = inspect.getsource(checks.consume_report)
|
||||
assert 'editor_cannot_approve_own_version' in source
|
||||
assert '_find_last_profile_editor_id' in source
|
||||
|
||||
|
||||
def test_editor_audit_events_cover_mapping_and_split():
|
||||
"""关键断言:查找最近编辑者覆盖映射、拆分与视觉绑定编辑审计事件。"""
|
||||
source = inspect.getsource(checks._find_last_profile_editor_id)
|
||||
for event in (
|
||||
'xfa_mapping_saved',
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_segment_mapping_updated',
|
||||
'xfa_profile_draft_saved',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
):
|
||||
assert event in source
|
||||
@@ -0,0 +1,88 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_safe_regex.py
|
||||
|
||||
用途:锁定 XFA 安全正则模块——RE2 优先、restricted_re 子进程 fallback、禁止灾难回溯模式。
|
||||
依赖:xfa_safe_regex。
|
||||
逻辑:纯单测;不读 PDF;超时用例通过 monkeypatch 慢 worker,避免无限挂死。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
from app.services.shipping_notice.document_layout import xfa_safe_regex as safe_regex_mod
|
||||
from app.services.shipping_notice.document_layout.xfa_safe_regex import (
|
||||
SafeRegexError,
|
||||
compile_safe_regex,
|
||||
has_re2_engine,
|
||||
search_safe,
|
||||
validate_restricted_regex_pattern,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def force_restricted_re(monkeypatch: pytest.MonkeyPatch):
|
||||
"""强制走 restricted_re 引擎,便于覆盖子进程匹配路径。"""
|
||||
monkeypatch.setattr(safe_regex_mod, '_HAS_RE2', False)
|
||||
|
||||
|
||||
def test_validate_rejects_forbidden_and_catastrophic_patterns():
|
||||
"""命名捕获与嵌套量词必须拒绝。"""
|
||||
with pytest.raises(SafeRegexError, match='forbidden'):
|
||||
validate_restricted_regex_pattern(r'(?P<name>x)', max_length=128, max_groups=5)
|
||||
with pytest.raises(SafeRegexError, match='catastrophic'):
|
||||
validate_restricted_regex_pattern(r'(a+)+$', max_length=128, max_groups=5)
|
||||
|
||||
|
||||
def test_compile_and_search_basic_capture():
|
||||
"""可编译并捕获分组。"""
|
||||
compiled = compile_safe_regex(r'^MPN:(.+)$', case_sensitive=True, max_length=128, max_groups=5)
|
||||
matched = search_safe(compiled, 'MPN:ABC123', timeout_ms=50)
|
||||
assert matched is not None
|
||||
assert matched.group(1) == 'ABC123'
|
||||
assert has_re2_engine() in (True, False)
|
||||
|
||||
|
||||
def test_search_returns_none_when_no_match():
|
||||
"""无匹配时返回 None。"""
|
||||
compiled = compile_safe_regex(r'^MPN:(.+)$', case_sensitive=True, max_length=128, max_groups=5)
|
||||
assert search_safe(compiled, 'NOPE', timeout_ms=50) is None
|
||||
|
||||
|
||||
def test_case_insensitive_search():
|
||||
"""不区分大小写时可命中。"""
|
||||
compiled = compile_safe_regex(r'^mpn:(.+)$', case_sensitive=False, max_length=128, max_groups=5)
|
||||
matched = search_safe(compiled, 'MPN:XYZ', timeout_ms=50)
|
||||
assert matched is not None
|
||||
assert matched.group(1) == 'XYZ'
|
||||
|
||||
|
||||
def test_restricted_re_subprocess_basic_match(force_restricted_re):
|
||||
"""restricted_re 子进程路径:基本捕获仍可用。"""
|
||||
compiled = compile_safe_regex(r'^MPN:(.+)$', case_sensitive=True, max_length=128, max_groups=5)
|
||||
assert compiled.engine == 'restricted_re'
|
||||
matched = search_safe(compiled, 'MPN:ABC123', timeout_ms=500)
|
||||
assert matched is not None
|
||||
assert matched.group(1) == 'ABC123'
|
||||
|
||||
|
||||
def test_restricted_re_subprocess_no_match(force_restricted_re):
|
||||
"""restricted_re 子进程路径:无匹配时返回 None。"""
|
||||
compiled = compile_safe_regex(r'^MPN:(.+)$', case_sensitive=True, max_length=128, max_groups=5)
|
||||
assert search_safe(compiled, 'NOPE', timeout_ms=500) is None
|
||||
|
||||
|
||||
def test_restricted_re_subprocess_timeout_kills_worker(force_restricted_re):
|
||||
"""restricted_re 灾难回溯场景:超时抛 TimeoutError,且不等待完整回溯结束。"""
|
||||
compiled = compile_safe_regex(r'(a|a)*X', case_sensitive=True, max_length=128, max_groups=5)
|
||||
haystack = 'a' * 32 + 'Y'
|
||||
started = time.monotonic()
|
||||
with pytest.raises(TimeoutError, match='timed out'):
|
||||
search_safe(compiled, haystack, timeout_ms=100)
|
||||
elapsed = time.monotonic() - started
|
||||
assert elapsed < 2.0
|
||||
safe_regex_mod._destroy_restricted_pool()
|
||||
@@ -19,6 +19,7 @@ REQUIRED_SPLIT_AUDIT_EVENTS = (
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_split_rule_previewed',
|
||||
'xfa_split_rule_validated',
|
||||
'xfa_split_rule_confirmed',
|
||||
'xfa_split_segment_created',
|
||||
'xfa_split_segment_updated',
|
||||
'xfa_split_segment_deleted',
|
||||
@@ -39,20 +40,16 @@ def test_split_audit_events_registered_in_contracts():
|
||||
|
||||
|
||||
def _rule_set(*, segment_id: str, handling: str = 'mapped', target: str | None = 'customer_part_number') -> dict:
|
||||
"""构造最小可 diff 的拆分规则集(stages 流水线)。"""
|
||||
"""构造最小可 diff 的拆分规则集(matcher 模型)。"""
|
||||
return {
|
||||
'rule_id': 'rs-1',
|
||||
'rule_set_id': 'rs-1',
|
||||
'rule_version': 1,
|
||||
'source_path_id': 'path-matnr',
|
||||
'source_scope': 'line',
|
||||
'source_field_code': 'MATNR',
|
||||
'strategy': 'pipeline',
|
||||
'rules': [{
|
||||
'rule_id': 'r-1',
|
||||
'order': 1,
|
||||
'stages': [
|
||||
{'stage_id': 'st-split', 'type': 'split_lines', 'line_breaks': ['\n']},
|
||||
{'stage_id': 'st-sel', 'type': 'select_line', 'line_index': 1},
|
||||
],
|
||||
'matcher': {'type': 'position', 'line_index': 1},
|
||||
'segment': {
|
||||
'segment_id': segment_id,
|
||||
'segment_code': 'cpn' if segment_id == 'seg-a' else segment_id.replace('-', '_'),
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_split_confirmation_gate.py
|
||||
|
||||
用途:反向锁定 BE-1/BE-2/BE-3/BE-4——拆分确认令牌消费、样本绑定、显式拒绝与审计。
|
||||
依赖:xfa_split_preview_token、_enforce_split_rule_confirmation_integrity。
|
||||
逻辑:纯单测 + Flask app 上下文签发令牌;禁止客户端无令牌声明 confirmed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.document_layout.xfa_split_preview_token import (
|
||||
issue_split_preview_token,
|
||||
split_rule_preview_fingerprint,
|
||||
verify_and_consume_split_preview_token,
|
||||
verify_split_preview_token,
|
||||
)
|
||||
from app.services.shipping_notice.order_document_profile_service import (
|
||||
_enforce_split_rule_confirmation_integrity,
|
||||
split_rules_definition_changed,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
SAMPLE_CHECKSUM = hashlib.sha256(b'test-split-sample').hexdigest()[:32]
|
||||
FAKE_PATH_CONTEXT = {
|
||||
'path_map': {'path-a': '/data/ITEMS/DATA/MATNR'},
|
||||
'dataset_analysis': object(),
|
||||
'analysis': None,
|
||||
'template_packet_checksum': 'sha256:tpl-test',
|
||||
'dataset_structure_fingerprint': 'sha256:fp-test',
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _stable_sample_checksum(monkeypatch):
|
||||
"""单测固定 sample_checksum,避免依赖完整 XFA dataset 树。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_document_profile_service._compute_split_source_sample_checksum',
|
||||
lambda **_kw: SAMPLE_CHECKSUM,
|
||||
)
|
||||
|
||||
|
||||
def _rule_set(*, status: str = 'draft', path_id: str = 'path-a') -> dict:
|
||||
return {
|
||||
'rule_set_id': 'rs1',
|
||||
'rule_id': 'rs1',
|
||||
'rule_version': 1,
|
||||
'source_path_id': path_id,
|
||||
'source_field_code': 'MATNR',
|
||||
'strategy': 'matcher',
|
||||
'normalization': {'trim': True, 'remove_empty_lines': True, 'line_breaks': ['\n']},
|
||||
'rules': [{
|
||||
'rule_id': 'r1',
|
||||
'order': 1,
|
||||
'matcher': {'type': 'position', 'line_index': 1},
|
||||
'segment': {
|
||||
'segment_id': 's1',
|
||||
'segment_code': 'customer_part',
|
||||
'display_name': 'CPN',
|
||||
'handling': 'mapped',
|
||||
'target_field_code': 'customer_part_number',
|
||||
},
|
||||
}],
|
||||
'unmatched_line_policy': 'evidence_only',
|
||||
'duplicate_match_policy': 'needs_review',
|
||||
'same_field_multiple_segment_policy': 'needs_review',
|
||||
'source': 'user',
|
||||
'status': status,
|
||||
'requires_confirmation': status != 'confirmed',
|
||||
}
|
||||
|
||||
|
||||
def _issue_token(app, rule: dict, *, actor_id: int = 7, sample_checksum: str = SAMPLE_CHECKSUM) -> str:
|
||||
with app.app_context():
|
||||
return issue_split_preview_token(
|
||||
actor_id=actor_id,
|
||||
profile_id=11,
|
||||
document_id=22,
|
||||
path_id='path-a',
|
||||
rule_fingerprint=split_rule_preview_fingerprint(rule),
|
||||
sample_checksum=sample_checksum,
|
||||
analysis_id=99,
|
||||
template_packet_checksum=FAKE_PATH_CONTEXT['template_packet_checksum'],
|
||||
dataset_structure_fingerprint=FAKE_PATH_CONTEXT['dataset_structure_fingerprint'],
|
||||
)
|
||||
|
||||
|
||||
def test_client_cannot_confirm_split_rules_without_token(app):
|
||||
"""关键断言:无 preview token 时客户端声明 confirmed 须显式抛错,不得静默降级 draft。"""
|
||||
with app.app_context():
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
_enforce_split_rule_confirmation_integrity(
|
||||
previous_definition={},
|
||||
definition={'split_rules': [_rule_set(status='confirmed')]},
|
||||
confirmation_tokens=None,
|
||||
actor_id=7,
|
||||
profile_id=11,
|
||||
document_id=22,
|
||||
path_context=FAKE_PATH_CONTEXT,
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_CONFIRM_REJECTED'
|
||||
assert caught.value.details.get('reason') == 'token_missing'
|
||||
|
||||
|
||||
def test_valid_preview_token_allows_confirmed(app, monkeypatch):
|
||||
"""关键断言:服务端签发令牌可把规则确认为 confirmed(一次消费)。"""
|
||||
audit_calls: list[str] = []
|
||||
platform_calls: list[str] = []
|
||||
|
||||
def _capture_audit(**kwargs):
|
||||
audit_calls.append(str(kwargs.get('event_type')))
|
||||
|
||||
def _capture_platform(**kwargs):
|
||||
platform_calls.append(str(kwargs.get('event_type')))
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_document_profile_service._audit',
|
||||
_capture_audit,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.audit_service.append_shipping_audit_event',
|
||||
_capture_platform,
|
||||
)
|
||||
with app.app_context():
|
||||
rule = _rule_set(status='confirmed')
|
||||
token = _issue_token(app, rule)
|
||||
out = _enforce_split_rule_confirmation_integrity(
|
||||
previous_definition={},
|
||||
definition={'split_rules': [rule]},
|
||||
confirmation_tokens={'path-a': token},
|
||||
actor_id=7,
|
||||
profile_id=11,
|
||||
document_id=22,
|
||||
path_context=FAKE_PATH_CONTEXT,
|
||||
)
|
||||
assert out['split_rules'][0]['status'] == 'confirmed'
|
||||
assert out['split_rules'][0]['requires_confirmation'] is False
|
||||
assert 'xfa_split_rule_confirmed' in audit_calls
|
||||
assert 'xfa_split_rule_confirmed' in platform_calls
|
||||
|
||||
|
||||
def test_preview_token_rejects_replay(app):
|
||||
"""关键断言:同一令牌二次消费须失败(token_replay)。"""
|
||||
with app.app_context():
|
||||
rule = _rule_set()
|
||||
token = _issue_token(app, rule)
|
||||
verify_and_consume_split_preview_token(
|
||||
token,
|
||||
actor_id=7,
|
||||
profile_id=11,
|
||||
document_id=22,
|
||||
path_id='path-a',
|
||||
rule_fingerprint=split_rule_preview_fingerprint(rule),
|
||||
sample_checksum=SAMPLE_CHECKSUM,
|
||||
analysis_id=99,
|
||||
template_packet_checksum=FAKE_PATH_CONTEXT['template_packet_checksum'],
|
||||
dataset_structure_fingerprint=FAKE_PATH_CONTEXT['dataset_structure_fingerprint'],
|
||||
)
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
verify_and_consume_split_preview_token(
|
||||
token,
|
||||
actor_id=7,
|
||||
profile_id=11,
|
||||
document_id=22,
|
||||
path_id='path-a',
|
||||
rule_fingerprint=split_rule_preview_fingerprint(rule),
|
||||
sample_checksum=SAMPLE_CHECKSUM,
|
||||
analysis_id=99,
|
||||
template_packet_checksum=FAKE_PATH_CONTEXT['template_packet_checksum'],
|
||||
dataset_structure_fingerprint=FAKE_PATH_CONTEXT['dataset_structure_fingerprint'],
|
||||
)
|
||||
assert caught.value.details.get('reason') == 'token_replay'
|
||||
|
||||
|
||||
def test_preview_token_rejects_sample_checksum_mismatch(app):
|
||||
"""关键断言:样本 checksum 不匹配时确认须被拒绝。"""
|
||||
with app.app_context():
|
||||
rule = _rule_set(status='confirmed')
|
||||
token = _issue_token(app, rule, sample_checksum='deadbeef' * 2)
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
_enforce_split_rule_confirmation_integrity(
|
||||
previous_definition={},
|
||||
definition={'split_rules': [rule]},
|
||||
confirmation_tokens={'path-a': token},
|
||||
actor_id=7,
|
||||
profile_id=11,
|
||||
document_id=22,
|
||||
path_context=FAKE_PATH_CONTEXT,
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_CONFIRM_REJECTED'
|
||||
assert caught.value.details.get('reason') == 'sample_checksum_mismatch'
|
||||
|
||||
|
||||
def test_preview_token_rejects_actor_mismatch(app):
|
||||
"""关键断言:令牌绑定 actor,他人不可复用。"""
|
||||
with app.app_context():
|
||||
rule = _rule_set()
|
||||
token = _issue_token(app, rule)
|
||||
with pytest.raises(ValidationError):
|
||||
verify_split_preview_token(
|
||||
token,
|
||||
actor_id=8,
|
||||
profile_id=11,
|
||||
document_id=22,
|
||||
path_id='path-a',
|
||||
rule_fingerprint=split_rule_preview_fingerprint(rule),
|
||||
sample_checksum=SAMPLE_CHECKSUM,
|
||||
)
|
||||
|
||||
|
||||
def test_split_rules_definition_changed_detects_content_drift():
|
||||
"""关键断言:内容变更检测供 xfa_split_rule_edit 门禁使用。"""
|
||||
prev = {'split_rules': [_rule_set(status='confirmed')]}
|
||||
nxt = {'split_rules': [_rule_set(status='confirmed')]}
|
||||
nxt['split_rules'][0]['rules'][0]['matcher'] = {'type': 'position', 'line_index': 2}
|
||||
assert split_rules_definition_changed(prev, nxt) is True
|
||||
assert split_rules_definition_changed(prev, prev) is False
|
||||
@@ -0,0 +1,114 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_split_preview_api.py
|
||||
|
||||
用途:验收拆分规则 preview API 零写库,并保留 rule_checksum/preview_token。
|
||||
依赖:Flask test client、多行 MATNR 夹具、SQLAlchemy session 监听。
|
||||
逻辑:preview 前后业务表/审计表写入计数为 0;响应含 checksum 与 token。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import event
|
||||
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.extensions import db
|
||||
from app.models import ShippingAuditEvent, ShippingOrderDocumentProfileAudit, User
|
||||
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
|
||||
from tests.conftest import parse_api_data
|
||||
from tests.test_shipping_xfa_formal_multiline_extraction import _confirmed_matnr_rule_set, _multiline_datasets_xml
|
||||
from tests.test_shipping_xfa_unified_mapping_api import _admin_headers, _multiline_sample, _schema_version_id
|
||||
|
||||
|
||||
def _count_pending_writes(session) -> int:
|
||||
"""统计 session 中待 flush 的新对象数。"""
|
||||
return len(session.new) + len(session.dirty) + len(session.deleted)
|
||||
|
||||
|
||||
def test_split_preview_api_zero_db_writes(app, monkeypatch):
|
||||
"""preview API 不得 commit 任何业务或审计写入。"""
|
||||
with app.app_context():
|
||||
user = User(username='preview-zero', email='preview-zero@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
schema_id = _schema_version_id(app)
|
||||
document_id, paths = _multiline_sample(app, monkeypatch, user=user)
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'Preview Zero',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'preview-tab',
|
||||
'operation_id': 'preview-wizard',
|
||||
}, actor_id=user.id)
|
||||
profile_id = created['id']
|
||||
rule_set = _confirmed_matnr_rule_set()
|
||||
rule_set['source_path_id'] = paths['MATNR']
|
||||
rule_set['status'] = 'draft'
|
||||
rule_set['requires_confirmation'] = True
|
||||
|
||||
audit_before = ShippingOrderDocumentProfileAudit.query.count()
|
||||
shipping_audit_before = ShippingAuditEvent.query.count()
|
||||
|
||||
write_events: list[int] = []
|
||||
|
||||
def _before_flush(session, _flush_context, _instances):
|
||||
write_events.append(_count_pending_writes(session))
|
||||
|
||||
event.listen(db.session, 'before_flush', _before_flush)
|
||||
try:
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profile-samples/{document_id}/xfa/split-rules/preview',
|
||||
json={
|
||||
'path_id': paths['MATNR'],
|
||||
'rule_set': rule_set,
|
||||
'profile_id': profile_id,
|
||||
},
|
||||
headers=_admin_headers(app, 'preview-zero'),
|
||||
)
|
||||
finally:
|
||||
event.remove(db.session, 'before_flush', _before_flush)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = parse_api_data(response.get_json())
|
||||
assert data['rule_checksum']
|
||||
assert data['preview_token']
|
||||
assert data['sample_checksum']
|
||||
assert write_events == []
|
||||
assert ShippingOrderDocumentProfileAudit.query.count() == audit_before
|
||||
assert ShippingAuditEvent.query.count() == shipping_audit_before
|
||||
|
||||
|
||||
def test_split_preview_service_returns_mapped_values(app, monkeypatch):
|
||||
"""preview 须对多行 MATNR 样本产出映射预览。"""
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
with app.app_context():
|
||||
user = User(username='preview-values', email='preview-values@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
schema_id = _schema_version_id(app)
|
||||
document_id, paths = _multiline_sample(app, monkeypatch, user=user)
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'Preview Values',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'pv-tab',
|
||||
'operation_id': 'pv-wizard',
|
||||
}, actor_id=user.id)
|
||||
rule_set = _confirmed_matnr_rule_set()
|
||||
rule_set['source_path_id'] = paths['MATNR']
|
||||
rule_set['status'] = 'draft'
|
||||
payload = profile_service.preview_xfa_split_rules(
|
||||
document_id,
|
||||
path_id=paths['MATNR'],
|
||||
rule_set=rule_set,
|
||||
actor_id=user.id,
|
||||
profile_id=created['id'],
|
||||
include_full_values=True,
|
||||
write_audit=False,
|
||||
)
|
||||
mapped = payload['preview']['mapped_fields']
|
||||
assert mapped['customer_part_number'] == 'TEMP-S000218922'
|
||||
assert mapped['part_number'] == 'D4-A08AR12000001'
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_split_rule_contract.py
|
||||
|
||||
用途:锁定 XFA 字段拆分规则契约——segment/stages 白名单、Schema 映射边界、
|
||||
用途:锁定 XFA 字段拆分规则契约——matcher 模型、Schema 映射边界、
|
||||
evidence_only 约束与正则资源上限。
|
||||
依赖:xfa_split_rule_contract。
|
||||
逻辑:纯契约单测;不读 PDF;不执行引擎。
|
||||
@@ -13,13 +13,14 @@ import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
XFA_SPLIT_MATCHER_PRIORITY,
|
||||
XfaSplitMatcher,
|
||||
XfaSplitRule,
|
||||
XfaSplitRuleSet,
|
||||
XfaSplitSegment,
|
||||
XfaSplitStage,
|
||||
new_segment_id,
|
||||
new_stage_id,
|
||||
parse_split_rule_sets,
|
||||
split_rule_content_fingerprint,
|
||||
validate_split_rules_against_schema,
|
||||
)
|
||||
|
||||
@@ -38,12 +39,19 @@ def _mapped_segment(**overrides):
|
||||
return XfaSplitSegment.model_validate(payload)
|
||||
|
||||
|
||||
def _select_line_pipeline(*, line_index: int = 1) -> list[XfaSplitStage]:
|
||||
"""构造最小流水线:换行 → 选行。"""
|
||||
return [
|
||||
XfaSplitStage(stage_id=new_stage_id('split'), type='split_lines'),
|
||||
XfaSplitStage(stage_id=new_stage_id('sel'), type='select_line', line_index=line_index),
|
||||
]
|
||||
def _position_rule(*, line_index: int = 1, **segment_overrides) -> XfaSplitRule:
|
||||
"""构造 position 规则。"""
|
||||
return XfaSplitRule(
|
||||
rule_id='r-position',
|
||||
matcher=XfaSplitMatcher(type='position', line_index=line_index),
|
||||
segment=_mapped_segment(**segment_overrides),
|
||||
)
|
||||
|
||||
|
||||
def test_matcher_priority_constants():
|
||||
"""冻结优先级 prefix > regex > position。"""
|
||||
assert XFA_SPLIT_MATCHER_PRIORITY['prefix'] < XFA_SPLIT_MATCHER_PRIORITY['regex']
|
||||
assert XFA_SPLIT_MATCHER_PRIORITY['regex'] < XFA_SPLIT_MATCHER_PRIORITY['position']
|
||||
|
||||
|
||||
def test_mapped_requires_target_fields():
|
||||
@@ -70,43 +78,50 @@ def test_evidence_only_forbids_target_fields():
|
||||
)
|
||||
|
||||
|
||||
def test_stage_whitelist_and_regex_limits():
|
||||
"""仅允许声明式 stage;过长/命名捕获/嵌套量词正则拒绝。"""
|
||||
assert XfaSplitStage(stage_id='s1', type='select_line', line_index=1).type == 'select_line'
|
||||
line_range = XfaSplitStage(
|
||||
stage_id='range-1', type='select_line_range',
|
||||
line_start=2, line_end=4, join_with='newline',
|
||||
def test_matcher_whitelist_and_regex_limits():
|
||||
"""matcher 白名单;过长/命名捕获/嵌套量词正则拒绝。"""
|
||||
assert XfaSplitMatcher(type='position', line_index=1).type == 'position'
|
||||
assert XfaSplitMatcher(type='prefix', value='MPN').value == 'MPN'
|
||||
assert XfaSplitMatcher(
|
||||
type='regex', pattern=r'^MPN[::](.+)$', capture_group=1,
|
||||
).type == 'regex'
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitMatcher(type='position')
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitMatcher(type='prefix', value='')
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitMatcher(type='regex', pattern='a' * 200)
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitMatcher(type='regex', pattern=r'(?P<name>x)')
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitMatcher(type='regex', pattern=r'(a+)+$')
|
||||
|
||||
|
||||
def test_rule_set_accepts_rule_id_alias():
|
||||
"""历史 rule_id 字段可解析为 rule_set_id。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='matnr-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_scope='line',
|
||||
rules=[_position_rule()],
|
||||
source='user',
|
||||
status='confirmed',
|
||||
requires_confirmation=False,
|
||||
)
|
||||
assert line_range.line_end == 4
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitStage(stage_id='range-2', type='select_line_range', line_start=4, line_end=2)
|
||||
assert XfaSplitStage(stage_id='s2', type='extract_prefix', value='MPN').value == 'MPN'
|
||||
assert XfaSplitStage(
|
||||
stage_id='s3', type='regex_capture', pattern=r'^MPN[::](.+)$', capture_group=1,
|
||||
).type == 'regex_capture'
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitStage(stage_id='s4', type='regex_capture', pattern='a' * 200)
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitStage(stage_id='s5', type='regex_capture', pattern=r'(?P<name>x)')
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitStage(stage_id='s6', type='regex_capture', pattern=r'(a+)+$')
|
||||
assert rule_set.rule_set_id == 'matnr-v1'
|
||||
assert rule_set.rule_id == 'matnr-v1'
|
||||
|
||||
|
||||
def test_system_suggestion_must_be_draft():
|
||||
"""系统推荐必须 draft + requires_confirmation。"""
|
||||
rule = XfaSplitRule(
|
||||
rule_id='r1',
|
||||
order=1,
|
||||
segment=_mapped_segment(),
|
||||
stages=_select_line_pipeline(),
|
||||
)
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitRuleSet(
|
||||
rule_id='matnr-v1',
|
||||
rule_set_id='matnr-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_field_code='MATNR',
|
||||
rules=[rule],
|
||||
source_scope='line',
|
||||
rules=[_position_rule()],
|
||||
source='system_suggestion',
|
||||
status='confirmed',
|
||||
requires_confirmation=True,
|
||||
@@ -129,20 +144,19 @@ def test_validate_against_schema_requires_source_target_scope_match(
|
||||
):
|
||||
"""拆分结果只能映射与源节点相同作用域的 Schema 字段。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='matnr-v1',
|
||||
rule_set_id='matnr-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_field_code='MATNR',
|
||||
source_scope=source_scope, # type: ignore[arg-type]
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='r1',
|
||||
order=1,
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=_mapped_segment(
|
||||
target_field_id='f-target',
|
||||
target_field_code='target_field',
|
||||
segment_code='scope_target',
|
||||
),
|
||||
stages=_select_line_pipeline(),
|
||||
),
|
||||
],
|
||||
source='user',
|
||||
@@ -171,18 +185,11 @@ def test_validate_against_schema_requires_source_target_scope_match(
|
||||
def test_validate_against_schema_rejects_unknown_field():
|
||||
"""目标 Schema 不存在时拒绝。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='matnr-v1',
|
||||
rule_set_id='matnr-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_field_code='MATNR',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='r1',
|
||||
order=1,
|
||||
segment=_mapped_segment(),
|
||||
stages=_select_line_pipeline(),
|
||||
),
|
||||
],
|
||||
source_scope='line',
|
||||
rules=[_position_rule()],
|
||||
source='user',
|
||||
status='confirmed',
|
||||
requires_confirmation=False,
|
||||
@@ -201,28 +208,50 @@ def test_parse_split_rule_sets_empty():
|
||||
assert parse_split_rule_sets([]) == []
|
||||
|
||||
|
||||
def test_duplicate_order_rejected():
|
||||
"""同一规则集内 order 必须唯一。"""
|
||||
def test_duplicate_rule_id_rejected():
|
||||
"""同一规则集内 rule_id 必须唯一。"""
|
||||
segment = _mapped_segment(segment_code='code_a')
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitRuleSet(
|
||||
rule_id='matnr-v1',
|
||||
rule_set_id='matnr-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_field_code='MATNR',
|
||||
source_scope='line',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='r1', order=1, segment=_mapped_segment(segment_code='a'),
|
||||
stages=_select_line_pipeline(line_index=1),
|
||||
rule_id='dup', matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=segment,
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='r2', order=1,
|
||||
rule_id='dup', matcher=XfaSplitMatcher(type='position', line_index=2),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='b',
|
||||
display_name='B',
|
||||
handling='evidence_only',
|
||||
segment_id=new_segment_id(), segment_code='b',
|
||||
display_name='B', handling='evidence_only',
|
||||
),
|
||||
stages=_select_line_pipeline(line_index=2),
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_mapping_target_does_not_change_confirmed_rule_fingerprint():
|
||||
"""Schema 映射与 matcher 分离,绑定目标字段不得改变内容指纹。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_set_id='header-v1', rule_version=1,
|
||||
source_path_id='path-header', source_scope='header',
|
||||
rules=[XfaSplitRule(
|
||||
rule_id='r1',
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id='segment-1', segment_code='bill_customer', display_name='账款客户',
|
||||
handling='evidence_only',
|
||||
),
|
||||
)],
|
||||
status='confirmed', requires_confirmation=False,
|
||||
)
|
||||
mapped = rule_set.model_dump(mode='json', by_alias=True)
|
||||
mapped['rules'][0]['segment'].update({
|
||||
'handling': 'mapped',
|
||||
'target_field_id': 'f-bill',
|
||||
'target_field_code': 'bill_to_customer',
|
||||
})
|
||||
assert split_rule_content_fingerprint(rule_set) == split_rule_content_fingerprint(mapped)
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_split_rule_engine.py
|
||||
|
||||
用途:锁定 XFA 多阶段拆分引擎——流水线解析、同行冲突、脱敏投影、order 执行。
|
||||
用途:锁定 XFA 优先级拆分引擎——prefix > regex > position、冲突语义与 MATNR 五行样本。
|
||||
依赖:xfa_split_rule_engine、xfa_split_rule_contract。
|
||||
逻辑:纯引擎单测;不读真实 PDF。
|
||||
"""
|
||||
@@ -13,12 +13,11 @@ from app.services.shipping_notice.document_layout.xfa_split_rule_engine import (
|
||||
project_split_result_safe,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
XfaSplitMatcher,
|
||||
XfaSplitRule,
|
||||
XfaSplitRuleSet,
|
||||
XfaSplitSegment,
|
||||
XfaSplitStage,
|
||||
new_segment_id,
|
||||
new_stage_id,
|
||||
)
|
||||
|
||||
MATNR_RAW = (
|
||||
@@ -30,25 +29,18 @@ MATNR_RAW = (
|
||||
)
|
||||
|
||||
|
||||
def _stage(**kwargs) -> XfaSplitStage:
|
||||
"""构造 stage,自动补 stage_id。"""
|
||||
payload = {'stage_id': new_stage_id()}
|
||||
payload.update(kwargs)
|
||||
return XfaSplitStage.model_validate(payload)
|
||||
|
||||
|
||||
def _matnr_pipeline_rule_set(*, status: str = 'confirmed', requires_confirmation: bool = False) -> XfaSplitRuleSet:
|
||||
"""用户配置的 MATNR 多阶段规则集。"""
|
||||
def _matnr_rule_set(*, status: str = 'confirmed', requires_confirmation: bool = False) -> XfaSplitRuleSet:
|
||||
"""MATNR 五行样本:position1 + prefix MPN,其余 unmatched evidence_only。"""
|
||||
return XfaSplitRuleSet(
|
||||
rule_id='matnr-multiline-v1',
|
||||
rule_set_id='matnr-multiline-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_scope='line',
|
||||
source_field_code='MATNR',
|
||||
strategy='pipeline',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='cpn',
|
||||
order=1,
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='customer_material_candidate',
|
||||
@@ -57,28 +49,12 @@ def _matnr_pipeline_rule_set(*, status: str = 'confirmed', requires_confirmation
|
||||
target_field_id='f-cpn',
|
||||
target_field_code='customer_part_number',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line', line_index=1),
|
||||
],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='desc',
|
||||
order=2,
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='material_description',
|
||||
display_name='品名规格',
|
||||
handling='evidence_only',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line', line_index=2),
|
||||
],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='mpn',
|
||||
order=3,
|
||||
matcher=XfaSplitMatcher(
|
||||
type='prefix', value='MPN', separators=[':', ':'], case_sensitive=False,
|
||||
),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='mpn_candidate',
|
||||
@@ -87,26 +63,6 @@ def _matnr_pipeline_rule_set(*, status: str = 'confirmed', requires_confirmation
|
||||
target_field_id='f-pn',
|
||||
target_field_code='part_number',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line', line_index=3),
|
||||
_stage(type='extract_prefix', value='MPN', separators=[':', ':'], case_sensitive=False),
|
||||
],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='cust',
|
||||
order=4,
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='customer_number_evidence',
|
||||
display_name='客户编号',
|
||||
handling='evidence_only',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line', line_index=4),
|
||||
_stage(type='extract_prefix', value='Cust nr', separators=[':', ':'], case_sensitive=False),
|
||||
],
|
||||
),
|
||||
],
|
||||
unmatched_line_policy='evidence_only',
|
||||
@@ -118,7 +74,7 @@ def _matnr_pipeline_rule_set(*, status: str = 'confirmed', requires_confirmation
|
||||
|
||||
def test_project_split_result_masks_by_default():
|
||||
"""默认投影必须脱敏,不得泄露完整 raw_text。"""
|
||||
result = execute_split_rule_set(raw_value=MATNR_RAW, rule_set=_matnr_pipeline_rule_set())
|
||||
result = execute_split_rule_set(raw_value=MATNR_RAW, rule_set=_matnr_rule_set())
|
||||
masked = project_split_result_safe(result, include_full_values=False)
|
||||
assert masked['full_values_revealed'] is False
|
||||
assert 'TEMP-S000218922' not in str(masked['mapped_fields'])
|
||||
@@ -128,30 +84,74 @@ def test_project_split_result_masks_by_default():
|
||||
assert full['evidence_only_segments'] == []
|
||||
|
||||
|
||||
def test_multiline_pipeline_parses_matnr_sample():
|
||||
"""多阶段流水线:正式字段两项 + 证据保留。"""
|
||||
rule_set = _matnr_pipeline_rule_set()
|
||||
result = execute_split_rule_set(raw_value=MATNR_RAW, rule_set=rule_set)
|
||||
def test_matnr_five_line_sample():
|
||||
"""五行 MATNR:position1→customer_part_number,prefix MPN→part_number,其余 evidence_only。"""
|
||||
result = execute_split_rule_set(raw_value=MATNR_RAW, rule_set=_matnr_rule_set())
|
||||
assert result.status == 'parsed'
|
||||
assert result.mapped_fields['customer_part_number'] == 'TEMP-S000218922'
|
||||
assert result.mapped_fields['part_number'] == 'D4-A08AR12000001'
|
||||
evidence = {item.normalized_text for item in result.evidence_only_segments}
|
||||
assert 'CAB 42.5U AR1.2 FRAME' in evidence
|
||||
assert '504-006043-001' in evidence
|
||||
assert 'Cust nr:504-006043-001' in evidence
|
||||
assert 'S-ENC-FOBU260702-286' in evidence
|
||||
mapped_lines = {item.line_no for item in result.segments if item.handling == 'mapped'}
|
||||
assert mapped_lines == {1, 3}
|
||||
|
||||
|
||||
def test_same_line_claimed_by_two_pipelines_needs_review():
|
||||
"""两条流水线认领同一行 → duplicate_line_match。"""
|
||||
def test_prefix_beats_position_on_same_line():
|
||||
"""同行 prefix 优先级高于 position。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='dup-v1',
|
||||
rule_set_id='prio-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_field_code='MATNR',
|
||||
source_scope='line',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='pos',
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='line1_full',
|
||||
display_name='整行',
|
||||
handling='mapped',
|
||||
target_field_id='f-cpn',
|
||||
target_field_code='customer_part_number',
|
||||
),
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='pref',
|
||||
matcher=XfaSplitMatcher(type='prefix', value='MPN', separators=[':']),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='mpn_only',
|
||||
display_name='MPN',
|
||||
handling='mapped',
|
||||
target_field_id='f-pn',
|
||||
target_field_code='part_number',
|
||||
),
|
||||
),
|
||||
],
|
||||
unmatched_line_policy='evidence_only',
|
||||
source='user',
|
||||
status='confirmed',
|
||||
requires_confirmation=False,
|
||||
)
|
||||
result = execute_split_rule_set(raw_value='MPN:HELLO', rule_set=rule_set)
|
||||
assert result.mapped_fields['part_number'] == 'HELLO'
|
||||
assert 'customer_part_number' not in result.mapped_fields
|
||||
|
||||
|
||||
def test_same_priority_mapped_conflict_needs_review():
|
||||
"""同优先级两个 mapped 命中同一行 → duplicate_line_match。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_set_id='dup-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_scope='line',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='a',
|
||||
order=1,
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='a_part',
|
||||
@@ -160,11 +160,10 @@ def test_same_line_claimed_by_two_pipelines_needs_review():
|
||||
target_field_id='f-cpn',
|
||||
target_field_code='customer_part_number',
|
||||
),
|
||||
stages=[_stage(type='split_lines'), _stage(type='select_line', line_index=1)],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='b',
|
||||
order=2,
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='b_part',
|
||||
@@ -173,7 +172,6 @@ def test_same_line_claimed_by_two_pipelines_needs_review():
|
||||
target_field_id='f-pn',
|
||||
target_field_code='part_number',
|
||||
),
|
||||
stages=[_stage(type='split_lines'), _stage(type='select_line', line_index=1)],
|
||||
),
|
||||
],
|
||||
source='user',
|
||||
@@ -185,91 +183,17 @@ def test_same_line_claimed_by_two_pipelines_needs_review():
|
||||
assert any(d.code == 'duplicate_line_match' for d in result.diagnostics)
|
||||
|
||||
|
||||
def test_consecutive_line_range_preserves_newlines_and_claims_full_range():
|
||||
"""连续多行提取保留换行,并确保范围内行不再生成 unmatched 证据。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='address-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-address',
|
||||
source_field_code='DELIVER_TO',
|
||||
rules=[XfaSplitRule(
|
||||
rule_id='address',
|
||||
order=1,
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='delivery_address',
|
||||
display_name='收货地址',
|
||||
handling='evidence_only',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(
|
||||
type='select_line_range', line_start=2, line_end=4,
|
||||
join_with='newline',
|
||||
),
|
||||
],
|
||||
)],
|
||||
source='user',
|
||||
status='confirmed',
|
||||
requires_confirmation=False,
|
||||
)
|
||||
result = execute_split_rule_set(
|
||||
raw_value='Cloud Network Technology Kft.\nBánki Donát u. 1,\n2900 Komárom,\nHungary\nFooter',
|
||||
rule_set=rule_set,
|
||||
)
|
||||
address = next(item for item in result.segments if item.rule_id == 'address')
|
||||
assert address.normalized_text == 'Bánki Donát u. 1,\n2900 Komárom,\nHungary'
|
||||
assert (address.line_no, address.line_end_no) == (2, 4)
|
||||
unmatched_lines = {item.line_no for item in result.evidence_only_segments if item.rule_id == 'unmatched'}
|
||||
assert unmatched_lines == {1, 5}
|
||||
|
||||
|
||||
def test_overlapping_line_range_needs_review():
|
||||
"""连续行范围与单行规则重叠时必须进入复核。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='overlap-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-address',
|
||||
source_field_code='DELIVER_TO',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='range', order=1,
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(), segment_code='address',
|
||||
display_name='地址', handling='evidence_only',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line_range', line_start=2, line_end=4, join_with='space'),
|
||||
],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='single', order=2,
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(), segment_code='country',
|
||||
display_name='国家', handling='evidence_only',
|
||||
),
|
||||
stages=[_stage(type='split_lines'), _stage(type='select_line', line_index=4)],
|
||||
),
|
||||
],
|
||||
source='user', status='confirmed', requires_confirmation=False,
|
||||
)
|
||||
result = execute_split_rule_set(raw_value='Company\nStreet\nCity\nCountry', rule_set=rule_set)
|
||||
assert result.status == 'needs_review'
|
||||
assert any(d.code == 'duplicate_line_match' and d.line_no == 4 for d in result.diagnostics)
|
||||
|
||||
|
||||
def test_same_field_multiple_segment_needs_review():
|
||||
"""同一正式字段被多段命中 → needs_review。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='conflict-v1',
|
||||
rule_set_id='conflict-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_field_code='MATNR',
|
||||
source_scope='line',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='r1',
|
||||
order=1,
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='a_part',
|
||||
@@ -278,11 +202,10 @@ def test_same_field_multiple_segment_needs_review():
|
||||
target_field_id='f-pn',
|
||||
target_field_code='part_number',
|
||||
),
|
||||
stages=[_stage(type='split_lines'), _stage(type='select_line', line_index=1)],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='r2',
|
||||
order=2,
|
||||
matcher=XfaSplitMatcher(type='position', line_index=2),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='b_part',
|
||||
@@ -291,7 +214,6 @@ def test_same_field_multiple_segment_needs_review():
|
||||
target_field_id='f-pn',
|
||||
target_field_code='part_number',
|
||||
),
|
||||
stages=[_stage(type='split_lines'), _stage(type='select_line', line_index=2)],
|
||||
),
|
||||
],
|
||||
source='user',
|
||||
@@ -303,63 +225,24 @@ def test_same_field_multiple_segment_needs_review():
|
||||
assert any(d.code == 'same_field_multiple_segment' for d in result.diagnostics)
|
||||
|
||||
|
||||
def test_prefix_after_select_line():
|
||||
"""选行后再按前缀提取。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='prio-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_field_code='MATNR',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='pref',
|
||||
order=1,
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='mpn_only',
|
||||
display_name='MPN',
|
||||
handling='mapped',
|
||||
target_field_id='f-pn',
|
||||
target_field_code='part_number',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line', line_index=1),
|
||||
_stage(type='extract_prefix', value='MPN', separators=[':']),
|
||||
],
|
||||
),
|
||||
],
|
||||
unmatched_line_policy='evidence_only',
|
||||
source='user',
|
||||
status='confirmed',
|
||||
requires_confirmation=False,
|
||||
)
|
||||
result = execute_split_rule_set(raw_value='MPN:HELLO', rule_set=rule_set)
|
||||
assert result.mapped_fields['part_number'] == 'HELLO'
|
||||
|
||||
|
||||
def test_line_breaks_config_is_honored():
|
||||
"""normalization.line_breaks 参与未匹配行盘点切分。"""
|
||||
"""normalization.line_breaks 参与拆行与未匹配行盘点。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='breaks-v1',
|
||||
rule_set_id='breaks-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-x',
|
||||
source_field_code='X',
|
||||
source_scope='line',
|
||||
normalization={'trim': True, 'remove_empty_lines': True, 'line_breaks': ['|']},
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='r1',
|
||||
order=1,
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='first',
|
||||
display_name='First',
|
||||
handling='evidence_only',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines', line_breaks=['|'], trim=True, remove_empty_lines=True),
|
||||
_stage(type='select_line', line_index=1),
|
||||
],
|
||||
),
|
||||
],
|
||||
source='user',
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_audit.py
|
||||
|
||||
用途:验收统一视觉/拆分审计事件已注册,并在确认视觉绑定与保存草稿路径被触发;
|
||||
confirm 路径双写平台审计含加密快照引用。
|
||||
依赖:xfa_contract、progress_audit_contract、visual_binding_service、order_document_profile_service、
|
||||
audit_service、ShippingAuditEvent、ShippingXfaAuditSnapshot。
|
||||
逻辑:契约白名单断言 + mock 审计写入 + confirm 路径 snapshot refs 集成断言。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent, ShippingXfaAuditSnapshot
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import XFA_AUDIT_EVENT_TYPES
|
||||
from app.services.shipping_notice.progress_audit_contract import XFA_PROGRESS_EVENT_CODES
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
from app.services.shipping_notice import order_document_profile_visual_binding_service as visual_svc
|
||||
from app.services.shipping_notice.order_document_profile_audit_service import (
|
||||
XFA_VISUAL_BINDING_AUDIT_EVENTS,
|
||||
build_profile_audit_context,
|
||||
record_visual_binding_audit,
|
||||
)
|
||||
|
||||
|
||||
REQUIRED_UNIFIED_AUDIT_EVENTS = (
|
||||
'xfa_visual_binding_suggested',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_split_rule_previewed',
|
||||
'xfa_profile_draft_saved',
|
||||
'order_profile_unified_migration_dry_run',
|
||||
'order_profile_unified_migration_executed',
|
||||
)
|
||||
|
||||
|
||||
def _ensure_secret_key(app) -> None:
|
||||
"""确保 SECRET_KEY 可用于派生 XFA 审计快照 Fernet。"""
|
||||
if not str(app.config.get('SECRET_KEY') or '').strip():
|
||||
app.config['SECRET_KEY'] = 'test-shipping-xfa-visual-audit-secret'
|
||||
|
||||
|
||||
def test_unified_visual_and_split_audit_events_registered():
|
||||
"""关键审计事件必须同时出现在 XFA 契约与进度事件白名单。"""
|
||||
for event in REQUIRED_UNIFIED_AUDIT_EVENTS:
|
||||
assert event in XFA_AUDIT_EVENT_TYPES, event
|
||||
assert event in XFA_PROGRESS_EVENT_CODES, event
|
||||
for event in XFA_VISUAL_BINDING_AUDIT_EVENTS:
|
||||
assert event in XFA_AUDIT_EVENT_TYPES
|
||||
|
||||
|
||||
def test_confirm_visual_binding_fires_confirmed_audit():
|
||||
"""确认视觉绑定路径必须写入 xfa_visual_binding_confirmed(Profile _audit)。"""
|
||||
with patch.object(profiles, '_audit') as audit_mock:
|
||||
with patch(
|
||||
'app.services.shipping_notice.audit_service.append_shipping_audit_event',
|
||||
) as platform_mock:
|
||||
record_visual_binding_audit(
|
||||
profile_id=11,
|
||||
document_id=None,
|
||||
event_type='xfa_visual_binding_confirmed',
|
||||
actor_id=3,
|
||||
before={'status': 'suggested', 'field_code': 'part_number'},
|
||||
after={'status': 'confirmed', 'field_code': 'part_number'},
|
||||
detail={'binding_id': 'bind-1', 'action': 'confirm'},
|
||||
operation_id='op-confirm-1',
|
||||
profile_context={
|
||||
'profile_code': 'PO-XFA',
|
||||
'profile_version': 1,
|
||||
'definition_checksum': 'sha256:abc',
|
||||
'revision_no': 2,
|
||||
'template_mode': 'xfa_dataset',
|
||||
},
|
||||
)
|
||||
assert audit_mock.call_count == 1
|
||||
kwargs = audit_mock.call_args.kwargs
|
||||
assert kwargs['event_type'] == 'xfa_visual_binding_confirmed'
|
||||
assert kwargs['detail']['before_visual_binding']['status'] == 'suggested'
|
||||
assert kwargs['detail']['after_visual_binding']['status'] == 'confirmed'
|
||||
assert platform_mock.call_count == 1
|
||||
platform_kwargs = platform_mock.call_args.kwargs
|
||||
assert platform_kwargs['event_type'] == 'xfa_visual_binding_confirmed'
|
||||
assert platform_kwargs['aggregate_type'] == 'shipping_order_document_profile'
|
||||
assert platform_kwargs['aggregate_id'] == '11'
|
||||
assert platform_kwargs['sensitivity_level'] == 'sensitive'
|
||||
assert platform_kwargs['context_refs']['binding_id'] == 'bind-1'
|
||||
assert platform_kwargs['context_refs']['action'] == 'confirm'
|
||||
|
||||
|
||||
def test_confirm_visual_binding_platform_audit_has_snapshot_refs(app):
|
||||
"""confirm 路径双写平台事件含加密 full 快照引用。"""
|
||||
with app.app_context():
|
||||
_ensure_secret_key(app)
|
||||
record_visual_binding_audit(
|
||||
profile_id=77,
|
||||
document_id=None,
|
||||
event_type='xfa_visual_binding_confirmed',
|
||||
actor_id=3,
|
||||
before={'status': 'suggested', 'field_code': 'part_number', 'binding_id': 'bind-77'},
|
||||
after={'status': 'confirmed', 'field_code': 'part_number', 'binding_id': 'bind-77'},
|
||||
detail={'binding_id': 'bind-77', 'action': 'confirm'},
|
||||
operation_id='op-confirm-snap',
|
||||
request_id='req-confirm-snap',
|
||||
raw_binding_before={'binding_id': 'bind-77', 'field_code': 'part_number', 'visual_binding': {'status': 'suggested'}},
|
||||
raw_binding_after={'binding_id': 'bind-77', 'field_code': 'part_number', 'visual_binding': {'status': 'confirmed'}},
|
||||
profile_context={
|
||||
'profile_code': 'PO-XFA-77',
|
||||
'profile_version': 3,
|
||||
'definition_checksum': 'sha256:before-cs',
|
||||
'revision_no': 4,
|
||||
'template_mode': 'xfa_dataset',
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
event = (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(
|
||||
aggregate_type='shipping_order_document_profile',
|
||||
aggregate_id='77',
|
||||
event_type='xfa_visual_binding_confirmed',
|
||||
)
|
||||
.order_by(ShippingAuditEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
assert event is not None
|
||||
assert event.operation_id == 'op-confirm-snap'
|
||||
assert event.request_id == 'req-confirm-snap'
|
||||
ctx = event.context_refs_json or {}
|
||||
assert ctx.get('snapshot_before_ref', '').startswith('xfa-snap-')
|
||||
assert ctx.get('snapshot_after_ref', '').startswith('xfa-snap-')
|
||||
assert ctx.get('binding_id') == 'bind-77'
|
||||
assert ctx.get('action') == 'confirm'
|
||||
assert event.before_hash
|
||||
assert event.after_hash
|
||||
assert ShippingXfaAuditSnapshot.query.filter_by(object_id='77').count() >= 2
|
||||
assert event.metadata_json.get('binding_id') == 'bind-77'
|
||||
|
||||
|
||||
def test_save_draft_path_emits_draft_saved_audit_hook():
|
||||
"""保存草稿路径上的 binding/split diff 审计钩子可被调用(mock)。"""
|
||||
before = {'bindings': [], 'split_rules': []}
|
||||
after = {
|
||||
'bindings': [{
|
||||
'binding_id': 'bind-0001-aaaa',
|
||||
'field_id': 'fld-1',
|
||||
'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-1',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.3, 'y1': 0.25},
|
||||
'source': 'manual_draw',
|
||||
'status': 'confirmed',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
}],
|
||||
'split_rules': [],
|
||||
}
|
||||
with patch.object(profiles, '_audit') as audit_mock:
|
||||
profiles._audit_xfa_binding_changes(
|
||||
profile_id=21,
|
||||
actor_id=5,
|
||||
operation_id='op-save-1',
|
||||
browser_session_id='tab-1',
|
||||
previous_definition=before,
|
||||
next_definition=after,
|
||||
)
|
||||
profiles._audit(
|
||||
profile_id=21,
|
||||
event_type='xfa_profile_draft_saved',
|
||||
actor_id=5,
|
||||
operation_id='op-save-1',
|
||||
detail={'definition_checksum': 'sha256:test'},
|
||||
)
|
||||
events = [call.kwargs['event_type'] for call in audit_mock.call_args_list]
|
||||
assert 'xfa_profile_draft_saved' in events
|
||||
# binding 变更至少产出一条审计(created/updated 族)
|
||||
assert any(
|
||||
event.startswith('xfa_visual_binding_') or event == 'xfa_mapping_saved' or 'binding' in event
|
||||
for event in events
|
||||
) or audit_mock.call_count >= 2
|
||||
|
||||
|
||||
def test_confirm_service_calls_record_audit_when_definition_ready():
|
||||
"""confirm_xfa_visual_binding 在成功路径委托 record_visual_binding_audit(mock 编排)。"""
|
||||
profile = MagicMock()
|
||||
profile.id = 9
|
||||
profile.status = 'draft'
|
||||
profile.template_mode = 'xfa_dataset'
|
||||
profile.definition_json = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
'mirror_collection_paths': [],
|
||||
},
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [{
|
||||
'binding_id': 'bind-0001-aaaa',
|
||||
'field_id': 'fld-1',
|
||||
'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-1',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.3, 'y1': 0.25},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.5,
|
||||
},
|
||||
}],
|
||||
'split_rules': [],
|
||||
}
|
||||
with (
|
||||
patch.object(visual_svc, '_profile', return_value=profile),
|
||||
patch.object(visual_svc.lease_service, 'require_active_lease'),
|
||||
patch.object(visual_svc, 'record_visual_binding_audit') as audit_mock,
|
||||
patch.object(visual_svc.db.session, 'flush'),
|
||||
patch.object(visual_svc.db.session, 'commit'),
|
||||
):
|
||||
result = visual_svc.confirm_xfa_visual_binding(
|
||||
9,
|
||||
'bind-0001-aaaa',
|
||||
visual_binding={
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.3, 'y1': 0.25},
|
||||
'source': 'manual_draw',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
path_id=None,
|
||||
actor_id=7,
|
||||
browser_session_id='sess',
|
||||
lease_token='lease',
|
||||
operation_id='op-1',
|
||||
)
|
||||
assert result['status'] == 'confirmed'
|
||||
assert audit_mock.call_count == 1
|
||||
assert audit_mock.call_args.kwargs['event_type'] == 'xfa_visual_binding_confirmed'
|
||||
@@ -0,0 +1,117 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_auto_create.py
|
||||
|
||||
用途:阶段 6 统一自动建单——Profile checksum / 视觉可发布性再验 + CQ 指标消费。
|
||||
依赖:order_stp_auto_create_service、candidate_qualification_service、phase6 helpers。
|
||||
逻辑:适配 phase6 正例;断言低视觉率 / checksum 漂移阻断;STP 再验失败 needs_review。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.candidate_qualification_service import (
|
||||
evaluate_candidate_qualification,
|
||||
)
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
_revalidate_published_xfa_profile,
|
||||
_xfa_stp_precheck,
|
||||
)
|
||||
from tests.test_shipping_xfa_auto_create_phase6 import (
|
||||
_eligible_xfa_candidate,
|
||||
_patch_xfa_policy,
|
||||
_xfa_unit,
|
||||
)
|
||||
|
||||
|
||||
def test_unified_auto_create_passes_phase6_baseline(monkeypatch):
|
||||
"""关键断言:既有 phase6 正例在统一门禁下仍可自动建单。"""
|
||||
_patch_xfa_policy(monkeypatch)
|
||||
result = evaluate_candidate_qualification(
|
||||
candidate=_eligible_xfa_candidate(),
|
||||
unit=_xfa_unit(),
|
||||
fields_complete=True,
|
||||
customer_resolved=True,
|
||||
schema_auto_create_enabled=True,
|
||||
)
|
||||
assert result['can_auto_create'] is True
|
||||
|
||||
|
||||
def test_parser_trace_visual_rate_blocks_auto_create(monkeypatch):
|
||||
"""关键断言:parser_trace.visual_coverage_rate < 1.0 → 阻断。"""
|
||||
_patch_xfa_policy(monkeypatch)
|
||||
result = evaluate_candidate_qualification(
|
||||
candidate=_eligible_xfa_candidate(),
|
||||
unit=_xfa_unit(xfa_unified_metrics={
|
||||
'visual_coverage_rate': 0.5,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
}),
|
||||
fields_complete=True,
|
||||
customer_resolved=True,
|
||||
schema_auto_create_enabled=True,
|
||||
)
|
||||
assert result['can_auto_create'] is False
|
||||
assert result['gates'].get('xfa_unified_profile_snapshot') is False
|
||||
assert 'xfa_visual_coverage_insufficient' in result['blocking_reason_codes']
|
||||
|
||||
|
||||
def test_stp_revalidate_checksum_mismatch(monkeypatch):
|
||||
"""关键断言:已发布 Profile checksum 漂移 → xfa_profile_checksum_mismatch。"""
|
||||
profile = SimpleNamespace(
|
||||
status='published',
|
||||
checksum='sha256:other',
|
||||
structure_fingerprint='sha256:other',
|
||||
template_mode='xfa_dataset',
|
||||
definition_json={'template_mode': 'xfa_dataset', 'bindings': []},
|
||||
schema_version=SimpleNamespace(definition_json={'fields': []}),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.db.session.get',
|
||||
lambda model, pk: profile,
|
||||
)
|
||||
ok, reason = _revalidate_published_xfa_profile(
|
||||
validation={
|
||||
'qualification': {
|
||||
'parser_trace': {
|
||||
'profile_id': 88,
|
||||
'profile_checksum': 'sha256:deadbeef',
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
assert ok is False
|
||||
assert reason == 'xfa_profile_checksum_mismatch'
|
||||
|
||||
|
||||
def test_stp_precheck_blocks_when_unified_gate_failed(monkeypatch):
|
||||
"""关键断言:CQ 快照 xfa_unified_profile_snapshot=false 时 STP 阻断。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.extraction_emergency_stop_enabled',
|
||||
lambda: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.xfa_shadow_mode_enabled',
|
||||
lambda: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service._revalidate_published_xfa_profile',
|
||||
lambda **kwargs: (True, None),
|
||||
)
|
||||
allowed, reason = _xfa_stp_precheck(
|
||||
validation={
|
||||
'can_auto_create': True,
|
||||
'qualification': {
|
||||
'gates': {
|
||||
'xfa_auto_create_policy': True,
|
||||
'xfa_profile_blind_approved': True,
|
||||
'xfa_pilot_allowlist': True,
|
||||
'xfa_evidence_integrity': True,
|
||||
'xfa_unified_profile_snapshot': False,
|
||||
},
|
||||
'blocking_reason_codes': ['xfa_visual_coverage_insufficient'],
|
||||
},
|
||||
},
|
||||
)
|
||||
assert allowed is False
|
||||
assert reason == 'xfa_visual_coverage_insufficient'
|
||||
@@ -0,0 +1,220 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_binding_contract.py
|
||||
|
||||
用途:验收统一字段 binding 契约(value_binding + visual_binding + split_rule_ref)。
|
||||
依赖:xfa_contract、pytest。
|
||||
逻辑:覆盖合法绑定、非法值类型、视觉框面积、发布可发布性、checksum 稳定性;
|
||||
断言 XFA Profile 不得混入 coordinate 表区键,但允许 visual 归一化框。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
OrderXfaDatasetProfile,
|
||||
XfaLineMapping,
|
||||
XfaNormalizedBBox,
|
||||
XfaSourceContract,
|
||||
XfaUnifiedFieldBinding,
|
||||
XfaValueBinding,
|
||||
XfaVisualBinding,
|
||||
canonical_unified_bindings_payload,
|
||||
is_formal_binding_publishable,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_signature import (
|
||||
compute_definition_business_checksum,
|
||||
compute_unified_bindings_checksum,
|
||||
)
|
||||
|
||||
|
||||
def _source() -> XfaSourceContract:
|
||||
"""构造最小合法 source_contract。"""
|
||||
return XfaSourceContract(
|
||||
template_packet_checksum='sha256:' + ('a' * 64),
|
||||
dataset_structure_fingerprint='sha256:' + ('b' * 64),
|
||||
dataset_root_path='/data',
|
||||
authoritative_line_collection_path='/data/ITEMS/DATA',
|
||||
mirror_collection_paths=['/data/ITEMS1/DATA'],
|
||||
)
|
||||
|
||||
|
||||
def _confirmed_binding(**overrides: object) -> dict[str, object]:
|
||||
"""构造已确认的统一绑定字典。"""
|
||||
payload: dict[str, object] = {
|
||||
'binding_id': 'bind-0001-aaaa-bbbb',
|
||||
'field_id': 'fld-part',
|
||||
'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-matnr',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5},
|
||||
'source': 'acroform_widget',
|
||||
'status': 'confirmed',
|
||||
'confidence': 0.98,
|
||||
},
|
||||
}
|
||||
payload.update(overrides)
|
||||
return payload
|
||||
|
||||
|
||||
def test_unified_binding_accepts_visual_bbox_without_coordinate_keys() -> None:
|
||||
"""允许 visual_binding;拒绝 table_regions 等 coordinate 键。"""
|
||||
profile = OrderXfaDatasetProfile(
|
||||
source_contract=_source(),
|
||||
line_mapping=XfaLineMapping(row_path='/data/ITEMS/DATA', fields=[]),
|
||||
bindings=[XfaUnifiedFieldBinding.model_validate(_confirmed_binding())],
|
||||
)
|
||||
assert len(profile.bindings) == 1
|
||||
assert profile.bindings[0].visual_binding.status == 'confirmed'
|
||||
|
||||
with pytest.raises(ValidationError, match='coordinate keys'):
|
||||
OrderXfaDatasetProfile.model_validate(
|
||||
{
|
||||
'source_contract': _source().model_dump(mode='json'),
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'table_regions': [],
|
||||
'bindings': [_confirmed_binding()],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def test_xfa_profile_rejects_dual_binding_source() -> None:
|
||||
"""bindings 与 legacy mappings 不得共存。"""
|
||||
with pytest.raises(ValidationError, match='xfa_dual_binding_source'):
|
||||
OrderXfaDatasetProfile(
|
||||
source_contract=_source(),
|
||||
line_mapping=XfaLineMapping(
|
||||
row_path='/data/ITEMS/DATA',
|
||||
fields=[{
|
||||
'mapping_id': 'map-matnr',
|
||||
'field_id': 'fld-part',
|
||||
'field_code': 'part_number',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
'path_id': 'path-matnr',
|
||||
'value_type': 'string',
|
||||
}],
|
||||
),
|
||||
bindings=[XfaUnifiedFieldBinding.model_validate(_confirmed_binding())],
|
||||
)
|
||||
|
||||
|
||||
def test_xfa_profile_rejects_legacy_only_without_bindings() -> None:
|
||||
"""仅 legacy mappings 无 bindings 时正式契约 fail-closed。"""
|
||||
with pytest.raises(ValidationError, match='xfa_legacy_mappings_forbidden'):
|
||||
OrderXfaDatasetProfile(
|
||||
source_contract=_source(),
|
||||
line_mapping=XfaLineMapping(
|
||||
row_path='/data/ITEMS/DATA',
|
||||
fields=[{
|
||||
'mapping_id': 'map-matnr',
|
||||
'field_id': 'fld-part',
|
||||
'field_code': 'part_number',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
'path_id': 'path-matnr',
|
||||
'value_type': 'string',
|
||||
}],
|
||||
),
|
||||
bindings=[],
|
||||
)
|
||||
|
||||
|
||||
def test_xfa_profile_rejects_non_dataset_value_binding() -> None:
|
||||
"""XFA Profile 内正式绑定不得使用 pdf_coordinate。"""
|
||||
bad = _confirmed_binding(
|
||||
value_binding={'type': 'pdf_coordinate', 'region_id': 'region-1'},
|
||||
)
|
||||
with pytest.raises(ValidationError, match='xfa_dataset'):
|
||||
OrderXfaDatasetProfile(
|
||||
source_contract=_source(),
|
||||
line_mapping=XfaLineMapping(row_path='/data/ITEMS/DATA', fields=[]),
|
||||
bindings=[XfaUnifiedFieldBinding.model_validate(bad)],
|
||||
)
|
||||
|
||||
|
||||
def test_visual_bbox_requires_positive_area() -> None:
|
||||
"""归一化框必须正面积。"""
|
||||
with pytest.raises(ValidationError, match='positive area'):
|
||||
XfaNormalizedBBox(x0=0.5, y0=0.5, x1=0.4, y1=0.6)
|
||||
|
||||
|
||||
def test_publishable_requires_confirmed_visual() -> None:
|
||||
"""正式字段发布门禁:视觉状态须 confirmed。"""
|
||||
confirmed = XfaUnifiedFieldBinding.model_validate(_confirmed_binding())
|
||||
assert is_formal_binding_publishable(confirmed) is True
|
||||
|
||||
suggested = XfaUnifiedFieldBinding.model_validate(
|
||||
_confirmed_binding(
|
||||
visual_binding={
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.5,
|
||||
},
|
||||
),
|
||||
)
|
||||
assert is_formal_binding_publishable(suggested) is False
|
||||
|
||||
|
||||
def test_bindings_checksum_covers_visual_and_split_ref() -> None:
|
||||
"""checksum 随 visual 或 split_rule_ref 变化而变化。"""
|
||||
base = [_confirmed_binding()]
|
||||
with_split = [
|
||||
_confirmed_binding(
|
||||
split_rule_ref={'rule_set_id': 'ruleset-0001-aaaa', 'segment_id': 'seg-0001-bbbb'},
|
||||
),
|
||||
]
|
||||
moved = [
|
||||
_confirmed_binding(
|
||||
visual_binding={
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.11, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5},
|
||||
'source': 'manual_draw',
|
||||
'status': 'confirmed',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
),
|
||||
]
|
||||
c1 = compute_unified_bindings_checksum(base)
|
||||
c2 = compute_unified_bindings_checksum(with_split)
|
||||
c3 = compute_unified_bindings_checksum(moved)
|
||||
assert c1 != c2
|
||||
assert c1 != c3
|
||||
assert c1.startswith('sha256:')
|
||||
|
||||
# canonical 排序稳定
|
||||
assert canonical_unified_bindings_payload(base)[0]['binding_id'] == 'bind-0001-aaaa-bbbb'
|
||||
|
||||
|
||||
def test_definition_business_checksum_includes_split_rules() -> None:
|
||||
"""definition 业务 checksum 覆盖 split_rules。"""
|
||||
definition_a = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'bindings': [_confirmed_binding()],
|
||||
'split_rules': [],
|
||||
}
|
||||
definition_b = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'bindings': [_confirmed_binding()],
|
||||
'split_rules': [{'rule_set_id': 'x', 'rules': []}],
|
||||
}
|
||||
assert compute_definition_business_checksum(definition_a) != compute_definition_business_checksum(
|
||||
definition_b,
|
||||
)
|
||||
|
||||
|
||||
def test_value_binding_type_constraints() -> None:
|
||||
"""xfa_dataset 必须 path;坐标类型必须 region_id。"""
|
||||
with pytest.raises(ValidationError):
|
||||
XfaValueBinding(type='xfa_dataset', path_id=None, data_path=None)
|
||||
with pytest.raises(ValidationError):
|
||||
XfaValueBinding(type='pdf_coordinate')
|
||||
ok = XfaValueBinding(type='pdf_coordinate', region_id='r1')
|
||||
assert ok.region_id == 'r1'
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_blind_test.py
|
||||
|
||||
用途:阶段 6 独立盲测指标——视觉/证据率 < 1.0 时失败;哨兵 metrics 可序列化。
|
||||
依赖:document_profile_quality_service serialize / metrics 前缀。
|
||||
逻辑:纯单元验证 metrics 哨兵编解码与阈值语义。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_profile_quality_service import (
|
||||
_XFA_BLIND_METRICS_PREFIX,
|
||||
serialize_suite,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_serialize_suite_strips_metrics_sentinel():
|
||||
"""关键断言:failure_codes 中的指标哨兵剥离为 latest_run.metrics。"""
|
||||
metrics = {
|
||||
'visual_coverage_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'key_field_accuracy_rate': 1.0,
|
||||
}
|
||||
suite = SimpleNamespace(
|
||||
id=1,
|
||||
profile_id=9,
|
||||
profile_checksum='abc',
|
||||
status='draft',
|
||||
samples=[],
|
||||
approved_at=None,
|
||||
runs=[
|
||||
SimpleNamespace(
|
||||
status='passed',
|
||||
sample_count=1,
|
||||
passed_sample_count=1,
|
||||
failure_codes_json=[
|
||||
f"{_XFA_BLIND_METRICS_PREFIX}{json.dumps(metrics, sort_keys=True, separators=(',', ':'))}",
|
||||
'sample:1:order_field:po:mismatch',
|
||||
],
|
||||
),
|
||||
],
|
||||
)
|
||||
payload = serialize_suite(suite)
|
||||
assert payload['latest_run']['metrics'] == metrics
|
||||
assert payload['latest_run']['failure_codes'] == ['sample:1:order_field:po:mismatch']
|
||||
|
||||
|
||||
def test_blind_metrics_threshold_requires_full_coverage():
|
||||
"""关键断言:任一统一指标 < 1.0 即视为盲测不合格(契约语义)。"""
|
||||
rates = {
|
||||
'visual_coverage_rate': 0.99,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
}
|
||||
assert any(float(v) < 1.0 for v in rates.values())
|
||||
@@ -0,0 +1,280 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_mapping_api.py
|
||||
|
||||
用途:验收 XFA 统一映射 suggest API(视觉 + 拆分规则)与保存 bindings/split_rules。
|
||||
依赖:Flask test client、phase2 XFA 夹具、suggestion_service、profile_service。
|
||||
逻辑:统一 suggest 返回 suggested/draft 状态;保存后 definition 含 bindings 与 split_rules。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.extensions import db
|
||||
from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfileDraftRevision, User
|
||||
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice import order_document_profile_suggestion_service as suggestion_service
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import new_segment_id
|
||||
from tests.conftest import parse_api_data
|
||||
from tests.test_shipping_xfa_formal_multiline_extraction import (
|
||||
_confirmed_matnr_rule_set,
|
||||
_multiline_datasets_xml,
|
||||
_schema_definition,
|
||||
)
|
||||
from tests.test_shipping_xfa_helpers import build_synthetic_xfa_hybrid_pdf
|
||||
from tests.test_shipping_xfa_profile_phase2 import _patch_xfa_io, _seed_xfa_sample
|
||||
|
||||
|
||||
def _schema_version_id(app) -> int:
|
||||
"""发布含拆分目标字段的 Schema,返回 version id。"""
|
||||
from datetime import datetime
|
||||
|
||||
from app.models import ShippingOrderSchema, ShippingOrderSchemaVersion
|
||||
|
||||
with app.app_context():
|
||||
schema = ShippingOrderSchema(schema_code='XFA_UNIFIED', display_name='XFA Unified')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id,
|
||||
version=1,
|
||||
status='published',
|
||||
checksum='d' * 64,
|
||||
published_at=datetime.utcnow(),
|
||||
definition_json=_schema_definition(),
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.commit()
|
||||
return int(version.id)
|
||||
|
||||
|
||||
def _admin_headers(app, username: str = 'xfa-unified-admin') -> dict[str, str]:
|
||||
"""生成 admin JWT headers。"""
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if not user:
|
||||
user = User(username=username, email=f'{username}@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {'Authorization': f'Bearer {token}'}
|
||||
|
||||
|
||||
def _multiline_sample(app, monkeypatch, *, user: User):
|
||||
"""写入多行 MATNR XFA 样本。"""
|
||||
from datetime import datetime
|
||||
from hashlib import sha256
|
||||
|
||||
from app.models import FileAsset, ShippingOrderDocument, ShippingOrderIntake
|
||||
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
from app.services.shipping_notice.document_layout.xfa_analysis import analyze_xfa_pdf, persist_xfa_structure_analysis
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import _path_id_for
|
||||
|
||||
pdf_bytes = build_synthetic_xfa_hybrid_pdf(_multiline_datasets_xml())
|
||||
content_hash = sha256(pdf_bytes).hexdigest()
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-ML-{content_hash[:10]}',
|
||||
owner_user_id=user.id,
|
||||
original_filename='xfa-multiline.pdf',
|
||||
storage_provider='minio',
|
||||
storage_bucket='test',
|
||||
storage_key=f'xfa/{content_hash}.pdf',
|
||||
content_hash=content_hash,
|
||||
file_size=len(pdf_bytes),
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='referenced',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no=f'SNI-ML-{content_hash[:8].upper()}',
|
||||
asset_id=asset.id,
|
||||
user_id=user.id,
|
||||
purpose='order_document_profile_sample',
|
||||
parse_status='parsed',
|
||||
parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=asset.id,
|
||||
document_type='attachment',
|
||||
attachment_key=f'xfa/{content_hash}.pdf',
|
||||
filename='xfa-multiline.pdf',
|
||||
content_hash=content_hash,
|
||||
classification='supporting',
|
||||
parse_status='parsed',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
outcome = analyze_xfa_pdf(pdf_bytes)
|
||||
layout = dict(outcome.snapshot)
|
||||
layout['status'] = 'ready'
|
||||
layout['provider'] = 'xfa'
|
||||
layout.setdefault('xfa_capability', {})['structure_analysis_ready'] = True
|
||||
layout_version = record_inline_layout_snapshot(document, layout)
|
||||
persist_xfa_structure_analysis(
|
||||
document_id=document.id,
|
||||
layout_version_id=layout_version.id,
|
||||
source_content_hash=content_hash,
|
||||
outcome=outcome,
|
||||
)
|
||||
db.session.commit()
|
||||
paths = {
|
||||
'ITEMS_DATA': _path_id_for('/data/ITEMS/DATA'),
|
||||
'MATNR': _path_id_for('/data/ITEMS/DATA/MATNR'),
|
||||
'MENGE': _path_id_for('/data/ITEMS/DATA/MENGE'),
|
||||
}
|
||||
monkeypatch.setattr('app.services.file_assets.service.read_asset_bytes', lambda _a: pdf_bytes)
|
||||
return int(document.id), paths
|
||||
|
||||
|
||||
def test_unified_suggest_api_returns_visual_and_split(app, monkeypatch, _patch_xfa_io):
|
||||
"""统一 suggest API 须返回视觉候选与 draft 拆分建议。"""
|
||||
with app.app_context():
|
||||
user = User(username='unified-suggest', email='unified-suggest@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
schema_id = _schema_version_id(app)
|
||||
document_id, paths = _multiline_sample(app, monkeypatch, user=user)
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'Unified Suggest',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'unified-tab',
|
||||
'operation_id': 'unified-wizard',
|
||||
}, actor_id=user.id)
|
||||
profile_id = created['id']
|
||||
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa/unified-mapping/suggest',
|
||||
json={
|
||||
'document_id': document_id,
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.5, 'y1': 0.55},
|
||||
'path_id': paths['MATNR'],
|
||||
},
|
||||
headers=_admin_headers(app, 'unified-suggest'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = parse_api_data(response.get_json())
|
||||
assert data['suggestion_status'] == 'suggested'
|
||||
assert data['visual_suggestion']['diagnostics']['auto_confirm_blocked'] is True
|
||||
rule_set = data['split_rule_suggestion']['rule_set']
|
||||
assert rule_set['status'] == 'draft'
|
||||
assert rule_set['status'] != 'confirmed'
|
||||
assert rule_set['requires_confirmation'] is True
|
||||
matchers = [rule['matcher']['type'] for rule in rule_set['rules']]
|
||||
assert 'position' in matchers
|
||||
assert 'prefix' in matchers
|
||||
|
||||
|
||||
def test_save_bindings_and_split_rules_creates_revision(app, monkeypatch, _patch_xfa_io):
|
||||
"""保存 bindings + split_rules 须规范化写入 definition 并产生 Revision。"""
|
||||
with app.app_context():
|
||||
user = User(username='unified-save', email='unified-save@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
schema_id = _schema_version_id(app)
|
||||
document_id, paths = _multiline_sample(app, monkeypatch, user=user)
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'Unified Save',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'save-tab',
|
||||
'operation_id': 'save-wizard',
|
||||
}, actor_id=user.id)
|
||||
profile_id = created['id']
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
definition = dict(profile.definition_json)
|
||||
definition['header_mappings'] = []
|
||||
definition['line_mapping'] = {
|
||||
'row_path': definition['source_contract']['authoritative_line_collection_path'],
|
||||
'fields': [],
|
||||
}
|
||||
rule_set = _confirmed_matnr_rule_set()
|
||||
rule_set['source_path_id'] = paths['MATNR']
|
||||
rule_set['status'] = 'draft'
|
||||
rule_set['requires_confirmation'] = True
|
||||
segment_id = new_segment_id()
|
||||
definition['split_rules'] = [rule_set]
|
||||
definition['bindings'] = [{
|
||||
'binding_id': 'bind-save-test-001',
|
||||
'field_id': 'f-qty',
|
||||
'field_code': 'quantity',
|
||||
'scope': 'line',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': paths['MENGE'],
|
||||
'data_path': '/data/ITEMS/DATA/MENGE',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.5, 'y1': 0.55},
|
||||
'source': 'manual_draw',
|
||||
'status': 'confirmed',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
}]
|
||||
saved = profile_service.save_draft(
|
||||
{
|
||||
'profile_code': profile.profile_code,
|
||||
'display_name': profile.display_name,
|
||||
'schema_version_id': schema_id,
|
||||
'definition': definition,
|
||||
'expected_lock_version': profile.lock_version,
|
||||
'sample_document_id': document_id,
|
||||
},
|
||||
actor_id=user.id,
|
||||
profile_id=profile_id,
|
||||
browser_session_id='save-tab',
|
||||
lease_token=created['edit_lease']['lease_token'],
|
||||
operation_id='save-bindings-op-1',
|
||||
enforce_lease=True,
|
||||
)
|
||||
assert saved['definition']['bindings'][0]['field_code'] == 'quantity'
|
||||
assert saved['definition']['split_rules'][0]['status'] == 'draft'
|
||||
assert ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=profile_id, operation_id='save-bindings-op-1',
|
||||
).count() == 1
|
||||
revision = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=profile_id, operation_id='save-bindings-op-1',
|
||||
).one()
|
||||
snap = revision.definition_snapshot_json or {}
|
||||
assert 'bindings' in snap
|
||||
assert 'split_rules' in snap
|
||||
|
||||
|
||||
def test_suggest_split_rules_service_status_draft(app, monkeypatch, _patch_xfa_io):
|
||||
"""拆分建议 service 层 status 必须为 draft/suggested。"""
|
||||
with app.app_context():
|
||||
user = User(username='split-svc', email='split-svc@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
schema_id = _schema_version_id(app)
|
||||
document_id, paths = _multiline_sample(app, monkeypatch, user=user)
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'Split Svc',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'svc-tab',
|
||||
'operation_id': 'svc-wizard',
|
||||
}, actor_id=user.id)
|
||||
payload = suggestion_service.suggest_xfa_split_rules(
|
||||
created['id'],
|
||||
document_id=document_id,
|
||||
path_id=paths['MATNR'],
|
||||
actor_id=user.id,
|
||||
write_audit=False,
|
||||
)
|
||||
assert payload['suggestion_status'] == 'suggested'
|
||||
assert payload['rule_set']['status'] == 'draft'
|
||||
assert 'confirmed' != payload['rule_set']['status']
|
||||
@@ -0,0 +1,180 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_migration.py
|
||||
|
||||
用途:验收统一 binding 一次性迁移(坐标 + XFA Dry Run;路径保留 100%;正式字段差异 0)。
|
||||
依赖:order_profile_unified_migration、pytest。
|
||||
逻辑:使用合成 definition,不接真实 PDF;断言报告指标与 convert 稳定性。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.order_profile_unified_migration import (
|
||||
_clear_xfa_legacy_mappings,
|
||||
build_migration_report,
|
||||
convert_coordinate_definition_to_unified_bindings,
|
||||
convert_xfa_definition_to_unified_bindings,
|
||||
)
|
||||
|
||||
|
||||
def _coordinate_definition() -> dict:
|
||||
"""构造最小合法坐标 definition(含 order_field_layouts)。"""
|
||||
return {
|
||||
'template_mode': 'coordinate',
|
||||
'document_match': {
|
||||
'required_anchors': [],
|
||||
'optional_anchors': [],
|
||||
'negative_anchors': [],
|
||||
},
|
||||
'table_regions': [{
|
||||
'region_id': 'table_main',
|
||||
'page_scope': 'first_page',
|
||||
'region': {'x0': 0.1, 'y0': 0.2, 'x1': 0.9, 'y1': 0.8},
|
||||
'header_layouts': [],
|
||||
'line_layouts': [{
|
||||
'layout_id': 'line_1',
|
||||
'field_regions': [{
|
||||
'region_id': 'line_part',
|
||||
'field_id': 'fld-part',
|
||||
'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'region': {'x0': 0.2, 'y0': 0.3, 'x1': 0.4, 'y1': 0.35},
|
||||
'allowed_sources': ['pdf_text'],
|
||||
'extractor_key': 'direct',
|
||||
}],
|
||||
}],
|
||||
'continuation_rule': {'required_anchor_ids': []},
|
||||
}],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': 'hdr_po',
|
||||
'field_id': 'fld-po',
|
||||
'field_code': 'customer_po_number',
|
||||
'scope': 'header',
|
||||
'page_scope': 'first_page',
|
||||
'absolute_value_region': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.14},
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}],
|
||||
'draft_unbound_order_field_layouts': [],
|
||||
}
|
||||
|
||||
|
||||
def _xfa_definition() -> dict:
|
||||
"""构造最小合法 XFA definition(header + line mapping)。"""
|
||||
return {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
'mirror_collection_paths': ['/data/ITEMS1/DATA'],
|
||||
},
|
||||
'header_mappings': [{
|
||||
'mapping_id': 'map-po',
|
||||
'field_id': 'fld-po',
|
||||
'field_code': 'customer_po_number',
|
||||
'data_path': '/data/HEADER/EBELN',
|
||||
'path_id': 'path-ebeln',
|
||||
'value_type': 'string',
|
||||
}],
|
||||
'line_mapping': {
|
||||
'row_path': '/data/ITEMS/DATA',
|
||||
'fields': [{
|
||||
'mapping_id': 'map-matnr',
|
||||
'field_id': 'fld-part',
|
||||
'field_code': 'part_number',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
'path_id': 'path-matnr',
|
||||
'value_type': 'string',
|
||||
}],
|
||||
},
|
||||
'bindings': [],
|
||||
'split_rules': [],
|
||||
}
|
||||
|
||||
|
||||
def test_coordinate_dry_run_path_preserve_and_zero_field_diff():
|
||||
"""坐标迁移:正式字段差异 0;bindings 覆盖 order + line 字段。"""
|
||||
before = _coordinate_definition()
|
||||
after, stats = convert_coordinate_definition_to_unified_bindings(before)
|
||||
report = build_migration_report(before=before, after=after, stats=stats)
|
||||
assert report['field_diff_count'] == 0
|
||||
assert report['path_preserve_rate'] == 100.0
|
||||
assert report['binding_count'] >= 2
|
||||
assert report['pending_visual_count'] == 0
|
||||
assert all(
|
||||
item['value_binding']['type'] in {'pdf_coordinate', 'ocr_coordinate'}
|
||||
for item in after['bindings']
|
||||
)
|
||||
assert all(item['visual_binding']['status'] == 'confirmed' for item in after['bindings'])
|
||||
# 原 coordinate 键保留
|
||||
assert after['order_field_layouts']
|
||||
assert after['table_regions']
|
||||
|
||||
|
||||
def test_xfa_dry_run_path_preserve_100_and_zero_field_diff():
|
||||
"""XFA 迁移:path_id 保留率 100%;正式字段差异 0;视觉框为 suggested。"""
|
||||
before = _xfa_definition()
|
||||
after, stats = convert_xfa_definition_to_unified_bindings(before, widgets=[])
|
||||
report = build_migration_report(before=before, after=after, stats=stats)
|
||||
assert report['path_preserve_rate'] == 100.0
|
||||
assert report['field_diff_count'] == 0
|
||||
assert report['binding_count'] == 2
|
||||
assert report['pending_visual_count'] == 2
|
||||
assert report['legacy_will_be_cleared'] is True
|
||||
assert report['legacy_mapping_counts'] == {'header': 1, 'line': 1}
|
||||
assert after['header_mappings'] == before['header_mappings']
|
||||
assert after['line_mapping'] == before['line_mapping']
|
||||
assert after['source_contract'] == before['source_contract']
|
||||
assert all(item['value_binding']['type'] == 'xfa_dataset' for item in after['bindings'])
|
||||
assert {item['value_binding']['path_id'] for item in after['bindings']} == {
|
||||
'path-ebeln', 'path-matnr',
|
||||
}
|
||||
assert all(item['visual_binding']['status'] == 'suggested' for item in after['bindings'])
|
||||
|
||||
|
||||
def test_xfa_execute_clears_legacy_mappings():
|
||||
"""Execute 后须清除 header_mappings / line_mapping.fields,仅保留 bindings。"""
|
||||
before = _xfa_definition()
|
||||
after, _stats = convert_xfa_definition_to_unified_bindings(before, widgets=[])
|
||||
cleared = _clear_xfa_legacy_mappings(after)
|
||||
assert cleared['bindings']
|
||||
assert cleared['header_mappings'] == []
|
||||
assert cleared['line_mapping']['fields'] == []
|
||||
assert cleared['line_mapping']['row_path'] == before['source_contract']['authoritative_line_collection_path']
|
||||
|
||||
|
||||
def test_xfa_migrated_pending_visual_blocks_publish_gate():
|
||||
"""关键断言:迁移 Execute 清除 legacy 后 suggested 视觉框仍阻断发布。"""
|
||||
from app.services.shipping_notice.order_document_profile_publish_check_service import (
|
||||
_blocking_xfa_visual_bindings,
|
||||
)
|
||||
|
||||
before = _xfa_definition()
|
||||
after, _stats = convert_xfa_definition_to_unified_bindings(before, widgets=[])
|
||||
migrated = _clear_xfa_legacy_mappings(after)
|
||||
schema_field_ids = {'fld-po', 'fld-part'}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=migrated,
|
||||
schema_field_ids=schema_field_ids,
|
||||
)
|
||||
assert any(item.get('key') == 'xfa_visual_binding_incomplete' for item in blocking)
|
||||
|
||||
|
||||
def test_scan_unified_migration_profiles_synthetic():
|
||||
"""scan 返回逐族状态;无 DB 时用 summarize 逻辑(纯函数部分)。"""
|
||||
from app.services.shipping_notice.order_profile_unified_migration import (
|
||||
scan_unified_migration_profiles,
|
||||
summarize_unified_migration_status,
|
||||
)
|
||||
|
||||
coord = summarize_unified_migration_status(_coordinate_definition(), template_mode='coordinate')
|
||||
assert coord['unified_binding_status'] == 'needs_migration'
|
||||
assert coord['field_diff_count'] == 0
|
||||
|
||||
xfa = summarize_unified_migration_status(_xfa_definition(), template_mode='xfa_dataset')
|
||||
assert xfa['unified_binding_status'] == 'needs_migration'
|
||||
assert xfa['pending_visual_count'] == 2
|
||||
assert xfa['path_preserve_rate'] == 100.0
|
||||
|
||||
# scan 需 DB;此处只验证函数可导入且 summarize 与 convert 一致
|
||||
assert callable(scan_unified_migration_profiles)
|
||||
@@ -0,0 +1,172 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_visual_binding.py
|
||||
|
||||
用途:验收 XFA 视觉绑定候选评分、歧义诊断与审计 before/after。
|
||||
依赖:xfa_visual_binding、xfa_acroform、order_document_profile_visual_binding_service。
|
||||
逻辑:纯函数 + mock Widget/datasets;不接真实 PDFium/google-re2。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_acroform import XfaAcroformWidget
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import XfaDatasetAnalysis
|
||||
from app.services.shipping_notice.document_layout.xfa_visual_binding import (
|
||||
suggest_visual_binding_candidates,
|
||||
visual_binding_audit_snapshot,
|
||||
)
|
||||
from app.services.shipping_notice.order_document_profile_audit_service import (
|
||||
XFA_VISUAL_BINDING_AUDIT_EVENTS,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import XFA_AUDIT_EVENT_TYPES
|
||||
from app.services.shipping_notice.progress_audit_contract import XFA_PROGRESS_EVENT_CODES
|
||||
|
||||
|
||||
def _dataset_analysis() -> XfaDatasetAnalysis:
|
||||
"""构造最小 datasets 分析(双 MATNR 歧义路径)。"""
|
||||
return XfaDatasetAnalysis(
|
||||
nodes=[],
|
||||
dataset_root_path='/data',
|
||||
leaf_values_by_path={
|
||||
'/data/HEADER/EBELN': '4510039227',
|
||||
'/data/ITEMS/DATA/MATNR': 'TEMP-S000218922',
|
||||
'/data/ITEMS1/DATA/MATNR': 'TEMP-S000218922',
|
||||
},
|
||||
header_candidates=['/data/HEADER'],
|
||||
collection_candidates=[],
|
||||
known_path_ids=set(),
|
||||
stats={},
|
||||
)
|
||||
|
||||
|
||||
def _widget(
|
||||
*,
|
||||
short_name: str,
|
||||
value: str,
|
||||
page_no: int = 1,
|
||||
bbox: dict[str, float] | None = None,
|
||||
) -> XfaAcroformWidget:
|
||||
"""合成单个 Widget。"""
|
||||
region = bbox or {'x0': 0.1, 'y0': 0.4, 'x1': 0.5, 'y1': 0.55}
|
||||
qname = f'form[0].{short_name}[0]'
|
||||
return XfaAcroformWidget(
|
||||
widget_id=f'wgt-{short_name}',
|
||||
qualified_name=qname,
|
||||
short_name=short_name,
|
||||
page_no=page_no,
|
||||
normalized_bbox=region,
|
||||
value=value,
|
||||
value_masked=value[:4] + '***' if value else '',
|
||||
)
|
||||
|
||||
|
||||
def test_visual_binding_candidates_never_auto_confirm():
|
||||
"""所有候选 status 必须为 suggested,diagnostics 阻断自动确认。"""
|
||||
widgets = [
|
||||
_widget(short_name='EBELN', value='4510039227', bbox={'x0': 0.1, 'y0': 0.1, 'x1': 0.4, 'y1': 0.2}),
|
||||
_widget(short_name='MATNR', value='TEMP-S000218922', bbox={'x0': 0.1, 'y0': 0.4, 'x1': 0.5, 'y1': 0.55}),
|
||||
]
|
||||
result = suggest_visual_binding_candidates(
|
||||
page_no=1,
|
||||
normalized_bbox={'x0': 0.1, 'y0': 0.38, 'x1': 0.52, 'y1': 0.58},
|
||||
dataset_analysis=_dataset_analysis(),
|
||||
widgets=widgets,
|
||||
)
|
||||
assert result['candidates']
|
||||
assert all(item['status'] == 'suggested' for item in result['candidates'])
|
||||
assert result['diagnostics']['auto_confirm_blocked'] is True
|
||||
assert 'confirmed' not in str(result).lower() or all(
|
||||
item['status'] != 'confirmed' for item in result['candidates']
|
||||
)
|
||||
|
||||
|
||||
def test_ambiguous_path_candidates_flagged():
|
||||
"""同短名多 datasets 路径时必须标记 ambiguous。"""
|
||||
widgets = [_widget(short_name='MATNR', value='TEMP-S000218922')]
|
||||
result = suggest_visual_binding_candidates(
|
||||
page_no=1,
|
||||
normalized_bbox={'x0': 0.1, 'y0': 0.4, 'x1': 0.5, 'y1': 0.55},
|
||||
dataset_analysis=_dataset_analysis(),
|
||||
widgets=widgets,
|
||||
)
|
||||
top = result['candidates'][0]
|
||||
assert len(top['path_candidates']) >= 2
|
||||
assert result['diagnostics']['ambiguous'] is True
|
||||
|
||||
|
||||
def test_visual_binding_audit_events_registered():
|
||||
"""视觉绑定审计事件须注册于契约白名单。"""
|
||||
for event in XFA_VISUAL_BINDING_AUDIT_EVENTS:
|
||||
assert event in XFA_AUDIT_EVENT_TYPES, event
|
||||
assert event in XFA_PROGRESS_EVENT_CODES, event
|
||||
|
||||
|
||||
def test_confirm_visual_binding_writes_before_after_audit(app):
|
||||
"""确认视觉绑定必须写入 before/after 审计摘要。"""
|
||||
from app.services.shipping_notice import order_document_profile_visual_binding_service as svc
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
'mirror_collection_paths': [],
|
||||
},
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [{
|
||||
'binding_id': 'bind-test-001',
|
||||
'field_id': 'f-po',
|
||||
'field_code': 'customer_po_no',
|
||||
'scope': 'header',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-ebeln',
|
||||
'data_path': '/data/HEADER/EBELN',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.2},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.9,
|
||||
},
|
||||
}],
|
||||
}
|
||||
before_snap = visual_binding_audit_snapshot(definition['bindings'][0])
|
||||
assert before_snap['status'] == 'suggested'
|
||||
|
||||
with patch.object(lease_service, 'require_active_lease', return_value=object()):
|
||||
with patch.object(svc, '_profile') as profile_mock:
|
||||
profile = type('P', (), {'id': 1, 'status': 'draft', 'template_mode': 'xfa_dataset', 'definition_json': definition})()
|
||||
profile_mock.return_value = profile
|
||||
with patch.object(svc.db.session, 'flush', lambda: None):
|
||||
with patch.object(svc.db.session, 'commit', lambda: None):
|
||||
with patch.object(svc, 'record_visual_binding_audit') as audit_mock:
|
||||
svc.confirm_xfa_visual_binding(
|
||||
1,
|
||||
'bind-test-001',
|
||||
visual_binding={
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.11, 'y0': 0.11, 'x1': 0.31, 'y1': 0.21},
|
||||
'source': 'manual_draw',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
path_id=None,
|
||||
actor_id=1,
|
||||
browser_session_id='tab',
|
||||
lease_token='lease',
|
||||
)
|
||||
audit_mock.assert_called_once()
|
||||
kwargs = audit_mock.call_args.kwargs
|
||||
assert kwargs['event_type'] == 'xfa_visual_binding_confirmed'
|
||||
assert kwargs['before']['status'] == 'suggested'
|
||||
assert kwargs['after']['status'] == 'confirmed'
|
||||
assert kwargs['before']['normalized_bbox']['x0'] == 0.1
|
||||
assert kwargs['after']['normalized_bbox']['x0'] == 0.11
|
||||
@@ -0,0 +1,142 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_visual_binding_permissions.py
|
||||
|
||||
用途:验收 XFA 视觉绑定 API 的管理员鉴权与租约门禁。
|
||||
依赖:Flask test client、JWT、XFA phase2 样本夹具。
|
||||
逻辑:非 admin 403;suggest 可读;confirm/reject 无租约 409。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.extensions import db
|
||||
from app.models import User
|
||||
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_visual_binding_service as vb_service
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
from tests.test_shipping_xfa_profile_phase2 import _patch_xfa_io, _schema_with_required, _seed_xfa_sample
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_headers_factory(app):
|
||||
"""生成 admin Bearer JWT。"""
|
||||
|
||||
def _build(username: str):
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if not user:
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
role='admin',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {'Authorization': f'Bearer {token}'}
|
||||
|
||||
return _build
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def user_headers_factory(app):
|
||||
"""生成普通用户 Bearer JWT。"""
|
||||
|
||||
def _build(username: str):
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if not user:
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {'Authorization': f'Bearer {token}'}
|
||||
|
||||
return _build
|
||||
|
||||
|
||||
def _xfa_draft_profile(app, monkeypatch):
|
||||
"""创建含 binding 占位的最小 XFA 草稿 Profile。"""
|
||||
with app.app_context():
|
||||
admin = User(username='xfa-vb-admin', email='xfa-vb-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin)
|
||||
db.session.commit()
|
||||
schema = _schema_with_required()
|
||||
document, paths, _pdf = _seed_xfa_sample(user=admin)
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'XFA Visual Binding',
|
||||
'schema_version_id': schema.id,
|
||||
'document_id': document.id,
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'mirror_collection_path_ids': [paths['ITEMS1_DATA']],
|
||||
'browser_session_id': 'vb-tab',
|
||||
'operation_id': 'vb-wizard-op',
|
||||
}, actor_id=admin.id)
|
||||
profile_id = int(created['id'])
|
||||
binding = vb_service.ensure_binding_stub(
|
||||
profile_id,
|
||||
field_id='f-po',
|
||||
field_code='customer_po_no',
|
||||
scope='header',
|
||||
path_id=paths['EBELN'],
|
||||
data_path='/data/HEADER/EBELN',
|
||||
actor_id=admin.id,
|
||||
browser_session_id='vb-tab',
|
||||
lease_token=created['edit_lease']['lease_token'],
|
||||
)
|
||||
return profile_id, document.id, binding['binding_id'], created['edit_lease']['lease_token']
|
||||
|
||||
|
||||
def test_visual_binding_suggest_requires_admin(app, monkeypatch, admin_headers_factory, user_headers_factory, _patch_xfa_io):
|
||||
"""非 admin 不得调用视觉建议 API。"""
|
||||
profile_id, document_id, _, _ = _xfa_draft_profile(app, monkeypatch)
|
||||
client = app.test_client()
|
||||
payload = {
|
||||
'document_id': document_id,
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.2},
|
||||
}
|
||||
forbidden = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa/visual-bindings/suggest',
|
||||
json=payload,
|
||||
headers=user_headers_factory('vb-user'),
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
|
||||
ok = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa/visual-bindings/suggest',
|
||||
json=payload,
|
||||
headers=admin_headers_factory('vb-admin2'),
|
||||
)
|
||||
assert ok.status_code == 200
|
||||
data = parse_api_data(ok.get_json())
|
||||
assert data['diagnostics']['auto_confirm_blocked'] is True
|
||||
|
||||
|
||||
def test_visual_binding_confirm_requires_lease(app, monkeypatch, admin_headers_factory, _patch_xfa_io):
|
||||
"""确认视觉绑定必须持有有效租约。"""
|
||||
profile_id, _document_id, binding_id, _lease_token = _xfa_draft_profile(app, monkeypatch)
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa/visual-bindings/{binding_id}/confirm',
|
||||
json={
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.2},
|
||||
'source': 'manual_draw',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
},
|
||||
headers=admin_headers_factory('vb-admin3'),
|
||||
)
|
||||
assert response.status_code == 409
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED'
|
||||
@@ -0,0 +1,127 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_visual_publish_gate.py
|
||||
|
||||
用途:阶段 5 视觉绑定发布门禁——缺 bindings / 双源 / 未确认框阻断发布。
|
||||
依赖:publish_check_service 内部 _blocking_xfa_visual_bindings、xfa_contract。
|
||||
逻辑:纯单元构造 definition;断言 xfa_visual_bindings_required / dual source / incomplete。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.order_document_profile_publish_check_service import (
|
||||
_blocking_xfa_validation_metrics,
|
||||
_blocking_xfa_visual_bindings,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def _source_contract() -> dict:
|
||||
"""最小 XFA source_contract。"""
|
||||
return {
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
}
|
||||
|
||||
|
||||
def _confirmed_binding(*, field_id: str, field_code: str, status: str = 'confirmed') -> dict:
|
||||
"""构造最小统一绑定。"""
|
||||
return {
|
||||
'binding_id': f'bind-{field_id}-aaaa-bbbb',
|
||||
'field_id': field_id,
|
||||
'field_code': field_code,
|
||||
'scope': 'header' if field_id.startswith('f-h') else 'line',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': f'path-{field_id}',
|
||||
'data_path': f'/data/HEADER/{field_code.upper()}' if field_id.startswith('f-h') else f'/data/ITEMS/DATA/{field_code.upper()}',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5},
|
||||
'source': 'manual_draw',
|
||||
'status': status,
|
||||
'confidence': 1.0,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_missing_bindings_blocks_xfa_profile():
|
||||
"""关键断言:XFA 无 bindings → xfa_visual_bindings_required。"""
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert any(item.get('key') == 'xfa_visual_bindings_required' for item in blocking)
|
||||
|
||||
|
||||
def test_dual_binding_source_blocks_publish():
|
||||
"""关键断言:bindings 与 legacy mappings 共存 → xfa_dual_binding_source。"""
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [{
|
||||
'mapping_id': 'm-po', 'field_id': 'f-h-po', 'field_code': 'customer_po_no',
|
||||
'data_path': '/data/HEADER/EBELN', 'path_id': 'path-po',
|
||||
}],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [_confirmed_binding(field_id='f-h-po', field_code='customer_po_no')],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert any(item.get('key') == 'xfa_dual_binding_source' for item in blocking)
|
||||
|
||||
|
||||
def test_unconfirmed_visual_binding_blocks_publish():
|
||||
"""关键断言:正式字段视觉状态非 confirmed → xfa_visual_binding_incomplete。"""
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [_confirmed_binding(field_id='f-h-po', field_code='customer_po_no', status='suggested')],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert any(item.get('key') == 'xfa_visual_binding_incomplete' for item in blocking)
|
||||
|
||||
|
||||
def test_confirmed_bindings_pass_visual_gate():
|
||||
"""关键断言:全部正式字段 confirmed → 无视觉阻断。"""
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [_confirmed_binding(field_id='f-h-po', field_code='customer_po_no')],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert blocking == []
|
||||
|
||||
|
||||
def test_validation_metrics_threshold_blocks_below_100_percent():
|
||||
"""关键断言:摘要指标 < 1.0 时发布门禁阻断。"""
|
||||
blocking = _blocking_xfa_validation_metrics({
|
||||
'visual_coverage_rate': 0.5,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
})
|
||||
assert any(item.get('key') == 'xfa_visual_coverage_insufficient' for item in blocking)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""
|
||||
backend/xfa_regex_worker.py
|
||||
|
||||
用途:restricted re 匹配的隔离子进程 worker(仅标准库 re,不导入 app 包)。
|
||||
依赖:re、dataclasses。
|
||||
逻辑:由 xfa_safe_regex 经 ProcessPoolExecutor spawn 调用;独立模块避免 Windows 下重载 app/__init__ 挂死。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MatchSnapshot:
|
||||
"""子进程 re.search 结果快照,供父进程重建 Match 最小接口。"""
|
||||
|
||||
groups: tuple[str, ...]
|
||||
lastindex: int | None
|
||||
|
||||
|
||||
def run_restricted_search(pattern: str, flags: int, haystack: str) -> MatchSnapshot | None:
|
||||
"""
|
||||
在 pool worker 进程内执行 re.search 并返回快照。
|
||||
|
||||
核心逻辑:编译 pattern → search → 序列化分组;无匹配时返回 None。
|
||||
|
||||
Args:
|
||||
pattern: 已通过 validate 的正则 pattern。
|
||||
flags: re 编译 flags。
|
||||
haystack: 待搜索文本。
|
||||
|
||||
Returns:
|
||||
MatchSnapshot 或 None。
|
||||
|
||||
Raises:
|
||||
re.error: pattern 编译失败(子进程内不应出现,validate 已拦截)。
|
||||
"""
|
||||
compiled = re.compile(pattern, flags)
|
||||
match = compiled.search(haystack)
|
||||
if match is None:
|
||||
return None
|
||||
groups: list[str] = [match.group(0)]
|
||||
for idx in range(1, compiled.groups + 1):
|
||||
groups.append(match.group(idx) or '')
|
||||
return MatchSnapshot(groups=tuple(groups), lastindex=match.lastindex)
|
||||
+4
-1
@@ -226,7 +226,8 @@
|
||||
- 订单抽取最终必须以持久化 `ShippingOrderExtractionRun` 为业务生命周期真相;发送时 Run 冻结用户、入口 Agent、会话、Intake、Schema 与附件选择计划的轻量请求快照,Worker 物化后另冻结 Document 正文执行快照。幂等键始终锚定请求快照,不依赖浏览器 request ID。
|
||||
- 订单附件结构化必须支持版本化订单坐标 Profile v2。模板真相为静态文档锚点、表区相对坐标、独立表头布局、明细物理行布局、字段区域到稳定 `field_id + field_code` 的绑定、注册解析器、跨页/终止规则;表头文字只能用于建议、校准和匹配,不能决定最终字段。已发布版本不可原地修改,同模板发布新版本时原子退役旧版本;Run 必须复制完整 published Profile,不能只保存当前 Profile ID。
|
||||
- **XFA 客户采购订单(PO)数据路径 Profile(2026-08-04)**:对含 `/XFA datasets` 且 datasets 已保存最终业务值的混合型 XFA PDF,新增 `template_mode=xfa_dataset`,从受控 XML 路径提取 Header/Line;普通 PDF 继续 `coordinate`。第一版不执行 XFA 脚本/FormCalc、不自动合并多明细集合、不回退 OCR/VLM/猜列;管理员在映射工作台选择唯一权威集合并绑定冻结 Schema 字段。正式提取须精确命中唯一 published Profile,并完成 AcroForm/镜像集合/业务恒等式对账;失败一律 `needs_review`。自动建单与坐标路径共用 Schema `auto_creation_policy` / 统一 Candidate Qualification(**无**独立 XFA 自动建单环境变量);须客户/checksum/场景白名单、当前 checksum 盲测批准与 CQ 全绿后方可试点;5 日 live shadow 与生产审批完成前不得开启生产自动建单。Dify 不参与 XFA 解析(见 [xfa-profile-dify-config.md](features/shipping-notice/xfa-profile-dify-config.md))。权威方案/验收:[xfa-profile-implementation-plan.md](features/shipping-notice/xfa-profile-implementation-plan.md)、[xfa-profile-acceptance.md](features/shipping-notice/xfa-profile-acceptance.md)。
|
||||
- **XFA 字段拆分映射(2026-08-05)**:允许对单一 XFA 叶子(如多行 `MATNR`)配置**多阶段**声明式拆分流水线(`stages[]`:换行/单行/连续行范围/前缀/正则/替换/子串/归一化),连续行范围支持保留换行、空格或逗号合并并完整参与行认领冲突检测;输出自定义拆分段并映射到**现有**订单 Schema 字段,或标记为 `evidence_only`。XFA 工作台只描述当前模板的可提取能力,不继承 Schema `required` / `auto_create_key_field` 作为模板覆盖要求;未映射字段不阻断模板保存、验证或发布,最终完整性由 EML、PDF/XFA 及其他附件 Observation 合并后的 Candidate/Task/履约 Gate 判定。禁止新增 Schema 字段、禁止规则引擎执行脚本/LLM;**无系统推荐**;规则内容变更强制回退 Draft 并递增版本;正式解析只读已发布 Profile;规则编辑与发布审核职责分离;完整值访问独立审计。契约:[xfa-field-split-mapping.md](features/shipping-notice/xfa-field-split-mapping.md)。
|
||||
- **XFA 统一视觉标注、字段拆分与精确解析(2026-08-05 冻结)**:普通 PDF 与 XFA 共用同一页面画框工作台;XFA 正式值仍只从 datasets 读取,页面框仅作视觉证据。所有正式字段必须同时具备已确认 `value_binding` 与 `visual_binding`。声明式拆分支持所有 Header/明细字符串字段;匹配优先级固定为 `prefix > regex > position > unmatched`;同优先级冲突 `needs_review`;`evidence_only` 保留但不写 Schema。正则优先 RE2。现有模板一次性迁移到统一 binding,不要求人工从零重建。发布门禁含视觉覆盖、拆分安全、独立盲测与编辑/审核职责分离;自动建单须发布门禁与 CQ/STP 运行门禁全部通过。Dify 不参与解析主链。权威方案:[xfa-unified-visual-split-implementation-plan.md](features/shipping-notice/xfa-unified-visual-split-implementation-plan.md);验收:[xfa-profile-acceptance.md](features/shipping-notice/xfa-profile-acceptance.md) §15;线框:[shipping-xfa-profile-wireframes.md](prototype/shipping-xfa-profile-wireframes.md)。
|
||||
- **XFA 字段拆分映射(历史增量,已由统一方案接管)**:早期曾落地多阶段 `stages[]` 流水线与独立 XFA 映射页。统一方案冻结后,拆分语义以 `prefix > regex > position > unmatched` 为准,工作台并入统一画框编辑器;历史契约文档 [xfa-field-split-mapping.md](features/shipping-notice/xfa-field-split-mapping.md) 仅作迁移对照,不再作为新开发权威。
|
||||
- 业务管理员必须通过受控样本页面维护订单坐标 Profile:可配置相对区域、静态锚点、独立表头/明细布局和注册解析器;不得编辑 HTML、原始 bbox、JSON、正则、脚本、Prompt 或结构指纹。草稿更新使用乐观锁;每个明细字段区域必须绑定 Schema 允许的 `pdf_coordinate`/`ocr_coordinate` 来源和最低证据等级;不可变版本可复制为新草稿或退役。
|
||||
- Profile 治理必须保存模板模式、训练样本计数和不含锚点正文的匹配策略摘要;训练/标注样本、盲测样本及其增删、草稿保存、区域/字段绑定变化、测试执行/批准、发布和退役均追加审计。样本文档被训练或盲测引用后不得删除;审计不得保存 PDF、HTML、对象存储地址、正文或凭据。
|
||||
- 订单文档模板后续统一按 `profile_code` 作为模板族管理版本;`version` 只在同一模板族内递增。每个模板族最多一个 `draft`、最多一个 `published`,可有多个 `retired`;默认选择顺序固定为 `published -> draft -> 最新 retired`,URL 显式指定版本时必须严格按该版本返回,找不到时返回明确 404,不得自动跳转到其他版本。
|
||||
@@ -727,3 +728,5 @@
|
||||
### XFA 拆分规则作用域补充(2026-08-05)
|
||||
|
||||
拆分规则继承源节点作用域:权威明细集合之外的 Header 叶子只能映射 Header Schema 字段,正式提取按文档执行一次;集合之下的 Line 叶子只能映射 Line 字段,并逐条明细执行。
|
||||
|
||||
XFA 模板管理端暂不启用字段脱敏,树、拆分预览和样本验证直接展示完整值;模板试读不以订单 Schema 必填或自动建单关键字段缺值作为失败条件。
|
||||
@@ -23,6 +23,67 @@
|
||||
|
||||
**阶段状态**:0–5 PASS;6 并入统一 CQ/STP;7 文档 PASS。
|
||||
|
||||
### 0.Y XFA 统一视觉标注、字段拆分与精确解析(2026-08-05 冻结)
|
||||
|
||||
> 权威方案:**[xfa-unified-visual-split-implementation-plan.md](xfa-unified-visual-split-implementation-plan.md)**
|
||||
> 线框:**[shipping-xfa-profile-wireframes.md](../../prototype/shipping-xfa-profile-wireframes.md)**
|
||||
> 验收:**[xfa-profile-acceptance.md](xfa-profile-acceptance.md)** §15
|
||||
> Dify:**NONE**(解析主链不经 Dify;配置说明仍见 [xfa-profile-dify-config.md](xfa-profile-dify-config.md))
|
||||
|
||||
**业务目标**:普通 PDF 与 XFA 共用同一页面画框工作台;XFA 正式值仍只从 datasets 读取;页面框负责定位、展示、复核与审计证据;必要时执行声明式字段拆分;验证 → 独立盲测 → 双人发布 → CQ/STP → 自动建单。
|
||||
|
||||
**统一字段绑定(目标模型)**:
|
||||
|
||||
```text
|
||||
binding = {
|
||||
binding_id, field_id, field_code, scope,
|
||||
value_binding: { type: xfa_dataset|pdf_coordinate|ocr_coordinate, ... },
|
||||
visual_binding: { page_no, normalized_bbox, source, status, confidence },
|
||||
split_rule_ref?: { rule_set_id, segment_id }
|
||||
}
|
||||
```
|
||||
|
||||
约束:
|
||||
|
||||
- XFA 正式绑定只允许 `value_binding.type=xfa_dataset`。
|
||||
- `visual_binding.status ∈ {suggested, confirmed, rejected, unavailable}`;正式字段非 `confirmed` 不得发布。
|
||||
- 同一 Schema 字段在同一作用域最多一个正式来源。
|
||||
- 历史「XFA definition 排斥坐标键」限制将被移除,改为允许并存的视觉证据(值仍来自 datasets)。
|
||||
|
||||
**拆分规则(目标执行语义)**:
|
||||
|
||||
- 匹配优先级固定:`prefix > regex > position > unmatched`。
|
||||
- 同一行仅一个胜出 segment;同优先级多个 mapped 规则命中 → `needs_review`。
|
||||
- `evidence_only` 保留原始行证据,不写订单 Schema,不参与必填/冲突/镜像阻断。
|
||||
- 正则优先 `google-re2` 线性时间语义;部署失败时仅允许受限安全子集,禁止无限制 Python `re`。
|
||||
- 规则执行不得访问网络、文件、数据库或 LLM。
|
||||
- 历史增量 `stages[]` 流水线实现将被对齐到本冻结语义(阶段 1)。
|
||||
|
||||
**数据流**:
|
||||
|
||||
```text
|
||||
上传 PDF
|
||||
→ 统一页面预览与坐标画框
|
||||
→ 选择订单 Schema 字段
|
||||
→ 识别正式值来源(XFA datasets / PDF 坐标 / OCR 兜底)
|
||||
→ 可选声明式拆分
|
||||
→ 当前样本验证(视觉覆盖 + 拆分 + 镜像/AcroForm)
|
||||
→ 独立盲测
|
||||
→ 双人发布审核
|
||||
→ 正式解析 + 字段血缘
|
||||
→ CQ/STP 门禁 → 自动建单或 needs_review
|
||||
```
|
||||
|
||||
**字段血缘最小集**:FileAsset → packet checksum → datasets path_id → collection row → source line → rule_set/rule_version/rule_id → segment_id → Schema field_id → normalized value → visual page/bbox。
|
||||
|
||||
**安全边界**:禁止 DTD/外部实体/外部资源;限制 packet/节点/深度/行数;敏感快照加密 + 独立读审计;审计保留 1095 天且只追加;关键写操作缺审计则事务失败关闭。
|
||||
|
||||
**迁移**:现有模板一次性无损迁移为统一 binding Draft;普通坐标直接转换;XFA 保留路径与 Schema;优先 AcroForm Widget 生成候选框;待补框模板不得发布;新 Draft 发布后删除旧 definition 运行时兼容分支。
|
||||
|
||||
**自动建单口径**:模板发布门禁与现有 Candidate Qualification / STP 运行门禁**全部通过后允许**;自动建单前重验统一 Profile 快照。
|
||||
|
||||
**阶段状态**:阶段 0–6 **PASS(2026-08-06)**;阶段 7–8 **PASS(代码,2026-08-06)**。阶段 5–6 证据见 [xfa-profile-acceptance.md §15.5](xfa-profile-acceptance.md);合规报告:[xfa-unified-visual-split-compliance-report.md](xfa-unified-visual-split-compliance-report.md);迁移手册:[xfa-profile-migration-runbook.md](xfa-profile-migration-runbook.md)。
|
||||
|
||||
### 1. 已确认的业务与架构边界
|
||||
|
||||
- 一封 EML 可以包含多个 PDF,一般一个 PDF 对应一个 PO,系统按 PDF 自动拆分处理单元。
|
||||
@@ -543,6 +604,8 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open
|
||||
|
||||
**多附件提交边界(2026-07-31)**:聊天输入框是一次订单抽取的业务提交边界。用户可以分多次打开文件选择器追加 EML/PDF;发送时前端必须汇集输入框内全部已就绪、未消费且无阻断的 Intake,并通过一个 `intake_nos[]` 请求创建统一 Run。单次文件选择生成的 `uploadBatchId` 仅用于上传幂等和状态关联;多个 ID 不得阻断共同发送,也不得导致只提交最后一次选择的附件。
|
||||
|
||||
**多 PDF Unit → Review Case 生命周期(2026-08-05)**:任意数量 PDF 可乱序完成,但每个 PDF 只能在自身 Unit 进入 `candidate_ready` 或 `review_required`、且当前 Candidate 已持久化后,幂等创建或修复自己的 Review Case;单个 Unit 完成不得遍历并提前初始化仍处于 `pending/routing/extracting` 的兄弟 Unit。Run 级 Case 入口仅用于终态对账。首个 Candidate 使用 Run 根 OT,后续兄弟 PDF 使用稳定子 OT,避免并发换绑同一 `candidate_id`;历史竞态产生的空 Case 仅在未人工编辑时补回唯一当前 Candidate 和机器 Draft。等待 Layout 的当前 Job 以 `handoff_status=deferred_to_layout` 成功完成交接,后续订单识别由 Layout 完成后新 Job 继续,不能把该占位 Job 解读为抽取卡死。
|
||||
|
||||
**阶段 3 Dify 手工配置**:无需为订单抽取配置 `execution_manifest`、附件输入、模型重试节点或 `orders` 输出。附件选择、深度解析、模板路由、Candidate 裁决均由 HXOPS Worker 执行;无法确定的文档进入人工复核。用户可在复核工作台按字段调用同一 Chatflow 的 `REVIEW_*` 分支获取最小证据建议,但该建议不属于 Run 抽取结果,也不能自动裁决。
|
||||
|
||||
**阶段 4 历史结论(2026-07-21)**:非确定性单元以 Run 冻结的 `unit_concurrency=2..4` 受控并行调用 Dify;线程只持有冻结 Run/Unit 和 Provider 网络字段的纯快照,不共享 ORM Session。每个单元按 `unit_max_attempts=1..3` 独立重试,并使用 `unit_retry_backoff_ms=100..5000` 指数退避加抖动;已成功和确定性单元不重跑。主线程串行写入单元状态、结果、attempt 和 latency,并按冻结 position 汇总,完成顺序不改变业务顺序。任一单元耗尽局部重试后保留其他成功结果,再由 Job 重试恢复失败单元;全局 Provider 治理与熔断在阶段 6 完成。
|
||||
@@ -2577,7 +2640,7 @@ primary_pdf_parsed_value
|
||||
- EML 多 PDF:每个 PDF 独立 Candidate;禁止跨 PDF 拼行、补字段或因客户相似合并。
|
||||
- 直接 PDF:`document_parsing → candidate_creating`,不得进入 `email_parsing` / `email_adjudicating`。
|
||||
|
||||
关键字段冲突策略(当前值仍取 PDF,默认阻断自动建单):`po_number`、`customer_name` / `bill_to_name` / `sold_to_name`、`part_number` / `customer_part_number`、`qty` / `quantity`。
|
||||
关键字段冲突策略(当前值仍取 PDF,默认阻断自动建单):`po_number`、`customer_name` / `bill_to_name` / `sold_to_name`、`part_number` / `customer_part_number`、`qty` / `quantity`。
|
||||
非关键字段可按策略继续;`reservation_id` / `inventory_source_hint` / `source_type` 允许 PDF 缺失时补充。
|
||||
|
||||
**核心原则**:当前裁决值优先 PDF ≠ 所有 PDF 冲突都允许自动建单。
|
||||
@@ -2602,7 +2665,7 @@ Intake 仍在解析且已有 OT → 显示 Intake + childOrderTasks
|
||||
Intake 不再产生 Candidate → completed/handed_off;进行中列表只留未完成 OT
|
||||
```
|
||||
|
||||
DTO 字段见 `ShippingProcessingProjection`(`workItemType` / `status` / `stage` / `progressVersion` / `sourceType` / `childOrderTasks` 等)。
|
||||
DTO 字段见 `ShippingProcessingProjection`(`workItemType` / `status` / `stage` / `progressVersion` / `sourceType` / `childOrderTasks` 等)。
|
||||
状态只能由后端领域服务原子更新并 `progress_version+1` 同事务写审计;前端只展示。
|
||||
|
||||
#### 4. 审计事件(阶段 0 冻结码)
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
# 统一进度与正式任务编辑 — 全阶段最终验收合规报告
|
||||
|
||||
> **日期**:2026-08-05
|
||||
> **日期**:2026-08-05(勘误 2026-08-05 晚)
|
||||
> **方案**:15 阶统一进度 + 确认后原地正式任务编辑 + Schema 策略 + change_effect + 审计
|
||||
> **总结论**:阶段 0–6 关键验收标准已达标;Dify 为 NONE(见配置说明)
|
||||
> **总结论(勘误)**:阶段 0–6 **契约与正式编辑**已落地;但「统一进度」曾被误实现为四页面同一网格 UI。
|
||||
> **当前口径**:统一的是后端业务进度事实、Gate、动作意图与审计;四页面必须差异化 Presenter。
|
||||
> **页面命名**:原「复核工作台」→ **订单处理工作台**(单 OT 从复核到上传连续处理);原「任务工作台」→ **任务中心**(多任务列表)。
|
||||
|
||||
## 勘误清单(相对本文件初版「已达标」声明)
|
||||
|
||||
| 项 | 状态 |
|
||||
| --- | --- |
|
||||
| status/stage/gate/action 不变量 + `stage_nodes` | 已补 `processing_projection_invariants` |
|
||||
| Extraction Run completed ≠ 全流程 completed | 已修正映射 |
|
||||
| 四页面差异化 Presenter(非同网格 density) | 已挂 Chat/Sidebar/Review/Workbench Presenter |
|
||||
| 中性阶段名 / 复核页隐藏「进入复核」 | 已改 i18n + surface 过滤 |
|
||||
| Excel Artifact ready 冻结 / 全量 15 阶状态机写链 | Excel ready 已直查 Artifact;确认前客户/查重/库存源 stage 写链已接入;履约 Excel/上传回写 OT;Candidate 前早期 stage 写入 Run.progress_summary_json.processing_stage;OT 进度写入口强制 `order_task_progress_changed` 审计;Notice→stage 领域映射已抽离;投影读路径以 OT.stage/status 为准(不再用 Notice 覆盖) |
|
||||
|
||||
## 阶段总览
|
||||
|
||||
| 阶段 | 主题 | 验收文档 | 结论 |
|
||||
| --- | --- | --- | --- |
|
||||
| 0 | 契约冻结(15 阶 / 动作意图) | stage0-acceptance | 通过 |
|
||||
| 0 | 契约冻结(15 阶 / 动作意图) | stage0-acceptance | 契约通过;运行态继续收敛 |
|
||||
| 1 | Projection 写读 / 库存源硬门禁 | stage1-acceptance | 通过 |
|
||||
| 2 | UnifiedProgressTrack / ActionBar | stage2-acceptance | 通过 |
|
||||
| 2 | 进度呈现 / ActionBar | stage2-acceptance | **勘误**:不得再要求「四页面同网格」 |
|
||||
| 3 | 原地 formal_task 编辑 | stage3-acceptance | 通过 |
|
||||
| 4 | change_effect 下游失效 | stage4-acceptance | 通过 |
|
||||
| 5 | 正式编辑审计矩阵 | stage5-acceptance | 通过 |
|
||||
@@ -22,13 +34,13 @@
|
||||
| --- | --- | --- |
|
||||
| 1 | 四页面消费同一 ShippingProcessingProjection | 通过(阶段 1–2) |
|
||||
| 2 | 15 阶顺序一致(库存源前置) | 通过 |
|
||||
| 3 | 页面只改密度 | 通过(shipping-progress) |
|
||||
| 4 | Gate/按钮由 ActionPresentation | 通过(阶段 2) |
|
||||
| 5 | 建单后复核台原地切换 | 通过(阶段 3) |
|
||||
| 3 | 页面差异化呈现(非同组件缩放) | **勘误后**:ChatSummary / SidebarInline / ReviewStrip / WorkbenchGrouped |
|
||||
| 4 | Gate/按钮由 ActionPresentation(含页面语境) | 复核页隐藏 open_order_review |
|
||||
| 5 | 建单后订单处理台原地切换 | 通过(阶段 3) |
|
||||
| 6 | 编辑对象切换为正式任务 | 通过 |
|
||||
| 7 | 默认只读,Schema 放行才可写 | 通过 |
|
||||
| 8 | 库存影响字段回退匹配 | 通过(阶段 4) |
|
||||
| 9 | Excel 成功后冻结边界 | 通过(快照冻结 + editable_until) |
|
||||
| 9 | Excel ready 冻结边界 | **BE-09**:ready Artifact + 路径 + version 指纹 |
|
||||
| 10 | 无库存源不得建单 | 通过(阶段 1) |
|
||||
| 11–12 | 解析恢复 / 对话删除恢复 | 既有能力;本方案未回归阻断 |
|
||||
| 13–15 | 审计完整 / 不可改删 / 哈希链 | 正式编辑矩阵已补;全账本既有 |
|
||||
@@ -41,6 +53,6 @@
|
||||
## 已知非阻断项
|
||||
|
||||
- 候选快照历史 UI 仍为占位
|
||||
-
|
||||
equire_revision 无专门前端提示条
|
||||
- require_revision 无专门前端提示条
|
||||
- editable_until=excel_ready 完整导出 E2E 建议发布前人工抽检
|
||||
- ~~任务中心内嵌 ShippingTaskWorkbench~~(**UI-04 已收口**:任务中心仅列表+深链;履约登记挂在订单处理工作台 TaskTodoPanel)
|
||||
Loaded 100 of 195 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user