feat(shipping-notice): 落地 XFA 拆分、版面签名、统一进度与处理域履约
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
3a9fbac2fc
commit
d2b3d74def
571 files changed
+78064
-24681
No files matched your search
@@ -65,6 +65,12 @@ HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
|
||||
# --- 9. 业务模块 ---
|
||||
|
||||
# XFA 试点门禁覆盖(默认见 .env.shared;自动建单走 Schema 总开关;空客户/checksum 白名单 fail-closed)
|
||||
# SHIPPING_NOTICE_XFA_SHADOW_MODE=false
|
||||
# SHIPPING_NOTICE_XFA_CUSTOMER_ALLOWLIST=
|
||||
# SHIPPING_NOTICE_XFA_PROFILE_CHECKSUM_ALLOWLIST=
|
||||
# SHIPPING_NOTICE_XFA_SCENARIO_ALLOWLIST=shipping_notice_order
|
||||
|
||||
# 自动推进(auto_progress)
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
# 进度细化灰度(阶段 5):新进度 UI / Run-Unit 取消 / 管理员审计导出;回滚只关开关,不删审计
|
||||
@@ -72,6 +78,8 @@ SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
|
||||
# 复核工作台字段级 AI 建议;仅开发环境启用,建议仍须证据校验与人工裁决
|
||||
SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
@@ -98,7 +106,7 @@ SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=false
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL=
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS=10
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS=300
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=4
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=10
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000
|
||||
|
||||
@@ -72,6 +72,12 @@ WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||
|
||||
# --- 9. 业务模块 ---
|
||||
|
||||
# XFA 试点门禁覆盖(默认见 .env.shared;自动建单走 Schema 总开关;空客户/checksum 白名单 fail-closed)
|
||||
# SHIPPING_NOTICE_XFA_SHADOW_MODE=false
|
||||
# SHIPPING_NOTICE_XFA_CUSTOMER_ALLOWLIST=
|
||||
# SHIPPING_NOTICE_XFA_PROFILE_CHECKSUM_ALLOWLIST=
|
||||
# SHIPPING_NOTICE_XFA_SCENARIO_ALLOWLIST=shipping_notice_order
|
||||
|
||||
# 进度细化灰度(阶段 5;生产默认开启,回滚时按需关闭,禁止删除审计事实)
|
||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||
@@ -89,7 +95,7 @@ SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=false
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL=
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS=10
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS=300
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=4
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=10
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000
|
||||
|
||||
+20
-2
@@ -147,7 +147,7 @@ FAQ_HOT_ANSWER_DOMINANCE=0.6 # (聚类已关闭)最大答案簇
|
||||
FAQ_HOT_GOOD_SCORE=4 # 选代表答案时「好评」反馈分阈值(≥此分优先)
|
||||
FAQ_HOT_BAD_SCORE=2 # 选代表答案时「差评」反馈分阈值(≤此分排除)
|
||||
# 货代客户自动确认默认关闭;仅 approved + auto_match_allowed 强规则唯一命中时可开启。
|
||||
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED=false
|
||||
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED=true
|
||||
# 发货通知专用 Worker 进程数;版面解析为长任务,默认并发处理同批两份文档。
|
||||
SHIPPING_NOTICE_WORKER_CONCURRENCY=2
|
||||
# 通用 Job 回收阈值须高于版面 Worker 360 秒上限,避免并发 Worker 误回收正常长任务。
|
||||
@@ -176,8 +176,26 @@ SHIPPING_NOTICE_GENERIC_EXTRACTION_ENABLED=false
|
||||
SHIPPING_NOTICE_GENERIC_AUTO_FREEZE_ENABLED=false
|
||||
# 模板多维评分自动采用(Top1 决胜);关闭后评分命中仍须人工确认。
|
||||
SHIPPING_NOTICE_PROFILE_AUTO_SELECTION_ENABLED=true
|
||||
# 阶段四全量切换:全部模板重签并重新发布后改为 true
|
||||
SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED=true
|
||||
# XFA 数据路径 Profile(识别到 xfa_hybrid 即正式提取)
|
||||
SHIPPING_NOTICE_XFA_ENABLED=true
|
||||
# 自动建单走 Schema auto_creation_policy / 统一 CQ;无独立 XFA_AUTO_CREATE 开关。
|
||||
# shadow=true:完整解析与资格评估,但阻断真实自动建单(仅记录 would_auto_create)
|
||||
SHIPPING_NOTICE_XFA_SHADOW_MODE=false
|
||||
# 自动建单硬门禁白名单:客户或 Profile checksum 为空 → fail-closed
|
||||
SHIPPING_NOTICE_XFA_CUSTOMER_ALLOWLIST=
|
||||
SHIPPING_NOTICE_XFA_PROFILE_CHECKSUM_ALLOWLIST=
|
||||
SHIPPING_NOTICE_XFA_SCENARIO_ALLOWLIST=shipping_notice_order
|
||||
SHIPPING_NOTICE_XFA_MAX_PDF_BYTES=20971520
|
||||
SHIPPING_NOTICE_XFA_MAX_PACKET_BYTES=10485760
|
||||
SHIPPING_NOTICE_XFA_MAX_XML_DEPTH=64
|
||||
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
|
||||
# 复核台 Dify 最小证据建议;永不自动冻结。
|
||||
SHIPPING_NOTICE_LLM_REVIEW_ENABLED=false
|
||||
SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true
|
||||
# 全局紧急停止:新 Run 自动冻结立即为 0(进程配置;多 worker 需逐进程/重启生效)。
|
||||
SHIPPING_NOTICE_EXTRACTION_EMERGENCY_STOP=false
|
||||
# 货代统一审计默认保留天数(三年);到期由 shipping-audit-retention Job 清理。
|
||||
|
||||
@@ -75,6 +75,12 @@ WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
|
||||
|
||||
# --- 9. 业务模块 ---
|
||||
|
||||
# XFA 试点门禁覆盖(默认见 .env.shared;自动建单走 Schema 总开关;空客户/checksum 白名单 fail-closed)
|
||||
# SHIPPING_NOTICE_XFA_SHADOW_MODE=false
|
||||
# SHIPPING_NOTICE_XFA_CUSTOMER_ALLOWLIST=
|
||||
# SHIPPING_NOTICE_XFA_PROFILE_CHECKSUM_ALLOWLIST=
|
||||
# SHIPPING_NOTICE_XFA_SCENARIO_ALLOWLIST=shipping_notice_order
|
||||
|
||||
# 自动推进(auto_progress)
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
# 进度细化灰度(阶段 5):新进度 UI / Run-Unit 取消 / 管理员审计导出;回滚只关开关,不删审计
|
||||
@@ -108,7 +114,7 @@ SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL=http://192.168.100.192:8100/
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS=10
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS=300
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=4
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=10
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000
|
||||
|
||||
@@ -15,6 +15,7 @@ from flask import g, request, send_file
|
||||
from app import db
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ForbiddenError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice import order_document_profile_audit_service as audit_service
|
||||
from app.services.shipping_notice import order_document_profile_diff as diff_service
|
||||
@@ -170,13 +171,6 @@ def get_order_document_profile_sample_tables(document_id: int):
|
||||
return _ok(service.get_sample_tables(document_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-samples/coordinate-reconstruction-preview', methods=['POST'])
|
||||
@require_admin
|
||||
def preview_order_document_profile_coordinate_reconstruction():
|
||||
"""根据管理员确认的相对列边界返回只读坐标重建候选。"""
|
||||
return _ok(service.preview_coordinate_reconstruction(request.get_json(silent=True) or {}, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-samples/coordinate-reconstruction-suggestion', methods=['POST'])
|
||||
@require_admin
|
||||
def suggest_order_document_profile_coordinate_reconstruction():
|
||||
@@ -230,8 +224,18 @@ def create_order_document_profile():
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_order_document_profile(profile_id: int):
|
||||
"""按乐观锁整体更新模板 Profile 草稿。"""
|
||||
"""按乐观锁整体更新模板 Profile 草稿;变更 split_rules 需 xfa_split_rule_edit。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
from app.extensions import db as _db
|
||||
from app.models import ShippingOrderDocumentProfile
|
||||
|
||||
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
|
||||
if profile_row is not None and isinstance(profile_row.definition_json, dict)
|
||||
else {}
|
||||
)
|
||||
return _ok(service.save_draft(
|
||||
data, actor_id=_actor_id(), profile_id=profile_id, **_write_context(data), enforce_lease=True,
|
||||
))
|
||||
@@ -400,14 +404,28 @@ def create_order_document_profile_publish_check(profile_id: int):
|
||||
@require_admin
|
||||
def get_order_document_profile_publish_check(profile_id: int, report_no: str):
|
||||
"""读取发布检查报告及失效、阻断和逐项警告确认状态。"""
|
||||
return _ok(publish_check_service.get_report(profile_id, report_no))
|
||||
payload = publish_check_service.get_report(profile_id, report_no)
|
||||
_log_profile_view_event(profile_id, event_type='publish_check_viewed', detail={'report_no': report_no})
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/publish-checks/<string:report_no>/confirm', methods=['POST'])
|
||||
@require_admin
|
||||
def confirm_order_document_profile_publish_check(profile_id: int, report_no: str):
|
||||
"""消费有效报告并原子发布,警告必须逐项确认。"""
|
||||
from app.models import ShippingOrderDocumentProfile
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
entity = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
definition = dict((entity.definition_json or {}) if entity is not None else {})
|
||||
if str(definition.get('template_mode') or '') == 'xfa_dataset':
|
||||
user = getattr(g, 'current_user', None)
|
||||
if not bool(user and user.has_feature_permission('shipping_notice.xfa_split_rule_publish')):
|
||||
raise ForbiddenError(
|
||||
'XFA split rule publish permission is required',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_VALUE_FORBIDDEN',
|
||||
details={'permission': 'shipping_notice.xfa_split_rule_publish'},
|
||||
)
|
||||
return _ok(publish_check_service.consume_report(profile_id, report_no, data=data, actor_id=_actor_id(), **_write_context(data)))
|
||||
|
||||
|
||||
@@ -615,6 +633,34 @@ def run_order_document_profile_current_sample(profile_id: int):
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/validation-runs/layout-signature', methods=['POST'])
|
||||
@require_admin
|
||||
def run_order_document_profile_layout_signature(profile_id: int):
|
||||
"""
|
||||
生成当前草稿的版面签名 ValidationRun,并更新 Profile 轻量签名引用。
|
||||
|
||||
前端不得提交 Matcher 分数或签名正文;服务端仅消费租约与 operation_id。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(validation_service.run_layout_signature(
|
||||
profile_id, data=data, actor_id=_actor_id(), **_write_context(data),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/validation-runs/cross-template-overlap', methods=['POST'])
|
||||
@require_admin
|
||||
def run_order_document_profile_cross_template_overlap(profile_id: int):
|
||||
"""
|
||||
执行跨模板唯一性 ValidationRun;要求当前草稿已有有效 layout_signature 或请求体允许自动生成。
|
||||
|
||||
前端不得提交 matcher 分数或 layout 正文;服务端只返回安全摘要与 conflict_profiles。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(validation_service.run_cross_template_overlap(
|
||||
profile_id, data=data, actor_id=_actor_id(), **_write_context(data),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/ocr-coordinate-evidence', methods=['POST'])
|
||||
@require_admin
|
||||
def generate_bound_order_document_profile_ocr_coordinate_evidence(profile_id: int):
|
||||
@@ -672,7 +718,9 @@ def confirm_order_document_profile_test_reviews(suite_id: int):
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(quality.confirm_sample_reviews(
|
||||
suite_id=suite_id, document_id=data.get('document_id'), table_id=str(data.get('table_id') or ''),
|
||||
row_reviews=data.get('row_reviews'), order_field_reviews=data.get('order_field_reviews'), actor_id=_actor_id(),
|
||||
row_reviews=data.get('row_reviews'), order_field_reviews=data.get('order_field_reviews'),
|
||||
layout_version_id=data.get('layout_version_id'),
|
||||
layout_payload_checksum=data.get('layout_payload_checksum'), actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@@ -698,3 +746,88 @@ def approve_order_document_profile_test_suite(suite_id: int):
|
||||
"""批准最新合格盲测,使该模板可参与确定性自动建单。"""
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
return _ok(quality.approve_suite(suite_id=suite_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/xfa/field-tree',
|
||||
methods=['GET'],
|
||||
)
|
||||
@require_admin
|
||||
def get_order_document_profile_sample_xfa_field_tree(document_id: int):
|
||||
"""返回 XFA 字段树安全投影;不含 XML/PDF 正文。"""
|
||||
return _private_ok(service.get_xfa_field_tree(document_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/xfa/collections',
|
||||
methods=['GET'],
|
||||
)
|
||||
@require_admin
|
||||
def get_order_document_profile_sample_xfa_collections(document_id: int):
|
||||
"""返回 XFA 重复集合候选摘要。"""
|
||||
return _private_ok(service.get_xfa_collections(document_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/xfa/value-preview',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def preview_order_document_profile_sample_xfa_value(document_id: int):
|
||||
"""按 path_id 返回分级样本值;完整值读取要求敏感权限并由服务层留痕。"""
|
||||
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',
|
||||
)
|
||||
return _private_ok(service.preview_xfa_sample_value(
|
||||
document_id,
|
||||
path_id=str(data.get('path_id') or ''),
|
||||
actor_id=_actor_id(),
|
||||
include_full_value=reveal,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/xfa/split-rules/preview',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def preview_order_document_profile_sample_xfa_split_rules(document_id: int):
|
||||
"""预览拆分规则执行结果;默认脱敏,完整值需敏感读权限。"""
|
||||
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')
|
||||
return _private_ok(service.preview_xfa_split_rules(
|
||||
document_id,
|
||||
path_id=str(data.get('path_id') or ''),
|
||||
rule_set=rule_set,
|
||||
actor_id=_actor_id(),
|
||||
profile_id=int(profile_id) if profile_id not in (None, '') else None,
|
||||
include_full_values=reveal,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/split-rules/validate',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def validate_order_document_profile_xfa_split_rules(profile_id: int):
|
||||
"""校验 Profile 拆分规则契约与 Schema 映射;不持久化。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
split_rules = data.get('split_rules')
|
||||
if split_rules is not None and not isinstance(split_rules, list):
|
||||
raise ValidationError(
|
||||
'split_rules must be a list',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
return _private_ok(service.validate_xfa_split_rules(
|
||||
profile_id,
|
||||
split_rules=split_rules,
|
||||
actor_id=_actor_id(),
|
||||
))
|
||||
@@ -389,3 +389,23 @@ def export_shipping_notice_audit_events():
|
||||
'X-Exported-Count': str(exported['exported']),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/audit-snapshots/<string:snapshot_ref>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_notice_xfa_audit_snapshot(snapshot_ref: str):
|
||||
"""
|
||||
读取 XFA 加密完整审计快照。
|
||||
|
||||
核心逻辑:仅 shipping_notice.audit_sensitive_read 可获明文;每次读取再写访问审计;
|
||||
无权限时仅返回脱敏摘要。
|
||||
"""
|
||||
from app.services.shipping_notice.audit_query_service import get_xfa_audit_full_snapshot
|
||||
|
||||
payload = get_xfa_audit_full_snapshot(
|
||||
admin_user_id=g.current_user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
snapshot_ref=snapshot_ref,
|
||||
include_sensitive=_caller_can_read_audit_sensitive(),
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
+98
-19
@@ -2,8 +2,10 @@
|
||||
backend/app/api/chat.py
|
||||
|
||||
用途:聊天 BFF(SSE 流式、会话 CRUD、PLM/Excel 预览、反馈)。
|
||||
依赖:app.core.decorators、app.core.errors、services.dify、integrations。
|
||||
逻辑:/completions 按意图分流(Wave 3 抽至 services/chat/router.py);错误统一 raise AppError。
|
||||
依赖:app.core.decorators、app.core.errors、app.core.response、services.dify、integrations、
|
||||
shipping_notice.audit_service(货代会话删除审计)。
|
||||
逻辑:/completions 按意图分流(Wave 3 抽至 services/chat/router.py);错误统一 raise AppError;
|
||||
shipping_notice 会话删除写不可变审计并返回标准 envelope。
|
||||
"""
|
||||
import io
|
||||
import ipaddress
|
||||
@@ -28,7 +30,7 @@ from app.services.dify import DifyService
|
||||
from app.core.config.settings import Config
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
from app.core.decorators import require_agent_permission
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback, ShippingOrderExtractionRun
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback, ShippingOrderProcessingRun
|
||||
from app import db
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
@@ -237,14 +239,14 @@ def _order_extraction_attention_by_conversation(
|
||||
'cancelled': 'error',
|
||||
}
|
||||
rows = db.session.query(
|
||||
ShippingOrderExtractionRun.conversation_id,
|
||||
ShippingOrderExtractionRun.status,
|
||||
ShippingOrderProcessingRun.conversation_id,
|
||||
ShippingOrderProcessingRun.status,
|
||||
).filter(
|
||||
ShippingOrderExtractionRun.user_id == user_id,
|
||||
ShippingOrderExtractionRun.owner_agent_id == agent_id,
|
||||
ShippingOrderExtractionRun.conversation_id.in_(conversation_ids),
|
||||
ShippingOrderExtractionRun.attention_generated_at.isnot(None),
|
||||
ShippingOrderExtractionRun.seen_at.is_(None),
|
||||
ShippingOrderProcessingRun.user_id == user_id,
|
||||
ShippingOrderProcessingRun.owner_agent_id == agent_id,
|
||||
ShippingOrderProcessingRun.conversation_id.in_(conversation_ids),
|
||||
ShippingOrderProcessingRun.attention_generated_at.isnot(None),
|
||||
ShippingOrderProcessingRun.seen_at.is_(None),
|
||||
).all()
|
||||
aggregate: dict[str, tuple[int, str]] = {}
|
||||
for conversation_id, status in rows:
|
||||
@@ -1087,30 +1089,75 @@ def get_chat_sessions():
|
||||
@require_agent_permission
|
||||
def delete_all_chat_sessions():
|
||||
"""
|
||||
删除当前用户与当前 Agent 的所有历史会话
|
||||
删除当前用户与当前 Agent 的所有历史会话。
|
||||
|
||||
核心逻辑:批量清理 ChatLog / Feedback / ChatSession;shipping_notice 写审计;
|
||||
返回标准 success envelope。
|
||||
|
||||
Returns:
|
||||
Flask JSON:`{ success, data: { deleted: true } }`。
|
||||
"""
|
||||
from app.core.response import ok
|
||||
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
chat_logs = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id).all()
|
||||
chat_log_ids = [log.id for log in chat_logs]
|
||||
session_count = (
|
||||
db.session.query(ChatSession)
|
||||
.filter_by(user_id=user.id, agent_id=agent.id)
|
||||
.count()
|
||||
)
|
||||
if chat_log_ids:
|
||||
from app.models import GeneralFeedback
|
||||
db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(ChatSession).filter_by(user_id=user.id, agent_id=agent.id).delete(synchronize_session=False)
|
||||
|
||||
if str(getattr(agent, 'code', None) or '').strip() == SHIPPING_NOTICE_AGENT_CODE:
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
append_shipping_audit_event(
|
||||
event_type='conversation_sessions_deleted_all',
|
||||
aggregate_type='chat_session',
|
||||
aggregate_id=f'user:{int(user.id)}:agent:{int(agent.id)}',
|
||||
actor_type='user',
|
||||
actor_id=user.id,
|
||||
owner_user_id=user.id,
|
||||
action='delete_all_chat_sessions',
|
||||
reason_code='user_deleted_all_sessions',
|
||||
before={'session_count': int(session_count), 'chat_log_count': len(chat_log_ids)},
|
||||
after={'deleted': True},
|
||||
metadata={'agent_id': int(agent.id)},
|
||||
source='workspace_api',
|
||||
sensitivity_level='sensitive',
|
||||
request_id=str(getattr(g, 'request_id', '') or '') or None,
|
||||
)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({'status': 'ok'})
|
||||
return ok({'deleted': True, 'session_count': int(session_count)})
|
||||
|
||||
@chat_bp.route('/sessions/<conversation_id>', methods=['DELETE'])
|
||||
@require_agent_permission
|
||||
def delete_chat_session(conversation_id):
|
||||
"""
|
||||
删除指定的会话记录
|
||||
删除指定的会话记录。
|
||||
|
||||
核心逻辑:清理 ChatLog / Feedback;shipping_notice Agent 额外写不可变审计;
|
||||
返回标准 success envelope。
|
||||
|
||||
Args:
|
||||
conversation_id: 会话 ID(路径参数)。
|
||||
|
||||
Returns:
|
||||
Flask JSON:`{ success, data: { deleted: true, conversation_id } }`。
|
||||
"""
|
||||
from app.core.response import ok
|
||||
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
@@ -1134,6 +1181,9 @@ def delete_chat_session(conversation_id):
|
||||
).all()
|
||||
|
||||
chat_log_ids = [log.id for log in chat_logs]
|
||||
session_id_for_audit = str(
|
||||
getattr(session, 'session_id', None) or conversation_id or ''
|
||||
).strip()
|
||||
if chat_log_ids:
|
||||
from app.models import GeneralFeedback
|
||||
db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
@@ -1141,9 +1191,38 @@ def delete_chat_session(conversation_id):
|
||||
db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
if session:
|
||||
db.session.delete(session)
|
||||
|
||||
# [BE-16] 货代会话删除必须留审计;与业务删除同事务提交。
|
||||
if str(getattr(agent, 'code', None) or '').strip() == SHIPPING_NOTICE_AGENT_CODE:
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
append_shipping_audit_event(
|
||||
event_type='conversation_session_deleted',
|
||||
aggregate_type='chat_session',
|
||||
aggregate_id=session_id_for_audit or str(conversation_id),
|
||||
actor_type='user',
|
||||
actor_id=user.id,
|
||||
owner_user_id=user.id,
|
||||
conversation_id=session_id_for_audit or str(conversation_id),
|
||||
action='delete_chat_session',
|
||||
reason_code='user_deleted_session',
|
||||
before={
|
||||
'conversation_id': session_id_for_audit or str(conversation_id),
|
||||
'chat_log_count': len(chat_log_ids),
|
||||
},
|
||||
after={'deleted': True},
|
||||
metadata={'agent_id': int(agent.id), 'chat_log_count': len(chat_log_ids)},
|
||||
source='workspace_api',
|
||||
sensitivity_level='sensitive',
|
||||
request_id=str(getattr(g, 'request_id', '') or '') or None,
|
||||
)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({'status': 'ok'})
|
||||
return ok({
|
||||
'deleted': True,
|
||||
'conversation_id': session_id_for_audit or str(conversation_id),
|
||||
})
|
||||
|
||||
@chat_bp.route('/messages', methods=['GET'])
|
||||
@require_agent_permission
|
||||
@@ -1180,11 +1259,11 @@ def get_chat_messages():
|
||||
if run_nos:
|
||||
order_extraction_runs = {
|
||||
run.run_no: run
|
||||
for run in db.session.query(ShippingOrderExtractionRun).filter(
|
||||
ShippingOrderExtractionRun.user_id == g.current_user.id,
|
||||
ShippingOrderExtractionRun.owner_agent_id == g.current_agent.id,
|
||||
ShippingOrderExtractionRun.conversation_id == (session.session_id if session else conversation_id),
|
||||
ShippingOrderExtractionRun.run_no.in_(run_nos),
|
||||
for run in db.session.query(ShippingOrderProcessingRun).filter(
|
||||
ShippingOrderProcessingRun.user_id == g.current_user.id,
|
||||
ShippingOrderProcessingRun.owner_agent_id == g.current_agent.id,
|
||||
ShippingOrderProcessingRun.conversation_id == (session.session_id if session else conversation_id),
|
||||
ShippingOrderProcessingRun.run_no.in_(run_nos),
|
||||
).all()
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
api/shipping_notice_tools.py
|
||||
|
||||
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
|
||||
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url。
|
||||
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url、
|
||||
batch_legacy_removed(create_batch 410)。
|
||||
逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError;
|
||||
`_payload()` 剥离 body 中的操作人伪造字段,禁止集成密钥冒充用户写审计。
|
||||
`_payload()` 剥离 body 中的操作人伪造字段,禁止集成密钥冒充用户写审计;
|
||||
co8 后 /tools/create_batch 固定 410,改走 order-extraction-submissions。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -24,17 +26,11 @@ from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
get_batch_by_no,
|
||||
get_focus_task_for_batch,
|
||||
get_task_by_ref,
|
||||
get_task_in_batch,
|
||||
list_batch_task_summaries,
|
||||
resolve_task_export_download,
|
||||
serialize_batch_summary,
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import switch_batch_focus
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import record_rpa_worker_heartbeat
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
@@ -205,20 +201,15 @@ def tool_confirm_temporary_inventory_use():
|
||||
@shipping_notice_bp.route('/tools/create_batch', methods=['POST'])
|
||||
def tool_create_batch():
|
||||
"""
|
||||
创建或复用发货批次。
|
||||
【AI 触发时机】:仅供 Hxops 内部建批链路调用;不是 Dify 画布正式入口。
|
||||
历史建批 Tool(已下线)。
|
||||
【AI 触发时机】:禁止调用;shipping_batches 已物理删除,请改走 order-extraction-submissions。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
payload = _payload()
|
||||
if isinstance(payload.get('notice_items'), list) and payload.get('notice_items'):
|
||||
return jsonify(shipping_tools.create_batch_tasks(payload))
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
if batch_no:
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if batch:
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已复用批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
|
||||
batch, _created = shipping_tools.create_batch(payload)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已创建批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
raise_shipping_batches_removed(action='tools.create_batch')
|
||||
|
||||
@shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST'])
|
||||
def tool_update_notice_fields():
|
||||
@@ -334,44 +325,28 @@ def tool_get_task_status():
|
||||
@shipping_notice_bp.route('/tools/get_batch_status', methods=['POST'])
|
||||
def tool_get_batch_status():
|
||||
"""
|
||||
查询批次状态。
|
||||
【AI 触发时机】:当用户关注整批任务处理进度,或 Agent 需要查看当前 focus task 与批次摘要时调用。
|
||||
历史批次状态查询(已下线)。
|
||||
【AI 触发时机】:禁止调用;请改用 get_task_status 或 shipping-processing。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
payload = _payload()
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
if not batch_no:
|
||||
raise ValidationError("batch_no is required")
|
||||
_require_read_capability(payload, scope='get_batch_status', batch_no=batch_no)
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if not batch:
|
||||
raise NotFoundError("batch not found")
|
||||
focus_task = get_focus_task_for_batch(batch_no, batch.user_id or 0) if batch.user_id is not None else None
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已获取批次 {batch.batch_no} 状态', 'data': {**serialize_batch_summary(batch), 'focus_task': serialize_task_summary(focus_task) if focus_task else None, 'tasks': list_batch_task_summaries(batch)}})
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
raise_shipping_batches_removed(action='tools.get_batch_status')
|
||||
|
||||
@shipping_notice_bp.route('/tools/switch_focus_task', methods=['POST'])
|
||||
def tool_switch_focus_task():
|
||||
"""
|
||||
切换批次当前焦点任务。
|
||||
【AI 触发时机】:当前仅保留给 Hxops 内部切票能力;不属于 Dify 正式导出 Tool。
|
||||
历史批次焦点切换(已下线)。
|
||||
【AI 触发时机】:禁止调用;shipping_batches 已物理删除。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
payload = _payload()
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
task_no = str(payload.get('task_no') or payload.get('target_task_no') or '').strip()
|
||||
if not batch_no or not task_no:
|
||||
raise ValidationError("batch_no and task_no are required")
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if not batch:
|
||||
raise NotFoundError("batch not found")
|
||||
task = get_task_in_batch(batch_no, task_no)
|
||||
if not task:
|
||||
raise NotFoundError("task not found in batch")
|
||||
switch_batch_focus(
|
||||
batch,
|
||||
task,
|
||||
source="tool_api",
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'task_no': task.task_no, 'message': f'已切换当前任务到 {task.task_no}', 'data': {'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}})
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
raise_shipping_batches_removed(action='tools.switch_focus_task')
|
||||
|
||||
@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST'])
|
||||
def rpa_worker_heartbeat():
|
||||
|
||||
@@ -3,9 +3,11 @@ backend/app/api/workspace/shipping_notice.py
|
||||
|
||||
用途:HXOPS 工作台发货通知用户态 API(任务处理工作台为履约写操作入口;Chat 仅通知/上传)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.core.response.ok、shipping_notice.query_service /
|
||||
tools / notice_upload / ui_state、workflow_progress_projection / workflow_ledger_service。
|
||||
tools / notice_upload / ui_state、shipping_processing_projection、batch_legacy_removed。
|
||||
逻辑:薄路由层鉴权与参数校验;成功响应统一走 `_ok`/`ok` envelope;写接口保留乐观锁、幂等键与
|
||||
统一 AppError;人工上传强制证据资产;Chat Turn 履约写路径已废弃,请改走本 Blueprint。
|
||||
统一 AppError;人工上传强制证据资产;Chat Turn 履约写路径已废弃,请改走本 Blueprint;
|
||||
`/shipping-processing/*` 为统一进度读源;co8 后 `/shipping-batches*` 写 410 / 读空或 404;
|
||||
Workflow ledger 路由已整段删除,进度请读 shipping-processing / Run API。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -19,27 +21,22 @@ from app import db
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import ShippingBatch, ShippingNoticeIntake, ShippingOrderExtraction, ShippingTask
|
||||
from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice
|
||||
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
|
||||
from app.services.shipping_notice.constants import (
|
||||
AUTO_CHAIN_FALLBACK,
|
||||
CP_EXPORT_GENERATED,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import switch_batch_focus
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
count_my_todos,
|
||||
get_batch_for_user,
|
||||
get_conversation_batch_workspace,
|
||||
get_focus_task_for_batch,
|
||||
get_task_for_user,
|
||||
list_batches_for_user,
|
||||
list_my_todos,
|
||||
list_tasks_page_for_user,
|
||||
list_tasks_for_batch,
|
||||
resolve_task_export_download,
|
||||
serialize_batch_summary,
|
||||
serialize_task_detail,
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
@@ -51,7 +48,7 @@ from app.services.shipping_notice.task_disposition_service import (
|
||||
purge_task_permanently,
|
||||
restore_task_from_recycle_bin,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
from app.services.shipping_notice.customer_identity_gate import (
|
||||
confirm_task_customer,
|
||||
list_customer_options,
|
||||
@@ -165,7 +162,7 @@ def _batch_task_nos(data: dict) -> list[str]:
|
||||
return normalized
|
||||
|
||||
|
||||
def _can_dispose_task(user, task: ShippingTask) -> bool:
|
||||
def _can_dispose_task(user, task: ShippingNotice) -> bool:
|
||||
"""管理员可跨用户处置;普通用户仅可处置自己名下或未归属任务。"""
|
||||
return str(getattr(user, 'role', '')).lower() == 'admin' or task.user_id in {None, user.id}
|
||||
|
||||
@@ -259,12 +256,102 @@ def workspace_batch_restore_shipping_tasks():
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET'])
|
||||
def workspace_shipping_batches():
|
||||
"""列出当前用户的发货批次摘要。"""
|
||||
"""列出当前用户的发货批次摘要;co8 后 shipping_batches 已 DROP,恒返回空列表。"""
|
||||
user = _require_user()
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return _ok(list_batches_for_user(user.id, limit=limit))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST'])
|
||||
def workspace_create_shipping_batch_from_notices():
|
||||
"""
|
||||
历史:多附件建批(已下线)。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
_require_user()
|
||||
raise_shipping_batches_removed(action='workspace.create_from_notices')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>', methods=['GET'])
|
||||
def workspace_shipping_batch_detail(batch_no: str):
|
||||
"""批次详情;shipping_batches 已 DROP,恒 404。"""
|
||||
_require_user()
|
||||
del batch_no
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/ui-state', methods=['GET'])
|
||||
def workspace_shipping_batch_ui_state(batch_no: str):
|
||||
"""批次 UI State;shipping_batches 已 DROP,恒 404。"""
|
||||
_require_user()
|
||||
del batch_no
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/tasks', methods=['GET'])
|
||||
def workspace_shipping_batch_tasks(batch_no: str):
|
||||
"""批次任务列表;shipping_batches 已 DROP,恒 404。"""
|
||||
_require_user()
|
||||
del batch_no
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET'])
|
||||
def workspace_shipping_batch_focus_task(batch_no: str):
|
||||
"""批次焦点任务;shipping_batches 已 DROP,恒 404。"""
|
||||
_require_user()
|
||||
del batch_no
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['POST'])
|
||||
def workspace_switch_shipping_batch_focus_task(batch_no: str):
|
||||
"""
|
||||
切换批次焦点(已下线)。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
_require_user()
|
||||
del batch_no
|
||||
raise_shipping_batches_removed(action='workspace.switch_batch_focus')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-intakes', methods=['POST'])
|
||||
def workspace_create_shipping_batch_from_intakes():
|
||||
"""
|
||||
历史:从 Intake 建批(已下线)。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
_require_user()
|
||||
raise_shipping_batches_removed(action='workspace.create_from_intakes')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/retry-pending', methods=['POST'])
|
||||
def workspace_retry_shipping_batch_pending(batch_no: str):
|
||||
"""
|
||||
历史:重试批次待推进任务(已下线)。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
_require_user()
|
||||
del batch_no
|
||||
raise_shipping_batches_removed(action='workspace.retry_batch_pending')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST'])
|
||||
def workspace_shipping_export_archive():
|
||||
"""按批次或显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。"""
|
||||
@@ -282,6 +369,25 @@ def workspace_shipping_export_archive():
|
||||
return response
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['POST'])
|
||||
def workspace_create_shipping_task():
|
||||
"""创建单个发货任务,适用于手工录入或聊天入口先建单。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {'user_id': user.id}
|
||||
source_type = str(data.get('source_type') or '').strip()
|
||||
if source_type:
|
||||
payload['source_type'] = source_type
|
||||
conversation_id = str(data.get('conversation_id') or '').strip()
|
||||
if conversation_id:
|
||||
payload['conversation_id'] = conversation_id
|
||||
raw_content = str(data.get('raw_content') or '').strip()
|
||||
if raw_content:
|
||||
payload['raw_content'] = raw_content
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return _ok(shipping_tools.create_task(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-customers', methods=['GET'])
|
||||
def workspace_shipping_customers():
|
||||
"""列出可供当前业务用户确认的启用标准客户。"""
|
||||
@@ -323,10 +429,10 @@ def workspace_confirm_order_customer_match(extraction_id: int, role: str):
|
||||
user = _require_user()
|
||||
extraction = (
|
||||
db.session.query(ShippingOrderExtraction)
|
||||
.join(ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingOrderExtraction.intake_id)
|
||||
.join(ShippingOrderIntake, ShippingOrderIntake.id == ShippingOrderExtraction.intake_id)
|
||||
.filter(
|
||||
ShippingOrderExtraction.id == extraction_id,
|
||||
ShippingNoticeIntake.user_id == user.id,
|
||||
ShippingOrderIntake.user_id == user.id,
|
||||
)
|
||||
.one_or_none()
|
||||
)
|
||||
@@ -357,144 +463,10 @@ def workspace_confirm_order_customer_match(extraction_id: int, role: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-conversations/<conversation_id>/batch-workspace', methods=['GET'])
|
||||
def workspace_shipping_conversation_batch_workspace(conversation_id: str):
|
||||
"""返回一个 Agent 会话下的多批次执行工作台快照。"""
|
||||
"""返回一个 Agent 会话下的多批次执行工作台快照;co8 后恒为空工作台。"""
|
||||
user = _require_user()
|
||||
return _ok(get_conversation_batch_workspace(conversation_id, user.id))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST'])
|
||||
def workspace_create_shipping_batch_from_notices():
|
||||
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
|
||||
user = _require_user()
|
||||
uploads = request.files.getlist('files')
|
||||
if not uploads:
|
||||
single = request.files.get('file')
|
||||
if single:
|
||||
uploads = [single]
|
||||
if not uploads:
|
||||
raise ValidationError('files is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.batch_from_notices import (
|
||||
create_shipping_batch_from_notice_items,
|
||||
intake_notice_uploads_for_batch,
|
||||
)
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
normalize_create_idempotency_key,
|
||||
warn_missing_create_idempotency_key,
|
||||
)
|
||||
from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads
|
||||
conversation_id = str(request.form.get('conversation_id') or '').strip()
|
||||
idempotency_key = normalize_create_idempotency_key(
|
||||
request.headers.get('Idempotency-Key') or request.form.get('idempotency_key')
|
||||
)
|
||||
if not idempotency_key:
|
||||
warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_notices')
|
||||
temp_request_id = str(getattr(g, 'request_id', None) or uuid.uuid4().hex)
|
||||
try:
|
||||
notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads)
|
||||
finally:
|
||||
cleanup_temp_notice_uploads(temp_request_id)
|
||||
|
||||
created = create_shipping_batch_from_notice_items(
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id or None,
|
||||
notice_items=notice_items,
|
||||
file_summary=file_summary,
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
return _ok(created)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>', methods=['GET'])
|
||||
def workspace_shipping_batch_detail(batch_no: str):
|
||||
"""
|
||||
返回批次详情与聚合 UI State。
|
||||
|
||||
核心逻辑:工作台详情页与独立 `/ui-state` 端点共享同一份批次状态构建结果,
|
||||
避免批次摘要、焦点任务和任务卡片在不同接口里各自推导造成漂移。
|
||||
"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_batch_ui_state(batch))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/ui-state', methods=['GET'])
|
||||
def workspace_shipping_batch_ui_state(batch_no: str):
|
||||
"""
|
||||
返回批次级 UI State。
|
||||
|
||||
核心逻辑:供右侧工作台、步骤条与批次任务卡统一读取同源状态,
|
||||
保持与批次详情接口返回的 `focus_task_ui_state/tasks[].ui_state` 完全一致。
|
||||
"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_batch_ui_state(batch))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/tasks', methods=['GET'])
|
||||
def workspace_shipping_batch_tasks(batch_no: str):
|
||||
"""返回指定批次下的任务列表。"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(list_tasks_for_batch(batch_no, user.id))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET'])
|
||||
def workspace_shipping_batch_focus_task(batch_no: str):
|
||||
"""返回指定批次当前焦点任务的摘要。"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
if not focus_task:
|
||||
raise NotFoundError('Focus task not found')
|
||||
return _ok(serialize_task_summary(focus_task))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['POST'])
|
||||
def workspace_switch_shipping_batch_focus_task(batch_no: str):
|
||||
"""切换批次当前焦点任务,供工作台在同批次任务间跳转。"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_no = str(data.get('task_no') or data.get('target_task_no') or '').strip()
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if not task_no:
|
||||
raise ValidationError('task_no is required')
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task or task.batch_id != batch.id:
|
||||
raise NotFoundError('Task not found in batch')
|
||||
switch_batch_focus(
|
||||
batch,
|
||||
task,
|
||||
source='workspace_api',
|
||||
comment=comment or None,
|
||||
extra={'actor_user_id': user.id},
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok({'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)})
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['POST'])
|
||||
def workspace_create_shipping_task():
|
||||
"""创建单个发货任务,适用于手工录入或聊天入口先建单。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {'user_id': user.id}
|
||||
source_type = str(data.get('source_type') or '').strip()
|
||||
if source_type:
|
||||
payload['source_type'] = source_type
|
||||
conversation_id = str(data.get('conversation_id') or '').strip()
|
||||
if conversation_id:
|
||||
payload['conversation_id'] = conversation_id
|
||||
raw_content = str(data.get('raw_content') or '').strip()
|
||||
if raw_content:
|
||||
payload['raw_content'] = raw_content
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return _ok(shipping_tools.create_task(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
|
||||
def workspace_create_shipping_task_from_notice():
|
||||
@@ -527,7 +499,7 @@ def workspace_create_shipping_task_from_notice():
|
||||
if not intake.accepted:
|
||||
# 旧 action_buttons 业务调用清零:仅保留 human_options 文案提示,不再下发可点击恢复按钮。
|
||||
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': []})
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.raw_content = intake.text
|
||||
task.source_file_name = intake.filename or task.source_file_name
|
||||
@@ -589,6 +561,38 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/audit-timeline', methods=['GET'])
|
||||
def workspace_list_shipping_task_audit_timeline(task_no: str):
|
||||
"""业务用户 Task 审计时间线(统一 ShippingAuditEvent,无敏感快照)。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
from app.services.shipping_notice.audit_query_service import list_task_audit_timeline
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
|
||||
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
page = request.args.get('page', 1, type=int)
|
||||
page_size = request.args.get('page_size', 50, type=int)
|
||||
payload = list_task_audit_timeline(
|
||||
user_id=user.id,
|
||||
task_no=str(task.task_no),
|
||||
task=task,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
record_access_audit(
|
||||
action='view_task_audit_trail',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=str(task.task_no),
|
||||
actor_id=user.id,
|
||||
task_no=str(task.task_no),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/ui-state', methods=['GET'])
|
||||
def workspace_shipping_task_ui_state(task_no: str):
|
||||
"""
|
||||
@@ -755,7 +759,7 @@ def workspace_complete_shipping_freight_cancellation(cancellation_id: int):
|
||||
cancellation = ShippingFreightCancellation.query.filter_by(id=cancellation_id).one_or_none()
|
||||
if cancellation is None:
|
||||
raise NotFoundError('Not found')
|
||||
old_task = db.session.get(ShippingTask, cancellation.old_task_id)
|
||||
old_task = db.session.get(ShippingNotice, cancellation.old_task_id)
|
||||
if old_task is None or int(old_task.user_id or 0) != int(user.id):
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice.freight_cancellation_service import complete_freight_cancellation
|
||||
@@ -1062,7 +1066,7 @@ def workspace_shipping_task_export(task_no: str):
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['GET'])
|
||||
def workspace_list_shipping_notice_intakes():
|
||||
def workspace_list_shipping_order_intakes():
|
||||
"""列出当前会话下未消费的活跃接入记录。"""
|
||||
user = _require_user()
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip() or None
|
||||
@@ -1129,6 +1133,159 @@ def workspace_create_shipping_order_extraction_run():
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-submissions', methods=['POST'])
|
||||
def workspace_create_order_extraction_submission():
|
||||
"""
|
||||
统一订单抽取提交:后端事务内裁决追加或新建用户可见任务。
|
||||
|
||||
核心逻辑:校验 submission_id / intake_nos → 委托 submit_order_extraction →
|
||||
返回 decision + processing 投影;前端不得本地选择 append/create。
|
||||
"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True)
|
||||
if body is None:
|
||||
body = {}
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('JSON body must be an object')
|
||||
try:
|
||||
agent_id = int(body.get('agent_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'agent_id is required',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_AGENT_INVALID',
|
||||
) from exc
|
||||
conversation_id = str(body.get('conversation_id') or '').strip()
|
||||
submission_id = str(body.get('submission_id') or '').strip()
|
||||
if not submission_id:
|
||||
raise ValidationError(
|
||||
'submission_id is required',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_SUBMISSION_ID_INVALID',
|
||||
)
|
||||
intake_nos = body.get('intake_nos')
|
||||
if not isinstance(intake_nos, list):
|
||||
raise ValidationError(
|
||||
'intake_nos must be a list',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_INTAKES_INVALID',
|
||||
)
|
||||
upload_batch_id = str(body.get('upload_batch_id') or '').strip() or None
|
||||
composer_context_id = str(body.get('composer_context_id') or '').strip() or None
|
||||
focused_user_task_no = str(body.get('focused_user_task_no') or '').strip() or None
|
||||
|
||||
from app.services.shipping_notice.order_extraction_run_service import submit_order_extraction
|
||||
|
||||
payload = submit_order_extraction(
|
||||
user=user,
|
||||
agent_id=agent_id,
|
||||
conversation_id=conversation_id,
|
||||
intake_nos=intake_nos,
|
||||
submission_id=submission_id,
|
||||
composer_context_id=composer_context_id,
|
||||
focused_user_task_no=focused_user_task_no,
|
||||
upload_batch_id=upload_batch_id,
|
||||
)
|
||||
db.session.commit()
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None), status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-processing/conversations/<conversation_id>',
|
||||
methods=['GET'],
|
||||
)
|
||||
def workspace_get_shipping_processing_conversation(conversation_id: str):
|
||||
"""
|
||||
拉取会话级统一 ShippingProcessingProjection(唯一进度读源)。
|
||||
|
||||
核心逻辑:委托 project_conversation_processing_items;含 order_intake + order_task;
|
||||
旧 /conversations/.../processing GET 已移除(无历史兼容)。
|
||||
"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.shipping_processing_projection import (
|
||||
project_conversation_processing_items,
|
||||
)
|
||||
|
||||
agent_raw = request.args.get('agent_id')
|
||||
agent_id = int(agent_raw) if agent_raw not in (None, '') else None
|
||||
payload = project_conversation_processing_items(
|
||||
user_id=user.id,
|
||||
conversation_id=str(conversation_id or '').strip(),
|
||||
agent_id=agent_id,
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-processing/work-items/<work_item_type>/<work_item_no>',
|
||||
methods=['GET'],
|
||||
)
|
||||
def workspace_get_shipping_processing_work_item(work_item_type: str, work_item_no: str):
|
||||
"""
|
||||
按工作项类型与编号拉取单个统一 ShippingProcessingProjection。
|
||||
|
||||
核心逻辑:委托 get_shipping_processing_work_item;鉴权与 conversation processing 相同。
|
||||
"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.shipping_processing_projection import (
|
||||
get_shipping_processing_work_item,
|
||||
)
|
||||
|
||||
payload = get_shipping_processing_work_item(
|
||||
user_id=user.id,
|
||||
work_item_type=str(work_item_type or '').strip(),
|
||||
work_item_no=str(work_item_no or '').strip(),
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/conversation-tasks/<task_no>/focus',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_focus_conversation_task(task_no: str):
|
||||
"""标记用户可见任务为当前焦点,并返回刷新后的 processing。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body and not isinstance(body, dict):
|
||||
raise ValidationError('Request body must be an object')
|
||||
conversation_id = str(body.get('conversation_id') or '').strip()
|
||||
if not conversation_id:
|
||||
raise ValidationError('conversation_id is required')
|
||||
from app.services.shipping_notice.order_extraction_run_service import focus_conversation_task
|
||||
|
||||
payload = focus_conversation_task(
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
task_no=task_no,
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/conversation-tasks/<task_no>/viewed',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_mark_conversation_task_viewed(task_no: str):
|
||||
"""标记用户可见任务详情已查看(viewed ≠ 业务已处理)。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body and not isinstance(body, dict):
|
||||
raise ValidationError('Request body must be an object')
|
||||
conversation_id = str(body.get('conversation_id') or '').strip()
|
||||
if not conversation_id:
|
||||
raise ValidationError('conversation_id is required')
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
mark_conversation_task_viewed,
|
||||
)
|
||||
|
||||
payload = mark_conversation_task_viewed(
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
task_no=task_no,
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>', methods=['GET'])
|
||||
def workspace_get_shipping_order_extraction_run(run_no: str):
|
||||
"""查询当前用户的一次订单抽取 Run;正文快照不会暴露给前端;访问留痕。"""
|
||||
@@ -1433,16 +1590,28 @@ def workspace_delete_shipping_order_review_line(case_no: str, line_key: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/validate', methods=['POST'])
|
||||
def workspace_validate_shipping_order_review_draft(case_no: str):
|
||||
"""显式重跑当前草稿校验,供自动保存后的用户可见状态刷新。"""
|
||||
"""显式重跑当前草稿校验,并触发统一恢复协调器(可 auto_gate)。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import validate_draft
|
||||
from app.services.shipping_notice.order_review_resume_service import (
|
||||
attach_resume_outcome,
|
||||
resume_after_review_change,
|
||||
)
|
||||
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='draft_validated')
|
||||
result = validate_draft(
|
||||
user_id=user.id, case_no=case_no, expected_draft_version=payload.get('expected_draft_version'),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
resume = resume_after_review_change(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
trigger='draft_validated',
|
||||
change_type=None,
|
||||
skip_validate=True,
|
||||
allow_auto_create=True,
|
||||
)
|
||||
return _ok(attach_resume_outcome({'case': result}, resume))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
@@ -1594,6 +1763,169 @@ def workspace_confirm_shipping_order_review_customer(case_no: str):
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/reservation/revalidate',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_revalidate_shipping_order_review_reservation(case_no: str):
|
||||
"""
|
||||
显式重校验 Reservation 并触发统一恢复协调。
|
||||
|
||||
Body: expected_draft_version
|
||||
"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
from app.services.shipping_notice.order_review_reservation_service import (
|
||||
revalidate_review_case_reservation,
|
||||
)
|
||||
|
||||
result = revalidate_review_case_reservation(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
expected_draft_version=data.get('expected_draft_version'),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/audit-timeline',
|
||||
methods=['GET'],
|
||||
)
|
||||
def workspace_list_shipping_order_review_audit_timeline(case_no: str):
|
||||
"""业务用户 Case 审计时间线(无敏感快照)。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
from app.services.shipping_notice.audit_query_service import list_review_case_audit_timeline
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
|
||||
case = get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin)
|
||||
page = request.args.get('page', 1, type=int)
|
||||
page_size = request.args.get('page_size', 50, type=int)
|
||||
payload = list_review_case_audit_timeline(
|
||||
user_id=user.id,
|
||||
case_no=str(case.case_no),
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
record_access_audit(
|
||||
action='view_order_review_audit_trail',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(case.case_no),
|
||||
actor_id=user.id,
|
||||
review_case_no=str(case.case_no),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/line-fulfillment/decide',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_decide_shipping_order_review_line_fulfillment(case_no: str):
|
||||
"""
|
||||
写入行级履约决定。
|
||||
|
||||
Body: line_key, decision_code, reason?, expected_draft_version?
|
||||
"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
decide_review_line_fulfillment,
|
||||
)
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
result = decide_review_line_fulfillment(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
line_key=str(data.get('line_key') or ''),
|
||||
decision_code=str(data.get('decision_code') or ''),
|
||||
reason=str(data.get('reason') or '').strip() or None,
|
||||
expected_draft_version=data.get('expected_draft_version'),
|
||||
actor_is_admin=is_admin,
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/line-fulfillment/wave',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_create_shipping_order_review_fulfillment_wave(case_no: str):
|
||||
"""
|
||||
为选中完整明细行创建履约波次 Task。
|
||||
|
||||
Body: line_keys[], expected_draft_version, idempotency_key, reason?
|
||||
与确认建单同样在同事务入队自动推进。
|
||||
"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
from app.services.shipping_notice.order_review_confirmation_service import (
|
||||
finalize_sync_auto_progress_after_commit,
|
||||
resolve_confirm_outcome,
|
||||
schedule_auto_progress_after_review_confirm,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
create_fulfillment_wave,
|
||||
)
|
||||
|
||||
result = create_fulfillment_wave(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
line_keys=list(data.get('line_keys') or []),
|
||||
expected_draft_version=data.get('expected_draft_version'),
|
||||
idempotency_key=data.get('idempotency_key') or request.headers.get('Idempotency-Key'),
|
||||
reason=str(data.get('reason') or '').strip() or None,
|
||||
)
|
||||
progress = schedule_auto_progress_after_review_confirm(
|
||||
task_no=result.get('task_no'),
|
||||
idempotent_replay=bool(result.get('idempotent_replay')),
|
||||
created_by_id=int(user.id),
|
||||
commit=False,
|
||||
)
|
||||
db.session.commit()
|
||||
progress = finalize_sync_auto_progress_after_commit(progress)
|
||||
result = dict(result)
|
||||
result.pop('trigger_auto_progress', None)
|
||||
result['confirm_ok'] = True
|
||||
result['confirm_outcome'] = resolve_confirm_outcome(progress)
|
||||
result['auto_progress'] = progress
|
||||
result['auto_progress_started'] = bool((progress or {}).get('auto_progress_started'))
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/line-fulfillment/close',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_close_shipping_order_review_fulfillment(case_no: str):
|
||||
"""
|
||||
关闭行级或 Case 剩余开放行。
|
||||
|
||||
Body: reason, line_keys?, expected_draft_version?
|
||||
"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
close_remaining_fulfillment,
|
||||
)
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
result = close_remaining_fulfillment(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
reason=str(data.get('reason') or ''),
|
||||
line_keys=list(data.get('line_keys') or []) or None,
|
||||
expected_draft_version=data.get('expected_draft_version'),
|
||||
actor_is_admin=is_admin,
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/duplicate-refresh',
|
||||
methods=['POST'],
|
||||
@@ -2272,132 +2604,6 @@ def workspace_list_shipping_order_extraction_runs():
|
||||
return _ok({'items': [serialize_order_extraction_run(row) for row in rows]})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/workflows', methods=['GET'])
|
||||
def workspace_list_shipping_notice_workflows():
|
||||
"""列出会话开放 Workflow 与 Items;版面阶段 Item 已存在;访问留痕。"""
|
||||
user = _require_user()
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip()
|
||||
if not conversation_id:
|
||||
raise ValidationError('conversation_id is required')
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.workflow_progress_projection import project_conversation_workflows
|
||||
|
||||
payload = project_conversation_workflows(user_id=user.id, conversation_id=conversation_id)
|
||||
record_access_audit(
|
||||
action='view_workflows',
|
||||
aggregate_type='shipping_notice_workflow',
|
||||
aggregate_id=conversation_id,
|
||||
actor_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
metadata={
|
||||
'workflow_count': len(payload.get('workflows') or []),
|
||||
'poll': True,
|
||||
},
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/workflows/<workflow_no>', methods=['GET'])
|
||||
def workspace_get_shipping_notice_workflow(workflow_no: str):
|
||||
"""读取当前用户的 Workflow 详情与 Items;访问留痕。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.workflow_progress_projection import (
|
||||
get_workflow_for_user,
|
||||
serialize_workflow,
|
||||
)
|
||||
|
||||
workflow = get_workflow_for_user(user_id=user.id, workflow_no=workflow_no)
|
||||
payload = serialize_workflow(workflow, user_id=user.id, include_items=True)
|
||||
record_access_audit(
|
||||
action='view_workflow',
|
||||
aggregate_type='shipping_notice_workflow',
|
||||
aggregate_id=str(workflow.workflow_no),
|
||||
actor_id=user.id,
|
||||
conversation_id=workflow.conversation_id,
|
||||
metadata={'status': str(workflow.status or ''), 'poll': True},
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/workflow-items/<item_no>', methods=['GET'])
|
||||
def workspace_get_shipping_notice_workflow_item(item_no: str):
|
||||
"""读取当前用户的 WorkflowItem 详情(含事件);访问留痕。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.workflow_progress_projection import get_workflow_item_dto_for_user
|
||||
|
||||
payload = get_workflow_item_dto_for_user(user_id=user.id, item_no=item_no, include_events=True)
|
||||
record_access_audit(
|
||||
action='view_workflow_item',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id=str(payload.get('item_no') or item_no),
|
||||
actor_id=user.id,
|
||||
conversation_id=str(payload.get('conversation_id') or '') or None,
|
||||
metadata={
|
||||
'lifecycle_status': str(payload.get('lifecycle_status') or ''),
|
||||
'poll': True,
|
||||
},
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/workflow-items/<item_no>/cancel', methods=['POST'])
|
||||
def workspace_cancel_shipping_notice_workflow_item(item_no: str):
|
||||
"""
|
||||
用户取消单个 WorkflowItem。
|
||||
|
||||
核心逻辑:必填 reason;委托 cancel_workflow_item_for_user;返回关闭后的 Item 投影。
|
||||
"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body and not isinstance(body, dict):
|
||||
raise ValidationError('Request body must be an object')
|
||||
from app.services.shipping_notice.workflow_ledger_service import cancel_workflow_item_for_user
|
||||
from app.services.shipping_notice.workflow_progress_projection import serialize_workflow_item
|
||||
|
||||
item = cancel_workflow_item_for_user(
|
||||
user_id=user.id,
|
||||
item_no=item_no,
|
||||
reason=body.get('reason'),
|
||||
expected_lock_version=body.get('expected_lock_version'),
|
||||
request_id=str(getattr(g, 'request_id', '') or '') or None,
|
||||
operation_id=str(body.get('operation_id') or getattr(g, 'request_id', '') or '') or None,
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok({'item': serialize_workflow_item(item, include_events=False)})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/workflow-items/<item_no>/reparse', methods=['POST'])
|
||||
def workspace_reparse_shipping_notice_workflow_item(item_no: str):
|
||||
"""
|
||||
用户对单个 WorkflowItem 发起重试/重新识别。
|
||||
|
||||
核心逻辑:必填 reason;有 Case 走单 PDF 重识别(新 Version);无 Case 且 Run 失败则重试入队;
|
||||
返回最新 Item 投影与 reused 标记。
|
||||
"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body and not isinstance(body, dict):
|
||||
raise ValidationError('Request body must be an object')
|
||||
from app.services.shipping_notice.workflow_ledger_service import reparse_workflow_item_for_user
|
||||
from app.services.shipping_notice.workflow_progress_projection import serialize_workflow_item
|
||||
|
||||
item, reused = reparse_workflow_item_for_user(
|
||||
user_id=user.id,
|
||||
item_no=item_no,
|
||||
reason=body.get('reason'),
|
||||
comment=body.get('comment'),
|
||||
request_id=str(getattr(g, 'request_id', '') or '') or None,
|
||||
operation_id=str(body.get('operation_id') or getattr(g, 'request_id', '') or '') or None,
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok({
|
||||
'item': serialize_workflow_item(item, include_events=False),
|
||||
'reused': bool(reused),
|
||||
})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['POST'])
|
||||
def workspace_create_shipping_notice_intake():
|
||||
"""基于 FileAsset 创建发货通知接入记录并投递预解析任务。"""
|
||||
@@ -2585,47 +2791,3 @@ def workspace_resolve_shipping_notice_candidate(candidate_no: str):
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-intakes', methods=['POST'])
|
||||
def workspace_create_shipping_batch_from_intakes():
|
||||
"""从已解析接入记录确认建批。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('请求体必须为对象')
|
||||
intake_nos = body.get('intake_nos')
|
||||
if not isinstance(intake_nos, list) or not intake_nos:
|
||||
raise ValidationError('intake_nos is required')
|
||||
conversation_id = str(body.get('conversation_id') or '').strip() or None
|
||||
candidate_nos = body.get('candidate_nos')
|
||||
if candidate_nos is not None and not isinstance(candidate_nos, list):
|
||||
raise ValidationError('candidate_nos must be a list')
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
normalize_create_idempotency_key,
|
||||
warn_missing_create_idempotency_key,
|
||||
)
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
|
||||
|
||||
idempotency_key = normalize_create_idempotency_key(
|
||||
request.headers.get('Idempotency-Key') or body.get('idempotency_key')
|
||||
)
|
||||
if not idempotency_key:
|
||||
warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_intakes')
|
||||
result = create_shipping_batch_from_intakes(
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
intake_nos=[str(item) for item in intake_nos],
|
||||
candidate_nos=[str(item) for item in candidate_nos] if isinstance(candidate_nos, list) else None,
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/retry-pending', methods=['POST'])
|
||||
def workspace_retry_shipping_batch_pending(batch_no: str):
|
||||
"""重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
|
||||
return _ok(retry_batch_pending_tasks(batch.batch_no))
|
||||
@@ -235,6 +235,39 @@ class Config:
|
||||
SHIPPING_NOTICE_PROFILE_AUTO_SELECTION_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_PROFILE_AUTO_SELECTION_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
# 阶段四:要求候选模板具备有效版面签名;默认 false,全量重签发布后开启。
|
||||
SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED = (
|
||||
os.getenv('SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED', 'false').lower() == 'true'
|
||||
)
|
||||
# XFA 数据路径 Profile:识别到 xfa_hybrid 即走 xfa_dataset。
|
||||
# 自动建单与坐标路径共用 Schema auto_creation_policy / CQ,无独立 XFA 自动建单开关。
|
||||
SHIPPING_NOTICE_XFA_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_XFA_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_XFA_SHADOW_MODE = (
|
||||
os.getenv('SHIPPING_NOTICE_XFA_SHADOW_MODE', 'false').lower() == 'true'
|
||||
)
|
||||
# 客户 / Profile checksum / 场景白名单:空客户或空 checksum 对自动建单 fail-closed。
|
||||
SHIPPING_NOTICE_XFA_CUSTOMER_ALLOWLIST = os.getenv('SHIPPING_NOTICE_XFA_CUSTOMER_ALLOWLIST') or ''
|
||||
SHIPPING_NOTICE_XFA_PROFILE_CHECKSUM_ALLOWLIST = (
|
||||
os.getenv('SHIPPING_NOTICE_XFA_PROFILE_CHECKSUM_ALLOWLIST') or ''
|
||||
)
|
||||
SHIPPING_NOTICE_XFA_SCENARIO_ALLOWLIST = (
|
||||
os.getenv('SHIPPING_NOTICE_XFA_SCENARIO_ALLOWLIST') or 'shipping_notice_order'
|
||||
)
|
||||
SHIPPING_NOTICE_XFA_MAX_PDF_BYTES = int(
|
||||
os.getenv('SHIPPING_NOTICE_XFA_MAX_PDF_BYTES') or str(20 * 1024 * 1024)
|
||||
)
|
||||
SHIPPING_NOTICE_XFA_MAX_PACKET_BYTES = int(
|
||||
os.getenv('SHIPPING_NOTICE_XFA_MAX_PACKET_BYTES') or str(10 * 1024 * 1024)
|
||||
)
|
||||
SHIPPING_NOTICE_XFA_MAX_XML_DEPTH = int(os.getenv('SHIPPING_NOTICE_XFA_MAX_XML_DEPTH') or '64')
|
||||
SHIPPING_NOTICE_XFA_MAX_XML_NODES = int(os.getenv('SHIPPING_NOTICE_XFA_MAX_XML_NODES') or '100000')
|
||||
SHIPPING_NOTICE_XFA_MAX_LINE_ROWS = int(os.getenv('SHIPPING_NOTICE_XFA_MAX_LINE_ROWS') or '2000')
|
||||
SHIPPING_NOTICE_XFA_PARSE_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_XFA_PARSE_TIMEOUT_SECONDS') or '30'
|
||||
)
|
||||
SHIPPING_NOTICE_XFA_MAX_RETRIES = int(os.getenv('SHIPPING_NOTICE_XFA_MAX_RETRIES') or '2')
|
||||
SHIPPING_NOTICE_LLM_REVIEW_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_LLM_REVIEW_ENABLED', 'false').lower() == 'true'
|
||||
)
|
||||
@@ -259,7 +292,7 @@ class Config:
|
||||
os.getenv('SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED', 'false').lower() == 'true'
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
# 自动确认必须同时满足人工标注样本量和准确率门禁,避免仅凭开关放大解析误识别。
|
||||
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES = int(
|
||||
@@ -521,7 +554,7 @@ class Config:
|
||||
os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS', '300')
|
||||
)
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE = int(
|
||||
os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', '4')
|
||||
os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', '10')
|
||||
)
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY = int(
|
||||
os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY', '2')
|
||||
@@ -600,4 +633,3 @@ config = {
|
||||
'production': ProductionConfig,
|
||||
'default': DevelopmentConfig,
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_document_layout.py
|
||||
|
||||
用途:独立执行单份 ShippingNoticeDocument 的 MinerU 布局解析任务。
|
||||
用途:独立执行单份 ShippingOrderDocument 的 MinerU 布局解析任务。
|
||||
依赖:Layout lifecycle/runtime、FileAsset、通用 Job queue、audit_service、workflow_ledger(尽力引用)。
|
||||
逻辑:按 job attempt 领取版本 lease,读取对象存储调用 MinerU;收口时旧 lease 无权覆盖新版本;
|
||||
起止与异常轻量写统一审计(若能定位 WorkflowItem 则带软引用)。
|
||||
@@ -144,13 +144,75 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
if job.started_at and job.created_at else 0,
|
||||
'asset_read_ms': round((perf_counter() - asset_started) * 1000),
|
||||
}
|
||||
snapshot = build_mineru_table_snapshot(
|
||||
filename=str(document.filename or asset.original_filename or 'document.pdf'),
|
||||
content=content,
|
||||
document_id=document.id,
|
||||
content_hash=document.content_hash,
|
||||
timings=timings,
|
||||
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_contract import default_xfa_resource_limits
|
||||
|
||||
xfa_started = perf_counter()
|
||||
xfa_outcome = None
|
||||
if str(document.filename or '').lower().endswith('.pdf') and content.startswith(b'%PDF'):
|
||||
_layout_job_audit(
|
||||
event_type='xfa_parse_started',
|
||||
job=job,
|
||||
version=version,
|
||||
metadata={'document_id': int(document.id)},
|
||||
)
|
||||
xfa_outcome = analyze_xfa_pdf(content, limits=default_xfa_resource_limits())
|
||||
timings['xfa_analysis_ms'] = round((perf_counter() - xfa_started) * 1000)
|
||||
|
||||
snapshot = None
|
||||
if (
|
||||
xfa_outcome is not None
|
||||
and xfa_outcome.packet_result is not None
|
||||
and xfa_outcome.packet_result.document_kind not in {'plain_pdf', 'acroform'}
|
||||
):
|
||||
snapshot = dict(xfa_outcome.snapshot)
|
||||
persist_xfa_structure_analysis(
|
||||
document_id=int(document.id),
|
||||
layout_version_id=int(version.id),
|
||||
source_content_hash=str(document.content_hash or ''),
|
||||
outcome=xfa_outcome,
|
||||
)
|
||||
if xfa_outcome.error_code == 'XFA_UNSAFE_XML':
|
||||
_layout_job_audit(
|
||||
event_type='xfa_parse_rejected_unsafe',
|
||||
job=job,
|
||||
version=version,
|
||||
result='failure',
|
||||
error_code=xfa_outcome.error_code,
|
||||
)
|
||||
elif snapshot.get('status') == 'ready':
|
||||
_layout_job_audit(
|
||||
event_type='xfa_structure_analysis_ready',
|
||||
job=job,
|
||||
version=version,
|
||||
metadata={
|
||||
'document_kind': snapshot.get('document_kind'),
|
||||
'structure_analysis_id': (
|
||||
(snapshot.get('xfa_capability') or {}).get('structure_analysis_id')
|
||||
),
|
||||
},
|
||||
)
|
||||
_layout_job_audit(event_type='xfa_parse_completed', job=job, version=version)
|
||||
else:
|
||||
_layout_job_audit(
|
||||
event_type='xfa_parse_failed',
|
||||
job=job,
|
||||
version=version,
|
||||
result='failure',
|
||||
error_code=xfa_outcome.error_code,
|
||||
metadata={'route_reason': xfa_outcome.route_reason},
|
||||
)
|
||||
if snapshot is None:
|
||||
snapshot = build_mineru_table_snapshot(
|
||||
filename=str(document.filename or asset.original_filename or 'document.pdf'),
|
||||
content=content,
|
||||
document_id=document.id,
|
||||
content_hash=document.content_hash,
|
||||
timings=timings,
|
||||
)
|
||||
timings['snapshot_build_ms'] = round((perf_counter() - total_started) * 1000)
|
||||
if snapshot is None:
|
||||
snapshot = {
|
||||
@@ -170,7 +232,8 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
)
|
||||
finish_job(
|
||||
job.id, result={
|
||||
'status': str(snapshot.get('status') or 'failed'),
|
||||
'status': final_status,
|
||||
'provider_status': str(snapshot.get('status') or 'failed'),
|
||||
'timings': {key: int(value) for key, value in timings.items()},
|
||||
},
|
||||
message=(
|
||||
@@ -197,7 +260,7 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
event_type='document_layout_job_failed',
|
||||
job=job,
|
||||
version=version,
|
||||
result='error',
|
||||
result='failure',
|
||||
error_code=LAYOUT_JOB_ERROR,
|
||||
metadata={'error': str(exc)[:200]},
|
||||
)
|
||||
|
||||
@@ -21,7 +21,7 @@ from app.jobs.context import JobContext
|
||||
from app.jobs.queue import fail_job, finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import FileAsset, Job, ShippingNoticeIntake
|
||||
from app.models import FileAsset, Job, ShippingOrderIntake
|
||||
from app.services.shipping_notice.intake_parse_workflow import (
|
||||
fail_intake_with_stage2_cleanup,
|
||||
run_intake_parse,
|
||||
@@ -69,7 +69,7 @@ def _claim_intake_for_parsing(
|
||||
*,
|
||||
job_id: int | None,
|
||||
owned_attempt: int | None,
|
||||
) -> tuple[ShippingNoticeIntake, str] | None:
|
||||
) -> tuple[ShippingOrderIntake, str] | None:
|
||||
"""
|
||||
原子领取 Intake 并轮转 parse_lease。
|
||||
|
||||
@@ -81,13 +81,13 @@ def _claim_intake_for_parsing(
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
lease = _build_parse_lease(job_id=job_id, owned_attempt=owned_attempt)
|
||||
claim_predicate = ShippingNoticeIntake.parse_status.in_(tuple(_CLAIMABLE_STATUSES))
|
||||
claim_predicate = ShippingOrderIntake.parse_status.in_(tuple(_CLAIMABLE_STATUSES))
|
||||
if job_id is not None:
|
||||
claim_predicate = or_(
|
||||
claim_predicate,
|
||||
and_(
|
||||
ShippingNoticeIntake.parse_status == 'parsing',
|
||||
ShippingNoticeIntake.parse_job_id == int(job_id),
|
||||
ShippingOrderIntake.parse_status == 'parsing',
|
||||
ShippingOrderIntake.parse_job_id == int(job_id),
|
||||
),
|
||||
)
|
||||
values: dict = {
|
||||
@@ -98,9 +98,9 @@ def _claim_intake_for_parsing(
|
||||
if job_id is not None:
|
||||
values['parse_job_id'] = int(job_id)
|
||||
stmt = (
|
||||
update(ShippingNoticeIntake)
|
||||
update(ShippingOrderIntake)
|
||||
.where(
|
||||
ShippingNoticeIntake.intake_no == intake_no,
|
||||
ShippingOrderIntake.intake_no == intake_no,
|
||||
claim_predicate,
|
||||
)
|
||||
.values(**values)
|
||||
@@ -111,7 +111,7 @@ def _claim_intake_for_parsing(
|
||||
return None
|
||||
db.session.commit()
|
||||
intake = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter_by(intake_no=intake_no)
|
||||
.first()
|
||||
)
|
||||
@@ -156,7 +156,7 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
|
||||
)
|
||||
return
|
||||
|
||||
intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first()
|
||||
intake = db.session.query(ShippingOrderIntake).filter_by(intake_no=intake_no).first()
|
||||
if not intake:
|
||||
if job_id is not None:
|
||||
fail_job(
|
||||
@@ -198,7 +198,7 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
|
||||
intake_no, job_id=job_id, owned_attempt=owned_attempt
|
||||
)
|
||||
if claimed is None:
|
||||
current = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first()
|
||||
current = db.session.query(ShippingOrderIntake).filter_by(intake_no=intake_no).first()
|
||||
if job_id is not None:
|
||||
finish_job(
|
||||
job_id,
|
||||
|
||||
@@ -3,9 +3,12 @@ backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
|
||||
用途:消费订单抽取 Run,使用固定模板/通用确定性解析并持久化可复核结果。
|
||||
依赖:Job queue、冻结 Run/Plan、确定性路由和解析、统一审计服务、版面排程、
|
||||
ensure_workflow_items_for_run(物化后兜底建 Item)。
|
||||
ensure_workflow_items_for_run(物化后兜底建 Item)、order_extraction_merge、
|
||||
order_supplement_merge(仅 eml)。
|
||||
逻辑:物化附件与排版面 Job 均在主 try 内执行;每个 Unit 按 STP route_decision
|
||||
直通或落 provisional;needs_review 剥离验收标记;不调用 Dify 主链。
|
||||
阶段 2:direct_pdf 跳过 email_supplements 与 ORDER_EMAIL_ADJUDICATION_*;
|
||||
合并默认 keep_primary_documents_separate(多 PDF 各成 Candidate)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,16 +26,18 @@ from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
Job,
|
||||
ShippingOrderExtractionPlan,
|
||||
ShippingOrderExtractionRouteDecision,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtractionUnit,
|
||||
ShippingOrderProcessingPlan,
|
||||
ShippingOrderRouteDecision,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderProcessingUnit,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction_run_result
|
||||
from app.services.shipping_notice.order_extraction_merge import merge_unit_orders
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
begin_input_freeze,
|
||||
complete_input_freeze,
|
||||
mark_order_extraction_persistence_started,
|
||||
order_extraction_layout_prerequisite_issues,
|
||||
materialize_order_extraction_run_inputs,
|
||||
@@ -62,6 +67,31 @@ EXPANDABLE_UNIT_REVIEW_REASON_CODES = {
|
||||
}
|
||||
|
||||
|
||||
def _intake_source_types(intake_ids: set[int]) -> dict[int, str | None]:
|
||||
"""
|
||||
批量读取 Intake.source_type,供 merge 阶段分流 direct_pdf / eml。
|
||||
|
||||
核心逻辑:按主键加载 ShippingOrderIntake;缺失 id 不入结果。
|
||||
|
||||
Args:
|
||||
intake_ids: 待查询的 Intake 主键集合。
|
||||
|
||||
Returns:
|
||||
intake_id → source_type(eml|direct_pdf|None)映射。
|
||||
"""
|
||||
if not intake_ids:
|
||||
return {}
|
||||
rows = (
|
||||
ShippingOrderIntake.query
|
||||
.filter(ShippingOrderIntake.id.in_(sorted(intake_ids)))
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
int(row.id): (str(row.source_type).strip() if row.source_type else None)
|
||||
for row in rows
|
||||
}
|
||||
|
||||
|
||||
def _json_safe_order_payload(value: Any) -> Any:
|
||||
"""将坐标解析的 Decimal/date 递归转为 JSON 标量后写入 Unit 快照。
|
||||
|
||||
@@ -101,7 +131,7 @@ def _append_route_decision(*, run, unit, job, attempt_no: int, route_result) ->
|
||||
'route_decision': str(decision.get('route_decision') or ''),
|
||||
'policy_versions': decision.get('policy_versions') if isinstance(decision.get('policy_versions'), dict) else {},
|
||||
}
|
||||
db.session.add(ShippingOrderExtractionRouteDecision(
|
||||
db.session.add(ShippingOrderRouteDecision(
|
||||
run_id=run.id, unit_id=unit.id, job_id=job.id, attempt_no=attempt_no,
|
||||
decision=route_result.execution_mode,
|
||||
match_status=str(decision.get('match_status') or 'no_match'),
|
||||
@@ -145,7 +175,7 @@ def _append_route_decision(*, run, unit, job, attempt_no: int, route_result) ->
|
||||
)
|
||||
|
||||
|
||||
def _result_requires_review(*, units: list[ShippingOrderExtractionUnit], result: dict) -> bool:
|
||||
def _result_requires_review(*, units: list[ShippingOrderProcessingUnit], result: dict) -> bool:
|
||||
"""汇总人工复核、未接受候选、技术失败和自动冻结阻断,避免不完整 Run 被标记完成。"""
|
||||
return bool(
|
||||
result.get('pending_count')
|
||||
@@ -154,7 +184,7 @@ def _result_requires_review(*, units: list[ShippingOrderExtractionUnit], result:
|
||||
)
|
||||
|
||||
|
||||
def _selection_progress_summary(run: ShippingOrderExtractionRun) -> dict[str, int]:
|
||||
def _selection_progress_summary(run: ShippingOrderProcessingRun) -> dict[str, int]:
|
||||
"""从冻结选择计划提取首轮预算摘要,供 Run 级事件和卡片文案直接使用。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {}
|
||||
@@ -175,7 +205,7 @@ def _selection_progress_summary(run: ShippingOrderExtractionRun) -> dict[str, in
|
||||
}
|
||||
|
||||
|
||||
def _units_for_batch(plan: ShippingOrderExtractionPlan, *, selection_batch: int) -> list[ShippingOrderExtractionUnit]:
|
||||
def _units_for_batch(plan: ShippingOrderProcessingPlan, *, selection_batch: int) -> list[ShippingOrderProcessingUnit]:
|
||||
"""按批次读取计划单元;未标批次的普通文件视为首轮。"""
|
||||
normalized_batch = int(selection_batch or 1)
|
||||
return [
|
||||
@@ -184,7 +214,7 @@ def _units_for_batch(plan: ShippingOrderExtractionPlan, *, selection_batch: int)
|
||||
]
|
||||
|
||||
|
||||
def _next_existing_batch(plan: ShippingOrderExtractionPlan, *, after_batch: int) -> int | None:
|
||||
def _next_existing_batch(plan: ShippingOrderProcessingPlan, *, after_batch: int) -> int | None:
|
||||
"""返回计划中已存在但尚未轮到的下一批。"""
|
||||
candidates = sorted({
|
||||
int(unit.selection_batch or 1)
|
||||
@@ -194,7 +224,7 @@ def _next_existing_batch(plan: ShippingOrderExtractionPlan, *, after_batch: int)
|
||||
return candidates[0] if candidates else None
|
||||
|
||||
|
||||
def _pending_snapshot_batches(run: ShippingOrderExtractionRun, plan: ShippingOrderExtractionPlan) -> list[int]:
|
||||
def _pending_snapshot_batches(run: ShippingOrderProcessingRun, plan: ShippingOrderProcessingPlan) -> list[int]:
|
||||
"""从冻结选择计划中找出尚未激活为执行单元的后续批次。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {}
|
||||
@@ -211,14 +241,14 @@ def _pending_snapshot_batches(run: ShippingOrderExtractionRun, plan: ShippingOrd
|
||||
return [batch for batch in planned_batches if batch not in existing_batches]
|
||||
|
||||
|
||||
def _should_expand_after_wave(*, wave_units: list[ShippingOrderExtractionUnit], wave_orders: list[dict]) -> bool:
|
||||
def _should_expand_after_wave(*, wave_units: list[ShippingOrderProcessingUnit], wave_orders: list[dict]) -> bool:
|
||||
"""仅在可通过更多附件补证的业务缺口出现时才扩下一轮。"""
|
||||
return bool(_expansion_trigger_reason_codes(wave_units=wave_units, wave_orders=wave_orders))
|
||||
|
||||
|
||||
def _expansion_trigger_reason_codes(
|
||||
*,
|
||||
wave_units: list[ShippingOrderExtractionUnit],
|
||||
wave_units: list[ShippingOrderProcessingUnit],
|
||||
wave_orders: list[dict],
|
||||
) -> list[str]:
|
||||
"""汇总当前批次触发扩批的业务原因码,供事件与工作台共享。"""
|
||||
@@ -244,7 +274,7 @@ def _expansion_trigger_reason_codes(
|
||||
return sorted(code for code in reason_codes if code)
|
||||
|
||||
|
||||
def _schema_field_ids_by_code(run: ShippingOrderExtractionRun) -> dict[str, set[str]]:
|
||||
def _schema_field_ids_by_code(run: ShippingOrderProcessingRun) -> dict[str, set[str]]:
|
||||
"""读取冻结 Schema 中稳定 field_code -> field_id 集合,供业务缺口判定复用。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
@@ -284,7 +314,7 @@ def _order_requires_expansion(order: dict[str, Any]) -> bool:
|
||||
|
||||
|
||||
def _mark_expandable_business_gaps(
|
||||
run: ShippingOrderExtractionRun,
|
||||
run: ShippingOrderProcessingRun,
|
||||
*,
|
||||
orders: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
@@ -306,7 +336,7 @@ def _mark_expandable_business_gaps(
|
||||
|
||||
|
||||
def _wave_orders_for_expansion(
|
||||
run: ShippingOrderExtractionRun,
|
||||
run: ShippingOrderProcessingRun,
|
||||
*,
|
||||
orders: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
@@ -334,10 +364,10 @@ def _wave_orders_for_expansion(
|
||||
|
||||
def _activate_expansion_batch(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
plan: ShippingOrderExtractionPlan,
|
||||
run: ShippingOrderProcessingRun,
|
||||
plan: ShippingOrderProcessingPlan,
|
||||
selection_batch: int,
|
||||
) -> list[ShippingOrderExtractionUnit]:
|
||||
) -> list[ShippingOrderProcessingUnit]:
|
||||
"""按冻结批次计划补物化附件并追加执行单元;重复触发保持幂等。"""
|
||||
from app.services.shipping_notice.order_extraction_materialization import ensure_order_extraction_input_documents
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan_batch
|
||||
@@ -351,9 +381,9 @@ def _activate_expansion_batch(
|
||||
if isinstance(item, dict) and item.get('intake_id') is not None
|
||||
]
|
||||
intakes = (
|
||||
ShippingNoticeIntake.query
|
||||
.filter(ShippingNoticeIntake.id.in_(intake_ids))
|
||||
.order_by(ShippingNoticeIntake.id.asc())
|
||||
ShippingOrderIntake.query
|
||||
.filter(ShippingOrderIntake.id.in_(intake_ids))
|
||||
.order_by(ShippingOrderIntake.id.asc())
|
||||
.all()
|
||||
) if intake_ids else []
|
||||
ensure_order_extraction_input_documents(
|
||||
@@ -365,10 +395,10 @@ def _activate_expansion_batch(
|
||||
return ensure_order_extraction_plan_batch(run, selection_batch=int(selection_batch))
|
||||
|
||||
|
||||
def _reload_run_and_unit(*, run_id: int, unit_id: int) -> tuple[ShippingOrderExtractionRun, ShippingOrderExtractionUnit]:
|
||||
def _reload_run_and_unit(*, run_id: int, unit_id: int) -> tuple[ShippingOrderProcessingRun, ShippingOrderProcessingUnit]:
|
||||
"""在单元异常回滚后重新加载实体,避免继续使用失效会话对象。"""
|
||||
run = ShippingOrderExtractionRun.query.filter_by(id=run_id).with_for_update().first()
|
||||
unit = db.session.get(ShippingOrderExtractionUnit, int(unit_id))
|
||||
run = ShippingOrderProcessingRun.query.filter_by(id=run_id).with_for_update().first()
|
||||
unit = db.session.get(ShippingOrderProcessingUnit, int(unit_id))
|
||||
if run is None or unit is None:
|
||||
raise RuntimeError('order extraction run or unit disappeared during retry handling')
|
||||
return run, unit
|
||||
@@ -415,6 +445,9 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
|
||||
"""
|
||||
独立处理一个附件单元;技术失败最多自动重试 2 次,不影响其他单元继续执行。
|
||||
|
||||
核心逻辑:正常从 pending 开始;若进程/事务异常遗留 routing、matching_profile、extracting
|
||||
或 merging_supplement,则先经 failed→pending 恢复稳定检查点,再开启新的确定性尝试。
|
||||
|
||||
Returns:
|
||||
`list[dict]`: 当前单元产出的订单数组(确定性成功)。
|
||||
`None`: 当前单元进入 review_required、最终技术失败或取消中止。
|
||||
@@ -432,6 +465,13 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
db.session.commit()
|
||||
return None
|
||||
if unit.status in {'routing', 'matching_profile', 'extracting', 'merging_supplement'}:
|
||||
transition_order_extraction_unit(
|
||||
unit,
|
||||
target_status='failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_WORKER_RECOVERY',
|
||||
error_message='Interrupted order extraction unit reset before worker retry',
|
||||
)
|
||||
if unit.status == 'failed':
|
||||
transition_order_extraction_unit(unit, target_status='pending')
|
||||
if unit.status in {'review_required', 'candidate_ready', 'cancelled'}:
|
||||
@@ -596,7 +636,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
if job is None:
|
||||
return
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
run = ShippingOrderExtractionRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
|
||||
run = ShippingOrderProcessingRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
|
||||
if run is None:
|
||||
fail_job(job.id, error='order extraction run not found', retryable=False, owned_attempt=owned_attempt)
|
||||
return
|
||||
@@ -609,6 +649,14 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
# [STEP 0][BE-F03] 物化前先 open→freezing,阻断并发追加窗口。
|
||||
begin_input_freeze(run)
|
||||
db.session.commit()
|
||||
run = ShippingOrderProcessingRun.query.filter_by(id=int(run.id)).with_for_update().first()
|
||||
if run is None:
|
||||
fail_job(job.id, error='order extraction run missing after freeze', retryable=False, owned_attempt=owned_attempt)
|
||||
return
|
||||
|
||||
# [STEP 1] 邮件附件先物化成 Document,再排布局 Job;发送阶段没有 PDF Document。
|
||||
# 必须落在本 try 内:MinerU 关闭/排程失败时 ValidationError 需同步收口 Run,避免 Job 重试耗尽前 UI 一直 queued。
|
||||
materialize_order_extraction_run_inputs(run, finalize_plan=False)
|
||||
@@ -619,12 +667,14 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
# [STEP 2] 订单解析绝不能把仍在生成或缺失的版面快照当作“没有订单表”。
|
||||
layout_issues = order_extraction_layout_prerequisite_issues(run)
|
||||
if 'layout_pending' in layout_issues.values():
|
||||
# 布局等待期已进入 freezing;仍禁止追加,待布局就绪后完成冻结。
|
||||
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)
|
||||
return
|
||||
if layout_issues:
|
||||
complete_input_freeze(run)
|
||||
transition_order_extraction_run(run, target_status='processing', phase='layout_prerequisite_failed')
|
||||
transition_order_extraction_run(
|
||||
run, target_status='failed', phase='layout_prerequisite_failed',
|
||||
@@ -644,6 +694,8 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
plan = materialize_order_extraction_run_inputs(run)
|
||||
if plan is None:
|
||||
raise RuntimeError('order extraction plan was not finalized')
|
||||
# [BE-F03] 物化完成 → frozen,再进入 processing。
|
||||
complete_input_freeze(run)
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing')
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
@@ -731,7 +783,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
continue
|
||||
unit_orders = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=owned_attempt)
|
||||
db.session.expire_all()
|
||||
unit = db.session.get(ShippingOrderExtractionUnit, int(unit.id))
|
||||
unit = db.session.get(ShippingOrderProcessingUnit, int(unit.id))
|
||||
if unit is None or not unit_orders or unit.status != 'merging_supplement':
|
||||
continue
|
||||
unit_orders_by_id[int(unit.id)] = unit_orders
|
||||
@@ -769,7 +821,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
next_batch = pending_batches[0]
|
||||
created_units = _activate_expansion_batch(run=run, plan=plan, selection_batch=next_batch)
|
||||
db.session.flush()
|
||||
plan = ShippingOrderExtractionPlan.query.filter_by(id=plan.id).first() or plan
|
||||
plan = ShippingOrderProcessingPlan.query.filter_by(id=plan.id).first() or plan
|
||||
if created_units or _units_for_batch(plan, selection_batch=next_batch):
|
||||
record_run_progress(
|
||||
run=run,
|
||||
@@ -790,35 +842,123 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
continue
|
||||
break
|
||||
|
||||
units = ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id).order_by(ShippingOrderExtractionUnit.position.asc()).all()
|
||||
units = ShippingOrderProcessingUnit.query.filter_by(plan_id=plan.id).order_by(ShippingOrderProcessingUnit.position.asc()).all()
|
||||
|
||||
schema_snapshot = run.input_snapshot_json.get('schema') or {}
|
||||
orders_to_merge = [
|
||||
order
|
||||
for unit_id in pending_merge_unit_ids
|
||||
for order in unit_orders_by_id.get(unit_id, [])
|
||||
if isinstance(order, dict)
|
||||
schema_definition = schema_snapshot.get('definition') or {}
|
||||
pending_unit_id_set = {int(unit_id) for unit_id in pending_merge_unit_ids}
|
||||
pending_units = [
|
||||
unit for unit in units
|
||||
if int(unit.id) in pending_unit_id_set and unit.status == 'merging_supplement'
|
||||
]
|
||||
orders_to_merge = merge_unit_orders(orders=orders_to_merge, schema_definition=schema_snapshot.get('definition') or {})
|
||||
# [STEP] 阶段 2:按 Intake.source_type 分流;direct_pdf 跳过邮件补充与裁决审计。
|
||||
pending_intake_ids = {
|
||||
int(unit.intake_id) for unit in pending_units if unit.intake_id is not None
|
||||
}
|
||||
run_intake_ids = {
|
||||
int(item.get('intake_id'))
|
||||
for item in (run.input_snapshot_json.get('intakes') or [])
|
||||
if isinstance(item, dict) and item.get('intake_id') is not None
|
||||
}
|
||||
source_by_intake = _intake_source_types(pending_intake_ids | run_intake_ids)
|
||||
all_run_direct_pdf = bool(run_intake_ids) and all(
|
||||
source_by_intake.get(intake_id) == 'direct_pdf' for intake_id in run_intake_ids
|
||||
)
|
||||
|
||||
def _unit_is_direct_pdf(unit: ShippingOrderProcessingUnit) -> bool:
|
||||
"""Unit 所属 Intake 为 direct_pdf,或本 Run 全部 Intake 均为 direct_pdf。"""
|
||||
if all_run_direct_pdf:
|
||||
return True
|
||||
return source_by_intake.get(int(unit.intake_id or 0)) == 'direct_pdf'
|
||||
|
||||
direct_pdf_units = [unit for unit in pending_units if _unit_is_direct_pdf(unit)]
|
||||
eml_units = [unit for unit in pending_units if not _unit_is_direct_pdf(unit)]
|
||||
|
||||
from app.services.shipping_notice.order_supplement_merge import merge_email_supplements
|
||||
supplements_by_intake = {
|
||||
int(intake.get('intake_id') or 0): supplement
|
||||
for intake in run.input_snapshot_json.get('intakes') or [] if isinstance(intake, dict)
|
||||
for supplement in intake.get('email_supplements') or [] if isinstance(supplement, dict)
|
||||
}
|
||||
merged_orders = merge_email_supplements(
|
||||
orders=orders_to_merge,
|
||||
supplements_by_intake=supplements_by_intake,
|
||||
schema_definition=schema_snapshot.get('definition') or {},
|
||||
)
|
||||
offset = 0
|
||||
merged_by_unit_id: dict[int, list[dict[str, Any]]] = {}
|
||||
|
||||
def _merge_group_orders(
|
||||
group_units: list[ShippingOrderProcessingUnit],
|
||||
*,
|
||||
apply_email_supplements: bool,
|
||||
) -> None:
|
||||
"""
|
||||
对同路径 Unit 批量 merge;可选跳过 email_supplements。
|
||||
|
||||
Args:
|
||||
group_units: 同路径(direct_pdf 或 eml)且保持 plan 顺序的 Unit。
|
||||
apply_email_supplements: False 时直接 PDF 跳过正文补充合并。
|
||||
"""
|
||||
if not group_units:
|
||||
return
|
||||
orders_to_merge = [
|
||||
order
|
||||
for unit in group_units
|
||||
for order in unit_orders_by_id.get(int(unit.id), [])
|
||||
if isinstance(order, dict)
|
||||
]
|
||||
merged = merge_unit_orders(
|
||||
orders=orders_to_merge,
|
||||
schema_definition=schema_definition,
|
||||
keep_primary_documents_separate=True,
|
||||
)
|
||||
if apply_email_supplements:
|
||||
merged = merge_email_supplements(
|
||||
orders=merged,
|
||||
supplements_by_intake=supplements_by_intake,
|
||||
schema_definition=schema_definition,
|
||||
)
|
||||
offset = 0
|
||||
for unit in group_units:
|
||||
count = len(unit_orders_by_id.get(int(unit.id), []))
|
||||
merged_by_unit_id[int(unit.id)] = [
|
||||
item for item in merged[offset:offset + count] if isinstance(item, dict)
|
||||
]
|
||||
offset += count
|
||||
|
||||
_merge_group_orders(direct_pdf_units, apply_email_supplements=False)
|
||||
if eml_units:
|
||||
append_shipping_audit_event(
|
||||
event_type='ORDER_EMAIL_ADJUDICATION_STARTED',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=str(run.id),
|
||||
run_no=run.run_no,
|
||||
actor_type='system',
|
||||
source='shipping_order_extraction',
|
||||
metadata={
|
||||
'unit_count': len(eml_units),
|
||||
'source_type': 'eml',
|
||||
'decision_rule_version': 'pdf-priority-v1',
|
||||
},
|
||||
)
|
||||
_merge_group_orders(eml_units, apply_email_supplements=True)
|
||||
append_shipping_audit_event(
|
||||
event_type='ORDER_EMAIL_ADJUDICATION_COMPLETED',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=str(run.id),
|
||||
run_no=run.run_no,
|
||||
actor_type='system',
|
||||
source='shipping_order_extraction',
|
||||
result='success',
|
||||
metadata={
|
||||
'unit_count': len(eml_units),
|
||||
'source_type': 'eml',
|
||||
'decision_rule_version': 'pdf-priority-v1',
|
||||
},
|
||||
)
|
||||
|
||||
merged_orders: list[dict[str, Any]] = []
|
||||
for unit in units:
|
||||
unit_orders = unit_orders_by_id.get(int(unit.id), [])
|
||||
if unit.status != 'merging_supplement':
|
||||
continue
|
||||
count = len(unit_orders)
|
||||
merged_unit_orders = merged_orders[offset:offset + count]
|
||||
offset += count
|
||||
merged_unit_orders = merged_by_unit_id.get(int(unit.id), list(unit_orders))
|
||||
merged_orders.extend(merged_unit_orders)
|
||||
relation_codes = sorted({
|
||||
str(order.get('_hxops_email_supplement_relation') or '').strip()
|
||||
for order in merged_unit_orders
|
||||
@@ -1020,12 +1160,12 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
finish_job(job.id, result=summary, message='订单抽取完成', owned_attempt=owned_attempt)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
run = ShippingOrderExtractionRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
|
||||
run = ShippingOrderProcessingRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
|
||||
retryable = not isinstance(exc, AppError) or bool(getattr(exc, 'retryable', False))
|
||||
if run is not None and run.status in {'queued', 'processing', 'failed'}:
|
||||
running_unit = ShippingOrderExtractionUnit.query.join(ShippingOrderExtractionPlan).filter(
|
||||
ShippingOrderExtractionPlan.run_id == run.id,
|
||||
ShippingOrderExtractionUnit.status.in_(['routing', 'matching_profile', 'extracting', 'merging_supplement']),
|
||||
running_unit = ShippingOrderProcessingUnit.query.join(ShippingOrderProcessingPlan).filter(
|
||||
ShippingOrderProcessingPlan.run_id == run.id,
|
||||
ShippingOrderProcessingUnit.status.in_(['routing', 'matching_profile', 'extracting', 'merging_supplement']),
|
||||
).first()
|
||||
if running_unit is not None:
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
@@ -143,7 +143,7 @@ def _is_safe_supersede_target(sibling: Job, *, cancelled_job: Job) -> bool:
|
||||
if status != "running":
|
||||
return False
|
||||
|
||||
from app.models import ShippingNoticeIntake
|
||||
from app.models import ShippingOrderIntake
|
||||
|
||||
intake_no = str(
|
||||
(cancelled_job.payload_json or {}).get("intake_no")
|
||||
@@ -154,8 +154,8 @@ def _is_safe_supersede_target(sibling: Job, *, cancelled_job: Job) -> bool:
|
||||
if not intake_no:
|
||||
return False
|
||||
locked = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(ShippingNoticeIntake.intake_no == intake_no)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(ShippingOrderIntake.intake_no == intake_no)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
.first()
|
||||
@@ -210,7 +210,7 @@ def _retarget_intake_parse_job_after_supersede(
|
||||
"""
|
||||
if not _subject_to_parse_queued_unique(str(cancelled_job.job_type or "")):
|
||||
return
|
||||
from app.models import ShippingNoticeIntake
|
||||
from app.models import ShippingOrderIntake
|
||||
|
||||
intake_no = str(
|
||||
(cancelled_job.payload_json or {}).get("intake_no")
|
||||
@@ -227,8 +227,8 @@ def _retarget_intake_parse_job_after_supersede(
|
||||
return
|
||||
|
||||
locked = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(ShippingNoticeIntake.intake_no == intake_no)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(ShippingOrderIntake.intake_no == intake_no)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
.first()
|
||||
|
||||
@@ -18,17 +18,23 @@ from app.models.schedule import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||
from app.models.settings import AppSetting
|
||||
from app.models.file_asset import FileAsset
|
||||
from app.models.shipping import (
|
||||
ShippingBatch,
|
||||
ShippingInventoryFile,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
ShippingNotice,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingTaskEvent,
|
||||
ShippingTaskPurgeAudit,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.models.shipping_order_submission import ShippingOrderSubmission
|
||||
from app.models.shipping_order_task import ShippingOrderTask
|
||||
from app.models.shipping_order_candidate_evidence import ShippingOrderCandidateEvidence
|
||||
from app.models.shipping_notice_line import ShippingNoticeLine
|
||||
from app.models.shipping_order_document_version import ShippingOrderDocumentVersion
|
||||
from app.models.shipping_task_line import ShippingTaskFieldConflict
|
||||
# [BE-14] 已移除 ShippingTask=ShippingNotice 兼容别名;正式发货通知统一用 ShippingNotice,
|
||||
# 建单前 OT 用 ShippingOrderTask,禁止再引入 ShippingTask 混淆二者。
|
||||
from app.models.shipping_context_provider import ShippingContextProvider, ShippingContextProviderOption
|
||||
from app.models.shipping_excel_template import ShippingExcelTemplate, ShippingExportArtifact
|
||||
from app.models.shipping_fulfillment import (
|
||||
@@ -43,6 +49,11 @@ from app.models.shipping_process_gate import (
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
)
|
||||
|
||||
# 短期兼容别名:历史代码仍可 import ShippingNotice*;新代码优先用 ShippingOrder*。
|
||||
ShippingNoticeIntake = ShippingOrderIntake
|
||||
ShippingNoticeDocument = ShippingOrderDocument
|
||||
ShippingNoticeCandidate = ShippingOrderCandidate
|
||||
from app.models.shipping_order_schema import (
|
||||
ShippingFieldAsset,
|
||||
ShippingOrderExtraction,
|
||||
@@ -68,23 +79,27 @@ from app.models.shipping_order_review import (
|
||||
ShippingOrderReviewCaseEvent,
|
||||
ShippingOrderReviewConfirmedRevision,
|
||||
)
|
||||
from app.models.shipping_order_review_line_decision import ShippingOrderReviewLineDecision
|
||||
from app.models.shipping_order_review_wave_line import ShippingOrderReviewWaveLine
|
||||
from app.models.shipping_order_review_suggestion import ShippingOrderReviewSuggestion
|
||||
from app.models.shipping_order_extraction_run import (
|
||||
ShippingOrderExtractionDiagnosticAudit,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionPlan,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionRunIntake,
|
||||
ShippingOrderExtractionRouteDecision,
|
||||
ShippingOrderExtractionUnit,
|
||||
ShippingOrderExtractionSubmission,
|
||||
ShippingOrderProcessingPlan,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderProcessingRunIntake,
|
||||
ShippingOrderProcessingUnit,
|
||||
ShippingOrderRouteDecision,
|
||||
)
|
||||
|
||||
# 短期兼容别名:历史代码仍可 import ShippingOrderExtractionRun*;新代码优先用 Processing*。
|
||||
ShippingOrderExtractionRun = ShippingOrderProcessingRun
|
||||
ShippingOrderExtractionRunIntake = ShippingOrderProcessingRunIntake
|
||||
ShippingOrderExtractionPlan = ShippingOrderProcessingPlan
|
||||
ShippingOrderExtractionUnit = ShippingOrderProcessingUnit
|
||||
ShippingOrderExtractionRouteDecision = ShippingOrderRouteDecision
|
||||
from app.models.shipping_audit_event import ShippingAuditEvent
|
||||
from app.models.shipping_notice_workflow import (
|
||||
ShippingNoticeWorkflow,
|
||||
ShippingNoticeWorkflowEvent,
|
||||
ShippingNoticeWorkflowItem,
|
||||
ShippingNoticeWorkflowItemVersion,
|
||||
)
|
||||
from app.models.shipping_order_document_profile import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
@@ -104,6 +119,8 @@ from app.models.shipping_document_profile_auto_freeze import ShippingDocumentPro
|
||||
from app.models.shipping_order_candidate_qualification import ShippingOrderCandidateQualification
|
||||
from app.models.shipping_freight_cancellation import ShippingFreightCancellation
|
||||
from app.models.shipping_document_layout import ShippingDocumentLayoutVersion
|
||||
from app.models.shipping_xfa_structure_analysis import ShippingXfaStructureAnalysis
|
||||
from app.models.shipping_xfa_audit_snapshot import ShippingXfaAuditSnapshot
|
||||
from app.models.shipping_inventory_config import (
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryExternalMapping,
|
||||
@@ -178,8 +195,7 @@ __all__ = [
|
||||
'ScheduleTask',
|
||||
'ScheduleTaskConfig',
|
||||
'ScheduleRun',
|
||||
'ShippingBatch',
|
||||
'ShippingTask',
|
||||
'ShippingNotice',
|
||||
'ShippingTaskFieldConflict',
|
||||
'ShippingContextProvider',
|
||||
'ShippingContextProviderOption',
|
||||
@@ -202,19 +218,23 @@ __all__ = [
|
||||
'ShippingOrderReviewDraft',
|
||||
'ShippingOrderReviewCaseEvent',
|
||||
'ShippingOrderReviewConfirmedRevision',
|
||||
'ShippingOrderReviewLineDecision',
|
||||
'ShippingOrderReviewWaveLine',
|
||||
'ShippingOrderReviewSuggestion',
|
||||
'ShippingOrderProcessingRun',
|
||||
'ShippingOrderProcessingRunIntake',
|
||||
'ShippingOrderProcessingPlan',
|
||||
'ShippingOrderProcessingUnit',
|
||||
'ShippingOrderRouteDecision',
|
||||
'ShippingOrderExtractionRun',
|
||||
'ShippingOrderExtractionRunIntake',
|
||||
'ShippingOrderExtractionSubmission',
|
||||
'ShippingOrderExtractionPlan',
|
||||
'ShippingOrderExtractionRouteDecision',
|
||||
'ShippingOrderExtractionUnit',
|
||||
'ShippingOrderExtractionProgressEvent',
|
||||
'ShippingOrderExtractionDiagnosticAudit',
|
||||
'ShippingAuditEvent',
|
||||
'ShippingNoticeWorkflow',
|
||||
'ShippingNoticeWorkflowItem',
|
||||
'ShippingNoticeWorkflowItemVersion',
|
||||
'ShippingNoticeWorkflowEvent',
|
||||
'ShippingOrderExtractionQualityBatch',
|
||||
'ShippingOrderExtractionQualityLabel',
|
||||
'ShippingOrderDocumentProfile',
|
||||
@@ -227,6 +247,8 @@ __all__ = [
|
||||
'ShippingOrderCandidateQualification',
|
||||
'ShippingFreightCancellation',
|
||||
'ShippingDocumentLayoutVersion',
|
||||
'ShippingXfaStructureAnalysis',
|
||||
'ShippingXfaAuditSnapshot',
|
||||
'ShippingCustomer',
|
||||
'ShippingCustomerIdentifier',
|
||||
'ShippingCustomerExternalRef',
|
||||
@@ -271,9 +293,17 @@ __all__ = [
|
||||
'ShippingProcessExecution',
|
||||
'ShippingProcessGate',
|
||||
'ShippingProcessGateAttempt',
|
||||
'ShippingNoticeIntake',
|
||||
'ShippingNoticeDocument',
|
||||
'ShippingNoticeCandidate',
|
||||
'ShippingOrderIntake',
|
||||
'ShippingOrderDocument',
|
||||
'ShippingOrderCandidate',
|
||||
'ShippingNoticeIntake', # 兼容别名
|
||||
'ShippingNoticeDocument', # 兼容别名
|
||||
'ShippingNoticeCandidate', # 兼容别名
|
||||
'ShippingOrderSubmission',
|
||||
'ShippingOrderTask',
|
||||
'ShippingOrderCandidateEvidence',
|
||||
'ShippingNoticeLine',
|
||||
'ShippingOrderDocumentVersion',
|
||||
'FileAsset',
|
||||
'AgentGuide',
|
||||
'AgentDirectoryMember',
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/models/file_asset.py
|
||||
|
||||
用途:平台级通用文件资产模型,承载私有 MinIO 存储元数据与生命周期。
|
||||
依赖:models.base.Base。
|
||||
逻辑:由 file_assets.service 创建与更新;ShippingNoticeIntake 经 asset_id 引用上传根资产;
|
||||
逻辑:由 file_assets.service 创建与更新;ShippingOrderIntake 经 asset_id 引用上传根资产;
|
||||
EML 解析后的订单附件以 parent_asset_id 挂为 derived 子资产(阶段二);
|
||||
派生资产对 (parent_asset_id, content_hash) 使用未删除行的部分唯一索引。
|
||||
"""
|
||||
|
||||
+113
-126
@@ -1,15 +1,19 @@
|
||||
"""
|
||||
backend/app/models/shipping.py
|
||||
|
||||
用途:货代发货通知批次、任务、事件、库存文件、接入记录、文档/候选与库存映射模型。
|
||||
依赖:models.base.Base;规范订单行见 shipping_task_line。
|
||||
逻辑:ShippingBatch.create_idempotency_key 为建单幂等;ShippingTask.idempotency_key 为货代上传幂等;
|
||||
用途:货代发货通知正式 Notice(shipping_notices)、事件、库存文件、接入记录、文档/候选与库存映射模型。
|
||||
依赖:models.base.Base;规范订单行见 shipping_task_line;建单前 OT 见 shipping_order_task。
|
||||
逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列;
|
||||
Intake 消费绑定仅保留 consumed_task_id / consumed_at;upload_batch_id 为上传边界批次(非 shipping_batches);
|
||||
ShippingNotice.idempotency_key 为货代上传幂等;
|
||||
Intake.create_idempotency_key 承载混合/open_existing 确认请求重放;
|
||||
Intake/Task/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离;
|
||||
Document/Candidate 承载「一邮件多订单」识别;ShippingTask.source_candidate_id 记录正式建单来源;
|
||||
ShippingTask.supersedes_task_id 唯一约束保证修订链线性;
|
||||
Intake/Notice/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离;
|
||||
Document/Candidate 承载「一邮件多订单」识别;ShippingNotice.source_candidate_id 记录正式建单来源;
|
||||
ShippingNotice.order_task_id 挂接建单前 OT(shipping_order_tasks);ShippingNotice.supersedes_task_id 唯一约束保证修订链线性;
|
||||
order_data_version 为冻结前 Candidate/Extraction 纠错的乐观锁版本;
|
||||
current_order_extraction_id 追溯解析事实,order_snapshot_id 指向不可变履约事实。
|
||||
current_order_extraction_id 追溯解析事实,order_snapshot_id 指向不可变履约事实;
|
||||
阶段 1:Intake.source_type / order_submission_id 挂接 shipping_order_submissions;
|
||||
建单前接入层表名为 shipping_order_intakes / documents / candidates(类名 ShippingOrder*)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -38,64 +42,29 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingBatch(Base):
|
||||
"""货代发货通知批次(一次多文件上传的聚合容器)"""
|
||||
class ShippingNotice(Base):
|
||||
"""
|
||||
正式发货通知(Candidate 建单后的履约实体)。
|
||||
|
||||
__tablename__ = 'shipping_batches'
|
||||
核心逻辑:Chatflow Tool 编排状态机;建单前 OT 聚合根见 ShippingOrderTask(shipping_order_tasks)。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_notices'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_batches_user_created', 'user_id', 'created_at'),
|
||||
Index('ix_shipping_batches_conversation', 'conversation_id'),
|
||||
UniqueConstraint(
|
||||
'user_id',
|
||||
'create_idempotency_key',
|
||||
name='uq_shipping_batches_user_create_idempotency',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
batch_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
current_focus_task_no: Mapped[Optional[str]] = mapped_column(
|
||||
String(64),
|
||||
ForeignKey(
|
||||
'shipping_tasks.task_no',
|
||||
name='fk_shipping_batches_current_focus_task_no_shipping_tasks',
|
||||
use_alter=True,
|
||||
),
|
||||
nullable=True,
|
||||
)
|
||||
file_count: Mapped[int] = mapped_column(Integer, default=1)
|
||||
create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
process_summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
tasks: Mapped[List['ShippingTask']] = relationship(
|
||||
'ShippingTask',
|
||||
back_populates='batch',
|
||||
foreign_keys='ShippingTask.batch_id',
|
||||
)
|
||||
|
||||
|
||||
class ShippingTask(Base):
|
||||
"""货代发货通知 task(Chatflow Tool 编排状态机)"""
|
||||
|
||||
__tablename__ = 'shipping_tasks'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_tasks_user_status', 'user_id', 'process_status'),
|
||||
Index('ix_shipping_tasks_conversation', 'conversation_id'),
|
||||
Index('ix_shipping_tasks_batch_step', 'batch_id', 'current_step'),
|
||||
Index('ix_shipping_tasks_upload_status', 'upload_status'),
|
||||
Index('ix_shipping_tasks_inventory_source_code', 'inventory_source_code'),
|
||||
Index('ix_shipping_tasks_inventory_source_status', 'inventory_source_status'),
|
||||
Index('ix_shipping_tasks_inventory_routing_fingerprint', 'inventory_routing_fingerprint'),
|
||||
Index('ix_shipping_tasks_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'),
|
||||
Index('ix_shipping_tasks_user_source_content_hash', 'user_id', 'source_content_hash'),
|
||||
Index('ix_shipping_tasks_user_business_fingerprint', 'user_id', 'business_fingerprint'),
|
||||
Index('ix_shipping_tasks_user_content_fingerprint', 'user_id', 'content_fingerprint'),
|
||||
Index('ix_shipping_notices_user_status', 'user_id', 'process_status'),
|
||||
Index('ix_shipping_notices_conversation', 'conversation_id'),
|
||||
Index('ix_shipping_notices_current_step', 'current_step'),
|
||||
Index('ix_shipping_notices_upload_status', 'upload_status'),
|
||||
Index('ix_shipping_notices_inventory_source_code', 'inventory_source_code'),
|
||||
Index('ix_shipping_notices_inventory_source_status', 'inventory_source_status'),
|
||||
Index('ix_shipping_notices_inventory_routing_fingerprint', 'inventory_routing_fingerprint'),
|
||||
Index('ix_shipping_notices_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'),
|
||||
Index('ix_shipping_notices_user_source_content_hash', 'user_id', 'source_content_hash'),
|
||||
Index('ix_shipping_notices_user_business_fingerprint', 'user_id', 'business_fingerprint'),
|
||||
Index('ix_shipping_notices_user_content_fingerprint', 'user_id', 'content_fingerprint'),
|
||||
# 线性版本链:同一父任务至多一个后继(NULL 不冲突)
|
||||
UniqueConstraint('supersedes_task_id', name='uq_shipping_tasks_supersedes_task_id'),
|
||||
Index('ix_shipping_tasks_duplicate_source_task_id', 'duplicate_source_task_id'),
|
||||
UniqueConstraint('supersedes_task_id', name='uq_shipping_notices_supersedes_task_id'),
|
||||
Index('ix_shipping_notices_duplicate_source_task_id', 'duplicate_source_task_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -105,7 +74,6 @@ class ShippingTask(Base):
|
||||
index=True,
|
||||
nullable=True,
|
||||
)
|
||||
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), index=True, nullable=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
source_type: Mapped[str] = mapped_column(String(32), default='manual')
|
||||
@@ -114,31 +82,40 @@ class ShippingTask(Base):
|
||||
source_content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
source_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=True)
|
||||
source_intake_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_notice_intakes.id'),
|
||||
ForeignKey('shipping_order_intakes.id'),
|
||||
index=True,
|
||||
nullable=True,
|
||||
)
|
||||
# 阶段二:由 Candidate 正式建单时回填;与 Candidate.consumed_task_id 对向引用,用 use_alter
|
||||
source_candidate_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey(
|
||||
'shipping_notice_candidates.id',
|
||||
name='fk_shipping_tasks_source_candidate_id',
|
||||
'shipping_order_candidates.id',
|
||||
name='fk_shipping_notices_source_candidate_id',
|
||||
use_alter=True,
|
||||
),
|
||||
index=True,
|
||||
nullable=True,
|
||||
)
|
||||
order_task_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey(
|
||||
'shipping_order_tasks.id',
|
||||
name='fk_shipping_notices_order_task_id',
|
||||
use_alter=True,
|
||||
),
|
||||
nullable=True,
|
||||
index=True,
|
||||
)
|
||||
business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
content_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
content_fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
document_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
supersedes_task_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_tasks.id'),
|
||||
ForeignKey('shipping_notices.id'),
|
||||
nullable=True,
|
||||
)
|
||||
duplicate_source_task_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_tasks.id'),
|
||||
ForeignKey('shipping_notices.id'),
|
||||
nullable=True,
|
||||
)
|
||||
duplicate_override_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
@@ -177,7 +154,7 @@ class ShippingTask(Base):
|
||||
current_order_extraction_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey(
|
||||
'shipping_order_extractions.id',
|
||||
name='fk_shipping_tasks_current_order_extraction_id',
|
||||
name='fk_shipping_notices_current_order_extraction_id',
|
||||
use_alter=True,
|
||||
),
|
||||
nullable=True,
|
||||
@@ -187,7 +164,7 @@ class ShippingTask(Base):
|
||||
order_snapshot_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey(
|
||||
'shipping_order_snapshots.id',
|
||||
name='fk_shipping_tasks_order_snapshot_id',
|
||||
name='fk_shipping_notices_order_snapshot_id',
|
||||
use_alter=True,
|
||||
),
|
||||
nullable=True,
|
||||
@@ -240,11 +217,6 @@ class ShippingTask(Base):
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
batch: Mapped[Optional['ShippingBatch']] = relationship(
|
||||
'ShippingBatch',
|
||||
back_populates='tasks',
|
||||
foreign_keys=[batch_id],
|
||||
)
|
||||
shipping_case: Mapped[Optional['ShippingCase']] = relationship(
|
||||
'ShippingCase',
|
||||
back_populates='tasks',
|
||||
@@ -268,7 +240,7 @@ class ShippingTaskEvent(Base):
|
||||
__tablename__ = 'shipping_task_events'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), index=True)
|
||||
event_type: Mapped[str] = mapped_column(String(64), index=True)
|
||||
detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
before_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
@@ -278,7 +250,7 @@ class ShippingTaskEvent(Base):
|
||||
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
task: Mapped['ShippingTask'] = relationship('ShippingTask', back_populates='events')
|
||||
task: Mapped['ShippingNotice'] = relationship('ShippingNotice', back_populates='events')
|
||||
|
||||
|
||||
class ShippingTaskPurgeAudit(Base):
|
||||
@@ -301,7 +273,6 @@ class ShippingInventoryFile(Base):
|
||||
|
||||
__tablename__ = 'shipping_inventory_files'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_inventory_files_batch_created', 'batch_id', 'created_at'),
|
||||
Index('ix_shipping_inventory_files_user_created', 'user_id', 'created_at'),
|
||||
Index(
|
||||
'ix_shipping_inventory_files_source_snapshot',
|
||||
@@ -349,7 +320,6 @@ class ShippingInventoryFile(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
inventory_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), index=True, nullable=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
storage_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
@@ -375,7 +345,6 @@ class ShippingInventoryFile(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
batch: Mapped[Optional['ShippingBatch']] = relationship('ShippingBatch', foreign_keys=[batch_id])
|
||||
links: Mapped[List['ShippingTaskInventoryLink']] = relationship(
|
||||
'ShippingTaskInventoryLink',
|
||||
back_populates='inventory_file',
|
||||
@@ -398,7 +367,7 @@ class ShippingTaskInventoryLink(Base):
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), index=True)
|
||||
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id'), index=True)
|
||||
link_role: Mapped[str] = mapped_column(String(32), default='member')
|
||||
access_mode: Mapped[str] = mapped_column(String(32), default='readonly')
|
||||
@@ -413,7 +382,7 @@ class ShippingTaskInventoryLink(Base):
|
||||
linked_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
task: Mapped['ShippingTask'] = relationship('ShippingTask', foreign_keys=[task_id])
|
||||
task: Mapped['ShippingNotice'] = relationship('ShippingNotice', foreign_keys=[task_id])
|
||||
inventory_file: Mapped['ShippingInventoryFile'] = relationship(
|
||||
'ShippingInventoryFile',
|
||||
back_populates='links',
|
||||
@@ -421,30 +390,41 @@ class ShippingTaskInventoryLink(Base):
|
||||
)
|
||||
|
||||
|
||||
class ShippingNoticeIntake(Base):
|
||||
"""发货通知接入记录:分别跟踪文件预处理与订单抽取状态。"""
|
||||
class ShippingOrderIntake(Base):
|
||||
"""
|
||||
发货通知接入记录:分别跟踪文件预处理与订单抽取状态。
|
||||
|
||||
__tablename__ = 'shipping_notice_intakes'
|
||||
阶段 1:source_type=eml|direct_pdf 标识裁决边界;order_submission_id 挂接上传 Submission。
|
||||
表名 shipping_order_intakes(建单前接入层)。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_order_intakes'
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"purpose IN ('shipping_notice', 'order_document_profile_sample')",
|
||||
name='ck_shipping_notice_intakes_purpose',
|
||||
name='ck_shipping_order_intakes_purpose',
|
||||
),
|
||||
UniqueConstraint('intake_no', name='uq_shipping_notice_intakes_intake_no'),
|
||||
CheckConstraint(
|
||||
"source_type IS NULL OR source_type IN ('eml', 'direct_pdf')",
|
||||
name='ck_shipping_order_intakes_source_type',
|
||||
),
|
||||
UniqueConstraint('intake_no', name='uq_shipping_order_intakes_intake_no'),
|
||||
UniqueConstraint(
|
||||
'asset_id',
|
||||
'purpose',
|
||||
'parser_version',
|
||||
name='uq_shipping_notice_intakes_asset_purpose_parser',
|
||||
name='uq_shipping_order_intakes_asset_purpose_parser',
|
||||
),
|
||||
Index('ix_shipping_notice_intakes_user_conversation_created', 'user_id', 'conversation_id', 'created_at'),
|
||||
Index('ix_shipping_notice_intakes_user_upload_batch_created', 'user_id', 'upload_batch_id', 'created_at'),
|
||||
Index('ix_shipping_notice_intakes_parse_status_created', 'parse_status', 'created_at'),
|
||||
Index('ix_shipping_notice_intakes_expires', 'expires_at'),
|
||||
Index('ix_shipping_notice_intakes_user_business_fingerprint', 'user_id', 'business_fingerprint'),
|
||||
Index('ix_shipping_notice_intakes_duplicate_status_created', 'duplicate_status', 'created_at'),
|
||||
Index('ix_shipping_notice_intakes_fp_version_fingerprint', 'fingerprint_version', 'business_fingerprint'),
|
||||
Index('ix_shipping_notice_intakes_user_create_idempotency', 'user_id', 'create_idempotency_key'),
|
||||
Index('ix_shipping_order_intakes_user_conversation_created', 'user_id', 'conversation_id', 'created_at'),
|
||||
Index('ix_shipping_order_intakes_user_upload_batch_created', 'user_id', 'upload_batch_id', 'created_at'),
|
||||
Index('ix_shipping_order_intakes_parse_status_created', 'parse_status', 'created_at'),
|
||||
Index('ix_shipping_order_intakes_expires', 'expires_at'),
|
||||
Index('ix_shipping_order_intakes_user_business_fingerprint', 'user_id', 'business_fingerprint'),
|
||||
Index('ix_shipping_order_intakes_duplicate_status_created', 'duplicate_status', 'created_at'),
|
||||
Index('ix_shipping_order_intakes_fp_version_fingerprint', 'fingerprint_version', 'business_fingerprint'),
|
||||
Index('ix_shipping_order_intakes_user_create_idempotency', 'user_id', 'create_idempotency_key'),
|
||||
Index('ix_shipping_order_intakes_source_type', 'source_type'),
|
||||
Index('ix_shipping_order_intakes_order_submission_id', 'order_submission_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -454,6 +434,13 @@ class ShippingNoticeIntake(Base):
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
# 同一输入框一次选取的上传批次;发送端只能冻结同一批次的 Intake。
|
||||
upload_batch_id: Mapped[str] = mapped_column(String(36), nullable=False, default=lambda: str(uuid.uuid4()))
|
||||
# 上传边界 Submission(阶段 1);与 OT 发送决策 submission 分离。
|
||||
order_submission_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_submissions.id'),
|
||||
nullable=True,
|
||||
)
|
||||
# eml = 一份邮件裁决边界;direct_pdf = 一份直接 PDF;其它类型暂 NULL。
|
||||
source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
purpose: Mapped[str] = mapped_column(String(32), default='shipping_notice', nullable=False)
|
||||
parse_status: Mapped[str] = mapped_column(String(32), default='created', nullable=False, index=True)
|
||||
order_extraction_status: Mapped[str] = mapped_column(
|
||||
@@ -491,37 +478,37 @@ class ShippingNoticeIntake(Base):
|
||||
duplicate_resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
consumed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
consumed_batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), nullable=True)
|
||||
consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True)
|
||||
# co8e9f0a1b2c 已 DROP shipping_batches 与 consumed_batch_id;消费绑定仅保留任务侧。
|
||||
consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True)
|
||||
create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
class ShippingNoticeDocument(Base):
|
||||
class ShippingOrderDocument(Base):
|
||||
"""
|
||||
发货通知文档单元:邮件正文或单个附件(阶段二)。
|
||||
|
||||
核心逻辑:Intake 解析后按 attachment_key 幂等 upsert;附件型 Document 可挂 derived FileAsset。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_notice_documents'
|
||||
__tablename__ = 'shipping_order_documents'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'intake_id',
|
||||
'attachment_key',
|
||||
name='uq_shipping_notice_documents_intake_attachment_key',
|
||||
name='uq_shipping_order_documents_intake_attachment_key',
|
||||
),
|
||||
# 支撑 Candidate (primary_document_id, intake_id) 复合外键
|
||||
UniqueConstraint('id', 'intake_id', name='uq_shipping_notice_documents_id_intake'),
|
||||
Index('ix_shipping_notice_documents_intake_id', 'intake_id'),
|
||||
Index('ix_shipping_notice_documents_asset_id', 'asset_id'),
|
||||
Index('ix_shipping_notice_documents_content_hash', 'content_hash'),
|
||||
Index('ix_shipping_notice_documents_parse_status', 'parse_status'),
|
||||
UniqueConstraint('id', 'intake_id', name='uq_shipping_order_documents_id_intake'),
|
||||
Index('ix_shipping_order_documents_intake_id', 'intake_id'),
|
||||
Index('ix_shipping_order_documents_asset_id', 'asset_id'),
|
||||
Index('ix_shipping_order_documents_content_hash', 'content_hash'),
|
||||
Index('ix_shipping_order_documents_parse_status', 'parse_status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
intake_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_intakes.id'),
|
||||
ForeignKey('shipping_order_intakes.id'),
|
||||
nullable=False,
|
||||
)
|
||||
asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True)
|
||||
@@ -535,8 +522,8 @@ class ShippingNoticeDocument(Base):
|
||||
parse_warnings_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
current_layout_version_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey(
|
||||
'shipping_document_layout_versions.id',
|
||||
name='fk_shipping_notice_documents_current_layout_version',
|
||||
'shipping_order_document_layout_versions.id',
|
||||
name='fk_shipping_order_documents_current_layout_version',
|
||||
ondelete='SET NULL',
|
||||
use_alter=True,
|
||||
),
|
||||
@@ -568,7 +555,7 @@ class ShippingNoticeDocument(Base):
|
||||
)
|
||||
|
||||
|
||||
class ShippingNoticeCandidate(Base):
|
||||
class ShippingOrderCandidate(Base):
|
||||
"""
|
||||
订单候选:一封邮件中识别出的独立发货通知(阶段二,尚未创建 Task)。
|
||||
|
||||
@@ -576,42 +563,42 @@ class ShippingNoticeCandidate(Base):
|
||||
重复检测、自动建单与待补字段状态均落在 Candidate 级。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_notice_candidates'
|
||||
__tablename__ = 'shipping_order_candidates'
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"candidate_status IN ('provisional', 'accepted', 'rejected', 'expired')",
|
||||
name='ck_shipping_notice_candidates_status',
|
||||
name='ck_shipping_order_candidates_status',
|
||||
),
|
||||
CheckConstraint(
|
||||
"acceptance_mode IS NULL OR acceptance_mode IN ('automatic', 'manual', 'legacy')",
|
||||
name='ck_shipping_notice_candidates_acceptance_mode',
|
||||
name='ck_shipping_order_candidates_acceptance_mode',
|
||||
),
|
||||
UniqueConstraint('candidate_no', name='uq_shipping_notice_candidates_candidate_no'),
|
||||
UniqueConstraint('candidate_no', name='uq_shipping_order_candidates_candidate_no'),
|
||||
UniqueConstraint(
|
||||
'intake_id', 'candidate_key', 'order_extraction_run_id',
|
||||
name='uq_shipping_notice_candidates_intake_key_run',
|
||||
name='uq_shipping_order_candidates_intake_key_run',
|
||||
),
|
||||
# 保证主文档与 Candidate 同属一 Intake,禁止跨 Intake 挂接
|
||||
ForeignKeyConstraint(
|
||||
['primary_document_id', 'intake_id'],
|
||||
['shipping_notice_documents.id', 'shipping_notice_documents.intake_id'],
|
||||
name='fk_shipping_notice_candidates_document_intake',
|
||||
['shipping_order_documents.id', 'shipping_order_documents.intake_id'],
|
||||
name='fk_shipping_order_candidates_document_intake',
|
||||
),
|
||||
Index('ix_shipping_notice_candidates_intake_id', 'intake_id'),
|
||||
Index('ix_shipping_notice_candidates_primary_document_id', 'primary_document_id'),
|
||||
Index('ix_shipping_notice_candidates_po_number', 'po_number'),
|
||||
Index('ix_shipping_order_candidates_intake_id', 'intake_id'),
|
||||
Index('ix_shipping_order_candidates_primary_document_id', 'primary_document_id'),
|
||||
Index('ix_shipping_order_candidates_po_number', 'po_number'),
|
||||
Index(
|
||||
'ix_shipping_notice_candidates_user_fingerprint',
|
||||
'ix_shipping_order_candidates_user_fingerprint',
|
||||
'business_fingerprint',
|
||||
),
|
||||
Index('ix_shipping_notice_candidates_duplicate_status', 'duplicate_status'),
|
||||
Index('ix_shipping_notice_candidates_fulfillment_gate', 'candidate_status', 'is_current_version'),
|
||||
Index('ix_shipping_order_candidates_duplicate_status', 'duplicate_status'),
|
||||
Index('ix_shipping_order_candidates_fulfillment_gate', 'candidate_status', 'is_current_version'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
candidate_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
intake_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_intakes.id'),
|
||||
ForeignKey('shipping_order_intakes.id'),
|
||||
nullable=False,
|
||||
)
|
||||
primary_document_id: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
@@ -622,7 +609,7 @@ class ShippingNoticeCandidate(Base):
|
||||
ForeignKey('shipping_order_extractions.id'), nullable=True, index=True,
|
||||
)
|
||||
order_extraction_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
|
||||
ForeignKey('shipping_order_processing_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
# 仅当前版本候选可进入建单;旧版本保留为只读审计和重新识别失败时的回退依据。
|
||||
is_current_version: Mapped[bool] = mapped_column(
|
||||
@@ -674,7 +661,7 @@ class ShippingNoticeCandidate(Base):
|
||||
duplicate_resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
consumed_task_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_tasks.id'),
|
||||
ForeignKey('shipping_notices.id'),
|
||||
nullable=True,
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
backend/app/models/shipping_customer.py
|
||||
|
||||
用途:货代标准客户、客户识别证据、业务单聚合与业务编号流水模型。
|
||||
依赖:models.base.Base、users、shipping_tasks。
|
||||
逻辑:客户主数据提供稳定身份;ShippingCase 聚合任务修订链;流水表供后续编号服务原子递增。
|
||||
依赖:models.base.Base、users、shipping_notices。
|
||||
逻辑:客户主数据提供稳定身份;ShippingCase 聚合 Notice 修订链;流水表供后续编号服务原子递增。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -216,8 +216,8 @@ class ShippingCase(Base):
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
customer: Mapped[Optional['ShippingCustomer']] = relationship('ShippingCustomer', back_populates='cases')
|
||||
tasks: Mapped[List['ShippingTask']] = relationship(
|
||||
'ShippingTask',
|
||||
tasks: Mapped[List['ShippingNotice']] = relationship(
|
||||
'ShippingNotice',
|
||||
back_populates='shipping_case',
|
||||
lazy='selectin',
|
||||
)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/models/shipping_customer_resolution.py
|
||||
|
||||
用途:保存订单候选的客户影子识别结果与人工标签。
|
||||
依赖:ShippingNoticeCandidate、ShippingNoticeIntake、ShippingCustomer、User。
|
||||
依赖:ShippingOrderCandidate、ShippingOrderIntake、ShippingCustomer、User。
|
||||
逻辑:订单候选抽取后幂等刷新本表;阶段 3 仅用于质量观测,禁止据此绑定业务单或生成编号。
|
||||
"""
|
||||
|
||||
@@ -32,12 +32,12 @@ class ShippingCustomerShadowResolution(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
candidate_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_candidates.id', ondelete='CASCADE'),
|
||||
ForeignKey('shipping_order_candidates.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
unique=True,
|
||||
)
|
||||
intake_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_intakes.id', ondelete='CASCADE'),
|
||||
ForeignKey('shipping_order_intakes.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/models/shipping_document_layout.py
|
||||
|
||||
用途:持久化每份发货通知 Document 的版本化版面解析生命周期、冻结快照和质量结果。
|
||||
依赖:shipping_notice_documents、jobs、SQLAlchemy Base。
|
||||
依赖:shipping_order_documents、jobs、SQLAlchemy Base。
|
||||
逻辑:同一 Document 版本递增;运行租约隔离旧 Worker,只有成功版本可成为 Document 当前布局。
|
||||
"""
|
||||
|
||||
@@ -20,17 +20,17 @@ from app.models.base import Base
|
||||
class ShippingDocumentLayoutVersion(Base):
|
||||
"""单文档版面解析版本;payload/checksum 一旦完成即不可原地改写。"""
|
||||
|
||||
__tablename__ = 'shipping_document_layout_versions'
|
||||
__tablename__ = 'shipping_order_document_layout_versions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('document_id', 'version', name='uq_shipping_document_layout_document_version'),
|
||||
UniqueConstraint('document_id', 'version', name='uq_shipping_order_document_layout_document_version'),
|
||||
CheckConstraint(
|
||||
"status IN ('queued', 'running', 'ready', 'needs_review', 'failed', 'unsupported')",
|
||||
name='ck_shipping_document_layout_status',
|
||||
name='ck_shipping_order_document_layout_status',
|
||||
),
|
||||
Index('ix_shipping_document_layout_document_status', 'document_id', 'status'),
|
||||
Index('ix_shipping_document_layout_content_parser', 'source_content_hash', 'parser_key'),
|
||||
Index('ix_shipping_order_document_layout_document_status', 'document_id', 'status'),
|
||||
Index('ix_shipping_order_document_layout_content_parser', 'source_content_hash', 'parser_key'),
|
||||
Index(
|
||||
'uq_shipping_document_layout_one_active',
|
||||
'uq_shipping_order_document_layout_one_active',
|
||||
'document_id',
|
||||
unique=True,
|
||||
postgresql_where=text("status IN ('queued', 'running')"),
|
||||
@@ -40,7 +40,7 @@ class ShippingDocumentLayoutVersion(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
document_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_documents.id', ondelete='CASCADE'), nullable=False,
|
||||
ForeignKey('shipping_order_documents.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(24), default='queued', server_default='queued', nullable=False)
|
||||
@@ -66,6 +66,6 @@ class ShippingDocumentLayoutVersion(Base):
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
document = relationship(
|
||||
'ShippingNoticeDocument', foreign_keys=[document_id], back_populates='layout_versions',
|
||||
'ShippingOrderDocument', foreign_keys=[document_id], back_populates='layout_versions',
|
||||
)
|
||||
job = relationship('Job', foreign_keys=[job_id])
|
||||
@@ -45,7 +45,7 @@ class ShippingDocumentProfileTestSuite(Base):
|
||||
|
||||
|
||||
class ShippingDocumentProfileTestSample(Base):
|
||||
"""盲测样本文档及管理员确认的明细/订单字段真值;不与建 Profile 的样本自动复用。"""
|
||||
"""盲测真值及确认时冻结的规范化 Layout 身份;不与建模样本自动复用。"""
|
||||
|
||||
__tablename__ = 'shipping_document_profile_test_samples'
|
||||
__table_args__ = (
|
||||
@@ -54,8 +54,14 @@ class ShippingDocumentProfileTestSample(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
suite_id: Mapped[int] = mapped_column(ForeignKey('shipping_document_profile_test_suites.id', ondelete='CASCADE'), nullable=False)
|
||||
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_documents.id'), nullable=False)
|
||||
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_documents.id'), nullable=False)
|
||||
table_id: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
layout_version_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_document_layout_versions.id'), nullable=True,
|
||||
)
|
||||
layout_payload_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
layout_parser_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
layout_parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
expected_rows_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
|
||||
expected_order_fields_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
created_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
models/shipping_excel_template.py
|
||||
|
||||
用途:定义版本化发货 Excel 模板及不可变任务导出产物。
|
||||
依赖:models.base.Base、库存源、订单 Schema、发货任务与库存快照模型。
|
||||
逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和。
|
||||
用途:定义版本化发货 Excel 模板及不可变 Notice 导出产物。
|
||||
依赖:models.base.Base、库存源、订单 Schema、ShippingNotice 与库存快照模型。
|
||||
逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和;
|
||||
co8e9f0a1b2c 已删除 export artifact 的 batch_id 列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -47,19 +48,17 @@ class ShippingExcelTemplate(Base):
|
||||
|
||||
|
||||
class ShippingExportArtifact(Base):
|
||||
"""一次任务导出的不可变产物及生成输入快照。"""
|
||||
"""一次 Notice 导出的不可变产物及生成输入快照。"""
|
||||
|
||||
__tablename__ = 'shipping_export_artifacts'
|
||||
__tablename__ = 'shipping_notice_export_artifacts'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('artifact_no', name='uq_shipping_export_artifacts_no'),
|
||||
Index('ix_shipping_export_artifacts_task_created', 'task_id', 'created_at'),
|
||||
Index('ix_shipping_export_artifacts_batch_created', 'batch_id', 'created_at'),
|
||||
UniqueConstraint('artifact_no', name='uq_shipping_notice_export_artifacts_no'),
|
||||
Index('ix_shipping_notice_export_artifacts_task_created', 'task_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
artifact_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False, index=True)
|
||||
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), nullable=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False, index=True)
|
||||
template_id: Mapped[int] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=False)
|
||||
order_schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
||||
order_extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
|
||||
@@ -74,4 +73,4 @@ class ShippingExportArtifact(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
template: Mapped[ShippingExcelTemplate] = relationship()
|
||||
task: Mapped['ShippingTask'] = relationship()
|
||||
task: Mapped['ShippingNotice'] = relationship()
|
||||
@@ -12,17 +12,17 @@ from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingFreightCancellation(Base):
|
||||
"""已上传旧任务的撤销申请与货代回执;成功前新版本不得履约。"""
|
||||
"""已上传旧 Notice 的撤销申请与货代回执;成功前新版本不得履约。"""
|
||||
|
||||
__tablename__ = 'shipping_freight_cancellations'
|
||||
__tablename__ = 'shipping_notice_freight_cancellations'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('old_task_id', 'new_task_id', name='uq_shipping_freight_cancellations_version_pair'),
|
||||
Index('ix_shipping_freight_cancellations_old_status', 'old_task_id', 'status'),
|
||||
UniqueConstraint('old_task_id', 'new_task_id', name='uq_shipping_notice_freight_cancellations_version_pair'),
|
||||
Index('ix_shipping_notice_freight_cancellations_old_status', 'old_task_id', 'status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
old_task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False)
|
||||
new_task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False)
|
||||
old_task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
|
||||
new_task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='cancellation_required')
|
||||
requested_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
requested_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/models/shipping_fulfillment.py
|
||||
|
||||
用途:保存预约单全局注册、每轮库存核验和 Excel 对预约单的不可重叠归属。
|
||||
依赖:冻结订单 Snapshot、库存文件、导出 Artifact 与 SQLAlchemy Base。
|
||||
依赖:冻结订单 Snapshot、库存文件、导出 Artifact 与 SQLAlchemy Base;Notice 主表 shipping_notices。
|
||||
逻辑:Snapshot 行可保留历史预约号;全局 Reservation 决定当前有效行和履约状态,核验与 Artifact 行均追加保存。
|
||||
"""
|
||||
|
||||
@@ -21,25 +21,27 @@ from app.models.base import Base
|
||||
class ShippingReservation(Base):
|
||||
"""预约单当前履约注册表;Reservation ID 全局只能归属一个采购单。"""
|
||||
|
||||
__tablename__ = 'shipping_reservations'
|
||||
__tablename__ = 'shipping_notice_reservations'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('reservation_id', name='uq_shipping_reservations_reservation_id'),
|
||||
UniqueConstraint('reservation_id', name='uq_shipping_notice_reservations_reservation_id'),
|
||||
CheckConstraint(
|
||||
"status IN ('pending', 'available', 'artifact_reserved', 'uploaded', 'external_change_required')",
|
||||
name='ck_shipping_reservations_status',
|
||||
name='ck_shipping_notice_reservations_status',
|
||||
),
|
||||
Index('ix_shipping_reservations_task_status', 'task_id', 'status'),
|
||||
Index('ix_shipping_notice_reservations_task_status', 'task_id', 'status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
|
||||
snapshot_line_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_snapshot_lines.id'), nullable=False)
|
||||
reservation_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
po_number_normalized: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
part_number: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
|
||||
current_artifact_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_export_artifacts.id'), nullable=True)
|
||||
current_artifact_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_notice_export_artifacts.id'), nullable=True,
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
@@ -47,14 +49,17 @@ class ShippingReservation(Base):
|
||||
class ShippingInventoryVerification(Base):
|
||||
"""一次任务库存核验的不可变轮次,绑定当时有效库存快照。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_verifications'
|
||||
__tablename__ = 'shipping_notice_inventory_verifications'
|
||||
__table_args__ = (
|
||||
CheckConstraint("status IN ('completed', 'expired', 'superseded')", name='ck_shipping_inventory_verifications_status'),
|
||||
Index('ix_shipping_inventory_verifications_task_created', 'task_id', 'created_at'),
|
||||
CheckConstraint(
|
||||
"status IN ('completed', 'expired', 'superseded')",
|
||||
name='ck_shipping_notice_inventory_verifications_status',
|
||||
),
|
||||
Index('ix_shipping_notice_inventory_verifications_task_created', 'task_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
|
||||
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
|
||||
source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='completed', server_default='completed')
|
||||
@@ -69,15 +74,23 @@ class ShippingInventoryVerification(Base):
|
||||
class ShippingInventoryVerificationLine(Base):
|
||||
"""一个预约单在一轮库存中的需求、可用数量和确定性结果。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_verification_lines'
|
||||
__tablename__ = 'shipping_notice_inventory_verification_lines'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('verification_id', 'reservation_id', name='uq_shipping_inventory_verification_lines_reservation'),
|
||||
CheckConstraint("status IN ('available', 'shortage', 'invalid')", name='ck_shipping_inventory_verification_lines_status'),
|
||||
UniqueConstraint(
|
||||
'verification_id', 'reservation_id',
|
||||
name='uq_shipping_notice_inventory_verification_lines_reservation',
|
||||
),
|
||||
CheckConstraint(
|
||||
"status IN ('available', 'shortage', 'invalid')",
|
||||
name='ck_shipping_notice_inventory_verification_lines_status',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
verification_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_verifications.id', ondelete='CASCADE'), nullable=False)
|
||||
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_reservations.id'), nullable=False)
|
||||
verification_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_inventory_verifications.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
|
||||
required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
|
||||
available_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
@@ -89,33 +102,43 @@ class ShippingInventoryVerificationLine(Base):
|
||||
class ShippingExportArtifactLine(Base):
|
||||
"""将本轮 Excel 与预约单一对一绑定,防止同一预约单进入两个有效 Artifact。"""
|
||||
|
||||
__tablename__ = 'shipping_export_artifact_lines'
|
||||
__tablename__ = 'shipping_notice_export_artifact_lines'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('artifact_id', 'reservation_id', name='uq_shipping_export_artifact_lines_artifact_reservation'),
|
||||
UniqueConstraint(
|
||||
'artifact_id', 'reservation_id',
|
||||
name='uq_shipping_notice_export_artifact_lines_artifact_reservation',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
artifact_id: Mapped[int] = mapped_column(ForeignKey('shipping_export_artifacts.id', ondelete='CASCADE'), nullable=False)
|
||||
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_reservations.id'), nullable=False)
|
||||
verification_line_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_verification_lines.id'), nullable=False)
|
||||
artifact_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_export_artifacts.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
|
||||
verification_line_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_inventory_verification_lines.id'), nullable=False,
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingUploadAttempt(Base):
|
||||
"""一次 Artifact 上传尝试;回调幂等键和人工回执均在此处归档。"""
|
||||
|
||||
__tablename__ = 'shipping_upload_attempts'
|
||||
__tablename__ = 'shipping_notice_upload_attempts'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('artifact_id', 'attempt_no', name='uq_shipping_upload_attempts_artifact_attempt'),
|
||||
UniqueConstraint('idempotency_key', name='uq_shipping_upload_attempts_idempotency'),
|
||||
UniqueConstraint('callback_id', name='uq_shipping_upload_attempts_callback'),
|
||||
CheckConstraint("mode IN ('rpa', 'manual')", name='ck_shipping_upload_attempts_mode'),
|
||||
CheckConstraint("status IN ('pending', 'running', 'succeeded', 'failed', 'timed_out')", name='ck_shipping_upload_attempts_status'),
|
||||
Index('ix_shipping_upload_attempts_artifact_created', 'artifact_id', 'created_at'),
|
||||
UniqueConstraint('artifact_id', 'attempt_no', name='uq_shipping_notice_upload_attempts_artifact_attempt'),
|
||||
UniqueConstraint('idempotency_key', name='uq_shipping_notice_upload_attempts_idempotency'),
|
||||
UniqueConstraint('callback_id', name='uq_shipping_notice_upload_attempts_callback'),
|
||||
CheckConstraint("mode IN ('rpa', 'manual')", name='ck_shipping_notice_upload_attempts_mode'),
|
||||
CheckConstraint(
|
||||
"status IN ('pending', 'running', 'succeeded', 'failed', 'timed_out')",
|
||||
name='ck_shipping_notice_upload_attempts_status',
|
||||
),
|
||||
Index('ix_shipping_notice_upload_attempts_artifact_created', 'artifact_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
artifact_id: Mapped[int] = mapped_column(ForeignKey('shipping_export_artifacts.id'), nullable=False)
|
||||
artifact_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_export_artifacts.id'), nullable=False)
|
||||
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
mode: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
@@ -126,6 +149,8 @@ class ShippingUploadAttempt(Base):
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
evidence_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True)
|
||||
# [BE-05] RPA 成功时持久化绿色 DOM 证据(kind/selector/observed_at/filename 等)。
|
||||
success_evidence_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
operator_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
backend/app/models/shipping_notice_line.py
|
||||
|
||||
用途:正式发货通知行(shipping_notice_lines),对齐蓝图建单后命名空间。
|
||||
依赖:shipping_notices、shipping_order_snapshot_lines、SQLAlchemy Base。
|
||||
逻辑:冻结 Snapshot 时双写;履约仍以 Snapshot 为权威,本表供 Notice 域查询与 1:N 扩展。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, Numeric, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingNoticeLine(Base):
|
||||
"""
|
||||
正式发货通知行投影。
|
||||
|
||||
核心逻辑:由 Snapshot 冻结路径幂等写入;position 在同一 Notice 内唯一。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_notice_lines'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('notice_id', 'position', name='uq_shipping_notice_lines_position'),
|
||||
Index('ix_shipping_notice_lines_notice_id', 'notice_id'),
|
||||
Index('ix_shipping_notice_lines_snapshot_line_id', 'snapshot_line_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
notice_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=False)
|
||||
snapshot_line_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_snapshot_lines.id', ondelete='SET NULL'), nullable=True,
|
||||
)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
line_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
reservation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
required_qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
|
||||
field_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
@@ -1,316 +0,0 @@
|
||||
"""
|
||||
backend/app/models/shipping_notice_workflow.py
|
||||
|
||||
用途:定义货代发货通知 Workflow / Item / Version / Event 四层事实源。
|
||||
依赖:users、agents、shipping_notice_documents、shipping_order_extraction_runs、
|
||||
shipping_order_review_cases、shipping_tasks。
|
||||
逻辑:一次上传批次 = Workflow;每个 PDF 创建时即有 WorkflowItem;
|
||||
重识别只新增 ItemVersion 并切换 current 指针;用户可见节点写入 WorkflowEvent;
|
||||
审计通过业务编号软引用本表,禁止级联删除抹除追溯。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
JSON,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
def _utc_now() -> datetime:
|
||||
"""Naive UTC now;供模型 default/onupdate,替代已弃用的 datetime.utcnow。"""
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
class ShippingNoticeWorkflow(Base):
|
||||
"""一次上传/识别批次;重新打开对话复用未关闭 Workflow,不新建。"""
|
||||
|
||||
__tablename__ = 'shipping_notice_workflows'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('workflow_no', name='uq_shipping_notice_workflows_no'),
|
||||
CheckConstraint(
|
||||
"status IN ("
|
||||
"'open', 'completed', 'cancelled', 'failed'"
|
||||
")",
|
||||
name='ck_shipping_notice_workflows_status',
|
||||
),
|
||||
CheckConstraint('lock_version >= 1', name='ck_shipping_notice_workflows_lock_version'),
|
||||
Index(
|
||||
'ix_shipping_notice_workflows_conversation_status',
|
||||
'conversation_id',
|
||||
'status',
|
||||
'updated_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflows_owner_status',
|
||||
'owner_user_id',
|
||||
'status',
|
||||
'updated_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflows_open_conversation',
|
||||
'conversation_id',
|
||||
'updated_at',
|
||||
postgresql_where=text("status = 'open'"),
|
||||
sqlite_where=text("status = 'open'"),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
workflow_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
|
||||
owner_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='open', server_default='open')
|
||||
current_stage: Mapped[str] = mapped_column(
|
||||
String(64), nullable=False, default='queued', server_default='queued',
|
||||
)
|
||||
last_activity_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
closed_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
|
||||
)
|
||||
|
||||
|
||||
class ShippingNoticeWorkflowItem(Base):
|
||||
"""PDF 级稳定实体;识别开始前即存在,覆盖解析到 Excel 全阶段。"""
|
||||
|
||||
__tablename__ = 'shipping_notice_workflow_items'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('item_no', name='uq_shipping_notice_workflow_items_no'),
|
||||
UniqueConstraint(
|
||||
'workflow_id',
|
||||
'root_document_id',
|
||||
name='uq_shipping_notice_workflow_items_workflow_root_doc',
|
||||
),
|
||||
UniqueConstraint(
|
||||
'current_case_id',
|
||||
name='uq_shipping_notice_workflow_items_current_case',
|
||||
),
|
||||
CheckConstraint(
|
||||
"lifecycle_status IN ("
|
||||
"'queued', 'layout_parsing', 'extracting', 'pending_review', "
|
||||
"'building_order', 'inventory_matching', 'generating_excel', "
|
||||
"'manual_upload_pending', 'reparse_failed', "
|
||||
"'cancelled', 'failed', 'closed'"
|
||||
")",
|
||||
name='ck_shipping_notice_workflow_items_lifecycle',
|
||||
),
|
||||
CheckConstraint(
|
||||
"closed_reason IS NULL OR closed_reason IN ("
|
||||
"'confirmed', 'non_order', 'user_cancelled', 'admin_terminated', 'failed'"
|
||||
")",
|
||||
name='ck_shipping_notice_workflow_items_closed_reason',
|
||||
),
|
||||
CheckConstraint('lock_version >= 1', name='ck_shipping_notice_workflow_items_lock_version'),
|
||||
CheckConstraint(
|
||||
'current_version_no >= 1',
|
||||
name='ck_shipping_notice_workflow_items_version_no',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_items_workflow_lifecycle',
|
||||
'workflow_id',
|
||||
'lifecycle_status',
|
||||
'updated_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_items_conversation_lifecycle',
|
||||
'conversation_id',
|
||||
'lifecycle_status',
|
||||
'updated_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_items_owner_lifecycle',
|
||||
'owner_user_id',
|
||||
'lifecycle_status',
|
||||
'updated_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
'conversation_id',
|
||||
'updated_at',
|
||||
postgresql_where=text(
|
||||
"lifecycle_status NOT IN ('closed', 'cancelled')"
|
||||
),
|
||||
sqlite_where=text(
|
||||
"lifecycle_status NOT IN ('closed', 'cancelled')"
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
item_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
workflow_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_workflows.id'), nullable=False, index=True,
|
||||
)
|
||||
workflow_no: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
|
||||
# 同源 PDF 稳定身份:首次纳入时的 Document;替换文件不改变本字段。
|
||||
root_document_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_documents.id'), nullable=False, index=True,
|
||||
)
|
||||
current_document_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_documents.id'), nullable=False, index=True,
|
||||
)
|
||||
# 软指针:避免与 Version.workflow_item_id 形成循环外键;由 ledger 保证一致性。
|
||||
current_version_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True, index=True)
|
||||
current_version_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
current_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
current_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
current_case_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_review_cases.id'), nullable=True,
|
||||
)
|
||||
current_case_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
current_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
lifecycle_status: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default='queued', server_default='queued',
|
||||
)
|
||||
current_stage: Mapped[str] = mapped_column(
|
||||
String(64), nullable=False, default='queued', server_default='queued',
|
||||
)
|
||||
closed_reason: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
last_activity_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
|
||||
)
|
||||
|
||||
|
||||
class ShippingNoticeWorkflowItemVersion(Base):
|
||||
"""重识别版本链;关联 Run / Case / Task / Excel,旧版本只读留存。"""
|
||||
|
||||
__tablename__ = 'shipping_notice_workflow_item_versions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'workflow_item_id',
|
||||
'version_no',
|
||||
name='uq_shipping_notice_workflow_item_versions_item_no',
|
||||
),
|
||||
CheckConstraint('version_no >= 1', name='ck_shipping_notice_workflow_item_versions_no'),
|
||||
CheckConstraint(
|
||||
"status IN ("
|
||||
"'active', 'superseded', 'failed', 'cancelled'"
|
||||
")",
|
||||
name='ck_shipping_notice_workflow_item_versions_status',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_item_versions_item_created',
|
||||
'workflow_item_id',
|
||||
'created_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_item_versions_run',
|
||||
'run_id',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_item_versions_case',
|
||||
'case_id',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
workflow_item_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_workflow_items.id'), nullable=False, index=True,
|
||||
)
|
||||
item_no: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
workflow_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_workflows.id'), nullable=False, index=True,
|
||||
)
|
||||
workflow_no: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
version_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
document_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_documents.id'), nullable=False, index=True,
|
||||
)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
case_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_review_cases.id'), nullable=True,
|
||||
)
|
||||
case_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
task_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_tasks.id'), nullable=True,
|
||||
)
|
||||
task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
excel_artifact_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default='active', server_default='active',
|
||||
)
|
||||
is_current: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default='true')
|
||||
is_readonly: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default='false')
|
||||
superseded_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
|
||||
)
|
||||
|
||||
|
||||
class ShippingNoticeWorkflowEvent(Base):
|
||||
"""用户可见、按 Workflow 顺序递增的节点事件(与审计账本并存)。"""
|
||||
|
||||
__tablename__ = 'shipping_notice_workflow_events'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'workflow_id',
|
||||
'seq_no',
|
||||
name='uq_shipping_notice_workflow_events_seq',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_events_workflow_occurred',
|
||||
'workflow_id',
|
||||
'occurred_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_events_item_occurred',
|
||||
'workflow_item_id',
|
||||
'occurred_at',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
workflow_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_workflows.id'), nullable=False, index=True,
|
||||
)
|
||||
workflow_no: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
workflow_item_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_notice_workflow_items.id'), nullable=True, index=True,
|
||||
)
|
||||
item_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
workflow_item_version_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_notice_workflow_item_versions.id'), nullable=True,
|
||||
)
|
||||
version_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
seq_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
event_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
stage_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
message_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system')
|
||||
actor_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
occurred_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
|
||||
@@ -0,0 +1,55 @@
|
||||
"""
|
||||
backend/app/models/shipping_order_candidate_evidence.py
|
||||
|
||||
用途:Candidate 主证据/辅助证据/冲突证据的可查询关系表(蓝图 §六)。
|
||||
依赖:shipping_order_candidates、shipping_order_documents、SQLAlchemy Base。
|
||||
逻辑:替代仅落在 Candidate.evidence_json 的不可查询结构;PDF 优先裁决审计可按字段检索。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingOrderCandidateEvidence(Base):
|
||||
"""
|
||||
Candidate 与文档证据的角色化关联。
|
||||
|
||||
核心逻辑:primary_pdf 标识主证据;conflict 记录跨证据冲突;payload_json 存轻量引用非全文。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_order_candidate_evidences'
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"evidence_role IN ('primary_pdf', 'auxiliary', 'conflict', 'context')",
|
||||
name='ck_shipping_order_candidate_evidences_role',
|
||||
),
|
||||
CheckConstraint(
|
||||
"evidence_kind IN ('pdf', 'email_body', 'excel', 'word', 'image', 'ocr', 'model', 'other')",
|
||||
name='ck_shipping_order_candidate_evidences_kind',
|
||||
),
|
||||
Index('ix_shipping_order_candidate_evidences_candidate', 'candidate_id'),
|
||||
Index('ix_shipping_order_candidate_evidences_document', 'document_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
candidate_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_candidates.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
document_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_documents.id', ondelete='SET NULL'), nullable=True,
|
||||
)
|
||||
evidence_role: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
evidence_kind: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
is_primary: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false'))
|
||||
field_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
value_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
decision_rule_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
@@ -2,7 +2,7 @@
|
||||
models/shipping_order_candidate_qualification.py
|
||||
|
||||
用途:持久化 Candidate 级统一自动建单资格评估快照(追加式历史)。
|
||||
依赖:SQLAlchemy Base、shipping_notice_candidates / shipping_order_extraction_runs / users。
|
||||
依赖:SQLAlchemy Base、shipping_order_candidates / shipping_order_processing_runs / users。
|
||||
逻辑:每次评估追加一行;is_current 标记最新;模板质量信息仅出现在 parser_trace_json。
|
||||
"""
|
||||
|
||||
@@ -43,12 +43,12 @@ class ShippingOrderCandidateQualification(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
candidate_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_candidates.id'),
|
||||
ForeignKey('shipping_order_candidates.id'),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'),
|
||||
ForeignKey('shipping_order_processing_runs.id'),
|
||||
nullable=True,
|
||||
index=True,
|
||||
)
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
backend/app/models/shipping_order_document_profile.py
|
||||
|
||||
用途:保存订单坐标 Profile 的版本、样本绑定、可选客户范围与追加式配置审计。
|
||||
用途:保存订单坐标 Profile 的版本、样本绑定、可选客户范围、版面签名引用与追加式配置审计。
|
||||
依赖:订单 Schema、订单文档、用户和 SQLAlchemy Base。
|
||||
逻辑:Profile 主表保存可索引摘要与 scoring_policy_version;完整 v2 定义仍在 definition_json,
|
||||
样本/审计实体提供可追溯治理事实。
|
||||
逻辑:Profile 主表保存可索引摘要、scoring_policy_version 与当前有效版面签名轻量引用;
|
||||
完整签名存 ValidationRun.result_snapshot_json;完整 v2 定义仍在 definition_json。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -38,6 +38,8 @@ class ShippingOrderDocumentProfile(Base):
|
||||
postgresql_where=text("status = 'published'"),
|
||||
sqlite_where=text("status = 'published'"),
|
||||
),
|
||||
Index('ix_shipping_order_document_profiles_matching_signature_run', 'matching_signature_run_id'),
|
||||
Index('ix_shipping_order_document_profiles_matching_signature_checksum', 'matching_signature_checksum'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -50,13 +52,25 @@ class ShippingOrderDocumentProfile(Base):
|
||||
)
|
||||
structure_fingerprint: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
template_mode: Mapped[str] = mapped_column(String(32), nullable=False, default='coordinate_v2', server_default='coordinate_v2')
|
||||
template_mode: Mapped[str] = mapped_column(String(32), nullable=False, default='coordinate', server_default='coordinate')
|
||||
training_sample_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
|
||||
match_strategy_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
customer_ids_json: Mapped[Optional[list[int]]] = mapped_column(JSON, nullable=True)
|
||||
scoring_policy_version: Mapped[str] = mapped_column(
|
||||
String(64), nullable=False, default='order-profile-scoring.v1', server_default='order-profile-scoring.v1',
|
||||
)
|
||||
# 当前有效版面签名轻量引用;完整签名仅存在于 ValidationRun.result_snapshot_json。
|
||||
matching_signature_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey(
|
||||
'shipping_order_document_profile_validation_runs.id',
|
||||
ondelete='SET NULL',
|
||||
use_alter=True,
|
||||
name='fk_sodp_matching_signature_run',
|
||||
),
|
||||
nullable=True,
|
||||
)
|
||||
matching_signature_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
matching_signature_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
change_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
@@ -76,6 +90,11 @@ class ShippingOrderDocumentProfile(Base):
|
||||
source_profile: Mapped[Optional['ShippingOrderDocumentProfile']] = relationship(
|
||||
remote_side='ShippingOrderDocumentProfile.id', foreign_keys=[source_profile_id],
|
||||
)
|
||||
matching_signature_run: Mapped[Optional['ShippingOrderDocumentProfileValidationRun']] = relationship(
|
||||
'ShippingOrderDocumentProfileValidationRun',
|
||||
foreign_keys=[matching_signature_run_id],
|
||||
post_update=True,
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderDocumentProfileSample(Base):
|
||||
@@ -91,11 +110,11 @@ class ShippingOrderDocumentProfileSample(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
|
||||
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_documents.id'), nullable=False)
|
||||
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_documents.id'), nullable=False)
|
||||
table_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
sample_role: Mapped[str] = mapped_column(String(16), nullable=False, default='annotation', server_default='annotation')
|
||||
layout_version_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_document_layout_versions.id'), nullable=True,
|
||||
ForeignKey('shipping_order_document_layout_versions.id'), nullable=True,
|
||||
)
|
||||
source_content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
layout_payload_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
@@ -124,7 +143,7 @@ class ShippingOrderDocumentProfileAudit(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='SET NULL'), nullable=True)
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_documents.id', ondelete='SET NULL'), nullable=True)
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_documents.id', ondelete='SET NULL'), nullable=True)
|
||||
event_type: Mapped[str] = mapped_column(String(48), nullable=False)
|
||||
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
@@ -194,7 +213,7 @@ class ShippingOrderDocumentProfileSuggestionDecision(Base):
|
||||
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
|
||||
revision_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
sample_binding_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profile_samples.id', ondelete='SET NULL'), nullable=True)
|
||||
layout_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_document_layout_versions.id'), nullable=True)
|
||||
layout_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_layout_versions.id'), nullable=True)
|
||||
parser_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
||||
@@ -213,7 +232,11 @@ class ShippingOrderDocumentProfileValidationRun(Base):
|
||||
|
||||
__tablename__ = 'shipping_order_document_profile_validation_runs'
|
||||
__table_args__ = (
|
||||
CheckConstraint("run_type IN ('instant_check', 'current_sample', 'blind_test', 'scenario_coverage', 'schema_compatibility')", name='ck_shipping_order_document_profile_validation_runs_type'),
|
||||
CheckConstraint(
|
||||
"run_type IN ('instant_check', 'current_sample', 'blind_test', 'scenario_coverage', "
|
||||
"'schema_compatibility', 'layout_signature', 'cross_template_overlap', 'xfa_structure_signature')",
|
||||
name='ck_shipping_order_document_profile_validation_runs_type',
|
||||
),
|
||||
CheckConstraint("status IN ('pending', 'running', 'passed', 'failed')", name='ck_shipping_order_document_profile_validation_runs_status'),
|
||||
Index('ix_shipping_order_document_profile_validation_runs_profile_created', 'profile_id', 'created_at'),
|
||||
Index('ix_shipping_order_document_profile_validation_runs_checksum', 'profile_id', 'definition_checksum'),
|
||||
@@ -226,7 +249,7 @@ class ShippingOrderDocumentProfileValidationRun(Base):
|
||||
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
||||
schema_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
sample_binding_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profile_samples.id', ondelete='SET NULL'), nullable=True)
|
||||
layout_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_document_layout_versions.id'), nullable=True)
|
||||
layout_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_layout_versions.id'), nullable=True)
|
||||
layout_payload_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
parser_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
@@ -258,6 +281,16 @@ class ShippingOrderDocumentProfilePublishCheckReport(Base):
|
||||
definition_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
lock_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
validation_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profile_validation_runs.id', ondelete='SET NULL'), nullable=True)
|
||||
matching_signature_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_document_profile_validation_runs.id', ondelete='SET NULL'),
|
||||
nullable=True,
|
||||
)
|
||||
matching_signature_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
overlap_validation_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_document_profile_validation_runs.id', ondelete='SET NULL'),
|
||||
nullable=True,
|
||||
)
|
||||
matcher_policy_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
base_published_profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='SET NULL'), nullable=True)
|
||||
semantic_diff_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
blocking_items_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
backend/app/models/shipping_order_document_version.py
|
||||
|
||||
用途:OT 文档/重识别版本台账(shipping_order_document_versions),对齐蓝图。
|
||||
依赖:shipping_order_tasks、shipping_order_processing_runs、SQLAlchemy Base。
|
||||
逻辑:每次新建/重识别 Run 挂到同一 OT 时追加版本;替代仅靠 Notice.document_version 的弱模型。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingOrderDocumentVersion(Base):
|
||||
"""
|
||||
OT 下的文档识别版本。
|
||||
|
||||
核心逻辑:(order_task_id, version) 唯一;extraction_run_id 追溯本次识别。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_order_document_versions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('order_task_id', 'version', name='uq_shipping_order_document_versions_task_version'),
|
||||
Index('ix_shipping_order_document_versions_run', 'extraction_run_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
order_task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=False)
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
extraction_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_processing_runs.id', ondelete='SET NULL'), nullable=True,
|
||||
)
|
||||
content_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/models/shipping_order_extraction_quality.py
|
||||
|
||||
用途:保存订单抽取 L7 影子验收批次、双人匿名标签和双角色批准事实。
|
||||
依赖:Agent、User、ShippingOrderSchemaVersion、ShippingOrderExtractionRun。
|
||||
依赖:Agent、User、ShippingOrderSchemaVersion、ShippingOrderProcessingRun。
|
||||
逻辑:批次锁定 owner/schema/阈值;同 Run 两名管理员标签一致后计入指标,达标后双人批准供 Runtime Binding 门禁引用。
|
||||
"""
|
||||
|
||||
@@ -69,7 +69,7 @@ class ShippingOrderExtractionQualityLabel(Base):
|
||||
batch_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_quality_batches.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extraction_runs.id'), nullable=False)
|
||||
run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_processing_runs.id'), nullable=False)
|
||||
reviewer_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
|
||||
core_expected_count: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
core_extracted_count: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
"""
|
||||
backend/app/models/shipping_order_extraction_run.py
|
||||
|
||||
用途:定义建单前订单抽取的领域运行记录及其冻结 Intake 集合。
|
||||
依赖:agents、users、jobs、shipping_notice_intakes、shipping_order_schema_versions。
|
||||
用途:定义建单前订单 Processing Run 的领域运行记录及其冻结 Intake 集合。
|
||||
物理表名:shipping_order_processing_runs / _run_intakes / _plans / _units /
|
||||
shipping_order_route_decisions(本文件名保留以减少 import 变更)。
|
||||
依赖:agents、users、jobs、shipping_order_intakes、shipping_order_schema_versions。
|
||||
逻辑:Run 保存用户可见生命周期和不可变输入快照;自动建单策略随 Schema 快照冻结。
|
||||
取消为请求语义:cancellation_* 元数据记录请求与生效;Worker 在安全点收口,
|
||||
progress_version 作为最后活动版本供轮询与乐观协作。
|
||||
会话多任务聚合(2026-08-03 阶段 1):用户可见任务(OT-…)与内部 Run(WF-/SNER-…)分层;
|
||||
已移除 uq_*_active_conversation,同会话允许多个 queued|processing Run;
|
||||
统一提交靠 can_append / composer_context / focused_user_task 裁决追加或新建。
|
||||
upload_batch_id 仅隔离 Intake 选择,不得充当 user_task_no;
|
||||
user_task_no 延迟至 Candidate/OT 形成后分配(nullable);reparse/后继 Run 继承谱系 OT。
|
||||
client_submission_id 为客户端幂等键(与 user_id 部分唯一);
|
||||
根任务 submission_ordinal 在 (user_id, conversation_id) 上部分唯一。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
@@ -31,44 +41,80 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingOrderExtractionRun(Base):
|
||||
"""一次建单前订单抽取业务运行;状态只允许按领域状态机单调推进。"""
|
||||
def _default_user_task_no() -> str:
|
||||
"""生成默认用户可见任务号;正式创建路径会覆盖为与 Run 对齐的 OT- 编号。"""
|
||||
return f"OT-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
__tablename__ = 'shipping_order_extraction_runs'
|
||||
|
||||
class ShippingOrderProcessingRun(Base):
|
||||
"""一次建单前订单 Processing 业务运行;状态只允许按领域状态机单调推进。"""
|
||||
|
||||
__tablename__ = 'shipping_order_processing_runs'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('run_no', name='uq_shipping_order_extraction_runs_no'),
|
||||
UniqueConstraint('idempotency_key', name='uq_shipping_order_extraction_runs_idempotency'),
|
||||
UniqueConstraint('run_no', name='uq_shipping_order_processing_runs_no'),
|
||||
UniqueConstraint('idempotency_key', name='uq_shipping_order_processing_runs_idempotency'),
|
||||
CheckConstraint(
|
||||
"status IN ('queued', 'processing', 'completed', "
|
||||
"'partially_completed', 'review_required', 'failed', 'cancelled')",
|
||||
name='ck_shipping_order_extraction_runs_status',
|
||||
name='ck_shipping_order_processing_runs_status',
|
||||
),
|
||||
Index('ix_shipping_order_extraction_runs_user_created', 'user_id', 'created_at'),
|
||||
Index('ix_shipping_order_extraction_runs_conversation_created', 'conversation_id', 'created_at'),
|
||||
Index('ix_shipping_order_extraction_runs_status_created', 'status', 'created_at'),
|
||||
CheckConstraint(
|
||||
"input_lifecycle IN ('open', 'freezing', 'frozen', 'closed')",
|
||||
name='ck_shipping_order_processing_runs_input_lifecycle',
|
||||
),
|
||||
Index('ix_shipping_order_processing_runs_user_created', 'user_id', 'created_at'),
|
||||
Index('ix_shipping_order_processing_runs_conversation_created', 'conversation_id', 'created_at'),
|
||||
Index('ix_shipping_order_processing_runs_status_created', 'status', 'created_at'),
|
||||
# 阶段 1:非唯一查询索引,替代原 partial unique(同会话多活跃 Run)。
|
||||
Index(
|
||||
'uq_shipping_order_extraction_runs_active_conversation',
|
||||
'ix_shipping_order_processing_runs_conversation_status',
|
||||
'user_id',
|
||||
'owner_agent_id',
|
||||
'conversation_id',
|
||||
unique=True,
|
||||
postgresql_where=text("status IN ('queued', 'processing')"),
|
||||
sqlite_where=text("status IN ('queued', 'processing')"),
|
||||
'status',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_order_extraction_runs_cancel_requested',
|
||||
'ix_shipping_order_processing_runs_user_task_no',
|
||||
'user_task_no',
|
||||
),
|
||||
Index(
|
||||
'uq_shipping_order_processing_runs_client_submission',
|
||||
'user_id',
|
||||
'client_submission_id',
|
||||
unique=True,
|
||||
postgresql_where=text('client_submission_id IS NOT NULL'),
|
||||
sqlite_where=text('client_submission_id IS NOT NULL'),
|
||||
),
|
||||
# 根任务(非 reparse/后继)会话内提交序号唯一;后继 Run 可继承同一序号。
|
||||
Index(
|
||||
'uq_shipping_order_processing_runs_submission_ordinal',
|
||||
'user_id',
|
||||
'conversation_id',
|
||||
'submission_ordinal',
|
||||
unique=True,
|
||||
postgresql_where=text(
|
||||
'reparse_of_run_id IS NULL AND submission_ordinal IS NOT NULL'
|
||||
),
|
||||
sqlite_where=text(
|
||||
'reparse_of_run_id IS NULL AND submission_ordinal IS NOT NULL'
|
||||
),
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_order_processing_runs_cancel_requested',
|
||||
'cancellation_requested_at',
|
||||
'status',
|
||||
),
|
||||
CheckConstraint(
|
||||
"cancellation_actor_type IS NULL OR cancellation_actor_type IN "
|
||||
"('user', 'admin', 'system')",
|
||||
name='ck_shipping_order_extraction_runs_cancel_actor',
|
||||
name='ck_shipping_order_processing_runs_cancel_actor',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# 用户可见任务号(OT-…);Candidate/OT 形成前为 NULL;reparse 继承源号。
|
||||
user_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
|
||||
owner_agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), nullable=False, index=True)
|
||||
parser_engine_version: Mapped[str] = mapped_column(String(64), nullable=False, default='deterministic-order-parser.v1')
|
||||
@@ -76,10 +122,10 @@ class ShippingOrderExtractionRun(Base):
|
||||
auto_freeze_policy_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
# 重新识别创建新 Run;谱系字段保留旧结果,禁止用原地覆盖破坏审计事实。
|
||||
reparse_of_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
|
||||
ForeignKey('shipping_order_processing_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
superseded_by_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
|
||||
ForeignKey('shipping_order_processing_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
reparse_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
reparse_comment: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
@@ -96,6 +142,15 @@ class ShippingOrderExtractionRun(Base):
|
||||
idempotency_key: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||
phase: Mapped[str] = mapped_column(String(64), nullable=False, default='queued', server_default='queued')
|
||||
# 用户可见任务输入生命周期;前端只消费 can_append,不展示原文案。
|
||||
input_lifecycle: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default='open', server_default='open',
|
||||
)
|
||||
input_frozen_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
composer_context_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
submission_ordinal: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
# 客户端提交幂等键;与 user_id 组成部分唯一索引。
|
||||
client_submission_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
current_job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True, index=True)
|
||||
execution_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
extraction_completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
@@ -131,20 +186,20 @@ class ShippingOrderExtractionRun(Base):
|
||||
result_persisted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
intakes: Mapped[list['ShippingOrderExtractionRunIntake']] = relationship(
|
||||
back_populates='run', cascade='all, delete-orphan', order_by='ShippingOrderExtractionRunIntake.position',
|
||||
intakes: Mapped[list['ShippingOrderProcessingRunIntake']] = relationship(
|
||||
back_populates='run', cascade='all, delete-orphan', order_by='ShippingOrderProcessingRunIntake.position',
|
||||
)
|
||||
reparse_source: Mapped[Optional['ShippingOrderExtractionRun']] = relationship(
|
||||
'ShippingOrderExtractionRun', foreign_keys=[reparse_of_run_id], remote_side='ShippingOrderExtractionRun.id',
|
||||
reparse_source: Mapped[Optional['ShippingOrderProcessingRun']] = relationship(
|
||||
'ShippingOrderProcessingRun', foreign_keys=[reparse_of_run_id], remote_side='ShippingOrderProcessingRun.id',
|
||||
)
|
||||
superseding_run: Mapped[Optional['ShippingOrderExtractionRun']] = relationship(
|
||||
'ShippingOrderExtractionRun', foreign_keys=[superseded_by_run_id], remote_side='ShippingOrderExtractionRun.id',
|
||||
superseding_run: Mapped[Optional['ShippingOrderProcessingRun']] = relationship(
|
||||
'ShippingOrderProcessingRun', foreign_keys=[superseded_by_run_id], remote_side='ShippingOrderProcessingRun.id',
|
||||
)
|
||||
extraction_plan: Mapped[Optional['ShippingOrderExtractionPlan']] = relationship(
|
||||
extraction_plan: Mapped[Optional['ShippingOrderProcessingPlan']] = relationship(
|
||||
back_populates='run', cascade='all, delete-orphan', uselist=False,
|
||||
)
|
||||
route_decisions: Mapped[list['ShippingOrderExtractionRouteDecision']] = relationship(
|
||||
back_populates='run', cascade='all, delete-orphan', order_by='ShippingOrderExtractionRouteDecision.id',
|
||||
route_decisions: Mapped[list['ShippingOrderRouteDecision']] = relationship(
|
||||
back_populates='run', cascade='all, delete-orphan', order_by='ShippingOrderRouteDecision.id',
|
||||
)
|
||||
review_cases: Mapped[list['ShippingOrderReviewCase']] = relationship(
|
||||
'ShippingOrderReviewCase', back_populates='run', cascade='all, delete-orphan',
|
||||
@@ -152,16 +207,16 @@ class ShippingOrderExtractionRun(Base):
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderExtractionRunIntake(Base):
|
||||
class ShippingOrderProcessingRunIntake(Base):
|
||||
"""Run 冻结的 Intake 成员;position 保证输入集合顺序稳定且可审计。"""
|
||||
|
||||
__tablename__ = 'shipping_order_extraction_run_intakes'
|
||||
__tablename__ = 'shipping_order_processing_run_intakes'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('run_id', 'intake_id', name='uq_shipping_order_extraction_run_intake'),
|
||||
UniqueConstraint('run_id', 'position', name='uq_shipping_order_extraction_run_position'),
|
||||
Index('ix_shipping_order_extraction_run_intakes_intake', 'intake_id'),
|
||||
UniqueConstraint('run_id', 'intake_id', name='uq_shipping_order_processing_run_intake'),
|
||||
UniqueConstraint('run_id', 'position', name='uq_shipping_order_processing_run_position'),
|
||||
Index('ix_shipping_order_processing_run_intakes_intake', 'intake_id'),
|
||||
Index(
|
||||
'uq_shipping_order_extraction_run_intakes_active_intake',
|
||||
'uq_shipping_order_processing_run_intakes_active_intake',
|
||||
'intake_id',
|
||||
unique=True,
|
||||
postgresql_where=text('released_at IS NULL'),
|
||||
@@ -171,32 +226,32 @@ class ShippingOrderExtractionRunIntake(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id', ondelete='CASCADE'), nullable=False,
|
||||
ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
intake_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_intakes.id'), nullable=False)
|
||||
intake_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=False)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
released_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
run: Mapped['ShippingOrderExtractionRun'] = relationship(back_populates='intakes')
|
||||
run: Mapped['ShippingOrderProcessingRun'] = relationship(back_populates='intakes')
|
||||
|
||||
|
||||
class ShippingOrderExtractionPlan(Base):
|
||||
class ShippingOrderProcessingPlan(Base):
|
||||
"""Run 的不可变抽取计划;计划版本和快照哈希共同锚定冻结输入。"""
|
||||
|
||||
__tablename__ = 'shipping_order_extraction_plans'
|
||||
__tablename__ = 'shipping_order_processing_plans'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('run_id', name='uq_shipping_order_extraction_plans_run'),
|
||||
UniqueConstraint('run_id', name='uq_shipping_order_processing_plans_run'),
|
||||
CheckConstraint(
|
||||
"status IN ('planned', 'running', 'completed', 'partial_failed', 'failed')",
|
||||
name='ck_shipping_order_extraction_plans_status',
|
||||
name='ck_shipping_order_processing_plans_status',
|
||||
),
|
||||
Index('ix_shipping_order_extraction_plans_status_created', 'status', 'created_at'),
|
||||
Index('ix_shipping_order_processing_plans_status_created', 'status', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id', ondelete='CASCADE'), nullable=False,
|
||||
ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
# 版本标识是稳定的可读契约,须容纳带业务命名空间的版本号。
|
||||
plan_version: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
@@ -208,52 +263,52 @@ class ShippingOrderExtractionPlan(Base):
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
|
||||
run: Mapped['ShippingOrderExtractionRun'] = relationship(back_populates='extraction_plan')
|
||||
units: Mapped[list['ShippingOrderExtractionUnit']] = relationship(
|
||||
back_populates='plan', cascade='all, delete-orphan', order_by='ShippingOrderExtractionUnit.position',
|
||||
run: Mapped['ShippingOrderProcessingRun'] = relationship(back_populates='extraction_plan')
|
||||
units: Mapped[list['ShippingOrderProcessingUnit']] = relationship(
|
||||
back_populates='plan', cascade='all, delete-orphan', order_by='ShippingOrderProcessingUnit.position',
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderExtractionUnit(Base):
|
||||
class ShippingOrderProcessingUnit(Base):
|
||||
"""计划内单个冻结附件抽取单元;状态、选择事实和错误相互隔离。"""
|
||||
|
||||
__tablename__ = 'shipping_order_extraction_units'
|
||||
__tablename__ = 'shipping_order_processing_units'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('plan_id', 'document_id', name='uq_shipping_order_extraction_units_document'),
|
||||
UniqueConstraint('plan_id', 'position', name='uq_shipping_order_extraction_units_position'),
|
||||
UniqueConstraint('plan_id', 'document_id', name='uq_shipping_order_processing_units_document'),
|
||||
UniqueConstraint('plan_id', 'position', name='uq_shipping_order_processing_units_position'),
|
||||
CheckConstraint(
|
||||
"unit_type IN ('document_extraction', 'email_relation')",
|
||||
name='ck_shipping_order_extraction_units_type',
|
||||
name='ck_shipping_order_processing_units_type',
|
||||
),
|
||||
CheckConstraint(
|
||||
"status IN ('pending', 'routing', 'matching_profile', 'extracting', "
|
||||
"'merging_supplement', 'candidate_ready', 'review_required', 'failed', 'cancelled')",
|
||||
name='ck_shipping_order_extraction_units_status',
|
||||
name='ck_shipping_order_processing_units_status',
|
||||
),
|
||||
ForeignKeyConstraint(
|
||||
['document_id', 'intake_id'],
|
||||
['shipping_notice_documents.id', 'shipping_notice_documents.intake_id'],
|
||||
name='fk_shipping_order_extraction_units_document_intake',
|
||||
['shipping_order_documents.id', 'shipping_order_documents.intake_id'],
|
||||
name='fk_shipping_order_processing_units_document_intake',
|
||||
),
|
||||
Index('ix_shipping_order_extraction_units_plan_status', 'plan_id', 'status'),
|
||||
Index('ix_shipping_order_extraction_units_document', 'document_id'),
|
||||
Index('ix_shipping_order_processing_units_plan_status', 'plan_id', 'status'),
|
||||
Index('ix_shipping_order_processing_units_document', 'document_id'),
|
||||
Index(
|
||||
'ix_shipping_order_extraction_units_cancel_requested',
|
||||
'ix_shipping_order_processing_units_cancel_requested',
|
||||
'cancellation_requested_at',
|
||||
'status',
|
||||
),
|
||||
CheckConstraint(
|
||||
"cancellation_actor_type IS NULL OR cancellation_actor_type IN "
|
||||
"('user', 'admin', 'system')",
|
||||
name='ck_shipping_order_extraction_units_cancel_actor',
|
||||
name='ck_shipping_order_processing_units_cancel_actor',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
plan_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_plans.id', ondelete='CASCADE'), nullable=False,
|
||||
ForeignKey('shipping_order_processing_plans.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
intake_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_intakes.id'), nullable=False)
|
||||
intake_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=False)
|
||||
document_id: Mapped[int] = mapped_column(nullable=False)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
unit_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
@@ -288,44 +343,44 @@ class ShippingOrderExtractionUnit(Base):
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
|
||||
plan: Mapped['ShippingOrderExtractionPlan'] = relationship(back_populates='units')
|
||||
route_decisions: Mapped[list['ShippingOrderExtractionRouteDecision']] = relationship(
|
||||
back_populates='unit', cascade='all, delete-orphan', order_by='ShippingOrderExtractionRouteDecision.id',
|
||||
plan: Mapped['ShippingOrderProcessingPlan'] = relationship(back_populates='units')
|
||||
route_decisions: Mapped[list['ShippingOrderRouteDecision']] = relationship(
|
||||
back_populates='unit', cascade='all, delete-orphan', order_by='ShippingOrderRouteDecision.id',
|
||||
)
|
||||
review_case: Mapped[Optional['ShippingOrderReviewCase']] = relationship(
|
||||
'ShippingOrderReviewCase', back_populates='unit', uselist=False,
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderExtractionRouteDecision(Base):
|
||||
class ShippingOrderRouteDecision(Base):
|
||||
"""Unit 每次模板分流的不可变脱敏审计;禁止存储文档、字段值和 Provider 输入。"""
|
||||
|
||||
__tablename__ = 'shipping_order_extraction_route_decisions'
|
||||
__tablename__ = 'shipping_order_route_decisions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('unit_id', 'job_id', 'attempt_no', name='uq_shipping_order_extraction_route_decision_attempt'),
|
||||
UniqueConstraint('unit_id', 'job_id', 'attempt_no', name='uq_shipping_order_route_decision_attempt'),
|
||||
CheckConstraint(
|
||||
"decision IN ('deterministic', 'review_required', 'skipped')",
|
||||
name='ck_shipping_order_extraction_route_decision',
|
||||
name='ck_shipping_order_route_decision',
|
||||
),
|
||||
CheckConstraint(
|
||||
"match_status IN ("
|
||||
"'unique_match', 'selected_by_score', 'no_special_profile_feature', "
|
||||
"'no_match', 'ambiguous', 'layout_drift', 'evidence_insufficient'"
|
||||
")",
|
||||
name='ck_shipping_order_extraction_route_match_status',
|
||||
name='ck_shipping_order_route_match_status',
|
||||
),
|
||||
Index('ix_shipping_order_extraction_route_decisions_run_unit', 'run_id', 'unit_id', 'id'),
|
||||
Index('ix_shipping_order_extraction_route_decisions_unit_created', 'unit_id', 'created_at'),
|
||||
Index('ix_shipping_order_extraction_route_decisions_profile_id', 'selected_profile_id', 'id'),
|
||||
Index('ix_shipping_order_route_decisions_run_unit', 'run_id', 'unit_id', 'id'),
|
||||
Index('ix_shipping_order_route_decisions_unit_created', 'unit_id', 'created_at'),
|
||||
Index('ix_shipping_order_route_decisions_profile_id', 'selected_profile_id', 'id'),
|
||||
Index(
|
||||
'ix_shipping_order_extraction_route_decisions_profile_snapshot',
|
||||
'ix_shipping_order_route_decisions_profile_snapshot',
|
||||
'selected_profile_code', 'selected_profile_version', 'selected_profile_checksum', 'id',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extraction_runs.id', ondelete='CASCADE'), nullable=False)
|
||||
unit_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extraction_units.id', ondelete='CASCADE'), nullable=False)
|
||||
run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'), nullable=False)
|
||||
unit_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_processing_units.id', ondelete='CASCADE'), nullable=False)
|
||||
job_id: Mapped[int] = mapped_column(ForeignKey('jobs.id'), nullable=False)
|
||||
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
decision: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
@@ -346,8 +401,8 @@ class ShippingOrderExtractionRouteDecision(Base):
|
||||
fallback_reason_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
run: Mapped['ShippingOrderExtractionRun'] = relationship(back_populates='route_decisions')
|
||||
unit: Mapped['ShippingOrderExtractionUnit'] = relationship(back_populates='route_decisions')
|
||||
run: Mapped['ShippingOrderProcessingRun'] = relationship(back_populates='route_decisions')
|
||||
unit: Mapped['ShippingOrderProcessingUnit'] = relationship(back_populates='route_decisions')
|
||||
|
||||
|
||||
class ShippingOrderExtractionProgressEvent(Base):
|
||||
@@ -363,8 +418,8 @@ class ShippingOrderExtractionProgressEvent(Base):
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extraction_runs.id', ondelete='CASCADE'), nullable=False)
|
||||
unit_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_extraction_units.id', ondelete='CASCADE'), nullable=True)
|
||||
run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'), nullable=False)
|
||||
unit_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_processing_units.id', ondelete='CASCADE'), nullable=True)
|
||||
document_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True)
|
||||
attempt_count: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
@@ -382,6 +437,50 @@ class ShippingOrderExtractionProgressEvent(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingOrderExtractionSubmission(Base):
|
||||
"""
|
||||
统一提交幂等记录:每次用户发送独立一行,禁止用 Run.client_submission_id 覆盖历史键。
|
||||
|
||||
用途:submission_id 重放只返回原决策;追加不会破坏更早的 submission 幂等。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_order_extraction_submissions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'user_id', 'submission_id',
|
||||
name='uq_shipping_order_extraction_submissions_user_submission',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_order_extraction_submissions_run',
|
||||
'run_id',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_order_extraction_submissions_conversation',
|
||||
'user_id',
|
||||
'conversation_id',
|
||||
'created_at',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
submission_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
|
||||
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
user_task_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
run_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
)
|
||||
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
decision: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
operation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
composer_context_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
intake_nos_json: Mapped[list[Any]] = mapped_column(JSON, nullable=False, default=list)
|
||||
appended_intake_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingOrderExtractionDiagnosticAudit(Base):
|
||||
"""管理员订单抽取诊断访问审计;不记录Run业务正文或原始筛选参数。"""
|
||||
|
||||
@@ -393,7 +492,7 @@ class ShippingOrderExtractionDiagnosticAudit(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
admin_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_extraction_runs.id'), nullable=True)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_processing_runs.id'), nullable=True)
|
||||
action: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
query_summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
"""
|
||||
建单前订单人工复核领域模型。
|
||||
|
||||
依赖:订单抽取 Run/Unit、候选 Candidate、用户和后续 ShippingTask。
|
||||
依赖:订单抽取 Run/Unit、候选 Candidate、用户和后续 ShippingNotice、
|
||||
ShippingOrderReviewLineDecision(行级履约决定)、
|
||||
ShippingOrderReviewWaveLine(波次行不可变归属)。
|
||||
逻辑:Case 以 PDF Unit 为唯一复核对象,Draft 保存独立人工版本;机器 Candidate
|
||||
始终只读,后续确认服务将以 Case/Draft 生成不可变确认版本和 Task。
|
||||
始终只读,后续确认服务将以 Case/Draft 生成不可变确认版本和 Task;
|
||||
行级决定支持完整明细先行履约波次,禁止拆分数量;
|
||||
wave_lines 保证同一 (case, line_key) 最多关联一个 task_id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -37,13 +41,13 @@ class ShippingOrderReviewCase(Base):
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
case_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
run_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id', ondelete='CASCADE'), nullable=False,
|
||||
ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
unit_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_units.id', ondelete='CASCADE'), nullable=False,
|
||||
ForeignKey('shipping_order_processing_units.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_documents.id'), nullable=False)
|
||||
candidate_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_candidates.id'), nullable=True)
|
||||
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_documents.id'), nullable=False)
|
||||
candidate_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_candidates.id'), nullable=True)
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='unreviewed', server_default='unreviewed')
|
||||
disposition: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
@@ -51,13 +55,13 @@ class ShippingOrderReviewCase(Base):
|
||||
ForeignKey('shipping_order_review_drafts.id', use_alter=True, name='fk_shipping_order_review_cases_current_draft'),
|
||||
nullable=True,
|
||||
)
|
||||
confirmed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True)
|
||||
confirmed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True)
|
||||
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
run: Mapped['ShippingOrderExtractionRun'] = relationship('ShippingOrderExtractionRun', back_populates='review_cases')
|
||||
unit: Mapped['ShippingOrderExtractionUnit'] = relationship('ShippingOrderExtractionUnit', back_populates='review_case')
|
||||
run: Mapped['ShippingOrderProcessingRun'] = relationship('ShippingOrderProcessingRun', back_populates='review_cases')
|
||||
unit: Mapped['ShippingOrderProcessingUnit'] = relationship('ShippingOrderProcessingUnit', back_populates='review_case')
|
||||
current_draft: Mapped[Optional['ShippingOrderReviewDraft']] = relationship(
|
||||
'ShippingOrderReviewDraft', foreign_keys=[current_draft_id], post_update=True,
|
||||
)
|
||||
@@ -69,6 +73,18 @@ class ShippingOrderReviewCase(Base):
|
||||
'ShippingOrderReviewSuggestion', back_populates='case', cascade='all, delete-orphan',
|
||||
order_by='ShippingOrderReviewSuggestion.created_at.desc()',
|
||||
)
|
||||
line_decisions: Mapped[list['ShippingOrderReviewLineDecision']] = relationship(
|
||||
'ShippingOrderReviewLineDecision',
|
||||
back_populates='case',
|
||||
cascade='all, delete-orphan',
|
||||
order_by='ShippingOrderReviewLineDecision.line_key, ShippingOrderReviewLineDecision.decision_version',
|
||||
)
|
||||
wave_lines: Mapped[list['ShippingOrderReviewWaveLine']] = relationship(
|
||||
'ShippingOrderReviewWaveLine',
|
||||
back_populates='case',
|
||||
cascade='all, delete-orphan',
|
||||
order_by='ShippingOrderReviewWaveLine.wave_no, ShippingOrderReviewWaveLine.line_key',
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderReviewDraft(Base):
|
||||
@@ -119,20 +135,21 @@ class ShippingOrderReviewCaseEvent(Base):
|
||||
|
||||
|
||||
class ShippingOrderReviewConfirmedRevision(Base):
|
||||
"""一次不可变建单确认快照;每个 PDF Case 最多确认一次。"""
|
||||
"""一次不可变建单确认快照;同一 Case 可对应多个履约波次 Task。"""
|
||||
|
||||
__tablename__ = 'shipping_order_review_confirmed_revisions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('case_id', name='uq_shipping_order_review_confirmed_revisions_case'),
|
||||
UniqueConstraint('case_id', 'task_id', name='uq_shipping_order_review_confirmed_revisions_case_task'),
|
||||
UniqueConstraint('idempotency_key', name='uq_shipping_order_review_confirmed_revisions_idempotency'),
|
||||
Index('ix_shipping_order_review_confirmed_revisions_task', 'task_id'),
|
||||
Index('ix_shipping_order_review_confirmed_revisions_case', 'case_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
case_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
|
||||
draft_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
||||
header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
models/shipping_order_review_line_decision.py
|
||||
|
||||
用途:建单前复核 Case 的行级履约决定(版本化、可追溯)。
|
||||
依赖:ShippingOrderReviewCase、ShippingNotice、users。
|
||||
逻辑:由 order_review_fulfillment_decision_service 写入;同一 (case, line_key, version) 唯一;
|
||||
活动决定不可覆盖,重开生成新版本;Task 波次通过 task_id 关联。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingOrderReviewLineDecision(Base):
|
||||
"""一条订单明细的履约决定版本;禁止拆分数量。"""
|
||||
|
||||
__tablename__ = 'shipping_order_review_line_decisions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'review_case_id',
|
||||
'line_key',
|
||||
'decision_version',
|
||||
name='uq_shipping_review_line_decisions_case_line_ver',
|
||||
),
|
||||
CheckConstraint(
|
||||
"decision_code IN ("
|
||||
"'wait_inventory', 'use_new_inventory_file', 'change_inventory_source', "
|
||||
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen'"
|
||||
")",
|
||||
name='ck_shipping_review_line_decisions_code',
|
||||
),
|
||||
CheckConstraint(
|
||||
"line_status IN ("
|
||||
"'pending_decision', 'waiting_inventory', 'ready_to_fulfill', "
|
||||
"'task_created', 'fulfilled', 'closed_unfulfillable', 'reopened'"
|
||||
")",
|
||||
name='ck_shipping_review_line_decisions_status',
|
||||
),
|
||||
CheckConstraint('decision_version >= 1', name='ck_shipping_review_line_decisions_version'),
|
||||
Index('ix_shipping_review_line_decisions_case_line', 'review_case_id', 'line_key'),
|
||||
Index('ix_shipping_review_line_decisions_case_active', 'review_case_id', 'is_active'),
|
||||
Index('ix_shipping_review_line_decisions_task', 'task_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
review_case_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
)
|
||||
line_key: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
decision_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
decision_code: Mapped[str] = mapped_column(String(48), nullable=False)
|
||||
line_status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending_decision')
|
||||
is_active: Mapped[bool] = mapped_column(nullable=False, default=True, server_default='true')
|
||||
reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
required_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True)
|
||||
wave_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
actor_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
|
||||
case: Mapped['ShippingOrderReviewCase'] = relationship(
|
||||
'ShippingOrderReviewCase',
|
||||
back_populates='line_decisions',
|
||||
)
|
||||
@@ -46,10 +46,10 @@ class ShippingOrderReviewSuggestion(Base):
|
||||
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
document_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_documents.id'), nullable=False,
|
||||
ForeignKey('shipping_order_documents.id'), nullable=False,
|
||||
)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'), nullable=True,
|
||||
ForeignKey('shipping_order_processing_runs.id'), nullable=True,
|
||||
)
|
||||
field_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
line_key: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""
|
||||
models/shipping_order_review_wave_line.py
|
||||
|
||||
用途:复核 Case 履约波次行归属(不可变),保证同一明细行最多进入一个 Task。
|
||||
依赖:ShippingOrderReviewCase、ShippingNotice、ShippingOrderReviewConfirmedRevision。
|
||||
逻辑:由 order_review_confirmation_service 在建波次/整单确认时写入;
|
||||
(review_case_id, line_key) 数据库唯一约束防并发重复入波次。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingOrderReviewWaveLine(Base):
|
||||
"""一条复核明细行与履约 Task 的不可变归属记录。"""
|
||||
|
||||
__tablename__ = 'shipping_order_review_wave_lines'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'review_case_id',
|
||||
'line_key',
|
||||
name='uq_shipping_review_wave_lines_case_line',
|
||||
),
|
||||
Index('ix_shipping_review_wave_lines_task', 'task_id'),
|
||||
Index('ix_shipping_review_wave_lines_case_wave', 'review_case_id', 'wave_no'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
review_case_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
)
|
||||
line_key: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
|
||||
wave_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
confirmed_revision_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_review_confirmed_revisions.id', ondelete='SET NULL'),
|
||||
nullable=True,
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
case: Mapped['ShippingOrderReviewCase'] = relationship(
|
||||
'ShippingOrderReviewCase',
|
||||
back_populates='wave_lines',
|
||||
)
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/models/shipping_order_schema.py
|
||||
|
||||
用途:定义货代字段资产、Schema 族/不可变版本、配置审计及动态订单解析结果。
|
||||
依赖:models.base.Base、shipping_tasks、shipping_notice_intakes、users。
|
||||
依赖:models.base.Base、shipping_notices、shipping_order_intakes、users。
|
||||
逻辑:字段资产全局存活(标准只读、扩展可弃用);Schema 族版本仅采用资产并冻结 definition_json;
|
||||
definition_json 含 fields / auto_creation_policy / derivation_rules(及 checksum);
|
||||
写操作追加审计;解析链锁定发布版本。表名保留历史命名以降低迁移耦合。
|
||||
@@ -230,10 +230,10 @@ class ShippingOrderExtraction(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
|
||||
ForeignKey('shipping_order_processing_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True)
|
||||
intake_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_intakes.id'), nullable=True)
|
||||
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True)
|
||||
intake_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=True)
|
||||
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
||||
input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
input_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
@@ -285,7 +285,7 @@ class ShippingOrderFieldObservation(Base):
|
||||
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False)
|
||||
line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True)
|
||||
field_id: Mapped[str] = mapped_column(String(36), nullable=False) # 软引用:历史 Run 可保留孤儿 field_id
|
||||
source_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_documents.id'), nullable=True)
|
||||
source_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_documents.id'), nullable=True)
|
||||
source_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
extractor: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
raw_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/models/shipping_order_snapshot.py
|
||||
|
||||
用途:保存从订单解析候选冻结而来的不可变履约订单快照及人工复核审计。
|
||||
依赖:shipping_order_schema 的 Extraction、shipping_tasks、shipping_customers 与 users。
|
||||
依赖:shipping_order_schema 的 Extraction、shipping_notices、shipping_customers 与 users。
|
||||
逻辑:order_freeze_service 将已接受 Extraction 的字段按稳定 field_id 冻结为 Snapshot;库存、导出和上传阶段只消费本模块的快照。
|
||||
Phase 0+ 扩展约定:rule_versions_json 可含 derivation_rules_snapshot / derivation_rules_checksum;
|
||||
source_manifest_json 可含 field_lineage(值来源、规则引用、覆盖原因、证据引用)。
|
||||
@@ -31,7 +31,7 @@ class ShippingOrderSnapshot(Base):
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False, index=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False, index=True)
|
||||
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
|
||||
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
||||
customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True, index=True)
|
||||
@@ -111,7 +111,7 @@ class ShippingOrderReviewEvent(Base):
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
|
||||
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
|
||||
snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_snapshots.id', ondelete='CASCADE'), nullable=True)
|
||||
scope: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
models/shipping_order_submission.py
|
||||
|
||||
用途:一次文件选择/上传批次的订单材料 Submission 边界(多 EML / 直接 PDF 阶段 1)。
|
||||
依赖:users、agents、shipping_order_intakes(反向关联)。
|
||||
逻辑:同一 (user_id, upload_batch_id) 唯一;仅承载幂等、文件集合汇总与会话关联,
|
||||
不拥有端到端业务进度。由 order_submission_service 创建;Intake 通过
|
||||
order_submission_id 挂接。与 shipping_order_extraction_submissions(OT 发送决策)
|
||||
概念分离。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import (
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
def generate_order_submission_no() -> str:
|
||||
"""
|
||||
生成上传 Submission 业务编号。
|
||||
|
||||
核心逻辑:SOS-日期-短 UUID,保证可读且碰撞概率极低。
|
||||
|
||||
Returns:
|
||||
形如 SOS-YYYYMMDD-XXXXXXXX 的编号。
|
||||
"""
|
||||
return f"SOS-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
class ShippingOrderSubmission(Base):
|
||||
"""一次上传提交:聚合同 upload_batch 下的多个 Intake。"""
|
||||
|
||||
__tablename__ = 'shipping_order_submissions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('submission_no', name='uq_shipping_order_submissions_submission_no'),
|
||||
UniqueConstraint(
|
||||
'user_id',
|
||||
'upload_batch_id',
|
||||
name='uq_shipping_order_submissions_user_upload_batch',
|
||||
),
|
||||
CheckConstraint(
|
||||
"status IN ('accepted', 'processing', 'completed', 'failed', 'cancelled')",
|
||||
name='ck_shipping_order_submissions_status',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_order_submissions_user_conversation_created',
|
||||
'user_id',
|
||||
'conversation_id',
|
||||
'created_at',
|
||||
),
|
||||
Index('ix_shipping_order_submissions_status_created', 'status', 'created_at'),
|
||||
Index(
|
||||
'ix_shipping_order_submissions_client_submission',
|
||||
'user_id',
|
||||
'client_submission_id',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
submission_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
client_submission_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
|
||||
owner_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
upload_batch_id: Mapped[str] = mapped_column(String(36), nullable=False)
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(32),
|
||||
nullable=False,
|
||||
default='accepted',
|
||||
server_default=text("'accepted'"),
|
||||
)
|
||||
intake_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||||
eml_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||||
direct_pdf_count: Mapped[int] = mapped_column(
|
||||
Integer, nullable=False, default=0, server_default=text('0')
|
||||
)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
backend/app/models/shipping_order_task.py
|
||||
|
||||
用途:正式发货通知创建前的 OT(shipping_order_tasks)聚合根,对齐多 EML/PDF 蓝图。
|
||||
依赖:users、agents、shipping_order_submissions/intakes/candidates、extraction_runs、shipping_notices。
|
||||
逻辑:由 Extraction Run 的 user_task_no 双写/回填;建单成功后挂 shipping_notice_id。
|
||||
页面链路以 task_no(OT-…)为根身份;1 OT 可对应 0..N Notice。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import (
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
def _default_order_task_no() -> str:
|
||||
"""生成默认 OT 编号;正式路径由 Run 派生覆盖。"""
|
||||
return f"OT-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
class ShippingOrderTask(Base):
|
||||
"""
|
||||
建单前订单任务(OT)聚合根。
|
||||
|
||||
核心逻辑:与 Extraction Run.user_task_no 对齐;进度由领域服务单调推进并 bump progress_version。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_order_tasks'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('task_no', name='uq_shipping_order_tasks_task_no'),
|
||||
CheckConstraint(
|
||||
"source_type IS NULL OR source_type IN ('eml', 'direct_pdf')",
|
||||
name='ck_shipping_order_tasks_source_type',
|
||||
),
|
||||
Index('ix_shipping_order_tasks_user_created', 'user_id', 'created_at'),
|
||||
Index('ix_shipping_order_tasks_conversation', 'conversation_id'),
|
||||
Index('ix_shipping_order_tasks_status', 'status'),
|
||||
Index('ix_shipping_order_tasks_extraction_run_id', 'extraction_run_id'),
|
||||
Index('ix_shipping_order_tasks_shipping_notice_id', 'shipping_notice_id'),
|
||||
# 一 Candidate 一 OT;NULL candidate_id 仅遗留行,新创建路径禁止。
|
||||
Index(
|
||||
'uq_shipping_order_tasks_candidate_id',
|
||||
'candidate_id',
|
||||
unique=True,
|
||||
postgresql_where=text('candidate_id IS NOT NULL'),
|
||||
sqlite_where=text('candidate_id IS NOT NULL'),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_no: Mapped[str] = mapped_column(String(64), nullable=False, default=_default_order_task_no)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
|
||||
owner_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
submission_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_submissions.id'), nullable=True,
|
||||
)
|
||||
intake_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=True)
|
||||
candidate_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_candidates.id'), nullable=True,
|
||||
)
|
||||
extraction_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_processing_runs.id'), nullable=True,
|
||||
)
|
||||
shipping_notice_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_notices.id', name='fk_shipping_order_tasks_shipping_notice_id', use_alter=True),
|
||||
nullable=True,
|
||||
)
|
||||
source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='processing')
|
||||
stage: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
progress_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
@@ -2,10 +2,10 @@
|
||||
models/shipping_process_gate.py
|
||||
|
||||
用途:门禁级中断恢复的持久化模型——Execution / Gate / Attempt。
|
||||
依赖:SQLAlchemy Base、WorkflowItem/Version、ReviewCase、ShippingTask、Job;
|
||||
状态枚举与 process_gate_contract 对齐。
|
||||
依赖:SQLAlchemy Base、ReviewCase、ShippingNotice、Job;状态枚举与 process_gate_contract 对齐。
|
||||
逻辑:Execution 为业务恢复真相;Gate 保存当前门禁状态;Attempt 不可变执行尝试并承载租约。
|
||||
由领域服务独占写入;Job 仅调度,WorkflowItem 仅聚合台账。
|
||||
由领域服务独占写入;Job 仅调度。
|
||||
co8e9f0a1b2c:已移除对 shipping_notice_workflow_* 的硬外键(无历史兼容)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -41,10 +41,6 @@ class ShippingProcessExecution(Base):
|
||||
__tablename__ = 'shipping_process_executions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('execution_no', name='uq_shipping_process_executions_no'),
|
||||
UniqueConstraint(
|
||||
'workflow_item_version_id',
|
||||
name='uq_shipping_process_executions_workflow_item_version',
|
||||
),
|
||||
CheckConstraint(
|
||||
"status IN ('active', 'blocked', 'waiting_external', 'completed', 'cancelled', 'failed')",
|
||||
name='ck_shipping_process_executions_status',
|
||||
@@ -55,11 +51,6 @@ class ShippingProcessExecution(Base):
|
||||
'status',
|
||||
'updated_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_process_executions_workflow_item',
|
||||
'workflow_item_id',
|
||||
'updated_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_process_executions_current_gate',
|
||||
'current_gate_code',
|
||||
@@ -78,17 +69,11 @@ class ShippingProcessExecution(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
execution_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
workflow_item_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_workflow_items.id'), nullable=False,
|
||||
)
|
||||
workflow_item_version_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_workflow_item_versions.id'), nullable=False,
|
||||
)
|
||||
review_case_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_review_cases.id'), nullable=True,
|
||||
)
|
||||
task_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_tasks.id'), nullable=True,
|
||||
ForeignKey('shipping_notices.id'), nullable=True,
|
||||
)
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default='active', server_default='active',
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/models/shipping_task_line.py
|
||||
|
||||
用途:订单字段冲突审计(ShippingTaskFieldConflict)模型。
|
||||
依赖:models.base.Base、shipping_tasks、users。
|
||||
依赖:models.base.Base、shipping_notices、users。
|
||||
逻辑:冲突按动态订单 Extraction 的行 position 定位,不保留固定订单行投影。
|
||||
"""
|
||||
|
||||
@@ -60,7 +60,7 @@ class ShippingTaskFieldConflict(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_tasks.id', ondelete='CASCADE'),
|
||||
ForeignKey('shipping_notices.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
@@ -91,4 +91,4 @@ class ShippingTaskFieldConflict(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
task: Mapped[ShippingTask] = relationship('ShippingTask', back_populates='field_conflicts')
|
||||
task: Mapped['ShippingNotice'] = relationship('ShippingNotice', back_populates='field_conflicts')
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
models/shipping_temporary_inventory.py
|
||||
|
||||
用途:定义对话上传库存文件的临时会话,隔离其分析、确认与后续批次使用过程。
|
||||
依赖:Base、FileAsset、ChatSession、ShippingBatch/ShippingTask、库存结构分析记录。
|
||||
用途:定义对话上传库存文件的临时会话,隔离其分析、确认与后续任务挂接过程。
|
||||
依赖:Base、FileAsset、ChatSession、ShippingNotice(shipping_notices)、库存结构分析记录。
|
||||
逻辑:Dify Tool 与工作台均先创建本会话,再由后端对受控文件资产进行结构初检;
|
||||
co8e9f0a1b2c 已删除 batch_id;会话仅可关联 task_id;
|
||||
本表不代表库存站点配置,也不代表生产库存快照。
|
||||
"""
|
||||
|
||||
@@ -38,8 +39,7 @@ class ShippingTemporaryInventorySession(Base):
|
||||
analysis_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True,
|
||||
)
|
||||
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), nullable=True, index=True)
|
||||
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True, index=True)
|
||||
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True, index=True)
|
||||
declared_intent: Mapped[str] = mapped_column(String(32), nullable=False, default='inventory_candidate')
|
||||
file_classification_status: Mapped[str] = mapped_column(String(32), nullable=False, default='created')
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='created')
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
backend/app/models/shipping_xfa_audit_snapshot.py
|
||||
|
||||
用途:持久化 XFA 审计完整快照密文(不可变、可校验、默认保留 3 年)。
|
||||
依赖:SQLAlchemy Base;由 audit_snapshot_service 写入/只读解密;禁止业务层直接改删。
|
||||
逻辑:普通 ShippingAuditEvent 仅保存脱敏 diff 与 snapshot_ref;完整请求/definition/
|
||||
受控原值经 envelope encryption 落入本表。ORM before_update/before_delete 与
|
||||
PostgreSQL 触发器共同保证 append-only;到期清理须 set_config
|
||||
('hxops.shipping_xfa_audit_purge','1')。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import JSON, CheckConstraint, DateTime, Index, Integer, String, Text, event
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingXfaAuditSnapshot(Base):
|
||||
"""XFA 审计完整快照密文行;禁止业务更新或删除。"""
|
||||
|
||||
__tablename__ = 'shipping_xfa_audit_snapshots'
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"purpose IN ('before', 'after', 'request', 'full', 'sample_values')",
|
||||
name='ck_shipping_xfa_audit_snapshots_purpose',
|
||||
),
|
||||
CheckConstraint(
|
||||
"encryption_alg IN ('fernet-v1')",
|
||||
name='ck_shipping_xfa_audit_snapshots_encryption_alg',
|
||||
),
|
||||
Index('ix_shipping_xfa_audit_snapshots_object', 'object_type', 'object_id', 'created_at'),
|
||||
Index('ix_shipping_xfa_audit_snapshots_retention', 'retention_expires_at', 'id'),
|
||||
Index('ix_shipping_xfa_audit_snapshots_operation', 'operation_id', 'created_at'),
|
||||
Index('ix_shipping_xfa_audit_snapshots_request', 'request_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# 对外稳定引用(写入审计事件 context_refs / evidence_refs),禁止猜测递增 id。
|
||||
snapshot_ref: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
|
||||
object_type: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
object_id: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
purpose: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
schema_version: Mapped[str] = mapped_column(String(32), nullable=False, default='xfa_audit_v1')
|
||||
encryption_alg: Mapped[str] = mapped_column(String(32), nullable=False, default='fernet-v1')
|
||||
key_id: Mapped[str] = mapped_column(String(64), nullable=False, default='primary')
|
||||
# Fernet 密文;静态不可读,仅敏感读 API 在权限校验后解密。
|
||||
ciphertext: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
ciphertext_sha256: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
plaintext_sha256: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# 脱敏摘要(可进普通导出);不得含明文订单值或 XML。
|
||||
redacted_summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
actor_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
operation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
audit_event_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
retention_expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
@event.listens_for(ShippingXfaAuditSnapshot, 'before_update')
|
||||
def _reject_xfa_audit_snapshot_update(_mapper, _connection, _target) -> None:
|
||||
"""拒绝 ORM 更新,保证完整快照不可篡改。"""
|
||||
raise ValidationError(
|
||||
'Shipping XFA audit snapshot is append-only',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_IMMUTABLE',
|
||||
)
|
||||
|
||||
|
||||
@event.listens_for(ShippingXfaAuditSnapshot, 'before_delete')
|
||||
def _reject_xfa_audit_snapshot_delete(_mapper, _connection, _target) -> None:
|
||||
"""拒绝 ORM 删除,避免业务清理抹除加密审计事实。"""
|
||||
raise ValidationError(
|
||||
'Shipping XFA audit snapshot is append-only',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_IMMUTABLE',
|
||||
)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""
|
||||
backend/app/models/shipping_xfa_structure_analysis.py
|
||||
|
||||
用途:持久化 XFA 样本/文档的结构分析摘要(document_kind、packet checksum、结构指纹、统计与安全摘要)。
|
||||
依赖:shipping_order_documents、shipping_order_document_layout_versions、SQLAlchemy Base。
|
||||
逻辑:由 shipping_document_layout Job 在 XFA 分支写入;admin API 只读投影,不返回原始 XML/PDF。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingXfaStructureAnalysis(Base):
|
||||
"""单文档 XFA 结构分析记录;保存脱敏结构证据,完整敏感值仅通过 encrypted_snapshot_ref 占位。"""
|
||||
|
||||
__tablename__ = 'shipping_xfa_structure_analyses'
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"analysis_status IN ('ready', 'failed', 'rejected')",
|
||||
name='ck_shipping_xfa_structure_analysis_status',
|
||||
),
|
||||
CheckConstraint(
|
||||
"document_kind IN ('plain_pdf', 'acroform', 'xfa_hybrid', 'pure_xfa', 'unsupported')",
|
||||
name='ck_shipping_xfa_structure_analysis_document_kind',
|
||||
),
|
||||
Index('ix_shipping_xfa_structure_analysis_document', 'document_id', 'created_at'),
|
||||
Index('ix_shipping_xfa_structure_analysis_content_hash', 'source_content_hash'),
|
||||
Index('ix_shipping_xfa_structure_analysis_fingerprint', 'dataset_structure_fingerprint'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
document_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_documents.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
layout_version_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_document_layout_versions.id', ondelete='SET NULL'), nullable=True,
|
||||
)
|
||||
source_content_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
document_kind: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
analysis_status: Mapped[str] = mapped_column(String(16), nullable=False, default='ready', server_default='ready')
|
||||
template_packet_checksum: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
datasets_packet_checksum: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
dataset_structure_fingerprint: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
packet_checksums_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
stats_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
security_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
tree_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
route_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
encrypted_snapshot_ref: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
|
||||
parser_identity: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
contract_version: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
document = relationship('ShippingOrderDocument', foreign_keys=[document_id])
|
||||
layout_version = relationship('ShippingDocumentLayoutVersion', foreign_keys=[layout_version_id])
|
||||
@@ -93,6 +93,10 @@ class User(Base):
|
||||
'shipping_notice_force_create': self.role == 'admin',
|
||||
# 货代审计敏感快照/前后 Diff 读取:admin 默认开;不新建角色,可显式关闭或授予
|
||||
'shipping_notice.audit_sensitive_read': self.role == 'admin',
|
||||
# XFA 字段拆分:编辑 / 预览 / 发布审核;admin 默认开,可显式收紧
|
||||
'shipping_notice.xfa_split_rule_edit': self.role == 'admin',
|
||||
'shipping_notice.xfa_split_rule_preview': self.role == 'admin',
|
||||
'shipping_notice.xfa_split_rule_publish': self.role == 'admin',
|
||||
}
|
||||
|
||||
def get_feature_permissions(self) -> dict[str, bool]:
|
||||
|
||||
@@ -15,7 +15,7 @@ from app.extensions import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingInventoryExternalMapping, ShippingInventoryFile, ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition,
|
||||
ShippingInventoryRoutingRuleVersion, ShippingInventorySource, ShippingRpaProfile, ScheduleRun, ScheduleTask, ShippingTask,
|
||||
ShippingInventoryRoutingRuleVersion, ShippingInventorySource, ShippingRpaProfile, ScheduleRun, ScheduleTask, ShippingNotice,
|
||||
ShippingOrderField,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis,
|
||||
@@ -389,7 +389,7 @@ def delete_source(source_id: int) -> None:
|
||||
for candidates in [(rule.action_payload_json or {}).get('source_codes', [])]
|
||||
if isinstance(candidates, list)
|
||||
)
|
||||
has_task = ShippingTask.query.filter_by(inventory_source_code=source_code).count() > 0
|
||||
has_task = ShippingNotice.query.filter_by(inventory_source_code=source_code).count() > 0
|
||||
has_export_run = any(
|
||||
source_code in {str(code).strip().upper() for code in source_codes}
|
||||
for run in ScheduleRun.query.all()
|
||||
|
||||
@@ -53,8 +53,8 @@ agent_types:
|
||||
conversation_mode_default: task_chat
|
||||
runtime_provider_default: hybrid
|
||||
models:
|
||||
- ShippingBatch
|
||||
- ShippingTask
|
||||
- ShippingNotice
|
||||
- ShippingOrderTask
|
||||
- ShippingTaskEvent
|
||||
required_fields: []
|
||||
default_capabilities:
|
||||
|
||||
@@ -71,18 +71,12 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
task = get_task_by_ref(task_id) if task_id else None
|
||||
batch = get_batch_by_no(batch_no) if batch_no else None
|
||||
session_id = str(getattr(ctx.session, 'session_id', '') or '')
|
||||
if task is None and batch is not None:
|
||||
focus_task_no = str(batch.current_focus_task_no or '').strip()
|
||||
if focus_task_no:
|
||||
candidate = get_task_by_ref(focus_task_no)
|
||||
if candidate is not None and candidate.batch_id == batch.id:
|
||||
task = candidate
|
||||
if task is not None:
|
||||
return {
|
||||
'event': 'shipping_ui_state',
|
||||
'conversation_id': session_id,
|
||||
'task_no': task.task_no,
|
||||
'batch_no': task.batch.batch_no if task.batch is not None else None,
|
||||
'batch_no': None,
|
||||
'ui_state': build_task_ui_state(task),
|
||||
}
|
||||
if batch is not None:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/file_assets/cleanup.py
|
||||
|
||||
用途:过期未引用 FileAsset 与关联 intake 的清理编排。
|
||||
依赖:file_assets.storage、models.FileAsset/ShippingNoticeIntake。
|
||||
依赖:file_assets.storage、models.FileAsset/ShippingOrderIntake。
|
||||
逻辑:由排程或 file_asset_cleanup Job 调用;先标记 expired → 删 MinIO → 成功后 mark deleted;
|
||||
MinIO 删除失败不伪装成功,保留记录供下次重试。
|
||||
"""
|
||||
@@ -15,7 +15,7 @@ from datetime import datetime
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.models import FileAsset, ShippingNoticeIntake
|
||||
from app.models import FileAsset, ShippingOrderIntake
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
@@ -49,10 +49,10 @@ def cleanup_expired_temporary_assets(*, limit: int = 100) -> dict[str, int]:
|
||||
stats = {'scanned': len(assets), 'expired': 0, 'deleted': 0, 'errors': 0}
|
||||
for asset in assets:
|
||||
consumed = (
|
||||
db.session.query(ShippingNoticeIntake.id)
|
||||
db.session.query(ShippingOrderIntake.id)
|
||||
.filter(
|
||||
ShippingNoticeIntake.asset_id == asset.id,
|
||||
ShippingNoticeIntake.parse_status == 'consumed',
|
||||
ShippingOrderIntake.asset_id == asset.id,
|
||||
ShippingOrderIntake.parse_status == 'consumed',
|
||||
)
|
||||
.first()
|
||||
)
|
||||
@@ -61,11 +61,11 @@ def cleanup_expired_temporary_assets(*, limit: int = 100) -> dict[str, int]:
|
||||
stats['expired'] += 1
|
||||
asset.lifecycle_status = 'expired'
|
||||
(
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.asset_id == asset.id,
|
||||
ShippingNoticeIntake.consumed_at.is_(None),
|
||||
ShippingNoticeIntake.parse_status.notin_(('consumed', 'cancelled')),
|
||||
ShippingOrderIntake.asset_id == asset.id,
|
||||
ShippingOrderIntake.consumed_at.is_(None),
|
||||
ShippingOrderIntake.parse_status.notin_(('consumed', 'cancelled')),
|
||||
)
|
||||
.update({'parse_status': 'expired', 'updated_at': now}, synchronize_session=False)
|
||||
)
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
"""
|
||||
services/schedule/shipping_audit_retention_job.py
|
||||
|
||||
用途:货代统一审计到期清理与哈希链抽样校验的 platform Job 入口。
|
||||
依赖:audit_query_service.purge_expired_shipping_audit_events、
|
||||
用途:货代统一审计到期清理、XFA 加密快照到期清理与哈希链抽样校验的 platform Job 入口。
|
||||
依赖:audit_query_service.purge_expired_shipping_audit_events / purge_expired_xfa_audit_snapshots、
|
||||
audit_snapshot_service.verify_event_hash_chain、progress_feature_flags.audit_retention_days。
|
||||
逻辑:platform_api_path=shipping-audit-retention 时由 job_registry 调用;仅清理
|
||||
retention_expires_at 非空且已到期的事件;新写入事件永久保留(expires=None)永不删除;
|
||||
PostgreSQL 上 purge 在同事务设置 hxops.shipping_audit_purge=1,配合 append-only DELETE 触发器;
|
||||
可选对近期聚合抽样校验 previous_event_hash / event_hash 链完整性。
|
||||
retention_expires_at 非空且已到期的事件与 XFA 快照;新写入事件永久保留(expires=None)
|
||||
永不删除;XFA 快照默认 3 年;哈希校验抽样检测篡改断链。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,7 +16,10 @@ from typing import Any
|
||||
from flask import current_app
|
||||
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_query_service import purge_expired_shipping_audit_events
|
||||
from app.services.shipping_notice.audit_query_service import (
|
||||
purge_expired_shipping_audit_events,
|
||||
purge_expired_xfa_audit_snapshots,
|
||||
)
|
||||
from app.services.shipping_notice.audit_snapshot_service import verify_event_hash_chain
|
||||
from app.services.shipping_notice.progress_feature_flags import audit_retention_days
|
||||
|
||||
@@ -94,6 +96,11 @@ def run_shipping_audit_retention_schedule(task: Any, run: Any) -> dict[str, Any]
|
||||
actor_id=f'schedule:{getattr(task, "id", "unknown")}',
|
||||
)
|
||||
result['retention_days'] = audit_retention_days()
|
||||
result['xfa_snapshots'] = purge_expired_xfa_audit_snapshots(
|
||||
limit=int(params.get('xfa_snapshot_limit') or params.get('limit') or 1000),
|
||||
dry_run=dry_run,
|
||||
actor_id=f'schedule:{getattr(task, "id", "unknown")}',
|
||||
)
|
||||
|
||||
hash_verify_enabled = bool(
|
||||
current_app.config.get('SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED', True)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/attachment_selection.py
|
||||
|
||||
用途:基于 Intake 快览事实生成可审计的附件选择计划。
|
||||
依赖:ShippingNoticeIntake、标准库正则与哈希;只读取 structured_result_json,不回读 Document/布局结果。
|
||||
依赖:ShippingOrderIntake、标准库正则与哈希;只读取 structured_result_json,不回读 Document/布局结果。
|
||||
逻辑:发送阶段调用本文件,把当前批次附件目录转换为“为何选择/为何跳过”的稳定计划;
|
||||
后续深度解析、预算扩展与审计都应复用这份快照,而不是重新猜测附件优先级。
|
||||
"""
|
||||
@@ -13,7 +13,7 @@ import re
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingNoticeIntake
|
||||
from app.models import ShippingOrderIntake
|
||||
|
||||
_PO_HINT_RE = re.compile(r'\b(?:PO[-_ ]*)?([A-Z]{0,4}\d{5,})\b', re.IGNORECASE)
|
||||
_TOKEN_RE = re.compile(r'[A-Z0-9]{4,}', re.IGNORECASE)
|
||||
@@ -57,7 +57,7 @@ _NEGATIVE_NAME_HINTS: tuple[tuple[str, int, str], ...] = (
|
||||
)
|
||||
|
||||
|
||||
def _structured(intake: ShippingNoticeIntake) -> dict[str, Any]:
|
||||
def _structured(intake: ShippingOrderIntake) -> dict[str, Any]:
|
||||
"""读取 Intake 快览摘要;缺失时返回空对象,调用方决定是否视为不可选。"""
|
||||
return intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
|
||||
@@ -134,7 +134,7 @@ def _score_attachment(*, filename: str, mime_type: str, size: int, mail_text: st
|
||||
|
||||
def build_attachment_selection_snapshot(
|
||||
*,
|
||||
intakes: list[ShippingNoticeIntake],
|
||||
intakes: list[ShippingOrderIntake],
|
||||
max_initial_attachments: int = 2,
|
||||
max_initial_concurrency: int = 2,
|
||||
expansion_batch_size: int = 2,
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
"""
|
||||
services/shipping_notice/audit_query_service.py
|
||||
|
||||
用途:管理员货代审计查询、关联链追溯、权限裁剪脱敏详情、哈希链校验、受控导出与到期清理。
|
||||
依赖:ShippingAuditEvent、audit_service、audit_snapshot_service、fulfillment_audit、
|
||||
progress_audit_contract、SQLAlchemy。
|
||||
逻辑:由 admin API 调用;列表/详情/导出/关联链均做管理员访问审计(失败阻断查询);
|
||||
敏感 before/after/diff 仅当调用方具备 shipping_notice.audit_sensitive_read;
|
||||
支持 event_type_group=review_workbench|chat_workbench|process_gate|
|
||||
candidate_qualification|workflow_node;支持 candidate_no / gate_code 筛选;
|
||||
PostgreSQL 清理前在同事务 set_config('hxops.shipping_audit_purge','1'),
|
||||
以便 DB 触发器仅放行已到期行的 DELETE;SQLite/测试仍用 Core DELETE + ORM 守卫。
|
||||
用途:管理员货代审计查询、关联链追溯、权限裁剪脱敏详情、哈希链校验、受控导出与到期清理;
|
||||
XFA 加密完整快照的敏感读(每次再审计);另提供业务用户 Case 审计时间线(无敏感快照)。
|
||||
依赖:ShippingAuditEvent、ShippingXfaAuditSnapshot、audit_service、audit_snapshot_service、
|
||||
fulfillment_audit、progress_audit_contract、SQLAlchemy。
|
||||
逻辑:由 admin API 调用列表/详情/导出/关联链/完整快照读(失败阻断查询);
|
||||
workspace `list_review_case_audit_timeline` / `list_task_audit_timeline` 返回业务摘要;
|
||||
任务工作台时间线按 task_no 种子 + 关联键扩张,不另建事件表。
|
||||
敏感 before/after/diff 与 XFA 完整快照仅当调用方具备 shipping_notice.audit_sensitive_read;
|
||||
普通导出仅脱敏摘要,禁止完整密文/明文;支持 event_type_group 与关联键筛选;
|
||||
PostgreSQL 清理前 set_config purge GUC;XFA 快照到期清理使用独立 GUC。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,12 +27,22 @@ from app import db
|
||||
from app.core.errors import NotFoundError, ServiceUnavailableError, ValidationError
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.audit_snapshot_service import verify_event_hash_chain
|
||||
from app.services.shipping_notice.audit_snapshot_service import (
|
||||
decrypt_xfa_audit_snapshot_row,
|
||||
get_xfa_audit_snapshot_row,
|
||||
serialize_xfa_audit_snapshot_summary,
|
||||
verify_event_hash_chain,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_audit import resolve_request_audit_context
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
AUDIT_SNAPSHOT_ALLOWED_KEYS,
|
||||
CANDIDATE_QUALIFICATION_AUDIT_EVENT_TYPES,
|
||||
CHAT_WORKBENCH_AUDIT_EVENT_TYPES,
|
||||
CONVERSATION_PROCESSING_TASK_AUDIT_EVENT_TYPES,
|
||||
FORMAL_TASK_EDIT_AUDIT_EVENT_TYPES,
|
||||
ORDER_DOCUMENT_AUDIT_EVENT_TYPES,
|
||||
ORDER_EMAIL_ADJUDICATION_AUDIT_EVENT_TYPES,
|
||||
ORDER_SUBMISSION_INTAKE_AUDIT_EVENT_TYPES,
|
||||
PROCESS_GATE_AUDIT_EVENT_TYPES,
|
||||
REVIEW_WORKBENCH_AUDIT_EVENT_TYPES,
|
||||
WORKFLOW_NODE_AUDIT_EVENT_TYPES,
|
||||
@@ -162,7 +173,9 @@ def serialize_shipping_audit_event(
|
||||
'retention_expires_at': _iso(event.retention_expires_at),
|
||||
'created_at': _iso(event.created_at),
|
||||
'has_snapshots': bool(event.before_snapshot_json or event.after_snapshot_json),
|
||||
'has_xfa_full_snapshots': _has_xfa_full_snapshot_refs(event),
|
||||
'sensitive_redacted': False,
|
||||
'xfa_snapshot_refs': _xfa_snapshot_refs_from_event(event),
|
||||
}
|
||||
if include_snapshots:
|
||||
# [STEP 1] 敏感事件无权限时脱敏:不回传 before/after/diff 正文。
|
||||
@@ -182,12 +195,136 @@ def serialize_shipping_audit_event(
|
||||
return payload
|
||||
|
||||
|
||||
def _xfa_snapshot_refs_from_event(event: ShippingAuditEvent) -> list[dict[str, Any]]:
|
||||
"""从 context_refs / evidence_refs 提取 XFA 完整快照引用(不含密文)。"""
|
||||
refs: list[dict[str, Any]] = []
|
||||
context = event.context_refs_json if isinstance(event.context_refs_json, dict) else {}
|
||||
for key, purpose in (
|
||||
('snapshot_before_ref', 'before'),
|
||||
('snapshot_after_ref', 'after'),
|
||||
('snapshot_full_ref', 'full'),
|
||||
):
|
||||
value = str(context.get(key) or '').strip()
|
||||
if value:
|
||||
refs.append({'purpose': purpose, 'snapshot_ref': value})
|
||||
evidence = event.evidence_refs_json if isinstance(event.evidence_refs_json, list) else []
|
||||
for item in evidence:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if str(item.get('kind') or '') != 'xfa_audit_snapshot':
|
||||
continue
|
||||
ref = str(item.get('snapshot_ref') or '').strip()
|
||||
if not ref:
|
||||
continue
|
||||
if any(row['snapshot_ref'] == ref for row in refs):
|
||||
continue
|
||||
refs.append({
|
||||
'purpose': str(item.get('purpose') or 'full'),
|
||||
'snapshot_ref': ref,
|
||||
'plaintext_sha256': item.get('plaintext_sha256'),
|
||||
})
|
||||
return refs
|
||||
|
||||
|
||||
def _has_xfa_full_snapshot_refs(event: ShippingAuditEvent) -> bool:
|
||||
"""事件是否挂接了 XFA 加密完整快照引用。"""
|
||||
return bool(_xfa_snapshot_refs_from_event(event))
|
||||
|
||||
|
||||
def get_xfa_audit_full_snapshot(
|
||||
*,
|
||||
admin_user_id: int,
|
||||
request_id: str | None,
|
||||
snapshot_ref: str,
|
||||
include_sensitive: bool,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
读取 XFA 加密完整快照。
|
||||
|
||||
核心逻辑:无 shipping_notice.audit_sensitive_read 时仅返回脱敏摘要并再写访问审计;
|
||||
有权限时解密完整载荷,并追加 xfa_audit_snapshot_viewed 审计事件(同事务提交)。
|
||||
|
||||
Args:
|
||||
admin_user_id: 管理员用户 ID。
|
||||
request_id: 请求关联 ID。
|
||||
snapshot_ref: 快照稳定引用。
|
||||
include_sensitive: 调用方是否具备敏感读权限。
|
||||
|
||||
Returns:
|
||||
{summary, payload|null, sensitive_redacted}。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 快照不存在。
|
||||
ValidationError: 密文篡改。
|
||||
ServiceUnavailableError: 密钥缺失导致无法解密。
|
||||
"""
|
||||
row = get_xfa_audit_snapshot_row(snapshot_ref)
|
||||
summary = serialize_xfa_audit_snapshot_summary(row)
|
||||
if not include_sensitive:
|
||||
append_shipping_audit_event(
|
||||
event_type='xfa_audit_snapshot_viewed',
|
||||
aggregate_type='shipping_xfa_audit_snapshot',
|
||||
aggregate_id=row.snapshot_ref,
|
||||
actor_type='admin',
|
||||
actor_id=admin_user_id,
|
||||
request_id=request_id,
|
||||
operation_id=request_id,
|
||||
action='read_xfa_snapshot_redacted',
|
||||
result='success',
|
||||
sensitivity_level='normal',
|
||||
metadata={
|
||||
'snapshot_ref': row.snapshot_ref,
|
||||
'purpose': row.purpose,
|
||||
'sensitive_redacted': True,
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return {
|
||||
'summary': summary,
|
||||
'payload': None,
|
||||
'sensitive_redacted': True,
|
||||
}
|
||||
|
||||
# [STEP 1] 解密并校验完整性。
|
||||
try:
|
||||
payload = decrypt_xfa_audit_snapshot_row(row)
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
# [STEP 2] 每次完整读必须再审计;审计失败则回滚,禁止无痕泄露。
|
||||
append_shipping_audit_event(
|
||||
event_type='xfa_audit_snapshot_viewed',
|
||||
aggregate_type='shipping_xfa_audit_snapshot',
|
||||
aggregate_id=row.snapshot_ref,
|
||||
actor_type='admin',
|
||||
actor_id=admin_user_id,
|
||||
request_id=request_id,
|
||||
operation_id=request_id,
|
||||
action='read_xfa_snapshot_full',
|
||||
result='success',
|
||||
sensitivity_level='sensitive',
|
||||
metadata={
|
||||
'snapshot_ref': row.snapshot_ref,
|
||||
'purpose': row.purpose,
|
||||
'plaintext_sha256': row.plaintext_sha256,
|
||||
'sensitive_redacted': False,
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return {
|
||||
'summary': summary,
|
||||
'payload': payload,
|
||||
'sensitive_redacted': False,
|
||||
}
|
||||
|
||||
|
||||
def _apply_filters(query, *, filters: dict[str, Any]):
|
||||
"""按管理员筛选条件收窄查询;禁止自由文本全文检索正文。"""
|
||||
event_type_group = str(filters.get('event_type_group') or '').strip().lower()
|
||||
# [STEP] 事件分组:与 progress_audit_contract 各字典一一对齐,禁止前端私造分组名。
|
||||
if event_type_group in {'review_workbench', 'order_review_workbench'}:
|
||||
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 {'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'}:
|
||||
@@ -198,6 +335,34 @@ def _apply_filters(query, *, filters: dict[str, Any]):
|
||||
)
|
||||
elif event_type_group in {'workflow_node', 'workflow_nodes'}:
|
||||
query = query.filter(ShippingAuditEvent.event_type.in_(sorted(WORKFLOW_NODE_AUDIT_EVENT_TYPES)))
|
||||
elif event_type_group in {
|
||||
'conversation_processing',
|
||||
'conversation_processing_task',
|
||||
'conversation_tasks',
|
||||
}:
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(CONVERSATION_PROCESSING_TASK_AUDIT_EVENT_TYPES))
|
||||
)
|
||||
elif event_type_group in {
|
||||
'order_intake',
|
||||
'order_submission_intake',
|
||||
'shipping_order_intake',
|
||||
}:
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(ORDER_SUBMISSION_INTAKE_AUDIT_EVENT_TYPES))
|
||||
)
|
||||
elif event_type_group in {'order_document', 'shipping_order_document'}:
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(ORDER_DOCUMENT_AUDIT_EVENT_TYPES))
|
||||
)
|
||||
elif event_type_group in {
|
||||
'order_email_adjudication',
|
||||
'email_adjudication',
|
||||
'pdf_priority_adjudication',
|
||||
}:
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(ORDER_EMAIL_ADJUDICATION_AUDIT_EVENT_TYPES))
|
||||
)
|
||||
if filters.get('event_type'):
|
||||
query = query.filter(ShippingAuditEvent.event_type == str(filters['event_type'])[:64])
|
||||
if filters.get('actor_type'):
|
||||
@@ -810,3 +975,324 @@ def purge_expired_shipping_audit_events(
|
||||
'deleted': deleted,
|
||||
'cutoff': _iso(current),
|
||||
}
|
||||
|
||||
|
||||
def purge_expired_xfa_audit_snapshots(
|
||||
*,
|
||||
limit: int = 1000,
|
||||
dry_run: bool = False,
|
||||
now: datetime | None = None,
|
||||
actor_id: str | int | None = 'system',
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
清理已过保留期的 XFA 加密审计快照。
|
||||
|
||||
核心逻辑:仅删除 retention_expires_at 已到期行;归档不改写哈希链引用字段;
|
||||
PostgreSQL 须 set_config('hxops.shipping_xfa_audit_purge','1')。
|
||||
|
||||
Args:
|
||||
limit: 单批上限。
|
||||
dry_run: True 时只统计。
|
||||
now: 可注入当前时间。
|
||||
actor_id: 执行者。
|
||||
|
||||
Returns:
|
||||
{dry_run, scanned, deleted, cutoff}。
|
||||
"""
|
||||
from app.models import ShippingXfaAuditSnapshot
|
||||
|
||||
current = now or datetime.utcnow()
|
||||
safe_limit = min(5000, max(1, int(limit or 1000)))
|
||||
candidate_ids = [
|
||||
int(row[0])
|
||||
for row in db.session.query(ShippingXfaAuditSnapshot.id)
|
||||
.filter(ShippingXfaAuditSnapshot.retention_expires_at < current)
|
||||
.order_by(ShippingXfaAuditSnapshot.retention_expires_at.asc(), ShippingXfaAuditSnapshot.id.asc())
|
||||
.limit(safe_limit)
|
||||
.all()
|
||||
]
|
||||
if dry_run or not candidate_ids:
|
||||
return {
|
||||
'dry_run': bool(dry_run),
|
||||
'scanned': len(candidate_ids),
|
||||
'deleted': 0,
|
||||
'cutoff': _iso(current),
|
||||
}
|
||||
|
||||
tracked = [
|
||||
obj
|
||||
for eid in candidate_ids
|
||||
if (obj := db.session.get(ShippingXfaAuditSnapshot, eid)) is not None
|
||||
]
|
||||
if db.engine.dialect.name == 'postgresql':
|
||||
db.session.execute(text("SELECT set_config('hxops.shipping_xfa_audit_purge', '1', true)"))
|
||||
result = db.session.execute(
|
||||
delete(ShippingXfaAuditSnapshot).where(ShippingXfaAuditSnapshot.id.in_(candidate_ids))
|
||||
)
|
||||
deleted = int(result.rowcount or 0)
|
||||
for obj in tracked:
|
||||
db.session.expunge(obj)
|
||||
|
||||
append_shipping_audit_event(
|
||||
event_type='audit_retention_purged',
|
||||
aggregate_type='shipping_xfa_audit_snapshot',
|
||||
aggregate_id=f'purge:{current.strftime("%Y%m%d%H%M%S")}',
|
||||
actor_type='system',
|
||||
actor_id=actor_id,
|
||||
source='retention_job',
|
||||
result='success',
|
||||
action='purge_expired_xfa_snapshots',
|
||||
metadata={'deleted': deleted, 'limit': safe_limit, 'dry_run': False},
|
||||
persist_snapshots=False,
|
||||
)
|
||||
db.session.commit()
|
||||
return {
|
||||
'dry_run': False,
|
||||
'scanned': len(candidate_ids),
|
||||
'deleted': deleted,
|
||||
'cutoff': _iso(current),
|
||||
}
|
||||
|
||||
|
||||
def _serialize_workspace_audit_timeline_item(
|
||||
row: ShippingAuditEvent,
|
||||
*,
|
||||
include_snapshots: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将 ShippingAuditEvent 序列化为工作台业务用户可读时间线条目。
|
||||
|
||||
核心逻辑:调用 serialize_shipping_audit_event 并裁剪为前端时间线所需字段;
|
||||
敏感快照对业务用户脱敏(sensitive_redacted=True)。
|
||||
|
||||
Args:
|
||||
row: 审计事件 ORM。
|
||||
include_snapshots: 是否附带白名单 before/after/diff。
|
||||
|
||||
Returns:
|
||||
含 id/event_type/actor_display/created_at 等业务摘要 dict。
|
||||
"""
|
||||
serialized = serialize_shipping_audit_event(
|
||||
row,
|
||||
include_snapshots=bool(include_snapshots),
|
||||
include_sensitive=False,
|
||||
)
|
||||
return {
|
||||
'id': serialized['id'],
|
||||
'event_type': serialized.get('event_type'),
|
||||
'action': serialized.get('action'),
|
||||
'result': serialized.get('result'),
|
||||
'actor_type': serialized.get('actor_type'),
|
||||
'actor_display': serialized.get('actor_display'),
|
||||
'task_no': serialized.get('task_no'),
|
||||
'error_code': serialized.get('error_code'),
|
||||
'reason': serialized.get('reason'),
|
||||
'reason_code': serialized.get('reason_code'),
|
||||
'metadata': serialized.get('metadata') or {},
|
||||
'created_at': serialized.get('created_at'),
|
||||
'source': serialized.get('source'),
|
||||
'has_snapshots': bool(serialized.get('has_snapshots')),
|
||||
'sensitive_redacted': bool(serialized.get('sensitive_redacted')),
|
||||
'before_snapshot': serialized.get('before_snapshot') if include_snapshots else None,
|
||||
'after_snapshot': serialized.get('after_snapshot') if include_snapshots else None,
|
||||
'diff': serialized.get('diff') if include_snapshots else [],
|
||||
}
|
||||
|
||||
|
||||
def _collect_task_audit_seed_values(*, task_no: str, task: Any | None = None) -> dict[str, set[str]]:
|
||||
"""
|
||||
收集任务工作台审计时间线的关联种子键。
|
||||
|
||||
核心逻辑:以 task_no 为主种子;若传入 ShippingNotice,则补充 confirmed Case 的
|
||||
review_case_no / run_no / document_id,便于关联建单前 Run 与复核事件。
|
||||
|
||||
Args:
|
||||
task_no: 对外任务编号(ShippingNotice.task_no)。
|
||||
task: 可选已校验可见的任务 ORM。
|
||||
|
||||
Returns:
|
||||
关联键 → 编号集合;至少含 task_no(非空时)。
|
||||
"""
|
||||
seeds: dict[str, set[str]] = {}
|
||||
normalized = str(task_no or '').strip()[:64]
|
||||
if normalized:
|
||||
seeds['task_no'] = {normalized}
|
||||
if task is None:
|
||||
return seeds
|
||||
try:
|
||||
from app.models import ShippingOrderReviewCase
|
||||
|
||||
cases = (
|
||||
ShippingOrderReviewCase.query.filter_by(confirmed_task_id=int(task.id))
|
||||
.order_by(ShippingOrderReviewCase.updated_at.desc())
|
||||
.limit(20)
|
||||
.all()
|
||||
)
|
||||
for case in cases:
|
||||
case_no = str(getattr(case, 'case_no', '') or '').strip()
|
||||
if case_no:
|
||||
seeds.setdefault('review_case_no', set()).add(case_no[:64])
|
||||
run = getattr(case, 'run', None)
|
||||
run_no = str(getattr(run, 'run_no', '') or '').strip()
|
||||
if run_no:
|
||||
seeds.setdefault('run_no', set()).add(run_no[:64])
|
||||
document_id = getattr(case, 'document_id', None)
|
||||
if document_id is not None:
|
||||
seeds.setdefault('document_id', set()).add(str(document_id)[:64])
|
||||
except Exception:
|
||||
pass
|
||||
return seeds
|
||||
|
||||
|
||||
def _task_audit_association_clause(*, task_no: str, task: Any | None = None):
|
||||
"""
|
||||
构建任务工作台审计时间线的 OR 关联过滤条件。
|
||||
|
||||
核心逻辑:种子键直查 → 从命中行扩张 workflow/run/case 等稳定编号 → 全链 OR;
|
||||
无种子时返回 None。
|
||||
|
||||
Args:
|
||||
task_no: 任务编号。
|
||||
task: 可选已校验任务,用于补充 Case/Run 种子。
|
||||
|
||||
Returns:
|
||||
SQLAlchemy OR 子句或 None。
|
||||
"""
|
||||
seeds = _collect_task_audit_seed_values(task_no=task_no, task=task)
|
||||
if not seeds:
|
||||
return None
|
||||
column_map = {
|
||||
'workflow_id': ShippingAuditEvent.workflow_id,
|
||||
'workflow_item_id': ShippingAuditEvent.workflow_item_id,
|
||||
'run_no': ShippingAuditEvent.run_no,
|
||||
'document_id': ShippingAuditEvent.document_id,
|
||||
'review_case_no': ShippingAuditEvent.review_case_no,
|
||||
'task_no': ShippingAuditEvent.task_no,
|
||||
}
|
||||
seed_clauses = []
|
||||
for key, values in seeds.items():
|
||||
column = column_map.get(key)
|
||||
if column is not None and values:
|
||||
seed_clauses.append(column.in_(sorted(values)))
|
||||
if not seed_clauses:
|
||||
return None
|
||||
seed_rows = (
|
||||
ShippingAuditEvent.query
|
||||
.filter(or_(*seed_clauses))
|
||||
.order_by(ShippingAuditEvent.id.asc())
|
||||
.limit(500)
|
||||
.all()
|
||||
)
|
||||
expanded = _expand_association_keys(seed_rows)
|
||||
for key, values in seeds.items():
|
||||
expanded.setdefault(key, set()).update(values)
|
||||
return _association_or_clause(expanded)
|
||||
|
||||
|
||||
def list_review_case_audit_timeline(
|
||||
*,
|
||||
user_id: int,
|
||||
case_no: str,
|
||||
page: int = 1,
|
||||
page_size: int = 50,
|
||||
include_snapshots: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
业务用户可读的 Case 审计时间线。
|
||||
|
||||
核心逻辑:按 review_case_no 过滤;返回白名单 before/after/diff;
|
||||
sensitivity=sensitive 的快照对业务用户脱敏(sensitive_redacted=True)。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户(仅用于可见性由调用方保证)。
|
||||
case_no: 复核 Case 编号。
|
||||
page: 页码。
|
||||
page_size: 页大小(最大 100)。
|
||||
include_snapshots: 是否附带变更前后快照与字段差异。
|
||||
|
||||
Returns:
|
||||
items/total/page/page_size;条目含业务摘要与可选快照。
|
||||
"""
|
||||
del user_id # 可见性由 workspace 路由预先校验
|
||||
safe_page = max(1, int(page or 1))
|
||||
safe_page_size = min(100, max(1, int(page_size or 50)))
|
||||
query = ShippingAuditEvent.query.filter(
|
||||
ShippingAuditEvent.review_case_no == str(case_no)[:64],
|
||||
)
|
||||
total = query.count()
|
||||
rows = (
|
||||
query.order_by(ShippingAuditEvent.created_at.desc(), ShippingAuditEvent.id.desc())
|
||||
.offset((safe_page - 1) * safe_page_size)
|
||||
.limit(safe_page_size)
|
||||
.all()
|
||||
)
|
||||
items = [
|
||||
_serialize_workspace_audit_timeline_item(row, include_snapshots=bool(include_snapshots))
|
||||
for row in rows
|
||||
]
|
||||
return {
|
||||
'items': items,
|
||||
'total': total,
|
||||
'page': safe_page,
|
||||
'page_size': safe_page_size,
|
||||
'case_no': str(case_no),
|
||||
}
|
||||
|
||||
|
||||
def list_task_audit_timeline(
|
||||
*,
|
||||
user_id: int,
|
||||
task_no: str,
|
||||
task: Any | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 50,
|
||||
include_snapshots: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
业务用户可读的任务工作台审计时间线(统一 ShippingAuditEvent)。
|
||||
|
||||
核心逻辑:以 task_no 及关联 Case/Run 为种子,扩张关联键后分页返回;
|
||||
默认不含快照正文(工作台时间线只读摘要);敏感事件仍标记 sensitive_redacted。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户(可见性由 workspace 路由预先校验)。
|
||||
task_no: 发货任务编号。
|
||||
task: 可选已校验可见的 ShippingNotice,用于补充关联种子。
|
||||
page: 页码。
|
||||
page_size: 页大小(最大 100)。
|
||||
include_snapshots: 是否附带变更前后快照与字段差异。
|
||||
|
||||
Returns:
|
||||
items/total/page/page_size/task_no。
|
||||
"""
|
||||
del user_id
|
||||
safe_page = max(1, int(page or 1))
|
||||
safe_page_size = min(100, max(1, int(page_size or 50)))
|
||||
clause = _task_audit_association_clause(task_no=task_no, task=task)
|
||||
if clause is None:
|
||||
return {
|
||||
'items': [],
|
||||
'total': 0,
|
||||
'page': safe_page,
|
||||
'page_size': safe_page_size,
|
||||
'task_no': str(task_no),
|
||||
}
|
||||
query = ShippingAuditEvent.query.filter(clause)
|
||||
total = query.count()
|
||||
rows = (
|
||||
query.order_by(ShippingAuditEvent.created_at.desc(), ShippingAuditEvent.id.desc())
|
||||
.offset((safe_page - 1) * safe_page_size)
|
||||
.limit(safe_page_size)
|
||||
.all()
|
||||
)
|
||||
items = [
|
||||
_serialize_workspace_audit_timeline_item(row, include_snapshots=bool(include_snapshots))
|
||||
for row in rows
|
||||
]
|
||||
return {
|
||||
'items': items,
|
||||
'total': total,
|
||||
'page': safe_page,
|
||||
'page_size': safe_page_size,
|
||||
'task_no': str(task_no),
|
||||
}
|
||||
@@ -2,14 +2,14 @@
|
||||
backend/app/services/shipping_notice/audit_service.py
|
||||
|
||||
用途:货代领域统一审计事件的唯一写入入口;要求操作上下文与前后快照(可为空),
|
||||
写入 Workflow 软引用与哈希链字段。
|
||||
写入 Workflow 软引用与哈希链字段;XFA 敏感变更可同事务挂接加密完整快照引用。
|
||||
依赖:ShippingAuditEvent、progress_audit_contract、audit_snapshot_service(在 append 内导入以避免环)、
|
||||
SQLAlchemy 会话。
|
||||
逻辑:Run、Task、Workflow Item、库存、门禁 Attempt 和 Chatflow 服务调用本模块写入状态与决策事实;
|
||||
写入前投影白名单快照 → 计算 diff → 解析同聚合 previous_event_hash → 计算 event_hash;
|
||||
本服务不提交事务,由调用方保证业务与审计原子性。支持 operation_id、白名单前后快照、
|
||||
证据引用、Workflow 软引用(非 session_item)、属主;actor_type 含 worker(门禁 Job);
|
||||
货代全业务审计事件永久保留(retention_expires_at=None),清理 Job 仅处理历史遗留到期行。
|
||||
逻辑:Run、Task、Workflow Item、库存、门禁 Attempt、Chatflow 与 XFA Profile 服务调用本模块;
|
||||
写入前投影白名单快照 → 可选创建 XFA 加密完整快照 → 计算 diff → 解析同聚合
|
||||
previous_event_hash → 计算 event_hash;本服务不提交事务,由调用方保证业务与审计原子性;
|
||||
审计/快照写入失败时业务不得提交。支持 operation_id、白名单前后快照、证据引用、
|
||||
Workflow 软引用、属主;actor_type 含 worker;货代统一账本永久保留(expires=None)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -210,6 +210,10 @@ def append_shipping_audit_event(
|
||||
sensitivity_level: str | None = None,
|
||||
retention_expires_at: datetime | None = None,
|
||||
persist_snapshots: bool = True,
|
||||
full_before: dict[str, Any] | None = None,
|
||||
full_after: dict[str, Any] | None = None,
|
||||
full_payload: dict[str, Any] | None = None,
|
||||
full_payload_purpose: str = 'full',
|
||||
) -> ShippingAuditEvent:
|
||||
"""
|
||||
追加一条货代审计事实(唯一写入口)。
|
||||
@@ -230,18 +234,23 @@ def append_shipping_audit_event(
|
||||
evidence_refs/artifact_refs: FileAsset ID、SHA-256、版本与证据坐标,禁止 URL/正文。
|
||||
metadata: 仅允许原因码、计数、版本等脱敏诊断事实。
|
||||
persist_snapshots: False 时只写哈希(兼容历史调用方仅传 before/after 哈希语义)。
|
||||
full_before/full_after/full_payload: XFA 完整敏感载荷;加密写入 shipping_xfa_audit_snapshots,
|
||||
引用挂到 context_refs.snapshot_*_ref;缺主密钥时失败关闭。
|
||||
full_payload_purpose: full_payload 的用途标签(默认 full)。
|
||||
|
||||
Returns:
|
||||
尚未提交的审计事件,由调用方与业务写入在同一事务提交。
|
||||
|
||||
Raises:
|
||||
ValidationError: actor 类型、元数据或快照包含正文、凭据等敏感字段。
|
||||
ServiceUnavailableError: 需要加密快照但主密钥缺失。
|
||||
"""
|
||||
# 延迟导入:audit_snapshot_service.sanitize_snapshot 会回引 project_audit_snapshot,避免模块环。
|
||||
from app.services.shipping_notice.audit_snapshot_service import (
|
||||
build_event_hash_payload,
|
||||
compute_event_hash,
|
||||
compute_snapshot_diff,
|
||||
create_xfa_audit_snapshot,
|
||||
resolve_previous_event_hash,
|
||||
)
|
||||
|
||||
@@ -256,8 +265,66 @@ def append_shipping_audit_event(
|
||||
before_snapshot = project_audit_snapshot(before) if before is not None else None
|
||||
after_snapshot = project_audit_snapshot(after) if after is not None else None
|
||||
diff_json = compute_snapshot_diff(before_snapshot, after_snapshot)
|
||||
if context_refs is not None:
|
||||
_sanitize_metadata(context_refs)
|
||||
|
||||
# [STEP 1b] XFA 完整载荷 → 加密不可变快照;失败则阻断业务提交。
|
||||
resolved_context = dict(context_refs or {}) if context_refs is not None else {}
|
||||
snapshot_refs: list[dict[str, Any]] = []
|
||||
if full_before is not None:
|
||||
before_row = create_xfa_audit_snapshot(
|
||||
payload=full_before,
|
||||
object_type=str(aggregate_type)[:64],
|
||||
object_id=str(aggregate_id)[:128],
|
||||
purpose='before',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
)
|
||||
resolved_context['snapshot_before_ref'] = before_row.snapshot_ref
|
||||
snapshot_refs.append({
|
||||
'kind': 'xfa_audit_snapshot',
|
||||
'purpose': 'before',
|
||||
'snapshot_ref': before_row.snapshot_ref,
|
||||
'plaintext_sha256': before_row.plaintext_sha256,
|
||||
})
|
||||
if full_after is not None:
|
||||
after_row = create_xfa_audit_snapshot(
|
||||
payload=full_after,
|
||||
object_type=str(aggregate_type)[:64],
|
||||
object_id=str(aggregate_id)[:128],
|
||||
purpose='after',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
)
|
||||
resolved_context['snapshot_after_ref'] = after_row.snapshot_ref
|
||||
snapshot_refs.append({
|
||||
'kind': 'xfa_audit_snapshot',
|
||||
'purpose': 'after',
|
||||
'snapshot_ref': after_row.snapshot_ref,
|
||||
'plaintext_sha256': after_row.plaintext_sha256,
|
||||
})
|
||||
if full_payload is not None:
|
||||
full_row = create_xfa_audit_snapshot(
|
||||
payload=full_payload,
|
||||
object_type=str(aggregate_type)[:64],
|
||||
object_id=str(aggregate_id)[:128],
|
||||
purpose=str(full_payload_purpose or 'full'),
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
)
|
||||
resolved_context['snapshot_full_ref'] = full_row.snapshot_ref
|
||||
snapshot_refs.append({
|
||||
'kind': 'xfa_audit_snapshot',
|
||||
'purpose': full_row.purpose,
|
||||
'snapshot_ref': full_row.snapshot_ref,
|
||||
'plaintext_sha256': full_row.plaintext_sha256,
|
||||
})
|
||||
if resolved_context:
|
||||
_sanitize_metadata(resolved_context)
|
||||
merged_evidence = list(evidence_refs or [])
|
||||
if snapshot_refs:
|
||||
merged_evidence.extend(snapshot_refs)
|
||||
|
||||
resolved_ip_hash = client_ip_hash or hash_client_context_value(client_ip)
|
||||
resolved_ua_hash = user_agent_hash or hash_client_context_value(user_agent)
|
||||
@@ -361,13 +428,14 @@ def append_shipping_audit_event(
|
||||
previous_event_hash=previous_event_hash,
|
||||
event_hash=event_hash,
|
||||
sensitivity_level=resolved_sensitivity,
|
||||
evidence_refs_json=_sanitize_refs(evidence_refs, field_name='evidence_refs'),
|
||||
evidence_refs_json=_sanitize_refs(merged_evidence or None, field_name='evidence_refs'),
|
||||
artifact_refs_json=_sanitize_refs(artifact_refs, field_name='artifact_refs'),
|
||||
context_refs_json=dict(context_refs) if context_refs else None,
|
||||
context_refs_json=resolved_context or None,
|
||||
metadata_json=_sanitize_metadata(metadata),
|
||||
retention_expires_at=resolved_retention,
|
||||
)
|
||||
db.session.add(event)
|
||||
db.session.flush()
|
||||
return event
|
||||
|
||||
|
||||
|
||||
@@ -1,23 +1,59 @@
|
||||
"""
|
||||
services/shipping_notice/audit_snapshot_service.py
|
||||
|
||||
用途:审计快照标准化、敏感字段脱敏、前后差异与哈希链计算。
|
||||
依赖:progress_audit_contract、hashlib/json;由 audit_service 写入前调用。
|
||||
用途:审计快照标准化、敏感字段脱敏、前后差异、哈希链,以及 XFA 加密不可变完整快照。
|
||||
依赖:progress_audit_contract、ShippingAuditEvent、ShippingXfaAuditSnapshot、cryptography.fernet、
|
||||
Flask current_app(SECRET_KEY);由 audit_service / audit_query_service / XFA 写路径调用。
|
||||
逻辑:业务写路径先投影白名单快照 → 计算 diff → 读取同聚合上一条 event_hash
|
||||
作为 previous_event_hash → 再计算本条 event_hash;保留任务可离线校验链完整性。
|
||||
作为 previous_event_hash → 再计算本条 event_hash;XFA 敏感写另将完整载荷
|
||||
用 SECRET_KEY 派生 Fernet 加密落入 shipping_xfa_audit_snapshots(无独立审计密钥),
|
||||
并在事件 context_refs 挂 ref;SECRET_KEY 缺失时敏感写失败关闭;
|
||||
完整解密仅敏感读路径且每次再写访问审计。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingAuditEvent
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.models import ShippingAuditEvent, ShippingXfaAuditSnapshot
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
AUDIT_SNAPSHOT_ALLOWED_KEYS,
|
||||
is_forbidden_audit_key,
|
||||
)
|
||||
from app.services.shipping_notice.progress_feature_flags import audit_retention_days
|
||||
|
||||
XFA_AUDIT_SNAPSHOT_SCHEMA = 'xfa_audit_v1'
|
||||
XFA_AUDIT_SNAPSHOT_PURPOSES = frozenset({'before', 'after', 'request', 'full', 'sample_values'})
|
||||
# 完整快照脱敏摘要允许键;禁止 XML / 明文订单值。
|
||||
XFA_REDACTED_SUMMARY_KEYS = frozenset({
|
||||
'template_mode',
|
||||
'definition_checksum',
|
||||
'template_packet_checksum',
|
||||
'datasets_packet_checksum',
|
||||
'dataset_structure_fingerprint',
|
||||
'authoritative_collection_path_hash',
|
||||
'header_mapping_count',
|
||||
'line_mapping_count',
|
||||
'bound_field_count',
|
||||
'mirror_collection_count',
|
||||
'xfa_document_kind',
|
||||
'analysis_id',
|
||||
'revision_no',
|
||||
'profile_code',
|
||||
'profile_version',
|
||||
'path_id_hash',
|
||||
'field_count',
|
||||
'purpose',
|
||||
})
|
||||
|
||||
|
||||
def _canonical_json(value: Any) -> str:
|
||||
@@ -267,3 +303,315 @@ def verify_event_hash_chain(
|
||||
})
|
||||
previous_hash = event.event_hash
|
||||
return (len(failures) == 0, failures)
|
||||
|
||||
|
||||
def _xfa_snapshot_fernet() -> Fernet:
|
||||
"""
|
||||
构造 XFA 审计快照加密器。
|
||||
|
||||
核心逻辑:仅用应用 SECRET_KEY 派生稳定 Fernet 密钥,**不存在也不读取**
|
||||
独立审计密钥环境变量;SECRET_KEY 缺失时失败关闭。
|
||||
|
||||
Returns:
|
||||
Fernet 实例。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: SECRET_KEY 缺失。
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
|
||||
secret = str(current_app.config.get('SECRET_KEY') or '').strip()
|
||||
if not secret:
|
||||
raise ServiceUnavailableError(
|
||||
'SECRET_KEY is not configured for XFA audit snapshots',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_SECRET_MISSING',
|
||||
)
|
||||
digest = hashlib.sha256(f'shipping-xfa-audit-snapshot-v1:{secret}'.encode('utf-8')).digest()
|
||||
return Fernet(base64.urlsafe_b64encode(digest))
|
||||
|
||||
|
||||
def require_xfa_audit_crypto() -> None:
|
||||
"""
|
||||
敏感写路径前置检查:确认 SECRET_KEY 可派生快照加密器。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: SECRET_KEY 未配置。
|
||||
"""
|
||||
_xfa_snapshot_fernet()
|
||||
|
||||
|
||||
def require_xfa_audit_snapshot_key() -> None:
|
||||
"""
|
||||
兼容旧调用名;等价于 require_xfa_audit_crypto(无独立审计密钥)。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: SECRET_KEY 未配置。
|
||||
"""
|
||||
require_xfa_audit_crypto()
|
||||
|
||||
|
||||
def encrypt_xfa_audit_payload(payload: dict[str, Any]) -> tuple[str, str, str]:
|
||||
"""
|
||||
将完整 XFA 审计载荷加密为 Fernet 密文。
|
||||
|
||||
Args:
|
||||
payload: 可 JSON 化的完整快照对象(definition / 受控原值等)。
|
||||
|
||||
Returns:
|
||||
(ciphertext, ciphertext_sha256, plaintext_sha256)。
|
||||
|
||||
Raises:
|
||||
ValidationError: payload 非对象。
|
||||
ServiceUnavailableError: 主密钥缺失。
|
||||
"""
|
||||
if not isinstance(payload, dict):
|
||||
raise ValidationError(
|
||||
'XFA audit snapshot payload must be an object',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_INVALID',
|
||||
)
|
||||
plaintext = _canonical_json(payload)
|
||||
plaintext_sha = hashlib.sha256(plaintext.encode('ascii')).hexdigest()
|
||||
ciphertext = _xfa_snapshot_fernet().encrypt(plaintext.encode('utf-8')).decode('ascii')
|
||||
ciphertext_sha = hashlib.sha256(ciphertext.encode('ascii')).hexdigest()
|
||||
return ciphertext, ciphertext_sha, plaintext_sha
|
||||
|
||||
|
||||
def decrypt_xfa_audit_payload(ciphertext: str) -> dict[str, Any]:
|
||||
"""
|
||||
解密 XFA 审计完整快照。
|
||||
|
||||
Args:
|
||||
ciphertext: 数据库中的 Fernet 密文。
|
||||
|
||||
Returns:
|
||||
明文 dict。
|
||||
|
||||
Raises:
|
||||
ValidationError: 密文空/损坏/密钥不匹配。
|
||||
ServiceUnavailableError: 主密钥缺失。
|
||||
"""
|
||||
value = str(ciphertext or '').strip()
|
||||
if not value:
|
||||
raise ValidationError(
|
||||
'XFA audit snapshot ciphertext is missing',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_INVALID',
|
||||
)
|
||||
try:
|
||||
raw = _xfa_snapshot_fernet().decrypt(value.encode('ascii')).decode('utf-8')
|
||||
payload = json.loads(raw)
|
||||
except (InvalidToken, UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
raise ValidationError(
|
||||
'XFA audit snapshot ciphertext is invalid',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_INVALID',
|
||||
) from exc
|
||||
if not isinstance(payload, dict):
|
||||
raise ValidationError(
|
||||
'XFA audit snapshot plaintext must be an object',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_INVALID',
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def build_xfa_redacted_summary(payload: dict[str, Any] | None, *, purpose: str) -> dict[str, Any]:
|
||||
"""
|
||||
从完整载荷提取可导出的脱敏摘要。
|
||||
|
||||
核心逻辑:仅保留 XFA_REDACTED_SUMMARY_KEYS;禁止敏感键进入摘要。
|
||||
|
||||
Args:
|
||||
payload: 完整或半完整载荷。
|
||||
purpose: 快照用途标签。
|
||||
|
||||
Returns:
|
||||
脱敏摘要 dict。
|
||||
"""
|
||||
source = payload if isinstance(payload, dict) else {}
|
||||
summary: dict[str, Any] = {'purpose': purpose}
|
||||
for key in sorted(XFA_REDACTED_SUMMARY_KEYS):
|
||||
if key == 'purpose':
|
||||
continue
|
||||
if key not in source:
|
||||
continue
|
||||
if is_forbidden_audit_key(key):
|
||||
continue
|
||||
summary[key] = source[key]
|
||||
return summary
|
||||
|
||||
|
||||
def default_xfa_snapshot_retention_expires_at(*, now: datetime | None = None) -> datetime:
|
||||
"""
|
||||
计算 XFA 快照保留到期时间(默认 3 年 / 1095 天)。
|
||||
|
||||
Args:
|
||||
now: 可选当前时间。
|
||||
|
||||
Returns:
|
||||
UTC naive 到期时间。
|
||||
"""
|
||||
base = now or datetime.utcnow()
|
||||
return base + timedelta(days=audit_retention_days())
|
||||
|
||||
|
||||
def create_xfa_audit_snapshot(
|
||||
*,
|
||||
payload: dict[str, Any],
|
||||
object_type: str,
|
||||
object_id: str,
|
||||
purpose: str,
|
||||
actor_id: str | int | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
redacted_summary: dict[str, Any] | None = None,
|
||||
retention_expires_at: datetime | None = None,
|
||||
) -> ShippingXfaAuditSnapshot:
|
||||
"""
|
||||
在当前事务中写入一条加密不可变 XFA 审计快照。
|
||||
|
||||
核心逻辑:缺密钥失败关闭 → 加密 → 落库密文与双 checksum → 返回 ORM(未 commit)。
|
||||
调用方须与业务变更、ShippingAuditEvent 同事务提交;任一失败整体回滚。
|
||||
|
||||
Args:
|
||||
payload: 完整敏感载荷。
|
||||
object_type/object_id: 业务对象身份。
|
||||
purpose: before/after/request/full/sample_values。
|
||||
actor_id/request_id/operation_id: 操作上下文。
|
||||
redacted_summary: 可选预计算脱敏摘要;缺省由 payload 投影。
|
||||
retention_expires_at: 可选到期时间;缺省 3 年。
|
||||
|
||||
Returns:
|
||||
尚未提交的 ShippingXfaAuditSnapshot。
|
||||
|
||||
Raises:
|
||||
ValidationError: purpose 非法或 payload 非法。
|
||||
ServiceUnavailableError: 主密钥缺失。
|
||||
"""
|
||||
safe_purpose = str(purpose or '').strip()
|
||||
if safe_purpose not in XFA_AUDIT_SNAPSHOT_PURPOSES:
|
||||
raise ValidationError(
|
||||
'Invalid XFA audit snapshot purpose',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_INVALID',
|
||||
details={'purpose': safe_purpose},
|
||||
)
|
||||
# [STEP 1] 加密完整载荷(缺密钥在此失败关闭)。
|
||||
ciphertext, ciphertext_sha, plaintext_sha = encrypt_xfa_audit_payload(payload)
|
||||
summary = redacted_summary if isinstance(redacted_summary, dict) else build_xfa_redacted_summary(
|
||||
payload, purpose=safe_purpose,
|
||||
)
|
||||
# [STEP 2] 生成不可猜测的 snapshot_ref 并登记密文行。
|
||||
row = ShippingXfaAuditSnapshot(
|
||||
snapshot_ref=f'xfa-snap-{uuid.uuid4().hex}',
|
||||
object_type=str(object_type)[:64],
|
||||
object_id=str(object_id)[:128],
|
||||
purpose=safe_purpose,
|
||||
schema_version=XFA_AUDIT_SNAPSHOT_SCHEMA,
|
||||
encryption_alg='fernet-v1',
|
||||
key_id='primary',
|
||||
ciphertext=ciphertext,
|
||||
ciphertext_sha256=ciphertext_sha,
|
||||
plaintext_sha256=plaintext_sha,
|
||||
redacted_summary_json=summary,
|
||||
actor_id=str(actor_id)[:128] if actor_id is not None else None,
|
||||
request_id=str(request_id)[:64] if request_id else None,
|
||||
operation_id=str(operation_id)[:64] if operation_id else None,
|
||||
retention_expires_at=retention_expires_at or default_xfa_snapshot_retention_expires_at(),
|
||||
created_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(row)
|
||||
db.session.flush()
|
||||
return row
|
||||
|
||||
|
||||
def get_xfa_audit_snapshot_row(snapshot_ref: str) -> ShippingXfaAuditSnapshot:
|
||||
"""
|
||||
按 snapshot_ref 加载快照行(不含解密)。
|
||||
|
||||
Args:
|
||||
snapshot_ref: 稳定引用。
|
||||
|
||||
Returns:
|
||||
ORM 行。
|
||||
|
||||
Raises:
|
||||
ValidationError: ref 为空。
|
||||
上层用 NotFoundError 包装缺失。
|
||||
"""
|
||||
ref = str(snapshot_ref or '').strip()
|
||||
if not ref:
|
||||
raise ValidationError(
|
||||
'XFA audit snapshot_ref is required',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_INVALID',
|
||||
)
|
||||
row = ShippingXfaAuditSnapshot.query.filter_by(snapshot_ref=ref).first()
|
||||
if row is None:
|
||||
from app.core.errors import NotFoundError
|
||||
|
||||
raise NotFoundError(
|
||||
'XFA audit snapshot not found',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_NOT_FOUND',
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def serialize_xfa_audit_snapshot_summary(row: ShippingXfaAuditSnapshot) -> dict[str, Any]:
|
||||
"""
|
||||
序列化普通权限可见的快照摘要(无密文、无明文)。
|
||||
|
||||
Args:
|
||||
row: 快照 ORM。
|
||||
|
||||
Returns:
|
||||
脱敏摘要 dict。
|
||||
"""
|
||||
return {
|
||||
'snapshot_ref': row.snapshot_ref,
|
||||
'object_type': row.object_type,
|
||||
'object_id': row.object_id,
|
||||
'purpose': row.purpose,
|
||||
'schema_version': row.schema_version,
|
||||
'encryption_alg': row.encryption_alg,
|
||||
'ciphertext_sha256': row.ciphertext_sha256,
|
||||
'plaintext_sha256': row.plaintext_sha256,
|
||||
'redacted_summary': (
|
||||
dict(row.redacted_summary_json)
|
||||
if isinstance(row.redacted_summary_json, dict)
|
||||
else {}
|
||||
),
|
||||
'operation_id': row.operation_id,
|
||||
'request_id': row.request_id,
|
||||
'retention_expires_at': (
|
||||
row.retention_expires_at.isoformat() if row.retention_expires_at else None
|
||||
),
|
||||
'created_at': row.created_at.isoformat() if row.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
def decrypt_xfa_audit_snapshot_row(row: ShippingXfaAuditSnapshot) -> dict[str, Any]:
|
||||
"""
|
||||
解密快照并校验 ciphertext / plaintext 完整性。
|
||||
|
||||
核心逻辑:重算密文 sha;解密后校验 plaintext sha;任一不匹配视为篡改。
|
||||
|
||||
Args:
|
||||
row: 快照 ORM。
|
||||
|
||||
Returns:
|
||||
明文 payload。
|
||||
|
||||
Raises:
|
||||
ValidationError: 哈希不匹配或密文无效。
|
||||
"""
|
||||
expected_cipher = hashlib.sha256(str(row.ciphertext or '').encode('ascii')).hexdigest()
|
||||
if expected_cipher != str(row.ciphertext_sha256 or ''):
|
||||
raise ValidationError(
|
||||
'XFA audit snapshot ciphertext integrity check failed',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_TAMPERED',
|
||||
)
|
||||
payload = decrypt_xfa_audit_payload(row.ciphertext)
|
||||
actual_plain = stable_content_hash(payload)
|
||||
if actual_plain != str(row.plaintext_sha256 or ''):
|
||||
raise ValidationError(
|
||||
'XFA audit snapshot plaintext integrity check failed',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_TAMPERED',
|
||||
)
|
||||
return payload
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
services/shipping_notice/batch_create_idempotency.py
|
||||
|
||||
用途:发货通知建单幂等键标准化、批次回查与跨请求文件内容重复校验。
|
||||
依赖:models.ShippingBatch/ShippingTask、query_service、tool_response 序列化。
|
||||
逻辑:batch_from_notices 与 task_workflow 共用本模块;与 ShippingTask.idempotency_key(货代上传幂等)语义分离。
|
||||
用途:发货通知建单幂等键标准化、跨请求文件内容重复校验(co8 起批次回查已移除)。
|
||||
依赖:models.ShippingNotice、query_service、batch_legacy_removed。
|
||||
逻辑:batch_from_notices 与 task_workflow 共用本模块;与 ShippingNotice.idempotency_key(货代上传幂等)语义分离。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,13 +19,8 @@ from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_focus_task_for_batch,
|
||||
list_sorted_batch_tasks,
|
||||
serialize_batch_for_tool,
|
||||
serialize_task_summary,
|
||||
)
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -108,52 +103,35 @@ def compute_notice_items_content_fingerprint(notice_items: list[dict[str, Any]])
|
||||
return hashlib.sha256("|".join(hashes).encode("utf-8")).hexdigest().lower()
|
||||
|
||||
|
||||
def batch_stored_content_fingerprint(batch: ShippingBatch) -> str | None:
|
||||
"""
|
||||
读取批次已持久化的文件集合指纹;历史批次无字段时从任务 source_content_hash 推导。
|
||||
"""
|
||||
summary = batch.process_summary_json if isinstance(batch.process_summary_json, dict) else {}
|
||||
stored = str(summary.get("create_content_fingerprint") or "").strip().lower()
|
||||
if stored:
|
||||
return stored
|
||||
tasks = list_sorted_batch_tasks(batch)
|
||||
hashes = sorted(
|
||||
{
|
||||
str(task.source_content_hash or "").strip().lower()
|
||||
for task in tasks
|
||||
if str(task.source_content_hash or "").strip()
|
||||
}
|
||||
)
|
||||
if not hashes:
|
||||
return None
|
||||
return hashlib.sha256("|".join(hashes).encode("utf-8")).hexdigest().lower()
|
||||
def batch_stored_content_fingerprint(batch: Any) -> str | None:
|
||||
"""shipping_batches 已删除;保留签名供过渡调用方,固定返回 None。"""
|
||||
del batch
|
||||
return None
|
||||
|
||||
|
||||
def assert_idempotent_batch_content_matches(
|
||||
batch: ShippingBatch,
|
||||
batch: Any,
|
||||
notice_items: list[dict[str, Any]],
|
||||
) -> None:
|
||||
"""
|
||||
校验幂等键命中时,本次文件集合与已有批次一致。
|
||||
"""shipping_batches 已删除;幂等批次内容校验不再适用。"""
|
||||
del batch, notice_items
|
||||
|
||||
Raises:
|
||||
ConflictError: 文件集合不一致(SHIPPING.BATCH_IDEMPOTENCY_CONFLICT)。
|
||||
|
||||
def find_batch_by_create_idempotency(user_id: int, create_idempotency_key: str) -> None:
|
||||
"""
|
||||
stored_fp = batch_stored_content_fingerprint(batch)
|
||||
request_fp = compute_notice_items_content_fingerprint(notice_items)
|
||||
if not stored_fp or not request_fp:
|
||||
return
|
||||
if stored_fp == request_fp:
|
||||
return
|
||||
raise ConflictError(
|
||||
"建单幂等键对应的文件集合与本次上传不一致,请更换幂等键后重试",
|
||||
code="SHIPPING.BATCH_IDEMPOTENCY_CONFLICT",
|
||||
details={
|
||||
"batch_no": batch.batch_no,
|
||||
"stored_content_fingerprint": stored_fp,
|
||||
"request_content_fingerprint": request_fp,
|
||||
},
|
||||
)
|
||||
按用户与建单幂等键查找已有批次。
|
||||
|
||||
Returns:
|
||||
固定 None(shipping_batches 已删除)。
|
||||
"""
|
||||
del user_id, create_idempotency_key
|
||||
return None
|
||||
|
||||
|
||||
def build_existing_batch_tool_response(batch: Any, *, user_id: int) -> dict[str, Any]:
|
||||
"""shipping_batches 已删除;禁止构建批次重放响应。"""
|
||||
del batch, user_id
|
||||
raise_shipping_batches_removed()
|
||||
|
||||
|
||||
def _advisory_lock_key(*parts: str) -> int:
|
||||
@@ -179,72 +157,32 @@ def acquire_notice_create_locks(user_id: int, content_hashes: Iterable[str]) ->
|
||||
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": lock_key})
|
||||
|
||||
|
||||
def find_batch_by_create_idempotency(user_id: int, create_idempotency_key: str) -> ShippingBatch | None:
|
||||
"""
|
||||
按用户与建单幂等键查找已有批次。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户 ID。
|
||||
create_idempotency_key: 已标准化的建单幂等键。
|
||||
|
||||
Returns:
|
||||
匹配的 ShippingBatch 或 None。
|
||||
"""
|
||||
key = str(create_idempotency_key or "").strip()
|
||||
if not key:
|
||||
return None
|
||||
return (
|
||||
ShippingBatch.query.filter_by(user_id=user_id, create_idempotency_key=key).first()
|
||||
)
|
||||
|
||||
|
||||
def build_existing_batch_tool_response(batch: ShippingBatch, *, user_id: int) -> dict[str, Any]:
|
||||
"""
|
||||
将已有批次序列化为 create_batch_tasks 兼容的 Tool 响应结构。
|
||||
|
||||
核心逻辑:不创建新任务、不启动编排器;供幂等重放与唯一约束竞争回查共用。
|
||||
"""
|
||||
tasks = list_sorted_batch_tasks(batch)
|
||||
focus_task = get_focus_task_for_batch(batch.batch_no, user_id)
|
||||
created_tasks = [
|
||||
{
|
||||
"task_id": task.task_no,
|
||||
"batch_index": task.batch_index,
|
||||
"parse_status": "deferred",
|
||||
}
|
||||
for task in tasks
|
||||
]
|
||||
data: dict[str, Any] = {
|
||||
"batch": serialize_batch_for_tool(batch),
|
||||
"tasks": created_tasks,
|
||||
"orchestrator_started": False,
|
||||
}
|
||||
if focus_task:
|
||||
data["focus_task"] = serialize_task_summary(focus_task)
|
||||
return {
|
||||
"status": "ok",
|
||||
"batch_no": batch.batch_no,
|
||||
"message": f"已恢复此前创建的批次 {batch.batch_no}",
|
||||
"data": data,
|
||||
"idempotent_replay": True,
|
||||
}
|
||||
|
||||
|
||||
def assert_no_exact_duplicate_notices(
|
||||
user_id: int,
|
||||
notice_items: list[dict[str, Any]],
|
||||
*,
|
||||
exclude_batch_id: int | None = None,
|
||||
exclude_task_ids: Iterable[int] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
校验跨请求是否存在相同文件内容且仍在进行中的任务。
|
||||
|
||||
核心逻辑:须在 acquire_notice_create_locks 之后调用,避免不同幂等键并发重复建单。
|
||||
合法的 duplicate_resolution_type=revision|force_create 跳过哈希阻断(业务 Gate 已授权)。
|
||||
exclude_task_ids 用于同一复核 Case 合法后续履约波次:豁免本 Case 已建非终态 Task,
|
||||
不得用于取消跨 Case / 跨入口的精确重复检查。
|
||||
|
||||
Args:
|
||||
user_id: 建单用户。
|
||||
notice_items: 含 source_content_hash / duplicate_resolution_type 的通知项。
|
||||
exclude_batch_id: 可选;忽略同批次内任务。
|
||||
exclude_task_ids: 可选;忽略这些已存在 Task(同 Case 既有波次)。
|
||||
|
||||
Raises:
|
||||
ConflictError: SHIPPING.NOTICE_EXACT_DUPLICATE,details 含已有 task_no。
|
||||
"""
|
||||
skipped_ids = {int(item) for item in (exclude_task_ids or []) if item is not None}
|
||||
hashes: list[tuple[str, str]] = []
|
||||
for item in notice_items:
|
||||
if not isinstance(item, dict):
|
||||
@@ -262,16 +200,14 @@ def assert_no_exact_duplicate_notices(
|
||||
return
|
||||
|
||||
for content_hash, _filename in hashes:
|
||||
query = ShippingTask.query.filter(
|
||||
ShippingTask.user_id == user_id,
|
||||
ShippingTask.source_content_hash == content_hash,
|
||||
ShippingTask.process_status.notin_(list(_TERMINAL_TASK_STATUSES)),
|
||||
query = ShippingNotice.query.filter(
|
||||
ShippingNotice.user_id == user_id,
|
||||
ShippingNotice.source_content_hash == content_hash,
|
||||
ShippingNotice.process_status.notin_(list(_TERMINAL_TASK_STATUSES)),
|
||||
)
|
||||
if exclude_batch_id is not None:
|
||||
query = query.filter(
|
||||
(ShippingTask.batch_id.is_(None)) | (ShippingTask.batch_id != exclude_batch_id)
|
||||
)
|
||||
existing = query.order_by(ShippingTask.id.desc()).first()
|
||||
if skipped_ids:
|
||||
query = query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
|
||||
existing = query.order_by(ShippingNotice.id.desc()).first()
|
||||
if existing:
|
||||
raise ConflictError(
|
||||
f"该文件已存在于进行中的任务 {existing.task_no}",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -48,7 +48,7 @@ def create_shipping_batch_from_notice_items(
|
||||
conversation_id: 可选 Agent 会话 ID。
|
||||
notice_items: notice_upload 产出的 notice item 列表。
|
||||
file_summary: 可选文件预检摘要,写入响应供前端展示。
|
||||
create_idempotency_key: 建单幂等键(与 ShippingTask.idempotency_key 货代上传幂等分离)。
|
||||
create_idempotency_key: 建单幂等键(与 ShippingNotice.idempotency_key 货代上传幂等分离)。
|
||||
defer_commit: True 时下层仅 flush,由调用方最终 commit。
|
||||
start_orchestrator: 是否启动编排器;默认与 defer_commit 相反(延后提交时不启动)。
|
||||
|
||||
@@ -56,77 +56,11 @@ def create_shipping_batch_from_notice_items(
|
||||
与 workspace create-from-notices 一致的结果字典,幂等重放时含 idempotent_replay=true。
|
||||
|
||||
Raises:
|
||||
ValidationError: notice_items 为空。
|
||||
ValidationError: notice_items 为空,或 shipping_batches 已删除(co8)。
|
||||
"""
|
||||
normalized_key = normalize_create_idempotency_key(create_idempotency_key)
|
||||
if not normalized_key:
|
||||
warn_missing_create_idempotency_key(source="create_shipping_batch_from_notice_items")
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
notice_items = dedupe_notice_items_by_content_hash(notice_items)
|
||||
if not notice_items:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError(
|
||||
"未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试",
|
||||
details={"file_summary": file_summary or {}},
|
||||
)
|
||||
|
||||
if normalized_key:
|
||||
existing_batch = find_batch_by_create_idempotency(user_id, normalized_key)
|
||||
if existing_batch:
|
||||
assert_idempotent_batch_content_matches(existing_batch, notice_items)
|
||||
created = build_existing_batch_tool_response(existing_batch, user_id=user_id)
|
||||
if file_summary:
|
||||
created["file_summary"] = file_summary
|
||||
return created
|
||||
|
||||
payload = {
|
||||
"user_id": user_id,
|
||||
"conversation_id": conversation_id or None,
|
||||
"file_count": len(notice_items),
|
||||
"notice_items": notice_items,
|
||||
"defer_parse": True,
|
||||
"create_idempotency_key": normalized_key,
|
||||
"defer_commit": bool(defer_commit),
|
||||
}
|
||||
try:
|
||||
created = shipping_tools.create_batch_tasks(payload)
|
||||
except IntegrityError as exc:
|
||||
replay = handle_batch_create_integrity_error(
|
||||
user_id=user_id,
|
||||
create_idempotency_key=normalized_key,
|
||||
exc=exc,
|
||||
)
|
||||
if replay is None:
|
||||
raise
|
||||
created = replay
|
||||
|
||||
if not isinstance(created, dict):
|
||||
return {"status": "failed", "message": "create batch failed"}
|
||||
|
||||
idempotent_replay = bool(created.get("idempotent_replay"))
|
||||
data = created.get("data") if isinstance(created.get("data"), dict) else {}
|
||||
batch_data = data.get("batch") if isinstance(data.get("batch"), dict) else {}
|
||||
batch_no = str(created.get("batch_no") or batch_data.get("batch_no") or "").strip()
|
||||
should_start = start_orchestrator if start_orchestrator is not None else (not defer_commit)
|
||||
orchestrator_started = False
|
||||
if batch_no and not idempotent_replay and should_start:
|
||||
from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator
|
||||
|
||||
orchestrator_started = start_batch_orchestrator(batch_no)
|
||||
if batch_no and isinstance(data, dict):
|
||||
focus_task = get_focus_task_for_batch(batch_no, user_id)
|
||||
if focus_task:
|
||||
data["focus_task"] = serialize_task_summary(focus_task)
|
||||
data["orchestrator_started"] = orchestrator_started
|
||||
base_message = str(created.get("message") or "").strip()
|
||||
if orchestrator_started:
|
||||
created["message"] = f"{base_message},后台已开始逐票处理。" if base_message else "后台已开始逐票处理。"
|
||||
if idempotent_replay:
|
||||
created["idempotent_replay"] = True
|
||||
if file_summary:
|
||||
created["file_summary"] = file_summary
|
||||
return created
|
||||
raise_shipping_batches_removed()
|
||||
|
||||
|
||||
def format_batch_created_assistant_message(
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/batch_legacy_removed.py
|
||||
|
||||
用途:shipping_batches 表物理删除(co8e9f0a1b2c)后的统一阻断与文案常量。
|
||||
依赖:app.core.errors.AppError。
|
||||
逻辑:create_batch / batch_from_* 等写路径在入口调用 raise_shipping_batches_removed(HTTP 410);
|
||||
读路径 list API 返回空集,按 batch_no 查询返回 None。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.core.errors import AppError
|
||||
|
||||
SHIPPING_BATCHES_REMOVED_MESSAGE = (
|
||||
"shipping_batches removed (migration co8e9f0a1b2c)"
|
||||
)
|
||||
|
||||
|
||||
def raise_shipping_batches_removed(*, action: str | None = None) -> None:
|
||||
"""
|
||||
阻断仍依赖 shipping_batches 表的写路径。
|
||||
|
||||
核心逻辑:ORM 已移除 ShippingBatch;调用方须在入口尽早抛出,避免 SQLAlchemy 访问已 DROP 表。
|
||||
|
||||
Args:
|
||||
action: 可选调用方动作名,写入 error.details 便于排查。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410,code=SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
details = {'migration': 'co8e9f0a1b2c', 'replacement': 'order-extraction-submissions'}
|
||||
if action:
|
||||
details['action'] = str(action)
|
||||
raise AppError(
|
||||
code='SHIPPING.BATCHES_REMOVED',
|
||||
message=SHIPPING_BATCHES_REMOVED_MESSAGE,
|
||||
http_status=410,
|
||||
details=details,
|
||||
retryable=False,
|
||||
)
|
||||
@@ -108,18 +108,8 @@ def _is_retryable_task(task: Any) -> bool:
|
||||
|
||||
|
||||
def _refresh_batch_focus(task_no: str) -> None:
|
||||
task = get_task_by_ref(task_no)
|
||||
if not task or not task.batch:
|
||||
return
|
||||
switch_batch_focus(
|
||||
task.batch,
|
||||
task,
|
||||
source="backend_orchestrator",
|
||||
event_type="focus_auto_switched",
|
||||
emit_when_unchanged=False,
|
||||
)
|
||||
recompute_batch_summary(task.batch)
|
||||
db.session.commit()
|
||||
"""shipping_batches 已删除;批次焦点刷新无操作。"""
|
||||
del task_no
|
||||
|
||||
|
||||
def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
@@ -226,8 +216,6 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
|
||||
refreshed = get_task_by_ref(normalized_task_no)
|
||||
if refreshed:
|
||||
if refreshed.batch:
|
||||
recompute_batch_summary(refreshed.batch)
|
||||
log_task_event(
|
||||
refreshed,
|
||||
"backend_orchestrator_task_finished",
|
||||
@@ -248,8 +236,6 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
if task:
|
||||
task.error_message = str(exc)
|
||||
log_task_event(task, "backend_orchestrator_task_failed", {"error": str(exc)[:1000]})
|
||||
if task.batch:
|
||||
recompute_batch_summary(task.batch)
|
||||
db.session.commit()
|
||||
return {"status": "failed", "message": str(exc)[:500] or "background task failed"}
|
||||
finally:
|
||||
@@ -310,8 +296,6 @@ def _background_batch_runner(app: Any, batch_no: str) -> None:
|
||||
"backend_orchestrator_task_failed",
|
||||
{"error": str(exc)[:1000], "source": "batch_dispatcher"},
|
||||
)
|
||||
if task.batch:
|
||||
recompute_batch_summary(task.batch)
|
||||
db.session.commit()
|
||||
|
||||
batch = get_batch_by_no(normalized_batch_no)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/business_case_service.py
|
||||
|
||||
用途:为新建货代任务创建或继承业务单聚合。
|
||||
依赖:db、ShippingCase、ShippingTask、uuid/datetime。
|
||||
依赖:db、ShippingCase、ShippingNotice、uuid/datetime。
|
||||
逻辑:普通任务和强制新建任务创建新业务单;修订任务继承父任务业务单。
|
||||
"""
|
||||
|
||||
@@ -13,7 +13,7 @@ from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingCase, ShippingTask
|
||||
from app.models import ShippingCase, ShippingNotice
|
||||
|
||||
|
||||
def generate_shipping_case_no() -> str:
|
||||
@@ -71,7 +71,7 @@ def resolve_shipping_case_for_new_task(
|
||||
'修订任务缺少父任务',
|
||||
code='SHIPPING_NOTICE.REVISION_TARGET_INVALID',
|
||||
)
|
||||
parent = db.session.get(ShippingTask, int(supersedes_task_id))
|
||||
parent = db.session.get(ShippingNotice, int(supersedes_task_id))
|
||||
if parent is None:
|
||||
raise ConflictError(
|
||||
'修订目标任务不存在',
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/candidate_evidence_service.py
|
||||
|
||||
用途:将 Candidate 主/辅/冲突证据写入 shipping_order_candidate_evidences(蓝图 §六)。
|
||||
依赖:ShippingOrderCandidateEvidence、ShippingOrderCandidate、ShippingOrderDocument、db。
|
||||
逻辑:由 document_candidate_persist / PDF 优先裁决路径调用;替换式写入避免重解析膨胀。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderCandidateEvidence,
|
||||
ShippingOrderDocument,
|
||||
)
|
||||
from app.services.shipping_notice.pdf_priority_adjudication import PDF_PRIORITY_DECISION_RULE_VERSION
|
||||
|
||||
|
||||
def _hash_value(value: Any) -> str | None:
|
||||
"""对值做 sha256;空值返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return None
|
||||
return hashlib.sha256(text.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _kind_for_document(document: ShippingOrderDocument | None) -> str:
|
||||
"""按 Document 类型推断 evidence_kind。"""
|
||||
if document is None:
|
||||
return 'other'
|
||||
dtype = str(document.document_type or '').strip().lower()
|
||||
filename = str(document.filename or '').strip().lower()
|
||||
if dtype in {'pdf', 'attachment_pdf'} or filename.endswith('.pdf'):
|
||||
return 'pdf'
|
||||
if dtype in {'email_body', 'body'}:
|
||||
return 'email_body'
|
||||
if 'xls' in filename or dtype in {'excel', 'spreadsheet'}:
|
||||
return 'excel'
|
||||
if filename.endswith('.doc') or filename.endswith('.docx') or dtype == 'word':
|
||||
return 'word'
|
||||
if any(filename.endswith(ext) for ext in ('.png', '.jpg', '.jpeg', '.tif', '.tiff', '.webp')):
|
||||
return 'image'
|
||||
return 'other'
|
||||
|
||||
|
||||
def _kind_from_source_type(source_type: str | None) -> str:
|
||||
"""将 Observation source_type 映射为 evidence_kind。"""
|
||||
st = str(source_type or '').strip().lower()
|
||||
if st.startswith('pdf_') or st in {'attachment_text', 'attachment_table'}:
|
||||
return 'pdf'
|
||||
if st.startswith('email_body'):
|
||||
return 'email_body'
|
||||
if 'excel' in st or 'xls' in st:
|
||||
return 'excel'
|
||||
if 'word' in st or 'doc' in st:
|
||||
return 'word'
|
||||
if st.startswith('image') or 'ocr' in st:
|
||||
return 'ocr'
|
||||
if 'model' in st or 'llm' in st:
|
||||
return 'model'
|
||||
return 'other'
|
||||
|
||||
|
||||
def replace_candidate_evidences_from_persist(
|
||||
candidate: ShippingOrderCandidate,
|
||||
*,
|
||||
document: ShippingOrderDocument,
|
||||
evidence: dict[str, Any] | None = None,
|
||||
conflicts: list[dict[str, Any]] | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
按 Candidate 落库结果替换证据行。
|
||||
|
||||
核心逻辑:删除该 Candidate 旧行;写入主文档 primary;再写入 evidence.items 与 conflicts。
|
||||
|
||||
Args:
|
||||
candidate: 已 flush 的 Candidate。
|
||||
document: 主文档。
|
||||
evidence: 持久化时的 evidence 字典(含 items)。
|
||||
conflicts: 冲突列表。
|
||||
|
||||
Returns:
|
||||
写入行数。
|
||||
"""
|
||||
candidate_id = int(candidate.id)
|
||||
db.session.query(ShippingOrderCandidateEvidence).filter_by(candidate_id=candidate_id).delete(
|
||||
synchronize_session=False
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
rows: list[ShippingOrderCandidateEvidence] = [
|
||||
ShippingOrderCandidateEvidence(
|
||||
candidate_id=candidate_id,
|
||||
document_id=int(document.id),
|
||||
evidence_role='primary_pdf' if _kind_for_document(document) == 'pdf' else 'context',
|
||||
evidence_kind=_kind_for_document(document),
|
||||
is_primary=True,
|
||||
payload_json={
|
||||
'document_type': document.document_type,
|
||||
'filename': document.filename,
|
||||
'content_hash': document.content_hash,
|
||||
},
|
||||
decision_rule_version=PDF_PRIORITY_DECISION_RULE_VERSION,
|
||||
created_at=now,
|
||||
)
|
||||
]
|
||||
items = list((evidence or {}).get('items') or []) if isinstance(evidence, dict) else []
|
||||
for item in items:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
kind = _kind_from_source_type(str(item.get('source_type') or item.get('kind') or ''))
|
||||
rows.append(
|
||||
ShippingOrderCandidateEvidence(
|
||||
candidate_id=candidate_id,
|
||||
document_id=int(item['document_id']) if item.get('document_id') else None,
|
||||
evidence_role='auxiliary',
|
||||
evidence_kind=kind,
|
||||
is_primary=False,
|
||||
field_code=str(item.get('field_code') or '').strip() or None,
|
||||
value_hash=_hash_value(item.get('value')),
|
||||
payload_json={
|
||||
'ref': item.get('ref') or item.get('evidence_ref'),
|
||||
'source_type': item.get('source_type'),
|
||||
},
|
||||
decision_rule_version=PDF_PRIORITY_DECISION_RULE_VERSION,
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
for conflict in list(conflicts or []):
|
||||
if not isinstance(conflict, dict):
|
||||
continue
|
||||
rows.append(
|
||||
ShippingOrderCandidateEvidence(
|
||||
candidate_id=candidate_id,
|
||||
document_id=None,
|
||||
evidence_role='conflict',
|
||||
evidence_kind=_kind_from_source_type(str(conflict.get('source_type') or '')),
|
||||
is_primary=False,
|
||||
field_code=str(conflict.get('field_code') or conflict.get('code') or '').strip() or None,
|
||||
value_hash=_hash_value(conflict.get('value') or conflict.get('message')),
|
||||
payload_json={
|
||||
'reason_code': conflict.get('reason_code') or conflict.get('code'),
|
||||
'blocked_auto_create': conflict.get('blocked_auto_create'),
|
||||
},
|
||||
decision_rule_version=PDF_PRIORITY_DECISION_RULE_VERSION,
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
db.session.add_all(rows)
|
||||
db.session.flush()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def append_pdf_priority_field_evidences(
|
||||
*,
|
||||
candidate_id: int,
|
||||
document_id: Optional[int],
|
||||
field_code: str,
|
||||
audit_payload: dict[str, Any],
|
||||
) -> int:
|
||||
"""
|
||||
为 PDF 优先字段裁决追加主/辅/冲突证据行(不整表替换)。
|
||||
|
||||
Args:
|
||||
candidate_id: Candidate 主键。
|
||||
document_id: 主 PDF Document(可空)。
|
||||
field_code: 字段码。
|
||||
audit_payload: build_pdf_priority_audit_payload 结果。
|
||||
|
||||
Returns:
|
||||
追加行数。
|
||||
"""
|
||||
if not candidate_id or not field_code:
|
||||
return 0
|
||||
now = datetime.utcnow()
|
||||
rows: list[ShippingOrderCandidateEvidence] = []
|
||||
if audit_payload.get('pdf_value_hash'):
|
||||
rows.append(
|
||||
ShippingOrderCandidateEvidence(
|
||||
candidate_id=int(candidate_id),
|
||||
document_id=int(document_id) if document_id else None,
|
||||
evidence_role='primary_pdf',
|
||||
evidence_kind='pdf',
|
||||
is_primary=True,
|
||||
field_code=str(field_code),
|
||||
value_hash=str(audit_payload.get('pdf_value_hash')),
|
||||
payload_json={
|
||||
'evidence_ref': audit_payload.get('evidence_ref'),
|
||||
'value_source': audit_payload.get('value_source'),
|
||||
},
|
||||
decision_rule_version=str(
|
||||
audit_payload.get('decision_rule_version') or PDF_PRIORITY_DECISION_RULE_VERSION
|
||||
),
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
if audit_payload.get('auxiliary_value_hash'):
|
||||
rows.append(
|
||||
ShippingOrderCandidateEvidence(
|
||||
candidate_id=int(candidate_id),
|
||||
document_id=None,
|
||||
evidence_role='conflict' if audit_payload.get('conflict') else 'auxiliary',
|
||||
evidence_kind='other',
|
||||
is_primary=False,
|
||||
field_code=str(field_code),
|
||||
value_hash=str(audit_payload.get('auxiliary_value_hash')),
|
||||
payload_json={
|
||||
'evidence_ref': audit_payload.get('auxiliary_evidence_ref'),
|
||||
'blocked_auto_create': audit_payload.get('blocked_auto_create'),
|
||||
},
|
||||
decision_rule_version=str(
|
||||
audit_payload.get('decision_rule_version') or PDF_PRIORITY_DECISION_RULE_VERSION
|
||||
),
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
if not rows:
|
||||
return 0
|
||||
db.session.add_all(rows)
|
||||
db.session.flush()
|
||||
return len(rows)
|
||||
@@ -21,9 +21,10 @@ CANDIDATE_QUALIFICATION_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
})
|
||||
|
||||
# 资格评估器版本;快照持久化时写入 evaluator_version。
|
||||
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION: Final[str] = 'candidate-qualification.v1'
|
||||
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION: Final[str] = 'candidate-qualification.v2-xfa'
|
||||
|
||||
# 统一检查顺序(不可重排):后置项依赖前置放行语义由服务层解释。
|
||||
# XFA 专属门禁对非 XFA Candidate 恒为 True(N/A 放行)。
|
||||
CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = (
|
||||
'auto_create_enabled',
|
||||
'classification_confidence',
|
||||
@@ -34,6 +35,10 @@ CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = (
|
||||
'duplicate_resolved',
|
||||
'customer_confirmed',
|
||||
'idempotency_ok',
|
||||
'xfa_auto_create_policy',
|
||||
'xfa_profile_blind_approved',
|
||||
'xfa_pilot_allowlist',
|
||||
'xfa_evidence_integrity',
|
||||
)
|
||||
|
||||
# 检查项失败 → 稳定用户原因码(对话 / Process Gate / 复核摘要共用)。
|
||||
@@ -47,6 +52,10 @@ CANDIDATE_QUALIFICATION_GATE_REASON_CODES: Final[dict[str, str]] = {
|
||||
'duplicate_resolved': 'duplicate_unresolved',
|
||||
'customer_confirmed': 'customer_confirmation_required',
|
||||
'idempotency_ok': 'task_already_exists',
|
||||
'xfa_auto_create_policy': 'xfa_auto_create_disabled',
|
||||
'xfa_profile_blind_approved': 'xfa_profile_not_blind_approved',
|
||||
'xfa_pilot_allowlist': 'xfa_allowlist_unconfigured',
|
||||
'xfa_evidence_integrity': 'xfa_evidence_incomplete',
|
||||
}
|
||||
|
||||
# 偏向「需人工轻量确认」而非硬阻断的原因码。
|
||||
@@ -57,6 +66,8 @@ CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'duplicate_unresolved',
|
||||
'classification_low_confidence',
|
||||
'field_low_confidence',
|
||||
# PDF 优先已选定当前值,但仍须人工确认冲突后方可自动建单。
|
||||
'pdf_preferred_critical_conflict',
|
||||
})
|
||||
|
||||
# 解析来源(写入 parser_trace,不直接决定资格)。
|
||||
|
||||
@@ -3,12 +3,17 @@ services/shipping_notice/candidate_qualification_service.py
|
||||
|
||||
用途:评估并追加持久化 Candidate 级统一自动建单资格快照。
|
||||
依赖:candidate_qualification_contract、order_schema.service(自动建单开关 / minimum_confidence)、
|
||||
ShippingNoticeCandidate / ShippingOrderCandidateQualification、fulfillment_audit。
|
||||
ShippingOrderCandidate / ShippingOrderCandidateQualification、fulfillment_audit、
|
||||
xfa_contract(XFA 对账可自动建单状态集)。
|
||||
逻辑:由抽取收尾、建单资格与 STP 自动建单调用;三种解析来源统一门禁;
|
||||
每次评估追加不可变历史行并写统一审计 before/after;
|
||||
模板 Profile 批准仅写入 parser_trace;LLM 路径不再天然阻断;
|
||||
分类/LLM 字段置信度缺失 fail-closed;阈值来源写入 confidence_policy;
|
||||
duplicate unchecked 与关键字段证据缺失均 fail-closed。
|
||||
duplicate unchecked 与关键字段证据缺失均 fail-closed;
|
||||
XFA 硬门禁:shadow 阻断、盲测批准、客户/checksum/场景白名单(自动建单总开关走 Schema/CQ);
|
||||
另要求 evidence 计数与四项 cross-check 齐全且仅为 matched/passed/skipped;
|
||||
PDF 优先关键冲突(conflicts_json.reason=pdf_preferred_critical_conflict)
|
||||
映射为 review_required,阻断 can_auto_create。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,10 +24,9 @@ from typing import Any
|
||||
from app.core.errors import ConflictError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingNoticeCandidate,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderCandidateQualification,
|
||||
ShippingOrderCustomerMatch,
|
||||
ShippingOrderExtraction,
|
||||
)
|
||||
from app.services.shipping_notice.candidate_qualification_contract import (
|
||||
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION,
|
||||
@@ -31,8 +35,18 @@ from app.services.shipping_notice.candidate_qualification_contract import (
|
||||
CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from app.services.shipping_notice.tool_common import extraction_emergency_stop_enabled
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_CROSS_CHECK_AUTO_CREATE_OK_STATUSES,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
extraction_emergency_stop_enabled,
|
||||
xfa_customer_allowlist,
|
||||
xfa_profile_checksum_allowlist,
|
||||
xfa_scenario_allowlist,
|
||||
xfa_shadow_mode_enabled,
|
||||
)
|
||||
|
||||
_DEFAULT_BUSINESS_SCENARIO = 'shipping_notice_order'
|
||||
|
||||
# 分类置信度默认下限;仅当 Schema auto_creation_policy 未配置 minimum_confidence 时回退。
|
||||
# 回退来源会写入评估结果 confidence_policy,供管理端核对,禁止静默偏离界面配置。
|
||||
@@ -41,6 +55,36 @@ _CONFIDENCE_SOURCE_SCHEMA_POLICY = 'schema_auto_creation_policy'
|
||||
_CONFIDENCE_SOURCE_KEY_FIELD_MIN = 'key_field_minimum_confidence'
|
||||
_CONFIDENCE_SOURCE_DEFAULT_FALLBACK = 'default_fallback_0_85'
|
||||
|
||||
# 文档表格坐标不足只影响证据高亮质量,不代表订单字段值存在冲突。
|
||||
# 保留在抽取诊断中供排查,但不得阻断人工建单或自动建单。
|
||||
_NON_BLOCKING_CONFLICT_REASONS = frozenset({'layout_table_needs_review'})
|
||||
|
||||
|
||||
def blocking_candidate_conflicts(candidate: Any) -> list[Any]:
|
||||
"""
|
||||
返回真正阻断建单的 Candidate 冲突。
|
||||
|
||||
核心逻辑:过滤仅描述文档版面/坐标质量的诊断项;字段值冲突、跨来源冲突
|
||||
与其他未知阻断项继续 fail-closed。
|
||||
|
||||
Args:
|
||||
candidate: ShippingOrderCandidate 或兼容替身。
|
||||
|
||||
Returns:
|
||||
仍需阻断建单的冲突列表。
|
||||
"""
|
||||
conflicts = getattr(candidate, 'conflicts_json', None)
|
||||
if not isinstance(conflicts, list):
|
||||
return [] if not conflicts else [conflicts]
|
||||
return [
|
||||
item for item in conflicts
|
||||
if not (
|
||||
isinstance(item, dict)
|
||||
and str(item.get('reason') or item.get('code') or '').strip()
|
||||
in _NON_BLOCKING_CONFLICT_REASONS
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def resolve_candidate_customer_resolved(
|
||||
*,
|
||||
@@ -151,7 +195,8 @@ def resolve_review_case_customer_resolved(
|
||||
"""
|
||||
判定复核 Case 关联客户是否已确认(建单前 fail-closed)。
|
||||
|
||||
核心逻辑:Candidate/Extraction 确认优先;否则查同 Run 已确认 Bill-to。
|
||||
核心逻辑:只读取当前 Case 关联 Candidate/Extraction 的 Bill-to 确认结果。
|
||||
同一 Run 可包含多份 PDF;不得把其他 PDF 的已确认客户串入当前 Case。
|
||||
|
||||
Args:
|
||||
case: ShippingOrderReviewCase。
|
||||
@@ -160,26 +205,7 @@ def resolve_review_case_customer_resolved(
|
||||
Returns:
|
||||
True 表示客户已确认。
|
||||
"""
|
||||
if resolve_candidate_customer_resolved(candidate=candidate):
|
||||
return True
|
||||
run_id = getattr(case, 'run_id', None)
|
||||
if run_id is None:
|
||||
return False
|
||||
row = (
|
||||
ShippingOrderCustomerMatch.query
|
||||
.join(
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderExtraction.id == ShippingOrderCustomerMatch.extraction_id,
|
||||
)
|
||||
.filter(
|
||||
ShippingOrderExtraction.run_id == int(run_id),
|
||||
ShippingOrderCustomerMatch.role == 'bill_to',
|
||||
ShippingOrderCustomerMatch.status == 'confirmed',
|
||||
ShippingOrderCustomerMatch.customer_id.isnot(None),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
return row is not None
|
||||
return resolve_candidate_customer_resolved(candidate=candidate)
|
||||
|
||||
|
||||
def evaluate_candidate_qualification(
|
||||
@@ -198,7 +224,7 @@ def evaluate_candidate_qualification(
|
||||
汇总 blocking_reason_codes 后映射 eligible / review_required / blocked / rejected。
|
||||
|
||||
Args:
|
||||
candidate: ShippingNoticeCandidate 或兼容 SimpleNamespace。
|
||||
candidate: ShippingOrderCandidate 或兼容 SimpleNamespace。
|
||||
run: 可选 Run(读取紧急停止 / auto_freeze_policy)。
|
||||
unit: 可选 Unit(读取路由摘要,仅 parser_trace)。
|
||||
fields_complete: 调用方已汇总的必填完整标志;缺省时读 missing_fields_json。
|
||||
@@ -244,6 +270,17 @@ def evaluate_candidate_qualification(
|
||||
customer_ok, customer_reason = _customer_ok(candidate, customer_resolved=customer_resolved)
|
||||
idempotency_ok = _idempotency_ok(candidate)
|
||||
|
||||
# [STEP 2b] XFA 专属硬门禁(非 XFA 恒 True)+ evidence/cross-check 完整性。
|
||||
xfa_eval = _evaluate_xfa_auto_create_gates(
|
||||
candidate=candidate,
|
||||
run=run,
|
||||
unit=unit,
|
||||
parser_trace=parser_trace,
|
||||
customer_resolved=customer_resolved,
|
||||
emergency_stop=emergency_stop,
|
||||
)
|
||||
parser_trace = {**parser_trace, **xfa_eval['parser_trace_extra']}
|
||||
|
||||
gates = {
|
||||
'auto_create_enabled': auto_create_enabled,
|
||||
'classification_confidence': classification_ok,
|
||||
@@ -254,19 +291,31 @@ def evaluate_candidate_qualification(
|
||||
'duplicate_resolved': duplicate_ok,
|
||||
'customer_confirmed': customer_ok,
|
||||
'idempotency_ok': idempotency_ok,
|
||||
'xfa_auto_create_policy': bool(xfa_eval['gates']['xfa_auto_create_policy']),
|
||||
'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']),
|
||||
}
|
||||
failed = [key for key in CANDIDATE_QUALIFICATION_GATE_KEYS if not gates.get(key)]
|
||||
|
||||
# [STEP 3] 映射原因码;客户细因覆盖默认码。
|
||||
# [STEP 3] 映射原因码;客户细因 / XFA 细因 / PDF 关键冲突细因覆盖默认码。
|
||||
blocking_reason_codes: list[str] = []
|
||||
for key in failed:
|
||||
if key == 'customer_confirmed' and customer_reason:
|
||||
blocking_reason_codes.append(customer_reason)
|
||||
continue
|
||||
if key in xfa_eval['reason_by_gate'] and xfa_eval['reason_by_gate'].get(key):
|
||||
blocking_reason_codes.append(str(xfa_eval['reason_by_gate'][key]))
|
||||
continue
|
||||
if key == 'field_conflicts_resolved':
|
||||
pdf_reason = _pdf_priority_conflict_reason(candidate)
|
||||
if pdf_reason:
|
||||
blocking_reason_codes.append(pdf_reason)
|
||||
continue
|
||||
blocking_reason_codes.append(
|
||||
CANDIDATE_QUALIFICATION_GATE_REASON_CODES.get(key, 'order_freeze_not_ready')
|
||||
)
|
||||
if emergency_stop and 'auto_create_disabled' not in blocking_reason_codes:
|
||||
if emergency_stop and 'extraction_emergency_stop' not in blocking_reason_codes:
|
||||
blocking_reason_codes.insert(0, 'extraction_emergency_stop')
|
||||
|
||||
# [STEP 4] 状态归类。
|
||||
@@ -276,6 +325,8 @@ def evaluate_candidate_qualification(
|
||||
blocking_reason_codes=blocking_reason_codes,
|
||||
)
|
||||
evidence_snapshot = _evidence_snapshot(candidate)
|
||||
if xfa_eval.get('evidence_extra'):
|
||||
evidence_snapshot = {**evidence_snapshot, **xfa_eval['evidence_extra']}
|
||||
score = _qualification_score(gates)
|
||||
confidence_policy = {
|
||||
'minimum_confidence': float(min_confidence),
|
||||
@@ -287,6 +338,7 @@ def evaluate_candidate_qualification(
|
||||
'confidence_policy': confidence_policy,
|
||||
}
|
||||
|
||||
can_auto_create = status == 'eligible'
|
||||
return {
|
||||
'status': status,
|
||||
'gates': gates,
|
||||
@@ -295,7 +347,8 @@ def evaluate_candidate_qualification(
|
||||
'parser_trace': parser_trace,
|
||||
'evidence_snapshot': evidence_snapshot,
|
||||
'qualification_score': score,
|
||||
'can_auto_create': status == 'eligible',
|
||||
'can_auto_create': can_auto_create,
|
||||
'shadow_would_auto_create': bool(xfa_eval.get('shadow_would_auto_create')),
|
||||
'evaluator_version': CANDIDATE_QUALIFICATION_EVALUATOR_VERSION,
|
||||
'confidence_policy': confidence_policy,
|
||||
}
|
||||
@@ -326,7 +379,7 @@ def build_qualification_snapshot(evaluation: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
def recalculate_candidate_qualification(
|
||||
*,
|
||||
candidate: ShippingNoticeCandidate,
|
||||
candidate: ShippingOrderCandidate,
|
||||
run: Any | None = None,
|
||||
unit: Any | None = None,
|
||||
fields_complete: bool | None = None,
|
||||
@@ -450,11 +503,269 @@ def recalculate_candidate_qualification(
|
||||
return evaluation
|
||||
|
||||
|
||||
def _build_parser_trace(*, candidate: Any, run: Any | None, unit: Any | None) -> dict[str, Any]:
|
||||
"""组装解析链路痕迹;模板批准仅作治理信息。"""
|
||||
def _route_decision(*, unit: Any | None, run: Any | None) -> dict[str, Any]:
|
||||
"""合并 Unit 路由决策与 Run 冻结策略中的 Profile 身份。"""
|
||||
route: dict[str, Any] = {}
|
||||
if unit is not None and isinstance(getattr(unit, 'route_decision_json', None), dict):
|
||||
route = dict(unit.route_decision_json or {})
|
||||
if run is not None:
|
||||
policy = getattr(run, 'auto_freeze_policy_json', None)
|
||||
if isinstance(policy, dict):
|
||||
if policy.get('selected_profile_id') and not route.get('selected_profile_id'):
|
||||
route = {
|
||||
**route,
|
||||
'selected_profile_id': policy.get('selected_profile_id'),
|
||||
'selected_profile_code': policy.get('selected_profile_code'),
|
||||
'selected_profile_checksum': policy.get('selected_profile_checksum'),
|
||||
}
|
||||
return route
|
||||
|
||||
|
||||
def _is_xfa_candidate(*, candidate: Any, route: dict[str, Any]) -> bool:
|
||||
"""
|
||||
判定 Candidate 是否来自 XFA 数据路径。
|
||||
|
||||
核心逻辑:优先 route.capability_kind / template_mode / xfa_* 摘要;
|
||||
其次 structured_result 上的 `_hxops_xfa_*` 痕迹。
|
||||
"""
|
||||
if str(route.get('capability_kind') or '').strip() == 'xfa_dataset':
|
||||
return True
|
||||
if str(route.get('template_mode') or '').strip() == 'xfa_dataset':
|
||||
return True
|
||||
if route.get('xfa_evidence_summary') or route.get('xfa_cross_checks') or route.get('xfa_structure'):
|
||||
return True
|
||||
extraction = str(getattr(candidate, 'extraction_source', '') or '').strip().lower()
|
||||
if extraction in {'xfa', 'xfa_dataset'}:
|
||||
return True
|
||||
structured = getattr(candidate, 'structured_result_json', None)
|
||||
if isinstance(structured, dict):
|
||||
if structured.get('_hxops_xfa_evidence') or structured.get('_hxops_xfa_structure'):
|
||||
return True
|
||||
if str(structured.get('template_mode') or '').strip() == 'xfa_dataset':
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _resolve_xfa_candidate_customer_id(candidate: Any) -> int | None:
|
||||
"""
|
||||
解析 XFA Candidate 的确认客户 ID(供白名单硬门禁)。
|
||||
|
||||
核心逻辑:优先 structured_result_json.customer.customer_id;再回退 bill_to 匹配表。
|
||||
"""
|
||||
structured = getattr(candidate, 'structured_result_json', None)
|
||||
if isinstance(structured, dict):
|
||||
customer = structured.get('customer')
|
||||
if isinstance(customer, dict) and customer.get('customer_id') is not None:
|
||||
try:
|
||||
return int(customer.get('customer_id'))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
try:
|
||||
return resolve_confirmed_bill_to_customer_id(candidate=candidate)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _evaluate_xfa_auto_create_gates(
|
||||
*,
|
||||
candidate: Any,
|
||||
run: Any | None,
|
||||
unit: Any | None,
|
||||
parser_trace: dict[str, Any],
|
||||
customer_resolved: bool | None,
|
||||
emergency_stop: bool,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
评估 XFA 试点硬门禁(并入统一 Candidate Qualification)。
|
||||
|
||||
核心逻辑(非 XFA 四门禁恒 True):
|
||||
1. 自动建单总开关由 Schema `auto_creation_policy` / CQ `auto_create_enabled` 统一裁决,
|
||||
本函数不再读取独立 XFA AUTO_CREATE 环境变量;
|
||||
2. shadow 开启时阻断真实建单但可写 would_auto_create;
|
||||
3. 当前 Profile checksum 须具备盲测批准(route/parser_trace.auto_create_approved);
|
||||
4. 客户 / Profile checksum / 场景白名单均须命中;空客户或空 checksum 名单 fail-closed;
|
||||
5. evidence 计数与四项 cross-check 状态齐全且仅为 matched/passed/skipped。
|
||||
|
||||
Returns:
|
||||
gates / reason_by_gate / parser_trace_extra / shadow_would_auto_create / evidence_extra。
|
||||
"""
|
||||
route = _route_decision(unit=unit, run=run)
|
||||
is_xfa = _is_xfa_candidate(candidate=candidate, route=route)
|
||||
na_gates = {
|
||||
'xfa_auto_create_policy': True,
|
||||
'xfa_profile_blind_approved': True,
|
||||
'xfa_pilot_allowlist': True,
|
||||
'xfa_evidence_integrity': True,
|
||||
}
|
||||
if not is_xfa:
|
||||
return {
|
||||
'gates': na_gates,
|
||||
'reason_by_gate': {},
|
||||
'parser_trace_extra': {
|
||||
'xfa_candidate': False,
|
||||
},
|
||||
'shadow_would_auto_create': False,
|
||||
'evidence_extra': {},
|
||||
}
|
||||
|
||||
# [STEP 1] 读取 shadow 与白名单;自动建单总开关不在此读取。
|
||||
shadow = False
|
||||
allow_customers: list[int] = []
|
||||
allow_checksums: list[str] = []
|
||||
allow_scenarios: list[str] = []
|
||||
try:
|
||||
shadow = bool(xfa_shadow_mode_enabled())
|
||||
allow_customers = list(xfa_customer_allowlist())
|
||||
allow_checksums = list(xfa_profile_checksum_allowlist())
|
||||
allow_scenarios = list(xfa_scenario_allowlist())
|
||||
except RuntimeError:
|
||||
shadow = False
|
||||
allow_customers, allow_checksums, allow_scenarios = [], [], ['shipping_notice_order']
|
||||
|
||||
profile_approved = bool(
|
||||
route.get('auto_create_approved')
|
||||
or parser_trace.get('profile_auto_create_approved')
|
||||
)
|
||||
|
||||
# [STEP 2] shadow 阻断真实建单;总开关由统一 auto_create_enabled 门禁负责。
|
||||
policy_ok = True
|
||||
policy_reason = None
|
||||
if shadow:
|
||||
policy_ok = False
|
||||
policy_reason = 'xfa_shadow_mode'
|
||||
|
||||
# [STEP 3] 盲测批准。
|
||||
blind_ok = profile_approved
|
||||
blind_reason = None if blind_ok else 'xfa_profile_not_blind_approved'
|
||||
|
||||
# [STEP 4] 三类白名单(空客户/checksum fail-closed)。
|
||||
allowlist_ok = True
|
||||
allowlist_reason = None
|
||||
customer_id = _resolve_xfa_candidate_customer_id(candidate)
|
||||
checksum = str(route.get('selected_profile_checksum') or parser_trace.get('profile_checksum') or '').strip()
|
||||
scenario = str(
|
||||
route.get('business_scenario')
|
||||
or parser_trace.get('business_scenario')
|
||||
or _DEFAULT_BUSINESS_SCENARIO
|
||||
).strip().lower()
|
||||
if not allow_customers or not allow_checksums:
|
||||
allowlist_ok = False
|
||||
allowlist_reason = 'xfa_allowlist_unconfigured'
|
||||
elif customer_id is None or int(customer_id) not in allow_customers:
|
||||
allowlist_ok = False
|
||||
allowlist_reason = 'xfa_customer_not_allowlisted'
|
||||
elif not checksum or checksum not in allow_checksums:
|
||||
allowlist_ok = False
|
||||
allowlist_reason = 'xfa_profile_checksum_not_allowlisted'
|
||||
elif scenario not in {str(item).strip().lower() for item in allow_scenarios}:
|
||||
allowlist_ok = False
|
||||
allowlist_reason = 'xfa_scenario_not_allowlisted'
|
||||
|
||||
# [STEP 5] evidence + cross-check 完整性。
|
||||
evidence_summary = route.get('xfa_evidence_summary')
|
||||
cross_checks = route.get('xfa_cross_checks')
|
||||
structured = getattr(candidate, 'structured_result_json', None)
|
||||
if not isinstance(evidence_summary, dict) and isinstance(structured, dict):
|
||||
evidence_summary = structured.get('_hxops_xfa_evidence')
|
||||
if not isinstance(cross_checks, dict) and isinstance(structured, dict):
|
||||
cross_checks = (
|
||||
structured.get('_hxops_xfa_cross_checks')
|
||||
if isinstance(structured.get('_hxops_xfa_cross_checks'), dict)
|
||||
else None
|
||||
)
|
||||
if not isinstance(evidence_summary, dict):
|
||||
evidence_summary = {}
|
||||
if not isinstance(cross_checks, dict):
|
||||
cross_checks = {}
|
||||
|
||||
evidence_ok = True
|
||||
evidence_reason = None
|
||||
header_count = int(evidence_summary.get('header_field_count') or 0)
|
||||
line_count = int(evidence_summary.get('line_row_count') or 0)
|
||||
required_cross_check_keys = (
|
||||
'mirror_status',
|
||||
'acroform_status',
|
||||
'line_amount_status',
|
||||
'total_amount_status',
|
||||
)
|
||||
if header_count <= 0 or line_count <= 0:
|
||||
evidence_ok = False
|
||||
evidence_reason = 'xfa_evidence_incomplete'
|
||||
else:
|
||||
missing_keys = [
|
||||
key for key in required_cross_check_keys
|
||||
if not str(cross_checks.get(key) or '').strip()
|
||||
]
|
||||
if missing_keys:
|
||||
evidence_ok = False
|
||||
evidence_reason = 'xfa_evidence_incomplete'
|
||||
else:
|
||||
statuses = {
|
||||
key: str(cross_checks.get(key) or '').strip().lower()
|
||||
for key in required_cross_check_keys
|
||||
}
|
||||
incomplete = {
|
||||
status for status in statuses.values()
|
||||
if status not in XFA_CROSS_CHECK_AUTO_CREATE_OK_STATUSES
|
||||
}
|
||||
if incomplete:
|
||||
evidence_ok = False
|
||||
evidence_reason = 'xfa_cross_check_failed'
|
||||
|
||||
gates = {
|
||||
'xfa_auto_create_policy': policy_ok,
|
||||
'xfa_profile_blind_approved': blind_ok,
|
||||
'xfa_pilot_allowlist': allowlist_ok,
|
||||
'xfa_evidence_integrity': evidence_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,
|
||||
}
|
||||
|
||||
# shadow:在其余试点门禁(除真实建单开关外)满足时记录 would_auto_create。
|
||||
shadow_base_ok = (
|
||||
blind_ok and allowlist_ok and evidence_ok and not emergency_stop
|
||||
)
|
||||
shadow_would = bool(shadow and shadow_base_ok)
|
||||
|
||||
_ = customer_resolved # 客户确认由统一 customer_confirmed 门禁负责。
|
||||
return {
|
||||
'gates': gates,
|
||||
'reason_by_gate': {k: v for k, v in reason_by_gate.items() if v},
|
||||
'parser_trace_extra': {
|
||||
'xfa_candidate': True,
|
||||
'xfa_shadow_mode': shadow,
|
||||
'xfa_auto_create_uses_schema_policy': True,
|
||||
'xfa_profile_blind_approved': profile_approved,
|
||||
'xfa_allowlist': {
|
||||
'customer_id': customer_id,
|
||||
'profile_checksum': checksum or None,
|
||||
'business_scenario': scenario,
|
||||
'customer_allowlisted': bool(
|
||||
customer_id is not None and int(customer_id) in allow_customers
|
||||
),
|
||||
'checksum_allowlisted': bool(checksum and checksum in allow_checksums),
|
||||
'scenario_allowlisted': scenario in {
|
||||
str(item).strip().lower() for item in allow_scenarios
|
||||
},
|
||||
},
|
||||
'note': 'xfa_hard_gates_plus_unified_candidate_qualification',
|
||||
},
|
||||
'shadow_would_auto_create': shadow_would,
|
||||
'evidence_extra': {
|
||||
'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()),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _build_parser_trace(*, candidate: Any, run: Any | None, unit: Any | None) -> dict[str, Any]:
|
||||
"""组装解析链路痕迹;坐标模板批准仅作治理信息,XFA 另有硬门禁。"""
|
||||
route = _route_decision(unit=unit, run=run)
|
||||
|
||||
extraction_source = str(getattr(candidate, 'extraction_source', '') or '').strip().lower()
|
||||
route_type = str(route.get('route_type') or '').strip()
|
||||
@@ -465,7 +776,7 @@ def _build_parser_trace(*, candidate: Any, run: Any | None, unit: Any | None) ->
|
||||
route_type = 'llm_assisted'
|
||||
elif extraction_source in {'generic', 'generic_deterministic'}:
|
||||
route_type = 'generic_deterministic'
|
||||
elif extraction_source in {'profile', 'template', 'profile_deterministic'}:
|
||||
elif extraction_source in {'profile', 'template', 'profile_deterministic', 'xfa', 'xfa_dataset'}:
|
||||
route_type = 'profile_deterministic'
|
||||
else:
|
||||
route_type = 'unknown'
|
||||
@@ -476,13 +787,6 @@ def _build_parser_trace(*, candidate: Any, run: Any | None, unit: Any | None) ->
|
||||
policy = getattr(run, 'auto_freeze_policy_json', None)
|
||||
if isinstance(policy, dict):
|
||||
policy_profile_status = policy.get('qualification_status')
|
||||
if policy.get('selected_profile_id') and not route.get('selected_profile_id'):
|
||||
route = {
|
||||
**route,
|
||||
'selected_profile_id': policy.get('selected_profile_id'),
|
||||
'selected_profile_code': policy.get('selected_profile_code'),
|
||||
'selected_profile_checksum': policy.get('selected_profile_checksum'),
|
||||
}
|
||||
|
||||
return {
|
||||
'parser_source': route_type,
|
||||
@@ -492,6 +796,8 @@ def _build_parser_trace(*, candidate: Any, run: Any | None, unit: Any | None) ->
|
||||
'profile_checksum': route.get('selected_profile_checksum'),
|
||||
'profile_auto_create_approved': profile_approved,
|
||||
'profile_qualification_status': policy_profile_status,
|
||||
'capability_kind': route.get('capability_kind'),
|
||||
'template_mode': route.get('template_mode'),
|
||||
'note': 'template_quality_only_not_auto_create_gate',
|
||||
}
|
||||
|
||||
@@ -650,27 +956,9 @@ def _key_fields_confidence_ok(
|
||||
if value < threshold:
|
||||
return False
|
||||
|
||||
# LLM 且未标注关键字段:要求每条置信度声明均可解析且达阈值。
|
||||
if is_llm and key_fields_seen == 0:
|
||||
numeric_only = all(not isinstance(v, dict) for v in raw.values())
|
||||
if numeric_only:
|
||||
for value in raw.values():
|
||||
try:
|
||||
if float(value) < default_threshold:
|
||||
return False
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return True
|
||||
for item in raw.values():
|
||||
if not isinstance(item, dict):
|
||||
return False
|
||||
if item.get('confidence', item.get('value')) is None:
|
||||
return False
|
||||
try:
|
||||
if float(item.get('confidence', item.get('value'))) < default_threshold:
|
||||
return False
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
# 没有任何字段被配置为自动建单关键字段时,字段置信度只做诊断,
|
||||
# 不得把普通字段的低分误作为自动建单阻断。
|
||||
if key_fields_seen == 0:
|
||||
return True
|
||||
|
||||
numeric_only = all(not isinstance(v, dict) for v in raw.values())
|
||||
@@ -733,13 +1021,36 @@ def _evidence_ok(candidate: Any) -> bool:
|
||||
|
||||
|
||||
def _conflicts_ok(candidate: Any) -> bool:
|
||||
"""字段冲突是否已清空。"""
|
||||
"""真正影响订单事实的字段冲突是否已清空;版面质量诊断不参与门禁。"""
|
||||
return len(blocking_candidate_conflicts(candidate)) == 0
|
||||
|
||||
|
||||
def _pdf_priority_conflict_reason(candidate: Any) -> str | None:
|
||||
"""
|
||||
从 Candidate.conflicts_json 提取 PDF 优先冲突细因码。
|
||||
|
||||
核心逻辑:优先返回 pdf_preferred_critical_conflict;其次 pdf_preferred;
|
||||
无匹配则返回 None,由门禁默认 field_conflict 承接。
|
||||
|
||||
Args:
|
||||
candidate: Candidate 或兼容替身。
|
||||
|
||||
Returns:
|
||||
细因码或 None。
|
||||
"""
|
||||
conflicts = getattr(candidate, 'conflicts_json', None)
|
||||
if not conflicts:
|
||||
return True
|
||||
if isinstance(conflicts, list):
|
||||
return len(conflicts) == 0
|
||||
return False
|
||||
if not isinstance(conflicts, list):
|
||||
return None
|
||||
reasons = {
|
||||
str(item.get('reason') or item.get('reason_code') or '').strip()
|
||||
for item in conflicts
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
if 'pdf_preferred_critical_conflict' in reasons:
|
||||
return 'pdf_preferred_critical_conflict'
|
||||
if 'pdf_preferred' in reasons:
|
||||
return 'pdf_preferred'
|
||||
return None
|
||||
|
||||
|
||||
def _duplicate_ok(candidate: Any) -> bool:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/shipping_notice/candidate_service.py
|
||||
|
||||
用途:提供订单候选的用户态查询、选择与重复决策能力;含 STP 严格建单门禁。
|
||||
依赖:ShippingNoticeCandidate/Document/Intake、duplicate_detection、business_fingerprint。
|
||||
依赖:ShippingOrderCandidate/Document/Intake、duplicate_detection、business_fingerprint。
|
||||
逻辑:workspace API 调用本模块;所有写操作锁定 Candidate,并在字段变化后重算双指纹和重复状态;
|
||||
仅严格门禁通过且客户已确认的 Candidate 可物化 Task
|
||||
(缺字段/低置信/缺证据/重复冲突/客户未确认 → 拒绝)。
|
||||
@@ -15,7 +15,7 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import FileAsset, ShippingNoticeCandidate, ShippingNoticeDocument, ShippingNoticeIntake, ShippingTask, User
|
||||
from app.models import FileAsset, ShippingOrderCandidate, ShippingOrderDocument, ShippingOrderIntake, ShippingNotice, User
|
||||
from app.services.shipping_notice.business_fingerprint import build_business_fingerprint, build_content_fingerprint
|
||||
from app.services.shipping_notice.document_candidate_persist import _serialize_candidate_brief
|
||||
from app.services.shipping_notice.duplicate_detection import apply_duplicate_result_to_candidate, detect_duplicates_for_candidate
|
||||
@@ -25,7 +25,7 @@ _ACTIONS = frozenset({'open_existing', 'create_revision', 'force_create'})
|
||||
_STP_DUPLICATE_OK = frozenset({'none', 'unchecked'})
|
||||
|
||||
|
||||
def evaluate_candidate_stp_gate(candidate: ShippingNoticeCandidate) -> tuple[bool, list[str]]:
|
||||
def evaluate_candidate_stp_gate(candidate: ShippingOrderCandidate) -> tuple[bool, list[str]]:
|
||||
"""
|
||||
评估 Candidate 是否通过 STP 严格建单门禁(不抛异常)。
|
||||
|
||||
@@ -43,7 +43,9 @@ def evaluate_candidate_stp_gate(candidate: ShippingNoticeCandidate) -> tuple[boo
|
||||
reasons: list[str] = []
|
||||
if str(candidate.validation_status or '') != 'ready':
|
||||
reasons.append('incomplete_fields')
|
||||
if candidate.conflicts_json:
|
||||
from app.services.shipping_notice.candidate_qualification_service import blocking_candidate_conflicts
|
||||
|
||||
if blocking_candidate_conflicts(candidate):
|
||||
reasons.append('blocking_conflict')
|
||||
missing = list(candidate.missing_fields_json or [])
|
||||
if missing:
|
||||
@@ -64,7 +66,7 @@ def evaluate_candidate_stp_gate(candidate: ShippingNoticeCandidate) -> tuple[boo
|
||||
return not reasons, sorted(set(reasons))
|
||||
|
||||
|
||||
def ensure_candidate_fulfillment_ready(candidate: ShippingNoticeCandidate) -> None:
|
||||
def ensure_candidate_fulfillment_ready(candidate: ShippingOrderCandidate) -> None:
|
||||
"""
|
||||
统一履约门禁:已接受、当前、无阻断;建 Task 前客户必须已确认;
|
||||
automatic 候选额外通过 STP 严格门禁。
|
||||
@@ -83,7 +85,9 @@ def ensure_candidate_fulfillment_ready(candidate: ShippingNoticeCandidate) -> No
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_SUPERSEDED', message='订单候选已被重新识别版本替代')
|
||||
if candidate.consumed_task_id is not None:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费')
|
||||
if str(candidate.validation_status or '') != 'ready' or candidate.conflicts_json:
|
||||
from app.services.shipping_notice.candidate_qualification_service import blocking_candidate_conflicts
|
||||
|
||||
if str(candidate.validation_status or '') != 'ready' or blocking_candidate_conflicts(candidate):
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
|
||||
message='订单候选仍有字段冲突或未完成审核',
|
||||
@@ -104,15 +108,15 @@ def ensure_candidate_fulfillment_ready(candidate: ShippingNoticeCandidate) -> No
|
||||
)
|
||||
|
||||
|
||||
def _candidate_for_user(candidate_no: str, user_id: int, *, lock: bool = False) -> tuple[ShippingNoticeCandidate, ShippingNoticeIntake, ShippingNoticeDocument]:
|
||||
def _candidate_for_user(candidate_no: str, user_id: int, *, lock: bool = False) -> tuple[ShippingOrderCandidate, ShippingOrderIntake, ShippingOrderDocument]:
|
||||
"""按候选编号和用户加载 Candidate、Intake、Document;写路径可加行锁。"""
|
||||
query = (
|
||||
db.session.query(ShippingNoticeCandidate, ShippingNoticeIntake, ShippingNoticeDocument)
|
||||
.join(ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeCandidate.intake_id)
|
||||
.join(ShippingNoticeDocument, ShippingNoticeDocument.id == ShippingNoticeCandidate.primary_document_id)
|
||||
db.session.query(ShippingOrderCandidate, ShippingOrderIntake, ShippingOrderDocument)
|
||||
.join(ShippingOrderIntake, ShippingOrderIntake.id == ShippingOrderCandidate.intake_id)
|
||||
.join(ShippingOrderDocument, ShippingOrderDocument.id == ShippingOrderCandidate.primary_document_id)
|
||||
.filter(
|
||||
ShippingNoticeCandidate.candidate_no == str(candidate_no or '').strip().upper(),
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingOrderCandidate.candidate_no == str(candidate_no or '').strip().upper(),
|
||||
ShippingOrderIntake.user_id == int(user_id),
|
||||
)
|
||||
)
|
||||
if lock:
|
||||
@@ -123,7 +127,7 @@ def _candidate_for_user(candidate_no: str, user_id: int, *, lock: bool = False)
|
||||
return row
|
||||
|
||||
|
||||
def _refresh_candidate(candidate: ShippingNoticeCandidate, intake: ShippingNoticeIntake, document: ShippingNoticeDocument) -> dict[str, Any]:
|
||||
def _refresh_candidate(candidate: ShippingOrderCandidate, intake: ShippingOrderIntake, document: ShippingOrderDocument) -> dict[str, Any]:
|
||||
"""重算 Candidate 双指纹和重复状态,不提交事务。"""
|
||||
structured = candidate.structured_result_json if isinstance(candidate.structured_result_json, dict) else {}
|
||||
summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {}
|
||||
@@ -166,7 +170,7 @@ def update_candidate(*, user_id: int, candidate_no: str, selected: bool) -> dict
|
||||
return _serialize_candidate_brief(candidate)
|
||||
|
||||
|
||||
def _append_candidate_decision_history(candidate: ShippingNoticeCandidate, *, action: str, user_id: int, reason: str | None = None) -> None:
|
||||
def _append_candidate_decision_history(candidate: ShippingOrderCandidate, *, action: str, user_id: int, reason: str | None = None) -> None:
|
||||
"""记录人工采纳或驳回事件,便于审核回放。"""
|
||||
structured = dict(candidate.structured_result_json or {})
|
||||
history = list(structured.get('manual_review_history') or [])
|
||||
@@ -192,7 +196,13 @@ def promote_candidate(*, user_id: int, candidate_no: str) -> dict[str, Any]:
|
||||
if candidate.consumed_task_id is not None or not candidate.is_current_version:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选不可再采纳')
|
||||
_refresh_candidate(candidate, intake, document)
|
||||
if candidate.validation_status != 'ready' or candidate.conflicts_json or candidate.duplicate_status not in {'none', 'unchecked'}:
|
||||
from app.services.shipping_notice.candidate_qualification_service import blocking_candidate_conflicts
|
||||
|
||||
if (
|
||||
candidate.validation_status != 'ready'
|
||||
or blocking_candidate_conflicts(candidate)
|
||||
or candidate.duplicate_status not in {'none', 'unchecked'}
|
||||
):
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED', message='请先完成字段和重复审核')
|
||||
candidate.candidate_status = 'accepted'
|
||||
candidate.acceptance_mode = 'manual'
|
||||
@@ -283,7 +293,7 @@ def resolve_candidate_duplicate(*, user_id: int, candidate_no: str, action: str,
|
||||
)
|
||||
if not target_no or not any(str(item.get('task_no') or '').upper() == target_no for item in matches):
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND', message='重复目标任务不存在或已变化')
|
||||
target = db.session.query(ShippingTask).filter_by(task_no=target_no, user_id=int(user_id)).first()
|
||||
target = db.session.query(ShippingNotice).filter_by(task_no=target_no, user_id=int(user_id)).first()
|
||||
if target is None:
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND', message='重复目标任务不存在')
|
||||
if action_norm == 'force_create':
|
||||
|
||||
@@ -13,6 +13,7 @@ from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.notice_lines import non_atomic_part_number_field, normalize_notice_line
|
||||
from app.services.shipping_notice.notice_line_values import parse_number
|
||||
from app.services.shipping_notice.order_schema.field_rules import compute_effective_reservation_id
|
||||
from app.services.shipping_notice.po_number import normalize_atomic_po_number
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
@@ -40,6 +41,7 @@ def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[st
|
||||
raw_lines = raw.get('lines') if isinstance(raw.get('lines'), list) else []
|
||||
normalized_lines: list[dict[str, Any]] = []
|
||||
invalid_lines: list[dict[str, Any]] = []
|
||||
missing_required: set[str] = set()
|
||||
for index, item in enumerate(raw_lines):
|
||||
raw_line = item if isinstance(item, dict) else None
|
||||
non_atomic_field = non_atomic_part_number_field(raw_line)
|
||||
@@ -52,7 +54,23 @@ def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[st
|
||||
continue
|
||||
normalized = normalize_notice_line(raw_line)
|
||||
if normalized is None:
|
||||
invalid_lines.append({'line_index': index, 'reason': 'missing_part_number_or_positive_qty'})
|
||||
raw_part_number = str((raw_line or {}).get('part_number') or '').strip()
|
||||
raw_qty = parse_number(
|
||||
(raw_line or {}).get('qty')
|
||||
if (raw_line or {}).get('qty') is not None
|
||||
else (raw_line or {}).get('quantity')
|
||||
)
|
||||
line_missing = []
|
||||
if not raw_part_number:
|
||||
line_missing.append('part_number')
|
||||
if raw_qty is None or raw_qty <= 0:
|
||||
line_missing.append('qty')
|
||||
missing_required.update(line_missing)
|
||||
invalid_lines.append({
|
||||
'line_index': index,
|
||||
'reason': 'missing_part_number_or_positive_qty',
|
||||
'fields': line_missing,
|
||||
})
|
||||
continue
|
||||
raw_reservation = str(normalized.get('reservation_id') or '').strip()
|
||||
if raw_reservation and not validated_reservation_id(raw_reservation):
|
||||
@@ -81,9 +99,8 @@ def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[st
|
||||
))
|
||||
})
|
||||
|
||||
missing_required: list[str] = []
|
||||
if not normalized_lines:
|
||||
missing_required.extend(BUILD_REQUIRED_FIELDS)
|
||||
if not normalized_lines and not invalid_lines:
|
||||
missing_required.update(BUILD_REQUIRED_FIELDS)
|
||||
# 有效 Reservation 是逐行匹配键;头级可回填行级缺失。
|
||||
missing_process = [
|
||||
field
|
||||
@@ -103,7 +120,7 @@ def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[st
|
||||
'normalized_summary': normalized_summary,
|
||||
'can_create_task': bool(normalized_lines) and not invalid_lines,
|
||||
'can_auto_progress': bool(normalized_lines) and not invalid_lines and not missing_process,
|
||||
'missing_required_fields': sorted(set(missing_required)),
|
||||
'missing_required_fields': sorted(missing_required),
|
||||
'missing_process_fields': missing_process,
|
||||
'invalid_lines': invalid_lines,
|
||||
'process_issues': [],
|
||||
|
||||
@@ -2,39 +2,36 @@
|
||||
backend/app/services/shipping_notice/chat_action_extended_handlers.py
|
||||
|
||||
用途:货代 Chat Turn 扩展 Action Handler(通知重传/切票/缺口查询)。
|
||||
依赖:shipping_tools、task_workflow、tool_common、shipping_turn_helpers、action_registry。
|
||||
逻辑:turn_runtime 路由至本模块;与 chat_action_handlers 分工,避免单文件过大。
|
||||
依赖:shipping_tools、task_workflow、batch_legacy_removed、shipping_turn_helpers、action_registry。
|
||||
逻辑:turn_runtime 路由至本模块;与 chat_action_handlers 分工,避免单文件过大;
|
||||
co8 后 switch_batch_focus 固定 410。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Iterator
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.services.chat.action_registry import register_action_handler
|
||||
from app.services.chat.action_schema import TurnEvent
|
||||
from app.services.chat.turn_context import TurnContext
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_batch_for_user,
|
||||
get_task_by_ref,
|
||||
get_task_for_user,
|
||||
serialize_task_detail,
|
||||
)
|
||||
from app.services.shipping_notice.shortage_details import format_shortage_details_message
|
||||
from app.services.shipping_notice.shipping_turn_context import (
|
||||
resolve_shipping_batch_no,
|
||||
resolve_shipping_task_no,
|
||||
)
|
||||
from app.services.shipping_notice.shipping_turn_helpers import (
|
||||
shipping_batch_ui_state_event,
|
||||
shipping_task_ui_state_event,
|
||||
stream_text_events,
|
||||
tool_result_message,
|
||||
)
|
||||
from app.services.shipping_notice.task_workflow import replace_task_notice
|
||||
from app.services.shipping_notice.tool_common import switch_batch_focus
|
||||
|
||||
|
||||
def _payload_str(payload: dict[str, Any], *keys: str) -> str:
|
||||
@@ -126,15 +123,10 @@ class ShippingReplaceNoticeAction:
|
||||
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield shipping_task_ui_state_event(refreshed)
|
||||
batch_no = refreshed.batch.batch_no if refreshed.batch is not None else None
|
||||
if batch_no and ctx.user_id is not None:
|
||||
batch_event = shipping_batch_ui_state_event(batch_no, ctx.user_id)
|
||||
if batch_event is not None:
|
||||
yield batch_event
|
||||
content = _format_replace_notice_message(result, task.task_no)
|
||||
yield from stream_text_events(
|
||||
content,
|
||||
payload={"task_no": task.task_no, "batch_no": batch_no, "tool_result": result},
|
||||
payload={"task_no": task.task_no, "tool_result": result},
|
||||
)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "replace_notice"})
|
||||
|
||||
@@ -176,41 +168,15 @@ class ShippingSwitchBatchFocusAction:
|
||||
action_type = "shipping.switch_batch_focus"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
user_id = ctx.user_id
|
||||
if user_id is None:
|
||||
raise ValidationError("user context is required")
|
||||
batch_no = resolve_shipping_batch_no(ctx)
|
||||
if not batch_no:
|
||||
raise ValidationError("batch_no is required")
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
task_no = _payload_str(payload, "task_no", "taskNo", "target_task_no").upper()
|
||||
if not task_no:
|
||||
task_no = resolve_shipping_task_no(ctx)
|
||||
if not task_no:
|
||||
raise ValidationError("task_no is required")
|
||||
batch = get_batch_for_user(batch_no, user_id)
|
||||
if batch is None:
|
||||
raise NotFoundError(f"Batch not found: {batch_no}")
|
||||
task = get_task_for_user(task_no, user_id)
|
||||
if task is None or task.batch_id != batch.id:
|
||||
raise NotFoundError("Task not found in batch")
|
||||
yield TurnEvent(event="step.started", data={"step_id": "switch_batch_focus", "label": "切换焦点任务..."})
|
||||
switch_batch_focus(
|
||||
batch,
|
||||
task,
|
||||
source="chat_turn",
|
||||
comment=_payload_str(payload, "comment") or None,
|
||||
extra={"actor_user_id": user_id},
|
||||
)
|
||||
db.session.commit()
|
||||
batch_event = shipping_batch_ui_state_event(batch_no, user_id)
|
||||
if batch_event is not None:
|
||||
yield batch_event
|
||||
else:
|
||||
yield shipping_task_ui_state_event(task)
|
||||
content = f"已切换到任务 {task_no},请继续当前票处理。"
|
||||
yield from stream_text_events(content, payload={"batch_no": batch_no, "task_no": task_no})
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "switch_batch_focus"})
|
||||
"""
|
||||
历史批次切票(已下线)。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
del ctx
|
||||
raise_shipping_batches_removed(action='shipping.switch_batch_focus')
|
||||
yield from () # pragma: no cover — raise 后不可达,满足 Iterator 注解
|
||||
|
||||
|
||||
class ShippingQueryShortageDetailsAction:
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
backend/app/services/shipping_notice/chat_action_handlers.py
|
||||
|
||||
用途:货代发货通知 Chat Turn Action Handler 注册实现。
|
||||
依赖:decision_workflow、fulfillment_workflow、inventory_rpa_workflow、query_service、ui_state、action_registry。
|
||||
逻辑:turn_runtime 按 action_type 路由至本模块 handler;handler 只编排 yield 事件,业务逻辑委托既有 workflow。
|
||||
依赖:decision_workflow、fulfillment_workflow、inventory_rpa_workflow、query_service、ui_state、action_registry、
|
||||
batch_legacy_removed。
|
||||
逻辑:turn_runtime 按 action_type 路由至本模块 handler;handler 只编排 yield 事件,业务逻辑委托既有 workflow;
|
||||
co8 后 create_batch_* 动作统一 raise_shipping_batches_removed,改走 order-extraction-submissions。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,7 +21,6 @@ from app.services.shipping_notice.decision_workflow import submit_decision
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref, get_task_for_user
|
||||
from app.services.shipping_notice.shipping_turn_context import resolve_shipping_task_no
|
||||
from app.services.shipping_notice.shipping_turn_helpers import (
|
||||
shipping_batch_ui_state_event as _shipping_batch_ui_state_event,
|
||||
shipping_task_ui_state_event as _shipping_ui_state_event,
|
||||
stream_text_events as _stream_text_events,
|
||||
tool_result_message as _tool_result_message,
|
||||
@@ -90,135 +91,41 @@ def _match_result_payload(task_no: str, result: dict[str, Any]) -> dict[str, Any
|
||||
|
||||
|
||||
class ShippingCreateBatchFromNoticesAction:
|
||||
"""上传发货通知附件并创建批次。"""
|
||||
"""历史:上传发货通知并创建 shipping_batches;co8 后已下线。"""
|
||||
|
||||
action_type = "shipping.create_batch_from_notices"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
user_id = ctx.user_id
|
||||
if user_id is None:
|
||||
raise ValidationError("user context is required")
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
notice_items = payload.get("notice_items")
|
||||
if not isinstance(notice_items, list) or not notice_items:
|
||||
raise ValidationError("notice_items is required")
|
||||
file_summary = payload.get("file_summary") if isinstance(payload.get("file_summary"), dict) else None
|
||||
conversation_id = _payload_str(payload, "conversation_id", "conversationId") or None
|
||||
idempotency_key = _payload_str(payload, "idempotency_key", "idempotencyKey") or None
|
||||
"""
|
||||
拒绝旧建批 Turn。
|
||||
|
||||
yield TurnEvent(event="step.started", data={"step_id": "create_batch_from_notices", "label": "处理发货通知..."})
|
||||
核心逻辑:shipping_batches 已 DROP;客户端须走 Intake + order-extraction-submissions。
|
||||
"""
|
||||
del ctx
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
from app.services.shipping_notice.batch_from_notices import (
|
||||
create_shipping_batch_from_notice_items,
|
||||
format_batch_created_assistant_message,
|
||||
)
|
||||
|
||||
result = create_shipping_batch_from_notice_items(
|
||||
user_id=user_id,
|
||||
conversation_id=conversation_id,
|
||||
notice_items=notice_items,
|
||||
file_summary=file_summary,
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
batch_no = str(result.get("batch_no") or "").strip()
|
||||
if batch_no:
|
||||
batch_event = _shipping_batch_ui_state_event(batch_no, user_id)
|
||||
if batch_event is not None:
|
||||
yield batch_event
|
||||
|
||||
file_count = len(notice_items)
|
||||
content = format_batch_created_assistant_message(result, file_count=file_count)
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
focus_task = data.get("focus_task") if isinstance(data.get("focus_task"), dict) else {}
|
||||
message_payload = {
|
||||
"batch_no": batch_no,
|
||||
"task_no": str(focus_task.get("task_no") or result.get("task_id") or "").strip(),
|
||||
"orchestrator_started": bool(data.get("orchestrator_started")),
|
||||
"idempotent_replay": bool(result.get("idempotent_replay")),
|
||||
}
|
||||
yield from _stream_text_events(content, message_type="text", payload=message_payload)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_notices"})
|
||||
raise_shipping_batches_removed(action='shipping.create_batch_from_notices')
|
||||
if False: # pragma: no cover — 满足 Iterator 注解
|
||||
yield TurnEvent(event='step.started', data={})
|
||||
|
||||
|
||||
class ShippingCreateBatchFromIntakesAction:
|
||||
"""基于已解析接入记录确认建批(第二阶段主路径)。"""
|
||||
"""历史:基于 Intake 确认建批;co8 后已下线,改走订单抽取提交。"""
|
||||
|
||||
action_type = "shipping.create_batch_from_intakes"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
user_id = ctx.user_id
|
||||
if user_id is None:
|
||||
raise ValidationError("user context is required")
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
intake_nos = payload.get("intake_nos")
|
||||
if not isinstance(intake_nos, list) or not intake_nos:
|
||||
raise ValidationError("intake_nos is required")
|
||||
# 空白新会话 payload 常无 conversation_id;回退到 Chat Turn 刚创建的本地 session_id
|
||||
conversation_id = (
|
||||
_payload_str(payload, "conversation_id", "conversationId")
|
||||
or str(getattr(ctx, "session_id", "") or "").strip()
|
||||
or None
|
||||
)
|
||||
idempotency_key = _payload_str(payload, "idempotency_key", "idempotencyKey") or None
|
||||
candidate_nos = payload.get("candidate_nos")
|
||||
if candidate_nos is not None and not isinstance(candidate_nos, list):
|
||||
raise ValidationError("candidate_nos must be a list")
|
||||
"""
|
||||
拒绝旧建批 Turn。
|
||||
|
||||
yield TurnEvent(event="step.started", data={"step_id": "create_batch_from_intakes", "label": "确认建单..."})
|
||||
核心逻辑:请使用 POST /order-extraction-submissions 创建 OT/Run。
|
||||
"""
|
||||
del ctx
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
|
||||
from app.services.shipping_notice.batch_from_notices import format_batch_created_assistant_message
|
||||
|
||||
result = create_shipping_batch_from_intakes(
|
||||
user_id=user_id,
|
||||
conversation_id=conversation_id,
|
||||
intake_nos=[str(item) for item in intake_nos],
|
||||
candidate_nos=[str(item) for item in candidate_nos] if isinstance(candidate_nos, list) else None,
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
opened = result.get("opened_existing") if isinstance(result.get("opened_existing"), list) else []
|
||||
if opened and not str(result.get("batch_no") or "").strip():
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
focus_task = data.get("focus_task") if isinstance(data.get("focus_task"), dict) else {}
|
||||
task_no = str(focus_task.get("task_no") or opened[0].get("task_no") or "").strip()
|
||||
if task_no:
|
||||
task = get_task_by_ref(task_no)
|
||||
if task is not None:
|
||||
yield _shipping_ui_state_event(task)
|
||||
content = str(result.get("message") or "已打开已有任务,未创建新批次")
|
||||
yield from _stream_text_events(
|
||||
content,
|
||||
message_type="text",
|
||||
payload={
|
||||
"opened_existing": True,
|
||||
"task_no": task_no,
|
||||
"intake_nos": [str(item.get("intake_no") or "") for item in opened],
|
||||
},
|
||||
)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_intakes"})
|
||||
return
|
||||
|
||||
batch_no = str(result.get("batch_no") or "").strip()
|
||||
if batch_no:
|
||||
batch_event = _shipping_batch_ui_state_event(batch_no, user_id)
|
||||
if batch_event is not None:
|
||||
yield batch_event
|
||||
|
||||
file_count = len(candidate_nos) if isinstance(candidate_nos, list) and candidate_nos else len(intake_nos)
|
||||
content = format_batch_created_assistant_message(result, file_count=file_count)
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
focus_task = data.get("focus_task") if isinstance(data.get("focus_task"), dict) else {}
|
||||
message_payload = {
|
||||
"batch_no": batch_no,
|
||||
"task_no": str(focus_task.get("task_no") or result.get("task_id") or "").strip(),
|
||||
"orchestrator_started": bool(data.get("orchestrator_started")),
|
||||
"idempotent_replay": bool(result.get("idempotent_replay")),
|
||||
"document_version": focus_task.get("document_version"),
|
||||
"duplicate_resolution_type": focus_task.get("duplicate_resolution_type"),
|
||||
"supersedes_task_no": focus_task.get("supersedes_task_no"),
|
||||
}
|
||||
yield from _stream_text_events(content, message_type="text", payload=message_payload)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_intakes"})
|
||||
raise_shipping_batches_removed(action='shipping.create_batch_from_intakes')
|
||||
if False: # pragma: no cover
|
||||
yield TurnEvent(event='step.started', data={})
|
||||
|
||||
|
||||
class ShippingSubmitDecisionAction:
|
||||
|
||||
@@ -42,7 +42,7 @@ def build_chat_actions_payload(task) -> dict:
|
||||
action_buttons 已由 ui_state 在存在 ProcessExecution 时按 Gate 规则收缩(阻断清零)。
|
||||
|
||||
Args:
|
||||
task: ShippingTask 模型实例。
|
||||
task: ShippingNotice 模型实例。
|
||||
|
||||
Returns:
|
||||
包含 task_no、checkpoint、process_gate、action_buttons 与摘要的字典。
|
||||
|
||||
@@ -13,7 +13,7 @@ from typing import Any
|
||||
from flask import current_app
|
||||
|
||||
from app.core.errors import ForbiddenError
|
||||
from app.models import ChatSession, ShippingTask
|
||||
from app.models import ChatSession, ShippingNotice
|
||||
|
||||
|
||||
READ_SCOPES = frozenset({'get_shipping_status', 'get_batch_status'})
|
||||
@@ -50,7 +50,7 @@ def require_chat_capability(*, token: Any, scope: str, task_no: str | None = Non
|
||||
if session is None:
|
||||
raise ForbiddenError('Chat capability session is invalid', code='SHIPPING.CHAT_CAPABILITY_DENIED')
|
||||
if task_no:
|
||||
task = ShippingTask.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none()
|
||||
task = ShippingNotice.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none()
|
||||
if task is None or str(body.get('task') or '').upper() != task.task_no:
|
||||
raise ForbiddenError('Task is outside chat capability scope', code='SHIPPING.CHAT_CAPABILITY_DENIED')
|
||||
if batch_no and str(body.get('batch') or '').upper() != str(batch_no).upper():
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/shipping_notice/context_fields/runtime.py
|
||||
|
||||
用途:从 Intake 冻结邮件元数据采集通用上下文字段,并写入统一 Observation/Decision/FieldValue 链路。
|
||||
依赖:ShippingNoticeIntake、订单动态字段模型、customer_normalization。
|
||||
依赖:ShippingOrderIntake、订单动态字段模型、customer_normalization。
|
||||
逻辑:只读取原始 EML From;按发布快照 option_key 投影邮箱/域名,缺失或非法时形成 missing Decision。
|
||||
"""
|
||||
|
||||
@@ -14,7 +14,7 @@ from typing import Any
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldObservation,
|
||||
@@ -23,7 +23,7 @@ from app.models import (
|
||||
from app.services.shipping_notice.customer_normalization import normalize_domain, normalize_email
|
||||
|
||||
|
||||
def canonical_mail_context(intake: ShippingNoticeIntake) -> dict[str, str]:
|
||||
def canonical_mail_context(intake: ShippingOrderIntake) -> dict[str, str]:
|
||||
"""从 Intake 的 EML From 解析唯一规范邮箱及域名,供快照和裁决共用。"""
|
||||
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
email_meta = structured.get('email') if isinstance(structured.get('email'), dict) else {}
|
||||
@@ -52,7 +52,7 @@ def _existing_value(extraction_id: int, field_id: str) -> tuple[ShippingOrderFie
|
||||
|
||||
|
||||
def persist_deterministic_context_fields(
|
||||
*, extraction: ShippingOrderExtraction, intake: ShippingNoticeIntake,
|
||||
*, extraction: ShippingOrderExtraction, intake: ShippingOrderIntake,
|
||||
configs: list[dict[str, Any]], frozen_values: dict[str, Any] | None = None,
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]], list[str]]:
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,851 @@
|
||||
"""
|
||||
services/shipping_notice/conversation_processing_projection.py
|
||||
|
||||
用途:将会话内订单抽取 Run 投影为「本次处理中」用户可见任务分组。
|
||||
依赖:ShippingOrderProcessingRun、progress_audit_contract、
|
||||
order_extraction_run_service.evaluate_can_append、workflow_ledger_service.find_workflow_for_run、
|
||||
order_extraction_workspace_projection._run_available_actions。
|
||||
逻辑:由 GET conversations/{id}/processing 与统一提交响应内嵌;按 needs_action /
|
||||
processing / completed / history 分组;未查看成功结果进 completed,与异常态分离;
|
||||
先加载全部当前有效右侧候选 Run(无归并前截断),再加载同 OT 的历史谱系;
|
||||
每个 PDF 独立选择最新有效版本,归并后再按任务数截断;
|
||||
任务—PDF 两层:单 PDF 用文件名作 title;多 PDF 用 display_kind=multi_document_task,
|
||||
file_count 按 content_hash/root/document 去重;objects 含当前 PDF 子对象。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingAuditEvent,
|
||||
ShippingOrderProcessingRun,
|
||||
)
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
CONVERSATION_PROCESSING_TASK_GROUPS,
|
||||
)
|
||||
|
||||
_NEEDS_ACTION_RUN_STATUSES = frozenset({
|
||||
'review_required',
|
||||
'failed',
|
||||
'partially_completed',
|
||||
})
|
||||
_PROCESSING_RUN_STATUSES = frozenset({
|
||||
'queued',
|
||||
'processing',
|
||||
})
|
||||
_HISTORY_RUN_STATUSES = frozenset({
|
||||
'completed',
|
||||
'cancelled',
|
||||
})
|
||||
# 右侧可能展示的 Run 状态(未替代前提下);completed 还需未查看才输出。
|
||||
_RIGHT_PANEL_RUN_STATUSES = frozenset({
|
||||
'queued',
|
||||
'processing',
|
||||
'failed',
|
||||
'review_required',
|
||||
'partially_completed',
|
||||
'completed',
|
||||
})
|
||||
_NEEDS_ACTION_ITEM_LIFECYCLES = frozenset({
|
||||
'pending_review',
|
||||
'manual_upload_pending',
|
||||
'failed',
|
||||
'reparse_failed',
|
||||
})
|
||||
_PROCESSING_ITEM_LIFECYCLES = frozenset({
|
||||
'queued',
|
||||
'layout_parsing',
|
||||
'extracting',
|
||||
'building_order',
|
||||
'inventory_matching',
|
||||
'generating_excel',
|
||||
})
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
"""UTC ISO8601(带 Z);空值返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
return value.isoformat() + 'Z'
|
||||
|
||||
|
||||
def _iter_snapshot_business_documents(run: ShippingOrderProcessingRun) -> list[dict[str, Any]]:
|
||||
"""
|
||||
收集 Run 快照中的业务 PDF 行(排除 email_body)。
|
||||
|
||||
核心逻辑:优先 input_snapshot,再回退 request_snapshot;保留快照原始字段供去重。
|
||||
"""
|
||||
rows: list[dict[str, Any]] = []
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
request = run.request_snapshot_json if isinstance(run.request_snapshot_json, dict) else {}
|
||||
for source in (snapshot, request):
|
||||
for intake_index, intake in enumerate(source.get('intakes') or []):
|
||||
if not isinstance(intake, dict):
|
||||
continue
|
||||
for doc_index, document in enumerate(intake.get('documents') or []):
|
||||
if not isinstance(document, dict):
|
||||
continue
|
||||
if str(document.get('document_type') or '') == 'email_body':
|
||||
continue
|
||||
rows.append({
|
||||
**document,
|
||||
'_intake_index': intake_index,
|
||||
'_doc_index': doc_index,
|
||||
})
|
||||
if rows:
|
||||
break
|
||||
if rows:
|
||||
return rows
|
||||
# 快照尚无 documents 时,回退选择计划中的附件行。
|
||||
for source in (snapshot, request):
|
||||
selection = source.get('attachment_selection') if isinstance(source.get('attachment_selection'), dict) else {}
|
||||
for item_index, item in enumerate(selection.get('items') or []):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if not bool(item.get('selected')) and not int(item.get('selection_batch') or 0):
|
||||
continue
|
||||
rows.append({
|
||||
'document_id': item.get('document_id'),
|
||||
'root_document_id': item.get('root_document_id'),
|
||||
'filename': item.get('filename'),
|
||||
'content_hash': item.get('content_hash') or item.get('asset_content_hash'),
|
||||
'document_type': 'attachment',
|
||||
'_intake_index': 0,
|
||||
'_doc_index': item_index,
|
||||
})
|
||||
if rows:
|
||||
break
|
||||
return rows
|
||||
|
||||
|
||||
def _document_identity_key(document: dict[str, Any]) -> str:
|
||||
"""
|
||||
业务 PDF 稳定身份:content_hash → root_document_id → document_id。
|
||||
|
||||
禁止仅用文件名去重(同名不同内容必须计为两个 PDF)。
|
||||
"""
|
||||
content_hash = str(
|
||||
document.get('content_hash') or document.get('asset_content_hash') or '',
|
||||
).strip().lower()
|
||||
if content_hash:
|
||||
return f'hash:{content_hash}'
|
||||
root_id = int(document.get('root_document_id') or 0)
|
||||
if root_id > 0:
|
||||
return f'root:{root_id}'
|
||||
document_id = int(document.get('document_id') or 0)
|
||||
if document_id > 0:
|
||||
return f'doc:{document_id}'
|
||||
# 无稳定 ID 时按快照位置区分,避免同名不同文件被误合并。
|
||||
return (
|
||||
f'anon:{int(document.get("_intake_index") or 0)}:'
|
||||
f'{int(document.get("_doc_index") or 0)}:'
|
||||
f'{str(document.get("filename") or "").strip().lower()}'
|
||||
)
|
||||
|
||||
|
||||
def _document_identity_keys(document: dict[str, Any]) -> list[str]:
|
||||
"""
|
||||
返回 PDF 的全部稳定身份别名,供多数据源交叉去重。
|
||||
|
||||
核心逻辑:哈希用于识别跨 document_id 重传;root/document ID 用于消除同一文档在
|
||||
快照、Unit、WorkflowItem 中字段完整度不同造成的重复。无稳定字段时回退单一匿名键。
|
||||
|
||||
Args:
|
||||
document: 任一来源的业务 PDF 行。
|
||||
|
||||
Returns:
|
||||
按 content_hash → root_document_id → document_id 排序的身份键列表。
|
||||
"""
|
||||
keys: list[str] = []
|
||||
content_hash = str(
|
||||
document.get('content_hash') or document.get('asset_content_hash') or '',
|
||||
).strip().lower()
|
||||
root_id = int(document.get('root_document_id') or 0)
|
||||
document_id = int(document.get('document_id') or 0)
|
||||
if content_hash:
|
||||
keys.append(f'hash:{content_hash}')
|
||||
if root_id > 0:
|
||||
keys.append(f'root:{root_id}')
|
||||
if document_id > 0:
|
||||
keys.append(f'doc:{document_id}')
|
||||
return keys or [_document_identity_key(document)]
|
||||
|
||||
|
||||
def _iter_unit_business_documents(run: ShippingOrderProcessingRun) -> list[dict[str, Any]]:
|
||||
"""
|
||||
从 ExtractionUnit + Document ORM 收集业务 PDF。
|
||||
|
||||
核心逻辑:快照可能尚未写全 documents,但 Unit 已按文档拆分;以 ORM 为准补齐。
|
||||
"""
|
||||
from app.models import ShippingOrderDocument
|
||||
|
||||
plan = getattr(run, 'extraction_plan', None)
|
||||
units = list(getattr(plan, 'units', None) or []) if plan is not None else []
|
||||
rows: list[dict[str, Any]] = []
|
||||
for index, unit in enumerate(units):
|
||||
document_id = int(getattr(unit, 'document_id', 0) or 0)
|
||||
if document_id <= 0:
|
||||
continue
|
||||
document = db.session.get(ShippingOrderDocument, document_id)
|
||||
if document is None:
|
||||
continue
|
||||
if str(getattr(document, 'document_type', None) or '') == 'email_body':
|
||||
continue
|
||||
rows.append({
|
||||
'document_id': int(document.id),
|
||||
'root_document_id': int(document.id),
|
||||
'document_type': str(getattr(document, 'document_type', None) or 'attachment'),
|
||||
'filename': str(getattr(document, 'filename', None) or '').strip() or None,
|
||||
'content_hash': str(getattr(document, 'content_hash', None) or '').strip().lower() or None,
|
||||
'unit_status': str(getattr(unit, 'status', None) or '').strip() or None,
|
||||
'_intake_index': 0,
|
||||
'_doc_index': index,
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def _iter_workflow_item_documents(run: ShippingOrderProcessingRun) -> list[dict[str, Any]]:
|
||||
"""
|
||||
历史:从 WorkflowItem 收集业务 PDF;co8 后台账已 DROP。
|
||||
|
||||
核心逻辑:直接返回空列表,由快照/Unit 路径提供文件列表。
|
||||
|
||||
Args:
|
||||
run: 抽取 Run(保留签名以兼容调用方)。
|
||||
|
||||
Returns:
|
||||
空列表。
|
||||
"""
|
||||
del run
|
||||
return []
|
||||
|
||||
|
||||
def _unique_business_documents(run: ShippingOrderProcessingRun) -> list[dict[str, Any]]:
|
||||
"""
|
||||
按稳定身份去重后的当前业务 PDF 列表(同一内容只保留一条)。
|
||||
|
||||
核心逻辑:合并快照 + ExtractionUnit + WorkflowItem 三路来源;
|
||||
同 hash 的重传不增加 file_count;同名不同 hash 计为多个。
|
||||
"""
|
||||
snapshot_documents = _iter_snapshot_business_documents(run)
|
||||
unit_documents = _iter_unit_business_documents(run)
|
||||
workflow_documents = _iter_workflow_item_documents(run)
|
||||
# [STEP 1] 完整快照是 Run 的审计事实;只有 Unit/Workflow 明确包含更多 PDF 时才补齐。
|
||||
# 这样既支持生产中的稀疏快照,也避免 ORM 中旧文件名/哈希覆盖已冻结快照。
|
||||
supplemental_count = max(len(unit_documents), len(workflow_documents))
|
||||
documents = list(snapshot_documents)
|
||||
if not snapshot_documents or supplemental_count > len(snapshot_documents):
|
||||
documents.extend(unit_documents)
|
||||
documents.extend(workflow_documents)
|
||||
|
||||
# [STEP 2] 对最终来源按全部稳定身份别名交叉去重。
|
||||
unique: list[dict[str, Any]] = []
|
||||
seen: dict[str, int] = {}
|
||||
for document in documents:
|
||||
keys = _document_identity_keys(document)
|
||||
existing_index = next((seen[key] for key in keys if key in seen), None)
|
||||
if existing_index is None:
|
||||
for key in keys:
|
||||
seen[key] = len(unique)
|
||||
unique.append(document)
|
||||
continue
|
||||
# 同身份保留 document_id 更大的当前版,并补齐缺失文件名/哈希。
|
||||
previous = unique[existing_index]
|
||||
prev_id = int(previous.get('document_id') or 0)
|
||||
next_id = int(document.get('document_id') or 0)
|
||||
merged = dict(previous)
|
||||
if next_id >= prev_id:
|
||||
merged.update({k: v for k, v in document.items() if v not in (None, '')})
|
||||
# update 可能留下旧 id;显式采用较大 document_id。
|
||||
if next_id > 0:
|
||||
merged['document_id'] = next_id
|
||||
else:
|
||||
for key_name in ('filename', 'content_hash', 'root_document_id', 'unit_status'):
|
||||
if not merged.get(key_name) and document.get(key_name):
|
||||
merged[key_name] = document.get(key_name)
|
||||
unique[existing_index] = merged
|
||||
for key in _document_identity_keys(merged):
|
||||
seen[key] = existing_index
|
||||
return unique
|
||||
|
||||
|
||||
def _file_count(run: ShippingOrderProcessingRun) -> int:
|
||||
"""统计去重后的业务 PDF 数(不含 email_body,不按文件名去重)。"""
|
||||
return len(_unique_business_documents(run))
|
||||
|
||||
|
||||
def _unit_status_by_document_id(run: ShippingOrderProcessingRun) -> dict[int, str]:
|
||||
"""从 ExtractionUnit 读取文档级状态,供 PDF 子对象投影。"""
|
||||
plan = getattr(run, 'extraction_plan', None)
|
||||
units = list(getattr(plan, 'units', None) or []) if plan is not None else []
|
||||
mapping: dict[int, str] = {}
|
||||
for unit in units:
|
||||
document_id = int(getattr(unit, 'document_id', 0) or 0)
|
||||
if document_id <= 0:
|
||||
continue
|
||||
mapping[document_id] = str(getattr(unit, 'status', None) or '').strip() or 'pending'
|
||||
return mapping
|
||||
|
||||
|
||||
def _task_title_and_display_kind(
|
||||
documents: list[dict[str, Any]],
|
||||
) -> tuple[str | None, str, list[str]]:
|
||||
"""
|
||||
解析任务标题与展示类型。
|
||||
|
||||
核心逻辑:仅单 PDF 允许用文件名作 title;多 PDF 返回 title=None + multi_document_task。
|
||||
|
||||
Returns:
|
||||
(title, display_kind, document_names)
|
||||
"""
|
||||
names: list[str] = []
|
||||
for document in documents:
|
||||
name = str(document.get('filename') or '').strip()
|
||||
if name:
|
||||
names.append(name)
|
||||
if len(documents) == 1:
|
||||
title = names[0] if names else None
|
||||
return title, 'single_document_task', names
|
||||
return None, 'multi_document_task', names
|
||||
|
||||
|
||||
def _attachment_fingerprint_key(run: ShippingOrderProcessingRun) -> tuple[str, ...] | None:
|
||||
"""会话投影用的附件身份键;空指纹返回 None。"""
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
_business_attachment_fingerprint,
|
||||
)
|
||||
|
||||
snapshot = (
|
||||
run.request_snapshot_json
|
||||
if isinstance(run.request_snapshot_json, dict)
|
||||
else run.input_snapshot_json
|
||||
)
|
||||
fingerprint = _business_attachment_fingerprint(snapshot if isinstance(snapshot, dict) else None)
|
||||
return fingerprint or None
|
||||
|
||||
|
||||
def _resolve_task_group(run: ShippingOrderProcessingRun) -> str:
|
||||
"""
|
||||
将「当前有效 Run」映射为会话顶层分组。
|
||||
|
||||
核心逻辑(版本维度与业务状态分离):
|
||||
- superseded_by_run_id 非空 → history(已被新版本替代);
|
||||
- needs_action:复核/失败/部分完成(异常或需人工决策);
|
||||
- processing:queued/processing;
|
||||
- completed 且尚未查看 → completed(成功通知,与 needs_action 分离);
|
||||
- completed 已查看 / cancelled → history(右侧不展示)。
|
||||
"""
|
||||
if getattr(run, 'superseded_by_run_id', None) is not None:
|
||||
return 'history'
|
||||
status = str(run.status or '')
|
||||
if status in _NEEDS_ACTION_RUN_STATUSES:
|
||||
return 'needs_action'
|
||||
if status in _PROCESSING_RUN_STATUSES:
|
||||
return 'processing'
|
||||
if status == 'completed':
|
||||
# [UI-01] 未查看的成功完成进入 completed 分组,不与失败/复核混排。
|
||||
if run.seen_at is None:
|
||||
return 'completed'
|
||||
if run.attention_generated_at is not None and run.seen_at < run.attention_generated_at:
|
||||
return 'completed'
|
||||
return 'history'
|
||||
if status in _HISTORY_RUN_STATUSES:
|
||||
return 'history'
|
||||
return 'history'
|
||||
|
||||
|
||||
def _status_label(run: ShippingOrderProcessingRun) -> str:
|
||||
"""
|
||||
用户可见状态码(前端 i18n);禁止直接拼自然语言。
|
||||
|
||||
映射为稳定展示码:queued / processing / pending_review / failed /
|
||||
completed / cancelling / cancelled / unknown。
|
||||
"""
|
||||
if getattr(run, 'cancellation_requested_at', None) is not None and str(run.status or '') not in {
|
||||
'cancelled', 'completed',
|
||||
}:
|
||||
return 'cancelling'
|
||||
status = str(run.status or '').strip() or 'unknown'
|
||||
if status == 'review_required':
|
||||
return 'pending_review'
|
||||
if status == 'partially_completed':
|
||||
return 'pending_review'
|
||||
if status in {
|
||||
'queued', 'processing', 'failed', 'completed', 'cancelled',
|
||||
}:
|
||||
return status
|
||||
return status or 'unknown'
|
||||
|
||||
|
||||
def _is_current_effective_run(run: ShippingOrderProcessingRun) -> bool:
|
||||
"""未被后继 Run 替代的当前有效版本。"""
|
||||
return getattr(run, 'superseded_by_run_id', None) is None
|
||||
|
||||
|
||||
def _run_recency_key(run: ShippingOrderProcessingRun) -> tuple:
|
||||
"""版本选择键:优先未替代 → 最近活动 → 最近创建 → 更大 id。"""
|
||||
activity = run.last_activity_at or run.created_at
|
||||
created = run.created_at
|
||||
return (
|
||||
1 if _is_current_effective_run(run) else 0,
|
||||
activity or datetime.min,
|
||||
created or datetime.min,
|
||||
int(run.id or 0),
|
||||
)
|
||||
|
||||
def _latest_focused_task_no(*, user_id: int, conversation_id: str) -> str | None:
|
||||
"""
|
||||
从最近一次 focus 审计恢复会话焦点(无 ChatSession 元数据时的轻量回退)。
|
||||
|
||||
Args:
|
||||
user_id: 属主用户。
|
||||
conversation_id: 聊天会话 ID。
|
||||
|
||||
Returns:
|
||||
最近聚焦的 user_task_no;无记录返回 None。
|
||||
"""
|
||||
row = (
|
||||
ShippingAuditEvent.query.filter(
|
||||
ShippingAuditEvent.event_type == 'conversation_processing_task_focused',
|
||||
ShippingAuditEvent.conversation_id == str(conversation_id),
|
||||
ShippingAuditEvent.owner_user_id == str(user_id),
|
||||
)
|
||||
.order_by(ShippingAuditEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
meta = row.metadata_json if isinstance(row.metadata_json, dict) else {}
|
||||
task_no = str(meta.get('user_task_no') or row.task_no or '').strip()
|
||||
return task_no or None
|
||||
|
||||
|
||||
def _effective_business_documents(
|
||||
runs: list[ShippingOrderProcessingRun],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
从同一用户任务的 Run 谱系中解析当前有效 PDF 集合。
|
||||
|
||||
核心逻辑:按 content_hash → root_document_id → document_id 识别 PDF;每个身份
|
||||
独立选择最近 Run 中的版本,避免局部重识别时把旧 Run 内未重识别的 PDF 一并丢失。
|
||||
|
||||
Args:
|
||||
runs: 同一用户任务的全部 Run,允许包含已被后继替代的来源 Run。
|
||||
|
||||
Returns:
|
||||
去重后的当前有效 PDF 行;每行附带 `_source_run` 供对象级状态与 Run 号投影。
|
||||
"""
|
||||
selected: list[tuple[tuple, dict[str, Any]]] = []
|
||||
identity_indexes: dict[str, int] = {}
|
||||
for run in runs:
|
||||
for document in _unique_business_documents(run):
|
||||
identities = _document_identity_keys(document)
|
||||
candidate = {
|
||||
**document,
|
||||
'_source_run': run,
|
||||
}
|
||||
key = (
|
||||
_run_recency_key(run),
|
||||
int(document.get('document_id') or 0),
|
||||
)
|
||||
existing_index = next(
|
||||
(identity_indexes[identity] for identity in identities if identity in identity_indexes),
|
||||
None,
|
||||
)
|
||||
if existing_index is None:
|
||||
existing_index = len(selected)
|
||||
selected.append((key, candidate))
|
||||
for identity in identities:
|
||||
identity_indexes[identity] = existing_index
|
||||
continue
|
||||
if key > selected[existing_index][0]:
|
||||
selected[existing_index] = (key, candidate)
|
||||
for identity in identities:
|
||||
identity_indexes[identity] = existing_index
|
||||
return [row[1] for row in selected]
|
||||
|
||||
|
||||
def _simplified_objects(
|
||||
run: ShippingOrderProcessingRun,
|
||||
*,
|
||||
documents: list[dict[str, Any]] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
投影任务下对象行:当前 Run + 去重后的当前 PDF 文档(不含历史版本重复)。
|
||||
|
||||
Args:
|
||||
run: 任务级操作与状态的代表 Run。
|
||||
documents: 可选的跨 Run 当前有效 PDF 集合;空时仅使用代表 Run。
|
||||
|
||||
Returns:
|
||||
ConversationProcessingObject 形状列表。
|
||||
"""
|
||||
user_task_no = str(getattr(run, 'user_task_no', None) or '').strip() or None
|
||||
objects: list[dict[str, Any]] = [{
|
||||
'kind': 'run',
|
||||
'object_key': f'RUN-{run.run_no}',
|
||||
'label': str(run.run_no),
|
||||
'status_label': _status_label(run),
|
||||
'run_no': run.run_no,
|
||||
'user_task_no': user_task_no,
|
||||
'focused': False,
|
||||
}]
|
||||
effective_documents = documents if documents is not None else _unique_business_documents(run)
|
||||
unit_status_by_run_id: dict[int, dict[int, str]] = {}
|
||||
for document in effective_documents:
|
||||
source_run = document.get('_source_run') or run
|
||||
source_run_id = int(getattr(source_run, 'id', 0) or 0)
|
||||
if source_run_id not in unit_status_by_run_id:
|
||||
unit_status_by_run_id[source_run_id] = _unit_status_by_document_id(source_run)
|
||||
unit_status = unit_status_by_run_id[source_run_id]
|
||||
document_id = int(document.get('document_id') or 0) or None
|
||||
root_document_id = int(document.get('root_document_id') or 0) or document_id
|
||||
filename = str(document.get('filename') or '').strip() or None
|
||||
content_hash = str(
|
||||
document.get('content_hash') or document.get('asset_content_hash') or '',
|
||||
).strip().lower() or None
|
||||
status_label = (
|
||||
str(document.get('unit_status') or '').strip()
|
||||
or (
|
||||
unit_status.get(int(document_id))
|
||||
if document_id is not None
|
||||
else None
|
||||
)
|
||||
or _status_label(source_run)
|
||||
)
|
||||
object_key = (
|
||||
f'DOC-{document_id}'
|
||||
if document_id is not None
|
||||
else f'DOC-{_document_identity_key(document)}'
|
||||
)
|
||||
objects.append({
|
||||
'kind': 'document',
|
||||
'object_key': object_key,
|
||||
'label': filename or object_key,
|
||||
'status_label': status_label,
|
||||
'run_no': source_run.run_no,
|
||||
'user_task_no': user_task_no,
|
||||
'document_id': document_id,
|
||||
'root_document_id': root_document_id,
|
||||
'filename': filename,
|
||||
'content_hash': content_hash,
|
||||
'current_run_no': source_run.run_no,
|
||||
'focused': False,
|
||||
})
|
||||
return objects
|
||||
|
||||
|
||||
def _resolve_workflow_no(run: ShippingOrderProcessingRun) -> str | None:
|
||||
"""
|
||||
解析用户任务所属 Workflow 编号,供前端跨批次切换文件列表。
|
||||
|
||||
核心逻辑:委托 find_workflow_for_run(Item.current_run_id / 重识别源 Case)。
|
||||
"""
|
||||
from app.services.shipping_notice.workflow_ledger_service import find_workflow_for_run
|
||||
|
||||
workflow = find_workflow_for_run(run=run)
|
||||
if workflow is None:
|
||||
return None
|
||||
return str(getattr(workflow, 'workflow_no', None) or '').strip() or None
|
||||
|
||||
|
||||
def _resolve_task_actions(run: ShippingOrderProcessingRun) -> tuple[str | None, list[str]]:
|
||||
"""
|
||||
聚合任务级权威操作;前端禁止自行按状态推导按钮。
|
||||
|
||||
核心逻辑:复用 workspace `_run_available_actions`,再映射会话任务卡常用动作码。
|
||||
|
||||
Returns:
|
||||
(primary_action, available_actions)
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import (
|
||||
_run_available_actions,
|
||||
)
|
||||
|
||||
plan = getattr(run, 'extraction_plan', None)
|
||||
units = list(getattr(plan, 'units', None) or []) if plan is not None else []
|
||||
raw_actions = _run_available_actions(run, units)
|
||||
# 会话任务卡动作别名:与评审契约对齐,同时保留既有 workspace 动作码。
|
||||
actions: list[str] = []
|
||||
for action in raw_actions:
|
||||
code = str(action or '').strip()
|
||||
if not code:
|
||||
continue
|
||||
if code not in actions:
|
||||
actions.append(code)
|
||||
if code == 'enter_manual_review' and 'open_review' not in actions:
|
||||
actions.append('open_review')
|
||||
if code == 'cancel_run' and 'cancel_task' not in actions:
|
||||
actions.append('cancel_task')
|
||||
if code == 'retry_failed_attachments' and 'retry_failed_documents' not in actions:
|
||||
actions.append('retry_failed_documents')
|
||||
|
||||
if 'view_details' not in actions:
|
||||
actions.insert(0, 'view_details')
|
||||
|
||||
primary: str | None = None
|
||||
for candidate in (
|
||||
'open_review',
|
||||
'enter_manual_review',
|
||||
'retry_failed_documents',
|
||||
'retry_failed_attachments',
|
||||
'cancel_task',
|
||||
'cancel_run',
|
||||
'view_details',
|
||||
):
|
||||
if candidate in actions:
|
||||
primary = candidate
|
||||
break
|
||||
return primary, actions
|
||||
|
||||
|
||||
def _project_user_task(
|
||||
run: ShippingOrderProcessingRun,
|
||||
*,
|
||||
focused_task_no: str | None,
|
||||
documents: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将单个 Run 投影为用户可见任务摘要。
|
||||
|
||||
Args:
|
||||
run: 当前用户会话内负责任务级状态与操作的代表 Run。
|
||||
focused_task_no: 当前焦点任务号。
|
||||
documents: 同 OT 跨 Run 汇总后的当前有效 PDF;空时仅投影代表 Run。
|
||||
|
||||
Returns:
|
||||
ConversationProcessingUserTask 字典。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
evaluate_can_append,
|
||||
)
|
||||
|
||||
can_append, block_reason = evaluate_can_append(run)
|
||||
# [UI-01 / BE-03] 仅暴露已持久化的 OT 编号;Candidate 前不得派生伪 OT。
|
||||
user_task_no = str(getattr(run, 'user_task_no', None) or '').strip()
|
||||
group = _resolve_task_group(run)
|
||||
assert group in CONVERSATION_PROCESSING_TASK_GROUPS
|
||||
viewed = run.seen_at is not None and run.attention_generated_at is not None and (
|
||||
run.seen_at >= run.attention_generated_at
|
||||
)
|
||||
primary_action, available_actions = _resolve_task_actions(run)
|
||||
effective_documents = documents if documents is not None else _unique_business_documents(run)
|
||||
title, display_kind, document_names = _task_title_and_display_kind(effective_documents)
|
||||
return {
|
||||
'user_task_no': user_task_no,
|
||||
'submission_ordinal': getattr(run, 'submission_ordinal', None),
|
||||
'title': title,
|
||||
'display_kind': display_kind,
|
||||
'document_names': document_names,
|
||||
'group': group,
|
||||
'status_label': _status_label(run),
|
||||
'file_count': len(effective_documents),
|
||||
'run_no': run.run_no,
|
||||
'workflow_no': _resolve_workflow_no(run),
|
||||
'can_append': can_append,
|
||||
'append_block_reason': block_reason,
|
||||
'input_lifecycle': getattr(run, 'input_lifecycle', None) or 'open',
|
||||
'input_frozen_at': _iso(getattr(run, 'input_frozen_at', None)),
|
||||
'focused': bool(focused_task_no and focused_task_no == user_task_no),
|
||||
'viewed': bool(viewed),
|
||||
'acknowledged': False,
|
||||
'last_activity_at': _iso(run.last_activity_at or run.updated_at),
|
||||
'created_at': _iso(run.created_at),
|
||||
'recent_append_count': None,
|
||||
'recently_created': False,
|
||||
'primary_action': primary_action,
|
||||
'available_actions': available_actions,
|
||||
'objects': _simplified_objects(run, documents=effective_documents),
|
||||
}
|
||||
|
||||
|
||||
def project_conversation_processing(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str,
|
||||
focused_task_no: str | None = None,
|
||||
recent_task_no: str | None = None,
|
||||
recent_decision: str | None = None,
|
||||
recent_append_count: int | None = None,
|
||||
limit: int = 50,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
投影会话级「本次处理中」用户可见任务。
|
||||
|
||||
核心逻辑:
|
||||
1. 先筛未替代且右侧可见状态的当前 Run,确定需要展示的用户任务;
|
||||
2. 加载这些 OT 的全部 Run 谱系,每个 PDF 身份独立选择最新版本;
|
||||
3. 同一 user_task_no 只输出一张任务卡,再按附件指纹归并重复任务;
|
||||
4. 输出 needs_action / processing / completed,最后按 task_limit 截断。
|
||||
"""
|
||||
normalized = str(conversation_id or '').strip()
|
||||
|
||||
focused = str(focused_task_no or '').strip() or None
|
||||
if not focused:
|
||||
focused = _latest_focused_task_no(user_id=int(user_id), conversation_id=normalized)
|
||||
|
||||
task_limit = max(1, min(int(limit or 50), 200))
|
||||
# [BE-02] 候选集仅含当前有效 + 右侧可见状态;不得在归并前用固定窗口截断。
|
||||
# 极端会话硬顶仅防失控读放大,远高于常规用户任务上限。
|
||||
# [UI-01 / BE-03] Candidate 前 user_task_no 为 NULL:不进右侧「订单任务」卡。
|
||||
candidate_hard_cap = 5000
|
||||
runs = (
|
||||
ShippingOrderProcessingRun.query.filter(
|
||||
ShippingOrderProcessingRun.user_id == int(user_id),
|
||||
ShippingOrderProcessingRun.conversation_id == normalized,
|
||||
ShippingOrderProcessingRun.superseded_by_run_id.is_(None),
|
||||
ShippingOrderProcessingRun.user_task_no.isnot(None),
|
||||
ShippingOrderProcessingRun.status.in_(sorted(_RIGHT_PANEL_RUN_STATUSES)),
|
||||
)
|
||||
.order_by(
|
||||
ShippingOrderProcessingRun.last_activity_at.desc().nullslast(),
|
||||
ShippingOrderProcessingRun.created_at.desc(),
|
||||
)
|
||||
.limit(candidate_hard_cap)
|
||||
.all()
|
||||
)
|
||||
|
||||
# [STEP 1] 同一 OT 只选择一个代表 Run(重识别不产生新用户任务)。
|
||||
latest_by_task: dict[str, ShippingOrderProcessingRun] = {}
|
||||
for run in runs:
|
||||
task_no = str(getattr(run, 'user_task_no', None) or '').strip()
|
||||
if not task_no:
|
||||
continue
|
||||
if task_no not in latest_by_task:
|
||||
latest_by_task[task_no] = run
|
||||
|
||||
active_task_nos = list(latest_by_task)
|
||||
lineage_runs = (
|
||||
ShippingOrderProcessingRun.query.filter(
|
||||
ShippingOrderProcessingRun.user_id == int(user_id),
|
||||
ShippingOrderProcessingRun.conversation_id == normalized,
|
||||
ShippingOrderProcessingRun.user_task_no.in_(active_task_nos),
|
||||
)
|
||||
.order_by(
|
||||
ShippingOrderProcessingRun.last_activity_at.asc().nullsfirst(),
|
||||
ShippingOrderProcessingRun.created_at.asc(),
|
||||
)
|
||||
.all()
|
||||
if active_task_nos
|
||||
else []
|
||||
)
|
||||
runs_by_task: dict[str, list[ShippingOrderProcessingRun]] = {
|
||||
task_no: [] for task_no in active_task_nos
|
||||
}
|
||||
for lineage_run in lineage_runs:
|
||||
task_no = str(getattr(lineage_run, 'user_task_no', None) or '').strip()
|
||||
if task_no in runs_by_task:
|
||||
runs_by_task[task_no].append(lineage_run)
|
||||
|
||||
# [STEP 2][BE-02] 按附件指纹归并任务卡;PDF 集合仍按各 OT 谱系独立汇总。
|
||||
latest_by_identity: dict[str, ShippingOrderProcessingRun] = {}
|
||||
task_nos_by_identity: dict[str, list[str]] = {}
|
||||
identity_order: list[str] = []
|
||||
for run in latest_by_task.values():
|
||||
fingerprint = _attachment_fingerprint_key(run)
|
||||
identity = (
|
||||
'fp:' + '|'.join(fingerprint)
|
||||
if fingerprint
|
||||
else f'task:{getattr(run, "user_task_no", None) or run.run_no}'
|
||||
)
|
||||
existing = latest_by_identity.get(identity)
|
||||
if existing is None:
|
||||
latest_by_identity[identity] = run
|
||||
task_nos_by_identity[identity] = [
|
||||
str(getattr(run, 'user_task_no', None) or '').strip(),
|
||||
]
|
||||
identity_order.append(identity)
|
||||
continue
|
||||
task_no = str(getattr(run, 'user_task_no', None) or '').strip()
|
||||
if task_no and task_no not in task_nos_by_identity[identity]:
|
||||
task_nos_by_identity[identity].append(task_no)
|
||||
if _run_recency_key(run) > _run_recency_key(existing):
|
||||
latest_by_identity[identity] = run
|
||||
|
||||
needs_action: list[dict[str, Any]] = []
|
||||
processing: list[dict[str, Any]] = []
|
||||
completed: list[dict[str, Any]] = []
|
||||
recent = str(recent_task_no or '').strip() or None
|
||||
decision = str(recent_decision or '').strip().lower() or None
|
||||
append_count = (
|
||||
max(0, int(recent_append_count))
|
||||
if recent_append_count is not None
|
||||
else None
|
||||
)
|
||||
for identity in identity_order:
|
||||
run = latest_by_identity[identity]
|
||||
# 已被替代的版本不进入右侧。
|
||||
if not _is_current_effective_run(run):
|
||||
continue
|
||||
source_runs: list[ShippingOrderProcessingRun] = []
|
||||
for task_no in task_nos_by_identity.get(identity, []):
|
||||
source_runs.extend(runs_by_task.get(task_no) or [latest_by_task[task_no]])
|
||||
effective_documents = _effective_business_documents(source_runs or [run])
|
||||
task = _project_user_task(
|
||||
run,
|
||||
focused_task_no=focused,
|
||||
documents=effective_documents,
|
||||
)
|
||||
if recent and task['user_task_no'] == recent:
|
||||
if decision == 'appended':
|
||||
task['recent_append_count'] = append_count if append_count is not None else 1
|
||||
task['recently_created'] = False
|
||||
else:
|
||||
task['recently_created'] = True
|
||||
task['recent_append_count'] = None
|
||||
group = task['group']
|
||||
if group == 'needs_action':
|
||||
needs_action.append(task)
|
||||
elif group == 'processing':
|
||||
processing.append(task)
|
||||
elif group == 'completed':
|
||||
completed.append(task)
|
||||
|
||||
# [STEP 3] 组内按最近活动时间降序;再按任务数截断(非原始 Run 数)。
|
||||
def _sort_key(item: dict[str, Any]) -> str:
|
||||
return str(item.get('last_activity_at') or item.get('created_at') or '')
|
||||
|
||||
needs_action.sort(key=_sort_key, reverse=True)
|
||||
processing.sort(key=_sort_key, reverse=True)
|
||||
completed.sort(key=_sort_key, reverse=True)
|
||||
|
||||
# 优先保留需处理与处理中,再填已完成通知。
|
||||
kept: list[tuple[str, dict[str, Any]]] = []
|
||||
for bucket, rows in (
|
||||
('needs_action', needs_action),
|
||||
('processing', processing),
|
||||
('completed', completed),
|
||||
):
|
||||
for row in rows:
|
||||
if len(kept) >= task_limit:
|
||||
break
|
||||
kept.append((bucket, row))
|
||||
if len(kept) >= task_limit:
|
||||
break
|
||||
needs_action = [row for bucket, row in kept if bucket == 'needs_action']
|
||||
processing = [row for bucket, row in kept if bucket == 'processing']
|
||||
completed = [row for bucket, row in kept if bucket == 'completed']
|
||||
|
||||
total_files = sum(
|
||||
int(item.get('file_count') or 0) for item in needs_action + processing + completed
|
||||
)
|
||||
total = len(needs_action) + len(processing) + len(completed)
|
||||
return {
|
||||
'summary': {
|
||||
'total_tasks': total,
|
||||
'total_files': total_files,
|
||||
'processing': len(processing),
|
||||
'needs_action': len(needs_action),
|
||||
'completed': len(completed),
|
||||
'history': 0,
|
||||
},
|
||||
'focused_task_no': focused,
|
||||
'recent_task_no': recent,
|
||||
'needs_action': needs_action,
|
||||
'processing': processing,
|
||||
'completed': completed,
|
||||
'history': [],
|
||||
}
|
||||
@@ -20,12 +20,12 @@ from app.models import (
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingIdentityRuleSet,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingTask,
|
||||
ShippingNotice,
|
||||
ShippingTaskEvent,
|
||||
)
|
||||
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
|
||||
@@ -49,7 +49,7 @@ CUSTOMER_AUDIT_EVENT_TYPES = (
|
||||
|
||||
def auto_customer_resolution_enabled() -> bool:
|
||||
"""读取自动客户确认总开关;默认关闭以支持安全降级。"""
|
||||
return cfg_bool("SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED", False)
|
||||
return cfg_bool("SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED", True)
|
||||
|
||||
|
||||
def _auto_confirmation_quality_gate() -> dict[str, Any]:
|
||||
@@ -227,7 +227,12 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
|
||||
if not definition or not normalized:
|
||||
continue
|
||||
verified_normalized = _verified_shadow_value(shadow, definition, evidence)
|
||||
if verified_normalized is None or verified_normalized != normalized:
|
||||
# 影子记录可能来自旧版本规则快照,邮箱/编码的大小写规范化存在历史差异。
|
||||
# 使用同一指纹的大小写无关比较,避免合法唯一命中被误判为 unmatched。
|
||||
if (
|
||||
verified_normalized is None
|
||||
or verified_normalized.casefold() != normalized.casefold()
|
||||
):
|
||||
continue
|
||||
field_value_source = evidence['source']
|
||||
if (
|
||||
@@ -238,16 +243,26 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
|
||||
continue
|
||||
field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
|
||||
context_source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {}
|
||||
# 兼容旧规则快照:若未保存 context_source,则从定义编码识别邮箱/域名指纹类型。
|
||||
option_key = str(context_source.get('option_key') or '').strip().lower()
|
||||
if not option_key:
|
||||
definition_code = str(definition.get('definition_code') or '').lower()
|
||||
if 'email' in definition_code or 'mail' in definition_code:
|
||||
option_key = 'from_email'
|
||||
elif 'domain' in definition_code:
|
||||
option_key = 'from_domain'
|
||||
email_domain = normalized.rsplit('@', 1)[-1] if '@' in normalized else normalized
|
||||
if context_source.get('option_key') in {'from_email', 'from_domain'} and is_public_email_domain(email_domain):
|
||||
if option_key in {'from_email', 'from_domain'} and is_public_email_domain(email_domain):
|
||||
continue
|
||||
records = db.session.query(ShippingIdentityEvidence).filter_by(
|
||||
definition_id=definition_id,
|
||||
normalized_value=normalized,
|
||||
status='approved',
|
||||
auto_match_allowed=True,
|
||||
).all()
|
||||
for record in records:
|
||||
# 主数据中历史录入值也可能保留不同大小写;按指纹语义比较而非原始字符串比较。
|
||||
if str(record.normalized_value or '').strip().casefold() != normalized.casefold():
|
||||
continue
|
||||
if record.customer_id is None:
|
||||
continue
|
||||
customer = db.session.get(ShippingCustomer, int(record.customer_id))
|
||||
@@ -273,7 +288,7 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
|
||||
return result
|
||||
|
||||
|
||||
def resolve_auto_customer_from_shadow(task: ShippingTask) -> dict[str, Any]:
|
||||
def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]:
|
||||
"""
|
||||
使用任务来源 Candidate 的影子证据执行受控自动裁决。
|
||||
|
||||
@@ -282,24 +297,15 @@ def resolve_auto_customer_from_shadow(task: ShippingTask) -> dict[str, Any]:
|
||||
Returns:
|
||||
status、规则版本、唯一 customer_id 与命中证据;歧义/关闭时 customer_id 为空。
|
||||
"""
|
||||
if not auto_customer_resolution_enabled():
|
||||
return {"status": "disabled", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
|
||||
quality_gate = _auto_confirmation_quality_gate()
|
||||
if not quality_gate['is_eligible']:
|
||||
return {
|
||||
'status': quality_gate['status'],
|
||||
'rule_version': AUTO_RESOLUTION_VERSION,
|
||||
'customer_id': None,
|
||||
'evidence': [],
|
||||
'quality_gate': quality_gate,
|
||||
}
|
||||
# [PARAM_TUNING] 业务策略改为:已发布识别指纹唯一命中即可自动确认;
|
||||
# 不再以全局开关、历史标注样本量或准确率二次阻断唯一确定结果。
|
||||
if task.source_candidate_id is None:
|
||||
return {"status": "no_candidate", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
|
||||
shadow = db.session.query(ShippingCustomerShadowResolution).filter_by(
|
||||
candidate_id=int(task.source_candidate_id),
|
||||
).first()
|
||||
if shadow is None:
|
||||
candidate = db.session.get(ShippingNoticeCandidate, int(task.source_candidate_id))
|
||||
candidate = db.session.get(ShippingOrderCandidate, int(task.source_candidate_id))
|
||||
if candidate is not None:
|
||||
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
|
||||
|
||||
@@ -307,10 +313,14 @@ def resolve_auto_customer_from_shadow(task: ShippingTask) -> dict[str, Any]:
|
||||
if shadow is None:
|
||||
return {"status": "no_shadow", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
|
||||
|
||||
return {**_resolve_auto_customer_from_shadow_resolution(shadow), 'quality_gate': quality_gate}
|
||||
return {**_resolve_auto_customer_from_shadow_resolution(shadow), 'quality_gate': {
|
||||
'status': 'bypassed_unique_match_policy',
|
||||
'is_eligible': True,
|
||||
'reason': '唯一识别指纹命中直接自动确认',
|
||||
}}
|
||||
|
||||
|
||||
def try_auto_confirm_task_customer(task: ShippingTask) -> dict[str, Any]:
|
||||
def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]:
|
||||
"""
|
||||
尝试自动确认并生成业务编号;未达门槛时保持 customer_review。
|
||||
|
||||
@@ -348,7 +358,7 @@ def try_auto_confirm_task_customer(task: ShippingTask) -> dict[str, Any]:
|
||||
|
||||
|
||||
def correct_numbered_task_customer(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
customer_id: int,
|
||||
reason: str,
|
||||
@@ -419,9 +429,9 @@ def correct_numbered_task_customer(
|
||||
)
|
||||
|
||||
versions = (
|
||||
db.session.query(ShippingTask)
|
||||
db.session.query(ShippingNotice)
|
||||
.filter_by(shipping_case_id=original_case.id)
|
||||
.order_by(ShippingTask.document_version.asc(), ShippingTask.id.asc())
|
||||
.order_by(ShippingNotice.document_version.asc(), ShippingNotice.id.asc())
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
@@ -539,8 +549,8 @@ def get_auto_resolution_metrics() -> dict[str, Any]:
|
||||
event_type="customer_correction_applied",
|
||||
).distinct().count()
|
||||
recent_events = (
|
||||
db.session.query(ShippingTaskEvent, ShippingTask.task_no)
|
||||
.join(ShippingTask, ShippingTask.id == ShippingTaskEvent.task_id)
|
||||
db.session.query(ShippingTaskEvent, ShippingNotice.task_no)
|
||||
.join(ShippingNotice, ShippingNotice.id == ShippingTaskEvent.task_id)
|
||||
.filter(ShippingTaskEvent.event_type.in_(CUSTOMER_AUDIT_EVENT_TYPES))
|
||||
.order_by(ShippingTaskEvent.id.desc())
|
||||
.limit(100)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/shipping_notice/customer_identity_gate.py
|
||||
|
||||
用途:货代任务标准客户确认、业务编号生成、候选查询与统一下游硬门禁。
|
||||
依赖:ShippingTask/Case/Customer/Event、business_numbering_service、统一 AppError、customer_normalization。
|
||||
依赖:ShippingNotice/Case/Customer/Event、business_numbering_service、统一 AppError、customer_normalization。
|
||||
逻辑:业务用户只能选择已启用标准客户;确认与业务编号在同一事务完成,并同步业务单全部任务版本。
|
||||
"""
|
||||
|
||||
@@ -16,14 +16,14 @@ from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import ShippingCase, ShippingCustomer, ShippingTask, ShippingTaskEvent
|
||||
from app.models import ShippingCase, ShippingCustomer, ShippingNotice, ShippingTaskEvent
|
||||
from app.services.shipping_notice.customer_normalization import clean_text
|
||||
from app.services.shipping_notice.business_numbering_service import assign_business_number
|
||||
|
||||
CUSTOMER_GATE_ERROR_CODE = 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
|
||||
|
||||
|
||||
def customer_identity_is_confirmed(task: ShippingTask) -> bool:
|
||||
def customer_identity_is_confirmed(task: ShippingNotice) -> bool:
|
||||
"""判断任务是否已关联业务单并通过标准客户确认。"""
|
||||
if task.shipping_case_id is None:
|
||||
return False
|
||||
@@ -34,7 +34,7 @@ def customer_identity_is_confirmed(task: ShippingTask) -> bool:
|
||||
return bool(customer and customer.status == 'active' and task.customer_resolution_status == 'confirmed')
|
||||
|
||||
|
||||
def assert_customer_identity_gate(task: ShippingTask, *, operation: str = 'continue') -> None:
|
||||
def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'continue') -> None:
|
||||
"""
|
||||
标准客户硬门禁;业务单缺失或客户未确认时阻断库存、RPA、匹配、Excel 与上传。
|
||||
|
||||
@@ -79,13 +79,13 @@ def list_customer_options(*, query: str = '', limit: int = 100) -> list[dict[str
|
||||
|
||||
|
||||
def confirm_task_customer(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
customer_id: int,
|
||||
actor_id: int | None,
|
||||
resolution_method: str = 'manual',
|
||||
commit: bool = True,
|
||||
) -> ShippingTask:
|
||||
) -> ShippingNotice:
|
||||
"""
|
||||
人工确认任务所属标准客户,并同步共享业务单下所有任务版本。
|
||||
|
||||
@@ -133,7 +133,7 @@ def confirm_task_customer(
|
||||
case.customer_short_code_snapshot = customer.short_code
|
||||
business_no = assign_business_number(case)
|
||||
fingerprint = hashlib.sha256(f'customer:{customer.id}'.encode('ascii')).hexdigest()
|
||||
tasks = db.session.query(ShippingTask).filter_by(shipping_case_id=case.id).all()
|
||||
tasks = db.session.query(ShippingNotice).filter_by(shipping_case_id=case.id).all()
|
||||
for version in tasks:
|
||||
version.customer_resolution_status = 'confirmed'
|
||||
version.customer_resolution_method = resolution_method
|
||||
@@ -165,12 +165,12 @@ def confirm_task_customer(
|
||||
))
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return db.session.get(ShippingTask, int(task.id))
|
||||
return db.session.get(ShippingNotice, int(task.id))
|
||||
db.session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def customer_gate_tool_response(task: ShippingTask, *, operation: str) -> dict[str, Any] | None:
|
||||
def customer_gate_tool_response(task: ShippingNotice, *, operation: str) -> dict[str, Any] | None:
|
||||
"""Tool 公共入口将客户 Gate 转为 needs_human 响应,未阻断时返回 None。"""
|
||||
if customer_identity_is_confirmed(task):
|
||||
return None
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/customer_shadow_resolution.py
|
||||
|
||||
用途:对订单 Candidate 执行只读客户影子识别,并提供质量报告与人工标签。
|
||||
依赖:客户主数据/识别证据、Candidate/Intake、customer_normalization。
|
||||
逻辑:确定性证据打分后只写 ShadowResolution;严禁修改 ShippingCase、ShippingTask 或业务编号。
|
||||
逻辑:确定性证据打分后只写 ShadowResolution;严禁修改 ShippingCase、ShippingNotice 或业务编号。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,17 +20,17 @@ from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerShadowMatch,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderIntake,
|
||||
)
|
||||
from app.services.shipping_notice.identity_resolution import resolve_candidate_identity
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def refresh_candidate_shadow_resolution(candidate: ShippingNoticeCandidate) -> ShippingCustomerShadowResolution:
|
||||
def refresh_candidate_shadow_resolution(candidate: ShippingOrderCandidate) -> ShippingCustomerShadowResolution:
|
||||
"""幂等刷新 Candidate 影子识别;只写审计结果,不执行客户绑定或自动确认。"""
|
||||
intake = db.session.get(ShippingNoticeIntake, int(candidate.intake_id))
|
||||
intake = db.session.get(ShippingOrderIntake, int(candidate.intake_id))
|
||||
if intake is None:
|
||||
raise NotFoundError('Shipping intake not found', code='SHIPPING_NOTICE.INTAKE_NOT_FOUND')
|
||||
resolution = resolve_candidate_identity(candidate, intake)
|
||||
@@ -82,7 +82,7 @@ def refresh_candidate_shadow_resolution(candidate: ShippingNoticeCandidate) -> S
|
||||
return row
|
||||
|
||||
|
||||
def refresh_candidate_shadow_resolution_safely(candidate: ShippingNoticeCandidate) -> None:
|
||||
def refresh_candidate_shadow_resolution_safely(candidate: ShippingOrderCandidate) -> None:
|
||||
"""用 SAVEPOINT 隔离影子识别异常;任何失败均不得中断 Candidate 主流程。"""
|
||||
try:
|
||||
with db.session.begin_nested():
|
||||
@@ -144,13 +144,13 @@ def label_shadow_resolution(resolution_id: int, *, customer_id: int, actor_id: i
|
||||
def serialize_shadow_resolution(
|
||||
row: ShippingCustomerShadowResolution,
|
||||
*,
|
||||
candidate: ShippingNoticeCandidate | None = None,
|
||||
intake: ShippingNoticeIntake | None = None,
|
||||
candidate: ShippingOrderCandidate | None = None,
|
||||
intake: ShippingOrderIntake | None = None,
|
||||
manual_customer: ShippingCustomer | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""序列化影子识别结果;报告可传入批量预加载对象以避免 N+1。"""
|
||||
candidate = candidate or db.session.get(ShippingNoticeCandidate, int(row.candidate_id))
|
||||
intake = intake or db.session.get(ShippingNoticeIntake, int(row.intake_id))
|
||||
candidate = candidate or db.session.get(ShippingOrderCandidate, int(row.candidate_id))
|
||||
intake = intake or db.session.get(ShippingOrderIntake, int(row.intake_id))
|
||||
if manual_customer is None and row.manual_customer_id is not None:
|
||||
manual_customer = db.session.get(ShippingCustomer, int(row.manual_customer_id))
|
||||
return {
|
||||
@@ -195,11 +195,11 @@ def get_shadow_quality_report(*, limit: int = 100) -> dict[str, Any]:
|
||||
manual_customer_ids = [int(item.manual_customer_id) for item in rows if item.manual_customer_id is not None]
|
||||
candidates = {
|
||||
item.id: item
|
||||
for item in db.session.query(ShippingNoticeCandidate).filter(ShippingNoticeCandidate.id.in_(candidate_ids)).all()
|
||||
for item in db.session.query(ShippingOrderCandidate).filter(ShippingOrderCandidate.id.in_(candidate_ids)).all()
|
||||
} if candidate_ids else {}
|
||||
intakes = {
|
||||
item.id: item
|
||||
for item in db.session.query(ShippingNoticeIntake).filter(ShippingNoticeIntake.id.in_(intake_ids)).all()
|
||||
for item in db.session.query(ShippingOrderIntake).filter(ShippingOrderIntake.id.in_(intake_ids)).all()
|
||||
} if intake_ids else {}
|
||||
manual_customers = {
|
||||
item.id: item
|
||||
|
||||
@@ -13,7 +13,7 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNoticeCandidate, ShippingOrderExtractionRun, ShippingTaskInventoryLink
|
||||
from app.models import ShippingOrderCandidate, ShippingOrderProcessingRun, ShippingTaskInventoryLink
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_PARSE_OK,
|
||||
@@ -467,14 +467,14 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
# [STEP 4] Task 不回退旧 Chatflow;从来源 Candidate 追溯到 Intake Run 后走统一重新识别服务。
|
||||
if decision == "reparse":
|
||||
candidate = (
|
||||
db.session.get(ShippingNoticeCandidate, int(task.source_candidate_id))
|
||||
db.session.get(ShippingOrderCandidate, int(task.source_candidate_id))
|
||||
if task.source_candidate_id else None
|
||||
)
|
||||
source_run_id = candidate.order_extraction_run_id if candidate is not None else None
|
||||
if source_run_id:
|
||||
from app.services.shipping_notice.order_extraction_run_service import reparse_order_extraction_run
|
||||
|
||||
run = db.session.get(ShippingOrderExtractionRun, source_run_id)
|
||||
run = db.session.get(ShippingOrderProcessingRun, source_run_id)
|
||||
if run is not None:
|
||||
replacement, reused = reparse_order_extraction_run(
|
||||
user_id=int(task.user_id), run_no=run.run_no, reason="other", comment=comment or None,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/dify_inputs.py
|
||||
|
||||
用途:识别发货通知 Dify Chatflow Agent,并构建会话级 Dify inputs。
|
||||
依赖:agent_runtime_context 平台协议、models.ShippingBatch/ShippingTask、shipping_notice.runtime_context。
|
||||
依赖:agent_runtime_context 平台协议、models.ShippingNotice、shipping_notice.runtime_context。
|
||||
逻辑:由 Context Adapter / api/chat 调用;本模块按会话号解析当前批次/任务焦点,
|
||||
仅输出 agent_runtime_context JSON 字符串,供 Dify 画布统一读取平台运行态快照。
|
||||
发货通知识别请使用 agent_registry.resolver.resolve_agent_code == 'shipping_notice'。
|
||||
@@ -13,30 +13,24 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingBatch, ShippingTask, ShippingTemporaryInventorySession
|
||||
from app.models import ShippingNotice, ShippingTemporaryInventorySession
|
||||
from app.services.agent_runtime_context.builder import serialize_for_dify
|
||||
from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT
|
||||
from app.services.shipping_notice.runtime_context import build_shipping_runtime_context
|
||||
|
||||
|
||||
def _latest_batch_for_conversation(conversation_id: str) -> ShippingBatch | None:
|
||||
"""按会话号获取最近一个发货批次,用于恢复当前批次焦点。"""
|
||||
conv_id = str(conversation_id or "").strip()
|
||||
if not conv_id:
|
||||
return None
|
||||
return (
|
||||
ShippingBatch.query.filter_by(conversation_id=conv_id)
|
||||
.order_by(ShippingBatch.id.desc())
|
||||
.first()
|
||||
)
|
||||
def _latest_batch_for_conversation(conversation_id: str) -> None:
|
||||
"""shipping_batches 已删除;固定返回 None。"""
|
||||
del conversation_id
|
||||
return None
|
||||
|
||||
|
||||
def _task_by_task_no(task_id: str) -> ShippingTask | None:
|
||||
def _task_by_task_no(task_id: str) -> ShippingNotice | None:
|
||||
"""按显式 task_id 获取任务;仅用于补齐批次 ref,禁止按会话号猜测当前任务。"""
|
||||
normalized = str(task_id or "").strip().upper()
|
||||
if not normalized:
|
||||
return None
|
||||
return ShippingTask.query.filter_by(task_no=normalized).first()
|
||||
return ShippingNotice.query.filter_by(task_no=normalized).first()
|
||||
|
||||
|
||||
def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | None:
|
||||
@@ -68,7 +62,7 @@ def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | N
|
||||
return str(item.session_no or '').strip().upper() or None if item else None
|
||||
|
||||
|
||||
def _focus_task_row(focus_task: str, explicit_task_row: ShippingTask | None) -> ShippingTask | None:
|
||||
def _focus_task_row(focus_task: str, explicit_task_row: ShippingNotice | None) -> ShippingNotice | None:
|
||||
"""
|
||||
解析当前显式焦点任务行。
|
||||
|
||||
@@ -87,7 +81,7 @@ def _focus_task_row(focus_task: str, explicit_task_row: ShippingTask | None) ->
|
||||
return None
|
||||
if explicit_task_row and str(explicit_task_row.task_no or "").strip().upper() == normalized:
|
||||
return explicit_task_row
|
||||
return ShippingTask.query.filter_by(task_no=normalized).first()
|
||||
return ShippingNotice.query.filter_by(task_no=normalized).first()
|
||||
|
||||
|
||||
def build_dify_chat_inputs(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_candidate_persist.py
|
||||
|
||||
用途:阶段二——EML 附件派生 FileAsset、ShippingNoticeDocument / Candidate 幂等落库。
|
||||
用途:阶段二——EML 附件派生 FileAsset、ShippingOrderDocument / Candidate 幂等落库。
|
||||
依赖:file_assets.service、intake_business_parser、business_fingerprint、duplicate_detection、客户影子识别、eml_parse。
|
||||
逻辑:由 intake_parse_workflow.run_intake_parse 在文本落库成功后调用;重试按
|
||||
(parent, content_hash)、(intake, attachment_key)、(intake, primary_document_id) 复用,不重复创建。
|
||||
@@ -21,9 +21,9 @@ from typing import Any
|
||||
from app import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
)
|
||||
from app.services.file_assets.service import (
|
||||
create_derived_file_asset_from_bytes,
|
||||
@@ -151,7 +151,7 @@ def _should_persist_attachment_asset(item: dict[str, Any], payload: bytes) -> bo
|
||||
|
||||
def _upsert_document(
|
||||
*,
|
||||
intake: ShippingNoticeIntake,
|
||||
intake: ShippingOrderIntake,
|
||||
attachment_key: str,
|
||||
document_type: str,
|
||||
filename: str | None,
|
||||
@@ -162,17 +162,17 @@ def _upsert_document(
|
||||
asset_id: int | None,
|
||||
classification: str,
|
||||
layout_snapshot: dict[str, Any] | None = None,
|
||||
) -> ShippingNoticeDocument:
|
||||
) -> ShippingOrderDocument:
|
||||
row = (
|
||||
db.session.query(ShippingNoticeDocument)
|
||||
db.session.query(ShippingOrderDocument)
|
||||
.filter(
|
||||
ShippingNoticeDocument.intake_id == int(intake.id),
|
||||
ShippingNoticeDocument.attachment_key == attachment_key,
|
||||
ShippingOrderDocument.intake_id == int(intake.id),
|
||||
ShippingOrderDocument.attachment_key == attachment_key,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
row = ShippingNoticeDocument(
|
||||
row = ShippingOrderDocument(
|
||||
intake_id=int(intake.id),
|
||||
attachment_key=attachment_key,
|
||||
document_type=document_type,
|
||||
@@ -206,8 +206,8 @@ def _upsert_document(
|
||||
|
||||
def _upsert_candidate(
|
||||
*,
|
||||
intake: ShippingNoticeIntake,
|
||||
document: ShippingNoticeDocument,
|
||||
intake: ShippingOrderIntake,
|
||||
document: ShippingOrderDocument,
|
||||
business_summary: dict[str, Any],
|
||||
fingerprint: dict[str, Any],
|
||||
content_fingerprint: dict[str, Any],
|
||||
@@ -221,18 +221,18 @@ def _upsert_candidate(
|
||||
conflicts: list[dict[str, Any]] | None = None,
|
||||
validation_status: str = 'ready',
|
||||
evidence: dict[str, Any] | None = None,
|
||||
) -> ShippingNoticeCandidate:
|
||||
) -> ShippingOrderCandidate:
|
||||
"""按 Intake + candidate_key 幂等写入一个订单草稿及其抽取审计。"""
|
||||
row = (
|
||||
db.session.query(ShippingNoticeCandidate)
|
||||
db.session.query(ShippingOrderCandidate)
|
||||
.filter(
|
||||
ShippingNoticeCandidate.intake_id == int(intake.id),
|
||||
ShippingNoticeCandidate.candidate_key == str(candidate_key),
|
||||
ShippingOrderCandidate.intake_id == int(intake.id),
|
||||
ShippingOrderCandidate.candidate_key == str(candidate_key),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
row = ShippingNoticeCandidate(
|
||||
row = ShippingOrderCandidate(
|
||||
candidate_no=generate_candidate_no(),
|
||||
intake_id=int(intake.id),
|
||||
primary_document_id=int(document.id),
|
||||
@@ -284,10 +284,20 @@ def _upsert_candidate(
|
||||
)
|
||||
|
||||
refresh_candidate_shadow_resolution_safely(row)
|
||||
from app.services.shipping_notice.candidate_evidence_service import (
|
||||
replace_candidate_evidences_from_persist,
|
||||
)
|
||||
|
||||
replace_candidate_evidences_from_persist(
|
||||
row,
|
||||
document=document,
|
||||
evidence=evidence if isinstance(evidence, dict) else None,
|
||||
conflicts=list(conflicts or []),
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def _serialize_document_brief(doc: ShippingNoticeDocument, *, include_text: bool) -> dict[str, Any]:
|
||||
def _serialize_document_brief(doc: ShippingOrderDocument, *, include_text: bool) -> dict[str, Any]:
|
||||
asset = db.session.get(FileAsset, int(doc.asset_id)) if doc.asset_id else None
|
||||
payload: dict[str, Any] = {
|
||||
'id': doc.id,
|
||||
@@ -308,7 +318,7 @@ def _serialize_document_brief(doc: ShippingNoticeDocument, *, include_text: bool
|
||||
return payload
|
||||
|
||||
|
||||
def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
|
||||
def _serialize_candidate_brief(cand: ShippingOrderCandidate) -> dict[str, Any]:
|
||||
"""序列化 Candidate 审核摘要,并保持 duplicate 契约与 Intake 一致。"""
|
||||
from app.services.shipping_notice.duplicate_detection import _allowed_actions_for
|
||||
|
||||
@@ -340,7 +350,7 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
|
||||
if isinstance(extraction.get('field_adjudication'), dict)
|
||||
else {}
|
||||
)
|
||||
document = db.session.get(ShippingNoticeDocument, int(cand.primary_document_id))
|
||||
document = db.session.get(ShippingOrderDocument, int(cand.primary_document_id))
|
||||
action_buttons: list[str] = []
|
||||
if cand.candidate_status == 'provisional' and cand.consumed_task_id is None and cand.is_current_version:
|
||||
action_buttons.extend(['edit', 'evidence', 'reject'])
|
||||
@@ -409,9 +419,9 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
|
||||
def list_intake_documents(intake_id: int, *, include_text: bool = False) -> list[dict[str, Any]]:
|
||||
"""列出 Intake 下 Document 摘要。"""
|
||||
rows = (
|
||||
db.session.query(ShippingNoticeDocument)
|
||||
.filter(ShippingNoticeDocument.intake_id == int(intake_id))
|
||||
.order_by(ShippingNoticeDocument.id.asc())
|
||||
db.session.query(ShippingOrderDocument)
|
||||
.filter(ShippingOrderDocument.intake_id == int(intake_id))
|
||||
.order_by(ShippingOrderDocument.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [_serialize_document_brief(row, include_text=include_text) for row in rows]
|
||||
@@ -420,9 +430,9 @@ def list_intake_documents(intake_id: int, *, include_text: bool = False) -> list
|
||||
def list_intake_candidates(intake_id: int) -> list[dict[str, Any]]:
|
||||
"""列出 Intake 下 Candidate 摘要。"""
|
||||
rows = (
|
||||
db.session.query(ShippingNoticeCandidate)
|
||||
.filter(ShippingNoticeCandidate.intake_id == int(intake_id))
|
||||
.order_by(ShippingNoticeCandidate.id.asc())
|
||||
db.session.query(ShippingOrderCandidate)
|
||||
.filter(ShippingOrderCandidate.intake_id == int(intake_id))
|
||||
.order_by(ShippingOrderCandidate.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [_serialize_candidate_brief(row) for row in rows]
|
||||
@@ -442,7 +452,7 @@ _UNCHECKED_DUP: dict[str, Any] = {
|
||||
|
||||
def persist_documents_and_candidates(
|
||||
*,
|
||||
intake: ShippingNoticeIntake,
|
||||
intake: ShippingOrderIntake,
|
||||
parent_asset: FileAsset,
|
||||
result: NoticeIntakeResult,
|
||||
uploaded_storage_keys: list[str] | None = None,
|
||||
@@ -489,8 +499,8 @@ def persist_documents_and_candidates(
|
||||
active_keys: set[str] = set()
|
||||
linked_asset_count = 0
|
||||
created_asset_count = 0
|
||||
documents: list[ShippingNoticeDocument] = []
|
||||
candidates: list[ShippingNoticeCandidate] = []
|
||||
documents: list[ShippingOrderDocument] = []
|
||||
candidates: list[ShippingOrderCandidate] = []
|
||||
active_candidate_doc_ids: set[int] = set()
|
||||
|
||||
# [STEP 1] 正文 Document:仅邮件级上下文,不生成 Candidate
|
||||
@@ -746,32 +756,39 @@ def persist_documents_and_candidates(
|
||||
|
||||
# [STEP 4] 清理消失的 Document,并释放其派生资产
|
||||
stale_docs = (
|
||||
db.session.query(ShippingNoticeDocument)
|
||||
db.session.query(ShippingOrderDocument)
|
||||
.filter(
|
||||
ShippingNoticeDocument.intake_id == int(intake.id),
|
||||
ShippingNoticeDocument.attachment_key.notin_(tuple(active_keys) or ('__none__',)),
|
||||
ShippingOrderDocument.intake_id == int(intake.id),
|
||||
ShippingOrderDocument.attachment_key.notin_(tuple(active_keys) or ('__none__',)),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
stale_ids = {int(d.id) for d in stale_docs}
|
||||
if stale_ids:
|
||||
db.session.query(ShippingNoticeCandidate).filter(
|
||||
ShippingNoticeCandidate.intake_id == int(intake.id),
|
||||
ShippingNoticeCandidate.primary_document_id.in_(tuple(stale_ids)),
|
||||
db.session.query(ShippingOrderCandidate).filter(
|
||||
ShippingOrderCandidate.intake_id == int(intake.id),
|
||||
ShippingOrderCandidate.primary_document_id.in_(tuple(stale_ids)),
|
||||
).delete(synchronize_session=False)
|
||||
for doc in stale_docs:
|
||||
_release_document_asset(int(doc.asset_id) if doc.asset_id else None)
|
||||
db.session.delete(doc)
|
||||
|
||||
# [STEP 5] 清理本轮不再具备候选资格的旧 Candidate(Document 仍在但 classification 变了)
|
||||
stale_cand_q = db.session.query(ShippingNoticeCandidate).filter(
|
||||
ShippingNoticeCandidate.intake_id == int(intake.id),
|
||||
# [STEP 5] Document 仍在但已不具备候选资格时,保留可能已被 Case/OT
|
||||
# 引用的历史 Candidate,只撤销其当前版本资格。
|
||||
stale_cand_q = db.session.query(ShippingOrderCandidate).filter(
|
||||
ShippingOrderCandidate.intake_id == int(intake.id),
|
||||
)
|
||||
if active_candidate_doc_ids:
|
||||
stale_cand_q = stale_cand_q.filter(
|
||||
ShippingNoticeCandidate.primary_document_id.notin_(tuple(active_candidate_doc_ids)),
|
||||
ShippingOrderCandidate.primary_document_id.notin_(tuple(active_candidate_doc_ids)),
|
||||
)
|
||||
stale_cand_q.filter(ShippingNoticeCandidate.consumed_task_id.is_(None)).delete(synchronize_session=False)
|
||||
for candidate in stale_cand_q.filter(ShippingOrderCandidate.consumed_task_id.is_(None)).all():
|
||||
if candidate.is_current_version:
|
||||
candidate.selected_before_superseded = bool(candidate.selected)
|
||||
candidate.candidate_status_before_superseded = candidate.candidate_status
|
||||
candidate.selected = False
|
||||
candidate.candidate_status = 'expired'
|
||||
candidate.is_current_version = False
|
||||
|
||||
# [STEP 6] 剥离 payload,防止后续 structured_result 泄漏
|
||||
strip_attachment_payloads(meta)
|
||||
@@ -793,7 +810,7 @@ def persist_documents_and_candidates(
|
||||
|
||||
def persist_intake_documents(
|
||||
*,
|
||||
intake: ShippingNoticeIntake,
|
||||
intake: ShippingOrderIntake,
|
||||
parent_asset: FileAsset,
|
||||
result: NoticeIntakeResult,
|
||||
uploaded_storage_keys: list[str] | None = None,
|
||||
@@ -826,7 +843,7 @@ def persist_intake_documents(
|
||||
)
|
||||
|
||||
|
||||
def clear_intake_stage2_structured_projection(intake: ShippingNoticeIntake) -> None:
|
||||
def clear_intake_stage2_structured_projection(intake: ShippingOrderIntake) -> None:
|
||||
"""
|
||||
清理 structured_result_json 中的阶段二投影(document/candidate 计数与附件资产标识)。
|
||||
|
||||
@@ -855,7 +872,7 @@ def clear_intake_stage2_structured_projection(intake: ShippingNoticeIntake) -> N
|
||||
intake.updated_at = datetime.utcnow()
|
||||
|
||||
|
||||
def release_unconsumed_intake_stage2(*, intake: ShippingNoticeIntake) -> dict[str, int]:
|
||||
def release_unconsumed_intake_stage2(*, intake: ShippingOrderIntake) -> dict[str, int]:
|
||||
"""
|
||||
删除未消费 Intake 的 Document/Candidate,并释放派生资产引用。
|
||||
|
||||
@@ -869,13 +886,13 @@ def release_unconsumed_intake_stage2(*, intake: ShippingNoticeIntake) -> dict[st
|
||||
删除的 candidate/document 数量及释放的 asset 次数。
|
||||
"""
|
||||
candidates = (
|
||||
db.session.query(ShippingNoticeCandidate)
|
||||
.filter(ShippingNoticeCandidate.intake_id == int(intake.id))
|
||||
db.session.query(ShippingOrderCandidate)
|
||||
.filter(ShippingOrderCandidate.intake_id == int(intake.id))
|
||||
.all()
|
||||
)
|
||||
documents = (
|
||||
db.session.query(ShippingNoticeDocument)
|
||||
.filter(ShippingNoticeDocument.intake_id == int(intake.id))
|
||||
db.session.query(ShippingOrderDocument)
|
||||
.filter(ShippingOrderDocument.intake_id == int(intake.id))
|
||||
.all()
|
||||
)
|
||||
for cand in candidates:
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/contracts.py
|
||||
|
||||
用途:定义解析器无关的 shipping_document_layout.v1 契约、稳定标识和完整性校验。
|
||||
用途:定义解析器无关的 shipping_document_layout.v1 契约、稳定标识和完整性校验;
|
||||
并再导出 XFA 阶段 0 契约入口,供布局与 Profile 模块统一引用。
|
||||
依赖:Pydantic 2、标准库 hashlib/json/unicodedata;字段高亮质量枚举与
|
||||
field_highlight_contract 对齐(本模块只声明可挂载到 LayoutCell 的状态字面量)。
|
||||
field_highlight_contract 对齐;XFA 鉴别联合与路径语法见同目录 xfa_contract。
|
||||
逻辑:PDF/OCR/HTML 解析器先构造 LayoutDocument;持久化、Schema 映射和评测只接受通过
|
||||
本模块校验的结果;复核高亮投影消费 cell/token 坐标,但不在本契约内裁决绘制质量。
|
||||
本模块校验的结果;XFA datasets 模式不走本模块几何契约,改由 xfa_contract 约束。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,6 +19,21 @@ from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import ( # noqa: F401
|
||||
ORDER_PROFILE_TEMPLATE_MODES,
|
||||
XFA_CONTRACT_VERSION,
|
||||
XFA_DOCUMENT_KINDS,
|
||||
XFA_DTO_FORBIDDEN_KEYS,
|
||||
XFA_EVIDENCE_SOURCES,
|
||||
XFA_SUPPORTED_DOCUMENT_KINDS,
|
||||
OrderXfaDatasetProfile,
|
||||
compute_dataset_structure_fingerprint,
|
||||
normalize_template_mode,
|
||||
sanitize_xfa_dto,
|
||||
validate_controlled_data_path,
|
||||
validate_xfa_dataset_definition,
|
||||
)
|
||||
|
||||
|
||||
LAYOUT_SCHEMA_VERSION = 'shipping_document_layout.v1'
|
||||
# 与 field_highlight_contract.HIGHLIGHT_QUALITY_VALUES 对齐;Cell 可选挂载,禁止自创同义状态。
|
||||
|
||||
@@ -1,26 +1,99 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/coordinate_region_text.py
|
||||
|
||||
用途:统一从页面坐标字符中读取受控区域文字。
|
||||
依赖:冻结 layout 的 page_glyphs/tables 字符坐标契约。
|
||||
逻辑:标注取字、模板匹配和版本诊断共同使用视觉行聚类与行内横坐标排序,避免阅读顺序分叉。
|
||||
用途:统一从页面坐标字符中读取受控区域文字,并恢复可靠的原始文本流空白。
|
||||
依赖:冻结 layout 的 page_glyphs/tables 字符坐标契约、PositionedCharacter 可选边界字段。
|
||||
逻辑:标注取字、模板匹配、字段抽取和版本诊断共享“原始边界优先、几何间距兜底”的渲染规则。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from typing import Any, Literal
|
||||
|
||||
|
||||
def visual_text_lines(glyphs: list[dict[str, Any]]) -> list[str]:
|
||||
def render_positioned_row(
|
||||
glyphs: list[Any], *, geometry_gap_limit: float | None = None,
|
||||
geometry_gap_ratio: float | None = None,
|
||||
geometry_width_mode: Literal['previous', 'average'] = 'average',
|
||||
minimum_gap_limit: float = 0.0,
|
||||
) -> str:
|
||||
"""
|
||||
将坐标字符按视觉行恢复为阅读顺序文本。
|
||||
将单个视觉行按横坐标渲染,优先采用 PDF 原始文本流的明确空白边界。
|
||||
|
||||
核心逻辑:boundary_before 为 space/line_break 时恢复一个普通空格;只有旧版证据或
|
||||
OCR 没有该边界时,才按调用方提供的几何阈值兜底,避免料号、金额被全局拆分。
|
||||
|
||||
Args:
|
||||
glyphs: 含 text 与 bbox 的页面字符;无效字符会被忽略。
|
||||
glyphs: 字典或 PositionedCharacter;必须包含 text 与 bbox。
|
||||
geometry_gap_limit: 可选固定几何阈值,适合以中位字宽计算的旧链路。
|
||||
geometry_gap_ratio: 可选动态比例;按相邻字宽逐对计算,保持旧版模板阈值口径。
|
||||
geometry_width_mode: previous 使用左字符宽度,average 使用相邻平均字宽。
|
||||
minimum_gap_limit: 动态阈值的最小页面距离,防止极窄 glyph 过度分词。
|
||||
|
||||
Returns:
|
||||
从上到下的文本行;同行字符按 x0 排序,并按视觉间距恢复单个空格。
|
||||
保留原文字面值的单行文本;相邻重复空白折叠为一个普通空格。
|
||||
"""
|
||||
ordered = sorted(glyphs, key=lambda item: (_glyph_bbox_value(item, 'x0'), _glyph_source_index(item)))
|
||||
parts: list[str] = []
|
||||
previous_x1: float | None = None
|
||||
previous_width: float | None = None
|
||||
for glyph in ordered:
|
||||
text = _glyph_value(glyph, 'text')
|
||||
if not text:
|
||||
continue
|
||||
boundary = str(_glyph_value(glyph, 'boundary_before') or 'none')
|
||||
x0, x1 = _glyph_bbox_value(glyph, 'x0'), _glyph_bbox_value(glyph, 'x1')
|
||||
width = max(0.01, x1 - x0)
|
||||
explicit_space = boundary in {'space', 'line_break'}
|
||||
resolved_gap_limit = geometry_gap_limit
|
||||
if geometry_gap_ratio is not None and previous_width is not None:
|
||||
reference_width = (
|
||||
previous_width if geometry_width_mode == 'previous'
|
||||
else (previous_width + width) / 2
|
||||
)
|
||||
resolved_gap_limit = max(minimum_gap_limit, reference_width * geometry_gap_ratio)
|
||||
fallback_space = (
|
||||
boundary == 'none'
|
||||
and resolved_gap_limit is not None
|
||||
and previous_x1 is not None
|
||||
and x0 - previous_x1 > resolved_gap_limit
|
||||
)
|
||||
if (explicit_space or fallback_space) and parts and not parts[-1].endswith(' ') and not text.isspace():
|
||||
parts.append(' ')
|
||||
parts.append(text)
|
||||
previous_x1 = x1
|
||||
previous_width = width
|
||||
return ''.join(parts).strip()
|
||||
|
||||
|
||||
def _glyph_value(glyph: Any, key: str) -> Any:
|
||||
"""兼容冻结字典和 Pydantic 字符模型读取字段,避免各坐标链路重复分支。"""
|
||||
return glyph.get(key) if isinstance(glyph, dict) else getattr(glyph, key, None)
|
||||
|
||||
|
||||
def _glyph_bbox_value(glyph: Any, key: str) -> float:
|
||||
"""从字典或 LayoutBBox 中读取坐标;调用方已过滤缺失 bbox 的异常字符。"""
|
||||
bbox = _glyph_value(glyph, 'bbox')
|
||||
value = bbox.get(key) if isinstance(bbox, dict) else getattr(bbox, key)
|
||||
return float(value)
|
||||
|
||||
|
||||
def _glyph_source_index(glyph: Any) -> int:
|
||||
"""以原始文本流序号稳定同坐标字符顺序;旧证据缺失时保持横坐标排序结果。"""
|
||||
value = _glyph_value(glyph, 'source_index')
|
||||
return int(value) if value is not None else 0
|
||||
|
||||
|
||||
def visual_glyph_rows(glyphs: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
|
||||
"""将坐标字符按视觉行分组,供表头签名与运行时 Matcher 共享同一阅读顺序。
|
||||
|
||||
Args:
|
||||
glyphs: 含 text 与 bbox 的页面字符。
|
||||
|
||||
Returns:
|
||||
从上到下的字符行;每行字符已按 x0 排序。
|
||||
"""
|
||||
# 行高容差与锨点匹配保持一致,防止同一 PDF 在签名和运行比对时产生不同行序。
|
||||
rows: list[list[dict[str, Any]]] = []
|
||||
for glyph in sorted(
|
||||
glyphs,
|
||||
@@ -46,20 +119,75 @@ def visual_text_lines(glyphs: list[dict[str, Any]]) -> list[str]:
|
||||
continue
|
||||
rows.append([glyph])
|
||||
|
||||
lines: list[str] = []
|
||||
for row in rows:
|
||||
ordered = sorted(row, key=lambda item: float((item.get('bbox') or {}).get('x0', 0)))
|
||||
parts: list[str] = []
|
||||
return [
|
||||
sorted(row, key=lambda item: float((item.get('bbox') or {}).get('x0', 0)))
|
||||
for row in rows
|
||||
]
|
||||
|
||||
|
||||
def positioned_token_spans(
|
||||
glyphs: list[dict[str, Any]], *, respect_explicit_spaces: bool = True,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
从视觉行中恢复带横向边界的 token。
|
||||
|
||||
Args:
|
||||
glyphs: 含坐标的页面字符。
|
||||
respect_explicit_spaces: False 时仅依赖显著几何间隔分列,用于抹平新旧
|
||||
PDF 证据是否保存 boundary_before 的差异。
|
||||
|
||||
Returns:
|
||||
从上到下、从左到右的 token 及其绝对横向边界。
|
||||
"""
|
||||
spans: list[dict[str, Any]] = []
|
||||
for row in visual_glyph_rows(glyphs):
|
||||
current: list[dict[str, Any]] = []
|
||||
previous_x1: float | None = None
|
||||
previous_width = 0.0
|
||||
for item in ordered:
|
||||
box = item['bbox']
|
||||
x0, x1 = float(box['x0']), float(box['x1'])
|
||||
if previous_x1 is not None and x0 - previous_x1 > max(1.5, previous_width * 1.45):
|
||||
parts.append(' ')
|
||||
parts.append(str(item.get('text') or ''))
|
||||
previous_x1, previous_width = x1, max(1.0, x1 - x0)
|
||||
text = ''.join(parts).strip()
|
||||
previous_width: float | None = None
|
||||
for glyph in row:
|
||||
bbox = glyph.get('bbox') or {}
|
||||
try:
|
||||
x0, x1 = float(bbox['x0']), float(bbox['x1'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
width = max(0.01, x1 - x0)
|
||||
boundary = str(glyph.get('boundary_before') or 'none')
|
||||
geometry_space = (
|
||||
previous_x1 is not None
|
||||
and previous_width is not None
|
||||
and x0 - previous_x1 > max(1.5, previous_width * (1.45 if respect_explicit_spaces else 0.75))
|
||||
)
|
||||
explicit_space = respect_explicit_spaces and boundary in {'space', 'line_break'}
|
||||
if current and (explicit_space or geometry_space):
|
||||
spans.append(_positioned_span(current))
|
||||
current = []
|
||||
current.append(glyph)
|
||||
previous_x1, previous_width = x1, width
|
||||
if current:
|
||||
spans.append(_positioned_span(current))
|
||||
return [item for item in spans if item.get('text')]
|
||||
|
||||
|
||||
def _positioned_span(glyphs: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""渲染单个 token 并返回其绝对横向边界。"""
|
||||
ordered = sorted(glyphs, key=lambda item: float((item.get('bbox') or {}).get('x0', 0)))
|
||||
return {
|
||||
'text': render_positioned_row(ordered),
|
||||
'x0': min(float(item['bbox']['x0']) for item in ordered),
|
||||
'x1': max(float(item['bbox']['x1']) for item in ordered),
|
||||
}
|
||||
|
||||
|
||||
def visual_text_lines(glyphs: list[dict[str, Any]]) -> list[str]:
|
||||
"""将坐标字符按视觉行恢复为阅读顺序文本。"""
|
||||
lines: list[str] = []
|
||||
for ordered in visual_glyph_rows(glyphs):
|
||||
text = render_positioned_row(
|
||||
ordered,
|
||||
geometry_gap_ratio=1.45,
|
||||
geometry_width_mode='previous',
|
||||
minimum_gap_limit=1.5,
|
||||
)
|
||||
if text:
|
||||
lines.append(text)
|
||||
return lines
|
||||
|
||||
+58
-31
@@ -15,6 +15,7 @@ from typing import Any, Literal
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import render_positioned_row
|
||||
from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter
|
||||
from app.services.shipping_notice.document_layout.order_profile_extractors import extract_profile_field_value
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
@@ -186,9 +187,10 @@ class HeaderLayoutSuggestion(CoordinateReconstructionModel):
|
||||
|
||||
|
||||
class CoordinateProfileLogicalRow(CoordinateReconstructionModel):
|
||||
"""v2 坐标模板重建的一条逻辑明细,字段仍由上层 Schema 规范化。"""
|
||||
"""坐标模板重建的一条逻辑明细,并保留每个字段的原生 glyph 几何证据。"""
|
||||
|
||||
fields: dict[str, str] = Field(default_factory=dict)
|
||||
field_evidence: dict[str, dict[str, Any]] = Field(default_factory=dict)
|
||||
source_row_indices: list[int] = Field(min_length=1)
|
||||
role: Literal['data', 'deleted'] = 'data'
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
@@ -354,9 +356,12 @@ def reconstruct_coordinate_profile_rows(
|
||||
if relative_y_rows is not None:
|
||||
return relative_y_rows
|
||||
|
||||
def values_for(band: list[tuple[int, PositionedCharacter]], layout: dict[str, Any]) -> tuple[dict[str, str], list[str]]:
|
||||
"""按当前物理行读取字段列;标注区域的纵向位置只表达子行版式,不限定绝对页坐标。"""
|
||||
def values_for(
|
||||
band: list[tuple[int, PositionedCharacter]], layout: dict[str, Any],
|
||||
) -> tuple[dict[str, str], dict[str, dict[str, Any]], list[str]]:
|
||||
"""读取字段值和同源 glyph 几何;纵向位置只表达子行版式,不限定绝对页坐标。"""
|
||||
values: dict[str, str] = {}
|
||||
evidence: dict[str, dict[str, Any]] = {}
|
||||
issues: list[str] = []
|
||||
for field in layout.get('field_regions') or []:
|
||||
if not isinstance(field, dict) or not isinstance(field.get('region'), dict):
|
||||
@@ -365,7 +370,8 @@ def reconstruct_coordinate_profile_rows(
|
||||
if not code:
|
||||
continue
|
||||
region = _absolute_relative_region(bbox, field['region'])
|
||||
text = _text_in_horizontal_region(band, region)
|
||||
selected = [item for item in band if _inside_horizontal_region(item[1].bbox, region)]
|
||||
text = _text_in_horizontal_region(selected, region)
|
||||
if text:
|
||||
extracted = extract_profile_field_value(
|
||||
extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=text,
|
||||
@@ -378,21 +384,24 @@ def reconstruct_coordinate_profile_rows(
|
||||
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
|
||||
else:
|
||||
values[extracted_code] = extracted_value
|
||||
return values, issues
|
||||
evidence[extracted_code] = _field_glyph_evidence(selected, text=text)
|
||||
return values, evidence, issues
|
||||
|
||||
results: list[CoordinateProfileLogicalRow] = []
|
||||
current: dict[str, str] | None = dict(initial_fields) if initial_fields else None
|
||||
current_evidence: dict[str, dict[str, Any]] = {}
|
||||
sources: list[int] = []
|
||||
next_offset = initial_next_offset if current is not None else 0
|
||||
current_issues: list[str] = []
|
||||
|
||||
def flush(*, role: Literal['data', 'deleted'] = 'data') -> None:
|
||||
nonlocal current, sources, next_offset, current_issues
|
||||
nonlocal current, current_evidence, sources, next_offset, current_issues
|
||||
if current is not None and (sources or initial_fields):
|
||||
results.append(CoordinateProfileLogicalRow(
|
||||
fields=current, source_row_indices=sources, role=role, issues=current_issues,
|
||||
fields=current, field_evidence=current_evidence,
|
||||
source_row_indices=sources, role=role, issues=current_issues,
|
||||
))
|
||||
current, sources, next_offset, current_issues = None, [], 0, []
|
||||
current, current_evidence, sources, next_offset, current_issues = None, {}, [], 0, []
|
||||
|
||||
for row_index, band in enumerate(_group_visual_rows(glyphs)):
|
||||
text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip()
|
||||
@@ -404,10 +413,11 @@ def reconstruct_coordinate_profile_rows(
|
||||
# the role to exclude it rather than silently losing the document row.
|
||||
flush(role='deleted')
|
||||
continue
|
||||
main_values, main_issues = values_for(band, ordered_layouts[0])
|
||||
main_values, main_evidence, main_issues = values_for(band, ordered_layouts[0])
|
||||
if is_valid_line_start_value(main_values.get(start_field_code, '')):
|
||||
flush()
|
||||
current, sources, next_offset, current_issues = main_values, [row_index], 1, main_issues
|
||||
current, current_evidence = main_values, main_evidence
|
||||
sources, next_offset, current_issues = [row_index], 1, main_issues
|
||||
continue
|
||||
if current is None or next_offset >= len(ordered_layouts):
|
||||
if include_unanchored_rows and main_values:
|
||||
@@ -418,7 +428,7 @@ def reconstruct_coordinate_profile_rows(
|
||||
current_issues.append('coordinate_profile_layout_region_mismatch')
|
||||
flush()
|
||||
continue
|
||||
continuation, continuation_issues = values_for(band, ordered_layouts[next_offset])
|
||||
continuation, continuation_evidence, continuation_issues = values_for(band, ordered_layouts[next_offset])
|
||||
if not continuation:
|
||||
# Once a logical row has started, its declared physical rows must be consecutive.
|
||||
# Continuing after an unexpected region would silently mix two visual records.
|
||||
@@ -432,6 +442,8 @@ def reconstruct_coordinate_profile_rows(
|
||||
current_issues.append(f'coordinate_profile_composite_conflict:{code}')
|
||||
else:
|
||||
current[code] = value
|
||||
if code in continuation_evidence:
|
||||
current_evidence[code] = continuation_evidence[code]
|
||||
sources.append(row_index)
|
||||
current_issues.extend(continuation_issues)
|
||||
next_offset += 1
|
||||
@@ -1310,15 +1322,7 @@ def _text_in_region(
|
||||
return ''
|
||||
widths = [glyph.bbox.x1 - glyph.bbox.x0 for _, glyph in selected]
|
||||
gap_limit = max(1.5, median(widths) * 0.65)
|
||||
result: list[str] = []
|
||||
for index, (_, glyph) in enumerate(selected):
|
||||
if index:
|
||||
previous = selected[index - 1][1]
|
||||
gap = glyph.bbox.x0 - previous.bbox.x1
|
||||
if gap > gap_limit and not result[-1].isspace() and not glyph.text.isspace():
|
||||
result.append(' ')
|
||||
result.append(glyph.text)
|
||||
return ''.join(result).strip()
|
||||
return render_positioned_row([glyph for _, glyph in selected], geometry_gap_limit=gap_limit)
|
||||
|
||||
|
||||
def _text_in_horizontal_region(
|
||||
@@ -1333,15 +1337,7 @@ def _text_in_horizontal_region(
|
||||
return ''
|
||||
widths = [glyph.bbox.x1 - glyph.bbox.x0 for _, glyph in selected]
|
||||
gap_limit = max(1.5, median(widths) * 0.65)
|
||||
result: list[str] = []
|
||||
for index, (_, glyph) in enumerate(selected):
|
||||
if index:
|
||||
previous = selected[index - 1][1]
|
||||
gap = glyph.bbox.x0 - previous.bbox.x1
|
||||
if gap > gap_limit and not result[-1].isspace() and not glyph.text.isspace():
|
||||
result.append(' ')
|
||||
result.append(glyph.text)
|
||||
return ''.join(result).strip()
|
||||
return render_positioned_row([glyph for _, glyph in selected], geometry_gap_limit=gap_limit)
|
||||
|
||||
|
||||
def _normalized_header_text(value: str) -> str:
|
||||
@@ -1461,15 +1457,46 @@ def _field_content_score(text: str, field_code: str | None) -> float:
|
||||
|
||||
|
||||
def _cell_from_glyphs(column_index: int, glyphs: list[tuple[int, PositionedCharacter]]) -> ReconstructedCell:
|
||||
"""合并同一视觉行、同一列的 glyph,保留按页面位置排序的证据索引。"""
|
||||
"""合并同一视觉行、同一列 glyph,保留原始空白和按页面位置排序的证据索引。"""
|
||||
ordered = sorted(glyphs, key=lambda item: item[1].bbox.x0)
|
||||
boxes = [item.bbox for _, item in ordered]
|
||||
return ReconstructedCell(
|
||||
column_index=column_index,
|
||||
text=''.join(item.text for _, item in ordered).strip(),
|
||||
text=render_positioned_row([item for _, item in ordered]),
|
||||
bbox=LayoutBBox(
|
||||
x0=min(item.x0 for item in boxes), y0=min(item.y0 for item in boxes),
|
||||
x1=max(item.x1 for item in boxes), y1=max(item.y1 for item in boxes),
|
||||
),
|
||||
glyph_indices=[index for index, _ in ordered],
|
||||
)
|
||||
|
||||
|
||||
def _field_glyph_evidence(
|
||||
glyphs: list[tuple[int, PositionedCharacter]], *, text: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
汇总字段实际消费的原生字符,供上层 Observation 生成字段级高亮。
|
||||
|
||||
Args:
|
||||
glyphs: 已按字段横向区域筛选的字符及稳定来源索引。
|
||||
text: 字段解析器消费的原始引文。
|
||||
|
||||
Returns:
|
||||
value_bbox、glyph_indices 与独立 bbox_text;无字符时返回空字典。
|
||||
"""
|
||||
if not glyphs:
|
||||
return {}
|
||||
boxes = [glyph.bbox for _, glyph in glyphs]
|
||||
return {
|
||||
'value_bbox': {
|
||||
'x0': min(item.x0 for item in boxes), 'y0': min(item.y0 for item in boxes),
|
||||
'x1': max(item.x1 for item in boxes), 'y1': max(item.y1 for item in boxes),
|
||||
},
|
||||
'glyph_indices': [index for index, _glyph in glyphs],
|
||||
'bbox_text': text[:1000],
|
||||
'quote_source': 'glyph_region',
|
||||
'source': 'pdf_coordinate',
|
||||
'has_value_coordinate': True,
|
||||
'coordinate_status': 'candidate',
|
||||
'highlight_quality': 'candidate',
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/lifecycle.py
|
||||
|
||||
用途:管理 ShippingNoticeDocument 的版面版本、checksum、大小门禁和当前成功快照。
|
||||
用途:管理 ShippingOrderDocument 的版面版本、checksum、大小门禁和当前成功快照。
|
||||
依赖:ShippingDocumentLayoutVersion、Flask 配置、SQLAlchemy Session、workflow_ledger_service
|
||||
(claim/complete/recovery 尽力同步 WorkflowItem,缺 Item 不阻断版面收口)。
|
||||
逻辑:相同内容/parser/checksum 幂等复用;失败版本保留审计,只有可用终态更新 Document 当前引用。
|
||||
@@ -20,7 +20,7 @@ from flask import current_app
|
||||
from sqlalchemy import and_, func, or_, update
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import ShippingDocumentLayoutVersion, ShippingNoticeDocument, ShippingNoticeIntake
|
||||
from app.models import ShippingDocumentLayoutVersion, ShippingOrderDocument, ShippingOrderIntake
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -38,6 +38,34 @@ LAYOUT_FINGERPRINT_FILES = (
|
||||
)
|
||||
CURRENT_LAYOUT_STATUSES = frozenset({'ready', 'needs_review'})
|
||||
TERMINAL_LAYOUT_STATUSES = frozenset({'ready', 'needs_review', 'failed', 'unsupported'})
|
||||
ON_DEMAND_COORDINATE_COMPACTION_ISSUES = frozenset({
|
||||
'shipping_document_layout_page_glyphs_compacted',
|
||||
'shipping_document_layout_table_glyphs_compacted',
|
||||
'shipping_document_layout_page_metadata_compacted',
|
||||
'shipping_document_layout_candidate_glyphs_compacted',
|
||||
'shipping_document_layout_candidate_page_metadata_compacted',
|
||||
})
|
||||
|
||||
|
||||
def _ready_layout_evidence_complete(*, document: ShippingOrderDocument, payload: dict[str, Any]) -> bool:
|
||||
"""判断布局快照是否可直接使用,或可由原 PDF 在订单识别时按需恢复。"""
|
||||
if str(payload.get('provider') or '') == 'xfa':
|
||||
capability = payload.get('xfa_capability') if isinstance(payload.get('xfa_capability'), dict) else {}
|
||||
return bool(capability.get('structure_analysis_ready')) and str(payload.get('status') or '') == 'ready'
|
||||
if Path(str(document.filename or '')).suffix.lower() != '.pdf':
|
||||
return True
|
||||
evidence = payload.get('coordinate_evidence') if isinstance(payload.get('coordinate_evidence'), dict) else {}
|
||||
complete = isinstance(evidence.get('pages'), dict) and isinstance(evidence.get('page_glyphs'), dict)
|
||||
recoverable = bool(document.asset_id) and isinstance(payload.get('layout_candidate'), dict)
|
||||
return complete or recoverable
|
||||
|
||||
|
||||
def _layout_version_reusable(*, document: ShippingOrderDocument, version: ShippingDocumentLayoutVersion) -> bool:
|
||||
"""仅复用可直接读取或能从原附件按需恢复坐标的成功布局版本。"""
|
||||
if str(version.status or '') not in CURRENT_LAYOUT_STATUSES:
|
||||
return False
|
||||
payload = version.payload_json if isinstance(version.payload_json, dict) else {}
|
||||
return _ready_layout_evidence_complete(document=document, payload=payload)
|
||||
|
||||
|
||||
def _conversation_id_for_document(document_id: int) -> str | None:
|
||||
@@ -45,15 +73,15 @@ def _conversation_id_for_document(document_id: int) -> str | None:
|
||||
从 Document → Intake 解析会话 ID,供 WorkflowItem 定位。
|
||||
|
||||
Args:
|
||||
document_id: ShippingNoticeDocument 主键。
|
||||
document_id: ShippingOrderDocument 主键。
|
||||
|
||||
Returns:
|
||||
conversation_id 或 None。
|
||||
"""
|
||||
row = (
|
||||
db.session.query(ShippingNoticeIntake.conversation_id)
|
||||
.join(ShippingNoticeDocument, ShippingNoticeDocument.intake_id == ShippingNoticeIntake.id)
|
||||
.filter(ShippingNoticeDocument.id == int(document_id))
|
||||
db.session.query(ShippingOrderIntake.conversation_id)
|
||||
.join(ShippingOrderDocument, ShippingOrderDocument.intake_id == ShippingOrderIntake.id)
|
||||
.filter(ShippingOrderDocument.id == int(document_id))
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
@@ -70,65 +98,15 @@ def _sync_workflow_item_for_layout(
|
||||
reason: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
尽力同步版面阶段的 WorkflowItem 状态/事件;Item 缺失时仅记日志。
|
||||
历史:同步版面阶段 WorkflowItem;co8 后台账已 DROP,本函数为 no-op。
|
||||
|
||||
Args:
|
||||
document_id: 版面所属 Document。
|
||||
lifecycle_status: 可选目标生命周期(queued/layout_parsing/failed 等)。
|
||||
event_code: 可选用户可见事件码(如 layout_completed)。
|
||||
reason: 迁移理由。
|
||||
document_id: 版面所属 Document(忽略)。
|
||||
lifecycle_status: 忽略。
|
||||
event_code: 忽略。
|
||||
reason: 忽略。
|
||||
"""
|
||||
try:
|
||||
from app.models.shipping_notice_workflow import ShippingNoticeWorkflow
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
append_workflow_event,
|
||||
find_item_by_root,
|
||||
transition_item_status,
|
||||
)
|
||||
|
||||
conversation_id = _conversation_id_for_document(int(document_id))
|
||||
if not conversation_id:
|
||||
return
|
||||
item = find_item_by_root(
|
||||
conversation_id=conversation_id,
|
||||
root_document_id=int(document_id),
|
||||
for_update=True,
|
||||
)
|
||||
if item is None:
|
||||
return
|
||||
if lifecycle_status and str(item.lifecycle_status or '') != str(lifecycle_status):
|
||||
if str(item.lifecycle_status or '') not in {
|
||||
'closed', 'cancelled', 'manual_upload_pending', 'pending_review',
|
||||
}:
|
||||
transition_item_status(
|
||||
item=item,
|
||||
lifecycle_status=str(lifecycle_status),
|
||||
stage=str(lifecycle_status),
|
||||
actor_type='system',
|
||||
actor_id='layout',
|
||||
reason=reason or f'layout:{lifecycle_status}',
|
||||
)
|
||||
if event_code:
|
||||
workflow = db.session.get(ShippingNoticeWorkflow, int(item.workflow_id))
|
||||
if workflow is not None:
|
||||
append_workflow_event(
|
||||
workflow=workflow,
|
||||
item=item,
|
||||
event_code=str(event_code),
|
||||
stage_code=str(item.current_stage or item.lifecycle_status),
|
||||
message_code=f'shipping.workflow_item.{event_code}',
|
||||
actor_type='system',
|
||||
actor_id='layout',
|
||||
payload={'document_id': int(document_id)},
|
||||
reason=reason,
|
||||
)
|
||||
except Exception:
|
||||
_LOGGER.exception(
|
||||
'layout workflow sync skipped document_id=%s status=%s event=%s',
|
||||
document_id,
|
||||
lifecycle_status,
|
||||
event_code,
|
||||
)
|
||||
del document_id, lifecycle_status, event_code, reason
|
||||
|
||||
|
||||
def layout_parser_implementation_fingerprint() -> str:
|
||||
@@ -176,8 +154,8 @@ def _fit_layout_payload_to_budget(
|
||||
) -> tuple[dict[str, Any] | None, list[str], int]:
|
||||
"""按证据优先级压缩布局快照,避免可重建证据阻断业务表保存。
|
||||
|
||||
核心逻辑:表格 HTML/结构是模板建模的核心;整页 glyph、文本块和页面尺寸
|
||||
属于可选证据。压缩过程只删除可重建字段,并返回最终大小与诊断码。
|
||||
核心逻辑:表格 HTML/结构是模板建模的核心;整页/表内 glyph、文本块和页面尺寸
|
||||
属于可从原 PDF 按需恢复的证据。压缩过程只删除可重建字段,并返回最终大小与诊断码。
|
||||
"""
|
||||
candidate = json.loads(json.dumps(payload, ensure_ascii=True))
|
||||
issues: list[str] = []
|
||||
@@ -185,16 +163,6 @@ def _fit_layout_payload_to_budget(
|
||||
if size <= max_bytes:
|
||||
return candidate, issues, size
|
||||
|
||||
evidence = candidate.get('coordinate_evidence')
|
||||
if isinstance(evidence, dict):
|
||||
if evidence.pop('page_glyphs', None) is not None:
|
||||
issues.append('shipping_document_layout_page_glyphs_compacted')
|
||||
if evidence.pop('pages', None) is not None:
|
||||
issues.append('shipping_document_layout_page_metadata_compacted')
|
||||
_, size = canonical_layout_payload(candidate)
|
||||
if size <= max_bytes:
|
||||
return candidate, issues, size
|
||||
|
||||
if candidate.pop('text_blocks', None) is not None:
|
||||
issues.append('shipping_document_layout_text_blocks_compacted')
|
||||
_, size = canonical_layout_payload(candidate)
|
||||
@@ -208,12 +176,22 @@ def _fit_layout_payload_to_budget(
|
||||
if layout_candidate.pop('pages', None) is not None:
|
||||
issues.append('shipping_document_layout_candidate_page_metadata_compacted')
|
||||
_, size = canonical_layout_payload(candidate)
|
||||
if size <= max_bytes:
|
||||
return candidate, issues, size
|
||||
|
||||
coordinate_evidence = candidate.get('coordinate_evidence')
|
||||
if isinstance(coordinate_evidence, dict):
|
||||
if coordinate_evidence.pop('page_glyphs', None) is not None:
|
||||
issues.append('shipping_document_layout_page_glyphs_compacted')
|
||||
if coordinate_evidence.pop('tables', None) is not None:
|
||||
issues.append('shipping_document_layout_table_glyphs_compacted')
|
||||
_, size = canonical_layout_payload(candidate)
|
||||
if size <= max_bytes:
|
||||
return candidate, issues, size
|
||||
return None, issues + ['shipping_document_layout_snapshot_size_exceeded'], size
|
||||
|
||||
|
||||
def current_layout_snapshot(document: ShippingNoticeDocument) -> dict[str, Any] | None:
|
||||
def current_layout_snapshot(document: ShippingOrderDocument) -> dict[str, Any] | None:
|
||||
"""读取 Document 当前可用冻结 payload;失败历史版本永不作为运行输入。"""
|
||||
version = document.current_layout_version
|
||||
if (
|
||||
@@ -226,7 +204,7 @@ def current_layout_snapshot(document: ShippingNoticeDocument) -> dict[str, Any]
|
||||
|
||||
|
||||
def record_inline_layout_snapshot(
|
||||
document: ShippingNoticeDocument,
|
||||
document: ShippingOrderDocument,
|
||||
snapshot: dict[str, Any],
|
||||
*,
|
||||
parser_key: str | None = None,
|
||||
@@ -276,6 +254,8 @@ def record_inline_layout_snapshot(
|
||||
'ready', 'needs_review', 'failed', 'unsupported',
|
||||
} else 'failed'
|
||||
issues = sorted({str(item) for item in (payload.get('issues') or []) if str(item)} | set(compact_issues))
|
||||
if status == 'ready' and ON_DEMAND_COORDINATE_COMPACTION_ISSUES.intersection(compact_issues):
|
||||
issues = sorted(set(issues) | {'shipping_document_layout_coordinate_evidence_on_demand'})
|
||||
stored_payload: dict[str, Any] | None = fitted_payload
|
||||
if stored_payload is None:
|
||||
status = 'failed'
|
||||
@@ -309,7 +289,7 @@ def record_inline_layout_snapshot(
|
||||
|
||||
|
||||
def _clone_reusable_layout_for_document(
|
||||
document: ShippingNoticeDocument,
|
||||
document: ShippingOrderDocument,
|
||||
reusable: ShippingDocumentLayoutVersion,
|
||||
) -> ShippingDocumentLayoutVersion | None:
|
||||
"""
|
||||
@@ -335,7 +315,7 @@ def _clone_reusable_layout_for_document(
|
||||
|
||||
|
||||
def schedule_layout_version(
|
||||
document: ShippingNoticeDocument,
|
||||
document: ShippingOrderDocument,
|
||||
*,
|
||||
force: bool = False,
|
||||
created_by_id: int | None = None,
|
||||
@@ -355,22 +335,27 @@ def schedule_layout_version(
|
||||
if len(source_hash) != 64:
|
||||
return None
|
||||
# Identical files from the same owner reuse a completed layout rather than waiting for MinerU again.
|
||||
owner_id = db.session.query(ShippingNoticeIntake.user_id).filter(
|
||||
ShippingNoticeIntake.id == document.intake_id,
|
||||
owner_id = db.session.query(ShippingOrderIntake.user_id).filter(
|
||||
ShippingOrderIntake.id == document.intake_id,
|
||||
).scalar()
|
||||
if not force:
|
||||
reusable_from_owner = (
|
||||
ShippingDocumentLayoutVersion.query
|
||||
.join(ShippingNoticeDocument, ShippingNoticeDocument.id == ShippingDocumentLayoutVersion.document_id)
|
||||
.join(ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeDocument.intake_id)
|
||||
.join(ShippingOrderDocument, ShippingOrderDocument.id == ShippingDocumentLayoutVersion.document_id)
|
||||
.join(ShippingOrderIntake, ShippingOrderIntake.id == ShippingOrderDocument.intake_id)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == owner_id,
|
||||
ShippingNoticeDocument.content_hash == source_hash,
|
||||
ShippingOrderIntake.user_id == owner_id,
|
||||
ShippingOrderDocument.content_hash == source_hash,
|
||||
ShippingDocumentLayoutVersion.parser_key == current_layout_parser_key(),
|
||||
ShippingDocumentLayoutVersion.status.in_(tuple(CURRENT_LAYOUT_STATUSES)),
|
||||
)
|
||||
.order_by(ShippingDocumentLayoutVersion.finished_at.desc(), ShippingDocumentLayoutVersion.id.desc())
|
||||
.first()
|
||||
.all()
|
||||
)
|
||||
reusable_from_owner = next(
|
||||
(version for version in reusable_from_owner
|
||||
if _layout_version_reusable(document=document, version=version)),
|
||||
None,
|
||||
)
|
||||
if reusable_from_owner is not None:
|
||||
localized = _clone_reusable_layout_for_document(document, reusable_from_owner)
|
||||
@@ -383,12 +368,17 @@ def schedule_layout_version(
|
||||
if active is not None:
|
||||
return active
|
||||
if not force:
|
||||
reusable = ShippingDocumentLayoutVersion.query.filter_by(
|
||||
reusable_candidates = ShippingDocumentLayoutVersion.query.filter_by(
|
||||
document_id=int(document.id), source_content_hash=source_hash,
|
||||
parser_key=current_layout_parser_key(),
|
||||
).filter(ShippingDocumentLayoutVersion.status.in_(tuple(CURRENT_LAYOUT_STATUSES))).order_by(
|
||||
ShippingDocumentLayoutVersion.version.desc(),
|
||||
).first()
|
||||
).all()
|
||||
reusable = next(
|
||||
(version for version in reusable_candidates
|
||||
if _layout_version_reusable(document=document, version=version)),
|
||||
None,
|
||||
)
|
||||
if reusable is not None:
|
||||
document.current_layout_version_id = reusable.id
|
||||
return reusable
|
||||
@@ -416,7 +406,7 @@ def schedule_layout_version(
|
||||
|
||||
|
||||
def schedule_document_layouts(
|
||||
documents: list[ShippingNoticeDocument], *, created_by_id: int | None = None,
|
||||
documents: list[ShippingOrderDocument], *, created_by_id: int | None = None,
|
||||
) -> list[ShippingDocumentLayoutVersion]:
|
||||
"""在 Document 持久化事务内为支持附件建立独立布局版本,超量文档保留 skipped 审计。"""
|
||||
from pathlib import Path
|
||||
@@ -424,7 +414,7 @@ def schedule_document_layouts(
|
||||
from app.services.shipping_notice.document_layout.mineru import MINERU_SUPPORTED_EXTENSIONS
|
||||
|
||||
max_documents = max(int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 4,
|
||||
'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 10,
|
||||
)), 0)
|
||||
eligible = [
|
||||
item for item in documents
|
||||
@@ -495,7 +485,7 @@ def serialize_layout_version(version: ShippingDocumentLayoutVersion) -> dict[str
|
||||
|
||||
def list_layout_versions(document_id: int) -> list[dict[str, Any]]:
|
||||
"""列出一个 Document 的布局版本安全摘要。"""
|
||||
document = db.session.get(ShippingNoticeDocument, int(document_id))
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
if document is None:
|
||||
from app.core.errors import NotFoundError
|
||||
|
||||
@@ -511,7 +501,7 @@ def request_layout_reparse(
|
||||
document_id: int, *, created_by_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""管理员显式创建下一布局版本;活动版本存在时幂等返回同一版本。"""
|
||||
document = db.session.get(ShippingNoticeDocument, int(document_id))
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
if document is None:
|
||||
from app.core.errors import NotFoundError
|
||||
|
||||
@@ -591,6 +581,14 @@ def complete_layout_version(
|
||||
issues = sorted({str(item) for item in (snapshot.get('issues') or []) if str(item)} | set(compact_issues))
|
||||
provider_status = str(snapshot.get('status') or 'failed')
|
||||
status = provider_status if provider_status in TERMINAL_LAYOUT_STATUSES else 'failed'
|
||||
if status == 'ready' and not _ready_layout_evidence_complete(
|
||||
document=version.document, payload=snapshot,
|
||||
):
|
||||
status = 'failed'
|
||||
issues = sorted(set(issues) | {'shipping_document_layout_coordinate_evidence_incomplete'})
|
||||
elif status == 'ready' and ON_DEMAND_COORDINATE_COMPACTION_ISSUES.intersection(compact_issues):
|
||||
# [STEP] 快照压缩只影响持久化体积;原 PDF 仍可读时由订单识别按需恢复坐标。
|
||||
issues = sorted(set(issues) | {'shipping_document_layout_coordinate_evidence_on_demand'})
|
||||
stored_payload: dict[str, Any] | None = fitted_snapshot
|
||||
if stored_payload is None:
|
||||
status = 'failed'
|
||||
|
||||
@@ -73,7 +73,10 @@ def extract_native_pdf_pages(
|
||||
content: bytes, *, render_scale: float = 2.0, render_images: bool = True,
|
||||
) -> list[NativePdfPage]:
|
||||
"""
|
||||
从 PDF bytes 提取左上原点字符坐标和页面图。
|
||||
从 PDF bytes 提取左上原点字符坐标、原始文本流边界和页面图。
|
||||
|
||||
核心逻辑:可见字符保留 PDFium 原始 char_index;零 bbox 空白不生成伪坐标,
|
||||
而是记录到下一个有效字符的 boundary_before,供文本重建优先于几何猜测使用。
|
||||
|
||||
Args:
|
||||
content: 原始 PDF 字节,不写文件和日志。
|
||||
@@ -93,12 +96,21 @@ def extract_native_pdf_pages(
|
||||
width, height = page.get_size()
|
||||
text_page = page.get_textpage()
|
||||
characters: list[PositionedCharacter] = []
|
||||
pending_boundary: str = 'none'
|
||||
for char_index in range(text_page.count_chars()):
|
||||
text = text_page.get_text_range(char_index, 1)
|
||||
if not text or not normalize_layout_text(text):
|
||||
if not text:
|
||||
continue
|
||||
if not normalize_layout_text(text):
|
||||
if any(character in {'\r', '\n'} for character in text):
|
||||
pending_boundary = 'line_break'
|
||||
elif pending_boundary == 'none' and any(character.isspace() for character in text):
|
||||
pending_boundary = 'space'
|
||||
continue
|
||||
left, bottom, right, top = text_page.get_charbox(char_index, loose=True)
|
||||
if right <= left or top <= bottom:
|
||||
# 非空白可见字符若无有效坐标,不得把之前的空白错误转嫁到后续字符。
|
||||
pending_boundary = 'none'
|
||||
continue
|
||||
try:
|
||||
# 不修改 PDFium 原始坐标;仅转为左上原点页面坐标。
|
||||
@@ -107,9 +119,12 @@ def extract_native_pdf_pages(
|
||||
bbox=LayoutBBox(
|
||||
x0=left, y0=height - top, x1=right, y1=height - bottom,
|
||||
),
|
||||
source_index=len(characters),
|
||||
source_index=char_index,
|
||||
boundary_before=pending_boundary,
|
||||
))
|
||||
pending_boundary = 'none'
|
||||
except ValueError:
|
||||
pending_boundary = 'none'
|
||||
continue
|
||||
characters = _assign_page_line_ids(characters, page_no=page_index + 1)
|
||||
rotation = int(getattr(page, 'get_rotation', lambda: 0)() or 0) % 360
|
||||
@@ -316,7 +331,7 @@ def build_native_pdf_layout_candidate(
|
||||
组合 MinerU HTML 与 PDFium 独立证据,生成始终 needs_review 的 layout.v1 候选。
|
||||
|
||||
Args:
|
||||
document_id: 当前 ShippingNoticeDocument 主键。
|
||||
document_id: 当前 ShippingOrderDocument 主键。
|
||||
content_hash: 当前附件 SHA-256,用于稳定 ID 和契约校验。
|
||||
content: 原始 PDF 字节。
|
||||
mineru: 同一文件的 MinerU pipeline 候选。
|
||||
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
"""按需从原始 PDF 恢复坐标证据;不改变上传阶段的轻量布局快照。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import FileAsset, ShippingOrderDocument
|
||||
|
||||
|
||||
def _coordinate_mapping(value: Any) -> dict[str, Any]:
|
||||
"""仅接受坐标证据的键值映射;业务表格列表不得被 `dict(...)` 误解释。"""
|
||||
return dict(value) if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def ensure_on_demand_coordinate_evidence(
|
||||
*, document: ShippingOrderDocument, layout: dict[str, Any], page_nos: set[int] | None,
|
||||
table_by_page: dict[int, dict[str, Any] | list[dict[str, Any]]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""为盲测和正式抽取恢复所需页坐标;同页多表必须分别保留字符证据。"""
|
||||
if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
|
||||
return layout
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
# 兼容历史布局快照:布局任务曾将坐标证据写在顶层,正式抽取仍需复用它。
|
||||
if not evidence:
|
||||
legacy_keys = ('pages', 'page_glyphs', 'sources', 'tables')
|
||||
evidence = {
|
||||
key: layout.get(key)
|
||||
for key in legacy_keys
|
||||
if isinstance(layout.get(key), dict)
|
||||
}
|
||||
# Run 快照可能早于最近一次布局重试;读取当前成功/失败版本仅作本次内存补充。
|
||||
current_version = getattr(document, 'current_layout_version', None)
|
||||
current_payload = getattr(current_version, 'payload_json', None)
|
||||
if isinstance(current_payload, dict):
|
||||
current_evidence = current_payload.get('coordinate_evidence')
|
||||
if isinstance(current_evidence, dict):
|
||||
evidence = {**current_evidence, **evidence}
|
||||
for key in ('pages', 'page_glyphs', 'sources', 'tables'):
|
||||
if key not in evidence and isinstance(current_payload.get(key), dict):
|
||||
evidence[key] = current_payload[key]
|
||||
pages = _coordinate_mapping(evidence.get('pages'))
|
||||
page_glyphs = _coordinate_mapping(evidence.get('page_glyphs'))
|
||||
sources = _coordinate_mapping(evidence.get('sources'))
|
||||
source_pages = _coordinate_mapping(sources.get('pages'))
|
||||
tables = _coordinate_mapping(evidence.get('tables'))
|
||||
if page_nos is not None and page_nos.issubset({int(p) for p in page_glyphs if str(p).isdigit()}):
|
||||
return layout
|
||||
tables_by_page: dict[int, list[dict[str, Any]]] = {}
|
||||
for raw_table in layout.get('tables') or []:
|
||||
if not isinstance(raw_table, dict):
|
||||
continue
|
||||
tables_by_page.setdefault(int(raw_table.get('page_no') or 1), []).append(raw_table)
|
||||
for raw_page_no, raw_tables in (table_by_page or {}).items():
|
||||
candidates = raw_tables if isinstance(raw_tables, list) else [raw_tables]
|
||||
page_tables = tables_by_page.setdefault(int(raw_page_no), [])
|
||||
existing_ids = {str(item.get('table_id') or '') for item in page_tables}
|
||||
for raw_table in candidates:
|
||||
if not isinstance(raw_table, dict):
|
||||
continue
|
||||
table_id = str(raw_table.get('table_id') or '')
|
||||
if table_id and table_id not in existing_ids:
|
||||
page_tables.append(raw_table)
|
||||
existing_ids.add(table_id)
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages
|
||||
from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines
|
||||
from app.services.shipping_notice.order_document_profile_service import (
|
||||
_native_characters_in_table, _ocr_lines_to_characters, _ocr_lines_to_page_characters,
|
||||
)
|
||||
asset = db.session.get(FileAsset, int(document.asset_id))
|
||||
if asset is None:
|
||||
return layout
|
||||
try:
|
||||
native_pages = extract_native_pdf_pages(read_asset_bytes(asset))
|
||||
except Exception:
|
||||
return layout
|
||||
for page in native_pages:
|
||||
if page_nos is not None and int(page.page_no) not in page_nos:
|
||||
continue
|
||||
glyphs = [item.model_dump(mode='json') for item in getattr(page, 'characters', []) or []]
|
||||
source = 'pdf_coordinate'
|
||||
if not glyphs:
|
||||
try:
|
||||
lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height)
|
||||
glyphs = _ocr_lines_to_page_characters(lines=lines)
|
||||
source = 'ocr_coordinate'
|
||||
except Exception:
|
||||
glyphs = []
|
||||
if not glyphs:
|
||||
continue
|
||||
page_key = str(page.page_no)
|
||||
pages[page_key] = {'width': page.width, 'height': page.height}
|
||||
page_glyphs[page_key] = glyphs
|
||||
source_pages[page_key] = source
|
||||
for table in tables_by_page.get(int(page.page_no), []):
|
||||
table_id = str(table.get('table_id') or '')
|
||||
chars = _native_characters_in_table(
|
||||
characters=list(getattr(page, 'characters', []) or []),
|
||||
table_bbox=table.get('bbox') or {},
|
||||
)
|
||||
if not chars:
|
||||
try:
|
||||
lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height)
|
||||
chars = _ocr_lines_to_characters(lines=lines, table_bbox=table.get('bbox') or {})
|
||||
except Exception:
|
||||
chars = []
|
||||
if table_id and chars:
|
||||
tables[table_id] = chars
|
||||
next_layout = dict(layout)
|
||||
next_layout['coordinate_evidence'] = {
|
||||
**evidence, 'pages': pages, 'page_glyphs': page_glyphs,
|
||||
'tables': tables, 'sources': {**sources, 'pages': source_pages},
|
||||
}
|
||||
return next_layout
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/shipping_notice/document_layout/order_field_extraction.py
|
||||
|
||||
用途:从冻结的整页 PDF/OCR 字符坐标中确定性提取独立订单级字段。
|
||||
依赖:OrderCoordinateProfileV2、冻结 Schema 字段规则和 LayoutBBox。
|
||||
依赖:OrderCoordinateProfile、冻结 Schema 字段规则和 LayoutBBox。
|
||||
逻辑:订单工作流先唯一匹配模板,再调用本模块;本模块仅返回可追溯候选,绝不回读资产、数据库或调用模型。
|
||||
"""
|
||||
|
||||
@@ -14,10 +14,11 @@ from typing import Any, Literal
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import render_positioned_row
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
AnchorRelativeRegion,
|
||||
AnchorRule,
|
||||
OrderCoordinateProfileV2,
|
||||
OrderCoordinateProfile,
|
||||
OrderFieldLayout,
|
||||
RelativeRegion,
|
||||
)
|
||||
@@ -46,14 +47,14 @@ class OrderFieldExtraction(BaseModel):
|
||||
|
||||
|
||||
def extract_order_fields(
|
||||
*, profile: OrderCoordinateProfileV2, schema_fields: dict[str, dict[str, Any]],
|
||||
*, profile: OrderCoordinateProfile, schema_fields: dict[str, dict[str, Any]],
|
||||
coordinate_evidence: dict[str, Any],
|
||||
) -> list[OrderFieldExtraction]:
|
||||
"""
|
||||
用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。
|
||||
|
||||
Args:
|
||||
profile: Run 冻结的 v2 坐标模板,不得包含待重新绑定字段。
|
||||
profile: Run 冻结的坐标模板,不得包含待重新绑定字段。
|
||||
schema_fields: 以 stable field_id 为键的冻结启用 Schema 字段。
|
||||
coordinate_evidence: 冻结页尺寸、page_glyphs 与来源;不接受表格内 glyph 兜底。
|
||||
|
||||
@@ -405,18 +406,14 @@ def _render_value(selected: list[tuple[int, dict[str, Any]]], *, multi_line: boo
|
||||
|
||||
|
||||
def _render_visual_row(row: list[tuple[int, dict[str, Any]]]) -> str:
|
||||
"""以字距推断缺失的 PDF 空白;仅大于常规字符间隔时补一个普通空格。"""
|
||||
rendered: list[str] = []
|
||||
previous: LayoutBBox | None = None
|
||||
for _index, glyph in row:
|
||||
bbox = _glyph_bbox(glyph)
|
||||
if previous is not None:
|
||||
typical_width = max((previous.x1 - previous.x0 + bbox.x1 - bbox.x0) / 2, 0.01)
|
||||
if bbox.x0 - previous.x1 > typical_width * 0.75:
|
||||
rendered.append(' ')
|
||||
rendered.append(str(glyph.get('text') or ''))
|
||||
previous = bbox
|
||||
return ''.join(rendered).strip()
|
||||
"""优先恢复原始 PDF 空白;旧证据继续沿用既有平均字宽阈值,避免模板行为漂移。"""
|
||||
glyphs = [glyph for _index, glyph in row]
|
||||
return render_positioned_row(
|
||||
glyphs,
|
||||
geometry_gap_ratio=0.75,
|
||||
geometry_width_mode='average',
|
||||
minimum_gap_limit=0.01,
|
||||
)
|
||||
|
||||
|
||||
def _visual_rows(items: list[tuple[int, dict[str, Any]]]) -> list[list[tuple[int, dict[str, Any]]]]:
|
||||
|
||||
@@ -1,38 +1,26 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/order_profile.py
|
||||
|
||||
用途:定义订单文档坐标模板 v2 的纯契约和受控字段绑定。
|
||||
用途:定义唯一的订单文档坐标模板契约与 v2 版面签名匹配评分维度。
|
||||
依赖:Pydantic、坐标 bbox 契约、订单字段规则和已注册解析器。
|
||||
逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;运行时匹配器与坐标解析器只消费该不可变定义。
|
||||
逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;order_profile_matcher 消费
|
||||
DocumentMatchProfile 分项权重与 negative_anchors;order_profile_signature 生成
|
||||
matching_signature 供运行时硬门禁与维度比对。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
from decimal import Decimal
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.html_table import HtmlGrid, parse_html_grid
|
||||
from app.services.shipping_notice.notice_line_values import parse_number
|
||||
from app.services.shipping_notice.notice_lines import resolve_composite_part_numbers
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
normalize_order_field_value,
|
||||
validate_order_field_value,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import (
|
||||
TableHeaderContract,
|
||||
normalize_table_header,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_table import HtmlGrid
|
||||
|
||||
|
||||
ORDER_PROFILE_VERSION = 'order_coordinate_profile.v2'
|
||||
PROFILE_EXTRACTORS = frozenset({'direct', 'temp_internal_parts', 'quantity_uom', 'amount_currency', 'price_currency'})
|
||||
HEADER_LINE_ITEM_VALUE_PATTERN = re.compile(
|
||||
r'\b(?:item|line)\s*(?:no\.?|number|#)?\s*[:#-]?\s*0{2,}\d+\b',
|
||||
@@ -319,27 +307,64 @@ class TableRegionProfile(OrderProfileModel):
|
||||
|
||||
|
||||
SCORING_DIMENSION_KEYS = (
|
||||
'table_topology',
|
||||
'row_structure',
|
||||
'anchor_geometry',
|
||||
'header_regions',
|
||||
'header_semantic_position',
|
||||
'column_topology',
|
||||
'table_geometry',
|
||||
'page_structure',
|
||||
'header_path',
|
||||
'customer_hint',
|
||||
'field_spatial_relation',
|
||||
'optional_static_text',
|
||||
'trusted_business_context',
|
||||
)
|
||||
CRITICAL_STRUCTURE_DIMENSION_KEYS = ('table_topology', 'row_structure', 'anchor_geometry')
|
||||
CRITICAL_STRUCTURE_DIMENSION_KEYS = (
|
||||
'header_semantic_position',
|
||||
'column_topology',
|
||||
'table_geometry',
|
||||
)
|
||||
# 历史 v1 权重键 → v2 键;供 model_validator 迁移旧模板配置。
|
||||
_LEGACY_SCORING_WEIGHT_KEYS: dict[str, str] = {
|
||||
'table_topology': 'column_topology',
|
||||
'row_structure': 'table_geometry',
|
||||
'anchor_geometry': 'header_semantic_position',
|
||||
'header_regions': 'field_spatial_relation',
|
||||
'page_structure': 'page_structure',
|
||||
'header_path': 'optional_static_text',
|
||||
'customer_hint': 'trusted_business_context',
|
||||
}
|
||||
|
||||
MatchDimensionState = Literal['matched', 'mismatched', 'unavailable']
|
||||
|
||||
|
||||
class MatchDimensionResult(OrderProfileModel):
|
||||
"""单维匹配结果:三态 + 0~1 得分;unavailable 不计入相似度分母。"""
|
||||
|
||||
state: MatchDimensionState
|
||||
score: float = Field(ge=0, le=1)
|
||||
|
||||
|
||||
class ProfileScoringWeights(OrderProfileModel):
|
||||
"""分项权重;七维之和必须为 1.0,供 matcher 加权汇总确定性评分。"""
|
||||
"""v2 分项权重;七维之和必须为 1.0,供 matcher 加权汇总确定性评分。"""
|
||||
|
||||
table_topology: float = Field(default=0.25, ge=0, le=1)
|
||||
row_structure: float = Field(default=0.20, ge=0, le=1)
|
||||
anchor_geometry: float = Field(default=0.20, ge=0, le=1)
|
||||
header_regions: float = Field(default=0.10, ge=0, le=1)
|
||||
header_semantic_position: float = Field(default=0.30, ge=0, le=1)
|
||||
column_topology: float = Field(default=0.25, ge=0, le=1)
|
||||
table_geometry: float = Field(default=0.15, ge=0, le=1)
|
||||
page_structure: float = Field(default=0.10, ge=0, le=1)
|
||||
header_path: float = Field(default=0.10, ge=0, le=1)
|
||||
customer_hint: float = Field(default=0.05, ge=0, le=1)
|
||||
field_spatial_relation: float = Field(default=0.10, ge=0, le=1)
|
||||
optional_static_text: float = Field(default=0.05, ge=0, le=1)
|
||||
trusted_business_context: float = Field(default=0.05, ge=0, le=1)
|
||||
|
||||
@model_validator(mode='before')
|
||||
@classmethod
|
||||
def migrate_legacy_weight_keys(cls, value: Any) -> Any:
|
||||
"""将 v1 七维权重键映射为 v2,避免历史模板在升级前无法解析。"""
|
||||
if not isinstance(value, dict):
|
||||
return value
|
||||
if any(key in value for key in SCORING_DIMENSION_KEYS):
|
||||
return value
|
||||
migrated = dict(value)
|
||||
for legacy_key, new_key in _LEGACY_SCORING_WEIGHT_KEYS.items():
|
||||
if legacy_key in migrated and new_key not in migrated:
|
||||
migrated[new_key] = migrated.pop(legacy_key)
|
||||
return migrated
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_weight_sum(self) -> 'ProfileScoringWeights':
|
||||
@@ -351,10 +376,11 @@ class ProfileScoringWeights(OrderProfileModel):
|
||||
|
||||
|
||||
class ProfileScoringThresholds(OrderProfileModel):
|
||||
"""自动决胜与关键结构单项阈值;与 minimum_score/minimum_margin 并存,服务多候选评分决胜。"""
|
||||
"""自动决胜阈值;evidence_coverage_minimum 与 matcher 硬门禁对齐。"""
|
||||
|
||||
auto_select_minimum_score: float = Field(default=0.95, ge=0, le=1)
|
||||
auto_select_minimum_margin: float = Field(default=0.15, ge=0, le=1)
|
||||
auto_select_minimum_score: float = Field(default=0.90, ge=0, le=1)
|
||||
auto_select_minimum_margin: float = Field(default=0.12, ge=0, le=1)
|
||||
evidence_coverage_minimum: float = Field(default=0.70, ge=0, le=1)
|
||||
critical_structure_minimum: float = Field(default=0.90, ge=0, le=1)
|
||||
|
||||
|
||||
@@ -378,24 +404,26 @@ class DocumentMatchProfile(OrderProfileModel):
|
||||
page_pattern: Literal['one_or_more'] = 'one_or_more'
|
||||
required_anchors: list[DocumentMatchAnchor] = Field(default_factory=list)
|
||||
optional_anchors: list[DocumentMatchAnchor] = Field(default_factory=list)
|
||||
negative_anchors: list[DocumentMatchAnchor] = Field(default_factory=list)
|
||||
minimum_score: float = Field(default=0.9, ge=0, le=1)
|
||||
minimum_margin: float = Field(default=0.15, ge=0, le=1)
|
||||
minimum_margin: float = Field(default=0.12, ge=0, le=1)
|
||||
scoring_weights: ProfileScoringWeights = Field(default_factory=ProfileScoringWeights)
|
||||
scoring_thresholds: ProfileScoringThresholds = Field(default_factory=ProfileScoringThresholds)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_anchor_ids(self) -> 'DocumentMatchProfile':
|
||||
"""要求必选和可选锚点名称唯一,避免评分器使用含糊证据。"""
|
||||
ids = [item.anchor_id for item in self.required_anchors + self.optional_anchors]
|
||||
"""要求必选、可选与排除锚点名称唯一,避免评分器使用含糊证据。"""
|
||||
ids = [
|
||||
item.anchor_id
|
||||
for item in self.required_anchors + self.optional_anchors + self.negative_anchors
|
||||
]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError('document match anchor ids must be unique')
|
||||
return self
|
||||
|
||||
|
||||
class OrderCoordinateProfileV2(OrderProfileModel):
|
||||
"""保存阶段 0 评审中的订单坐标模板 v2 定义,尚未接入旧运行路径。"""
|
||||
|
||||
contract_version: Literal[ORDER_PROFILE_VERSION] = ORDER_PROFILE_VERSION
|
||||
class OrderCoordinateProfile(OrderProfileModel):
|
||||
"""唯一的订单坐标模板定义;运行时和管理端只消费这一种契约。"""
|
||||
profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
|
||||
version: int = Field(ge=1)
|
||||
document_match: DocumentMatchProfile
|
||||
@@ -404,7 +432,7 @@ class OrderCoordinateProfileV2(OrderProfileModel):
|
||||
draft_unbound_order_field_layouts: list[DraftUnboundOrderFieldLayout] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_profile_rules(self) -> 'OrderCoordinateProfileV2':
|
||||
def validate_profile_rules(self) -> 'OrderCoordinateProfile':
|
||||
"""阻断重复表区和重叠表区,确保一个字段位置只有唯一模板解释。"""
|
||||
ids = [item.region_id for item in self.table_regions]
|
||||
if len(ids) != len(set(ids)):
|
||||
@@ -414,7 +442,14 @@ class OrderCoordinateProfileV2(OrderProfileModel):
|
||||
# Different exact pages may use identical coordinates without competing at runtime.
|
||||
if _table_regions_can_apply_same_page(left, right):
|
||||
_validate_non_overlapping_regions([left.region, right.region])
|
||||
anchor_ids = {item.anchor_id for item in self.document_match.required_anchors + self.document_match.optional_anchors}
|
||||
anchor_ids = {
|
||||
item.anchor_id
|
||||
for item in (
|
||||
self.document_match.required_anchors
|
||||
+ self.document_match.optional_anchors
|
||||
+ self.document_match.negative_anchors
|
||||
)
|
||||
}
|
||||
for table in self.table_regions:
|
||||
if not set(table.continuation_rule.required_anchor_ids).issubset(anchor_ids):
|
||||
raise ValueError('cross-page continuation anchor must be a document match anchor')
|
||||
@@ -451,108 +486,6 @@ def _table_regions_can_apply_same_page(left: TableRegionProfile, right: TableReg
|
||||
return left.page_scope == right.page_scope
|
||||
|
||||
|
||||
# Transitional adapters keep the currently deployed extraction workflow importable while its
|
||||
# callers are migrated to the v2 coordinate runtime in later gated stages. They are not part
|
||||
# of the persisted v2 contract and must not be used by new Profile writes.
|
||||
class OrderProfileColumnRule(OrderProfileModel):
|
||||
"""Legacy runtime column rule retained only until the frozen-run migration is complete."""
|
||||
|
||||
column_index: int = Field(ge=0)
|
||||
extractor_key: Literal['direct', 'temp_internal_parts']
|
||||
target_field_codes: list[str] = Field(min_length=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_extractor_targets(self) -> 'OrderProfileColumnRule':
|
||||
"""Preserve the established finite extractor whitelist for historical frozen snapshots."""
|
||||
targets = set(self.target_field_codes)
|
||||
if len(targets) != len(self.target_field_codes):
|
||||
raise ValueError('order profile target fields must be unique')
|
||||
if self.extractor_key == 'direct' and len(targets) != 1:
|
||||
raise ValueError('direct order profile extractor requires one target field')
|
||||
if self.extractor_key == 'temp_internal_parts' and targets != {'customer_part_number', 'part_number'}:
|
||||
raise ValueError('TEMP/internal extractor targets are fixed')
|
||||
return self
|
||||
|
||||
|
||||
class CoordinateReconstructionProfile(OrderProfileModel):
|
||||
"""Legacy frozen-run coordinate reconstruction adapter; v2 uses FieldRegion instead."""
|
||||
|
||||
method: Literal['native_pdf_coordinates.v1', 'ocr_pdf_coordinates.v1'] = 'native_pdf_coordinates.v1'
|
||||
column_boundaries: list[float] = Field(default_factory=list)
|
||||
column_field_codes: list[str | None] = Field(default_factory=list)
|
||||
line_start_column_index: int = Field(default=0, ge=0)
|
||||
subrow_layouts: list[dict[str, Any]] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_boundaries(self) -> 'CoordinateReconstructionProfile':
|
||||
"""Validate historical settings so existing frozen Run snapshots remain safe to load."""
|
||||
if self.subrow_layouts:
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import CoordinateSubrowLayout
|
||||
layouts = [CoordinateSubrowLayout.model_validate(item) for item in self.subrow_layouts]
|
||||
offsets = [item.row_offset for item in layouts]
|
||||
if len(offsets) != len(set(offsets)) or sorted(offsets) != list(range(len(offsets))) or sum(item.role == 'main' for item in layouts) != 1:
|
||||
raise ValueError('coordinate subrow layouts require contiguous offsets and one main row')
|
||||
return self
|
||||
if len(self.column_boundaries) < 3 or self.column_boundaries[0] != 0 or self.column_boundaries[-1] != 1:
|
||||
raise ValueError('coordinate reconstruction boundaries must cover the table')
|
||||
if any(left >= right for left, right in zip(self.column_boundaries, self.column_boundaries[1:])):
|
||||
raise ValueError('coordinate reconstruction boundaries must be strictly increasing')
|
||||
if self.column_field_codes and len(self.column_field_codes) != len(self.column_boundaries) - 1:
|
||||
raise ValueError('coordinate reconstruction field codes must match column count')
|
||||
return self
|
||||
|
||||
|
||||
class OrderDocumentProfile(OrderProfileModel):
|
||||
"""保存当前已发布运行路径的模板结构、列覆盖、数据起始行和质量策略。"""
|
||||
|
||||
contract_version: Literal['shipping_order_document_profile.v1'] = 'shipping_order_document_profile.v1'
|
||||
profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
|
||||
version: int = Field(ge=1)
|
||||
structure_fingerprint: str = Field(pattern=r'^[0-9a-f]{64}$')
|
||||
header_row_index: int = Field(ge=0)
|
||||
data_start_row_index: int = Field(ge=1)
|
||||
row_structure: Literal['preserved', 'unsupported_row_structure'] = 'preserved'
|
||||
column_rules: list[OrderProfileColumnRule] = Field(default_factory=list)
|
||||
coordinate_reconstruction: CoordinateReconstructionProfile | None = None
|
||||
drop_zero_qty: bool = True
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_profile_rules(self) -> 'OrderDocumentProfile':
|
||||
"""禁止列规则重复;不支持的行结构只能作为识别/路由 Profile,不能配置字段解析。"""
|
||||
columns = [item.column_index for item in self.column_rules]
|
||||
if len(columns) != len(set(columns)):
|
||||
raise ValueError('order profile source columns must be unique')
|
||||
targets = [code for item in self.column_rules for code in item.target_field_codes]
|
||||
if len(targets) != len(set(targets)):
|
||||
raise ValueError('order profile target fields must be unique across columns')
|
||||
if self.data_start_row_index <= self.header_row_index:
|
||||
raise ValueError('order profile data rows must start after the header')
|
||||
if self.row_structure == 'unsupported_row_structure' and self.column_rules:
|
||||
raise ValueError('unsupported row structure profile cannot expose column mappings')
|
||||
if self.row_structure == 'preserved' and not self.column_rules:
|
||||
raise ValueError('preserved row structure profile requires column mappings')
|
||||
return self
|
||||
|
||||
|
||||
class OrderProfileRowResult(OrderProfileModel):
|
||||
"""保存一条模板行的字段值或删除/复核状态,不包含来源原文。"""
|
||||
|
||||
row_index: int = Field(ge=0)
|
||||
status: Literal['parsed', 'deleted', 'needs_review']
|
||||
fields: dict[str, Any] = Field(default_factory=dict)
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class OrderProfileParseResult(OrderProfileModel):
|
||||
"""汇总 Profile 是否精确命中以及模板行解析结果。"""
|
||||
|
||||
matched: bool
|
||||
profile_code: str | None = None
|
||||
profile_version: int | None = Field(default=None, ge=1)
|
||||
rows: list[OrderProfileRowResult] = Field(default_factory=list)
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
def diagnose_order_profile_header(grid: HtmlGrid, *, header_row_index: int) -> list[str]:
|
||||
"""
|
||||
诊断管理员所选表头是否已经混入明显的订单明细值。
|
||||
@@ -606,266 +539,3 @@ def order_profile_structure_fingerprint(
|
||||
}
|
||||
encoded = json.dumps(payload, sort_keys=True, ensure_ascii=True, separators=(',', ':')).encode()
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def reconstruct_order_profile_html(
|
||||
*, characters: list[dict[str, Any]], table_bbox: dict[str, Any],
|
||||
reconstruction: CoordinateReconstructionProfile,
|
||||
) -> str:
|
||||
"""
|
||||
利用冻结坐标证据生成带稳定虚拟表头的逻辑明细 HTML。
|
||||
|
||||
核心逻辑:先按 x/y 重建物理行,再将 continuation 按列并入最近 data 行;deleted
|
||||
回写最近明细状态,summary 终止数据区。虚拟表头只表达列序,不依赖数据页表头是否完整。
|
||||
|
||||
Args:
|
||||
characters: 当前表格 bbox 内的原生或 OCR 字符坐标。
|
||||
table_bbox: 当前表格页面坐标。
|
||||
reconstruction: 管理员确认的相对列边界。
|
||||
Returns:
|
||||
可由既有 Profile 解析器消费的 HTML;行角色保存在 ``data-row-role`` 属性中。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
|
||||
CoordinateColumnAnchor,
|
||||
reconstruct_multi_subrow_table,
|
||||
reconstruct_table_from_positioned_text,
|
||||
)
|
||||
|
||||
bbox = LayoutBBox.model_validate(table_bbox)
|
||||
if reconstruction.subrow_layouts:
|
||||
logical_rows = reconstruct_multi_subrow_table(
|
||||
characters=characters,
|
||||
table_bbox=bbox,
|
||||
subrow_layouts=reconstruction.subrow_layouts,
|
||||
)
|
||||
field_codes = []
|
||||
for layout in reconstruction.subrow_layouts:
|
||||
for code in layout.get('column_field_codes') or []:
|
||||
if code and code not in field_codes:
|
||||
field_codes.append(code)
|
||||
header = '<tr data-row-role="header">' + ''.join(
|
||||
f'<th>{html.escape(code)}</th>' for code in field_codes
|
||||
) + '</tr>'
|
||||
body = ''.join(
|
||||
'<tr data-row-role="{}" data-source-rows="{}">{}</tr>'.format(
|
||||
row.role, ','.join(str(index) for index in row.source_row_indices),
|
||||
''.join(f'<td>{html.escape(row.fields.get(code, ""))}</td>' for code in field_codes),
|
||||
)
|
||||
for row in logical_rows
|
||||
)
|
||||
return f'<table>{header}{body}</table>'
|
||||
boundaries = reconstruction.column_boundaries
|
||||
width = bbox.x1 - bbox.x0
|
||||
anchors = [CoordinateColumnAnchor(
|
||||
column_index=index,
|
||||
field_code=(reconstruction.column_field_codes[index] if reconstruction.column_field_codes else None),
|
||||
bbox=LayoutBBox(
|
||||
x0=bbox.x0 + width * boundaries[index], y0=bbox.y0,
|
||||
x1=bbox.x0 + width * boundaries[index + 1], y1=bbox.y1,
|
||||
),
|
||||
) for index in range(len(boundaries) - 1)]
|
||||
result = reconstruct_table_from_positioned_text(
|
||||
characters=characters, table_bbox=bbox, column_anchors=anchors,
|
||||
line_start_column_index=reconstruction.line_start_column_index,
|
||||
)
|
||||
if not result.rows:
|
||||
raise ValidationError(
|
||||
'No coordinate reconstruction rows were produced',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE',
|
||||
)
|
||||
logical_rows: list[dict[str, Any]] = []
|
||||
for row in result.rows:
|
||||
values = {cell.column_index: cell.text for cell in row.cells}
|
||||
if row.role == 'data':
|
||||
logical_rows.append({'role': 'data', 'values': values, 'source_rows': [row.row_index]})
|
||||
elif row.role == 'continuation' and logical_rows:
|
||||
current = logical_rows[-1]
|
||||
for column_index, value in values.items():
|
||||
previous = str(current['values'].get(column_index) or '').strip()
|
||||
current['values'][column_index] = f'{previous} {value}'.strip()
|
||||
current['source_rows'].append(row.row_index)
|
||||
elif row.role == 'deleted' and logical_rows:
|
||||
logical_rows[-1]['role'] = 'deleted'
|
||||
logical_rows[-1]['source_rows'].append(row.row_index)
|
||||
elif row.role == 'summary':
|
||||
break
|
||||
|
||||
header = '<tr data-row-role="header">' + ''.join(
|
||||
f'<th>coordinate_column_{index + 1}</th>' for index in range(len(anchors))
|
||||
) + '</tr>'
|
||||
body = ''.join(
|
||||
'<tr data-row-role="{}" data-source-rows="{}">{}</tr>'.format(
|
||||
row['role'], ','.join(str(index) for index in row['source_rows']),
|
||||
''.join(
|
||||
f'<td>{html.escape(str(row["values"].get(index, "")))}</td>'
|
||||
for index in range(len(anchors))
|
||||
),
|
||||
)
|
||||
for row in logical_rows
|
||||
)
|
||||
return f'<table>{header}{body}</table>'
|
||||
|
||||
|
||||
def parse_html_table_with_order_profile(
|
||||
html: str,
|
||||
*,
|
||||
table_id: str,
|
||||
profile: OrderDocumentProfile,
|
||||
contract: TableHeaderContract,
|
||||
) -> OrderProfileParseResult:
|
||||
"""
|
||||
在结构指纹精确命中时按模板列规则解析订单行。
|
||||
|
||||
Args:
|
||||
html: MinerU 或 EML 提供的单张 HTML table。
|
||||
table_id: 当前文档内稳定表格 ID。
|
||||
profile: Run 锁定的 published 模板 Profile 快照。
|
||||
contract: Run 锁定订单 Schema 表头/字段契约。
|
||||
Returns:
|
||||
未命中时不产生行;不支持行结构时返回阻断问题;命中时逐行解析。
|
||||
"""
|
||||
grid = parse_html_grid(html, table_id=table_id)
|
||||
actual = order_profile_structure_fingerprint(
|
||||
grid,
|
||||
header_row_index=profile.header_row_index,
|
||||
)
|
||||
if actual != profile.structure_fingerprint:
|
||||
return OrderProfileParseResult(matched=False, issues=['order_profile_structure_mismatch'])
|
||||
if profile.row_structure == 'unsupported_row_structure':
|
||||
return OrderProfileParseResult(
|
||||
matched=True,
|
||||
profile_code=profile.profile_code,
|
||||
profile_version=profile.version,
|
||||
issues=['order_profile_row_structure_unsupported'],
|
||||
)
|
||||
if any(rule.column_index >= grid.column_count for rule in profile.column_rules):
|
||||
return OrderProfileParseResult(
|
||||
matched=True,
|
||||
profile_code=profile.profile_code,
|
||||
profile_version=profile.version,
|
||||
issues=['order_profile_column_out_of_range'],
|
||||
)
|
||||
row_roles = _profile_html_row_roles(html)
|
||||
rows = [
|
||||
_parse_profile_row(
|
||||
grid,
|
||||
row_index=index,
|
||||
profile=profile,
|
||||
contract=contract,
|
||||
source_role=row_roles[index] if index < len(row_roles) else 'data',
|
||||
)
|
||||
for index in range(profile.data_start_row_index, grid.row_count)
|
||||
]
|
||||
if not rows:
|
||||
return OrderProfileParseResult(matched=False)
|
||||
return OrderProfileParseResult(
|
||||
matched=True,
|
||||
profile_code=profile.profile_code,
|
||||
profile_version=profile.version,
|
||||
rows=rows,
|
||||
)
|
||||
|
||||
|
||||
def _parse_profile_row(
|
||||
grid: HtmlGrid,
|
||||
*,
|
||||
row_index: int,
|
||||
profile: OrderDocumentProfile,
|
||||
contract: TableHeaderContract,
|
||||
source_role: str = 'data',
|
||||
) -> OrderProfileRowResult:
|
||||
"""执行一条逻辑模板行;坐标重建删除状态和零 Qty 均映射为 deleted。"""
|
||||
fields: dict[str, Any] = {}
|
||||
issues: list[str] = []
|
||||
explicit_qty: float | None = None
|
||||
for rule in profile.column_rules:
|
||||
slot = grid.rows[row_index][rule.column_index]
|
||||
raw = slot.text.strip() if slot is not None else ''
|
||||
extracted = (
|
||||
{rule.target_field_codes[0]: raw}
|
||||
if rule.extractor_key == 'direct'
|
||||
else _apply_profile_extractor(rule.extractor_key, raw)
|
||||
)
|
||||
for code in rule.target_field_codes:
|
||||
candidate = extracted.get(code)
|
||||
if candidate in (None, ''):
|
||||
continue
|
||||
if code == 'qty':
|
||||
explicit_qty = parse_number(candidate)
|
||||
config = contract.fields_by_code.get(code)
|
||||
value = _normalize_profile_value(candidate, config)
|
||||
if value is None:
|
||||
issues.append(f'order_profile_field_invalid:{code}')
|
||||
continue
|
||||
fields[code] = _profile_json_value(value)
|
||||
if source_role == 'deleted' or (profile.drop_zero_qty and explicit_qty == 0):
|
||||
return OrderProfileRowResult(row_index=row_index, status='deleted')
|
||||
required_build = {'part_number', 'qty'}
|
||||
if not required_build.issubset(fields):
|
||||
issues.append('order_profile_build_fields_missing')
|
||||
return OrderProfileRowResult(
|
||||
row_index=row_index,
|
||||
status='parsed' if not issues else 'needs_review',
|
||||
fields=fields,
|
||||
issues=sorted(set(issues)),
|
||||
)
|
||||
|
||||
|
||||
def _profile_html_row_roles(source_html: str) -> list[str]:
|
||||
"""读取坐标重建写入的受控行角色;普通 MinerU HTML 默认按 data 处理。"""
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
table = BeautifulSoup(source_html or '', 'html.parser').find('table')
|
||||
if table is None:
|
||||
return []
|
||||
return [str(row.get('data-row-role') or 'data') for row in table.find_all('tr')]
|
||||
|
||||
|
||||
def _apply_profile_extractor(extractor_key: str, raw: str) -> dict[str, Any]:
|
||||
"""执行代码注册的有限解析器;未知 key 不允许运行。"""
|
||||
if extractor_key == 'temp_internal_parts':
|
||||
resolved = resolve_composite_part_numbers(raw)
|
||||
if resolved:
|
||||
return resolved
|
||||
customer = re.search(r'\b(?:AM)?TEMP-[A-Z0-9._-]+\b', raw, re.IGNORECASE)
|
||||
internal = re.search(r'\bD4-[A-Z0-9._-]+\b', raw, re.IGNORECASE)
|
||||
if customer and internal:
|
||||
return {
|
||||
'customer_part_number': customer.group(0),
|
||||
'part_number': internal.group(0),
|
||||
}
|
||||
return {}
|
||||
raise ValueError('order profile extractor is not registered')
|
||||
|
||||
|
||||
def _normalize_profile_value(raw: Any, config: dict[str, Any] | None) -> Any:
|
||||
"""按冻结 Schema 类型和 validator 规范化模板字段;模板日期兼容常见美式订单格式。"""
|
||||
if config is None:
|
||||
return None
|
||||
value_type = str(config.get('value_type') or 'string')
|
||||
candidate = raw
|
||||
if value_type == 'date':
|
||||
text = str(raw or '').strip()
|
||||
matched = re.fullmatch(r'(\d{1,2})/(\d{1,2})/(\d{4})', text)
|
||||
if matched:
|
||||
candidate = f'{matched.group(3)}-{int(matched.group(1)):02d}-{int(matched.group(2)):02d}'
|
||||
if value_type in {'decimal', 'integer'}:
|
||||
candidate = parse_number(raw)
|
||||
if candidate is None:
|
||||
return None
|
||||
if value_type == 'integer':
|
||||
if not float(candidate).is_integer():
|
||||
return None
|
||||
candidate = int(candidate)
|
||||
try:
|
||||
value = normalize_order_field_value(candidate, config)
|
||||
return value if value is not None and validate_order_field_value(value, config) else None
|
||||
except (ArithmeticError, TypeError, ValueError, ValidationError):
|
||||
return None
|
||||
|
||||
|
||||
def _profile_json_value(value: Any) -> Any:
|
||||
"""把字段规则返回值转换为数据库 JSON 可序列化标量。"""
|
||||
if isinstance(value, Decimal):
|
||||
return int(value) if value == value.to_integral_value() else float(value)
|
||||
return value.isoformat() if hasattr(value, 'isoformat') else value
|
||||
@@ -4,6 +4,7 @@ services/shipping_notice/document_layout/order_profile_extractors.py
|
||||
用途:执行订单坐标 Profile v2 的有限注册字段解析器。
|
||||
依赖:订单料号复合解析与数值解析。
|
||||
逻辑:坐标重建先取得管理员框选的原文,本模块再将其安全拆成固定业务字段;任何拆分失败均不返回部分字段。
|
||||
另提供 XFA/坐标共用的 ``unit_price / price_unit``(如 ``898.72 / 1``)确定性拆分。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,9 +19,44 @@ from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
_NUMBER_UNIT = re.compile(r'^\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*([A-Za-z]{1,12})\s*$')
|
||||
_MONEY_CURRENCY = re.compile(r'^\s*([A-Za-z]{3}|[$€£¥])\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*$')
|
||||
_CURRENCY_MONEY = re.compile(r'^\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*([A-Za-z]{3}|[$€£¥])\s*$')
|
||||
# 真实 XFA NETPR 常见写法:单价 / 价格单位,例如 ``898.72 / 1``。
|
||||
_UNIT_PRICE_PER_PRICE_UNIT = re.compile(
|
||||
r'^\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*/\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*$'
|
||||
)
|
||||
_CURRENCY_SYMBOLS = {'$': 'USD', '€': 'EUR', '£': 'GBP', '¥': 'CNY'}
|
||||
|
||||
|
||||
def parse_unit_price_with_price_unit(raw: str | None) -> dict[str, str] | None:
|
||||
"""
|
||||
解析 ``单价 / 价格单位`` 复合文本。
|
||||
|
||||
核心逻辑:仅接受确定性 ``number / number``;逗号千分位剔除后返回两段字符串。
|
||||
不匹配时返回 None(调用方回退单字段 Decimal 解析)。
|
||||
|
||||
Args:
|
||||
raw: datasets / 单元格原文,例如 ``898.72 / 1``。
|
||||
|
||||
Returns:
|
||||
``{'unit_price': '...', 'price_unit': '...'}`` 或 None。
|
||||
"""
|
||||
text = str(raw or '').strip()
|
||||
if not text or '/' not in text:
|
||||
return None
|
||||
matched = _UNIT_PRICE_PER_PRICE_UNIT.fullmatch(text)
|
||||
if not matched:
|
||||
return None
|
||||
unit_price = matched.group(1).replace(',', '')
|
||||
price_unit = matched.group(2).replace(',', '')
|
||||
try:
|
||||
Decimal(unit_price)
|
||||
Decimal(price_unit)
|
||||
except (InvalidOperation, ValueError):
|
||||
return None
|
||||
if not unit_price or not price_unit:
|
||||
return None
|
||||
return {'unit_price': unit_price, 'price_unit': price_unit}
|
||||
|
||||
|
||||
def extract_profile_field_value(*, extractor_key: str, field_code: str, raw: str) -> dict[str, str]:
|
||||
"""将已确认区域按注册解析器拆分,并把预约单号统一为合法纯数字。"""
|
||||
text = str(raw or '').strip()
|
||||
@@ -56,6 +92,8 @@ def extract_profile_field_value(*, extractor_key: str, field_code: str, raw: str
|
||||
'line_amount_before_tax' if extractor_key == 'amount_currency' else 'unit_price': amount.replace(',', ''),
|
||||
'currency': _CURRENCY_SYMBOLS.get(currency, currency.upper()),
|
||||
}
|
||||
if extractor_key == 'unit_price_price_unit':
|
||||
return parse_unit_price_with_price_unit(text) or {}
|
||||
return {}
|
||||
|
||||
|
||||
@@ -71,4 +109,6 @@ def registered_extractor_output_codes(*, extractor_key: str, field_code: str) ->
|
||||
return {'line_amount_before_tax', 'currency'}
|
||||
if extractor_key == 'price_currency':
|
||||
return {'unit_price', 'currency'}
|
||||
if extractor_key == 'unit_price_price_unit':
|
||||
return {'unit_price', 'price_unit'}
|
||||
return set()
|
||||
File diff suppressed because it is too large.
Load diff
+257
@@ -0,0 +1,257 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/order_profile_parse_validation.py
|
||||
|
||||
用途:对模板匹配候选做只读解析可行性校验,不创建 Candidate/Order/Task。
|
||||
依赖:OrderCoordinateProfile、coordinate_region_text、order_profile 契约。
|
||||
逻辑:由 order_extraction_workflow 在 matcher 硬门禁后调用;确定性/idempotent;
|
||||
返回 passed/reason_codes/metrics 供 unique_match 二次裁决。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text
|
||||
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile
|
||||
|
||||
|
||||
_NUMERIC_PATTERN = re.compile(r'^-?\d+([.,]\d+)?$')
|
||||
_DATE_PATTERN = re.compile(
|
||||
r'^(?:\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}|\d{1,2}[-/\.]\d{1,2}[-/\.]\d{4})$',
|
||||
)
|
||||
|
||||
|
||||
def validate_profile_parse_candidate(
|
||||
*,
|
||||
profile_snapshot: dict[str, Any],
|
||||
layout: dict[str, Any],
|
||||
definition: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
校验 Profile 是否具备在当前 layout 上完成坐标解析的结构前提。
|
||||
|
||||
核心逻辑:解析模板定义 → 统计 header/line 字段区覆盖 → 估计明细行数 →
|
||||
检测未知列与基础类型合理性;只读,不写入任何业务实体。
|
||||
|
||||
Args:
|
||||
profile_snapshot: 冻结 Profile 快照(含 definition)。
|
||||
layout: 冻结 layout 快照,含 coordinate_evidence。
|
||||
definition: Schema definition_json,用于字段 scope/类型参考。
|
||||
|
||||
Returns:
|
||||
{passed: bool, reason_codes: list[str], metrics: dict}。
|
||||
"""
|
||||
reason_codes: list[str] = []
|
||||
profile_def = profile_snapshot.get('definition') if isinstance(profile_snapshot.get('definition'), dict) else {}
|
||||
try:
|
||||
profile = OrderCoordinateProfile(
|
||||
profile_code=str(profile_snapshot.get('profile_code') or profile_def.get('profile_code') or 'TMP'),
|
||||
version=int(profile_snapshot.get('version') or profile_def.get('version') or 1),
|
||||
document_match=profile_def.get('document_match') or {'required_anchors': [], 'optional_anchors': []},
|
||||
table_regions=profile_def.get('table_regions') or [],
|
||||
order_field_layouts=profile_def.get('order_field_layouts') or [],
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
return {
|
||||
'passed': False,
|
||||
'reason_codes': ['profile_parse_definition_invalid'],
|
||||
'metrics': {},
|
||||
}
|
||||
|
||||
schema_fields = {
|
||||
str(item.get('field_code') or ''): item
|
||||
for item in definition.get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True) and item.get('field_code')
|
||||
}
|
||||
glyphs, page = _page_glyphs(layout)
|
||||
if glyphs is None or page is None:
|
||||
return {
|
||||
'passed': False,
|
||||
'reason_codes': ['profile_parse_evidence_missing'],
|
||||
'metrics': {'layouts_with_pages': 0},
|
||||
}
|
||||
|
||||
# [STEP 1] Header 字段覆盖
|
||||
header_required = [
|
||||
item for item in profile.order_field_layouts
|
||||
if item.scope == 'header' and item.required
|
||||
]
|
||||
header_bound = [item for item in profile.order_field_layouts if item.scope == 'header']
|
||||
header_coverage = _field_region_coverage(
|
||||
fields=header_bound, glyphs=glyphs, page=page,
|
||||
)
|
||||
|
||||
# [STEP 2] Line 字段覆盖
|
||||
line_fields = [
|
||||
field for table in profile.table_regions for layout in table.line_layouts
|
||||
for field in layout.field_regions if field.scope == 'line'
|
||||
]
|
||||
line_coverage = _field_region_coverage(fields=line_fields, glyphs=glyphs, page=page)
|
||||
|
||||
# [STEP 3] 明细行数启发式
|
||||
line_count = _estimate_line_count(profile=profile, glyphs=glyphs, page=page)
|
||||
min_lines = 1
|
||||
max_lines = max(500, len(glyphs) // max(1, len(line_fields) or 1))
|
||||
valid_line_count = min_lines <= line_count <= max_lines
|
||||
if not valid_line_count:
|
||||
reason_codes.append('profile_parse_line_count_invalid')
|
||||
|
||||
# [STEP 4] 未知列启发式:line 字段区无文字的比例
|
||||
empty_regions = line_coverage.get('empty_region_count', 0)
|
||||
total_regions = line_coverage.get('total_region_count', 0)
|
||||
unknown_column_ratio = (empty_regions / total_regions) if total_regions else 0.0
|
||||
if unknown_column_ratio > 0.6:
|
||||
reason_codes.append('profile_parse_unknown_columns')
|
||||
|
||||
# [STEP 5] 类型 sanity(轻量)
|
||||
type_issues = _type_sanity_issues(
|
||||
line_fields=line_fields, glyphs=glyphs, page=page, schema_fields=schema_fields,
|
||||
)
|
||||
if type_issues:
|
||||
reason_codes.append('profile_parse_type_sanity_failed')
|
||||
|
||||
required_header_ratio = header_coverage.get('coverage_ratio', 0.0)
|
||||
if header_required and required_header_ratio < 0.5:
|
||||
reason_codes.append('profile_parse_header_coverage_insufficient')
|
||||
|
||||
required_line_codes = {
|
||||
field.field_code
|
||||
for table in profile.table_regions
|
||||
for layout in table.line_layouts
|
||||
for field in layout.field_regions
|
||||
if field.scope == 'line'
|
||||
}
|
||||
if required_line_codes and line_coverage.get('coverage_ratio', 0.0) < 0.4:
|
||||
reason_codes.append('profile_parse_line_coverage_insufficient')
|
||||
|
||||
metrics = {
|
||||
'header_field_count': len(header_bound),
|
||||
'header_coverage_ratio': round(required_header_ratio, 4),
|
||||
'line_field_count': len(line_fields),
|
||||
'line_coverage_ratio': round(line_coverage.get('coverage_ratio', 0.0), 4),
|
||||
'estimated_line_count': line_count,
|
||||
'unknown_column_ratio': round(unknown_column_ratio, 4),
|
||||
'type_issue_count': len(type_issues),
|
||||
}
|
||||
passed = not reason_codes
|
||||
if not passed:
|
||||
reason_codes.append('profile_parse_validation_failed')
|
||||
return {
|
||||
'passed': passed,
|
||||
'reason_codes': sorted(set(reason_codes)),
|
||||
'metrics': metrics,
|
||||
}
|
||||
|
||||
|
||||
def _page_glyphs(layout: dict[str, Any]) -> tuple[list[dict[str, Any]] | None, dict[str, Any] | None]:
|
||||
"""读取首页字符与页尺寸。"""
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
page = pages.get('1') or pages.get(1)
|
||||
if not isinstance(page, dict):
|
||||
return None, None
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
|
||||
if not isinstance(glyphs, list):
|
||||
glyphs = []
|
||||
for table_glyphs in glyph_tables.values():
|
||||
if isinstance(table_glyphs, list):
|
||||
glyphs.extend(table_glyphs)
|
||||
if not isinstance(glyphs, list) or not glyphs:
|
||||
return None, page
|
||||
return glyphs, page
|
||||
|
||||
|
||||
def _field_region_coverage(
|
||||
*,
|
||||
fields: list[Any],
|
||||
glyphs: list[dict[str, Any]],
|
||||
page: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""统计字段区域是否有非空文字。"""
|
||||
if not fields:
|
||||
return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0}
|
||||
non_empty = 0
|
||||
measurable = 0
|
||||
for field in fields:
|
||||
region = _field_validation_region(field)
|
||||
if region is None:
|
||||
continue
|
||||
measurable += 1
|
||||
text = read_coordinate_region_text(glyphs=glyphs, page=page, region=region)
|
||||
if str(text or '').strip():
|
||||
non_empty += 1
|
||||
total = measurable
|
||||
return {
|
||||
'coverage_ratio': non_empty / total if total else 1.0,
|
||||
'empty_region_count': total - non_empty,
|
||||
'total_region_count': total,
|
||||
}
|
||||
|
||||
|
||||
def _field_validation_region(field: Any) -> dict[str, Any] | None:
|
||||
"""
|
||||
读取 FieldRegion 或 OrderFieldLayout 可直接验证的绝对区域。
|
||||
|
||||
核心逻辑:订单头相对 anchor 的 value_region 需要先定位锚点,当前轻量验证器不重复执行字段抽取;
|
||||
仅验证 absolute_value_region/fallback_value_region,无法直接度量时返回 None 而不是抛异常。
|
||||
"""
|
||||
for key in ('region', 'absolute_value_region', 'fallback_value_region'):
|
||||
value = getattr(field, key, None)
|
||||
if value is not None:
|
||||
return value.model_dump() if hasattr(value, 'model_dump') else value
|
||||
return None
|
||||
|
||||
|
||||
def _estimate_line_count(
|
||||
*,
|
||||
profile: OrderCoordinateProfile,
|
||||
glyphs: list[dict[str, Any]],
|
||||
page: dict[str, Any],
|
||||
) -> int:
|
||||
"""按主表区垂直带内非空行带估计明细行数。"""
|
||||
if not profile.table_regions:
|
||||
return 0
|
||||
table = profile.table_regions[0]
|
||||
region = table.region.model_dump()
|
||||
height = float(page.get('height') or 1)
|
||||
y0 = float(region.get('y0', 0)) * height
|
||||
y1 = float(region.get('y1', 1)) * height
|
||||
row_height = max(8.0, (y1 - y0) / max(1, len(table.line_layouts) or 1) / 3)
|
||||
lines: set[int] = set()
|
||||
for glyph in glyphs:
|
||||
bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else {}
|
||||
try:
|
||||
center_y = (float(bbox.get('y0', 0)) + float(bbox.get('y1', 0))) / 2
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if y0 <= center_y <= y1 and str(glyph.get('text') or '').strip():
|
||||
lines.add(int(center_y // row_height))
|
||||
return max(0, len(lines))
|
||||
|
||||
|
||||
def _type_sanity_issues(
|
||||
*,
|
||||
line_fields: list[Any],
|
||||
glyphs: list[dict[str, Any]],
|
||||
page: dict[str, Any],
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
) -> list[str]:
|
||||
"""对数量/日期类字段做轻量类型检查。"""
|
||||
issues: list[str] = []
|
||||
for field in line_fields:
|
||||
schema = schema_fields.get(field.field_code) or {}
|
||||
value_type = str(schema.get('value_type') or schema.get('type') or '').lower()
|
||||
if value_type not in {'number', 'integer', 'decimal', 'date', 'datetime'}:
|
||||
continue
|
||||
region = field.region.model_dump() if hasattr(field.region, 'model_dump') else field.region
|
||||
text = str(read_coordinate_region_text(glyphs=glyphs, page=page, region=region) or '').strip()
|
||||
if not text:
|
||||
continue
|
||||
if value_type in {'number', 'integer', 'decimal'} and not _NUMERIC_PATTERN.match(text.replace(',', '')):
|
||||
issues.append(field.field_code)
|
||||
if value_type in {'date', 'datetime'} and not _DATE_PATTERN.match(text):
|
||||
issues.append(field.field_code)
|
||||
return issues
|
||||
@@ -0,0 +1,576 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/order_profile_signature.py
|
||||
|
||||
用途:从模板定义与冻结样本坐标证据生成不可变版面签名(统计摘要,不含正文/URL)。
|
||||
依赖:order_profile 契约、coordinate_region_text、标准库 hashlib/json/statistics。
|
||||
逻辑:由 validation_service 在发布检查前调用;本模块不负责数据库提交或 Profile 引用更新。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import (
|
||||
positioned_token_spans,
|
||||
read_coordinate_region_text,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile, RelativeRegion
|
||||
from app.services.shipping_notice.order_extraction_route_contract import PROFILE_SCORING_POLICY_ID
|
||||
|
||||
|
||||
# 稳定签名类型用于审计识别,不参与运行时版本分支。
|
||||
LAYOUT_SIGNATURE_ID = 'order-profile-layout-signature'
|
||||
MATCHER_POLICY_ID = PROFILE_SCORING_POLICY_ID
|
||||
|
||||
# 动态业务值不得进入表头签名;仅保留多样本稳定出现的固定文字。
|
||||
_DYNAMIC_TOKEN_PATTERNS = (
|
||||
re.compile(r'^\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}$'),
|
||||
re.compile(r'^\d{1,2}[-/\.]\d{1,2}[-/\.]\d{2,4}$'),
|
||||
re.compile(r'^[A-Z]{0,4}\d{5,}[A-Z0-9\-]*$', re.IGNORECASE),
|
||||
re.compile(r'^\d+([.,]\d+)?$'),
|
||||
re.compile(r'^(po|p\.?o\.?|qty|quantity|amount|price|date|no\.?|#)\s*[:#-]?\s*\S+', re.IGNORECASE),
|
||||
)
|
||||
|
||||
|
||||
def build_layout_signature(
|
||||
*,
|
||||
definition: dict[str, Any],
|
||||
sample_layouts: list[dict[str, Any]],
|
||||
source_sample_refs: list[dict[str, Any]] | None = None,
|
||||
layout_version_refs: list[dict[str, Any]] | None = None,
|
||||
provider_versions: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
生成版面签名快照;相同输入必须得到相同 checksum。
|
||||
|
||||
核心逻辑:解析模板表区/表头/字段关系 → 从样本区域读取固定文字 → 多样本聚合
|
||||
中位数与容差 → 过滤动态值与单样本噪声 → 计算稳定 checksum。
|
||||
|
||||
Args:
|
||||
definition: 当前草稿或冻结 Profile 定义 JSON。
|
||||
sample_layouts: 冻结 layout 快照列表,含 coordinate_evidence。
|
||||
source_sample_refs: 安全样本身份引用(id/role/content_hash),不含文件名正文。
|
||||
layout_version_refs: Layout 版本身份引用。
|
||||
provider_versions: Provider/Parser 版本摘要。
|
||||
|
||||
Returns:
|
||||
含 signature / signature_checksum / matcher_policy_version 的快照字典。
|
||||
|
||||
Raises:
|
||||
ValueError: 定义无法解析为 OrderCoordinateProfile。
|
||||
"""
|
||||
# [STEP 1] 解析模板契约
|
||||
profile = OrderCoordinateProfile(
|
||||
profile_code=str(definition.get('profile_code') or 'TMP'),
|
||||
version=int(definition.get('version') or 1),
|
||||
document_match=definition.get('document_match') or {
|
||||
'required_anchors': [], 'optional_anchors': [],
|
||||
},
|
||||
table_regions=definition.get('table_regions') or [],
|
||||
order_field_layouts=definition.get('order_field_layouts') or [],
|
||||
)
|
||||
|
||||
# [STEP 2] 页面与表区几何模式
|
||||
page_patterns = _build_page_patterns(sample_layouts=sample_layouts)
|
||||
table_patterns = [
|
||||
_build_table_pattern(table=table, sample_layouts=sample_layouts)
|
||||
for table in profile.table_regions
|
||||
]
|
||||
field_relation_graph = _build_field_relation_graph(profile, sample_layouts=sample_layouts)
|
||||
evidence_quality = _build_evidence_quality(
|
||||
sample_layouts=sample_layouts,
|
||||
table_patterns=table_patterns,
|
||||
source_sample_count=len(sample_layouts),
|
||||
)
|
||||
|
||||
signature = {
|
||||
'signature_version': LAYOUT_SIGNATURE_ID,
|
||||
'page_patterns': page_patterns,
|
||||
'table_patterns': table_patterns,
|
||||
'field_relation_graph': field_relation_graph,
|
||||
'applicable_dimensions': [
|
||||
'header_semantic_position',
|
||||
'column_topology',
|
||||
'table_geometry',
|
||||
'page_structure',
|
||||
'field_spatial_relation',
|
||||
'optional_static_text',
|
||||
'trusted_business_context',
|
||||
],
|
||||
'evidence_quality': evidence_quality,
|
||||
}
|
||||
checksum = signature_checksum(signature)
|
||||
return {
|
||||
'signature': signature,
|
||||
'signature_checksum': checksum,
|
||||
'source_sample_refs': list(source_sample_refs or []),
|
||||
'layout_version_refs': list(layout_version_refs or []),
|
||||
'provider_versions': list(provider_versions or []),
|
||||
'matcher_policy_version': MATCHER_POLICY_ID,
|
||||
}
|
||||
|
||||
|
||||
def signature_checksum(signature: dict[str, Any]) -> str:
|
||||
"""
|
||||
对签名主体计算稳定 SHA-256;忽略非签名元数据字段。
|
||||
|
||||
Args:
|
||||
signature: 签名主体(不含 checksum / refs)。
|
||||
|
||||
Returns:
|
||||
64 位十六进制 checksum。
|
||||
"""
|
||||
encoded = json.dumps(signature, sort_keys=True, ensure_ascii=True, separators=(',', ':')).encode()
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def signature_is_safe_for_audit(snapshot: dict[str, Any]) -> bool:
|
||||
"""
|
||||
检查签名快照是否不含原件 URL、凭据或超长正文。
|
||||
|
||||
Args:
|
||||
snapshot: ValidationRun.result_snapshot_json 候选。
|
||||
|
||||
Returns:
|
||||
True 表示可通过审计安全边界。
|
||||
"""
|
||||
forbidden_substrings = ('http://', 'https://', 'minio', 'password', 'token=', 'secret')
|
||||
blob = json.dumps(snapshot, ensure_ascii=True).casefold()
|
||||
if any(item in blob for item in forbidden_substrings):
|
||||
return False
|
||||
# 表头 token 单条过长视为可能混入正文
|
||||
signature = snapshot.get('signature') if isinstance(snapshot.get('signature'), dict) else {}
|
||||
for table in signature.get('table_patterns') or []:
|
||||
for token in (table.get('header_tokens') or []):
|
||||
if len(str(token)) > 80:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _build_page_patterns(*, sample_layouts: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""汇总首页宽高比与表格数量范围。"""
|
||||
ratios: list[float] = []
|
||||
table_counts: list[int] = []
|
||||
for layout in sample_layouts:
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
first = pages.get('1') or pages.get(1) or next(iter(pages.values()), None)
|
||||
if isinstance(first, dict):
|
||||
width = float(first.get('width') or 0)
|
||||
height = float(first.get('height') or 0)
|
||||
if width > 0 and height > 0:
|
||||
ratios.append(width / height)
|
||||
tables = [item for item in (layout.get('tables') or []) if isinstance(item, dict)]
|
||||
if tables:
|
||||
table_counts.append(len(tables))
|
||||
# Evidence missing in every sample is not a template-shaped default. The
|
||||
# matcher will mark this dimension unavailable instead of rewarding config.
|
||||
if not ratios or not table_counts:
|
||||
return []
|
||||
median_ratio = statistics.median(ratios)
|
||||
low = min(table_counts)
|
||||
high = max(table_counts)
|
||||
return [{
|
||||
'page_scope': 'first_page',
|
||||
'aspect_ratio': {
|
||||
'median': round(median_ratio, 4),
|
||||
'tolerance': 0.03,
|
||||
},
|
||||
'table_count_range': [low, high],
|
||||
}]
|
||||
|
||||
|
||||
def _build_table_pattern(*, table: Any, sample_layouts: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""从样本实际表格与字符坐标聚合版面特征,不以标注框伪造观测结果。"""
|
||||
region = table.region
|
||||
bbox_samples: list[list[float]] = []
|
||||
header_tokens_by_sample: list[list[str]] = []
|
||||
column_centers_by_sample: list[list[float]] = []
|
||||
column_widths_by_sample: list[list[float]] = []
|
||||
|
||||
header_layouts = list(table.header_layouts or [])
|
||||
header_region = _union_relative_regions([item.region for item in header_layouts])
|
||||
field_regions = [
|
||||
field for layout in header_layouts for field in (layout.field_regions or [])
|
||||
] or [
|
||||
field for layout in (table.line_layouts or []) for field in (layout.field_regions or [])
|
||||
]
|
||||
column_count = len(field_regions) or max(
|
||||
(len(layout.field_regions or []) for layout in (table.line_layouts or [])),
|
||||
default=0,
|
||||
)
|
||||
|
||||
for layout in sample_layouts:
|
||||
observed = _observe_sample_table(
|
||||
layout, target_region=region, header_region=header_region,
|
||||
)
|
||||
if observed is None:
|
||||
continue
|
||||
bbox_samples.append(observed['bbox'])
|
||||
header_tokens_by_sample.append(observed['header_tokens'])
|
||||
if observed['column_centers']:
|
||||
column_centers_by_sample.append(observed['column_centers'])
|
||||
column_widths_by_sample.append(observed['column_width_ratios'])
|
||||
|
||||
stable_tokens = _stable_tokens(header_tokens_by_sample)
|
||||
median_bbox = _median_vector(bbox_samples)
|
||||
median_centers = _median_columns(column_centers_by_sample)
|
||||
median_widths = _median_columns(column_widths_by_sample)
|
||||
|
||||
return {
|
||||
'region_id': table.region_id,
|
||||
'page_scope': table.page_scope,
|
||||
'bbox': {
|
||||
'median': [round(v, 4) for v in median_bbox] if median_bbox else None,
|
||||
'tolerance': [0.03, 0.04, 0.03, 0.05],
|
||||
},
|
||||
'header_bbox': [
|
||||
header_region.x0, header_region.y0, header_region.x1, header_region.y1,
|
||||
] if header_region is not None else None,
|
||||
'header_row_count': max(1, len(header_layouts)),
|
||||
'column_count': int(len(median_centers) or column_count),
|
||||
'column_centers': median_centers,
|
||||
'column_width_ratios': median_widths,
|
||||
'header_tokens': stable_tokens,
|
||||
'header_order': list(stable_tokens),
|
||||
}
|
||||
|
||||
|
||||
def _build_field_relation_graph(
|
||||
profile: OrderCoordinateProfile, *, sample_layouts: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""记录样本中实际静态标签的相对位置;缺观测不以模板坐标替代。"""
|
||||
relations: list[dict[str, Any]] = []
|
||||
layouts = list(profile.order_field_layouts or [])
|
||||
for index, left in enumerate(layouts):
|
||||
if left.anchor is None:
|
||||
continue
|
||||
left_label = str(left.anchor.text or '').strip()
|
||||
if not left_label:
|
||||
continue
|
||||
for right in layouts[index + 1:]:
|
||||
if right.anchor is None:
|
||||
continue
|
||||
right_label = str(right.anchor.text or '').strip()
|
||||
if not right_label:
|
||||
continue
|
||||
offsets = []
|
||||
for sample in sample_layouts:
|
||||
left_center = _find_text_center(sample, left_label)
|
||||
right_center = _find_text_center(sample, right_label)
|
||||
if left_center and right_center:
|
||||
offsets.append((right_center[0] - left_center[0], right_center[1] - left_center[1]))
|
||||
if not offsets:
|
||||
continue
|
||||
relations.append({
|
||||
'left_field_code': left.field_code,
|
||||
'right_field_code': right.field_code,
|
||||
'left_label': left_label,
|
||||
'right_label': right_label,
|
||||
'dx': round(statistics.median(item[0] for item in offsets), 4),
|
||||
'dy': round(statistics.median(item[1] for item in offsets), 4),
|
||||
})
|
||||
return relations[:32]
|
||||
|
||||
|
||||
def _observe_sample_table(
|
||||
layout: dict[str, Any], *, target_region: RelativeRegion,
|
||||
header_region: RelativeRegion | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""读取样本中与标注区域重叠最高的真实表格及其页级字符几何。"""
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
selected: tuple[dict[str, Any], dict[str, Any], list[float]] | None = None
|
||||
for item in tables:
|
||||
page = pages.get(str(item.get('page_no') or 1)) or pages.get(item.get('page_no') or 1)
|
||||
bbox = item.get('bbox') if isinstance(item.get('bbox'), dict) else {}
|
||||
if not isinstance(page, dict):
|
||||
continue
|
||||
normalized = _normalized_bbox(bbox, page=page)
|
||||
if normalized is None:
|
||||
glyphs = page_glyphs.get(str(item.get('page_no') or 1)) or page_glyphs.get(item.get('page_no') or 1) or []
|
||||
normalized = _glyph_union_bbox(glyphs, page=page)
|
||||
if normalized is None:
|
||||
continue
|
||||
overlap = _bbox_overlap(normalized, [target_region.x0, target_region.y0, target_region.x1, target_region.y1])
|
||||
if selected is None or overlap > _bbox_overlap(selected[2], [target_region.x0, target_region.y0, target_region.x1, target_region.y1]):
|
||||
selected = (item, page, normalized)
|
||||
if selected is None:
|
||||
return None
|
||||
item, page, bbox = selected
|
||||
glyphs = page_glyphs.get(str(item.get('page_no') or 1)) or page_glyphs.get(item.get('page_no') or 1) or []
|
||||
if not isinstance(glyphs, list):
|
||||
return None
|
||||
table_glyphs = [glyph for glyph in glyphs if _glyph_center_in_bbox(glyph, bbox, page=page)]
|
||||
header_bbox = (
|
||||
[header_region.x0, header_region.y0, header_region.x1, header_region.y1]
|
||||
if header_region is not None else None
|
||||
)
|
||||
header_glyphs = _header_glyphs(
|
||||
table_glyphs, page=page, bbox=bbox, header_bbox=header_bbox,
|
||||
)
|
||||
header_tokens, centers, widths = _header_observation(
|
||||
header_glyphs, page=page, bbox=bbox,
|
||||
)
|
||||
return {
|
||||
'bbox': bbox,
|
||||
'header_tokens': header_tokens,
|
||||
'column_centers': centers,
|
||||
'column_width_ratios': widths,
|
||||
}
|
||||
|
||||
|
||||
def _normalized_bbox(bbox: dict[str, Any], *, page: dict[str, Any]) -> list[float] | None:
|
||||
"""将 MinerU/PDF 表格 bbox 统一为 0..1 坐标。"""
|
||||
try:
|
||||
raw = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')]
|
||||
width, height = float(page.get('width')), float(page.get('height'))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
if width <= 0 or height <= 0 or raw[2] <= raw[0] or raw[3] <= raw[1]:
|
||||
return None
|
||||
if max(raw) <= 1.0:
|
||||
return raw
|
||||
return [raw[0] / width, raw[1] / height, raw[2] / width, raw[3] / height]
|
||||
|
||||
|
||||
def _bbox_overlap(left: list[float], right: list[float]) -> float:
|
||||
"""计算两个规范化矩形的 IoU,供选择实际表格。"""
|
||||
x0, y0 = max(left[0], right[0]), max(left[1], right[1])
|
||||
x1, y1 = min(left[2], right[2]), min(left[3], right[3])
|
||||
intersection = max(0.0, x1 - x0) * max(0.0, y1 - y0)
|
||||
union = (left[2] - left[0]) * (left[3] - left[1]) + (right[2] - right[0]) * (right[3] - right[1]) - intersection
|
||||
return intersection / union if union > 0 else 0.0
|
||||
|
||||
|
||||
def _glyph_center_in_bbox(glyph: dict[str, Any], bbox: list[float], *, page: dict[str, Any]) -> bool:
|
||||
"""判断字符中心是否位于真实表格中。"""
|
||||
raw = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else {}
|
||||
try:
|
||||
x = (float(raw.get('x0')) + float(raw.get('x1'))) / 2 / float(page['width'])
|
||||
y = (float(raw.get('y0')) + float(raw.get('y1'))) / 2 / float(page['height'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return False
|
||||
return bbox[0] <= x <= bbox[2] and bbox[1] <= y <= bbox[3]
|
||||
|
||||
|
||||
def _header_glyphs(
|
||||
glyphs: list[dict[str, Any]], *, page: dict[str, Any], bbox: list[float],
|
||||
header_bbox: list[float] | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""优先消费管理员标注的表头区域;旧定义缺失时才使用保守顶部区域。"""
|
||||
region = header_bbox or [
|
||||
bbox[0], bbox[1], bbox[2],
|
||||
bbox[1] + max(0.06, (bbox[3] - bbox[1]) * 0.18),
|
||||
]
|
||||
return [
|
||||
item for item in glyphs
|
||||
if _glyph_center_in_bbox(item, region, page=page)
|
||||
]
|
||||
|
||||
|
||||
def _union_relative_regions(regions: list[RelativeRegion]) -> RelativeRegion | None:
|
||||
"""合并多行表头标注区域,冻结为 Matcher 可直接消费的唯一相对坐标框。"""
|
||||
if not regions:
|
||||
return None
|
||||
return RelativeRegion(
|
||||
x0=min(item.x0 for item in regions), y0=min(item.y0 for item in regions),
|
||||
x1=max(item.x1 for item in regions), y1=max(item.y1 for item in regions),
|
||||
)
|
||||
|
||||
|
||||
def _header_observation(
|
||||
glyphs: list[dict[str, Any]], *, page: dict[str, Any], bbox: list[float],
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""从表头 token 边界生成文本、中心和宽度,禁止按单字符连续间距伪造业务列。"""
|
||||
try:
|
||||
page_width = float(page['width'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return [], [], []
|
||||
spans = [
|
||||
item for item in positioned_token_spans(glyphs, respect_explicit_spaces=False)
|
||||
if _usable_header_token(str(item.get('text') or ''))
|
||||
][:32]
|
||||
tokens = [_normalize_header_token(str(item['text'])) for item in spans]
|
||||
centers = [round((float(item['x0']) + float(item['x1'])) / 2 / page_width, 4) for item in spans]
|
||||
span = max(bbox[2] - bbox[0], 0.0001)
|
||||
widths = [round((float(item['x1']) - float(item['x0'])) / page_width / span, 4) for item in spans]
|
||||
return tokens, centers, widths
|
||||
|
||||
|
||||
def _usable_header_token(token: str) -> bool:
|
||||
"""过滤分隔线、动态值和无意义短 token,仅冻结稳定表头文字。"""
|
||||
normalized = _normalize_header_token(token)
|
||||
if not normalized or not re.search(r'[A-Za-z\u3400-\u9fff]', normalized):
|
||||
return False
|
||||
return not _is_dynamic_token(normalized)
|
||||
|
||||
|
||||
def _find_text_center(layout: dict[str, Any], text: str) -> tuple[float, float] | None:
|
||||
"""在页级字符中定位静态标签中心;仅返回归一化坐标。"""
|
||||
expected = ''.join(text.casefold().split())
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
glyph_pages = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
for key, page in pages.items():
|
||||
glyphs = glyph_pages.get(key) or glyph_pages.get(str(key)) or []
|
||||
if not isinstance(page, dict) or not isinstance(glyphs, list):
|
||||
continue
|
||||
ordered = sorted((item for item in glyphs if isinstance(item.get('bbox'), dict)), key=lambda item: (item['bbox'].get('y0', 0), item['bbox'].get('x0', 0)))
|
||||
joined = ''.join(str(item.get('text') or '') for item in ordered).casefold()
|
||||
start = ''.join(joined.split()).find(expected)
|
||||
if start < 0:
|
||||
continue
|
||||
# Character evidence is normally one glyph per character; find the matching
|
||||
# compact-text span without persisting any document text.
|
||||
compact_index = 0
|
||||
matched: list[dict[str, Any]] = []
|
||||
for item in ordered:
|
||||
chars = ''.join(str(item.get('text') or '').casefold().split())
|
||||
if not chars:
|
||||
continue
|
||||
if start <= compact_index < start + len(expected):
|
||||
matched.append(item)
|
||||
compact_index += len(chars)
|
||||
if matched:
|
||||
try:
|
||||
width, height = float(page['width']), float(page['height'])
|
||||
xs = [(float(item['bbox']['x0']) + float(item['bbox']['x1'])) / 2 / width for item in matched]
|
||||
ys = [(float(item['bbox']['y0']) + float(item['bbox']['y1'])) / 2 / height for item in matched]
|
||||
return statistics.median(xs), statistics.median(ys)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _glyph_union_bbox(glyphs: Any, *, page: dict[str, Any]) -> list[float] | None:
|
||||
"""在 Provider 未给表框时由实际表内字符求并集,绝不回退模板标注框。"""
|
||||
if not isinstance(glyphs, list):
|
||||
return None
|
||||
try:
|
||||
width, height = float(page['width']), float(page['height'])
|
||||
boxes = [item['bbox'] for item in glyphs if isinstance(item, dict) and isinstance(item.get('bbox'), dict)]
|
||||
if not boxes:
|
||||
return None
|
||||
return [
|
||||
min(float(box['x0']) for box in boxes) / width,
|
||||
min(float(box['y0']) for box in boxes) / height,
|
||||
max(float(box['x1']) for box in boxes) / width,
|
||||
max(float(box['y1']) for box in boxes) / height,
|
||||
]
|
||||
except (KeyError, TypeError, ValueError, ZeroDivisionError):
|
||||
return None
|
||||
|
||||
|
||||
def _build_evidence_quality(
|
||||
*,
|
||||
sample_layouts: list[dict[str, Any]],
|
||||
table_patterns: list[dict[str, Any]],
|
||||
source_sample_count: int,
|
||||
) -> dict[str, Any]:
|
||||
"""输出证据质量摘要,供发布门禁与审计使用。"""
|
||||
headers_with_tokens = sum(1 for item in table_patterns if item.get('header_tokens'))
|
||||
pages_present = sum(
|
||||
1 for layout in sample_layouts
|
||||
if isinstance((layout.get('coordinate_evidence') or {}).get('pages'), dict)
|
||||
and (layout.get('coordinate_evidence') or {}).get('pages')
|
||||
)
|
||||
return {
|
||||
'source_sample_count': int(source_sample_count),
|
||||
'layouts_with_pages': pages_present,
|
||||
'tables_with_header_tokens': headers_with_tokens,
|
||||
'header_token_coverage': (
|
||||
round(headers_with_tokens / max(1, len(table_patterns)), 4) if table_patterns else 0.0
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _read_region_text(layout: dict[str, Any], region: RelativeRegion) -> str:
|
||||
"""从冻结 layout 首页坐标证据读取区域内文字;失败返回空串。"""
|
||||
try:
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
page = pages.get('1') or pages.get(1)
|
||||
if not isinstance(page, dict):
|
||||
return ''
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
glyphs = page_glyphs.get('1') or page_glyphs.get(1) or []
|
||||
if not glyphs:
|
||||
for table_glyphs in glyph_tables.values():
|
||||
if isinstance(table_glyphs, list):
|
||||
glyphs = list(glyphs) + table_glyphs
|
||||
if not isinstance(glyphs, list) or not glyphs:
|
||||
return ''
|
||||
return read_coordinate_region_text(
|
||||
glyphs=glyphs,
|
||||
page=page,
|
||||
region={'x0': region.x0, 'y0': region.y0, 'x1': region.x1, 'y1': region.y1},
|
||||
)
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
|
||||
def _normalize_header_token(text: str) -> str:
|
||||
"""规范化表头 token:折叠空白并截断。"""
|
||||
return ' '.join(str(text or '').split())[:80]
|
||||
|
||||
|
||||
def _split_header_tokens(text: str) -> list[str]:
|
||||
"""将表头区域整体文字按空白拆成候选 token。"""
|
||||
return [_normalize_header_token(part) for part in re.split(r'[\s|/]+', text) if part.strip()]
|
||||
|
||||
|
||||
def _is_dynamic_token(token: str) -> bool:
|
||||
"""判断 token 是否像 PO/日期/数量等动态值。"""
|
||||
compact = token.strip()
|
||||
if not compact or len(compact) <= 1:
|
||||
return True
|
||||
return any(pattern.search(compact) for pattern in _DYNAMIC_TOKEN_PATTERNS)
|
||||
|
||||
|
||||
def _stable_tokens(samples: list[list[str]]) -> list[str]:
|
||||
"""仅保留在多数样本中出现的 token,排除单样本噪声。"""
|
||||
if not samples:
|
||||
return []
|
||||
threshold = max(1, (len(samples) + 1) // 2)
|
||||
counts: dict[str, int] = {}
|
||||
for tokens in samples:
|
||||
for token in dict.fromkeys(tokens):
|
||||
counts[token] = counts.get(token, 0) + 1
|
||||
stable = [token for token, count in counts.items() if count >= threshold]
|
||||
# 保持首次样本中的相对顺序
|
||||
order_index = {token: index for index, token in enumerate(samples[0])}
|
||||
return sorted(stable, key=lambda item: order_index.get(item, 10_000))
|
||||
|
||||
|
||||
def _median_vector(vectors: list[list[float]]) -> list[float] | None:
|
||||
"""计算等长向量各维中位数。"""
|
||||
if not vectors:
|
||||
return None
|
||||
width = len(vectors[0])
|
||||
return [
|
||||
round(statistics.median(row[index] for row in vectors if len(row) == width), 4)
|
||||
for index in range(width)
|
||||
]
|
||||
|
||||
|
||||
def _median_columns(samples: list[list[float]]) -> list[float]:
|
||||
"""对列中心/列宽多样本取中位数;列数取众数。"""
|
||||
if not samples:
|
||||
return []
|
||||
lengths = [len(item) for item in samples]
|
||||
target = max(set(lengths), key=lengths.count)
|
||||
aligned = [item for item in samples if len(item) == target]
|
||||
if not aligned:
|
||||
return list(samples[0])
|
||||
return [
|
||||
round(statistics.median(row[index] for row in aligned), 4)
|
||||
for index in range(target)
|
||||
]
|
||||
@@ -37,6 +37,53 @@ def _enabled() -> bool:
|
||||
return bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED', False))
|
||||
|
||||
|
||||
def _try_build_xfa_layout_snapshot(
|
||||
*,
|
||||
content: bytes,
|
||||
document_id: int | None = None,
|
||||
content_hash: str | None = None,
|
||||
timings: dict[str, int] | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
在 MinerU/PDFium 表格路径前探测 XFA;supported hybrid 直接返回 XFA capability 快照。
|
||||
|
||||
核心逻辑:仅对 PDF 字节调用 xfa_analysis;xfa_hybrid 成功时跳过 MinerU,不要求 table ready。
|
||||
|
||||
Args:
|
||||
content: PDF 原始字节。
|
||||
document_id/content_hash: 文档身份(写入 capability 摘要)。
|
||||
timings: 可选运维耗时字典。
|
||||
|
||||
Returns:
|
||||
XFA 快照;非 XFA 或 plain/acroform 时返回 None 以继续常规 layout 路径。
|
||||
"""
|
||||
if not content or not content.startswith(b'%PDF'):
|
||||
return None
|
||||
started = perf_counter()
|
||||
from app.services.shipping_notice.document_layout.xfa_analysis import analyze_xfa_pdf
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import default_xfa_resource_limits
|
||||
|
||||
limits = default_xfa_resource_limits()
|
||||
outcome = analyze_xfa_pdf(content, limits=limits)
|
||||
if timings is not None:
|
||||
timings['xfa_probe_ms'] = round((perf_counter() - started) * 1000)
|
||||
packet_result = outcome.packet_result
|
||||
if packet_result is None:
|
||||
return None
|
||||
# plain_pdf / acroform:不拦截,继续 MinerU 表格路径。
|
||||
if packet_result.document_kind in {'plain_pdf', 'acroform'}:
|
||||
return None
|
||||
snapshot = dict(outcome.snapshot)
|
||||
if document_id:
|
||||
capability = snapshot.get('xfa_capability') if isinstance(snapshot.get('xfa_capability'), dict) else {}
|
||||
capability['document_id'] = int(document_id)
|
||||
if content_hash:
|
||||
capability['content_hash'] = str(content_hash)
|
||||
snapshot['xfa_capability'] = capability
|
||||
snapshot['capability'] = capability
|
||||
return snapshot
|
||||
|
||||
|
||||
def mineru_layout_capture_enabled(filename: str) -> bool:
|
||||
"""判断文件是否需要读取二进制并调用 MinerU,供上传链避免默认关闭时重复对象存储 I/O。"""
|
||||
return _enabled() and Path(str(filename or '')).suffix.lower() in MINERU_SUPPORTED_EXTENSIONS
|
||||
@@ -54,8 +101,8 @@ def build_mineru_table_snapshot(
|
||||
"""
|
||||
为一个受支持附件生成紧凑 MinerU 文本与表格快照。
|
||||
|
||||
核心逻辑:文字型 PDF 先用本地坐标和严格表头门槛恢复表格,成功即跳过 MinerU;
|
||||
本地证据不足时再调用 MinerU。两条路径都冻结相同的页面坐标契约。
|
||||
核心逻辑:PDFium 仅在 MinerU 前轻量预读原生字符;表格结构始终优先调用 MinerU。
|
||||
MinerU 空表、配置缺失、调用失败或响应非法时,才允许严格原生文字回退。
|
||||
|
||||
Args:
|
||||
filename: 原附件名,仅用于扩展名和 MinerU multipart,不进入返回错误详情。
|
||||
@@ -68,6 +115,15 @@ def build_mineru_table_snapshot(
|
||||
extension = Path(str(filename or '')).suffix.lower()
|
||||
if not mineru_layout_capture_enabled(filename) or not content:
|
||||
return None
|
||||
if extension == '.pdf':
|
||||
xfa_snapshot = _try_build_xfa_layout_snapshot(
|
||||
content=content,
|
||||
document_id=document_id,
|
||||
content_hash=content_hash,
|
||||
timings=timings,
|
||||
)
|
||||
if xfa_snapshot is not None:
|
||||
return xfa_snapshot
|
||||
native_pages: list[Any] | None = None
|
||||
if extension == '.pdf' and document_id and content_hash:
|
||||
try:
|
||||
@@ -77,24 +133,17 @@ def build_mineru_table_snapshot(
|
||||
native_pages = extract_native_pdf_pages(content, render_images=False)
|
||||
if timings is not None:
|
||||
timings['native_pdf_extract_ms'] = round((perf_counter() - native_started) * 1000)
|
||||
fast_snapshot = _native_pdf_fast_snapshot(
|
||||
content=content,
|
||||
document_id=int(document_id),
|
||||
content_hash=str(content_hash),
|
||||
native_pages=native_pages,
|
||||
timings=timings,
|
||||
)
|
||||
if fast_snapshot is not None:
|
||||
if timings is not None:
|
||||
timings['layout_fast_path'] = 1
|
||||
return fast_snapshot
|
||||
except Exception:
|
||||
native_pages = None
|
||||
if native_pages is not None:
|
||||
# 本地文字门槛未命中时,后续 MinerU 增强路径需要完整页面图,按需重新提取。
|
||||
native_pages = None
|
||||
base_url = str(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL') or '').strip()
|
||||
if not base_url:
|
||||
fallback = _native_pdf_fallback_snapshot(
|
||||
content=content, document_id=document_id, content_hash=content_hash,
|
||||
native_pages=native_pages, timings=timings,
|
||||
provider_issue='mineru_base_url_missing',
|
||||
)
|
||||
if fallback is not None:
|
||||
return fallback
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'mineru',
|
||||
@@ -124,6 +173,13 @@ def build_mineru_table_snapshot(
|
||||
if timings is not None:
|
||||
timings['mineru_result_parse_ms'] = round((perf_counter() - result_parse_started) * 1000)
|
||||
except AppError as exc:
|
||||
fallback = _native_pdf_fallback_snapshot(
|
||||
content=content, document_id=document_id, content_hash=content_hash,
|
||||
native_pages=native_pages, timings=timings,
|
||||
provider_issue=str(exc.code),
|
||||
)
|
||||
if fallback is not None:
|
||||
return fallback
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'mineru',
|
||||
@@ -133,6 +189,13 @@ def build_mineru_table_snapshot(
|
||||
'issues': [str(exc.code)],
|
||||
}
|
||||
except (TypeError, ValueError):
|
||||
fallback = _native_pdf_fallback_snapshot(
|
||||
content=content, document_id=document_id, content_hash=content_hash,
|
||||
native_pages=native_pages, timings=timings,
|
||||
provider_issue='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
if fallback is not None:
|
||||
return fallback
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'mineru',
|
||||
@@ -152,6 +215,7 @@ def build_mineru_table_snapshot(
|
||||
total_html_chars = 0
|
||||
total_text_chars = 0
|
||||
issues = list(candidate.capability.issues)
|
||||
mineru_has_tables = any(page.tables for page in candidate.pages)
|
||||
for page in candidate.pages:
|
||||
for block in sorted(
|
||||
page.text_blocks,
|
||||
@@ -209,16 +273,18 @@ def build_mineru_table_snapshot(
|
||||
extract_native_pdf_pages,
|
||||
)
|
||||
|
||||
if native_pages is None:
|
||||
native_started = perf_counter()
|
||||
native_pages = extract_native_pdf_pages(content)
|
||||
if timings is not None:
|
||||
timings['native_pdf_extract_ms'] = round((perf_counter() - native_started) * 1000)
|
||||
# MinerU 成功后进入坐标增强链;此时按需补齐页面图,供严格 OpenCV/OCR 门禁使用。
|
||||
# 前置轻量预读只缓存字符,不得因为已有无图页面而跳过必要的增强证据。
|
||||
native_started = perf_counter()
|
||||
native_pages = extract_native_pdf_pages(content)
|
||||
if timings is not None:
|
||||
timings['native_pdf_extract_ms'] = round((perf_counter() - native_started) * 1000)
|
||||
|
||||
layout_source_candidate = candidate
|
||||
# MinerU occasionally returns only text blocks for unbordered purchase-order lines.
|
||||
# Restrict the fallback to an otherwise empty table result so normal templates retain
|
||||
# the provider's original table structure unchanged.
|
||||
if not tables:
|
||||
if not tables and not mineru_has_tables:
|
||||
fallback_tables = build_native_pdf_text_table_fallbacks(
|
||||
content,
|
||||
native_pages=native_pages,
|
||||
@@ -226,15 +292,26 @@ def build_mineru_table_snapshot(
|
||||
if fallback_tables:
|
||||
tables.extend(fallback_tables)
|
||||
snapshot['tables'] = tables
|
||||
snapshot['issues'] = sorted(set(
|
||||
issue for issue in snapshot['issues']
|
||||
if issue not in {'mineru_table_structure_missing', 'mineru_cell_coordinates_missing'}
|
||||
) | {'native_pdf_text_table_fallback_used'})
|
||||
layout_source_candidate = _native_pdf_candidate_from_tables(
|
||||
native_pages=native_pages,
|
||||
tables=fallback_tables,
|
||||
)
|
||||
snapshot.update({
|
||||
'provider': 'pdfium',
|
||||
'provider_version': 'native-text-v1',
|
||||
'backend': 'native_pdf',
|
||||
'capability': layout_source_candidate.capability.model_dump(mode='json'),
|
||||
})
|
||||
snapshot['issues'] = sorted(set(snapshot['issues']) | {
|
||||
'mineru_provider_fallback_used',
|
||||
'mineru_table_structure_missing',
|
||||
'native_pdf_text_table_fallback_used',
|
||||
})
|
||||
|
||||
layout_started = perf_counter()
|
||||
layout = build_native_pdf_layout_candidate(
|
||||
document_id=int(document_id), content_hash=str(content_hash),
|
||||
content=content, mineru=candidate, native_pages=native_pages,
|
||||
content=content, mineru=layout_source_candidate, native_pages=native_pages,
|
||||
)
|
||||
if timings is not None:
|
||||
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
|
||||
@@ -260,37 +337,89 @@ def build_mineru_table_snapshot(
|
||||
return snapshot
|
||||
|
||||
|
||||
def _native_pdf_fast_snapshot(
|
||||
*, content: bytes, document_id: int, content_hash: str,
|
||||
native_pages: list[Any], timings: dict[str, int] | None,
|
||||
def _native_pdf_fallback_snapshot(
|
||||
*, content: bytes, document_id: int | None, content_hash: str | None,
|
||||
native_pages: list[Any] | None, timings: dict[str, int] | None,
|
||||
provider_issue: str,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
用严格原生文字表格证据生成可立即消费的布局快照。
|
||||
在 MinerU 不可用时,用严格原生文字表格证据生成降级布局快照。
|
||||
|
||||
AI/调用方触发时机:版面 Job 收到文字型 PDF 时先调用;只有表头、列边界和
|
||||
数据行同时成立才返回快照,否则返回 None 继续 MinerU,禁止宽松猜测表格。
|
||||
AI/调用方触发时机:仅在 MinerU 配置缺失、调用失败或响应非法后调用;MinerU
|
||||
正常返回时不得调用本函数替换 Provider 表格。只有表头、列边界和数据行同时成立
|
||||
才返回快照,否则返回 None 并保留原 Provider 失败,禁止宽松猜测表格。
|
||||
|
||||
Args:
|
||||
content: 当前 PDF 字节,仅传给既有布局构建器,不持久化。
|
||||
document_id/content_hash: 当前不可变 Document 身份。
|
||||
native_pages: 已完成一次 PDFium 提取的页面,后续阶段必须复用。
|
||||
document_id/content_hash: 当前不可变 Document 身份;缺失时禁止降级。
|
||||
native_pages: MinerU 调用前已轻量预读的 PDFium 页面;缺失时禁止降级。
|
||||
timings: 可选运维阶段耗时,不进入快照。
|
||||
provider_issue: 触发降级的 MinerU 稳定问题码。
|
||||
|
||||
Returns:
|
||||
证据充分时返回 ready 快照;无法证明业务表格时返回 None。
|
||||
证据充分时返回带 Provider 失败原因的 ready 降级快照;否则返回 None。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.native_pdf import (
|
||||
build_native_pdf_layout_candidate,
|
||||
build_native_pdf_text_table_fallbacks,
|
||||
)
|
||||
if not document_id or not content_hash or not native_pages:
|
||||
return None
|
||||
try:
|
||||
from app.services.shipping_notice.document_layout.native_pdf import (
|
||||
build_native_pdf_layout_candidate,
|
||||
build_native_pdf_text_table_fallbacks,
|
||||
)
|
||||
|
||||
fallback_started = perf_counter()
|
||||
tables = build_native_pdf_text_table_fallbacks(content, native_pages=native_pages)
|
||||
if timings is not None:
|
||||
timings['native_table_detect_ms'] = round((perf_counter() - fallback_started) * 1000)
|
||||
if not tables:
|
||||
fallback_started = perf_counter()
|
||||
tables = build_native_pdf_text_table_fallbacks(content, native_pages=native_pages)
|
||||
if timings is not None:
|
||||
timings['native_table_detect_ms'] = round((perf_counter() - fallback_started) * 1000)
|
||||
if not tables:
|
||||
return None
|
||||
|
||||
candidate = _native_pdf_candidate_from_tables(
|
||||
native_pages=native_pages,
|
||||
tables=tables,
|
||||
)
|
||||
layout_started = perf_counter()
|
||||
layout = build_native_pdf_layout_candidate(
|
||||
document_id=int(document_id), content_hash=str(content_hash),
|
||||
content=content, mineru=candidate, native_pages=native_pages,
|
||||
)
|
||||
if timings is not None:
|
||||
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
|
||||
layout_payload_preview = layout.model_dump(mode='json')
|
||||
capability = _capability_with_layout_cells(
|
||||
candidate.capability.model_dump(mode='json'),
|
||||
layout_payload=layout_payload_preview,
|
||||
)
|
||||
evidence_started = perf_counter()
|
||||
# Fallback snapshots only need table-local glyphs for template modeling. Keeping
|
||||
# every page glyph can exceed the persisted snapshot budget on text-heavy PDFs.
|
||||
evidence = _table_coordinate_evidence(
|
||||
pages=native_pages, tables=tables, include_page_glyphs=False,
|
||||
)
|
||||
if timings is not None:
|
||||
timings['coordinate_evidence_ms'] = round((perf_counter() - evidence_started) * 1000)
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'pdfium', 'provider_version': 'native-text-v1', 'backend': 'native_pdf',
|
||||
'status': 'ready', 'text_blocks': [], 'tables': tables,
|
||||
'capability': capability,
|
||||
'layout_candidate': layout_payload_preview,
|
||||
'coordinate_evidence': evidence,
|
||||
'issues': sorted({
|
||||
'mineru_provider_fallback_used',
|
||||
'native_pdf_text_table_fallback_used',
|
||||
str(provider_issue or 'mineru_provider_failed'),
|
||||
}),
|
||||
}
|
||||
except Exception:
|
||||
# 降级链不是新的业务真相来源;自身异常时保留 MinerU 原始失败,禁止反向覆盖。
|
||||
return None
|
||||
|
||||
|
||||
def _native_pdf_candidate_from_tables(
|
||||
*, native_pages: list[Any], tables: list[dict[str, Any]],
|
||||
) -> MinerUParseCandidate:
|
||||
"""把严格 PDFium 回退表转换为统一布局候选;仅供 MinerU 空表或失败降级使用。"""
|
||||
page_candidates = []
|
||||
for page in native_pages:
|
||||
page_tables = []
|
||||
@@ -308,7 +437,7 @@ def _native_pdf_fast_snapshot(
|
||||
page_no=int(page.page_no), width=float(page.width), height=float(page.height),
|
||||
text_blocks=[], tables=page_tables,
|
||||
))
|
||||
candidate = MinerUParseCandidate(
|
||||
return MinerUParseCandidate(
|
||||
provider_version='pdfium-native-text-v1', backend='native_pdf', pages=page_candidates,
|
||||
capability=MinerUCapabilityReport(
|
||||
provider_version='pdfium-native-text-v1', backend='native_pdf',
|
||||
@@ -322,35 +451,6 @@ def _native_pdf_fast_snapshot(
|
||||
issues=['native_pdf_text_table_fallback_used'],
|
||||
),
|
||||
)
|
||||
layout_started = perf_counter()
|
||||
layout = build_native_pdf_layout_candidate(
|
||||
document_id=document_id, content_hash=content_hash,
|
||||
content=content, mineru=candidate, native_pages=native_pages,
|
||||
)
|
||||
if timings is not None:
|
||||
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
|
||||
layout_payload_preview = layout.model_dump(mode='json')
|
||||
capability = _capability_with_layout_cells(
|
||||
candidate.capability.model_dump(mode='json'),
|
||||
layout_payload=layout_payload_preview,
|
||||
)
|
||||
evidence_started = perf_counter()
|
||||
# Fallback snapshots only need table-local glyphs for template modeling. Keeping
|
||||
# every page glyph can exceed the persisted snapshot budget on text-heavy PDFs.
|
||||
evidence = _table_coordinate_evidence(
|
||||
pages=native_pages, tables=tables, include_page_glyphs=False,
|
||||
)
|
||||
if timings is not None:
|
||||
timings['coordinate_evidence_ms'] = round((perf_counter() - evidence_started) * 1000)
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'pdfium', 'provider_version': 'native-text-v1', 'backend': 'native_pdf',
|
||||
'status': 'ready', 'text_blocks': [], 'tables': tables,
|
||||
'capability': capability,
|
||||
'layout_candidate': layout_payload_preview,
|
||||
'coordinate_evidence': evidence,
|
||||
'issues': ['native_pdf_text_table_fallback_used'],
|
||||
}
|
||||
|
||||
|
||||
def _table_coordinate_evidence(
|
||||
@@ -505,7 +605,7 @@ def attach_mineru_layout_snapshots(result: Any, *, root_asset_bytes: bytes | Non
|
||||
and mineru_layout_capture_enabled(str(item.get('filename') or ''))
|
||||
]
|
||||
max_documents = max(int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 4,
|
||||
'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 10,
|
||||
)), 0)
|
||||
concurrency = max(int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY', 2,
|
||||
|
||||
@@ -32,12 +32,13 @@ class TextCellAlignmentModel(BaseModel):
|
||||
|
||||
|
||||
class PositionedCharacter(TextCellAlignmentModel):
|
||||
"""保存 PDF 原生文本层的单个可见字符、页面坐标与视觉行身份。"""
|
||||
"""保存 PDF 原生可见字符、坐标及其前置文本流边界;零 bbox 空白不伪造成 glyph。"""
|
||||
|
||||
text: str = Field(min_length=1, max_length=8)
|
||||
bbox: LayoutBBox
|
||||
source_index: int | None = Field(default=None, ge=0)
|
||||
line_id: str | None = None
|
||||
boundary_before: Literal['none', 'space', 'line_break'] = 'none'
|
||||
|
||||
|
||||
class TextAlignedCell(TextCellAlignmentModel):
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_acroform.py
|
||||
|
||||
用途:读取 AcroForm 字段值并生成与 datasets 叶子节点的对账候选。
|
||||
依赖:pypdf、xfa_dataset.XfaDatasetAnalysis。
|
||||
逻辑:由 xfa_analysis / xfa_validation 调用;按短名聚合多实例值供行对齐对账;
|
||||
此处只做候选与分组,不因 display formatting 差异判失败。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from pypdf import PdfReader
|
||||
|
||||
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
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaAcroformField:
|
||||
"""单个 AcroForm 字段摘要。"""
|
||||
|
||||
qualified_name: str
|
||||
short_name: str
|
||||
value: str
|
||||
value_masked: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaReconciliationCandidate:
|
||||
"""datasets 叶子与 AcroForm 字段的对账候选。"""
|
||||
|
||||
data_path_hash: str
|
||||
dataset_value_masked: str
|
||||
acroform_field_name: str | None
|
||||
acroform_value_masked: str | None
|
||||
match_hint: str
|
||||
|
||||
|
||||
def _local_tail(name: str) -> str:
|
||||
"""
|
||||
取 SOM 路径最后一段业务短名(忽略实例下标)。
|
||||
|
||||
核心逻辑:`form[0].ITEMS[1].MENGE[0]` → `MENGE`;数字段与空段丢弃,
|
||||
便于按短名聚合多行 Widget 实例。
|
||||
"""
|
||||
text = str(name or '').strip()
|
||||
if not text:
|
||||
return ''
|
||||
parts = [part for part in re.split(r'[\.\[\]]+', text) if part and not part.isdigit()]
|
||||
return parts[-1] if parts else text
|
||||
|
||||
|
||||
def _instance_sort_key(qualified_name: str) -> tuple[int, ...]:
|
||||
"""
|
||||
从 SOM 限定名提取实例下标序列,用于多行 Widget 与明细行对齐排序。
|
||||
|
||||
Args:
|
||||
qualified_name: 如 `form[0].Page1[0].MENGE[2]`。
|
||||
|
||||
Returns:
|
||||
下标元组;无下标时返回 (0,)。
|
||||
"""
|
||||
matches = re.findall(r'\[(\d+)\]', str(qualified_name or ''))
|
||||
if not matches:
|
||||
return (0,)
|
||||
return tuple(int(item) for item in matches)
|
||||
|
||||
|
||||
def _normalize_key(value: str) -> str:
|
||||
"""用于候选匹配的规范化键(大小写/空白/标点无关)。"""
|
||||
text = unicodedata.normalize('NFKC', str(value or '')).strip().lower()
|
||||
return re.sub(r'[^a-z0-9]+', '', text)
|
||||
|
||||
|
||||
def read_acroform_fields(pdf_bytes: bytes) -> list[XfaAcroformField]:
|
||||
"""
|
||||
读取 PDF AcroForm 字段值。
|
||||
|
||||
核心逻辑:通过 pypdf get_fields 读取 `/V` 展示值;不执行任何脚本。
|
||||
|
||||
Args:
|
||||
pdf_bytes: 原始 PDF 字节。
|
||||
|
||||
Returns:
|
||||
AcroForm 字段摘要列表;无 AcroForm 时返回空列表。
|
||||
"""
|
||||
try:
|
||||
reader = PdfReader(BytesIO(pdf_bytes), strict=False)
|
||||
raw_fields = reader.get_fields() or {}
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
result: list[XfaAcroformField] = []
|
||||
for qualified_name, field_obj in raw_fields.items():
|
||||
if not isinstance(field_obj, dict):
|
||||
continue
|
||||
value = field_obj.get('/V')
|
||||
if value is None:
|
||||
continue
|
||||
text = str(getattr(value, 'name', value) or value).strip()
|
||||
if not text:
|
||||
continue
|
||||
short_name = _local_tail(str(qualified_name))
|
||||
result.append(XfaAcroformField(
|
||||
qualified_name=str(qualified_name),
|
||||
short_name=short_name,
|
||||
value=text,
|
||||
value_masked=mask_value_for_dto(text),
|
||||
))
|
||||
return result
|
||||
|
||||
|
||||
def build_reconciliation_candidates(
|
||||
*,
|
||||
dataset_analysis: XfaDatasetAnalysis,
|
||||
acroform_fields: list[XfaAcroformField],
|
||||
) -> list[XfaReconciliationCandidate]:
|
||||
"""
|
||||
为 datasets 叶子生成 AcroForm 对账候选。
|
||||
|
||||
核心逻辑:按 localName / 路径尾段做弱匹配;不在此阶段因 display formatting 差异判失败。
|
||||
|
||||
Args:
|
||||
dataset_analysis: datasets 结构分析。
|
||||
acroform_fields: AcroForm 字段列表。
|
||||
|
||||
Returns:
|
||||
对账候选列表。
|
||||
"""
|
||||
by_short_name: dict[str, list[XfaAcroformField]] = {}
|
||||
by_normalized: dict[str, list[XfaAcroformField]] = {}
|
||||
ordered = sorted(acroform_fields, key=lambda item: _instance_sort_key(item.qualified_name))
|
||||
for item in ordered:
|
||||
by_short_name.setdefault(item.short_name.upper(), []).append(item)
|
||||
by_normalized.setdefault(_normalize_key(item.short_name), []).append(item)
|
||||
|
||||
candidates: list[XfaReconciliationCandidate] = []
|
||||
for data_path, raw_value in dataset_analysis.leaf_values_by_path.items():
|
||||
local_name = data_path.rsplit('/', 1)[-1]
|
||||
dataset_masked = mask_value_for_dto(raw_value)
|
||||
matched: XfaAcroformField | None = None
|
||||
match_hint = 'unmatched'
|
||||
|
||||
exact = by_short_name.get(local_name.upper()) or []
|
||||
if len(exact) == 1:
|
||||
matched = exact[0]
|
||||
match_hint = 'local_name_exact'
|
||||
elif len(exact) > 1:
|
||||
matched = exact[0]
|
||||
match_hint = 'local_name_ambiguous'
|
||||
else:
|
||||
normalized = _normalize_key(local_name)
|
||||
fuzzy = by_normalized.get(normalized) or []
|
||||
if len(fuzzy) == 1:
|
||||
matched = fuzzy[0]
|
||||
match_hint = 'normalized_exact'
|
||||
elif len(fuzzy) > 1:
|
||||
matched = fuzzy[0]
|
||||
match_hint = 'normalized_ambiguous'
|
||||
|
||||
candidates.append(XfaReconciliationCandidate(
|
||||
data_path_hash=hash_data_path(data_path),
|
||||
dataset_value_masked=dataset_masked,
|
||||
acroform_field_name=matched.qualified_name if matched else None,
|
||||
acroform_value_masked=matched.value_masked if matched else None,
|
||||
match_hint=match_hint,
|
||||
))
|
||||
return candidates
|
||||
|
||||
|
||||
def group_acroform_values_by_short_name(fields: list[XfaAcroformField]) -> dict[str, list[str]]:
|
||||
"""
|
||||
按短名聚合 AcroForm 多实例值(SOM 下标排序)。
|
||||
|
||||
核心逻辑:同名多 Widget 全部保留,供明细行一一对账;禁止只取首个。
|
||||
|
||||
Args:
|
||||
fields: AcroForm 字段列表。
|
||||
|
||||
Returns:
|
||||
short_name.upper() → 按实例顺序排列的原始展示值列表。
|
||||
"""
|
||||
buckets: dict[str, list[XfaAcroformField]] = {}
|
||||
for item in fields:
|
||||
key = str(item.short_name or '').strip().upper()
|
||||
if not key:
|
||||
continue
|
||||
buckets.setdefault(key, []).append(item)
|
||||
result: dict[str, list[str]] = {}
|
||||
for key, items in buckets.items():
|
||||
ordered = sorted(items, key=lambda field: _instance_sort_key(field.qualified_name))
|
||||
result[key] = [field.value for field in ordered]
|
||||
return result
|
||||
|
||||
|
||||
def serialize_acroform_fields(fields: list[XfaAcroformField]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
序列化 AcroForm 字段供安全 DTO 返回。
|
||||
|
||||
Args:
|
||||
fields: AcroForm 字段列表。
|
||||
|
||||
Returns:
|
||||
不含原始 PDF 或完整路径明文的摘要列表。
|
||||
"""
|
||||
return [
|
||||
{
|
||||
'qualified_name_tail': item.short_name,
|
||||
'value_masked': item.value_masked,
|
||||
}
|
||||
for item in fields
|
||||
]
|
||||
@@ -0,0 +1,437 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_analysis.py
|
||||
|
||||
用途:编排 XFA packet 读取、datasets 解析、签名计算与布局快照/持久化。
|
||||
依赖:xfa_packets、xfa_dataset、xfa_signature、xfa_acroform、xfa_contract、
|
||||
ShippingXfaStructureAnalysis 模型。
|
||||
逻辑:由 runtime 与 shipping_document_layout Job 调用;成功时写入结构分析记录并返回
|
||||
不含 XML/PDF 正文的 capability 快照。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import ShippingXfaStructureAnalysis
|
||||
from app.services.shipping_notice.document_layout.xfa_acroform import (
|
||||
build_reconciliation_candidates,
|
||||
read_acroform_fields,
|
||||
serialize_acroform_fields,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_CONTRACT_VERSION,
|
||||
XFA_PARSER_IDENTITY,
|
||||
hash_data_path,
|
||||
sanitize_xfa_dto,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import (
|
||||
XfaDatasetAnalysis,
|
||||
XfaDatasetParseError,
|
||||
parse_xfa_datasets,
|
||||
serialize_tree_node,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_packets import (
|
||||
XfaPacketError,
|
||||
XfaPacketReadResult,
|
||||
is_deterministic_xfa_error,
|
||||
read_xfa_packets,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_signature import build_signature_summary
|
||||
from app.services.shipping_notice.document_layout.runtime import LAYOUT_SNAPSHOT_VERSION
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaAnalysisOutcome:
|
||||
"""XFA 结构分析完整结果。"""
|
||||
|
||||
snapshot: dict[str, Any]
|
||||
packet_result: XfaPacketReadResult | None = None
|
||||
dataset_analysis: XfaDatasetAnalysis | None = None
|
||||
error_code: str | None = None
|
||||
route_reason: str | None = None
|
||||
deterministic: bool = False
|
||||
analysis_record: ShippingXfaStructureAnalysis | None = None
|
||||
issues: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def analyze_xfa_pdf(
|
||||
pdf_bytes: bytes,
|
||||
*,
|
||||
limits: dict[str, int] | None = None,
|
||||
) -> XfaAnalysisOutcome:
|
||||
"""
|
||||
对 PDF 执行完整 XFA 结构分析(纯函数,不写数据库)。
|
||||
|
||||
Args:
|
||||
pdf_bytes: 原始 PDF 字节。
|
||||
limits: 可选资源上限。
|
||||
|
||||
Returns:
|
||||
XfaAnalysisOutcome:含 layout 快照或结构化失败码。
|
||||
"""
|
||||
issues: list[str] = []
|
||||
try:
|
||||
packet_result = read_xfa_packets(pdf_bytes, limits=limits)
|
||||
except XfaPacketError as exc:
|
||||
return XfaAnalysisOutcome(
|
||||
snapshot=_failed_snapshot(
|
||||
document_kind='unsupported',
|
||||
error_code=exc.error_code,
|
||||
route_reason=exc.route_reason,
|
||||
issues=[exc.route_reason],
|
||||
),
|
||||
error_code=exc.error_code,
|
||||
route_reason=exc.route_reason,
|
||||
deterministic=is_deterministic_xfa_error(exc.error_code),
|
||||
issues=[exc.route_reason],
|
||||
)
|
||||
|
||||
document_kind = packet_result.document_kind
|
||||
if packet_result.error_code and not packet_result.supported:
|
||||
return XfaAnalysisOutcome(
|
||||
snapshot=_failed_snapshot(
|
||||
document_kind=document_kind,
|
||||
error_code=packet_result.error_code,
|
||||
route_reason=packet_result.route_reason or 'xfa_unsupported_document',
|
||||
issues=[packet_result.route_reason or packet_result.error_code],
|
||||
packet_result=packet_result,
|
||||
),
|
||||
packet_result=packet_result,
|
||||
error_code=packet_result.error_code,
|
||||
route_reason=packet_result.route_reason,
|
||||
deterministic=is_deterministic_xfa_error(packet_result.error_code),
|
||||
issues=[packet_result.route_reason or packet_result.error_code],
|
||||
)
|
||||
|
||||
if not packet_result.supported:
|
||||
return XfaAnalysisOutcome(
|
||||
snapshot=_unsupported_snapshot(packet_result),
|
||||
packet_result=packet_result,
|
||||
error_code='XFA_UNSUPPORTED_DOCUMENT',
|
||||
route_reason='xfa_unsupported_document',
|
||||
deterministic=True,
|
||||
issues=['xfa_unsupported_document'],
|
||||
)
|
||||
|
||||
datasets_bytes = packet_result.packet_bytes_by_name.get('datasets')
|
||||
if not datasets_bytes:
|
||||
return XfaAnalysisOutcome(
|
||||
snapshot=_failed_snapshot(
|
||||
document_kind=document_kind,
|
||||
error_code='XFA_DATASET_MISSING',
|
||||
route_reason='xfa_dataset_missing',
|
||||
issues=['xfa_dataset_missing'],
|
||||
packet_result=packet_result,
|
||||
),
|
||||
packet_result=packet_result,
|
||||
error_code='XFA_DATASET_MISSING',
|
||||
route_reason='xfa_dataset_missing',
|
||||
deterministic=True,
|
||||
issues=['xfa_dataset_missing'],
|
||||
)
|
||||
|
||||
try:
|
||||
dataset_analysis = parse_xfa_datasets(datasets_bytes, limits=limits)
|
||||
except XfaDatasetParseError as exc:
|
||||
return XfaAnalysisOutcome(
|
||||
snapshot=_failed_snapshot(
|
||||
document_kind=document_kind,
|
||||
error_code=exc.error_code,
|
||||
route_reason=exc.route_reason,
|
||||
issues=[exc.route_reason],
|
||||
packet_result=packet_result,
|
||||
),
|
||||
packet_result=packet_result,
|
||||
error_code=exc.error_code,
|
||||
route_reason=exc.route_reason,
|
||||
deterministic=is_deterministic_xfa_error(exc.error_code),
|
||||
issues=[exc.route_reason],
|
||||
)
|
||||
|
||||
template_bytes = packet_result.packet_bytes_by_name.get('template')
|
||||
signatures = build_signature_summary(
|
||||
template_bytes=template_bytes,
|
||||
dataset_nodes=dataset_analysis.nodes,
|
||||
)
|
||||
acroform_fields = read_acroform_fields(pdf_bytes)
|
||||
reconciliation = build_reconciliation_candidates(
|
||||
dataset_analysis=dataset_analysis,
|
||||
acroform_fields=acroform_fields,
|
||||
)
|
||||
packet_checksums = {item.name: item.checksum for item in packet_result.packets}
|
||||
capability = {
|
||||
'parser_identity': XFA_PARSER_IDENTITY,
|
||||
'contract_version': XFA_CONTRACT_VERSION,
|
||||
'document_kind': document_kind,
|
||||
'structure_analysis_ready': True,
|
||||
'xfa_dataset_ready': True,
|
||||
'has_table_structure': False,
|
||||
'has_page_coordinates': False,
|
||||
'has_cell_coordinates': False,
|
||||
'deterministic_cell_evidence_ready': False,
|
||||
'template_packet_checksum': signatures.get('template_packet_checksum'),
|
||||
'dataset_structure_fingerprint': signatures.get('dataset_structure_fingerprint'),
|
||||
'dataset_root_path': dataset_analysis.dataset_root_path,
|
||||
'packet_checksums': packet_checksums,
|
||||
'stats': dict(dataset_analysis.stats),
|
||||
'header_candidate_count': len(dataset_analysis.header_candidates),
|
||||
'collection_candidate_count': len(dataset_analysis.collection_candidates),
|
||||
'acroform_field_count': len(acroform_fields),
|
||||
'reconciliation_candidate_count': len(reconciliation),
|
||||
'issues': [],
|
||||
}
|
||||
issues.append('xfa_document_kind_detected')
|
||||
issues.append('xfa_structure_analysis_ready')
|
||||
snapshot = {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'xfa',
|
||||
'provider_version': XFA_PARSER_IDENTITY,
|
||||
'backend': 'xfa_hardened_parser',
|
||||
'status': 'ready',
|
||||
'document_kind': document_kind,
|
||||
'tables': [],
|
||||
'text_blocks': [],
|
||||
'xfa_capability': capability,
|
||||
'capability': capability,
|
||||
'issues': sorted(set(issues)),
|
||||
}
|
||||
return XfaAnalysisOutcome(
|
||||
snapshot=snapshot,
|
||||
packet_result=packet_result,
|
||||
dataset_analysis=dataset_analysis,
|
||||
issues=snapshot['issues'],
|
||||
)
|
||||
|
||||
|
||||
def persist_xfa_structure_analysis(
|
||||
*,
|
||||
document_id: int,
|
||||
layout_version_id: int | None,
|
||||
source_content_hash: str,
|
||||
outcome: XfaAnalysisOutcome,
|
||||
) -> ShippingXfaStructureAnalysis:
|
||||
"""
|
||||
将 XFA 结构分析摘要持久化到数据库。
|
||||
|
||||
Args:
|
||||
document_id: ShippingOrderDocument 主键。
|
||||
layout_version_id: 关联布局版本 ID(可空)。
|
||||
source_content_hash: 文档内容哈希。
|
||||
outcome: analyze_xfa_pdf 的结果。
|
||||
|
||||
Returns:
|
||||
新建或更新的 ShippingXfaStructureAnalysis 记录。
|
||||
"""
|
||||
packet_result = outcome.packet_result
|
||||
dataset_analysis = outcome.dataset_analysis
|
||||
capability = (
|
||||
outcome.snapshot.get('xfa_capability')
|
||||
if isinstance(outcome.snapshot.get('xfa_capability'), dict)
|
||||
else {}
|
||||
)
|
||||
packet_checksums = capability.get('packet_checksums') if isinstance(capability.get('packet_checksums'), dict) else {}
|
||||
stats = capability.get('stats') if isinstance(capability.get('stats'), dict) else {}
|
||||
security_summary = {
|
||||
'parser_identity': XFA_PARSER_IDENTITY,
|
||||
'resolve_entities': False,
|
||||
'load_dtd': False,
|
||||
'no_network': True,
|
||||
'huge_tree': False,
|
||||
'scripts_executed': False,
|
||||
'preflight_rejected': outcome.error_code == 'XFA_UNSAFE_XML',
|
||||
}
|
||||
tree_summary: dict[str, Any] = {}
|
||||
if dataset_analysis is not None:
|
||||
tree_summary = {
|
||||
'dataset_root_path_hash': hash_data_path(dataset_analysis.dataset_root_path),
|
||||
'header_candidates': list(dataset_analysis.header_candidates),
|
||||
'collection_candidates': [
|
||||
{
|
||||
'collection_path_hash': hash_data_path(item.collection_path),
|
||||
'path_id': item.path_id,
|
||||
'row_count': item.row_count,
|
||||
'local_name': item.collection_path.rstrip('/').rsplit('/', 1)[-1],
|
||||
'path_label': ' / '.join(item.collection_path.strip('/').split('/')[-3:]),
|
||||
'sibling_collection_path_hashes': [
|
||||
hash_data_path(path) for path in item.sibling_collection_paths
|
||||
],
|
||||
}
|
||||
for item in dataset_analysis.collection_candidates
|
||||
],
|
||||
'known_path_ids': sorted(dataset_analysis.known_path_ids),
|
||||
}
|
||||
|
||||
status = 'ready' if outcome.snapshot.get('status') == 'ready' else 'failed'
|
||||
if outcome.error_code == 'XFA_UNSAFE_XML':
|
||||
status = 'rejected'
|
||||
|
||||
record = ShippingXfaStructureAnalysis(
|
||||
document_id=int(document_id),
|
||||
layout_version_id=int(layout_version_id) if layout_version_id else None,
|
||||
source_content_hash=str(source_content_hash or '').lower()[:64],
|
||||
document_kind=str(
|
||||
(packet_result.document_kind if packet_result else None)
|
||||
or outcome.snapshot.get('document_kind')
|
||||
or 'unsupported',
|
||||
),
|
||||
analysis_status=status,
|
||||
template_packet_checksum=capability.get('template_packet_checksum'),
|
||||
datasets_packet_checksum=packet_checksums.get('datasets'),
|
||||
dataset_structure_fingerprint=capability.get('dataset_structure_fingerprint'),
|
||||
packet_checksums_json=dict(packet_checksums),
|
||||
stats_json=dict(stats),
|
||||
security_summary_json=security_summary,
|
||||
tree_summary_json=sanitize_xfa_dto(tree_summary),
|
||||
error_code=outcome.error_code,
|
||||
route_reason=outcome.route_reason,
|
||||
encrypted_snapshot_ref=None,
|
||||
parser_identity=XFA_PARSER_IDENTITY,
|
||||
contract_version=XFA_CONTRACT_VERSION,
|
||||
finished_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(record)
|
||||
db.session.flush()
|
||||
if status == 'ready':
|
||||
outcome.snapshot.setdefault('xfa_capability', {})['structure_analysis_id'] = int(record.id)
|
||||
if isinstance(outcome.snapshot.get('capability'), dict):
|
||||
outcome.snapshot['capability']['structure_analysis_id'] = int(record.id)
|
||||
outcome.analysis_record = record
|
||||
return record
|
||||
|
||||
|
||||
def _failed_snapshot(
|
||||
*,
|
||||
document_kind: str,
|
||||
error_code: str,
|
||||
route_reason: str,
|
||||
issues: list[str],
|
||||
packet_result: XfaPacketReadResult | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""构造 failed 状态的 XFA 布局快照。"""
|
||||
capability = {
|
||||
'parser_identity': XFA_PARSER_IDENTITY,
|
||||
'contract_version': XFA_CONTRACT_VERSION,
|
||||
'document_kind': document_kind,
|
||||
'structure_analysis_ready': False,
|
||||
'xfa_dataset_ready': False,
|
||||
'has_table_structure': False,
|
||||
'error_code': error_code,
|
||||
'route_reason': route_reason,
|
||||
}
|
||||
if packet_result is not None:
|
||||
capability['packet_checksums'] = {item.name: item.checksum for item in packet_result.packets}
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'xfa',
|
||||
'provider_version': XFA_PARSER_IDENTITY,
|
||||
'backend': 'xfa_hardened_parser',
|
||||
'status': 'failed',
|
||||
'document_kind': document_kind,
|
||||
'tables': [],
|
||||
'text_blocks': [],
|
||||
'xfa_capability': capability,
|
||||
'capability': capability,
|
||||
'issues': sorted(set(issues)),
|
||||
}
|
||||
|
||||
|
||||
def _unsupported_snapshot(packet_result: XfaPacketReadResult) -> dict[str, Any]:
|
||||
"""构造 unsupported 状态的 XFA 布局快照。"""
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'xfa',
|
||||
'provider_version': XFA_PARSER_IDENTITY,
|
||||
'backend': 'xfa_hardened_parser',
|
||||
'status': 'unsupported',
|
||||
'document_kind': packet_result.document_kind,
|
||||
'tables': [],
|
||||
'text_blocks': [],
|
||||
'xfa_capability': {
|
||||
'parser_identity': XFA_PARSER_IDENTITY,
|
||||
'document_kind': packet_result.document_kind,
|
||||
'structure_analysis_ready': False,
|
||||
'packet_checksums': {item.name: item.checksum for item in packet_result.packets},
|
||||
},
|
||||
'capability': {
|
||||
'document_kind': packet_result.document_kind,
|
||||
'structure_analysis_ready': False,
|
||||
'has_table_structure': False,
|
||||
},
|
||||
'issues': sorted({'xfa_unsupported_document'}),
|
||||
}
|
||||
|
||||
|
||||
def project_field_tree(analysis: ShippingXfaStructureAnalysis, *, include_values: bool = False) -> dict[str, Any]:
|
||||
"""
|
||||
从持久化分析记录投影字段树 DTO(不含 XML 明文路径)。
|
||||
|
||||
Args:
|
||||
analysis: 结构分析记录。
|
||||
include_values: 是否包含脱敏样本值。
|
||||
|
||||
Returns:
|
||||
安全字段树摘要。
|
||||
"""
|
||||
# tree_summary 存的是候选摘要;完整树在 analyze 时重建需 layout job 再解析或存结构 JSON。
|
||||
# 阶段 1:从 tree_summary_json 返回已脱敏的节点摘要。
|
||||
summary = analysis.tree_summary_json if isinstance(analysis.tree_summary_json, dict) else {}
|
||||
return sanitize_xfa_dto({
|
||||
'analysis_id': analysis.id,
|
||||
'document_kind': analysis.document_kind,
|
||||
'dataset_root_path_hash': analysis.dataset_structure_fingerprint,
|
||||
'header_candidates': summary.get('header_candidates') or [],
|
||||
'known_path_ids': summary.get('known_path_ids') or [],
|
||||
'stats': analysis.stats_json or {},
|
||||
})
|
||||
|
||||
|
||||
def get_latest_analysis_for_document(document_id: int) -> ShippingXfaStructureAnalysis | None:
|
||||
"""
|
||||
读取文档最近一次成功的 XFA 结构分析。
|
||||
|
||||
Args:
|
||||
document_id: ShippingOrderDocument 主键。
|
||||
|
||||
Returns:
|
||||
分析记录或 None。
|
||||
"""
|
||||
return (
|
||||
ShippingXfaStructureAnalysis.query.filter_by(document_id=int(document_id))
|
||||
.order_by(ShippingXfaStructureAnalysis.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def rebuild_tree_dto_from_analysis(
|
||||
analysis: ShippingXfaStructureAnalysis,
|
||||
pdf_bytes: bytes,
|
||||
*,
|
||||
include_values: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
按需从 PDF 重建字段树 DTO(管理员 API 用,不持久化 XML)。
|
||||
|
||||
Args:
|
||||
analysis: 已有结构分析记录。
|
||||
pdf_bytes: 原始 PDF 字节。
|
||||
include_values: 是否包含脱敏值。
|
||||
|
||||
Returns:
|
||||
字段树 DTO。
|
||||
"""
|
||||
outcome = analyze_xfa_pdf(pdf_bytes)
|
||||
if outcome.dataset_analysis is None:
|
||||
return project_field_tree(analysis, include_values=include_values)
|
||||
root = outcome.dataset_analysis.nodes[0] if outcome.dataset_analysis.nodes else None
|
||||
tree = serialize_tree_node(root, include_values=include_values) if root else {}
|
||||
return sanitize_xfa_dto({
|
||||
'analysis_id': analysis.id,
|
||||
'document_kind': analysis.document_kind,
|
||||
'dataset_structure_fingerprint': analysis.dataset_structure_fingerprint,
|
||||
'tree': tree,
|
||||
'header_candidates': outcome.dataset_analysis.header_candidates,
|
||||
'stats': outcome.dataset_analysis.stats,
|
||||
})
|
||||
@@ -0,0 +1,733 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_contract.py
|
||||
|
||||
用途:冻结 XFA 数据路径 Profile 的阶段 0 契约——template_mode、受控路径语法、
|
||||
结构指纹算法、资源上限、支持/拒绝矩阵、鉴别联合 definition、evidence 与安全投影。
|
||||
依赖:Pydantic 2、标准库 hashlib/json/re/unicodedata;被 order_extraction_route_contract、
|
||||
error_explainability_contract、Profile 校验与后续 xfa_*.py 解析器引用。
|
||||
逻辑:本模块只定义契约与纯函数校验,不读 PDF/XML、不执行脚本、不接正式流量;
|
||||
coordinate 行为保持不变,xfa_dataset 定义不得混入坐标 region。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import Any, Final, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 契约版本与模式
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
XFA_CONTRACT_VERSION: Final[str] = 'shipping-xfa-dataset-contract.v1'
|
||||
XFA_PARSER_IDENTITY: Final[str] = 'shipping-xfa-hardened-parser.v1'
|
||||
XFA_STRUCTURE_FINGERPRINT_VERSION: Final[str] = 'xfa-dataset-structure-fingerprint.v1'
|
||||
XFA_STRUCTURE_SIGNATURE_ID: Final[str] = 'xfa-structure-signature.v1'
|
||||
# 盲测/正式提取共用的文档级 table_id 占位;XFA 无物理表格。
|
||||
XFA_DOCUMENT_TABLE_ID: Final[str] = 'xfa-authoritative-lines'
|
||||
|
||||
OrderProfileTemplateMode = Literal['coordinate', 'xfa_dataset']
|
||||
ORDER_PROFILE_TEMPLATE_MODES: Final[frozenset[str]] = frozenset({
|
||||
'coordinate',
|
||||
'xfa_dataset',
|
||||
})
|
||||
|
||||
XfaDocumentKind = Literal[
|
||||
'plain_pdf',
|
||||
'acroform',
|
||||
'xfa_hybrid',
|
||||
'pure_xfa',
|
||||
'unsupported',
|
||||
]
|
||||
XFA_DOCUMENT_KINDS: Final[frozenset[str]] = frozenset({
|
||||
'plain_pdf',
|
||||
'acroform',
|
||||
'xfa_hybrid',
|
||||
'pure_xfa',
|
||||
'unsupported',
|
||||
})
|
||||
|
||||
# 第一版正式支持:datasets 已含最终业务值的混合型 XFA。
|
||||
XFA_SUPPORTED_DOCUMENT_KINDS: Final[frozenset[str]] = frozenset({
|
||||
'xfa_hybrid',
|
||||
})
|
||||
|
||||
XFA_REJECTED_CAPABILITIES: Final[frozenset[str]] = frozenset({
|
||||
'execute_javascript',
|
||||
'execute_formcalc',
|
||||
'external_data_connection',
|
||||
'network_fetch',
|
||||
'fuzzy_template_match',
|
||||
'auto_merge_line_collections',
|
||||
'ocr_fallback',
|
||||
'vlm_fallback',
|
||||
'blank_page_coordinate_evidence',
|
||||
'flatten_legal_equivalent_pdf',
|
||||
})
|
||||
|
||||
XfaEvidenceSource = Literal['xfa_dataset']
|
||||
XFA_EVIDENCE_SOURCES: Final[frozenset[str]] = frozenset({'xfa_dataset'})
|
||||
|
||||
XfaCrossCheckStatus = Literal[
|
||||
'matched',
|
||||
'partial',
|
||||
'mismatched',
|
||||
'skipped',
|
||||
'unavailable',
|
||||
'failed',
|
||||
]
|
||||
XFA_CROSS_CHECK_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'matched',
|
||||
'partial',
|
||||
'mismatched',
|
||||
'skipped',
|
||||
'unavailable',
|
||||
'failed',
|
||||
})
|
||||
# 自动建单 CQ 仅接受可证明完整性的对账状态(不含 partial/unavailable)。
|
||||
XFA_CROSS_CHECK_AUTO_CREATE_OK_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'matched',
|
||||
'passed',
|
||||
'skipped',
|
||||
})
|
||||
|
||||
XfaMirrorCollectionPolicy = Literal['must_match_when_present', 'ignore']
|
||||
XFA_MIRROR_COLLECTION_POLICIES: Final[frozenset[str]] = frozenset({
|
||||
'must_match_when_present',
|
||||
'ignore',
|
||||
})
|
||||
|
||||
XfaLineAmountFormula = Literal['quantity_times_unit_price', 'disabled']
|
||||
XfaTotalAmountPolicy = Literal['must_equal_line_sum', 'disabled']
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 资源上限(与验收/实施方案一致;后续可由 settings 覆盖,但契约默认值冻结)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
XFA_DEFAULT_MAX_PDF_BYTES: Final[int] = 20 * 1024 * 1024
|
||||
XFA_DEFAULT_MAX_PACKET_BYTES: Final[int] = 10 * 1024 * 1024
|
||||
XFA_DEFAULT_MAX_XML_DEPTH: Final[int] = 64
|
||||
XFA_DEFAULT_MAX_XML_NODES: Final[int] = 100_000
|
||||
XFA_DEFAULT_MAX_LINE_ROWS: Final[int] = 2_000
|
||||
XFA_DEFAULT_PARSE_TIMEOUT_SECONDS: Final[int] = 30
|
||||
XFA_DEFAULT_MAX_RETRIES: Final[int] = 2
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 稳定错误码 / 路由原因码(阶段 0 冻结;后续只追加不改语义)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
XFA_ERROR_CODES: Final[frozenset[str]] = frozenset({
|
||||
'XFA_DATASET_MISSING',
|
||||
'XFA_UNSAFE_XML',
|
||||
'XFA_PACKET_TOO_LARGE',
|
||||
'XFA_XML_DEPTH_EXCEEDED',
|
||||
'XFA_XML_NODE_LIMIT_EXCEEDED',
|
||||
'XFA_LINE_ROW_LIMIT_EXCEEDED',
|
||||
'XFA_PARSE_TIMEOUT',
|
||||
'XFA_UNSUPPORTED_DOCUMENT',
|
||||
'XFA_PROFILE_NOT_MATCHED',
|
||||
'XFA_PROFILE_AMBIGUOUS',
|
||||
'XFA_REQUIRED_FIELD_MISSING',
|
||||
'XFA_MIRROR_COLLECTION_MISMATCH',
|
||||
'XFA_ACROFORM_MISMATCH',
|
||||
'XFA_BUSINESS_VALIDATION_FAILED',
|
||||
'XFA_AUTHORITATIVE_COLLECTION_MISSING',
|
||||
'XFA_PATH_INVALID',
|
||||
'XFA_PATH_UNKNOWN',
|
||||
'XFA_DEFINITION_INVALID',
|
||||
'XFA_SPLIT_RULE_INVALID',
|
||||
'XFA_SPLIT_FIELD_CONFLICT',
|
||||
'XFA_SPLIT_MIRROR_MISMATCH',
|
||||
})
|
||||
|
||||
XFA_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_dataset_missing',
|
||||
'xfa_unsafe_xml',
|
||||
'xfa_packet_too_large',
|
||||
'xfa_xml_depth_exceeded',
|
||||
'xfa_xml_node_limit_exceeded',
|
||||
'xfa_line_row_limit_exceeded',
|
||||
'xfa_parse_timeout',
|
||||
'xfa_unsupported_document',
|
||||
'xfa_profile_not_matched',
|
||||
'xfa_profile_ambiguous',
|
||||
'xfa_required_field_missing',
|
||||
'xfa_mirror_collection_mismatch',
|
||||
'xfa_acroform_mismatch',
|
||||
'xfa_business_validation_failed',
|
||||
'xfa_authoritative_collection_missing',
|
||||
'xfa_path_invalid',
|
||||
'xfa_path_unknown',
|
||||
'xfa_definition_invalid',
|
||||
'xfa_structure_identity_changed',
|
||||
'xfa_split_rule_invalid',
|
||||
'xfa_split_field_conflict',
|
||||
'xfa_split_mirror_mismatch',
|
||||
})
|
||||
|
||||
XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_sample_uploaded',
|
||||
'xfa_parse_started',
|
||||
'xfa_parse_completed',
|
||||
'xfa_parse_failed',
|
||||
'xfa_parse_rejected_unsafe',
|
||||
'xfa_document_kind_detected',
|
||||
'xfa_packet_parsed',
|
||||
'xfa_structure_analysis_ready',
|
||||
'xfa_field_tree_accessed',
|
||||
'xfa_collections_accessed',
|
||||
'xfa_sensitive_sample_value_read',
|
||||
'xfa_draft_created',
|
||||
'xfa_mapping_saved',
|
||||
'xfa_authoritative_collection_selected',
|
||||
'xfa_normalizer_changed',
|
||||
'xfa_profile_matched',
|
||||
'xfa_profile_not_matched',
|
||||
'xfa_profile_ambiguous',
|
||||
'xfa_extraction_completed',
|
||||
'xfa_extraction_failed',
|
||||
'xfa_cross_check_completed',
|
||||
'xfa_structure_signature_frozen',
|
||||
'xfa_audit_snapshot_viewed',
|
||||
# 字段拆分映射审计(阶段 3/7)
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_split_rule_previewed',
|
||||
'xfa_split_rule_validated',
|
||||
'xfa_split_segment_created',
|
||||
'xfa_split_segment_updated',
|
||||
'xfa_split_segment_deleted',
|
||||
'xfa_segment_mapping_updated',
|
||||
'xfa_profile_draft_saved',
|
||||
'xfa_profile_validation_executed',
|
||||
'blind_test_executed',
|
||||
'blind_test_approved',
|
||||
'xfa_profile_published',
|
||||
'xfa_profile_formal_extracted',
|
||||
'xfa_profile_needs_review',
|
||||
})
|
||||
|
||||
# Profile / Run / 分析 DTO 禁止键(大小写不敏感);完整 XML / PDF bytes / 存储地址不得外泄。
|
||||
XFA_DTO_FORBIDDEN_KEYS: Final[frozenset[str]] = frozenset({
|
||||
'xml',
|
||||
'raw_xml',
|
||||
'xfa_xml',
|
||||
'datasets_xml',
|
||||
'packet_bytes',
|
||||
'pdf_bytes',
|
||||
'file_bytes',
|
||||
'object_key',
|
||||
'object_url',
|
||||
'minio',
|
||||
'storage_url',
|
||||
'presigned_url',
|
||||
'api_key',
|
||||
'secret',
|
||||
'password',
|
||||
'authorization',
|
||||
'credential',
|
||||
'audit_snapshot_key',
|
||||
'raw_value', # 普通 DTO 仅允许脱敏预览或 encrypted ref
|
||||
'full_xml_path', # 普通用户 DTO 不返回明文路径;管理员敏感读另走受控 API
|
||||
})
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 受控数据路径语法
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# 路径形态:/localName[/localName...];禁止通配、函数、父级逃逸、属性谓词与脚本。
|
||||
_XFA_PATH_SEGMENT_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_.-]*$')
|
||||
_XFA_FORBIDDEN_PATH_SUBSTRINGS = (
|
||||
'*',
|
||||
'//',
|
||||
'..',
|
||||
'(',
|
||||
')',
|
||||
'[',
|
||||
']',
|
||||
'@',
|
||||
'=',
|
||||
'|',
|
||||
'::',
|
||||
)
|
||||
_XFA_FORBIDDEN_PATH_SEGMENTS = frozenset({
|
||||
'script',
|
||||
'javascript',
|
||||
'formcalc',
|
||||
})
|
||||
|
||||
|
||||
class XfaContractModel(BaseModel):
|
||||
"""XFA 契约模型基类:禁止额外字段,赋值时再次校验。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid', validate_assignment=True)
|
||||
|
||||
|
||||
class XfaSourceContract(XfaContractModel):
|
||||
"""冻结 XFA 模板结构身份:packet checksum + 结构指纹 + 权威集合路径。"""
|
||||
|
||||
template_packet_checksum: str = Field(min_length=16, max_length=128)
|
||||
dataset_structure_fingerprint: str = Field(min_length=16, max_length=128)
|
||||
dataset_root_path: str = Field(min_length=1, max_length=512)
|
||||
authoritative_line_collection_path: str = Field(min_length=1, max_length=512)
|
||||
mirror_collection_paths: list[str] = Field(default_factory=list)
|
||||
|
||||
@field_validator(
|
||||
'dataset_root_path',
|
||||
'authoritative_line_collection_path',
|
||||
mode='before',
|
||||
)
|
||||
@classmethod
|
||||
def validate_required_paths(cls, value: Any) -> str:
|
||||
"""校验必填受控路径语法。"""
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
@field_validator('mirror_collection_paths', mode='before')
|
||||
@classmethod
|
||||
def validate_mirror_paths(cls, value: Any) -> list[str]:
|
||||
"""校验镜像集合路径列表;允许空列表。"""
|
||||
items = list(value or [])
|
||||
return [validate_controlled_data_path(item) for item in items]
|
||||
|
||||
|
||||
class XfaHeaderMapping(XfaContractModel):
|
||||
"""Header 字段:Schema field ↔ 受控 datasets 路径。"""
|
||||
|
||||
mapping_id: str = Field(min_length=1, max_length=64)
|
||||
field_id: str = Field(min_length=1, max_length=64)
|
||||
field_code: str = Field(min_length=1, max_length=128)
|
||||
data_path: str = Field(min_length=1, max_length=512)
|
||||
path_id: str = Field(min_length=1, max_length=128)
|
||||
value_type: str = Field(min_length=1, max_length=64)
|
||||
normalizer_key: str | None = Field(default=None, max_length=64)
|
||||
validator_key: str | None = Field(default=None, max_length=64)
|
||||
|
||||
@field_validator('data_path', mode='before')
|
||||
@classmethod
|
||||
def validate_data_path(cls, value: Any) -> str:
|
||||
"""Header 映射路径必须通过受控语法。"""
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
|
||||
class XfaLineFieldMapping(XfaContractModel):
|
||||
"""明细行字段映射。"""
|
||||
|
||||
mapping_id: str = Field(min_length=1, max_length=64)
|
||||
field_id: str = Field(min_length=1, max_length=64)
|
||||
field_code: str = Field(min_length=1, max_length=128)
|
||||
data_path: str = Field(min_length=1, max_length=512)
|
||||
path_id: str = Field(min_length=1, max_length=128)
|
||||
value_type: str = Field(min_length=1, max_length=64)
|
||||
normalizer_key: str | None = Field(default=None, max_length=64)
|
||||
validator_key: str | None = Field(default=None, max_length=64)
|
||||
|
||||
@field_validator('data_path', mode='before')
|
||||
@classmethod
|
||||
def validate_data_path(cls, value: Any) -> str:
|
||||
"""明细映射路径必须通过受控语法。"""
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
|
||||
class XfaLineMapping(XfaContractModel):
|
||||
"""权威明细集合路径及行内字段映射。"""
|
||||
|
||||
row_path: str = Field(min_length=1, max_length=512)
|
||||
fields: list[XfaLineFieldMapping] = Field(default_factory=list)
|
||||
|
||||
@field_validator('row_path', mode='before')
|
||||
@classmethod
|
||||
def validate_row_path(cls, value: Any) -> str:
|
||||
"""行集合路径必须通过受控语法。"""
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
|
||||
class XfaCrossChecks(XfaContractModel):
|
||||
"""对账与业务恒等式策略。"""
|
||||
|
||||
acroform_enabled: bool = True
|
||||
mirror_collection_policy: XfaMirrorCollectionPolicy = 'must_match_when_present'
|
||||
line_amount_formula: XfaLineAmountFormula = 'quantity_times_unit_price'
|
||||
total_amount_policy: XfaTotalAmountPolicy = 'must_equal_line_sum'
|
||||
|
||||
|
||||
class OrderXfaDatasetProfile(XfaContractModel):
|
||||
"""
|
||||
xfa_dataset 模式的鉴别联合 definition。
|
||||
|
||||
核心逻辑:仅允许 XFA 映射字段;显式拒绝 coordinate 的 table_regions /
|
||||
order_field_layouts 等键混入;可选 split_rules 声明式多行拆分。
|
||||
"""
|
||||
|
||||
template_mode: Literal['xfa_dataset'] = 'xfa_dataset'
|
||||
source_contract: XfaSourceContract
|
||||
header_mappings: list[XfaHeaderMapping] = Field(default_factory=list)
|
||||
line_mapping: XfaLineMapping
|
||||
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。"""
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
forbidden = {
|
||||
'table_regions',
|
||||
'order_field_layouts',
|
||||
'draft_unbound_order_field_layouts',
|
||||
'document_match',
|
||||
'structure_fingerprint',
|
||||
'column_rules',
|
||||
'row_structure',
|
||||
'coordinate_reconstruction',
|
||||
}
|
||||
present = sorted(key for key in forbidden if key in data)
|
||||
if present:
|
||||
raise ValueError(
|
||||
f'xfa_dataset definition must not mix coordinate keys: {", ".join(present)}',
|
||||
)
|
||||
mode = str(data.get('template_mode') or 'xfa_dataset').strip()
|
||||
if mode != 'xfa_dataset':
|
||||
raise ValueError('OrderXfaDatasetProfile requires template_mode=xfa_dataset')
|
||||
return data
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_unique_bindings(self) -> 'OrderXfaDatasetProfile':
|
||||
"""同一 Schema 字段与同一 mapping_id 不得重复绑定;校验 split_rules 契约。"""
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
parse_split_rule_sets,
|
||||
)
|
||||
|
||||
field_ids: list[str] = []
|
||||
mapping_ids: list[str] = []
|
||||
for item in self.header_mappings:
|
||||
field_ids.append(item.field_id)
|
||||
mapping_ids.append(item.mapping_id)
|
||||
for item in self.line_mapping.fields:
|
||||
field_ids.append(item.field_id)
|
||||
mapping_ids.append(item.mapping_id)
|
||||
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)
|
||||
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',
|
||||
[item.model_dump(mode='json') for item in rule_sets],
|
||||
)
|
||||
return self
|
||||
|
||||
class XfaFieldEvidenceRef(XfaContractModel):
|
||||
"""字段证据引用:普通 DTO 仅含哈希与标准化值,不含明文路径与原始 XML。"""
|
||||
|
||||
source: XfaEvidenceSource = 'xfa_dataset'
|
||||
document_id: int = Field(ge=1)
|
||||
packet_checksum: str = Field(min_length=16, max_length=128)
|
||||
data_path_hash: str = Field(min_length=16, max_length=128)
|
||||
mapping_id: str = Field(min_length=1, max_length=64)
|
||||
raw_value_snapshot_ref: str | None = Field(default=None, max_length=256)
|
||||
normalized_value: str | None = None
|
||||
normalizer_key: str | None = Field(default=None, max_length=64)
|
||||
cross_check_status: XfaCrossCheckStatus = 'unavailable'
|
||||
|
||||
|
||||
class XfaStructureNodeSpec(XfaContractModel):
|
||||
"""结构指纹输入节点:只含名称/层级/基数/命名空间,不含业务值。"""
|
||||
|
||||
local_name: str = Field(min_length=1, max_length=256)
|
||||
namespace_uri: str = ''
|
||||
depth: int = Field(ge=0, le=XFA_DEFAULT_MAX_XML_DEPTH)
|
||||
cardinality: Literal['one', 'many'] = 'one'
|
||||
children: list['XfaStructureNodeSpec'] = Field(default_factory=list)
|
||||
|
||||
|
||||
XfaStructureNodeSpec.model_rebuild()
|
||||
|
||||
|
||||
def normalize_template_mode(value: Any) -> OrderProfileTemplateMode:
|
||||
"""
|
||||
将输入规范化为合法 template_mode。
|
||||
|
||||
Args:
|
||||
value: 原始模式字符串。
|
||||
|
||||
Returns:
|
||||
coordinate | xfa_dataset。
|
||||
|
||||
Raises:
|
||||
ValueError: 非法或不支持的模式。
|
||||
"""
|
||||
mode = str(value or '').strip()
|
||||
if mode not in ORDER_PROFILE_TEMPLATE_MODES:
|
||||
raise ValueError(
|
||||
f'template_mode must be one of {sorted(ORDER_PROFILE_TEMPLATE_MODES)}; got {mode!r}',
|
||||
)
|
||||
return mode # type: ignore[return-value]
|
||||
|
||||
|
||||
def validate_controlled_data_path(value: Any) -> str:
|
||||
"""
|
||||
校验受控数据路径语法。
|
||||
|
||||
核心逻辑:仅允许以 `/` 分段的 localName 路径;拒绝通配符、函数调用、
|
||||
父级逃逸、属性谓词、命名空间轴与脚本关键字。
|
||||
|
||||
Args:
|
||||
value: 候选路径字符串。
|
||||
|
||||
Returns:
|
||||
规范化后的绝对路径(保留段名大小写)。
|
||||
|
||||
Raises:
|
||||
ValueError: 路径语法非法。
|
||||
"""
|
||||
path = str(value or '').strip()
|
||||
if not path:
|
||||
raise ValueError('data path is required')
|
||||
lowered = path.lower()
|
||||
for token in _XFA_FORBIDDEN_PATH_SUBSTRINGS:
|
||||
if token in path or token in lowered:
|
||||
raise ValueError(f'data path contains forbidden token: {token}')
|
||||
if not path.startswith('/'):
|
||||
raise ValueError('data path must be absolute and start with /')
|
||||
if path != '/' and path.endswith('/'):
|
||||
raise ValueError('data path must not end with /')
|
||||
segments = [part for part in path.split('/') if part != '']
|
||||
if not segments:
|
||||
raise ValueError('data path must contain at least one segment')
|
||||
for segment in segments:
|
||||
if segment.lower() in _XFA_FORBIDDEN_PATH_SEGMENTS:
|
||||
raise ValueError(f'data path contains forbidden segment: {segment}')
|
||||
if not _XFA_PATH_SEGMENT_RE.fullmatch(segment):
|
||||
raise ValueError(f'invalid data path segment: {segment!r}')
|
||||
return '/' + '/'.join(segments)
|
||||
|
||||
|
||||
def assert_path_id_known(path_id: str, known_path_ids: set[str] | frozenset[str]) -> str:
|
||||
"""
|
||||
断言 path_id 属于当前结构分析记录中的已知集合。
|
||||
|
||||
Args:
|
||||
path_id: 映射保存的路径身份。
|
||||
known_path_ids: 分析记录产生的合法 path ID 集合。
|
||||
|
||||
Returns:
|
||||
原 path_id。
|
||||
|
||||
Raises:
|
||||
ValueError: path_id 未知。
|
||||
"""
|
||||
normalized = str(path_id or '').strip()
|
||||
if not normalized:
|
||||
raise ValueError('path_id is required')
|
||||
if normalized not in known_path_ids:
|
||||
raise ValueError(f'unknown path_id: {normalized}')
|
||||
return normalized
|
||||
|
||||
|
||||
def hash_data_path(path: str) -> str:
|
||||
"""
|
||||
对受控路径计算稳定 SHA-256(带 sha256: 前缀),供 evidence 与审计脱敏使用。
|
||||
|
||||
Args:
|
||||
path: 已通过语法校验的数据路径。
|
||||
|
||||
Returns:
|
||||
`sha256:<hex>` 字符串。
|
||||
"""
|
||||
validated = validate_controlled_data_path(path)
|
||||
digest = hashlib.sha256(validated.encode('utf-8')).hexdigest()
|
||||
return f'sha256:{digest}'
|
||||
|
||||
|
||||
def canonical_structure_payload(nodes: list[XfaStructureNodeSpec] | list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""
|
||||
生成结构指纹的 canonical 载荷。
|
||||
|
||||
核心逻辑:仅序列化 local_name / namespace_uri / depth / cardinality / children;
|
||||
不包含订单值、文件名或明细行数量。
|
||||
|
||||
Args:
|
||||
nodes: 结构树根列表(模型或 dict)。
|
||||
|
||||
Returns:
|
||||
可稳定哈希的字典。
|
||||
"""
|
||||
validated = [
|
||||
item if isinstance(item, XfaStructureNodeSpec) else XfaStructureNodeSpec.model_validate(item)
|
||||
for item in nodes
|
||||
]
|
||||
|
||||
def _dump(node: XfaStructureNodeSpec) -> dict[str, Any]:
|
||||
return {
|
||||
'local_name': node.local_name,
|
||||
'namespace_uri': node.namespace_uri or '',
|
||||
'depth': node.depth,
|
||||
'cardinality': node.cardinality,
|
||||
'children': [_dump(child) for child in node.children],
|
||||
}
|
||||
|
||||
return {
|
||||
'fingerprint_version': XFA_STRUCTURE_FINGERPRINT_VERSION,
|
||||
'roots': [_dump(node) for node in validated],
|
||||
}
|
||||
|
||||
|
||||
def compute_dataset_structure_fingerprint(
|
||||
nodes: list[XfaStructureNodeSpec] | list[dict[str, Any]],
|
||||
) -> str:
|
||||
"""
|
||||
计算 dataset 结构指纹。
|
||||
|
||||
Args:
|
||||
nodes: 不含业务值的结构树。
|
||||
|
||||
Returns:
|
||||
`sha256:<hex>` 指纹。
|
||||
"""
|
||||
payload = canonical_structure_payload(nodes)
|
||||
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
|
||||
return f'sha256:{hashlib.sha256(raw.encode("utf-8")).hexdigest()}'
|
||||
|
||||
|
||||
def validate_xfa_dataset_definition(payload: dict[str, Any] | OrderXfaDatasetProfile) -> OrderXfaDatasetProfile:
|
||||
"""
|
||||
将字典校验为 OrderXfaDatasetProfile。
|
||||
|
||||
Args:
|
||||
payload: 原始 definition 或已构造模型。
|
||||
|
||||
Returns:
|
||||
通过鉴别联合与路径语法校验的模型。
|
||||
|
||||
Raises:
|
||||
pydantic.ValidationError / ValueError: 契约不合法。
|
||||
"""
|
||||
if isinstance(payload, OrderXfaDatasetProfile):
|
||||
return OrderXfaDatasetProfile.model_validate(payload.model_dump(mode='json'))
|
||||
return OrderXfaDatasetProfile.model_validate(payload)
|
||||
|
||||
|
||||
def sanitize_xfa_dto(payload: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
递归剥离 Profile/Run/分析 DTO 中的禁止键。
|
||||
|
||||
核心逻辑:键名大小写不敏感匹配 XFA_DTO_FORBIDDEN_KEYS;用于阶段 0 契约测试
|
||||
与后续 API 投影共用。
|
||||
|
||||
Args:
|
||||
payload: 候选字典。
|
||||
|
||||
Returns:
|
||||
脱敏后的浅拷贝字典。
|
||||
"""
|
||||
if not isinstance(payload, dict):
|
||||
return {}
|
||||
forbidden = {key.lower() for key in XFA_DTO_FORBIDDEN_KEYS}
|
||||
|
||||
def _walk(value: Any) -> Any:
|
||||
if isinstance(value, dict):
|
||||
cleaned: dict[str, Any] = {}
|
||||
for key, item in value.items():
|
||||
if str(key).lower() in forbidden:
|
||||
continue
|
||||
cleaned[str(key)] = _walk(item)
|
||||
return cleaned
|
||||
if isinstance(value, list):
|
||||
return [_walk(item) for item in value]
|
||||
return value
|
||||
|
||||
return _walk(payload)
|
||||
|
||||
|
||||
_XFA_FULL_DISPLAY_FIELD_NAMES: Final[frozenset[str]] = frozenset({
|
||||
'AMOUNT', 'BEDAT', 'COUNTRY', 'EBELP', 'EINDT', 'INCO1', 'INCO2',
|
||||
'MEINS', 'MENGE', 'NETPR', 'PEINH', 'POST_CODE1', 'TOTAL_AMOUNT',
|
||||
'WAERS', 'WERKS', 'ZTERM',
|
||||
})
|
||||
_XFA_RESTRICTED_FIELD_TOKENS: Final[tuple[str, ...]] = (
|
||||
'ADDRESS', 'CITY', 'FAX', 'HOUSE', 'INSTRUCTION', 'INSPECTION', 'NAME',
|
||||
'PHONE', 'REMARK', 'SPECIFICATION', 'STRAS', 'STREET', 'TEL', 'VENDOR',
|
||||
)
|
||||
|
||||
|
||||
def mask_sample_value(value: Any, *, keep_head: int = 4, keep_tail: int = 3) -> str:
|
||||
"""
|
||||
对样本原值做默认脱敏展示。
|
||||
|
||||
Args:
|
||||
value: 原始业务值。
|
||||
keep_head: 保留前缀字符数。
|
||||
keep_tail: 保留后缀字符数。
|
||||
|
||||
Returns:
|
||||
脱敏字符串;短值整体替换为 `***`。
|
||||
"""
|
||||
text = unicodedata.normalize('NFKC', str(value or '')).strip()
|
||||
if not text:
|
||||
return ''
|
||||
if len(text) <= keep_head + keep_tail:
|
||||
return '***'
|
||||
return f'{text[:keep_head]}{"•" * 3}{text[-keep_tail:]}'
|
||||
|
||||
|
||||
def xfa_mapping_sample_display(field_name: str, value: Any) -> dict[str, Any]:
|
||||
"""
|
||||
为 XFA 映射工作台生成可辨识且分级受控的样本展示。
|
||||
|
||||
核心逻辑:业务代码、日期、数量、金额与单位完整展示;订单/物料等标识符保留
|
||||
足够前后缀;名称、地址、电话和自由文本默认限制展示并允许授权后临时展开。
|
||||
|
||||
Args:
|
||||
field_name: XML 叶子节点 localName。
|
||||
value: datasets 原始业务值。
|
||||
|
||||
Returns:
|
||||
display_value、display_policy 与 can_reveal 组成的安全展示字典。
|
||||
"""
|
||||
text = unicodedata.normalize('NFKC', str(value or '')).strip()
|
||||
name = unicodedata.normalize('NFKC', str(field_name or '')).strip().upper()
|
||||
if not text:
|
||||
return {'display_value': '', 'display_policy': 'empty', 'can_reveal': False}
|
||||
if name in _XFA_FULL_DISPLAY_FIELD_NAMES:
|
||||
return {'display_value': text, 'display_policy': 'full', 'can_reveal': False}
|
||||
if any(token in name for token in _XFA_RESTRICTED_FIELD_TOKENS):
|
||||
if len(text) <= 4:
|
||||
display = f'{text[:1]}•••'
|
||||
else:
|
||||
display = f'{text[: min(8, max(2, len(text) // 3))]}•••'
|
||||
return {'display_value': display, 'display_policy': 'restricted', 'can_reveal': True}
|
||||
|
||||
# 标识符需要足以区分字段和值;短标识不再整体压成无法判断语义的 ***。
|
||||
if len(text) <= 4:
|
||||
display = text
|
||||
elif len(text) <= 8:
|
||||
display = f'{text[:2]}••{text[-2:]}'
|
||||
else:
|
||||
head = min(16, max(4, len(text) // 2))
|
||||
display = f'{text[:head]}…{text[-3:]}'
|
||||
return {'display_value': display, 'display_policy': 'partial', 'can_reveal': True}
|
||||
|
||||
|
||||
def default_xfa_resource_limits() -> dict[str, int]:
|
||||
"""返回阶段 0 冻结的默认资源上限字典。"""
|
||||
return {
|
||||
'max_pdf_bytes': XFA_DEFAULT_MAX_PDF_BYTES,
|
||||
'max_packet_bytes': XFA_DEFAULT_MAX_PACKET_BYTES,
|
||||
'max_xml_depth': XFA_DEFAULT_MAX_XML_DEPTH,
|
||||
'max_xml_nodes': XFA_DEFAULT_MAX_XML_NODES,
|
||||
'max_line_rows': XFA_DEFAULT_MAX_LINE_ROWS,
|
||||
'parse_timeout_seconds': XFA_DEFAULT_PARSE_TIMEOUT_SECONDS,
|
||||
'max_retries': XFA_DEFAULT_MAX_RETRIES,
|
||||
}
|
||||
@@ -0,0 +1,605 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_dataset.py
|
||||
|
||||
用途: hardened 解析 XFA datasets XML,构建受控路径树并识别 Header/集合候选;
|
||||
提供单叶子与权威集合行读取供正式提取使用;叶子保留 raw/normalized/lines
|
||||
三层中间表示,供字段拆分规则引擎消费。
|
||||
依赖:lxml、xfa_contract(路径语法/指纹/脱敏)、xfa_packets.preflight_xml_bytes。
|
||||
逻辑:由 xfa_analysis、xfa_profile_extraction 与 admin XFA API 调用;
|
||||
只读内存 XML,不联网、不执行脚本;raw_value/lines 仅存内存树,不进入普通 DTO。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Literal
|
||||
|
||||
from lxml import etree
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_DEFAULT_MAX_LINE_ROWS,
|
||||
XFA_DEFAULT_MAX_XML_DEPTH,
|
||||
XFA_DEFAULT_MAX_XML_NODES,
|
||||
hash_data_path,
|
||||
mask_sample_value,
|
||||
xfa_mapping_sample_display,
|
||||
validate_controlled_data_path,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_packets import XfaPacketError, preflight_xml_bytes
|
||||
|
||||
_CARDINALITY = Literal['one', 'many']
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaLeafValue:
|
||||
"""
|
||||
叶子业务值的三层中间表示(阶段 1:字段拆分前置)。
|
||||
|
||||
raw_value:保留原始换行(统一为 \\n);
|
||||
normalized_value:空白折叠,供搜索/比较;
|
||||
lines:按换行切分后的行列表(含空行,规则引擎再按 normalization 过滤)。
|
||||
"""
|
||||
|
||||
raw_value: str
|
||||
normalized_value: str
|
||||
lines: list[str]
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaDatasetNode:
|
||||
"""受控路径树节点。"""
|
||||
|
||||
path_id: str
|
||||
local_name: str
|
||||
namespace_uri: str
|
||||
data_path: str
|
||||
depth: int
|
||||
cardinality: _CARDINALITY
|
||||
is_leaf: bool
|
||||
is_header_candidate: bool = False
|
||||
is_collection_candidate: bool = False
|
||||
sample_value_masked: str | None = None
|
||||
sample_value_display: str | None = None
|
||||
display_policy: str = 'empty'
|
||||
can_reveal: bool = False
|
||||
# 仅内存内部使用;serialize_tree_node / 普通 DTO 不得外泄原文。
|
||||
raw_value: str | None = None
|
||||
normalized_value: str | None = None
|
||||
lines: list[str] = field(default_factory=list)
|
||||
children: list['XfaDatasetNode'] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaCollectionCandidate:
|
||||
"""重复明细集合候选。"""
|
||||
|
||||
collection_path: str
|
||||
path_id: str
|
||||
row_count: int
|
||||
sibling_collection_paths: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaDatasetAnalysis:
|
||||
"""datasets 结构分析结果。"""
|
||||
|
||||
dataset_root_path: str
|
||||
nodes: list[XfaDatasetNode]
|
||||
header_candidates: list[dict[str, Any]]
|
||||
collection_candidates: list[XfaCollectionCandidate]
|
||||
stats: dict[str, Any]
|
||||
leaf_values_by_path: dict[str, str]
|
||||
known_path_ids: set[str]
|
||||
|
||||
|
||||
class XfaDatasetParseError(XfaPacketError):
|
||||
"""datasets 解析失败。"""
|
||||
|
||||
|
||||
def _local_name(tag: str) -> str:
|
||||
"""提取 XML localName,忽略命名空间前缀。"""
|
||||
return str(tag or '').rsplit('}', 1)[-1]
|
||||
|
||||
|
||||
def _namespace_uri(tag: str) -> str:
|
||||
"""提取命名空间 URI。"""
|
||||
text = str(tag or '')
|
||||
if text.startswith('{') and '}' in text:
|
||||
return text[1:text.index('}')]
|
||||
return ''
|
||||
|
||||
|
||||
def _normalize_leaf_text(value: str) -> str:
|
||||
"""
|
||||
将叶子文本折叠为单行规范化串(搜索/比较用)。
|
||||
|
||||
注意:不得用于正式拆分输入;拆分必须使用保留换行的 raw_value / lines。
|
||||
"""
|
||||
return re.sub(r'\s+', ' ', str(value or '')).strip()
|
||||
|
||||
|
||||
def build_xfa_leaf_value(text: str) -> XfaLeafValue:
|
||||
"""
|
||||
从 XML 叶子原文构建三层中间表示。
|
||||
|
||||
核心逻辑:统一 \\r\\n/\\r 为 \\n 且保留行结构;去掉整段首尾换行(pretty-print);
|
||||
normalized 折叠空白;lines 按 \\n 切分(含空行,供 position matcher 使用)。
|
||||
|
||||
Args:
|
||||
text: element.itertext() 拼接后的原文。
|
||||
|
||||
Returns:
|
||||
XfaLeafValue。
|
||||
"""
|
||||
raw = str(text or '').replace('\r\n', '\n').replace('\r', '\n').strip('\n')
|
||||
lines = raw.split('\n') if raw != '' else []
|
||||
return XfaLeafValue(
|
||||
raw_value=raw,
|
||||
normalized_value=_normalize_leaf_text(raw),
|
||||
lines=lines,
|
||||
)
|
||||
|
||||
|
||||
def _path_id_for(data_path: str) -> str:
|
||||
"""为受控路径生成稳定 path_id。"""
|
||||
digest = hashlib.sha256(data_path.encode('utf-8')).hexdigest()[:16]
|
||||
return f'path-{digest}'
|
||||
|
||||
|
||||
def _hardened_parser() -> etree.XMLParser:
|
||||
"""构造禁用外部实体与 DTD 的 lxml 解析器。"""
|
||||
return etree.XMLParser(
|
||||
resolve_entities=False,
|
||||
load_dtd=False,
|
||||
no_network=True,
|
||||
huge_tree=False,
|
||||
)
|
||||
|
||||
|
||||
def _iter_element_nodes(root: etree._Element) -> list[tuple[etree._Element, int]]:
|
||||
"""
|
||||
深度优先遍历元素节点并附带深度。
|
||||
|
||||
Args:
|
||||
root: XML 根元素。
|
||||
|
||||
Returns:
|
||||
(element, depth) 列表;depth 从 1 开始。
|
||||
"""
|
||||
result: list[tuple[etree._Element, int]] = []
|
||||
|
||||
def _walk(node: etree._Element, depth: int) -> None:
|
||||
result.append((node, depth))
|
||||
for child in node:
|
||||
if isinstance(child.tag, str):
|
||||
_walk(child, depth + 1)
|
||||
|
||||
_walk(root, 1)
|
||||
return result
|
||||
|
||||
|
||||
def _detect_cardinality(element: etree._Element) -> _CARDINALITY:
|
||||
"""
|
||||
根据同级重复 localName 判断基数。
|
||||
|
||||
核心逻辑:DATA 行容器在结构层始终视为 many,使明细行数量变化不影响指纹。
|
||||
"""
|
||||
local = _local_name(element.tag)
|
||||
if local.upper() == 'DATA':
|
||||
return 'many'
|
||||
if element.getparent() is None:
|
||||
return 'one'
|
||||
siblings = [
|
||||
_local_name(item.tag)
|
||||
for item in element.getparent()
|
||||
if isinstance(item.tag, str)
|
||||
]
|
||||
return 'many' if siblings.count(local) > 1 else 'one'
|
||||
|
||||
|
||||
def _build_tree(
|
||||
element: etree._Element,
|
||||
*,
|
||||
parent_path: str,
|
||||
depth: int,
|
||||
limits: dict[str, int],
|
||||
counters: dict[str, int],
|
||||
leaf_values: dict[str, str],
|
||||
) -> XfaDatasetNode:
|
||||
"""
|
||||
递归构建受控路径树。
|
||||
|
||||
Args:
|
||||
element: 当前 XML 元素。
|
||||
parent_path: 父级受控路径。
|
||||
depth: 当前深度。
|
||||
limits: 资源上限。
|
||||
counters: 可变计数器(node_count、max_depth、line_rows)。
|
||||
leaf_values: 输出叶子原值映射(仅内部使用,不外泄)。
|
||||
|
||||
Returns:
|
||||
XfaDatasetNode 子树。
|
||||
|
||||
Raises:
|
||||
XfaDatasetParseError: 深度/节点/行数超限。
|
||||
"""
|
||||
local = _local_name(element.tag)
|
||||
data_path = validate_controlled_data_path(f'{parent_path}/{local}' if parent_path else f'/{local}')
|
||||
counters['node_count'] = int(counters.get('node_count', 0)) + 1
|
||||
counters['max_depth'] = max(int(counters.get('max_depth', 0)), depth)
|
||||
if counters['node_count'] > limits['max_xml_nodes']:
|
||||
raise XfaDatasetParseError(
|
||||
error_code='XFA_XML_NODE_LIMIT_EXCEEDED',
|
||||
route_reason='xfa_xml_node_limit_exceeded',
|
||||
)
|
||||
if depth > limits['max_xml_depth']:
|
||||
raise XfaDatasetParseError(
|
||||
error_code='XFA_XML_DEPTH_EXCEEDED',
|
||||
route_reason='xfa_xml_depth_exceeded',
|
||||
)
|
||||
|
||||
element_children = [child for child in element if isinstance(child.tag, str)]
|
||||
is_leaf = not element_children
|
||||
cardinality = _detect_cardinality(element)
|
||||
masked_value: str | None = None
|
||||
raw_value: str | None = None
|
||||
normalized_value: str | None = None
|
||||
lines: list[str] = []
|
||||
if is_leaf:
|
||||
leaf = build_xfa_leaf_value(''.join(element.itertext()))
|
||||
leaf_values[data_path] = leaf.raw_value
|
||||
raw_value = leaf.raw_value
|
||||
normalized_value = leaf.normalized_value
|
||||
lines = list(leaf.lines)
|
||||
masked_value = mask_sample_value(leaf.normalized_value) if leaf.normalized_value else ''
|
||||
display = xfa_mapping_sample_display(local, leaf.normalized_value)
|
||||
else:
|
||||
display = {'display_value': '', 'display_policy': 'empty', 'can_reveal': False}
|
||||
|
||||
child_nodes: list[XfaDatasetNode] = []
|
||||
for child in element_children:
|
||||
child_nodes.append(
|
||||
_build_tree(
|
||||
child,
|
||||
parent_path=data_path,
|
||||
depth=depth + 1,
|
||||
limits=limits,
|
||||
counters=counters,
|
||||
leaf_values=leaf_values,
|
||||
),
|
||||
)
|
||||
|
||||
return XfaDatasetNode(
|
||||
path_id=_path_id_for(data_path),
|
||||
local_name=local,
|
||||
namespace_uri=_namespace_uri(element.tag),
|
||||
data_path=data_path,
|
||||
depth=depth,
|
||||
cardinality=cardinality,
|
||||
is_leaf=is_leaf,
|
||||
sample_value_masked=masked_value,
|
||||
sample_value_display=str(display['display_value']),
|
||||
display_policy=str(display['display_policy']),
|
||||
can_reveal=bool(display['can_reveal']),
|
||||
raw_value=raw_value,
|
||||
normalized_value=normalized_value,
|
||||
lines=lines,
|
||||
children=child_nodes,
|
||||
)
|
||||
|
||||
|
||||
def _mark_header_candidates(root: XfaDatasetNode) -> list[dict[str, Any]]:
|
||||
"""
|
||||
识别 Header 候选:位于 HEADER 子树下的叶子节点。
|
||||
|
||||
Args:
|
||||
root: 数据集根节点。
|
||||
|
||||
Returns:
|
||||
Header 候选摘要列表。
|
||||
"""
|
||||
candidates: list[dict[str, Any]] = []
|
||||
|
||||
def _walk(node: XfaDatasetNode, under_header: bool) -> None:
|
||||
in_header = under_header or node.local_name.upper() == 'HEADER'
|
||||
if in_header and node.is_leaf:
|
||||
node.is_header_candidate = True
|
||||
candidates.append({
|
||||
'path_id': node.path_id,
|
||||
'data_path_hash': hash_data_path(node.data_path),
|
||||
'local_name': node.local_name,
|
||||
'value_type': 'string',
|
||||
'sample_value_masked': node.sample_value_masked or '',
|
||||
})
|
||||
for child in node.children:
|
||||
_walk(child, in_header)
|
||||
|
||||
_walk(root, False)
|
||||
return candidates
|
||||
|
||||
|
||||
def _is_line_row_container(node: XfaDatasetNode) -> bool:
|
||||
"""判断 DATA 节点是否表现为明细行容器(子节点均为叶子字段)。"""
|
||||
if node.local_name.upper() != 'DATA':
|
||||
return False
|
||||
if not node.children:
|
||||
return node.is_leaf
|
||||
return all(child.is_leaf for child in node.children)
|
||||
|
||||
|
||||
def _mark_collection_candidates(
|
||||
root: XfaDatasetNode,
|
||||
*,
|
||||
limits: dict[str, int],
|
||||
) -> list[XfaCollectionCandidate]:
|
||||
"""
|
||||
识别独立重复集合候选,例如 ITEMS/DATA 与 ITEMS1/DATA。
|
||||
|
||||
核心逻辑:在每个父节点下查找 DATA 行容器;同一父下多行 DATA 只登记一次候选,
|
||||
row_count 为行数;ITEMS 与 ITEMS1 视为互不合并的独立集合。
|
||||
|
||||
Args:
|
||||
root: 数据集根节点。
|
||||
limits: 资源上限(用于行数统计)。
|
||||
|
||||
Returns:
|
||||
集合候选列表。
|
||||
|
||||
Raises:
|
||||
XfaDatasetParseError: 明细行数超过上限。
|
||||
"""
|
||||
candidates: list[XfaCollectionCandidate] = []
|
||||
total_line_rows = 0
|
||||
|
||||
def _walk(node: XfaDatasetNode) -> None:
|
||||
nonlocal total_line_rows
|
||||
data_children = [child for child in node.children if _is_line_row_container(child)]
|
||||
if data_children:
|
||||
sibling_paths = [item.data_path for item in data_children]
|
||||
total_line_rows += len(data_children)
|
||||
if total_line_rows > limits['max_line_rows']:
|
||||
raise XfaDatasetParseError(
|
||||
error_code='XFA_LINE_ROW_LIMIT_EXCEEDED',
|
||||
route_reason='xfa_line_row_limit_exceeded',
|
||||
)
|
||||
# 同一父节点下多行 DATA 共享同一集合路径;候选只登记一次,row_count=行数。
|
||||
for data_node in data_children:
|
||||
data_node.is_collection_candidate = True
|
||||
first = data_children[0]
|
||||
candidates.append(XfaCollectionCandidate(
|
||||
collection_path=first.data_path,
|
||||
path_id=first.path_id,
|
||||
row_count=len(data_children),
|
||||
sibling_collection_paths=sibling_paths,
|
||||
))
|
||||
for child in node.children:
|
||||
_walk(child)
|
||||
|
||||
_walk(root)
|
||||
return candidates
|
||||
|
||||
|
||||
def _collect_known_path_ids(node: XfaDatasetNode) -> set[str]:
|
||||
"""递归收集全部 path_id。"""
|
||||
ids = {node.path_id}
|
||||
for child in node.children:
|
||||
ids.update(_collect_known_path_ids(child))
|
||||
return ids
|
||||
|
||||
|
||||
def parse_xfa_datasets(
|
||||
xml_bytes: bytes,
|
||||
*,
|
||||
limits: dict[str, int] | None = None,
|
||||
) -> XfaDatasetAnalysis:
|
||||
"""
|
||||
安全解析 XFA datasets XML 并生成结构分析。
|
||||
|
||||
Args:
|
||||
xml_bytes: datasets packet 原始字节。
|
||||
limits: 可选 max_xml_depth/max_xml_nodes/max_line_rows 覆盖。
|
||||
|
||||
Returns:
|
||||
XfaDatasetAnalysis:含路径树、Header/集合候选与统计。
|
||||
|
||||
Raises:
|
||||
XfaDatasetParseError: 不安全 XML 或资源超限。
|
||||
"""
|
||||
resolved = {
|
||||
'max_xml_depth': XFA_DEFAULT_MAX_XML_DEPTH,
|
||||
'max_xml_nodes': XFA_DEFAULT_MAX_XML_NODES,
|
||||
'max_line_rows': XFA_DEFAULT_MAX_LINE_ROWS,
|
||||
}
|
||||
if isinstance(limits, dict):
|
||||
resolved.update({key: int(limits[key]) for key in resolved if key in limits})
|
||||
|
||||
try:
|
||||
preflight_xml_bytes(xml_bytes)
|
||||
except XfaPacketError as exc:
|
||||
raise XfaDatasetParseError(
|
||||
error_code=exc.error_code,
|
||||
route_reason=exc.route_reason,
|
||||
message=str(exc),
|
||||
) from exc
|
||||
parser = _hardened_parser()
|
||||
try:
|
||||
root_element = etree.fromstring(xml_bytes, parser=parser)
|
||||
except etree.XMLSyntaxError as exc:
|
||||
raise XfaDatasetParseError(
|
||||
error_code='XFA_UNSAFE_XML',
|
||||
route_reason='xfa_unsafe_xml',
|
||||
message='xml syntax error',
|
||||
) from exc
|
||||
|
||||
counters: dict[str, int] = {'node_count': 0, 'max_depth': 0}
|
||||
leaf_values: dict[str, str] = {}
|
||||
dataset_root_path = validate_controlled_data_path(f"/{_local_name(root_element.tag)}")
|
||||
root_node = _build_tree(
|
||||
root_element,
|
||||
parent_path='',
|
||||
depth=1,
|
||||
limits=resolved,
|
||||
counters=counters,
|
||||
leaf_values=leaf_values,
|
||||
)
|
||||
header_candidates = _mark_header_candidates(root_node)
|
||||
collection_candidates = _mark_collection_candidates(root_node, limits=resolved)
|
||||
known_path_ids = _collect_known_path_ids(root_node)
|
||||
|
||||
stats = {
|
||||
'node_count': counters['node_count'],
|
||||
'max_depth': counters['max_depth'],
|
||||
'leaf_count': len(leaf_values),
|
||||
'header_candidate_count': len(header_candidates),
|
||||
'collection_candidate_count': len(collection_candidates),
|
||||
'line_row_count': sum(item.row_count for item in collection_candidates),
|
||||
}
|
||||
return XfaDatasetAnalysis(
|
||||
dataset_root_path=dataset_root_path,
|
||||
nodes=[root_node],
|
||||
header_candidates=header_candidates,
|
||||
collection_candidates=collection_candidates,
|
||||
stats=stats,
|
||||
leaf_values_by_path=leaf_values,
|
||||
known_path_ids=known_path_ids,
|
||||
)
|
||||
|
||||
|
||||
def read_dataset_value(analysis: XfaDatasetAnalysis, data_path: str) -> str | None:
|
||||
"""
|
||||
按受控路径读取 datasets 叶子原值(保留换行)。
|
||||
|
||||
Args:
|
||||
analysis: 已完成的 datasets 分析。
|
||||
data_path: 绝对受控路径。
|
||||
|
||||
Returns:
|
||||
叶子 raw_value 或 None(路径不存在/非叶子)。
|
||||
|
||||
Raises:
|
||||
XfaDatasetParseError: 路径语法非法。
|
||||
"""
|
||||
leaf = read_dataset_leaf_value(analysis, data_path)
|
||||
return None if leaf is None else leaf.raw_value
|
||||
|
||||
|
||||
def read_dataset_leaf_value(analysis: XfaDatasetAnalysis, data_path: str) -> XfaLeafValue | None:
|
||||
"""
|
||||
按受控路径读取叶子三层中间表示。
|
||||
|
||||
核心逻辑:优先从内存树节点取 raw/normalized/lines;若仅有 leaf map 则重建。
|
||||
|
||||
Args:
|
||||
analysis: 已完成的 datasets 分析。
|
||||
data_path: 绝对受控路径。
|
||||
|
||||
Returns:
|
||||
XfaLeafValue;路径不存在时 None。
|
||||
|
||||
Raises:
|
||||
XfaDatasetParseError: 路径语法非法。
|
||||
"""
|
||||
normalized = validate_controlled_data_path(data_path)
|
||||
for root in analysis.nodes or []:
|
||||
for node in _iter_nodes(root):
|
||||
if node.data_path == normalized and node.is_leaf:
|
||||
return XfaLeafValue(
|
||||
raw_value=str(node.raw_value or ''),
|
||||
normalized_value=str(node.normalized_value or ''),
|
||||
lines=list(node.lines or []),
|
||||
)
|
||||
raw = analysis.leaf_values_by_path.get(normalized)
|
||||
if raw is None:
|
||||
return None
|
||||
return build_xfa_leaf_value(raw)
|
||||
|
||||
|
||||
def _iter_nodes(node: XfaDatasetNode) -> list[XfaDatasetNode]:
|
||||
"""深度优先展开路径树节点。"""
|
||||
result = [node]
|
||||
for child in node.children:
|
||||
result.extend(_iter_nodes(child))
|
||||
return result
|
||||
|
||||
|
||||
def read_collection_rows(
|
||||
analysis: XfaDatasetAnalysis,
|
||||
collection_path: str,
|
||||
) -> list[dict[str, str]]:
|
||||
"""
|
||||
按权威/镜像集合路径读取每一行叶子字段原值。
|
||||
|
||||
核心逻辑:查找 data_path 等于集合路径的全部 DATA 行容器;每行以
|
||||
子叶子的绝对受控路径为键返回原值。同路径多行互不覆盖(与 leaf_values_by_path 不同)。
|
||||
|
||||
Args:
|
||||
analysis: 已完成的 datasets 分析。
|
||||
collection_path: 权威或镜像集合绝对路径(如 /data/ITEMS/DATA)。
|
||||
|
||||
Returns:
|
||||
行字典列表;集合不存在时返回空列表。
|
||||
|
||||
Raises:
|
||||
XfaDatasetParseError: 路径语法非法。
|
||||
"""
|
||||
normalized = validate_controlled_data_path(collection_path)
|
||||
rows: list[dict[str, str]] = []
|
||||
roots = list(analysis.nodes or [])
|
||||
for root in roots:
|
||||
for node in _iter_nodes(root):
|
||||
if node.data_path != normalized or not _is_line_row_container(node):
|
||||
continue
|
||||
row: dict[str, str] = {}
|
||||
for child in node.children:
|
||||
if child.is_leaf:
|
||||
row[child.data_path] = str(child.raw_value or '')
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def serialize_tree_node(node: XfaDatasetNode, *, include_values: bool = False) -> dict[str, Any]:
|
||||
"""
|
||||
序列化单个树节点供 API 返回。
|
||||
|
||||
Args:
|
||||
node: 数据集树节点。
|
||||
include_values: 是否包含脱敏样本值。
|
||||
|
||||
Returns:
|
||||
安全 DTO 字典。
|
||||
"""
|
||||
payload: dict[str, Any] = {
|
||||
'path_id': node.path_id,
|
||||
'local_name': node.local_name,
|
||||
'namespace_uri': node.namespace_uri,
|
||||
'data_path_hash': hash_data_path(node.data_path),
|
||||
'depth': node.depth,
|
||||
'cardinality': node.cardinality,
|
||||
'is_leaf': node.is_leaf,
|
||||
'is_header_candidate': node.is_header_candidate,
|
||||
'is_collection_candidate': node.is_collection_candidate,
|
||||
'children': [serialize_tree_node(child, include_values=include_values) for child in node.children],
|
||||
}
|
||||
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['line_count'] = len(node.lines or [])
|
||||
return payload
|
||||
|
||||
|
||||
def mask_value_for_dto(value: Any) -> str:
|
||||
"""
|
||||
将业务原值转为 DTO 允许返回的脱敏字符串。
|
||||
|
||||
Args:
|
||||
value: 任意原值。
|
||||
|
||||
Returns:
|
||||
脱敏字符串。
|
||||
"""
|
||||
return mask_sample_value(value)
|
||||
@@ -0,0 +1,367 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_packets.py
|
||||
|
||||
用途:从 PDF 读取 AcroForm/XFA packet,识别文档类型并返回受控 packet 摘要。
|
||||
依赖:pypdf、xfa_contract 资源上限与文档类型枚举。
|
||||
逻辑:由 runtime 与 layout Job 在 MinerU 前调用;只读 packet 字节,不执行脚本、不联网。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from io import BytesIO
|
||||
from typing import Any, Literal
|
||||
|
||||
from pypdf import PdfReader
|
||||
from pypdf.errors import PdfReadError
|
||||
from pypdf.generic import ArrayObject, IndirectObject, StreamObject
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_DEFAULT_MAX_PACKET_BYTES,
|
||||
XFA_DEFAULT_MAX_PDF_BYTES,
|
||||
XFA_SUPPORTED_DOCUMENT_KINDS,
|
||||
XfaDocumentKind,
|
||||
default_xfa_resource_limits,
|
||||
)
|
||||
|
||||
XFA_PACKET_NAMES = frozenset({
|
||||
'template',
|
||||
'datasets',
|
||||
'config',
|
||||
'templateCache',
|
||||
'xfdf',
|
||||
'xslt',
|
||||
'pdf',
|
||||
'form',
|
||||
})
|
||||
|
||||
_UNSAFE_XML_MARKERS = re.compile(
|
||||
r'<!DOCTYPE|<!ENTITY|&[A-Za-z_][A-Za-z0-9_-]*;|<!ELEMENT|<!ATTLIST',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class XfaPacket:
|
||||
"""单个 XFA packet 的受控摘要;不含持久化所需的完整 XML 外泄面。"""
|
||||
|
||||
name: str
|
||||
byte_length: int
|
||||
checksum: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaPacketReadResult:
|
||||
"""XFA packet 读取结果。"""
|
||||
|
||||
document_kind: XfaDocumentKind
|
||||
packets: list[XfaPacket] = field(default_factory=list)
|
||||
packet_bytes_by_name: dict[str, bytes] = field(default_factory=dict)
|
||||
has_acroform: bool = False
|
||||
has_acroform_fields: bool = False
|
||||
has_xfa: bool = False
|
||||
page_count: int = 0
|
||||
error_code: str | None = None
|
||||
route_reason: str | None = None
|
||||
supported: bool = False
|
||||
|
||||
|
||||
class XfaPacketError(Exception):
|
||||
"""XFA packet 读取阶段的确定性业务失败。"""
|
||||
|
||||
def __init__(self, *, error_code: str, route_reason: str, message: str = '') -> None:
|
||||
super().__init__(message or error_code)
|
||||
self.error_code = error_code
|
||||
self.route_reason = route_reason
|
||||
|
||||
|
||||
def compute_packet_checksum(packet_bytes: bytes) -> str:
|
||||
"""
|
||||
计算 packet 稳定 SHA-256 校验和。
|
||||
|
||||
Args:
|
||||
packet_bytes: 原始 packet 字节。
|
||||
|
||||
Returns:
|
||||
带 `sha256:` 前缀的十六进制摘要。
|
||||
"""
|
||||
return f'sha256:{hashlib.sha256(packet_bytes).hexdigest()}'
|
||||
|
||||
|
||||
def _resolve_limits(limits: dict[str, int] | None) -> dict[str, int]:
|
||||
"""合并调用方 limits 与契约默认值。"""
|
||||
merged = default_xfa_resource_limits()
|
||||
if isinstance(limits, dict):
|
||||
merged.update({key: int(value) for key, value in limits.items() if key in merged})
|
||||
return merged
|
||||
|
||||
|
||||
def _stream_bytes(value: Any) -> bytes:
|
||||
"""从 pypdf StreamObject 或原始 bytes/str 提取 packet 字节。"""
|
||||
if isinstance(value, bytes):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
return value.encode('utf-8', errors='ignore')
|
||||
if isinstance(value, StreamObject):
|
||||
raw = value.get_data()
|
||||
return raw if isinstance(raw, bytes) else bytes(raw or b'')
|
||||
if isinstance(value, IndirectObject):
|
||||
resolved = value.get_object()
|
||||
return _stream_bytes(resolved)
|
||||
return bytes(value or b'')
|
||||
|
||||
|
||||
def _collect_xfa_packets_from_reader(
|
||||
reader: PdfReader,
|
||||
*,
|
||||
max_packet_bytes: int,
|
||||
) -> tuple[dict[str, bytes], list[XfaPacket], str | None]:
|
||||
"""
|
||||
从 PdfReader 提取命名 XFA packet。
|
||||
|
||||
核心逻辑:兼容 pypdf 的 reader.xfa 字典与 AcroForm `/XFA` 数组/单流两种容器形态。
|
||||
|
||||
Args:
|
||||
reader: 已打开的 PDF 阅读器。
|
||||
max_packet_bytes: 单 packet 字节上限。
|
||||
|
||||
Returns:
|
||||
(packet_bytes_by_name, packet_summaries, error_code)。
|
||||
"""
|
||||
packet_bytes: dict[str, bytes] = {}
|
||||
summaries: list[XfaPacket] = []
|
||||
|
||||
def _register(name: str, payload: bytes) -> str | None:
|
||||
normalized_name = str(name or '').strip()
|
||||
if not normalized_name:
|
||||
return None
|
||||
if len(payload) > max_packet_bytes:
|
||||
return 'XFA_PACKET_TOO_LARGE'
|
||||
checksum = compute_packet_checksum(payload)
|
||||
packet_bytes[normalized_name] = payload
|
||||
summaries.append(XfaPacket(name=normalized_name, byte_length=len(payload), checksum=checksum))
|
||||
return None
|
||||
|
||||
xfa_obj = getattr(reader, 'xfa', None)
|
||||
xfa_map = xfa_obj if isinstance(xfa_obj, dict) else getattr(xfa_obj, 'xfa', None)
|
||||
if isinstance(xfa_map, dict) and xfa_map:
|
||||
for name, payload in xfa_map.items():
|
||||
error_code = _register(str(name), _stream_bytes(payload))
|
||||
if error_code:
|
||||
return packet_bytes, summaries, error_code
|
||||
|
||||
try:
|
||||
root = reader.trailer.get('/Root') or reader.trailer['/Root']
|
||||
acroform = root.get('/AcroForm') if hasattr(root, 'get') else None
|
||||
if acroform is not None and hasattr(acroform, 'get_object'):
|
||||
acroform = acroform.get_object()
|
||||
xfa_ref = acroform.get('/XFA') if isinstance(acroform, dict) or hasattr(acroform, 'get') else None
|
||||
if xfa_ref is not None and hasattr(xfa_ref, 'get_object'):
|
||||
xfa_ref = xfa_ref.get_object()
|
||||
except Exception:
|
||||
xfa_ref = None
|
||||
|
||||
if isinstance(xfa_ref, ArrayObject):
|
||||
index = 0
|
||||
while index < len(xfa_ref):
|
||||
name_obj = xfa_ref[index]
|
||||
index += 1
|
||||
if index >= len(xfa_ref):
|
||||
break
|
||||
payload_obj = xfa_ref[index]
|
||||
index += 1
|
||||
name = str(getattr(name_obj, 'name', name_obj) or name_obj or '').strip().lstrip('/')
|
||||
error_code = _register(name, _stream_bytes(payload_obj))
|
||||
if error_code:
|
||||
return packet_bytes, summaries, error_code
|
||||
elif xfa_ref is not None and not packet_bytes:
|
||||
error_code = _register('xfa', _stream_bytes(xfa_ref))
|
||||
if error_code:
|
||||
return packet_bytes, summaries, error_code
|
||||
|
||||
return packet_bytes, summaries, None
|
||||
|
||||
|
||||
def _has_acroform_fields(reader: PdfReader) -> bool:
|
||||
"""判断 AcroForm 是否包含可读取字段。"""
|
||||
try:
|
||||
fields = reader.get_fields() or {}
|
||||
return bool(fields)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _detect_document_kind(
|
||||
*,
|
||||
has_acroform: bool,
|
||||
has_xfa: bool,
|
||||
has_datasets: bool,
|
||||
page_count: int,
|
||||
has_acroform_fields: bool,
|
||||
) -> XfaDocumentKind:
|
||||
"""
|
||||
根据 PDF 结构探测 document_kind。
|
||||
|
||||
Args:
|
||||
has_acroform: 是否存在 AcroForm 字典。
|
||||
has_xfa: 是否检测到 XFA packet 容器。
|
||||
has_datasets: 是否包含 datasets packet。
|
||||
page_count: 页面数。
|
||||
has_acroform_fields: 是否存在 AcroForm 字段。
|
||||
|
||||
Returns:
|
||||
plain_pdf | acroform | xfa_hybrid | pure_xfa | unsupported。
|
||||
"""
|
||||
if not has_xfa:
|
||||
if has_acroform and has_acroform_fields:
|
||||
return 'acroform'
|
||||
return 'plain_pdf'
|
||||
if not has_datasets:
|
||||
return 'unsupported'
|
||||
if page_count > 0 or has_acroform_fields:
|
||||
return 'xfa_hybrid'
|
||||
return 'pure_xfa'
|
||||
|
||||
|
||||
def read_xfa_packets(
|
||||
pdf_bytes: bytes,
|
||||
*,
|
||||
limits: dict[str, int] | None = None,
|
||||
) -> XfaPacketReadResult:
|
||||
"""
|
||||
读取 PDF 中的 XFA packet 并识别文档类型。
|
||||
|
||||
核心逻辑:先校验 PDF 总大小,再用 pypdf 只读 AcroForm/XFA;不执行 JavaScript/FormCalc,
|
||||
不触发任何网络访问。
|
||||
|
||||
Args:
|
||||
pdf_bytes: 原始 PDF 字节。
|
||||
limits: 可选资源上限覆盖项。
|
||||
|
||||
Returns:
|
||||
XfaPacketReadResult:含 packet 摘要、document_kind 与支持标记。
|
||||
|
||||
Raises:
|
||||
XfaPacketError: PDF 损坏或 packet 超限等确定性失败。
|
||||
"""
|
||||
resolved = _resolve_limits(limits)
|
||||
if len(pdf_bytes) > resolved['max_pdf_bytes']:
|
||||
raise XfaPacketError(
|
||||
error_code='XFA_PACKET_TOO_LARGE',
|
||||
route_reason='xfa_packet_too_large',
|
||||
message='pdf exceeds max_pdf_bytes',
|
||||
)
|
||||
if not pdf_bytes:
|
||||
raise XfaPacketError(
|
||||
error_code='XFA_UNSUPPORTED_DOCUMENT',
|
||||
route_reason='xfa_unsupported_document',
|
||||
message='empty pdf',
|
||||
)
|
||||
|
||||
try:
|
||||
reader = PdfReader(BytesIO(pdf_bytes), strict=False)
|
||||
except PdfReadError as exc:
|
||||
raise XfaPacketError(
|
||||
error_code='XFA_UNSUPPORTED_DOCUMENT',
|
||||
route_reason='xfa_unsupported_document',
|
||||
message='pdf unreadable',
|
||||
) from exc
|
||||
|
||||
page_count = len(reader.pages)
|
||||
has_acroform = False
|
||||
try:
|
||||
root = reader.trailer.get('/Root') or reader.trailer['/Root']
|
||||
acroform = root.get('/AcroForm') if hasattr(root, 'get') else None
|
||||
has_acroform = acroform is not None
|
||||
except Exception:
|
||||
has_acroform = False
|
||||
|
||||
packet_bytes, summaries, packet_error = _collect_xfa_packets_from_reader(
|
||||
reader,
|
||||
max_packet_bytes=int(resolved['max_packet_bytes']),
|
||||
)
|
||||
if packet_error:
|
||||
route = 'xfa_packet_too_large' if packet_error == 'XFA_PACKET_TOO_LARGE' else 'xfa_unsupported_document'
|
||||
raise XfaPacketError(error_code=packet_error, route_reason=route)
|
||||
|
||||
has_xfa = bool(packet_bytes)
|
||||
has_datasets = 'datasets' in packet_bytes
|
||||
has_acroform_fields = _has_acroform_fields(reader) if has_acroform else False
|
||||
document_kind = _detect_document_kind(
|
||||
has_acroform=has_acroform,
|
||||
has_xfa=has_xfa,
|
||||
has_datasets=has_datasets,
|
||||
page_count=page_count,
|
||||
has_acroform_fields=has_acroform_fields,
|
||||
)
|
||||
supported = document_kind in XFA_SUPPORTED_DOCUMENT_KINDS
|
||||
error_code: str | None = None
|
||||
route_reason: str | None = None
|
||||
if has_xfa and not has_datasets:
|
||||
error_code = 'XFA_DATASET_MISSING'
|
||||
route_reason = 'xfa_dataset_missing'
|
||||
elif document_kind == 'pure_xfa':
|
||||
error_code = 'XFA_UNSUPPORTED_DOCUMENT'
|
||||
route_reason = 'xfa_unsupported_document'
|
||||
elif document_kind == 'unsupported':
|
||||
error_code = 'XFA_UNSUPPORTED_DOCUMENT'
|
||||
route_reason = 'xfa_unsupported_document'
|
||||
|
||||
return XfaPacketReadResult(
|
||||
document_kind=document_kind,
|
||||
packets=summaries,
|
||||
packet_bytes_by_name=packet_bytes,
|
||||
has_acroform=has_acroform,
|
||||
has_acroform_fields=has_acroform_fields,
|
||||
has_xfa=has_xfa,
|
||||
page_count=page_count,
|
||||
error_code=error_code,
|
||||
route_reason=route_reason,
|
||||
supported=supported,
|
||||
)
|
||||
|
||||
|
||||
def preflight_xml_bytes(xml_bytes: bytes) -> None:
|
||||
"""
|
||||
在 lxml 解析前拒绝 DOCTYPE/ENTITY 等不安全标记。
|
||||
|
||||
Args:
|
||||
xml_bytes: 待解析 XML 字节。
|
||||
|
||||
Raises:
|
||||
XfaPacketError: 检测到不安全 XML 结构。
|
||||
"""
|
||||
sample = xml_bytes[:65536].decode('utf-8', errors='ignore')
|
||||
if _UNSAFE_XML_MARKERS.search(sample):
|
||||
raise XfaPacketError(
|
||||
error_code='XFA_UNSAFE_XML',
|
||||
route_reason='xfa_unsafe_xml',
|
||||
message='unsafe xml marker detected',
|
||||
)
|
||||
|
||||
|
||||
def is_deterministic_xfa_error(error_code: str | None) -> bool:
|
||||
"""
|
||||
判断 XFA 错误码是否属于确定性业务失败(不应重试)。
|
||||
|
||||
Args:
|
||||
error_code: XFA_ERROR_CODES 中的稳定错误码。
|
||||
|
||||
Returns:
|
||||
True 表示 Worker 不应重试。
|
||||
"""
|
||||
deterministic = {
|
||||
'XFA_DATASET_MISSING',
|
||||
'XFA_UNSAFE_XML',
|
||||
'XFA_PACKET_TOO_LARGE',
|
||||
'XFA_XML_DEPTH_EXCEEDED',
|
||||
'XFA_XML_NODE_LIMIT_EXCEEDED',
|
||||
'XFA_LINE_ROW_LIMIT_EXCEEDED',
|
||||
'XFA_UNSUPPORTED_DOCUMENT',
|
||||
'XFA_PATH_INVALID',
|
||||
'XFA_PATH_UNKNOWN',
|
||||
'XFA_DEFINITION_INVALID',
|
||||
}
|
||||
return str(error_code or '') in deterministic
|
||||
@@ -0,0 +1,761 @@
|
||||
"""
|
||||
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 字段)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.document_layout.order_profile_extractors import (
|
||||
parse_unit_price_with_price_unit,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
OrderXfaDatasetProfile,
|
||||
XfaFieldEvidenceRef,
|
||||
XFA_PARSER_IDENTITY,
|
||||
hash_data_path,
|
||||
sanitize_xfa_dto,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import (
|
||||
XfaDatasetAnalysis,
|
||||
read_collection_rows,
|
||||
read_dataset_value,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
XfaSplitRuleSet,
|
||||
parse_split_rule_sets,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_engine import (
|
||||
execute_split_rule_set,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
normalize_order_field_value,
|
||||
validate_order_field_value,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaExtractedField:
|
||||
"""单字段提取结果(含内部原始值,对外投影时剥离)。"""
|
||||
|
||||
field_id: str
|
||||
field_code: str
|
||||
mapping_id: str
|
||||
data_path: str
|
||||
raw_value: str | None
|
||||
normalized_value: Any
|
||||
quote: str
|
||||
normalizer_key: str | None
|
||||
evidence: dict[str, Any]
|
||||
issues: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaExtractionResult:
|
||||
"""XFA 正式提取结果;rows 形状对齐坐标路径以便复用订单组装。"""
|
||||
|
||||
status: str
|
||||
reason_codes: list[str] = field(default_factory=list)
|
||||
header_fields: list[XfaExtractedField] = field(default_factory=list)
|
||||
rows: list[dict[str, Any]] = field(default_factory=list)
|
||||
packet_checksum: str | None = None
|
||||
dataset_structure_fingerprint: str | None = None
|
||||
parser_identity: str = XFA_PARSER_IDENTITY
|
||||
profile_checksum: str | None = None
|
||||
evidence_summary: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
def _schema_field_config(
|
||||
*,
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
field_id: str,
|
||||
field_code: str,
|
||||
value_type: str,
|
||||
normalizer_key: str | None,
|
||||
validator_key: str | None,
|
||||
) -> dict[str, Any]:
|
||||
"""合并 Schema 字段配置与映射上的类型/normalizer。"""
|
||||
config = dict(schema_fields.get(field_id) or {})
|
||||
if not config:
|
||||
config = {
|
||||
'field_id': field_id,
|
||||
'field_code': field_code,
|
||||
'value_type': value_type or 'string',
|
||||
'normalizer_key': normalizer_key or 'trim',
|
||||
'validator_keys': [validator_key] if validator_key else [],
|
||||
}
|
||||
else:
|
||||
config = dict(config)
|
||||
config.setdefault('field_id', field_id)
|
||||
config.setdefault('field_code', field_code)
|
||||
if value_type:
|
||||
config['value_type'] = value_type
|
||||
if normalizer_key:
|
||||
config['normalizer_key'] = normalizer_key
|
||||
if validator_key:
|
||||
keys = list(config.get('validator_keys') or [])
|
||||
if validator_key not in keys:
|
||||
keys.append(validator_key)
|
||||
config['validator_keys'] = keys
|
||||
return config
|
||||
|
||||
|
||||
def _normalize_display_value(value: Any) -> Any:
|
||||
"""
|
||||
将 Decimal/date 收敛为 JSON 可序列化的业务可读形式。
|
||||
|
||||
核心逻辑:整数型 Decimal → int(30.000 → 30);非整数 Decimal → 去尾零字符串;
|
||||
date → ISO 字符串。与订单组装 json.dumps 共识逻辑兼容。
|
||||
"""
|
||||
if isinstance(value, Decimal):
|
||||
normalized = value.normalize()
|
||||
if normalized == normalized.to_integral_value():
|
||||
return int(normalized)
|
||||
text = format(normalized, 'f')
|
||||
if '.' in text:
|
||||
text = text.rstrip('0').rstrip('.')
|
||||
return text
|
||||
if isinstance(value, datetime):
|
||||
return value.date().isoformat()
|
||||
if isinstance(value, date):
|
||||
return value.isoformat()
|
||||
return value
|
||||
|
||||
|
||||
def _build_evidence_ref(
|
||||
*,
|
||||
document_id: int,
|
||||
packet_checksum: str,
|
||||
data_path: str,
|
||||
mapping_id: str,
|
||||
normalized_value: Any,
|
||||
normalizer_key: str | None,
|
||||
cross_check_status: str = 'unavailable',
|
||||
) -> dict[str, Any]:
|
||||
"""构建普通 DTO 允许的字段 evidence(无明文路径/XML)。"""
|
||||
display = normalized_value
|
||||
if isinstance(display, Decimal):
|
||||
display = format(display, 'f')
|
||||
elif display is not None and not isinstance(display, (str, int, float, bool)):
|
||||
display = str(display)
|
||||
ref = XfaFieldEvidenceRef(
|
||||
source='xfa_dataset',
|
||||
document_id=max(int(document_id or 1), 1),
|
||||
packet_checksum=packet_checksum,
|
||||
data_path_hash=hash_data_path(data_path),
|
||||
mapping_id=mapping_id,
|
||||
raw_value_snapshot_ref=None,
|
||||
normalized_value=None if display is None else str(display),
|
||||
normalizer_key=normalizer_key,
|
||||
cross_check_status=cross_check_status, # type: ignore[arg-type]
|
||||
)
|
||||
return sanitize_xfa_dto(ref.model_dump(mode='json'))
|
||||
|
||||
|
||||
def _extract_one_field(
|
||||
*,
|
||||
raw_value: str | None,
|
||||
mapping_id: str,
|
||||
field_id: str,
|
||||
field_code: str,
|
||||
data_path: str,
|
||||
value_type: str,
|
||||
normalizer_key: str | None,
|
||||
validator_key: str | None,
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
document_id: int,
|
||||
packet_checksum: str,
|
||||
) -> XfaExtractedField:
|
||||
"""标准化并校验单个映射字段。"""
|
||||
config = _schema_field_config(
|
||||
schema_fields=schema_fields,
|
||||
field_id=field_id,
|
||||
field_code=field_code,
|
||||
value_type=value_type,
|
||||
normalizer_key=normalizer_key,
|
||||
validator_key=validator_key,
|
||||
)
|
||||
issues: list[str] = []
|
||||
normalized: Any = None
|
||||
if raw_value in (None, ''):
|
||||
issues.append(f'order_profile_field_invalid:{field_code}')
|
||||
else:
|
||||
try:
|
||||
typed = normalize_order_field_value(raw_value, config)
|
||||
except (TypeError, ValueError, ValidationError):
|
||||
typed = None
|
||||
issues.append(f'order_profile_field_invalid:{field_code}')
|
||||
if typed is not None and not validate_order_field_value(typed, config):
|
||||
issues.append(f'order_profile_field_invalid:{field_code}')
|
||||
typed = None
|
||||
if typed is not None:
|
||||
normalized = _normalize_display_value(typed)
|
||||
evidence = _build_evidence_ref(
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
data_path=data_path,
|
||||
mapping_id=mapping_id,
|
||||
normalized_value=normalized,
|
||||
normalizer_key=str(config.get('normalizer_key') or normalizer_key or '') or None,
|
||||
)
|
||||
return XfaExtractedField(
|
||||
field_id=str(config.get('field_id') or field_id),
|
||||
field_code=str(config.get('field_code') or field_code),
|
||||
mapping_id=mapping_id,
|
||||
data_path=data_path,
|
||||
raw_value=raw_value,
|
||||
normalized_value=normalized,
|
||||
quote=str(raw_value or '')[:1000],
|
||||
normalizer_key=str(config.get('normalizer_key') or '') or None,
|
||||
evidence=evidence,
|
||||
issues=issues,
|
||||
)
|
||||
|
||||
|
||||
def _is_formal_ready_split_rule_set(rule_set: XfaSplitRuleSet) -> bool:
|
||||
"""
|
||||
判断拆分规则集是否可用于正式提取。
|
||||
|
||||
核心逻辑:须 confirmed/published、非 requires_confirmation、非 system_suggestion。
|
||||
"""
|
||||
if rule_set.requires_confirmation:
|
||||
return False
|
||||
if rule_set.status not in ('confirmed', 'published'):
|
||||
return False
|
||||
if rule_set.source == 'system_suggestion':
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _build_path_id_to_data_path(profile: OrderXfaDatasetProfile) -> dict[str, str]:
|
||||
"""从 Header/Line 映射构建 path_id → data_path 索引。"""
|
||||
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)
|
||||
return mapping
|
||||
|
||||
|
||||
def _resolve_split_source_data_path(
|
||||
rule_set: XfaSplitRuleSet,
|
||||
*,
|
||||
line_fields: list[Any],
|
||||
path_id_to_data_path: dict[str, str],
|
||||
) -> str | None:
|
||||
"""
|
||||
解析拆分规则集源字段 data_path。
|
||||
|
||||
核心逻辑:优先使用服务端冻结的 source_data_path,其次按 source_path_id 命中映射;
|
||||
旧定义最后按 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):
|
||||
return data_path or None
|
||||
return None
|
||||
|
||||
|
||||
def _apply_split_rules_for_header(
|
||||
*,
|
||||
dataset_analysis: XfaDatasetAnalysis,
|
||||
rule_sets: list[XfaSplitRuleSet],
|
||||
path_id_to_data_path: dict[str, str],
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
schema_by_code: dict[str, dict[str, Any]],
|
||||
document_id: int,
|
||||
packet_checksum: str,
|
||||
) -> tuple[list[XfaExtractedField], list[dict[str, Any]], list[str], bool]:
|
||||
"""
|
||||
对文档级源字段执行拆分规则一次。
|
||||
|
||||
Returns:
|
||||
(header_fields, split_evidence, issues, required_missing)
|
||||
"""
|
||||
fields: list[XfaExtractedField] = []
|
||||
evidence: list[dict[str, Any]] = []
|
||||
issues: list[str] = []
|
||||
required_missing = False
|
||||
for rule_set in rule_sets:
|
||||
data_path = _resolve_split_source_data_path(
|
||||
rule_set,
|
||||
line_fields=[],
|
||||
path_id_to_data_path=path_id_to_data_path,
|
||||
)
|
||||
if not data_path:
|
||||
issues.append('xfa_split_rule_unconfirmed')
|
||||
continue
|
||||
raw_value = read_dataset_value(dataset_analysis, data_path)
|
||||
split_result = execute_split_rule_set(raw_value=raw_value or '', rule_set=rule_set)
|
||||
if split_result.status != 'parsed':
|
||||
issues.append('xfa_split_rule_needs_review')
|
||||
issues.extend(
|
||||
f'xfa_split:{item.code}' for item in split_result.diagnostics if item.code
|
||||
)
|
||||
for segment in split_result.evidence_only_segments:
|
||||
evidence.append({
|
||||
'segment_id': segment.segment_id,
|
||||
'segment_code': segment.segment_code,
|
||||
'display_name': segment.display_name,
|
||||
'line_no': segment.line_no,
|
||||
'line_end_no': segment.line_end_no,
|
||||
'raw_text': segment.raw_text,
|
||||
'normalized_text': segment.normalized_text,
|
||||
'rule_id': segment.rule_id,
|
||||
'source_path_id': rule_set.source_path_id,
|
||||
})
|
||||
for field_code, mapped_raw in split_result.mapped_fields.items():
|
||||
cfg = schema_by_code.get(field_code) or {}
|
||||
extracted = _extract_one_field(
|
||||
raw_value=mapped_raw,
|
||||
mapping_id=f'split-{rule_set.rule_id}-{field_code}'[:64],
|
||||
field_id=str(cfg.get('field_id') or field_code),
|
||||
field_code=field_code,
|
||||
data_path=data_path,
|
||||
value_type=str(cfg.get('value_type') or 'string'),
|
||||
normalizer_key=str(cfg.get('normalizer_key') or 'trim') or None,
|
||||
validator_key=(cfg.get('validator_keys') or [None])[0],
|
||||
schema_fields=schema_fields,
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
)
|
||||
fields.append(extracted)
|
||||
issues.extend(extracted.issues)
|
||||
if extracted.normalized_value is None:
|
||||
required_missing = True
|
||||
return fields, evidence, issues, required_missing
|
||||
|
||||
|
||||
def _schema_by_field_code(schema_fields: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]:
|
||||
"""field_code → Schema 配置。"""
|
||||
indexed: dict[str, dict[str, Any]] = {}
|
||||
for item in schema_fields.values():
|
||||
code = str(item.get('field_code') or '').strip()
|
||||
if code:
|
||||
indexed[code] = item
|
||||
return indexed
|
||||
|
||||
|
||||
def _apply_split_rules_for_row(
|
||||
*,
|
||||
row_values: dict[str, str],
|
||||
rule_sets: list[XfaSplitRuleSet],
|
||||
line_fields: list[Any],
|
||||
path_id_to_data_path: dict[str, str],
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
schema_by_code: dict[str, dict[str, Any]],
|
||||
document_id: int,
|
||||
packet_checksum: str,
|
||||
row_index: int,
|
||||
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], set[str], list[str], bool]:
|
||||
"""
|
||||
对单行执行已确认拆分规则并产出 Schema 字段值与 evidence_only 段。
|
||||
|
||||
Returns:
|
||||
(values, split_evidence, produced_field_codes, issues, required_missing)
|
||||
"""
|
||||
values: list[dict[str, Any]] = []
|
||||
split_evidence: list[dict[str, Any]] = []
|
||||
produced_codes: set[str] = set()
|
||||
issues: list[str] = []
|
||||
required_missing = False
|
||||
|
||||
for rule_set in rule_sets:
|
||||
data_path = _resolve_split_source_data_path(
|
||||
rule_set,
|
||||
line_fields=line_fields,
|
||||
path_id_to_data_path=path_id_to_data_path,
|
||||
)
|
||||
if not data_path:
|
||||
issues.append('xfa_split_rule_unconfirmed')
|
||||
continue
|
||||
raw_value = row_values.get(data_path)
|
||||
split_result = execute_split_rule_set(raw_value=raw_value or '', rule_set=rule_set)
|
||||
if split_result.status != 'parsed':
|
||||
issues.append('xfa_split_rule_needs_review')
|
||||
for diagnostic in split_result.diagnostics:
|
||||
if diagnostic.code:
|
||||
issues.append(f'xfa_split:{diagnostic.code}')
|
||||
for segment in split_result.evidence_only_segments:
|
||||
split_evidence.append({
|
||||
'segment_id': segment.segment_id,
|
||||
'segment_code': segment.segment_code,
|
||||
'display_name': segment.display_name,
|
||||
'line_no': segment.line_no,
|
||||
'line_end_no': segment.line_end_no,
|
||||
'raw_text': segment.raw_text,
|
||||
'normalized_text': segment.normalized_text,
|
||||
'rule_id': segment.rule_id,
|
||||
'source_path_id': rule_set.source_path_id,
|
||||
'row_index': row_index,
|
||||
})
|
||||
for field_code, mapped_raw in split_result.mapped_fields.items():
|
||||
cfg = schema_by_code.get(field_code) or {}
|
||||
field_id = str(cfg.get('field_id') or field_code)
|
||||
extracted = _extract_one_field(
|
||||
raw_value=mapped_raw,
|
||||
mapping_id=f'split-{rule_set.rule_id}-{field_code}'[:64],
|
||||
field_id=field_id,
|
||||
field_code=field_code,
|
||||
data_path=data_path,
|
||||
value_type=str(cfg.get('value_type') or 'string'),
|
||||
normalizer_key=str(cfg.get('normalizer_key') or 'trim') or None,
|
||||
validator_key=(cfg.get('validator_keys') or [None])[0],
|
||||
schema_fields=schema_fields,
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
)
|
||||
if extracted.issues:
|
||||
issues.extend(extracted.issues)
|
||||
if extracted.normalized_value is None:
|
||||
required_missing = True
|
||||
continue
|
||||
produced_codes.add(field_code)
|
||||
values.append({
|
||||
'field_id': extracted.field_id,
|
||||
'field_code': extracted.field_code,
|
||||
'value': extracted.normalized_value,
|
||||
'quote': extracted.quote,
|
||||
'source': 'xfa_dataset',
|
||||
'evidence_ref': extracted.evidence,
|
||||
'highlight_source': 'xfa_split',
|
||||
'row_index': row_index,
|
||||
'split_rule_id': rule_set.rule_id,
|
||||
})
|
||||
return values, split_evidence, produced_codes, issues, required_missing
|
||||
|
||||
|
||||
def extract_xfa_profile(
|
||||
*,
|
||||
raw_profile: dict[str, Any],
|
||||
dataset_analysis: XfaDatasetAnalysis,
|
||||
schema_definition: dict[str, Any],
|
||||
document_id: int,
|
||||
packet_checksum: str,
|
||||
dataset_structure_fingerprint: str | None = None,
|
||||
) -> XfaExtractionResult:
|
||||
"""
|
||||
按冻结 XFA Profile 提取 Header 与权威明细行。
|
||||
|
||||
核心逻辑:校验 definition → 读 Header 叶子 → 读权威集合行 → Schema 标准化;
|
||||
权威集合缺失时 fail-closed(reason=xfa_authoritative_collection_missing)。
|
||||
|
||||
Args:
|
||||
raw_profile: 冻结 Profile 快照(含 definition / checksum)。
|
||||
dataset_analysis: 当前文档 datasets 分析。
|
||||
schema_definition: Run 冻结 Schema definition_json。
|
||||
document_id: 当前文档 ID(写入 evidence)。
|
||||
packet_checksum: datasets packet checksum。
|
||||
dataset_structure_fingerprint: 结构指纹(写入摘要)。
|
||||
|
||||
Returns:
|
||||
XfaExtractionResult:含 rows(对齐坐标路径)与安全 evidence_summary。
|
||||
"""
|
||||
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
|
||||
try:
|
||||
profile = OrderXfaDatasetProfile.model_validate(definition)
|
||||
except (TypeError, ValueError):
|
||||
return XfaExtractionResult(
|
||||
status='failed',
|
||||
reason_codes=['xfa_definition_invalid'],
|
||||
packet_checksum=packet_checksum,
|
||||
dataset_structure_fingerprint=dataset_structure_fingerprint,
|
||||
profile_checksum=str(raw_profile.get('checksum') or '') or None,
|
||||
)
|
||||
|
||||
schema_fields = {
|
||||
str(item.get('field_id') or ''): item
|
||||
for item in (schema_definition.get('fields') or [])
|
||||
if isinstance(item, dict) and item.get('enabled', True) and item.get('field_id')
|
||||
}
|
||||
|
||||
# [STEP 1] Header 映射
|
||||
header_fields: list[XfaExtractedField] = []
|
||||
header_issues: list[str] = []
|
||||
for mapping in profile.header_mappings:
|
||||
raw_value = read_dataset_value(dataset_analysis, mapping.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,
|
||||
schema_fields=schema_fields,
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
)
|
||||
header_fields.append(extracted)
|
||||
header_issues.extend(extracted.issues)
|
||||
|
||||
# [STEP 2] 权威集合行
|
||||
auth_path = profile.source_contract.authoritative_line_collection_path
|
||||
line_rows = read_collection_rows(dataset_analysis, auth_path)
|
||||
if not line_rows:
|
||||
return XfaExtractionResult(
|
||||
status='failed',
|
||||
reason_codes=['xfa_authoritative_collection_missing'],
|
||||
header_fields=header_fields,
|
||||
packet_checksum=packet_checksum,
|
||||
dataset_structure_fingerprint=dataset_structure_fingerprint,
|
||||
profile_checksum=str(raw_profile.get('checksum') or '') or None,
|
||||
evidence_summary={
|
||||
'header_field_count': len(header_fields),
|
||||
'line_row_count': 0,
|
||||
'parser_identity': XFA_PARSER_IDENTITY,
|
||||
},
|
||||
)
|
||||
|
||||
rows: list[dict[str, Any]] = []
|
||||
required_missing = False
|
||||
all_split_rule_sets = parse_split_rule_sets(profile.split_rules or [])
|
||||
# [STEP] 任意规则集未确认 → 彻底 fail-closed:不执行任何拆分产出 mapped 字段。
|
||||
has_unconfirmed_split_rules = bool(all_split_rule_sets) and any(
|
||||
not _is_formal_ready_split_rule_set(item) for item in all_split_rule_sets
|
||||
)
|
||||
formal_split_rule_sets = (
|
||||
[]
|
||||
if has_unconfirmed_split_rules
|
||||
else [item for item in all_split_rule_sets if _is_formal_ready_split_rule_set(item)]
|
||||
)
|
||||
path_id_to_data_path = _build_path_id_to_data_path(profile)
|
||||
schema_by_code = _schema_by_field_code(schema_fields)
|
||||
split_global_issues: list[str] = []
|
||||
normalized_auth_path = auth_path.rstrip('/')
|
||||
header_split_rule_sets = [
|
||||
item for item in formal_split_rule_sets
|
||||
if item.source_data_path and not str(item.source_data_path).startswith(f'{normalized_auth_path}/')
|
||||
]
|
||||
line_split_rule_sets = [item for item in formal_split_rule_sets if item not in header_split_rule_sets]
|
||||
header_split_evidence: list[dict[str, Any]] = []
|
||||
if header_split_rule_sets:
|
||||
split_headers, header_split_evidence, split_header_issues, split_header_missing = (
|
||||
_apply_split_rules_for_header(
|
||||
dataset_analysis=dataset_analysis,
|
||||
rule_sets=header_split_rule_sets,
|
||||
path_id_to_data_path=path_id_to_data_path,
|
||||
schema_fields=schema_fields,
|
||||
schema_by_code=schema_by_code,
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
)
|
||||
)
|
||||
header_fields.extend(split_headers)
|
||||
header_issues.extend(split_header_issues)
|
||||
required_missing = required_missing or split_header_missing
|
||||
split_source_path_ids = {str(item.source_path_id) for item in line_split_rule_sets}
|
||||
if has_unconfirmed_split_rules:
|
||||
split_global_issues.append('xfa_split_rule_unconfirmed')
|
||||
|
||||
for index, row_values in enumerate(line_rows, start=1):
|
||||
values: list[dict[str, Any]] = []
|
||||
issues = list(header_issues) + list(split_global_issues)
|
||||
split_evidence: list[dict[str, Any]] = []
|
||||
split_produced_codes: set[str] = set()
|
||||
# [STEP 2a] 已确认拆分规则:mapped 字段 + evidence_only 段。
|
||||
if line_split_rule_sets:
|
||||
split_values, split_evidence, split_produced_codes, split_issues, split_required_missing = (
|
||||
_apply_split_rules_for_row(
|
||||
row_values=row_values,
|
||||
rule_sets=line_split_rule_sets,
|
||||
line_fields=list(profile.line_mapping.fields),
|
||||
path_id_to_data_path=path_id_to_data_path,
|
||||
schema_fields=schema_fields,
|
||||
schema_by_code=schema_by_code,
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
row_index=index,
|
||||
)
|
||||
)
|
||||
values.extend(split_values)
|
||||
issues.extend(split_issues)
|
||||
if split_required_missing:
|
||||
required_missing = True
|
||||
# Header 字段挂到每行,供 _build_approved_profile_order_result 聚合。
|
||||
for header in header_fields:
|
||||
if header.normalized_value is None:
|
||||
required_missing = True
|
||||
continue
|
||||
values.append({
|
||||
'field_id': header.field_id,
|
||||
'field_code': header.field_code,
|
||||
'value': header.normalized_value,
|
||||
'quote': header.quote,
|
||||
'source': 'xfa_dataset',
|
||||
'evidence_ref': header.evidence,
|
||||
'highlight_source': 'xfa_dataset',
|
||||
})
|
||||
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:
|
||||
continue
|
||||
if str(mapping.path_id or '') in split_source_path_ids:
|
||||
continue
|
||||
raw_value = row_values.get(mapping.data_path)
|
||||
extract_raw = raw_value
|
||||
# [STEP] NETPR 复合值:拆出单价;价格单位若无独立映射则稍后补齐。
|
||||
if str(mapping.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
|
||||
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,
|
||||
schema_fields=schema_fields,
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
)
|
||||
# 保留原文 quote(含 ``898.72 / 1``)便于审计对账。
|
||||
if (
|
||||
str(mapping.field_code or '') == 'unit_price'
|
||||
and raw_value not in (None, '')
|
||||
and extract_raw != raw_value
|
||||
):
|
||||
extracted = XfaExtractedField(
|
||||
field_id=extracted.field_id,
|
||||
field_code=extracted.field_code,
|
||||
mapping_id=extracted.mapping_id,
|
||||
data_path=extracted.data_path,
|
||||
raw_value=str(raw_value),
|
||||
normalized_value=extracted.normalized_value,
|
||||
quote=str(raw_value)[:1000],
|
||||
normalizer_key=extracted.normalizer_key,
|
||||
evidence=extracted.evidence,
|
||||
issues=extracted.issues,
|
||||
)
|
||||
if extracted.issues:
|
||||
issues.extend(extracted.issues)
|
||||
if extracted.normalized_value is None:
|
||||
required_missing = True
|
||||
continue
|
||||
values.append({
|
||||
'field_id': extracted.field_id,
|
||||
'field_code': extracted.field_code,
|
||||
'value': extracted.normalized_value,
|
||||
'quote': extracted.quote,
|
||||
'source': 'xfa_dataset',
|
||||
'evidence_ref': extracted.evidence,
|
||||
'highlight_source': 'xfa_dataset',
|
||||
'row_index': index,
|
||||
})
|
||||
|
||||
# 仅映射 NETPR 复合值、未单独映射 PEINH 时,补齐 price_unit。
|
||||
present_codes = {
|
||||
str(item.get('field_code') or '')
|
||||
for item in values
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
if pending_price_unit_raw and 'price_unit' not in present_codes:
|
||||
pu_schema = next(
|
||||
(
|
||||
item for item in schema_fields.values()
|
||||
if str(item.get('field_code') or '') == 'price_unit'
|
||||
),
|
||||
None,
|
||||
)
|
||||
pu_field_id = str((pu_schema or {}).get('field_id') or 'price_unit')
|
||||
pu_extracted = _extract_one_field(
|
||||
raw_value=pending_price_unit_raw,
|
||||
mapping_id='derived-unit-price-price-unit',
|
||||
field_id=pu_field_id,
|
||||
field_code='price_unit',
|
||||
data_path=str(pending_price_unit_path or '/data'),
|
||||
value_type=str((pu_schema or {}).get('value_type') or 'integer'),
|
||||
normalizer_key=str((pu_schema or {}).get('normalizer_key') or 'trim') or None,
|
||||
validator_key=None,
|
||||
schema_fields=schema_fields,
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
)
|
||||
if pu_extracted.issues:
|
||||
issues.extend(pu_extracted.issues)
|
||||
if pu_extracted.normalized_value is None:
|
||||
required_missing = True
|
||||
else:
|
||||
values.append({
|
||||
'field_id': pu_extracted.field_id,
|
||||
'field_code': 'price_unit',
|
||||
'value': pu_extracted.normalized_value,
|
||||
'quote': pu_extracted.quote,
|
||||
'source': 'xfa_dataset',
|
||||
'evidence_ref': pu_extracted.evidence,
|
||||
'highlight_source': 'xfa_dataset',
|
||||
'row_index': index,
|
||||
'derived_from': 'unit_price_price_unit',
|
||||
})
|
||||
rows.append({
|
||||
'row_index': index,
|
||||
'status': 'parsed' if not issues else 'needs_review',
|
||||
'fields': values,
|
||||
'issues': sorted(set(issues)),
|
||||
'split_evidence': split_evidence,
|
||||
})
|
||||
|
||||
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):
|
||||
reason_codes.append('xfa_required_field_missing')
|
||||
|
||||
evidence_summary = sanitize_xfa_dto({
|
||||
'header_field_count': len(header_fields),
|
||||
'line_row_count': len(rows),
|
||||
'packet_checksum': packet_checksum,
|
||||
'dataset_structure_fingerprint': dataset_structure_fingerprint,
|
||||
'parser_identity': XFA_PARSER_IDENTITY,
|
||||
'profile_checksum': str(raw_profile.get('checksum') or '') or None,
|
||||
'header_split_evidence': header_split_evidence,
|
||||
'field_evidence_refs': [
|
||||
item.evidence for item in header_fields
|
||||
] + [
|
||||
field.get('evidence_ref')
|
||||
for row in rows
|
||||
for field in row.get('fields') or []
|
||||
if isinstance(field, dict) and field.get('evidence_ref')
|
||||
and str(field.get('field_code') or '') not in {h.field_code for h in header_fields}
|
||||
],
|
||||
})
|
||||
|
||||
return XfaExtractionResult(
|
||||
status='parsed' if not reason_codes else 'needs_review',
|
||||
reason_codes=reason_codes,
|
||||
header_fields=header_fields,
|
||||
rows=rows,
|
||||
packet_checksum=packet_checksum,
|
||||
dataset_structure_fingerprint=dataset_structure_fingerprint,
|
||||
profile_checksum=str(raw_profile.get('checksum') or '') or None,
|
||||
evidence_summary=evidence_summary,
|
||||
)
|
||||
@@ -0,0 +1,191 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_profile_matcher.py
|
||||
|
||||
用途:对冻结 published XFA Profile 做精确结构身份匹配(禁止模糊/OCR/VLM)。
|
||||
依赖:xfa_contract(OrderXfaDatasetProfile / sanitize)、ProfileMatchResult 形状对齐。
|
||||
逻辑:由 order_extraction_workflow XFA 分支调用;仅比较
|
||||
template_packet_checksum + dataset_structure_fingerprint;草稿/retired 不在快照内。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
OrderXfaDatasetProfile,
|
||||
sanitize_xfa_dto,
|
||||
)
|
||||
|
||||
|
||||
class XfaProfileMatchCandidate(BaseModel):
|
||||
"""单个冻结 XFA Profile 的精确身份匹配摘要(无业务值)。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
profile_code: str
|
||||
version: int = Field(ge=1)
|
||||
checksum: str | None = None
|
||||
hard_match: bool = False
|
||||
reason_codes: list[str] = Field(default_factory=list)
|
||||
template_packet_checksum: str | None = None
|
||||
dataset_structure_fingerprint: str | None = None
|
||||
|
||||
|
||||
class XfaProfileMatchResult(BaseModel):
|
||||
"""文档级 XFA Profile 精确匹配结果;仅 unique_match 可启动正式提取。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
status: Literal[
|
||||
'unique_match',
|
||||
'no_match',
|
||||
'ambiguous',
|
||||
'evidence_insufficient',
|
||||
'structure_identity_changed',
|
||||
]
|
||||
profile_code: str | None = None
|
||||
version: int | None = None
|
||||
checksum: str | None = None
|
||||
profile_id: int | None = None
|
||||
template_packet_checksum: str | None = None
|
||||
dataset_structure_fingerprint: str | None = None
|
||||
candidates: list[XfaProfileMatchCandidate] = Field(default_factory=list)
|
||||
reason_codes: list[str] = Field(default_factory=list)
|
||||
|
||||
def model_dump_safe(self) -> dict[str, Any]:
|
||||
"""返回经 sanitize 的可持久化字典。"""
|
||||
return sanitize_xfa_dto(self.model_dump(mode='json'))
|
||||
|
||||
|
||||
def _is_xfa_definition(definition: dict[str, Any] | None) -> bool:
|
||||
"""判断 definition 是否为 xfa_dataset 模式。"""
|
||||
if not isinstance(definition, dict):
|
||||
return False
|
||||
return str(definition.get('template_mode') or '').strip() == 'xfa_dataset'
|
||||
|
||||
|
||||
def match_frozen_xfa_profiles(
|
||||
*,
|
||||
profiles: list[dict[str, Any]],
|
||||
template_packet_checksum: str | None,
|
||||
dataset_structure_fingerprint: str | None,
|
||||
) -> XfaProfileMatchResult:
|
||||
"""
|
||||
对同一文档的冻结 published XFA Profile 做精确结构身份匹配。
|
||||
|
||||
核心逻辑:仅当 template_packet_checksum 与 dataset_structure_fingerprint
|
||||
同时相等时计为 hard_match;0 命中 → no_match,1 → unique_match,≥2 → ambiguous。
|
||||
禁止模糊相似度、客户 ID 单独命中或字段名猜测。
|
||||
|
||||
Args:
|
||||
profiles: Run 冻结的 order_document_profiles(应已排除 draft/retired)。
|
||||
template_packet_checksum: 当前文档 live template packet checksum。
|
||||
dataset_structure_fingerprint: 当前文档 live dataset 结构指纹。
|
||||
|
||||
Returns:
|
||||
XfaProfileMatchResult:含候选摘要与稳定 reason_codes。
|
||||
"""
|
||||
live_template = str(template_packet_checksum or '').strip() or None
|
||||
live_fingerprint = str(dataset_structure_fingerprint or '').strip() or None
|
||||
if not live_template or not live_fingerprint:
|
||||
return XfaProfileMatchResult(
|
||||
status='evidence_insufficient',
|
||||
reason_codes=['xfa_structure_identity_changed'],
|
||||
template_packet_checksum=live_template,
|
||||
dataset_structure_fingerprint=live_fingerprint,
|
||||
)
|
||||
|
||||
candidates: list[XfaProfileMatchCandidate] = []
|
||||
hard_matches: list[tuple[dict[str, Any], XfaProfileMatchCandidate]] = []
|
||||
|
||||
for raw in profiles:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
definition = raw.get('definition') if isinstance(raw.get('definition'), dict) else {}
|
||||
if not _is_xfa_definition(definition):
|
||||
continue
|
||||
# 防御:即使快照误含非 published,也不参与新 Run 匹配。
|
||||
status = str(raw.get('status') or 'published').strip()
|
||||
if status in {'draft', 'retired'}:
|
||||
continue
|
||||
reason_codes: list[str] = []
|
||||
try:
|
||||
profile = OrderXfaDatasetProfile.model_validate(definition)
|
||||
except (TypeError, ValueError):
|
||||
reason_codes.append('xfa_definition_invalid')
|
||||
candidates.append(XfaProfileMatchCandidate(
|
||||
profile_code=str(raw.get('profile_code') or ''),
|
||||
version=max(int(raw.get('version') or 1), 1),
|
||||
checksum=str(raw.get('checksum') or '') or None,
|
||||
hard_match=False,
|
||||
reason_codes=reason_codes,
|
||||
))
|
||||
continue
|
||||
|
||||
source = profile.source_contract
|
||||
profile_template = str(source.template_packet_checksum or '').strip()
|
||||
profile_fingerprint = str(source.dataset_structure_fingerprint or '').strip()
|
||||
hard = (
|
||||
bool(profile_template)
|
||||
and bool(profile_fingerprint)
|
||||
and profile_template == live_template
|
||||
and profile_fingerprint == live_fingerprint
|
||||
and bool(str(raw.get('checksum') or '').strip())
|
||||
)
|
||||
if not hard:
|
||||
if profile_template != live_template or profile_fingerprint != live_fingerprint:
|
||||
reason_codes.append('xfa_structure_identity_changed')
|
||||
else:
|
||||
reason_codes.append('xfa_profile_not_matched')
|
||||
candidate = XfaProfileMatchCandidate(
|
||||
profile_code=str(raw.get('profile_code') or ''),
|
||||
version=max(int(raw.get('version') or 1), 1),
|
||||
checksum=str(raw.get('checksum') or '') or None,
|
||||
hard_match=hard,
|
||||
reason_codes=reason_codes,
|
||||
template_packet_checksum=profile_template or None,
|
||||
dataset_structure_fingerprint=profile_fingerprint or None,
|
||||
)
|
||||
candidates.append(candidate)
|
||||
if hard:
|
||||
hard_matches.append((raw, candidate))
|
||||
|
||||
if not candidates:
|
||||
return XfaProfileMatchResult(
|
||||
status='no_match',
|
||||
reason_codes=['xfa_profile_not_matched'],
|
||||
template_packet_checksum=live_template,
|
||||
dataset_structure_fingerprint=live_fingerprint,
|
||||
candidates=candidates,
|
||||
)
|
||||
if len(hard_matches) == 0:
|
||||
return XfaProfileMatchResult(
|
||||
status='no_match',
|
||||
reason_codes=['xfa_profile_not_matched'],
|
||||
template_packet_checksum=live_template,
|
||||
dataset_structure_fingerprint=live_fingerprint,
|
||||
candidates=candidates,
|
||||
)
|
||||
if len(hard_matches) > 1:
|
||||
return XfaProfileMatchResult(
|
||||
status='ambiguous',
|
||||
reason_codes=['xfa_profile_ambiguous'],
|
||||
template_packet_checksum=live_template,
|
||||
dataset_structure_fingerprint=live_fingerprint,
|
||||
candidates=candidates,
|
||||
)
|
||||
|
||||
raw, winner = hard_matches[0]
|
||||
return XfaProfileMatchResult(
|
||||
status='unique_match',
|
||||
profile_code=winner.profile_code,
|
||||
version=winner.version,
|
||||
checksum=winner.checksum,
|
||||
profile_id=int(raw.get('profile_id') or raw.get('id') or 0) or None,
|
||||
template_packet_checksum=live_template,
|
||||
dataset_structure_fingerprint=live_fingerprint,
|
||||
candidates=candidates,
|
||||
reason_codes=[],
|
||||
)
|
||||
@@ -0,0 +1,147 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_signature.py
|
||||
|
||||
用途:计算 XFA template packet checksum、datasets 结构指纹与治理用 structure signature。
|
||||
依赖:xfa_contract、xfa_dataset.XfaDatasetNode、标准库 hashlib/json。
|
||||
逻辑:由 xfa_analysis / 验证服务调用;指纹忽略业务值与行数;structure signature
|
||||
冻结 analysis 与 packet 身份供发布门禁引用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_STRUCTURE_SIGNATURE_ID,
|
||||
XfaStructureNodeSpec,
|
||||
compute_dataset_structure_fingerprint,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import XfaDatasetNode
|
||||
from app.services.shipping_notice.document_layout.xfa_packets import compute_packet_checksum
|
||||
|
||||
|
||||
def compute_template_packet_checksum(template_bytes: bytes | None) -> str | None:
|
||||
"""
|
||||
计算 template packet 的稳定 checksum。
|
||||
|
||||
Args:
|
||||
template_bytes: template packet 原始字节;缺失时返回 None。
|
||||
|
||||
Returns:
|
||||
`sha256:<hex>` 或 None。
|
||||
"""
|
||||
if not template_bytes:
|
||||
return None
|
||||
return compute_packet_checksum(template_bytes)
|
||||
|
||||
|
||||
def dataset_nodes_to_structure_specs(nodes: list[XfaDatasetNode]) -> list[XfaStructureNodeSpec]:
|
||||
"""
|
||||
将受控路径树转换为结构指纹输入节点。
|
||||
|
||||
核心逻辑:只保留 local_name/namespace/depth/cardinality/children;不包含样本值与行计数。
|
||||
|
||||
Args:
|
||||
nodes: datasets 路径树根列表。
|
||||
|
||||
Returns:
|
||||
XfaStructureNodeSpec 列表。
|
||||
"""
|
||||
|
||||
def _convert(node: XfaDatasetNode) -> XfaStructureNodeSpec:
|
||||
return XfaStructureNodeSpec(
|
||||
local_name=node.local_name,
|
||||
namespace_uri=node.namespace_uri,
|
||||
depth=node.depth,
|
||||
cardinality=node.cardinality,
|
||||
children=[_convert(child) for child in node.children],
|
||||
)
|
||||
|
||||
return [_convert(item) for item in nodes]
|
||||
|
||||
|
||||
def compute_dataset_structure_fingerprint_from_nodes(nodes: list[XfaDatasetNode]) -> str:
|
||||
"""
|
||||
基于路径树计算 dataset 结构指纹。
|
||||
|
||||
Args:
|
||||
nodes: datasets 路径树根列表。
|
||||
|
||||
Returns:
|
||||
`sha256:<hex>` 结构指纹。
|
||||
"""
|
||||
specs = dataset_nodes_to_structure_specs(nodes)
|
||||
return compute_dataset_structure_fingerprint(specs)
|
||||
|
||||
|
||||
def build_signature_summary(
|
||||
*,
|
||||
template_bytes: bytes | None,
|
||||
dataset_nodes: list[XfaDatasetNode],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
汇总 template checksum 与 datasets 结构指纹。
|
||||
|
||||
Args:
|
||||
template_bytes: template packet 字节。
|
||||
dataset_nodes: 已解析 datasets 路径树。
|
||||
|
||||
Returns:
|
||||
含 template_packet_checksum 与 dataset_structure_fingerprint 的字典。
|
||||
"""
|
||||
return {
|
||||
'template_packet_checksum': compute_template_packet_checksum(template_bytes),
|
||||
'dataset_structure_fingerprint': compute_dataset_structure_fingerprint_from_nodes(dataset_nodes),
|
||||
}
|
||||
|
||||
|
||||
def build_xfa_structure_signature(
|
||||
*,
|
||||
template_packet_checksum: str | None,
|
||||
dataset_structure_fingerprint: str | None,
|
||||
datasets_packet_checksum: str | None,
|
||||
definition_checksum: str,
|
||||
analysis_ids: list[int],
|
||||
parser_identity: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
生成 XFA 结构签名快照(替代 coordinate layout_signature)。
|
||||
|
||||
核心逻辑:对 analysis/packet/structure/definition/parser 身份做稳定哈希;
|
||||
不含订单值、文件名或明细行数。
|
||||
|
||||
Args:
|
||||
template_packet_checksum: template packet 身份。
|
||||
dataset_structure_fingerprint: datasets 结构指纹。
|
||||
datasets_packet_checksum: datasets packet 内容 checksum(可与 template 不同)。
|
||||
definition_checksum: 当前草稿 definition checksum。
|
||||
analysis_ids: 冻结的结构分析记录 ID 列表。
|
||||
parser_identity: 解析器身份常量。
|
||||
|
||||
Returns:
|
||||
含 signature_version / signature_checksum / evidence 的安全快照。
|
||||
"""
|
||||
payload = {
|
||||
'signature_version': XFA_STRUCTURE_SIGNATURE_ID,
|
||||
'template_packet_checksum': str(template_packet_checksum or ''),
|
||||
'dataset_structure_fingerprint': str(dataset_structure_fingerprint or ''),
|
||||
'datasets_packet_checksum': str(datasets_packet_checksum or ''),
|
||||
'definition_checksum': str(definition_checksum or ''),
|
||||
'analysis_ids': sorted(int(item) for item in analysis_ids),
|
||||
'parser_identity': str(parser_identity or ''),
|
||||
}
|
||||
encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
checksum = hashlib.sha256(encoded).hexdigest()
|
||||
return {
|
||||
'signature_version': XFA_STRUCTURE_SIGNATURE_ID,
|
||||
'signature_checksum': checksum,
|
||||
'signature': payload,
|
||||
'evidence_quality': {
|
||||
'source_sample_count': len(analysis_ids),
|
||||
'analysis_count': len(analysis_ids),
|
||||
'has_template_checksum': bool(template_packet_checksum),
|
||||
'has_structure_fingerprint': bool(dataset_structure_fingerprint),
|
||||
},
|
||||
}
|
||||
Loaded 100 of 571 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user