feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置 新增收料报表管理的前端页面、路由和侧边栏入口 新增后端收料报表配置接口、数据库模型和RPA脚本 优化发货通知流程的重试策略,将shipping相关job默认不自动重试 移除废弃的库存源确认相关逻辑,更新流程门禁规则 重构订单模板的值适配器模块,新增坐标OCR值适配器 清理前端shipping菜单和action的废弃选项 更新相关文档和测试用例,调整.gitignore忽略规则
This commit is contained in:
1 parent
260465b72d
commit
1b6483a4ea
466 files changed
+32115
-33796
No files matched your search
@@ -165,6 +165,22 @@ def update_shipping_inventory_source(source_id: int):
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/receipt-report-config', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_receipt_report_config(source_id: int):
|
||||
"""读取站点独立收料报表配置;库存配置和收料配置永不混写。"""
|
||||
return _ok(shipping_inventory_service.get_receipt_report_config(source_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/receipt-report-config', methods=['PUT'])
|
||||
@require_admin
|
||||
def save_shipping_receipt_report_config(source_id: int):
|
||||
"""保存独立收料报表配置,并由服务记录可追溯的前后快照审计。"""
|
||||
return _ok(shipping_inventory_service.save_receipt_report_config(
|
||||
source_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/bind-parsing-profile', methods=['POST'])
|
||||
@require_admin
|
||||
def bind_shipping_inventory_source_parsing_profile(source_id: int):
|
||||
|
||||
@@ -3,10 +3,10 @@ backend/app/api/admin/shipping_order_document_profiles.py
|
||||
|
||||
用途:提供订单文档模板 Profile 的管理员版本治理 API。
|
||||
依赖:admin blueprint、require_admin、order_document_profile_service、
|
||||
order_document_profile_preview_service、order_document_profile_xfa_preview_service、
|
||||
order_document_profile_xfa_automark_service、order_document_profile_visual_binding_service、
|
||||
order_document_profile_preview_service、
|
||||
order_document_profile_pdf_automark_service、
|
||||
order_profile_unified_migration。
|
||||
逻辑:路由只转换请求和操作者;版本、Schema、字段、XFA 合成预览、OCR 自动标记、
|
||||
逻辑:路由只转换请求和操作者;版本、Schema、字段、原生 PDF 预览、统一自动标记、
|
||||
统一迁移与发布门禁由服务层执行。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -25,8 +25,6 @@ from app.services.shipping_notice import order_document_profile_diff as diff_ser
|
||||
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_preview_service as preview_service
|
||||
from app.services.shipping_notice import order_document_profile_xfa_preview_service as xfa_preview_service
|
||||
from app.services.shipping_notice import order_document_profile_xfa_automark_service as xfa_automark_service
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as pdf_automark_service
|
||||
from app.services.shipping_notice import order_document_profile_revision_service as revision_service
|
||||
from app.services.shipping_notice import order_document_profile_suggestion_service as suggestion_service
|
||||
@@ -35,8 +33,8 @@ from app.services.shipping_notice import order_document_profile_usage_service as
|
||||
from app.services.shipping_notice import order_document_profile_validation_service as validation_service
|
||||
from app.services.shipping_notice import order_document_profile_publish_check_service as publish_check_service
|
||||
from app.services.shipping_notice import order_document_profile_version_service as version_service
|
||||
from app.services.shipping_notice import order_document_profile_visual_binding_service as visual_binding_service
|
||||
from app.services.shipping_notice import order_profile_unified_migration as unified_migration
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_runtime_value_adapter
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
@@ -57,6 +55,15 @@ def _private_ok(data, *, status: int = 200):
|
||||
return response, response_status
|
||||
|
||||
|
||||
def _sample_mapping_adapter(document_id: int):
|
||||
"""从共同视觉 Layout 解析当前样本的末端值源 adapter。"""
|
||||
document = service._require_sample_document(document_id)
|
||||
return get_runtime_value_adapter(
|
||||
layout=service._document_layout(document),
|
||||
selected_profile=None,
|
||||
)
|
||||
|
||||
|
||||
def _query_int(name: str, default: int, *, minimum: int | None = None, maximum: int | None = None) -> int:
|
||||
"""读取可选整数查询参数,并做受控范围校验。"""
|
||||
raw = request.args.get(name)
|
||||
@@ -244,9 +251,20 @@ def update_order_document_profile(profile_id: int):
|
||||
if profile_row is not None and isinstance(profile_row.definition_json, dict)
|
||||
else {}
|
||||
)
|
||||
# [STEP] 变更 split_rules 强制校验 xfa_split_rule_edit(注释与实现一致)。
|
||||
if service.split_rules_definition_changed(previous_def, incoming_def if isinstance(incoming_def, dict) else {}):
|
||||
_require_xfa_split_edit_permission()
|
||||
# [STEP] 末端映射规则变化由当前样本 adapter 判定,Route 不识别文件格式。
|
||||
previous_adapter = get_runtime_value_adapter(
|
||||
layout=None,
|
||||
selected_profile={'definition': previous_def} if previous_def else None,
|
||||
)
|
||||
incoming_adapter = get_runtime_value_adapter(
|
||||
layout=None,
|
||||
selected_profile={'definition': incoming_def} if incoming_def else None,
|
||||
)
|
||||
if (
|
||||
previous_adapter.mapping_rules_changed(previous_def, incoming_def if isinstance(incoming_def, dict) else {})
|
||||
or incoming_adapter.mapping_rules_changed(previous_def, incoming_def if isinstance(incoming_def, dict) else {})
|
||||
):
|
||||
_require_value_mapping_edit_permission()
|
||||
return _ok(service.save_draft(
|
||||
data, actor_id=_actor_id(), profile_id=profile_id, **_write_context(data), enforce_lease=True,
|
||||
))
|
||||
@@ -428,8 +446,10 @@ def confirm_order_document_profile_publish_check(profile_id: int, report_no: str
|
||||
|
||||
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':
|
||||
value_adapter = service._publish_value_adapter(
|
||||
service._profile_template_mode(entity) if entity is not None else 'coordinate',
|
||||
)
|
||||
if value_adapter.requires_split_rule_publish_permission:
|
||||
user = getattr(g, 'current_user', None)
|
||||
if not bool(user and user.has_feature_permission('shipping_notice.xfa_split_rule_publish')):
|
||||
raise ForbiddenError(
|
||||
@@ -534,31 +554,6 @@ def get_order_document_profile_preview_page(profile_id: int, page_no: int):
|
||||
return response
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/xfa-pdf-preview', methods=['POST'])
|
||||
@require_admin
|
||||
def authorize_order_document_profile_xfa_pdf_preview(profile_id: int):
|
||||
"""兼容旧 XFA 路由:签发统一编辑画布的单用途原 PDF 令牌。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _private_ok(service.authorize_pdf_preview(
|
||||
profile_id, document_id=data.get('document_id'), actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/xfa-pdf-preview', methods=['GET'])
|
||||
@require_admin
|
||||
def get_order_document_profile_xfa_pdf_preview(profile_id: int):
|
||||
"""兼容旧 XFA 路由:消费短时令牌返回原 PDF,仅供 PDF.js 内存渲染。"""
|
||||
pdf = service.read_pdf_preview(
|
||||
token=str(request.args.get('preview_token') or ''), actor_id=_actor_id(),
|
||||
)
|
||||
response = send_file(io.BytesIO(pdf), mimetype='application/pdf', as_attachment=False, max_age=0)
|
||||
response.headers['Cache-Control'] = 'private, no-store, max-age=0'
|
||||
response.headers['Pragma'] = 'no-cache'
|
||||
response.headers['X-Content-Type-Options'] = 'nosniff'
|
||||
response.headers['Content-Disposition'] = 'inline'
|
||||
return response
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/pdf-preview', methods=['POST'])
|
||||
@require_admin
|
||||
def authorize_order_document_profile_pdf_preview(profile_id: int):
|
||||
@@ -694,16 +689,17 @@ 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/profile-identity-signature', methods=['POST'])
|
||||
@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):
|
||||
def run_order_document_profile_identity_signature(profile_id: int):
|
||||
"""
|
||||
生成当前草稿的版面签名 ValidationRun,并更新 Profile 轻量签名引用。
|
||||
生成当前草稿的统一身份签名 ValidationRun,并更新 Profile 轻量签名引用。
|
||||
|
||||
前端不得提交 Matcher 分数或签名正文;服务端仅消费租约与 operation_id。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(validation_service.run_layout_signature(
|
||||
return _ok(validation_service.run_profile_identity_signature(
|
||||
profile_id, data=data, actor_id=_actor_id(), **_write_context(data),
|
||||
), status=201)
|
||||
|
||||
@@ -810,31 +806,35 @@ def approve_order_document_profile_test_suite(suite_id: int):
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/xfa/field-tree',
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/value-adapter/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()))
|
||||
def get_order_document_profile_sample_value_field_tree(document_id: int):
|
||||
"""返回当前值源字段树安全投影;不含原始正文。"""
|
||||
return _private_ok(_sample_mapping_adapter(document_id).mapping_field_tree(
|
||||
document_id=document_id, actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/xfa/collections',
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/value-adapter/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()))
|
||||
def get_order_document_profile_sample_value_collections(document_id: int):
|
||||
"""返回当前值源的重复集合候选摘要。"""
|
||||
return _private_ok(_sample_mapping_adapter(document_id).mapping_collections(
|
||||
document_id=document_id, actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/xfa/value-preview',
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/value-adapter/value-preview',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def preview_order_document_profile_sample_xfa_value(document_id: int):
|
||||
def preview_order_document_profile_sample_value(document_id: int):
|
||||
"""
|
||||
按 path_id 返回样本值投影。
|
||||
|
||||
@@ -845,8 +845,8 @@ def preview_order_document_profile_sample_xfa_value(document_id: int):
|
||||
reveal = bool(data.get('reveal'))
|
||||
if reveal:
|
||||
_require_audit_sensitive_read_permission()
|
||||
return _private_ok(service.preview_xfa_sample_value(
|
||||
document_id,
|
||||
return _private_ok(_sample_mapping_adapter(document_id).mapping_value_preview(
|
||||
document_id=document_id,
|
||||
path_id=str(data.get('path_id') or ''),
|
||||
actor_id=_actor_id(),
|
||||
include_full_value=reveal,
|
||||
@@ -854,82 +854,26 @@ def preview_order_document_profile_sample_xfa_value(document_id: int):
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/xfa/preview',
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/value-adapter/split-rules/preview',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def request_order_document_profile_sample_xfa_synthetic_preview(document_id: int):
|
||||
"""
|
||||
生成或复用绑定冻结 Analysis 的 XFA 合成预览,返回身份与页元数据(不含大图)。
|
||||
|
||||
核心逻辑:委托 xfa_preview_service;可选 body.force=true 强制重生成。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _private_ok(xfa_preview_service.request_xfa_synthetic_preview(
|
||||
document_id,
|
||||
actor_id=_actor_id(),
|
||||
force=bool(data.get('force')),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/xfa/preview/pages',
|
||||
methods=['GET'],
|
||||
)
|
||||
@require_admin
|
||||
def list_order_document_profile_sample_xfa_synthetic_preview_pages(document_id: int):
|
||||
"""列出冻结 Analysis 绑定的最新 ready 合成预览页并签发短时 token。"""
|
||||
return _private_ok(xfa_preview_service.list_xfa_synthetic_preview_pages(
|
||||
document_id,
|
||||
actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/xfa/preview/pages/<int:page_no>',
|
||||
methods=['GET'],
|
||||
)
|
||||
@require_admin
|
||||
def get_order_document_profile_sample_xfa_synthetic_preview_page(document_id: int, page_no: int):
|
||||
"""
|
||||
消费一次性授权并返回合成预览单页 PNG。
|
||||
|
||||
核心逻辑:与既有 preview-pages 一致——query preview_token、private no-store。
|
||||
"""
|
||||
image = xfa_preview_service.render_xfa_synthetic_preview_page(
|
||||
document_id,
|
||||
page_no=page_no,
|
||||
token=str(request.args.get('preview_token') or ''),
|
||||
actor_id=_actor_id(),
|
||||
)
|
||||
response = send_file(io.BytesIO(image), mimetype='image/png', as_attachment=False, max_age=0)
|
||||
response.headers['Cache-Control'] = 'private, no-store, max-age=0'
|
||||
response.headers['Pragma'] = 'no-cache'
|
||||
response.headers['X-Content-Type-Options'] = 'nosniff'
|
||||
return response
|
||||
|
||||
|
||||
@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):
|
||||
def preview_order_document_profile_sample_value_split_rules(document_id: int):
|
||||
"""
|
||||
预览拆分规则执行结果并签发确认令牌。
|
||||
|
||||
核心逻辑:须 xfa_split_rule_preview;完整 mapped/raw 值另需 audit_sensitive_read,
|
||||
且完整值路径强制写访问审计。
|
||||
"""
|
||||
_require_xfa_split_preview_permission()
|
||||
_require_value_mapping_preview_permission()
|
||||
data = request.get_json(silent=True) or {}
|
||||
rule_set = data.get('rule_set') if isinstance(data.get('rule_set'), dict) else {}
|
||||
profile_id = data.get('profile_id')
|
||||
reveal = bool(data.get('reveal'))
|
||||
if reveal:
|
||||
_require_audit_sensitive_read_permission()
|
||||
return _private_ok(service.preview_xfa_split_rules(
|
||||
document_id,
|
||||
return _private_ok(_sample_mapping_adapter(document_id).mapping_split_preview(
|
||||
document_id=document_id,
|
||||
path_id=str(data.get('path_id') or ''),
|
||||
rule_set=rule_set,
|
||||
actor_id=_actor_id(),
|
||||
@@ -940,46 +884,46 @@ def preview_order_document_profile_sample_xfa_split_rules(document_id: int):
|
||||
|
||||
|
||||
def _require_audit_sensitive_read_permission() -> None:
|
||||
"""完整 XFA 样本/拆分值读取需 shipping_notice.audit_sensitive_read。"""
|
||||
"""完整值源样本/拆分值读取需 shipping_notice.audit_sensitive_read。"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
if not bool(user and user.has_feature_permission('shipping_notice.audit_sensitive_read')):
|
||||
raise ForbiddenError(
|
||||
'XFA sensitive value read permission is required',
|
||||
'Sensitive value read permission is required',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_VALUE_FORBIDDEN',
|
||||
details={'permission': 'shipping_notice.audit_sensitive_read'},
|
||||
)
|
||||
|
||||
|
||||
def _require_xfa_split_preview_permission() -> None:
|
||||
"""拆分规则预览/建议需 xfa_split_rule_preview 权限(admin 默认具备)。"""
|
||||
def _require_value_mapping_preview_permission() -> None:
|
||||
"""值源映射预览/建议需既有拆分预览权限(admin 默认具备)。"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
if not bool(user and user.has_feature_permission('shipping_notice.xfa_split_rule_preview')):
|
||||
raise ForbiddenError(
|
||||
'XFA split rule preview permission is required',
|
||||
'Value mapping preview permission is required',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_VALUE_FORBIDDEN',
|
||||
details={'permission': 'shipping_notice.xfa_split_rule_preview'},
|
||||
)
|
||||
|
||||
|
||||
def _require_xfa_split_edit_permission() -> None:
|
||||
"""变更拆分规则需 shipping_notice.xfa_split_rule_edit。"""
|
||||
def _require_value_mapping_edit_permission() -> None:
|
||||
"""变更末端映射拆分规则需既有编辑权限。"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
if not bool(user and user.has_feature_permission('shipping_notice.xfa_split_rule_edit')):
|
||||
raise ForbiddenError(
|
||||
'XFA split rule edit permission is required',
|
||||
'Value mapping edit permission is required',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_EDIT_FORBIDDEN',
|
||||
details={'permission': 'shipping_notice.xfa_split_rule_edit'},
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/split-rules/suggest',
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/value-adapter/split-rules/suggest',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def suggest_order_document_profile_xfa_split_rules(profile_id: int):
|
||||
def suggest_order_document_profile_value_split_rules(profile_id: int):
|
||||
"""生成 MATNR 类拆分规则建议;不写 Draft、不 commit。"""
|
||||
_require_xfa_split_preview_permission()
|
||||
_require_value_mapping_preview_permission()
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _private_ok(suggestion_service.suggest_xfa_split_rules(
|
||||
profile_id,
|
||||
@@ -991,34 +935,11 @@ def suggest_order_document_profile_xfa_split_rules(profile_id: int):
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/unified-mapping/suggest',
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/value-adapter/split-rules/validate',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def suggest_order_document_profile_xfa_unified_mapping(profile_id: int):
|
||||
"""统一返回视觉 + 拆分规则建议;不写 Draft、不 commit。"""
|
||||
_require_xfa_split_preview_permission()
|
||||
data = request.get_json(silent=True) or {}
|
||||
bbox = data.get('normalized_bbox') if isinstance(data.get('normalized_bbox'), dict) else {}
|
||||
return _private_ok(suggestion_service.suggest_xfa_unified_mapping(
|
||||
profile_id,
|
||||
document_id=data.get('document_id'),
|
||||
page_no=data.get('page_no', 1),
|
||||
normalized_bbox=bbox,
|
||||
path_id=str(data.get('path_id') or '').strip() or None,
|
||||
actor_id=_actor_id(),
|
||||
include_visual=bool(data.get('include_visual', True)),
|
||||
include_split=bool(data.get('include_split', True)),
|
||||
write_audit=False,
|
||||
))
|
||||
|
||||
|
||||
@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):
|
||||
def validate_order_document_profile_value_split_rules(profile_id: int):
|
||||
"""校验 Profile 拆分规则契约与 Schema 映射;不持久化。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
split_rules = data.get('split_rules')
|
||||
@@ -1027,78 +948,16 @@ def validate_order_document_profile_xfa_split_rules(profile_id: int):
|
||||
'split_rules must be a list',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
return _private_ok(service.validate_xfa_split_rules(
|
||||
profile_id,
|
||||
profile = service._profile(profile_id)
|
||||
return _private_ok(get_runtime_value_adapter(
|
||||
layout=None, selected_profile={'definition': profile.definition_json},
|
||||
).mapping_split_validation(
|
||||
profile_id=profile_id,
|
||||
split_rules=split_rules,
|
||||
actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/visual-bindings/suggest',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def suggest_order_document_profile_xfa_visual_bindings(profile_id: int):
|
||||
"""为页面区域生成 XFA 视觉绑定候选;歧义不自动确认。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
bbox = data.get('normalized_bbox') if isinstance(data.get('normalized_bbox'), dict) else {}
|
||||
return _private_ok(visual_binding_service.suggest_xfa_visual_bindings(
|
||||
profile_id,
|
||||
document_id=data.get('document_id'),
|
||||
page_no=data.get('page_no', 1),
|
||||
normalized_bbox=bbox,
|
||||
actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/visual-bindings/<string:binding_id>/confirm',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def confirm_order_document_profile_xfa_visual_binding(profile_id: int, binding_id: str):
|
||||
"""管理员确认视觉绑定;须携带合成预览 checksum / render_mode;写 before/after 审计。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
ctx = _write_context(data)
|
||||
visual = data.get('visual_binding') if isinstance(data.get('visual_binding'), dict) else {}
|
||||
return _private_ok(visual_binding_service.confirm_xfa_visual_binding(
|
||||
profile_id,
|
||||
binding_id,
|
||||
visual_binding=visual,
|
||||
path_id=str(data.get('path_id') or '').strip() or None,
|
||||
actor_id=_actor_id(),
|
||||
browser_session_id=ctx.get('browser_session_id'),
|
||||
lease_token=ctx.get('lease_token'),
|
||||
operation_id=ctx.get('operation_id'),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
preview_render_checksum=str(data.get('preview_render_checksum') or '').strip() or None,
|
||||
render_mode=str(data.get('render_mode') or '').strip() or None,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/visual-bindings/<string:binding_id>/reject',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def reject_order_document_profile_xfa_visual_binding(profile_id: int, binding_id: str):
|
||||
"""管理员驳回视觉绑定建议;写 before/after 审计。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
ctx = _write_context(data)
|
||||
return _private_ok(visual_binding_service.reject_xfa_visual_binding(
|
||||
profile_id,
|
||||
binding_id,
|
||||
reason_code=str(data.get('reason_code') or '').strip() or None,
|
||||
actor_id=_actor_id(),
|
||||
browser_session_id=ctx.get('browser_session_id'),
|
||||
lease_token=ctx.get('lease_token'),
|
||||
operation_id=ctx.get('operation_id'),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/pdf-automark',
|
||||
methods=['POST'],
|
||||
@@ -1131,97 +990,6 @@ def get_order_document_profile_pdf_automark_job(profile_id: int, job_id: int):
|
||||
return _private_ok(pdf_automark_service.get_pdf_automark_job(job_id, profile_id=profile_id))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/automark',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def enqueue_order_document_profile_xfa_ocr_automark(profile_id: int):
|
||||
"""
|
||||
入队 XFA OCR 自动标记异步 Job。
|
||||
|
||||
核心逻辑:body.document_id 必填;可选 force 强制重生成合成预览后入队。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
document_id = data.get('document_id')
|
||||
if document_id in (None, ''):
|
||||
raise ValidationError(
|
||||
'document_id is required',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
page_nos = data.get('page_nos') if isinstance(data.get('page_nos'), list) else None
|
||||
return _private_ok(xfa_automark_service.enqueue_xfa_ocr_automark(
|
||||
profile_id,
|
||||
document_id=int(document_id),
|
||||
actor_id=_actor_id(),
|
||||
force=bool(data.get('force')),
|
||||
page_nos=[int(item) for item in (page_nos or [])],
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/automark/jobs/<int:job_id>',
|
||||
methods=['GET'],
|
||||
)
|
||||
@require_admin
|
||||
def get_order_document_profile_xfa_ocr_automark_job(profile_id: int, job_id: int):
|
||||
"""轮询 OCR 自动标记 Job 状态与建议列表。"""
|
||||
return _private_ok(xfa_automark_service.get_xfa_ocr_automark_job(
|
||||
job_id,
|
||||
profile_id=profile_id,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/automark/suggestions/<string:suggestion_id>/accept',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def accept_order_document_profile_xfa_automark_suggestion(profile_id: int, suggestion_id: str):
|
||||
"""
|
||||
接受 OCR 自动标记建议。
|
||||
|
||||
核心逻辑:high→confirmed(须 checksum);medium/low→suggested;mismatch 阻断。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
ctx = _write_context(data)
|
||||
job_id = data.get('job_id')
|
||||
return _private_ok(xfa_automark_service.accept_xfa_automark_suggestion(
|
||||
profile_id,
|
||||
suggestion_id,
|
||||
actor_id=_actor_id(),
|
||||
browser_session_id=ctx.get('browser_session_id'),
|
||||
lease_token=ctx.get('lease_token'),
|
||||
operation_id=ctx.get('operation_id'),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
job_id=int(job_id) if job_id not in (None, '') else None,
|
||||
preview_render_checksum=str(data.get('preview_render_checksum') or '').strip() or None,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/automark/suggestions/<string:suggestion_id>/reject',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def reject_order_document_profile_xfa_automark_suggestion(profile_id: int, suggestion_id: str):
|
||||
"""驳回 OCR 自动标记建议并减少 unresolved mismatch 计数。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
ctx = _write_context(data)
|
||||
job_id = data.get('job_id')
|
||||
return _private_ok(xfa_automark_service.reject_xfa_automark_suggestion(
|
||||
profile_id,
|
||||
suggestion_id,
|
||||
actor_id=_actor_id(),
|
||||
browser_session_id=ctx.get('browser_session_id'),
|
||||
lease_token=ctx.get('lease_token'),
|
||||
operation_id=ctx.get('operation_id'),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
reason_code=str(data.get('reason_code') or '').strip() or None,
|
||||
job_id=int(job_id) if job_id not in (None, '') else None,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/unified-migration/dry-run',
|
||||
methods=['POST'],
|
||||
|
||||
@@ -24,6 +24,11 @@ from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
should_defer_schedule_run_finalization,
|
||||
)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
apply_deferred_receipt_schedule_run_state,
|
||||
recover_stale_receipt_rpa_schedule_runs,
|
||||
should_defer_receipt_schedule_run,
|
||||
)
|
||||
|
||||
internal_jobs_bp = Blueprint('internal_jobs', __name__)
|
||||
|
||||
@@ -134,6 +139,7 @@ def run_internal_job(name: str):
|
||||
|
||||
task, run = _resolve_schedule_task_and_run(key, data)
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
recover_stale_receipt_rpa_schedule_runs(task)
|
||||
try:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job(
|
||||
key, task, run, data,
|
||||
@@ -183,6 +189,19 @@ def run_internal_job(name: str):
|
||||
'awaiting_rpa_callback': True,
|
||||
})
|
||||
|
||||
if should_defer_receipt_schedule_run(task, step_logs):
|
||||
apply_deferred_receipt_schedule_run_state(
|
||||
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
|
||||
)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total_count, 'success_count': success_count,
|
||||
'failed_count': failed_count, 'skipped_count': skipped_count,
|
||||
},
|
||||
'details': details, 'errors': errors, 'step_logs': step_logs,
|
||||
'awaiting_receipt_rpa_callback': True,
|
||||
})
|
||||
|
||||
_finalize_run(
|
||||
run,
|
||||
total_count=total_count,
|
||||
|
||||
@@ -9,6 +9,7 @@ from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
import uuid
|
||||
|
||||
from flask import jsonify, request, send_file
|
||||
|
||||
@@ -17,10 +18,13 @@ from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ConflictError, NotFoundError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.query_service import get_run, list_runs, serialize_run
|
||||
from app.services.schedule.queue_service import enqueue_manual_schedule_run
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||
@@ -117,3 +121,130 @@ def get_schedule_run_inventory_raw_zip(run_id: int):
|
||||
download_name=file_name,
|
||||
mimetype='application/zip',
|
||||
)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/receipt-report-files/<int:file_id>/resend', methods=['POST'])
|
||||
@require_admin
|
||||
def resend_receipt_report_file(file_id: int):
|
||||
"""管理员重发已归档的收料文件;禁止借重发重新触发 RPA 导出。"""
|
||||
report_file = db.session.get(ShippingReceiptReportFile, file_id)
|
||||
if report_file is None or report_file.archive_deleted_at is not None:
|
||||
raise NotFoundError('Receipt report file not found')
|
||||
user = get_current_user()
|
||||
outcome = deliver_receipt_file(report_file.id, force=True)
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_report_notification_resent', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='admin', actor_id=getattr(user, 'id', None),
|
||||
owner_user_id=getattr(user, 'id', None), unit_id=report_file.unit_run_id, result='success',
|
||||
after={'status': 'resent', 'owner_user_id': getattr(user, 'id', None)},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
metadata={'success_count': int(outcome.get('success_count', 0)), 'failed_count': int(outcome.get('failed_count', 0))},
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'success': True, 'data': outcome})
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/receipt-rpa-units', methods=['GET'])
|
||||
@require_admin
|
||||
def list_receipt_rpa_units():
|
||||
"""管理员查看收料单元运行事实,供失败单元填写原因后人工重试。"""
|
||||
status = str(request.args.get('status') or '').strip().lower()
|
||||
if status and status not in {'queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled'}:
|
||||
from app.core.errors import ValidationError
|
||||
raise ValidationError('status is invalid')
|
||||
try:
|
||||
limit = max(1, min(int(request.args.get('limit') or 100), 200))
|
||||
except (TypeError, ValueError):
|
||||
from app.core.errors import ValidationError
|
||||
raise ValidationError('limit is invalid')
|
||||
query = ShippingReceiptRpaUnitRun.query.order_by(
|
||||
ShippingReceiptRpaUnitRun.created_at.desc(), ShippingReceiptRpaUnitRun.id.desc(),
|
||||
)
|
||||
if status:
|
||||
query = query.filter(ShippingReceiptRpaUnitRun.status == status)
|
||||
units = query.limit(limit).all()
|
||||
user = get_current_user()
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_rpa_units_listed', aggregate_type='shipping_receipt_unit_collection',
|
||||
aggregate_id=str(getattr(user, 'id', 'admin')), actor_type='admin', actor_id=getattr(user, 'id', None),
|
||||
owner_user_id=getattr(user, 'id', None), result='success',
|
||||
after={'visible_count': len(units), 'status': status or None, 'limit': limit},
|
||||
metadata={'surface': 'workspace_receipt_report_files'},
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'success': True, 'data': {'items': [{
|
||||
'id': unit.id,
|
||||
'source_code': unit.source_code,
|
||||
'warehouse_id': unit.warehouse_id,
|
||||
'status': unit.status,
|
||||
'error_code': unit.error_code,
|
||||
'error_message': unit.error_message,
|
||||
'retry_of_id': unit.retry_of_id,
|
||||
'schedule_run_id': unit.schedule_run_id,
|
||||
'created_at': unit.created_at.isoformat() if unit.created_at else None,
|
||||
'finished_at': unit.finished_at.isoformat() if unit.finished_at else None,
|
||||
} for unit in units]}})
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/receipt-rpa-units/<int:unit_id>/retry', methods=['POST'])
|
||||
@require_admin
|
||||
def retry_receipt_rpa_unit(unit_id: int):
|
||||
"""管理员为失败收料单元创建独立重试事实;旧单元永不覆盖。"""
|
||||
failed = db.session.get(ShippingReceiptRpaUnitRun, unit_id)
|
||||
if failed is None:
|
||||
raise NotFoundError('Receipt RPA unit not found')
|
||||
if failed.status not in {'failed', 'cancelled'}:
|
||||
raise ConflictError('Only failed receipt RPA units can be retried')
|
||||
data = request.get_json(silent=True) or {}
|
||||
reason = str(data.get('reason') or '').strip()
|
||||
if not reason:
|
||||
from app.core.errors import ValidationError
|
||||
raise ValidationError('reason is required', code='SHIPPING.RECEIPT_RETRY_REASON_REQUIRED')
|
||||
user = get_current_user()
|
||||
retry = ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=failed.schedule_run_id, inventory_source_id=failed.inventory_source_id,
|
||||
retry_of_id=failed.id, source_code=failed.source_code, connector_type=failed.connector_type,
|
||||
warehouse_id=failed.warehouse_id, callback_id=f'receipt:{uuid.uuid4().hex}', status='awaiting_rpa',
|
||||
config_snapshot_json=dict(failed.config_snapshot_json or {}),
|
||||
)
|
||||
db.session.add(retry)
|
||||
db.session.flush()
|
||||
source = retry.inventory_source
|
||||
profile = source.rpa_profile if source is not None else None
|
||||
if source is None or profile is None or not profile.enabled:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Receipt RPA profile is unavailable')
|
||||
snapshot = dict(retry.config_snapshot_json or {})
|
||||
trigger_unit = {
|
||||
'unit_run_id': retry.id, 'callback_id': retry.callback_id, 'source_code': retry.source_code,
|
||||
'connector_type': retry.connector_type, 'warehouse_id': retry.warehouse_id,
|
||||
'rpa_profile_id': profile.id, 'rpa_profile_code': profile.profile_code, 'login_url': profile.login_url,
|
||||
'login_config': dict(profile.login_config_json or {}),
|
||||
'credential_envelope': {'username_ciphertext': profile.username_ciphertext, 'password_ciphertext': profile.password_ciphertext},
|
||||
'report_path_json': dict(snapshot.get('report_path_json') or {}),
|
||||
'query_parameters_json': list(snapshot.get('query_parameters_json') or []), 'config_snapshot': snapshot,
|
||||
}
|
||||
retry.trigger_snapshot_json = trigger_unit
|
||||
run = retry.schedule_run
|
||||
trigger_path = write_receipt_export_batch_trigger(
|
||||
f'{run.run_no}-retry-{retry.id}', [trigger_unit],
|
||||
{'schedule_run_id': run.id, 'schedule_task_id': run.schedule_task_id, 'schema_version': 'shipping_receipt_rpa.v1', 'retry_of_unit_id': failed.id},
|
||||
)
|
||||
if not trigger_path:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Receipt RPA trigger directory is unavailable')
|
||||
run.status = 'running'
|
||||
run.finished_at = None
|
||||
summary = dict(run.response_summary_json or {})
|
||||
summary['awaiting_receipt_rpa'] = True
|
||||
run.response_summary_json = summary
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_rpa_unit_retried', aggregate_type='shipping_receipt_unit',
|
||||
aggregate_id=str(retry.id), actor_type='admin', actor_id=getattr(user, 'id', None),
|
||||
owner_user_id=getattr(user, 'id', None), unit_id=retry.id, result='success', reason=reason,
|
||||
before={'status': failed.status, 'error_code': failed.error_code},
|
||||
after={'status': retry.status, 'source_run_no': retry.callback_id, 'owner_user_id': getattr(user, 'id', None)},
|
||||
metadata={'retry_of_id': failed.id},
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'success': True, 'data': {'unit_id': retry.id, 'retry_of_id': failed.id, 'callback_id': retry.callback_id, 'trigger_path': trigger_path}})
|
||||
@@ -139,12 +139,6 @@ def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
|
||||
return jsonify(_dify_openapi_spec())
|
||||
|
||||
@shipping_notice_bp.route('/tools/checkpoint-catalog', methods=['GET'])
|
||||
def checkpoint_catalog():
|
||||
"""返回检查点目录,供开发联调和文档核对 human_options;业务按钮以 ui_state.actions 为准。"""
|
||||
from app.services.shipping_notice.state_machine import build_checkpoint_catalog
|
||||
return jsonify(build_checkpoint_catalog())
|
||||
|
||||
@shipping_notice_bp.route('/tools/openapi.dify.yaml', methods=['GET'])
|
||||
def openapi_dify_yaml():
|
||||
"""返回 Dify 导入用的 OpenAPI YAML 文档。"""
|
||||
@@ -290,15 +284,6 @@ def tool_submit_decision():
|
||||
return jsonify(shipping_tools.submit_decision(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/confirm_inventory_source', methods=['POST'])
|
||||
def tool_confirm_inventory_source():
|
||||
"""
|
||||
确认库存查询来源(仅提交 source_code)。
|
||||
【AI 触发时机】:用户在库存源人工检查点选择正式库存源后调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.confirm_inventory_source(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/confirm_customer', methods=['POST'])
|
||||
def tool_confirm_customer():
|
||||
"""
|
||||
@@ -396,6 +381,14 @@ def rpa_inventory_batch_ready():
|
||||
return jsonify(shipping_tools.rpa_report_inventory_batch(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/receipt-batch-ready', methods=['POST'])
|
||||
def rpa_receipt_batch_ready():
|
||||
"""收料 RPA 回调:独立归档文件,绝不进入库存回调或库存匹配链路。"""
|
||||
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
|
||||
|
||||
return jsonify({'success': True, 'data': ingest_receipt_callback(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-batch-claimed', methods=['POST'])
|
||||
def rpa_inventory_batch_claimed():
|
||||
"""v2 Worker 领取回调:仅记录 Attempt 执行阶段。"""
|
||||
|
||||
@@ -15,7 +15,7 @@ import uuid
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from flask import Blueprint, current_app, g, request, send_file
|
||||
from flask import Blueprint, Response, current_app, g, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import get_current_user
|
||||
@@ -55,7 +55,6 @@ from app.services.shipping_notice.customer_identity_gate import (
|
||||
list_customer_options,
|
||||
)
|
||||
from app.services.shipping_notice.order_customer_matching import confirm_order_customer_match
|
||||
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
|
||||
|
||||
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
|
||||
|
||||
@@ -90,6 +89,34 @@ def _ok(payload: Any, *, status: int = 200):
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None), status=status)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/receipt-report-files/<int:file_id>/download', methods=['GET'])
|
||||
def workspace_download_receipt_report_file(file_id: int):
|
||||
"""下载当前接收人或管理员有权读取的原样收料报表。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.receipt_report_access import resolve_receipt_report_download
|
||||
|
||||
stream, filename, content_type = resolve_receipt_report_download(file_id, user)
|
||||
response = send_file(
|
||||
stream, as_attachment=True, download_name=filename,
|
||||
mimetype=content_type or 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
response.call_on_close(stream.close)
|
||||
return response
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/receipt-report-files', methods=['GET'])
|
||||
def workspace_list_receipt_report_files():
|
||||
"""列出当前接收人或管理员可下载的收料归档文件,不返回对象存储定位。"""
|
||||
user = _require_user()
|
||||
try:
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('limit must be an integer') from exc
|
||||
from app.services.shipping_notice.receipt_report_access import list_receipt_report_files
|
||||
|
||||
return _ok({'items': list_receipt_report_files(user, limit=limit)})
|
||||
|
||||
|
||||
def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> None:
|
||||
"""
|
||||
履约写接口:若请求携带期望 OT/Case/Run,校验与正式 Notice 归属一致。
|
||||
@@ -491,7 +518,11 @@ def workspace_confirm_order_customer_match(extraction_id: int, role: str):
|
||||
# [STEP P1-7] 抽取侧客户确认后,同事务内触发 Case 级协调器(level-triggered reconcile 补偿)。
|
||||
# 通过 Extraction → Candidate → Review Case 反查未终态 Case;若抽取阶段太早尚无 Case,不报错跳过。
|
||||
if role == 'bill_to':
|
||||
from app.models import ShippingOrderCandidate, ShippingOrderReviewCase
|
||||
from app.models import (
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewStream,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
|
||||
reconcile_single_case_for_auto_progress,
|
||||
)
|
||||
@@ -508,13 +539,21 @@ def workspace_confirm_order_customer_match(extraction_id: int, role: str):
|
||||
if candidate_ids:
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.join(
|
||||
ShippingOrderReviewStream,
|
||||
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
|
||||
)
|
||||
.filter(ShippingOrderReviewCase.candidate_id.in_(candidate_ids))
|
||||
.first()
|
||||
)
|
||||
if case is None and extraction.run_id:
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(run_id=int(extraction.run_id))
|
||||
.join(
|
||||
ShippingOrderReviewStream,
|
||||
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
|
||||
)
|
||||
.filter(ShippingOrderReviewCase.run_id == int(extraction.run_id))
|
||||
.first()
|
||||
)
|
||||
if case is not None and str(case.status or '') not in _TERMINAL and not case.confirmed_task_id:
|
||||
@@ -533,89 +572,6 @@ def workspace_shipping_conversation_batch_workspace(conversation_id: str):
|
||||
return _ok(get_conversation_batch_workspace(conversation_id, user.id))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-conversations/<conversation_id>/retry-auto-progress',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_retry_conversation_auto_progress(conversation_id: str):
|
||||
"""
|
||||
对话级「重试自动推进」:扫描会话下可恢复 Case/正式 OT 并逐对象重试。
|
||||
|
||||
核心逻辑:委托 conversation_retry_auto_progress_service;前端不提交对象列表;
|
||||
返回 summary + items;写 conversation_retry_auto_progress 汇总审计。
|
||||
|
||||
异常保护:
|
||||
[STEP R-1] 路由级显式 try/except 兜底,保证模块导入期 SyntaxError/ImportError
|
||||
不冒泡为裸 500(与 conversation_retry_auto_progress_service 内部
|
||||
三分支 _execute_* 的 import 级 try/except 形成双层防护)。
|
||||
[STEP R-2] AppError 正常 re-raise,交给 @app.errorhandler(AppError);
|
||||
SyntaxError/ImportError/其他 Exception 统一转为 SHIPPING.RETRY_AUTO_PROGRESS_FAILED
|
||||
并返回 summary={failed:1} 的骨架,避免前端 JSON 解析失败。
|
||||
"""
|
||||
import logging as _rt_logging
|
||||
_rt_log = _rt_logging.getLogger(__name__)
|
||||
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
normalized_conv_id = str(conversation_id or '').strip()
|
||||
fallback_payload = {
|
||||
'conversation_id': normalized_conv_id,
|
||||
'summary': {'total': 1, 'retried': 0, 'skipped': 0, 'failed': 1},
|
||||
'items': [{
|
||||
'object_type': 'conversation',
|
||||
'object_ref': normalized_conv_id,
|
||||
'action': 'retry_auto_progress',
|
||||
'outcome': 'failed',
|
||||
'reason_code': 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED',
|
||||
'metadata': {},
|
||||
}],
|
||||
}
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.conversation_retry_auto_progress_service import (
|
||||
retry_auto_progress_for_conversation,
|
||||
)
|
||||
except (SyntaxError, ImportError) as mod_err:
|
||||
_rt_log.exception(
|
||||
'retry_conversation_auto_progress module import error conversation_id=%s err=%s',
|
||||
normalized_conv_id, type(mod_err).__name__,
|
||||
)
|
||||
fallback_payload['items'][0]['reason_code'] = 'SHIPPING.MODULE_IMPORT_ERROR'
|
||||
fallback_payload['items'][0]['metadata']['import_error'] = type(mod_err).__name__
|
||||
return _ok(fallback_payload)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_rt_log.exception(
|
||||
'retry_conversation_auto_progress import unexpected error conversation_id=%s',
|
||||
normalized_conv_id,
|
||||
)
|
||||
fallback_payload['items'][0]['reason_code'] = (
|
||||
'SHIPPING.RETRY_AUTO_PROGRESS_FAILED'
|
||||
)
|
||||
fallback_payload['items'][0]['metadata']['error_type'] = type(exc).__name__
|
||||
return _ok(fallback_payload)
|
||||
|
||||
try:
|
||||
result = retry_auto_progress_for_conversation(
|
||||
user_id=int(user.id),
|
||||
conversation_id=normalized_conv_id,
|
||||
reason=str(data.get('reason') or 'user_retry_auto_progress'),
|
||||
)
|
||||
except AppError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_rt_log.exception(
|
||||
'retry_conversation_auto_progress execution error conversation_id=%s',
|
||||
normalized_conv_id,
|
||||
)
|
||||
fallback_payload['items'][0]['reason_code'] = (
|
||||
'SHIPPING.RETRY_AUTO_PROGRESS_FAILED'
|
||||
)
|
||||
fallback_payload['items'][0]['metadata']['error_type'] = type(exc).__name__
|
||||
return _ok(fallback_payload)
|
||||
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
|
||||
def workspace_create_shipping_task_from_notice():
|
||||
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
|
||||
@@ -645,7 +601,7 @@ def workspace_create_shipping_task_from_notice():
|
||||
task_no=task_id,
|
||||
)
|
||||
if not intake.accepted:
|
||||
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})
|
||||
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED})
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.raw_content = intake.text
|
||||
@@ -817,62 +773,6 @@ def workspace_retry_shipping_task_line(task_no: str, line_key: str):
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-inventory-source', methods=['POST'])
|
||||
def workspace_confirm_shipping_inventory_source(task_no: str):
|
||||
"""
|
||||
确认当前任务的库存 RPA 来源,并继续触发库存导出。
|
||||
|
||||
核心逻辑:注入可信操作人 ID,供库存源确认事件与统一审计双写。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
source_code = str(data.get('source_code') or '').strip()
|
||||
if not source_code:
|
||||
raise ValidationError('source_code is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return _ok(shipping_tools.confirm_inventory_source({
|
||||
'task_id': task.task_no,
|
||||
'source_code': source_code,
|
||||
'operator_id': user.id,
|
||||
'actor_id': user.id,
|
||||
'_trusted_user_id': user.id,
|
||||
'event_source': 'workspace_api',
|
||||
}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/submit-decision', methods=['POST'])
|
||||
def workspace_submit_shipping_decision(task_no: str):
|
||||
"""
|
||||
以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。
|
||||
|
||||
核心逻辑:注入操作人与 event_source=workspace_api,保证决策审计非匿名。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
decision = str(data.get('decision') or '').strip()
|
||||
if not decision:
|
||||
raise ValidationError('decision is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {
|
||||
'task_id': task.task_no,
|
||||
'decision': decision,
|
||||
AUTO_CHAIN_FALLBACK: True,
|
||||
'event_source': 'workspace_api',
|
||||
'operator_id': user.id,
|
||||
'actor_id': user.id,
|
||||
'_trusted_user_id': user.id,
|
||||
'user_id': user.id,
|
||||
}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return _ok(shipping_tools.submit_decision(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-fields', methods=['POST'])
|
||||
def workspace_update_shipping_notice_fields(task_no: str):
|
||||
"""更新发货通知单头字段。"""
|
||||
@@ -899,32 +799,6 @@ def workspace_update_shipping_notice_fields(task_no: str):
|
||||
return _ok(shipping_tools.update_notice_fields(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/freeze-order', methods=['POST'])
|
||||
def workspace_freeze_shipping_order(task_no: str):
|
||||
"""冻结已复核订单为不可编辑的强类型履约快照。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
expected_version = int(data.get('expected_order_data_version'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('expected_order_data_version is required') from exc
|
||||
snapshot = freeze_order_snapshot(
|
||||
task,
|
||||
actor_id=int(user.id),
|
||||
expected_order_data_version=expected_version,
|
||||
rule_versions=data.get('rule_versions') if isinstance(data.get('rule_versions'), dict) else None,
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok({
|
||||
'task_no': task.task_no,
|
||||
'snapshot_id': snapshot.id,
|
||||
'order_data_version': snapshot.order_data_version,
|
||||
'frozen_at': snapshot.frozen_at.isoformat(),
|
||||
})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-freight-cancellations/<int:cancellation_id>/complete', methods=['POST'])
|
||||
def workspace_complete_shipping_freight_cancellation(cancellation_id: int):
|
||||
@@ -1121,46 +995,6 @@ def workspace_auto_progress_shipping_task(task_no: str):
|
||||
}
|
||||
return _ok(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/match-inventory', methods=['POST'])
|
||||
def workspace_match_shipping_inventory(task_no: str):
|
||||
"""兼容旧匹配入口:只提交当前 Gate 自动推进,不直接执行库存匹配。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
_assert_fulfillment_task_ownership(task, user.id)
|
||||
from app.services.shipping_notice.auto_progress_controller import (
|
||||
audit_legacy_forwarded_entrypoint,
|
||||
submit_auto_progress,
|
||||
)
|
||||
audit_legacy_forwarded_entrypoint(
|
||||
task=task, action_code='match_inventory', actor_id=user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
result = submit_auto_progress(task=task, trigger='legacy_match_inventory', operator_id=user.id)
|
||||
return _ok({'deprecated': True, 'projection_refresh_required': True, **result})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST'])
|
||||
def workspace_generate_shipping_excel(task_no: str):
|
||||
"""兼容旧导出入口:只提交当前 Gate 自动推进,不直接生成 Excel。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
_assert_fulfillment_task_ownership(task, user.id)
|
||||
from app.services.shipping_notice.auto_progress_controller import (
|
||||
audit_legacy_forwarded_entrypoint,
|
||||
submit_auto_progress,
|
||||
)
|
||||
audit_legacy_forwarded_entrypoint(
|
||||
task=task, action_code='generate_excel', actor_id=user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
result = submit_auto_progress(task=task, trigger='legacy_generate_excel', operator_id=user.id)
|
||||
return _ok({'deprecated': True, 'projection_refresh_required': True, **result})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
|
||||
def workspace_mark_manual_uploaded(task_no: str):
|
||||
"""
|
||||
@@ -1197,24 +1031,6 @@ def workspace_mark_manual_uploaded(task_no: str):
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST'])
|
||||
def workspace_retry_shipping_upload(task_no: str):
|
||||
"""
|
||||
货代上传重试入口;首期若全局禁用 RPA 则返回明确错误码。
|
||||
|
||||
核心逻辑:先做归属校验;若平台禁用 RPA 再抛 ValidationError,避免跳过归属门禁。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
_assert_fulfillment_task_ownership(task, user.id)
|
||||
raise ValidationError(
|
||||
'首期不支持货代 RPA 上传重试。请下载 Excel,在货代系统人工上传后提交截图/PDF 凭据。',
|
||||
code='SHIPPING.FREIGHT_RPA_UPLOAD_DISABLED',
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。"""
|
||||
@@ -1265,6 +1081,54 @@ def workspace_shipping_task_inventory_file(task_no: str):
|
||||
return send_file(path, as_attachment=True, download_name=download_name)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-tasks/<task_no>/inventory-files/<inventory_file_no>', methods=['GET'],
|
||||
)
|
||||
def workspace_shipping_task_line_inventory_file(task_no: str, inventory_file_no: str):
|
||||
"""下载当前任务明细已匹配引用的库存文件,禁止按任务或库存源宽泛猜测。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from pathlib import Path
|
||||
|
||||
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch
|
||||
|
||||
requested_file_no = str(inventory_file_no or '').strip()
|
||||
inventory_file = (
|
||||
ShippingInventoryFile.query
|
||||
.join(
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingNoticeLineInventoryMatch.inventory_snapshot_id == ShippingInventoryFile.id,
|
||||
)
|
||||
.filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
ShippingNoticeLineInventoryMatch.matched_file_no == requested_file_no,
|
||||
ShippingInventoryFile.inventory_file_no == requested_file_no,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
storage_path = str(getattr(inventory_file, 'storage_path', '') or '').strip()
|
||||
path = Path(storage_path).resolve() if storage_path else None
|
||||
if inventory_file is None or not storage_path or storage_path.startswith('failed://') or not path.is_file():
|
||||
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND')
|
||||
download_name = str(
|
||||
inventory_file.source_file_name or f'{inventory_file.inventory_file_no}{path.suffix or ".xlsx"}',
|
||||
).strip()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
record_access_audit(
|
||||
action='download_task_line_inventory_file',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=str(task.task_no),
|
||||
actor_id=user.id,
|
||||
task_no=str(task.task_no),
|
||||
reason_code='inventory_file_downloaded',
|
||||
metadata={'inventory_file': download_name, 'inventory_file_no': requested_file_no},
|
||||
)
|
||||
return send_file(path, as_attachment=True, download_name=download_name)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['GET'])
|
||||
def workspace_list_shipping_order_intakes():
|
||||
"""列出当前会话下未消费的活跃接入记录。"""
|
||||
@@ -1656,79 +1520,6 @@ def workspace_retry_shipping_order_stp_auto_create(case_no: str):
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/retry-auto-progress',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_retry_shipping_order_case_auto_progress(case_no: str):
|
||||
"""
|
||||
单个 Case 精确自动推进恢复入口。适用于 Projection primary_action.code = retry_auto_progress。
|
||||
禁止 duplicate 等业务阻断对象调用;assert_case_not_blocked_manual 前置双校验。
|
||||
|
||||
核心逻辑:
|
||||
[可见性] get_review_case_visible_to_user → [业务阻断] assert_case_not_blocked_manual
|
||||
→ [终态幂等] confirmed_task_id/status 终态 → [协调器] reconcile_single_case_for_auto_progress
|
||||
→ [审计] case_retry_auto_progress_invoked → 返回 success+case_no+reconcile_result+serialized case。
|
||||
|
||||
异常保护:
|
||||
[STEP R-1] 路由级显式 try/except 兜底,保证模块导入期 SyntaxError/ImportError
|
||||
不冒泡为裸 500(与 case_retry_auto_progress_service 内部双校验
|
||||
形成双层防护)。
|
||||
[STEP R-2] AppError 正常 re-raise;SyntaxError/ImportError/其他 Exception 转为
|
||||
success=false + error_code,前端统一消费 retry 结果投影。
|
||||
"""
|
||||
import logging as _rt_logging
|
||||
_rt_log = _rt_logging.getLogger(__name__)
|
||||
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
normalized_case_no = str(case_no or '').strip()
|
||||
fallback_result = {
|
||||
'success': False,
|
||||
'case_no': normalized_case_no,
|
||||
'error': 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED',
|
||||
'enqueue_status': 'not_eligible',
|
||||
}
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.case_retry_auto_progress_service import (
|
||||
case_retry_auto_progress,
|
||||
)
|
||||
except (SyntaxError, ImportError) as mod_err:
|
||||
_rt_log.exception(
|
||||
'case_retry_auto_progress module import error case_no=%s err=%s',
|
||||
normalized_case_no, type(mod_err).__name__,
|
||||
)
|
||||
fallback_result['error'] = 'SHIPPING.MODULE_IMPORT_ERROR'
|
||||
fallback_result['import_error'] = type(mod_err).__name__
|
||||
return _ok(fallback_result)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_rt_log.exception(
|
||||
'case_retry_auto_progress import unexpected error case_no=%s',
|
||||
normalized_case_no,
|
||||
)
|
||||
fallback_result['error_type'] = type(exc).__name__
|
||||
return _ok(fallback_result)
|
||||
|
||||
try:
|
||||
result = case_retry_auto_progress(
|
||||
user_id=int(user.id),
|
||||
case_no=normalized_case_no,
|
||||
is_admin=bool(is_admin),
|
||||
)
|
||||
except AppError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_rt_log.exception(
|
||||
'case_retry_auto_progress execution error case_no=%s',
|
||||
normalized_case_no,
|
||||
)
|
||||
fallback_result['error_type'] = type(exc).__name__
|
||||
return _ok(fallback_result)
|
||||
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/reconcile-and-progress',
|
||||
methods=['POST'],
|
||||
@@ -2039,41 +1830,13 @@ def workspace_validate_shipping_order_review_draft(case_no: str):
|
||||
return _ok(attach_resume_outcome({'case': result}, resume))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>/inventory-candidates',
|
||||
methods=['PUT'],
|
||||
)
|
||||
def workspace_set_shipping_order_review_inventory_candidates(case_no: str, line_key: str):
|
||||
"""
|
||||
人工为明细选择一个或多个已启用库存源候选。
|
||||
|
||||
核心逻辑:强制 reason;写入 Draft 行级覆盖后重跑资格校验。
|
||||
"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import set_line_inventory_candidates
|
||||
|
||||
payload = _review_draft_payload(
|
||||
user_id=user.id, case_no=case_no, action='line_inventory_candidates_selected',
|
||||
)
|
||||
result = set_line_inventory_candidates(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
line_key=line_key,
|
||||
source_codes=list(payload.get('source_codes') or []),
|
||||
reason=str(payload.get('reason') or ''),
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/draft/inventory-routing/reroute',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_reroute_shipping_order_review_inventory_routing(case_no: str):
|
||||
"""
|
||||
按最新已发布规则重算库存源路由;不重新识别 PDF,不静默覆盖人工决定。
|
||||
按最新已发布规则重算库存源路由;不重新识别 PDF,并清除历史人工库存源决定。
|
||||
|
||||
核心逻辑:可选 line_key;携带 expected_draft_version 与幂等键。
|
||||
"""
|
||||
@@ -2094,54 +1857,6 @@ def workspace_reroute_shipping_order_review_inventory_routing(case_no: str):
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>/inventory-routing/adopt-suggestion',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_adopt_shipping_order_review_inventory_routing_suggestion(case_no: str, line_key: str):
|
||||
"""采用当前规则建议为有效库存源候选。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import adopt_inventory_routing_suggestion
|
||||
|
||||
payload = _review_draft_payload(
|
||||
user_id=user.id, case_no=case_no, action='inventory_routing_suggestion_adopted',
|
||||
)
|
||||
result = adopt_inventory_routing_suggestion(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
line_key=line_key,
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
idempotency_key=payload.get('idempotency_key'),
|
||||
reason=payload.get('reason'),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>/inventory-routing/keep-manual',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_keep_shipping_order_review_inventory_routing_manual(case_no: str, line_key: str):
|
||||
"""明确保留人工库存源决定并拒绝规则建议。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import keep_manual_inventory_routing
|
||||
|
||||
payload = _review_draft_payload(
|
||||
user_id=user.id, case_no=case_no, action='inventory_routing_manual_kept',
|
||||
)
|
||||
result = keep_manual_inventory_routing(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
line_key=line_key,
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
idempotency_key=payload.get('idempotency_key'),
|
||||
reason=payload.get('reason'),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/customer-resolution/retry',
|
||||
methods=['POST'],
|
||||
@@ -2253,7 +1968,7 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str):
|
||||
"""
|
||||
写入行级履约决定。
|
||||
|
||||
Body: line_key, decision_code, reason?, expected_draft_version?
|
||||
Body: line_key, decision_code, reason?, release_field_values?, expected_draft_version?
|
||||
"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
@@ -2268,6 +1983,10 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str):
|
||||
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,
|
||||
release_field_values=(
|
||||
data.get('release_field_values')
|
||||
if isinstance(data.get('release_field_values'), dict) else None
|
||||
),
|
||||
expected_draft_version=data.get('expected_draft_version'),
|
||||
actor_is_admin=is_admin,
|
||||
)
|
||||
@@ -2628,33 +2347,6 @@ def workspace_reparse_shipping_order_review_document(case_no: str):
|
||||
return ok({'run': serialize_order_extraction_run(run), 'reused': reused}, request_id=getattr(g, 'request_id', None), status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/replacement-intakes', methods=['POST'])
|
||||
def workspace_create_shipping_order_review_replacement_intake(case_no: str):
|
||||
"""绑定已上传的新 PDF 为替代 Intake;原 PDF/Case 保留到替代识别成功后才被替代。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_disposition_service import create_replacement_upload_intake
|
||||
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='replacement_intake')
|
||||
intake = create_replacement_upload_intake(user_id=user.id, case_no=case_no, asset_no=payload.get('asset_no'))
|
||||
db.session.commit()
|
||||
return _ok(intake, status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/replacement-runs', methods=['POST'])
|
||||
def workspace_create_shipping_order_review_replacement_run(case_no: str):
|
||||
"""替代 Intake 解析完成后只为其唯一 PDF 创建新 Run;不覆盖旧文档证据。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_run
|
||||
from app.services.shipping_notice.order_review_disposition_service import create_replacement_document_run
|
||||
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='replacement_run')
|
||||
run, reused = create_replacement_document_run(
|
||||
user_id=user.id, case_no=case_no, intake_no=payload.get('intake_no'),
|
||||
)
|
||||
db.session.commit()
|
||||
return ok({'run': serialize_order_extraction_run(run), 'reused': reused}, request_id=getattr(g, 'request_id', None), status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/evidence', methods=['GET'])
|
||||
def workspace_list_shipping_order_review_evidence(case_no: str):
|
||||
"""列出当前用户 PDF 的安全证据摘要;不泄露全文、对象存储位置或模型响应;访问留痕。"""
|
||||
@@ -2920,13 +2612,41 @@ def workspace_get_shipping_order_review_intake_parse_context(case_no: str):
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/email-preview', methods=['GET'])
|
||||
def workspace_preview_shipping_order_review_email(case_no: str):
|
||||
"""消费 Case 绑定的短时令牌,返回强 CSP 隔离的 EML 原始 HTML 视觉预览。"""
|
||||
from app.services.shipping_notice.eml_preview_service import consume_eml_preview_grant
|
||||
|
||||
user = get_current_user()
|
||||
html = consume_eml_preview_grant(
|
||||
token=str(request.args.get('preview_token') or ''), user_id=user.id if user else None, case_no=case_no,
|
||||
)
|
||||
if not html:
|
||||
raise NotFoundError('Email preview is unavailable', code='SHIPPING.REVIEW_EMAIL_PREVIEW_NOT_FOUND')
|
||||
response = Response(html, mimetype='text/html')
|
||||
response.headers['Cache-Control'] = 'private, no-store, max-age=0'
|
||||
response.headers['Pragma'] = 'no-cache'
|
||||
response.headers['X-Content-Type-Options'] = 'nosniff'
|
||||
response.headers['Content-Security-Policy'] = (
|
||||
"default-src 'none'; script-src 'none'; connect-src 'none'; img-src 'none'; media-src 'none'; "
|
||||
"font-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; "
|
||||
"style-src 'unsafe-inline'; navigate-to 'none'"
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/email-evidence-preview/<int:document_id>', methods=['GET'])
|
||||
def workspace_preview_shipping_order_review_email_evidence(case_no: str, document_id: int):
|
||||
"""返回当前复核 Case 同 Intake 邮件正文的受控文本预览,不返回原始 EML 或附件。"""
|
||||
"""返回当前复核 Case 同 Intake 邮件正文的受控 HTML/文本证据预览。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_evidence_service import get_case_email_evidence_text
|
||||
|
||||
return _ok(get_case_email_evidence_text(user_id=user.id, case_no=case_no, document_id=document_id))
|
||||
return _ok(get_case_email_evidence_text(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
document_id=document_id,
|
||||
evidence_id=str(request.args.get('evidence_id') or '').strip() or None,
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/seen', methods=['POST'])
|
||||
@@ -3092,6 +2812,25 @@ def workspace_reparse_shipping_order_extraction_run(run_no: str):
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/reparse-batch', methods=['POST'])
|
||||
def workspace_reparse_shipping_order_extraction_batch(run_no: str):
|
||||
"""按 PDF 子任务重解析一个批次;已确认/履约文件由服务端预检排除。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True)
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('Request body must be an object')
|
||||
from app.services.shipping_notice.order_review_disposition_service import reparse_batch_documents
|
||||
|
||||
result = reparse_batch_documents(
|
||||
user_id=user.id,
|
||||
run_no=run_no,
|
||||
reason=str(body.get('reason') or ''),
|
||||
comment=str(body.get('comment') or '') or None,
|
||||
)
|
||||
db.session.commit()
|
||||
return ok(result, request_id=getattr(g, 'request_id', None), status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs', methods=['GET'])
|
||||
def workspace_list_shipping_order_extraction_runs():
|
||||
"""
|
||||
|
||||
@@ -300,34 +300,10 @@ class Config:
|
||||
SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED = (
|
||||
os.getenv('SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED', 'false').lower() == 'true'
|
||||
)
|
||||
# XFA 数据路径 Profile:识别到 xfa_hybrid 即走 xfa_dataset。
|
||||
# 独立自动建单总闸(阶段 5+);默认关。开启前须满足合成预览门禁 / CQ / 盲测 / 审计补偿。
|
||||
# XFA 数据路径 Profile:识别到 xfa_hybrid 后允许使用 datasets adapter。
|
||||
SHIPPING_NOTICE_XFA_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_XFA_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_XFA_AUTO_CREATE_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_XFA_AUTO_CREATE_ENABLED', 'false').lower() == 'true'
|
||||
)
|
||||
# 离线完整 flatten 引擎是否已交付并可返回 ready;默认 false(禁 overlay/壳图)。
|
||||
SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY = (
|
||||
os.getenv('SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY', 'false').lower() == 'true'
|
||||
)
|
||||
# 自动建单硬前置:审计写失败补偿能力就绪前禁止开自动建单(阶段 6)。
|
||||
SHIPPING_NOTICE_XFA_AUDIT_COMPENSATION_REQUIRED_FOR_AUTO_CREATE = (
|
||||
os.getenv('SHIPPING_NOTICE_XFA_AUDIT_COMPENSATION_REQUIRED_FOR_AUTO_CREATE', '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)
|
||||
)
|
||||
@@ -380,6 +356,9 @@ class Config:
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS') or '900'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
|
||||
)
|
||||
@@ -454,6 +433,12 @@ class Config:
|
||||
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = _rpa_data_path(
|
||||
'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'shipping_notice', 'freight_rpa', 'inventory_triggers'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = _rpa_data_path(
|
||||
'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR', 'shipping_notice', 'freight_receipt_rpa', 'receipt_drop'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = _rpa_data_path(
|
||||
'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR', 'shipping_notice', 'freight_receipt_rpa', 'receipt_triggers'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path(
|
||||
'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR', 'shipping_notice', 'freight_rpa', 'upload_queue'
|
||||
)
|
||||
|
||||
@@ -23,6 +23,5 @@ from app.jobs.handlers import ( # noqa: F401
|
||||
shipping_post_ot_wave_progress,
|
||||
shipping_review_revalidate_progress,
|
||||
shipping_pdf_automark,
|
||||
shipping_xfa_ocr_automark,
|
||||
wecom_directory_sync,
|
||||
)
|
||||
@@ -173,14 +173,16 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
xfa_outcome = analyze_xfa_pdf(content, limits=default_xfa_resource_limits())
|
||||
timings['xfa_analysis_ms'] = round((perf_counter() - xfa_started) * 1000)
|
||||
|
||||
xfa_capability: dict | None = None
|
||||
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)
|
||||
capability = snapshot.get('xfa_capability') if isinstance(snapshot.get('xfa_capability'), dict) else {}
|
||||
xfa_snapshot = dict(xfa_outcome.snapshot)
|
||||
capability = xfa_snapshot.get('xfa_capability') if isinstance(xfa_snapshot.get('xfa_capability'), dict) else {}
|
||||
xfa_capability = dict(capability)
|
||||
try:
|
||||
counts['page_count'] = int(capability.get('page_count') or 0)
|
||||
except (TypeError, ValueError):
|
||||
@@ -191,6 +193,11 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
source_content_hash=str(document.content_hash or ''),
|
||||
outcome=xfa_outcome,
|
||||
)
|
||||
# persist_xfa_structure_analysis 将冻结 analysis_id 回填到 outcome 快照;
|
||||
# 重新读取,确保随后合并到统一视觉 Layout 的 capability 可被精确复核。
|
||||
persisted_capability = xfa_outcome.snapshot.get('xfa_capability')
|
||||
if isinstance(persisted_capability, dict):
|
||||
xfa_capability = dict(persisted_capability)
|
||||
if xfa_outcome.error_code == 'XFA_UNSAFE_XML':
|
||||
_layout_job_audit(
|
||||
event_type='xfa_parse_rejected_unsafe',
|
||||
@@ -199,15 +206,15 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
result='failure',
|
||||
error_code=xfa_outcome.error_code,
|
||||
)
|
||||
elif snapshot.get('status') == 'ready':
|
||||
elif xfa_snapshot.get('status') == 'ready':
|
||||
_layout_job_audit(
|
||||
event_type='xfa_structure_analysis_ready',
|
||||
job=job,
|
||||
version=version,
|
||||
metadata={
|
||||
'document_kind': snapshot.get('document_kind'),
|
||||
'document_kind': xfa_snapshot.get('document_kind'),
|
||||
'structure_analysis_id': (
|
||||
(snapshot.get('xfa_capability') or {}).get('structure_analysis_id')
|
||||
(xfa_snapshot.get('xfa_capability') or {}).get('structure_analysis_id')
|
||||
),
|
||||
},
|
||||
)
|
||||
@@ -221,15 +228,19 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
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,
|
||||
counts=counts,
|
||||
)
|
||||
# XFA datasets 与视觉 Layout 是同一文档的两种证据。即使 XFA 结构分析成功,
|
||||
# 也必须继续构建通用表格/坐标 Layout,供统一 main_table_id、标注与验证使用。
|
||||
# datasets capability 仅在末端 value adapter 选择正式取值来源,不能再短路生命周期。
|
||||
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,
|
||||
counts=counts,
|
||||
)
|
||||
if snapshot is not None and xfa_capability is not None:
|
||||
snapshot['xfa_capability'] = xfa_capability
|
||||
timings['snapshot_build_ms'] = round((perf_counter() - total_started) * 1000)
|
||||
if snapshot is None:
|
||||
snapshot = {
|
||||
@@ -286,7 +297,7 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
error_code=LAYOUT_JOB_ERROR,
|
||||
metadata={'error': str(exc)[:200]},
|
||||
)
|
||||
fail_job(job.id, error=LAYOUT_JOB_ERROR, retryable=True, owned_attempt=owned_attempt)
|
||||
fail_job(job.id, error=LAYOUT_JOB_ERROR, retryable=False, owned_attempt=owned_attempt)
|
||||
sync_layout_after_job_failure(job.id)
|
||||
# 仅当重试已耗尽时版本才会转 failed;此时需要唤醒等待中的 Run,
|
||||
# 让用户看到“附件解析失败”而不是永久停留在“正在解析”。
|
||||
|
||||
@@ -34,6 +34,21 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import process_rpa_report_inventory_batch
|
||||
|
||||
result = process_rpa_report_inventory_batch(dict(job.payload_json or {}))
|
||||
result_data = result.get('data') if isinstance(result, dict) else None
|
||||
result_status = str(
|
||||
(result_data or {}).get('result_status') if isinstance(result_data, dict) else ''
|
||||
).strip().lower()
|
||||
if result_status in {'failed', 'partial_failed'}:
|
||||
failed_items = result_data.get('failed') if isinstance(result_data, dict) else []
|
||||
first_error = failed_items[0].get('error') if isinstance(failed_items, list) and failed_items and isinstance(failed_items[0], dict) else None
|
||||
fail_job(
|
||||
job.id,
|
||||
error=str(first_error or f'inventory_callback_business_{result_status}'),
|
||||
result={'status': 'processed', 'callback_result': result},
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
finish_job(
|
||||
job.id,
|
||||
result={'status': 'processed', 'callback_result': result},
|
||||
@@ -46,6 +61,6 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
|
||||
job.id,
|
||||
error=str(exc),
|
||||
result={'status': 'processing_failed', 'error': str(exc)[:1000]},
|
||||
retryable=True,
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
@@ -58,7 +58,7 @@ def handle_shipping_line_auto_fulfill(ctx: JobContext, payload: dict) -> None:
|
||||
job_id,
|
||||
error=str(result.get('error') or 'auto_fulfill_failed'),
|
||||
result=result,
|
||||
retryable=True,
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
@@ -74,7 +74,7 @@ def handle_shipping_line_auto_fulfill(ctx: JobContext, payload: dict) -> None:
|
||||
job_id,
|
||||
error=str(exc)[:500],
|
||||
result={'status': 'failed'},
|
||||
retryable=True,
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
raise
|
||||
@@ -264,7 +264,7 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
|
||||
# 租约已失效:旧 Worker 不得触碰 Job(条件 UPDATE 亦会 no-op,此处直接返回)
|
||||
if str(fail_result.get('reason') or '') == 'stale_parse_lease':
|
||||
return
|
||||
retryable = _is_retryable_exc(exc)
|
||||
retryable = False
|
||||
if job_id is not None:
|
||||
fail_job(
|
||||
job_id,
|
||||
@@ -272,5 +272,3 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
|
||||
retryable=retryable,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
if retryable:
|
||||
raise
|
||||
@@ -13,9 +13,13 @@ backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import inspect
|
||||
import sys
|
||||
import time
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
@@ -44,6 +48,7 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
ensure_workflow_items_for_run,
|
||||
progress_ready_extraction_unit,
|
||||
schedule_order_extraction_layouts,
|
||||
synchronize_order_extraction_expansion_snapshot,
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_progress import (
|
||||
@@ -55,7 +60,6 @@ from app.services.shipping_notice.order_extraction_workflow import (
|
||||
validate_unit_orders,
|
||||
)
|
||||
|
||||
MAX_UNIT_TECHNICAL_ATTEMPTS = 3
|
||||
EXPANDABLE_UNIT_REVIEW_REASON_CODES = {
|
||||
'required_anchor_missing',
|
||||
'required_field_missing',
|
||||
@@ -107,13 +111,52 @@ def _json_safe_order_payload(value: Any) -> Any:
|
||||
if isinstance(value, dict):
|
||||
return {str(key): _json_safe_order_payload(item) for key, item in value.items()}
|
||||
return value
|
||||
|
||||
|
||||
def _route_runtime_diagnostic() -> dict[str, str]:
|
||||
"""
|
||||
返回订单路由代码的最小运行期身份,用于定位 Worker 与本地重放不一致。
|
||||
|
||||
核心逻辑:仅记录解释器和已加载 ``route_deterministic_unit`` 源文件的路径/摘要;
|
||||
不读取或记录 PDF、datasets、坐标文字及订单字段值。
|
||||
|
||||
Returns:
|
||||
脱敏运行期身份字典。源文件不可读时以 ``unavailable`` 明确表示,不能阻断建单。
|
||||
"""
|
||||
source_path = inspect.getsourcefile(route_deterministic_unit)
|
||||
source_digest = 'unavailable'
|
||||
if source_path:
|
||||
try:
|
||||
source_digest = hashlib.sha256(Path(source_path).read_bytes()).hexdigest()
|
||||
except OSError:
|
||||
# 诊断是审计增强,文件暂不可读不能影响已完成的业务路由。
|
||||
pass
|
||||
return {
|
||||
'interpreter': str(sys.executable),
|
||||
'workflow_module_path': str(source_path or 'unavailable'),
|
||||
'workflow_source_sha256': source_digest,
|
||||
}
|
||||
|
||||
|
||||
EXPANDABLE_ORDER_CONFLICT_REASONS = {
|
||||
'supplement_relation_ambiguous',
|
||||
}
|
||||
|
||||
|
||||
def _append_route_decision(*, run, unit, job, attempt_no: int, route_result) -> None:
|
||||
"""追加 Unit 脱敏路由投影及统一审计,尝试号必须区分同一 Job 内的单元重试。"""
|
||||
"""
|
||||
追加 Unit 脱敏路由投影、统一审计和运行期身份,尝试号必须区分同一 Job 内的单元重试。
|
||||
|
||||
核心逻辑:结构化列保存查询字段;审计 metadata 追加不含业务原文的运行期源码身份,
|
||||
使 Worker 结果可与相同冻结 Run 的只读重放逐项比对。
|
||||
|
||||
Args:
|
||||
run: 当前冻结订单抽取 Run。
|
||||
unit: 当前附件处理单元。
|
||||
job: 消费该单元的 Job。
|
||||
attempt_no: Unit 内的执行代次。
|
||||
route_result: 统一确定性路由结果。
|
||||
"""
|
||||
decision = route_result.decision if isinstance(route_result.decision, dict) else {}
|
||||
candidates = decision.get('candidate_summary') if isinstance(decision.get('candidate_summary'), list) else []
|
||||
safe_candidates = [{
|
||||
@@ -171,6 +214,7 @@ def _append_route_decision(*, run, unit, job, attempt_no: int, route_result) ->
|
||||
decision.get('generic_completeness')
|
||||
if isinstance(decision.get('generic_completeness'), dict) else None
|
||||
),
|
||||
'runtime_diagnostic': _route_runtime_diagnostic(),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -397,6 +441,11 @@ def _activate_expansion_batch(
|
||||
schema_definition=schema_definition if isinstance(schema_definition, dict) else {},
|
||||
selection_batches={int(selection_batch)},
|
||||
)
|
||||
synchronize_order_extraction_expansion_snapshot(
|
||||
run,
|
||||
selection_batch=int(selection_batch),
|
||||
)
|
||||
schedule_order_extraction_layouts(run, created_by_id=run.user_id)
|
||||
return ensure_order_extraction_plan_batch(run, selection_batch=int(selection_batch))
|
||||
|
||||
|
||||
@@ -410,7 +459,7 @@ def _reload_run_and_unit(*, run_id: int, unit_id: int) -> tuple[ShippingOrderPro
|
||||
|
||||
|
||||
def _record_unit_technical_failure(*, run, unit, job, exc: Exception, retryable: bool) -> None:
|
||||
"""将单元异常收敛为稳定技术失败事实,并在可重试时回到 pending。"""
|
||||
"""将单元异常收敛为稳定技术失败事实;失败即停止,不回到 pending。"""
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
error_code = str(getattr(exc, 'code', None) or 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED')
|
||||
@@ -431,24 +480,11 @@ def _record_unit_technical_failure(*, run, unit, job, exc: Exception, retryable:
|
||||
},
|
||||
job_id=job.id,
|
||||
)
|
||||
if retryable and int(unit.attempt_count or 0) < MAX_UNIT_TECHNICAL_ATTEMPTS:
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
unit=unit,
|
||||
event_code='technical_retrying',
|
||||
reason_code=error_code,
|
||||
summary={
|
||||
'next_attempt_count': int(unit.attempt_count or 0) + 1,
|
||||
'max_attempt_count': MAX_UNIT_TECHNICAL_ATTEMPTS,
|
||||
},
|
||||
job_id=job.id,
|
||||
)
|
||||
transition_order_extraction_unit(unit, target_status='pending')
|
||||
|
||||
|
||||
def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[dict] | None:
|
||||
"""
|
||||
独立处理一个附件单元;技术失败最多自动重试 2 次,不影响其他单元继续执行。
|
||||
独立处理一个附件单元;技术失败立即停在失败事实,不自动重试。
|
||||
|
||||
核心逻辑:正常从 pending 开始;若进程/事务异常遗留 routing、matching_profile、extracting
|
||||
或 merging_supplement,则先经 failed→pending 恢复稳定检查点,再开启新的确定性尝试。
|
||||
@@ -613,12 +649,10 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
|
||||
return unit_orders
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
retryable = not isinstance(exc, AppError) or bool(getattr(exc, 'retryable', False))
|
||||
retryable = False
|
||||
run, unit = _reload_run_and_unit(run_id=int(run.id), unit_id=int(unit.id))
|
||||
_record_unit_technical_failure(run=run, unit=unit, job=job, exc=exc, retryable=retryable)
|
||||
db.session.commit()
|
||||
if retryable and int(unit.attempt_count or 0) < MAX_UNIT_TECHNICAL_ATTEMPTS:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
@@ -1177,7 +1211,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
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))
|
||||
retryable = False
|
||||
if run is not None and run.status in {'queued', 'processing', 'failed'}:
|
||||
running_unit = ShippingOrderProcessingUnit.query.join(ShippingOrderProcessingPlan).filter(
|
||||
ShippingOrderProcessingPlan.run_id == run.id,
|
||||
@@ -1198,18 +1232,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
reason_code=str(getattr(exc, 'code', None) or 'technical_failure'),
|
||||
job_id=job.id,
|
||||
)
|
||||
if retryable and owned_attempt < int(job.max_attempts or 1):
|
||||
if run.status == 'processing':
|
||||
if running_unit is not None:
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
unit=running_unit,
|
||||
event_code='technical_retrying',
|
||||
reason_code=str(getattr(exc, 'code', None) or 'technical_failure'),
|
||||
job_id=job.id,
|
||||
)
|
||||
transition_order_extraction_run(run, target_status='queued', phase='retry_queued')
|
||||
elif run.status in {'queued', 'processing'}:
|
||||
if run.status in {'queued', 'processing'}:
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='processing', phase='failing')
|
||||
transition_order_extraction_run(
|
||||
@@ -1219,5 +1242,3 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
)
|
||||
db.session.commit()
|
||||
fail_job(job.id, error=str(exc), retryable=retryable, owned_attempt=owned_attempt)
|
||||
if retryable:
|
||||
raise
|
||||
@@ -43,7 +43,7 @@ def run_shipping_pdf_automark(ctx: JobContext, payload: dict) -> None:
|
||||
job.id,
|
||||
error=str(exc)[:500],
|
||||
result={'status': 'failed', 'error_code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_FAILED'},
|
||||
retryable=True,
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
@@ -84,7 +84,7 @@ def handle_shipping_post_ot_wave_progress(ctx: JobContext, payload: dict) -> Non
|
||||
job_id,
|
||||
error=err[:500],
|
||||
result={'status': 'failed', 'wave_no': wave_no, 'generate_excel': gen},
|
||||
retryable=True,
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
@@ -115,7 +115,7 @@ def handle_shipping_post_ot_wave_progress(ctx: JobContext, payload: dict) -> Non
|
||||
job_id,
|
||||
error=str(exc)[:500],
|
||||
result={'status': 'failed', 'wave_no': wave_no},
|
||||
retryable=True,
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
raise
|
||||
@@ -4,13 +4,10 @@ backend/app/jobs/handlers/shipping_review_revalidate_progress.py
|
||||
用途:消费 Review Revalidate Job,在 Case 字段变更后异步刷新校验、
|
||||
重跑 STP 资格判定、推进自动入队协调。
|
||||
依赖:JobContext、order_review_auto_progress_coordinator.reconcile_single_case_for_auto_progress、
|
||||
jobs.queue finish/fail、recovery_contract.is_tech_retryable_error。
|
||||
jobs.queue finish/fail。
|
||||
逻辑:由 shipping worker 领取;按 business_ref(case_no)+ 部分唯一索引保证同 Case 不重复入队;
|
||||
成功 finish 写 result_json(包含 enqueue_status / customer_step_status / validate_status);
|
||||
失败统一走错误分类:
|
||||
- AppError.is_tech_retryable_error 命中 → fail_job(retryable=True)
|
||||
- 其它 AppError 业务阻断 → fail_job(retryable=False)
|
||||
- 非预期 Exception → category_hint=temporary_storage_error,默认 retryable=True
|
||||
失败统一终态化,等待用户再次提交明确动作。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -25,7 +22,6 @@ 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 Job
|
||||
from app.services.shipping_notice.recovery_contract import is_tech_retryable_error
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -47,16 +43,14 @@ def _classify_revalidate_error(
|
||||
category_hint: str | None = None,
|
||||
) -> tuple[bool, dict[str, Any]]:
|
||||
"""
|
||||
将 Revalidate Job 执行失败按 recovery_contract 统一分类,输出 retryable、合并后的 result。
|
||||
将 Revalidate Job 执行失败统一收口为人工阻断。
|
||||
|
||||
【AI 触发时机】:Handler 的两条 fail 路径(AppError 兜底、非预期 Exception 兜底)
|
||||
统一调用,确保 Job.result_json schema 一致。
|
||||
|
||||
核心逻辑(fail-closed):
|
||||
[STEP 1] is_tech_retryable_error(error_code, category_hint) 命中白名单或前缀
|
||||
→ result.status=failed_transient,retryable=True。
|
||||
[STEP 2] 否则 result.status=blocked_manual,retryable=False。
|
||||
[STEP 3] 返回二元组(retryable, normalized_result_dict)。
|
||||
[STEP 1] 记录稳定失败事实 result.status=blocked_manual、retryable=False。
|
||||
[STEP 2] 返回二元组(False, normalized_result_dict)。
|
||||
|
||||
Args:
|
||||
error_code: 业务错误码(SHIPPING.* 或顶层 reason_code)。
|
||||
@@ -66,8 +60,8 @@ def _classify_revalidate_error(
|
||||
Returns:
|
||||
(retryable: bool, normalized_result: dict)。
|
||||
"""
|
||||
tech = is_tech_retryable_error(error_code, category_hint=category_hint)
|
||||
result_status = 'failed_transient' if tech else 'blocked_manual'
|
||||
tech = False
|
||||
result_status = 'blocked_manual'
|
||||
normalized: dict[str, Any] = {
|
||||
'contract_version': 'shipping-recovery-v1-phase1',
|
||||
'status': result_status,
|
||||
@@ -78,7 +72,7 @@ def _classify_revalidate_error(
|
||||
'contract_version': 'shipping-recovery-v1-phase1',
|
||||
'stage': 'revalidate_classify_error',
|
||||
'retryable': bool(tech),
|
||||
'matched_rule': 'tech_retryable_whitelist' if tech else 'business_blocking_default',
|
||||
'matched_rule': 'failure_stops_for_user_action',
|
||||
'category_hint': category_hint,
|
||||
},
|
||||
}
|
||||
@@ -98,8 +92,7 @@ def handle_shipping_review_revalidate_progress(ctx: JobContext, payload: dict) -
|
||||
[STEP 3] 调用 reconcile_single_case_for_auto_progress(case, trigger='review_revalidate_job', refresh_validation=True)。
|
||||
[STEP 4] 按 enqueue_status / customer_step_status / validate_status 分类:
|
||||
- 全部成功 → finish_job,写 result_json。
|
||||
[STEP 5] AppError:is_tech_retryable_error 命中 → fail_job(retryable=True),否则 retryable=False。
|
||||
[STEP 6] 非预期 Exception:category_hint=temporary_storage_error,retryable=True,最终 re-raise 保持 Worker 心跳。
|
||||
[STEP 5] 任意异常:fail_job(retryable=False),不自动重新入队。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文;当前执行体不依赖请求上下文。
|
||||
@@ -297,4 +290,3 @@ def handle_shipping_review_revalidate_progress(ctx: JobContext, payload: dict) -
|
||||
retryable=retryable,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
raise
|
||||
@@ -3,16 +3,14 @@ backend/app/jobs/handlers/shipping_stp_auto_create.py
|
||||
|
||||
用途:消费 STP 自动建单 Job,执行 confirm_review_case 与确认后自动推进入队;
|
||||
按 recovery_contract 统一错误分类,业务阻断(如 NOTICE_EXACT_DUPLICATE)
|
||||
retryable=false + blocked_manual,技术失败白名单 retryable=true。
|
||||
任意失败均收口为 blocked_manual,等待用户选择明确恢复动作。
|
||||
依赖:JobContext、order_stp_auto_create_service.execute_stp_auto_create_job、
|
||||
jobs.queue finish/fail、recovery_contract(is_tech_retryable_error、
|
||||
build_stp_job_blocked_manual_result / build_stp_job_failed_transient_result、
|
||||
jobs.queue finish/fail、recovery_contract(build_stp_job_blocked_manual_result、
|
||||
derive_blocking_next_actions)、fulfillment_audit.emit_stp_auto_create_blocked_manual_audit。
|
||||
逻辑:由 shipping worker 领取;幂等键保证同一 Case/draft 不重复建单;
|
||||
成功 finish,附加 task_no / idempotent_replay;
|
||||
失败统一走 _classify_stp_result:
|
||||
- 技术白名单 → retryable=true(failed_transient)
|
||||
- 业务阻断 → retryable=false(blocked_manual + 注入 next_action + 写阻断审计)
|
||||
- 所有失败 → retryable=false(blocked_manual + 注入 next_action + 写阻断审计)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -34,9 +32,7 @@ from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
)
|
||||
from app.services.shipping_notice.recovery_contract import (
|
||||
build_stp_job_blocked_manual_result,
|
||||
build_stp_job_failed_transient_result,
|
||||
derive_blocking_next_actions,
|
||||
is_tech_retryable_error,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -56,12 +52,10 @@ def _classify_stp_job_result(
|
||||
非预期 Exception 兜底)统一调用,确保 Job.result_json schema 一致。
|
||||
|
||||
核心逻辑(fail-closed):
|
||||
[STEP 1] is_tech_retryable_error(error_code, category_hint) 命中白名单或前缀
|
||||
→ build_stp_job_failed_transient_result,retryable=True。
|
||||
[STEP 2] 否则 build_stp_job_blocked_manual_result:
|
||||
[STEP 1] build_stp_job_blocked_manual_result:
|
||||
derive_blocking_next_actions 取第一个动作作 next_action,默认 open_order_review;
|
||||
details 合并至 blocking_reason_details。
|
||||
[STEP 3] 返回三元组(retryable, normalized_result_dict, next_action)。
|
||||
[STEP 2] 返回三元组(False, normalized_result_dict, next_action)。
|
||||
|
||||
Args:
|
||||
error_code: 业务错误码(SHIPPING.* 或顶层 reason_code)。
|
||||
@@ -73,23 +67,10 @@ def _classify_stp_job_result(
|
||||
Returns:
|
||||
(retryable: bool, normalized_result: dict, next_action: str | None)。
|
||||
"""
|
||||
tech = is_tech_retryable_error(error_code, category_hint=category_hint)
|
||||
if tech:
|
||||
public_message = message
|
||||
if str(error_code or '').strip() == 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED':
|
||||
public_message = '自动建单失败,系统将自动重试'
|
||||
transient: dict[str, Any] = build_stp_job_failed_transient_result(
|
||||
error_code=error_code,
|
||||
message=public_message,
|
||||
category_hint=category_hint,
|
||||
)
|
||||
if details:
|
||||
transient['blocking_reason_details'] = {
|
||||
**dict(transient.get('blocking_reason_details') or {}),
|
||||
**dict(details),
|
||||
}
|
||||
return True, transient, transient.get('next_action')
|
||||
|
||||
# 非预期基础设施异常的原始文本可能包含驱动/SQL 细节;用户只需要知道
|
||||
# 当前执行已停止并应在当前 Gate 选择动作,原文仅保留在 Worker 日志。
|
||||
if str(error_code or '').strip() == 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED':
|
||||
message = '自动建单失败,已停止,等待用户选择下一步动作'
|
||||
actions = derive_blocking_next_actions(blocking_reason=error_code)
|
||||
next_action = actions[0] if actions else 'open_order_review'
|
||||
blocked: dict[str, Any] = build_stp_job_blocked_manual_result(
|
||||
@@ -295,7 +276,7 @@ def handle_shipping_stp_auto_create(ctx: JobContext, payload: dict) -> None:
|
||||
# 对外消息必须稳定且可读;原始异常只进入日志/诊断 details,禁止把 SQL/驱动文本写入用户态 Job。
|
||||
retryable, normalized, next_action = _classify_stp_job_result(
|
||||
error_code=raw_code,
|
||||
message='自动建单失败,系统将自动重试',
|
||||
message='自动建单失败,已停止,等待用户选择下一步动作',
|
||||
details=details,
|
||||
category_hint=category_hint,
|
||||
)
|
||||
@@ -309,7 +290,7 @@ def handle_shipping_stp_auto_create(ctx: JobContext, payload: dict) -> None:
|
||||
)
|
||||
fail_job(
|
||||
job_id,
|
||||
error=str(normalized.get('message') or '自动建单失败,系统将自动重试')[:2000],
|
||||
error=str(normalized.get('message') or '自动建单失败,已停止,等待用户选择下一步动作')[:2000],
|
||||
result=normalized,
|
||||
retryable=retryable,
|
||||
owned_attempt=owned_attempt,
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_xfa_ocr_automark.py
|
||||
|
||||
用途:异步执行 XFA OCR 自动标记(原生 PDF/PDFium 页图),产出 suggested visual_bindings(不自动 confirmed)。
|
||||
依赖:Job queue、order_document_profile_xfa_automark_service(执行体)、JobType。
|
||||
逻辑:由 shipping worker 领取;payload 含 profile_id/document_id/preview_render_checksum;
|
||||
不再依赖 /xfa/preview synthetic;空白壳返回空建议成功;OCR 不可用时 fail_job。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.extensions import db
|
||||
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 Job
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_XFA_OCR_AUTOMARK)
|
||||
def run_shipping_xfa_ocr_automark(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行 XFA OCR 自动标记 Job。
|
||||
|
||||
核心逻辑:读取冻结 Job 载荷 → 委托 automark_service.execute_xfa_ocr_automark_job →
|
||||
finish/fail。OCR 引擎不可用时不可重试(明确业务码)。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文(堆栈仅运维可见)。
|
||||
payload: 须含 job_id;业务字段在 Job.payload_json。
|
||||
|
||||
Returns:
|
||||
None。
|
||||
"""
|
||||
_ = ctx
|
||||
raw_job_id = payload.get('job_id')
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
if job is None:
|
||||
return
|
||||
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
frozen = dict(job.payload_json or {})
|
||||
frozen.setdefault('job_id', int(job.id))
|
||||
|
||||
from app.services.shipping_notice import order_document_profile_xfa_automark_service as automark_service
|
||||
|
||||
try:
|
||||
result = automark_service.execute_xfa_ocr_automark_job(frozen)
|
||||
except automark_service.XfaOcrAutomarkError as exc:
|
||||
fail_job(
|
||||
job.id,
|
||||
error=str(exc.message or exc)[:500],
|
||||
result={
|
||||
'status': 'failed',
|
||||
'error_code': exc.error_code,
|
||||
'preview_render_checksum': frozen.get('preview_render_checksum'),
|
||||
'details': dict(exc.details or {}),
|
||||
},
|
||||
retryable=bool(exc.retryable),
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001 — 未知异常走可重试失败
|
||||
fail_job(
|
||||
job.id,
|
||||
error=str(exc)[:500],
|
||||
result={
|
||||
'status': 'failed',
|
||||
'error_code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_AUTOMARK_FAILED',
|
||||
'preview_render_checksum': frozen.get('preview_render_checksum'),
|
||||
},
|
||||
retryable=True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
finish_job(
|
||||
job.id,
|
||||
result=result,
|
||||
message='XFA OCR automark completed',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
@@ -582,7 +582,7 @@ def recover_stale_jobs(
|
||||
sibling: Job | None = None
|
||||
rowcount = 0
|
||||
|
||||
if snap_attempts < max_attempts:
|
||||
if str(domain or '') != 'shipping_notice' and snap_attempts < max_attempts:
|
||||
if _subject_to_parse_queued_unique(str(job.job_type or "")):
|
||||
try:
|
||||
sibling = _resolve_safe_supersede_sibling(
|
||||
@@ -616,7 +616,7 @@ def recover_stale_jobs(
|
||||
)
|
||||
.values(
|
||||
status="queued",
|
||||
message="任务执行超时,已回收等待重试",
|
||||
message="任务执行超时,已停止,等待用户选择下一步动作",
|
||||
locked_by=None,
|
||||
locked_at=None,
|
||||
started_at=None,
|
||||
@@ -1054,5 +1054,12 @@ def process_next_job(
|
||||
return True, job_type_value
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
fail_job(job_id, error=str(exc), retryable=True, owned_attempt=owned_attempt)
|
||||
# 发货通知失败必须停在当前 Gate,不能由通用 runner 隐式重新入队。
|
||||
# 其它领域维持既有技术重试策略。
|
||||
fail_job(
|
||||
job_id,
|
||||
error=str(exc),
|
||||
retryable=(str(domain or '').strip() != 'shipping_notice'),
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
raise
|
||||
@@ -146,10 +146,12 @@ def mark_failed(job_id: int, *, message: str, owned_attempt: int | None = None)
|
||||
# 通用 Job 表命中则条件收口(rowcount=0 即代次/状态已变,安全 no-op)
|
||||
generic = db.session.query(Job.id).filter(Job.id == int(job_id)).first()
|
||||
if generic is not None:
|
||||
generic_job = db.session.get(Job, int(job_id))
|
||||
fail_job(
|
||||
int(job_id),
|
||||
error=message[:1000],
|
||||
retryable=True,
|
||||
# 发货通知失败即停止;Runner 的兜底异常也不得绕过业务 Gate 自动重新入队。
|
||||
retryable=False if str(getattr(generic_job, 'domain', '') or '') == 'shipping_notice' else True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
@@ -26,8 +26,6 @@ class JobType(StrEnum):
|
||||
SHIPPING_AUTO_PROGRESS = 'shipping_auto_progress'
|
||||
# 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。
|
||||
SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark'
|
||||
# 旧 XFA 专用 Job 仅兼容已入队任务;新入口一律使用 SHIPPING_PDF_AUTOMARK。
|
||||
SHIPPING_XFA_OCR_AUTOMARK = 'shipping_xfa_ocr_automark'
|
||||
# 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm)
|
||||
SHIPPING_STP_AUTO_CREATE = 'shipping_stp_auto_create'
|
||||
# OT 后行级自动履约协调(flag 关闭时不入队)
|
||||
@@ -72,7 +70,7 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'kb': frozenset({'clean', 'path_upload', 'sync_dify'}),
|
||||
'shipping': frozenset({
|
||||
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
|
||||
'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark', 'shipping_xfa_ocr_automark',
|
||||
'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark',
|
||||
'shipping_inventory_callback_process',
|
||||
'shipping_auto_progress',
|
||||
'shipping_stp_auto_create', 'shipping_line_auto_fulfill',
|
||||
|
||||
@@ -78,6 +78,7 @@ from app.models.shipping_order_snapshot import (
|
||||
)
|
||||
from app.models.shipping_order_review import (
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewStream,
|
||||
ShippingOrderReviewDraft,
|
||||
ShippingOrderReviewCaseEvent,
|
||||
ShippingOrderReviewConfirmedRevision,
|
||||
@@ -124,6 +125,7 @@ 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_eml_preview_snapshot import ShippingEmlPreviewSnapshot
|
||||
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 (
|
||||
@@ -140,6 +142,12 @@ from app.models.shipping_inventory_config import (
|
||||
ShippingInventoryStructureAnalysis,
|
||||
ShippingRpaProfile,
|
||||
)
|
||||
from app.models.shipping_receipt_report import (
|
||||
ShippingReceiptNotificationDelivery,
|
||||
ShippingReceiptReportConfig,
|
||||
ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun,
|
||||
)
|
||||
from app.models.shipping_temporary_inventory import ShippingTemporaryInventorySession
|
||||
from app.models.shipping_customer import (
|
||||
ShippingBusinessSequence,
|
||||
@@ -235,6 +243,7 @@ __all__ = [
|
||||
'ShippingOrderSnapshotLine',
|
||||
'ShippingOrderReviewEvent',
|
||||
'ShippingOrderReviewCase',
|
||||
'ShippingOrderReviewStream',
|
||||
'ShippingOrderReviewDraft',
|
||||
'ShippingOrderReviewCaseEvent',
|
||||
'ShippingOrderReviewConfirmedRevision',
|
||||
@@ -269,6 +278,7 @@ __all__ = [
|
||||
'ShippingOrderCandidateQualification',
|
||||
'ShippingFreightCancellation',
|
||||
'ShippingDocumentLayoutVersion',
|
||||
'ShippingEmlPreviewSnapshot',
|
||||
'ShippingXfaStructureAnalysis',
|
||||
'ShippingXfaAuditSnapshot',
|
||||
'ShippingCustomer',
|
||||
@@ -294,6 +304,10 @@ __all__ = [
|
||||
'ShippingTaskInventoryLink',
|
||||
'ShippingRpaProfile',
|
||||
'ShippingInventorySource',
|
||||
'ShippingReceiptReportConfig',
|
||||
'ShippingReceiptRpaUnitRun',
|
||||
'ShippingReceiptReportFile',
|
||||
'ShippingReceiptNotificationDelivery',
|
||||
'ShippingInventoryField',
|
||||
'ShippingInventoryStructureAnalysis',
|
||||
'ShippingInventoryRoutingRule',
|
||||
|
||||
@@ -86,6 +86,7 @@ class ShippingDocumentProfileTestRun(Base):
|
||||
sample_count: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
passed_sample_count: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
failure_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
|
||||
evidence_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
executed_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
models/shipping_eml_preview_snapshot.py
|
||||
|
||||
用途:持久化 EML 正文的安全 HTML 预览快照。
|
||||
依赖:ShippingOrderDocument、SQLAlchemy Base。
|
||||
逻辑:原始 EML 保持在私有 FileAsset;本表仅缓存已清洗、无图片和无主动内容的预览 HTML。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingEmlPreviewSnapshot(Base):
|
||||
"""按正文 Document、源哈希和清洗器版本复用的安全 EML 预览。"""
|
||||
|
||||
__tablename__ = 'shipping_eml_preview_snapshots'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'document_id', 'source_content_hash', 'sanitizer_version',
|
||||
name='uq_shipping_eml_preview_snapshot_identity',
|
||||
),
|
||||
Index('ix_shipping_eml_preview_snapshot_document', 'document_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
document_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_documents.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
source_content_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
sanitizer_version: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
html: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
html_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
html_size_bytes: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
@@ -122,6 +122,9 @@ class ShippingInventorySource(Base):
|
||||
external_mappings: Mapped[list['ShippingInventoryExternalMapping']] = relationship(
|
||||
back_populates='inventory_source', cascade='all, delete-orphan'
|
||||
)
|
||||
receipt_report_config: Mapped[Optional['ShippingReceiptReportConfig']] = relationship(
|
||||
back_populates='inventory_source', uselist=False, cascade='all, delete-orphan',
|
||||
)
|
||||
|
||||
|
||||
class ShippingInventorySourceParsingBindingAudit(Base):
|
||||
|
||||
@@ -215,10 +215,12 @@ class ShippingOrderProcessingRunIntake(Base):
|
||||
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'),
|
||||
# 同一 EML Intake 可由批次重解析拆成多个、各自冻结一个 PDF 的子 Run。
|
||||
# 并发互斥改由创建服务在锁定 Intake 后按目标 Document 裁决;不能再用
|
||||
# Intake 单列唯一索引,否则第二份 PDF 会被错误拒绝。
|
||||
Index(
|
||||
'uq_shipping_order_processing_run_intakes_active_intake',
|
||||
'ix_shipping_order_processing_run_intakes_active_intake',
|
||||
'intake_id',
|
||||
unique=True,
|
||||
postgresql_where=text('released_at IS NULL'),
|
||||
sqlite_where=text('released_at IS NULL'),
|
||||
),
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
依赖:订单抽取 Run/Unit、候选 Candidate、用户和后续 ShippingNotice、
|
||||
ShippingOrderReviewLineDecision(行级履约决定)、
|
||||
ShippingOrderReviewWaveLine(波次行不可变归属)。
|
||||
逻辑:Case 以 PDF Unit 为唯一复核对象,Draft 保存独立人工版本;机器 Candidate
|
||||
始终只读,后续确认服务将以 Case/Draft 生成不可变确认版本和 Task;
|
||||
逻辑:ReviewStream 是文件级复核主线,Case 是该主线的一次不可变复核版本;
|
||||
Draft 保存独立人工版本,机器 Candidate 始终只读,后续确认服务将以 Case/Draft 生成不可变确认版本和 Task;
|
||||
行级决定支持完整明细先行履约波次,禁止拆分数量;
|
||||
wave_lines 保证同一 (case, line_key) 最多关联一个 task_id。
|
||||
"""
|
||||
@@ -21,6 +21,51 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingOrderReviewStream(Base):
|
||||
"""一个原始订单文件的复核主线;唯一保存当前可操作 Case 的裁决事实。"""
|
||||
|
||||
__tablename__ = 'shipping_order_review_streams'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('document_id', name='uq_shipping_order_review_streams_document'),
|
||||
UniqueConstraint('current_case_id', name='uq_shipping_order_review_streams_current_case'),
|
||||
UniqueConstraint('confirmed_case_id', name='uq_shipping_order_review_streams_confirmed_case'),
|
||||
CheckConstraint(
|
||||
"state IN ('active', 'reparsing', 'confirmed', 'closed', 'conflict')",
|
||||
name='ck_shipping_order_review_streams_state',
|
||||
),
|
||||
Index('ix_shipping_order_review_streams_owner_state_updated', 'owner_user_id', 'state', 'updated_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_documents.id'), nullable=False)
|
||||
content_identity: Mapped[str] = mapped_column(String(96), nullable=False)
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
|
||||
current_case_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_review_cases.id', use_alter=True, name='fk_shipping_order_review_streams_current_case'),
|
||||
nullable=True,
|
||||
)
|
||||
confirmed_case_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_review_cases.id', use_alter=True, name='fk_shipping_order_review_streams_confirmed_case'),
|
||||
nullable=True,
|
||||
)
|
||||
state: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
|
||||
revision: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
|
||||
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
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)
|
||||
|
||||
current_case: Mapped[Optional['ShippingOrderReviewCase']] = relationship(
|
||||
'ShippingOrderReviewCase', foreign_keys=[current_case_id], post_update=True,
|
||||
)
|
||||
confirmed_case: Mapped[Optional['ShippingOrderReviewCase']] = relationship(
|
||||
'ShippingOrderReviewCase', foreign_keys=[confirmed_case_id], post_update=True,
|
||||
)
|
||||
cases: Mapped[list['ShippingOrderReviewCase']] = relationship(
|
||||
'ShippingOrderReviewCase', back_populates='stream', foreign_keys='ShippingOrderReviewCase.stream_id',
|
||||
order_by='ShippingOrderReviewCase.revision_no',
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderReviewCase(Base):
|
||||
"""一份 PDF 的建单前复核生命周期;终态 Case 不允许后续草稿写入。"""
|
||||
|
||||
@@ -36,6 +81,9 @@ class ShippingOrderReviewCase(Base):
|
||||
),
|
||||
Index('ix_shipping_order_review_cases_run_status', 'run_id', 'status'),
|
||||
Index('ix_shipping_order_review_cases_owner_updated', 'owner_user_id', 'updated_at'),
|
||||
UniqueConstraint('stream_id', 'revision_no', name='uq_shipping_order_review_cases_stream_revision'),
|
||||
Index('ix_shipping_order_review_cases_stream_revision', 'stream_id', 'revision_no'),
|
||||
Index('ix_shipping_order_review_cases_supersedes', 'supersedes_case_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -47,6 +95,12 @@ class ShippingOrderReviewCase(Base):
|
||||
ForeignKey('shipping_order_processing_units.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_documents.id'), nullable=False)
|
||||
stream_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_review_streams.id'), nullable=True)
|
||||
revision_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
supersedes_case_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_review_cases.id'), nullable=True)
|
||||
superseded_by_case_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_review_cases.id'), nullable=True)
|
||||
became_current_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
retired_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
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')
|
||||
@@ -61,6 +115,15 @@ class ShippingOrderReviewCase(Base):
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
run: Mapped['ShippingOrderProcessingRun'] = relationship('ShippingOrderProcessingRun', back_populates='review_cases')
|
||||
stream: Mapped[Optional['ShippingOrderReviewStream']] = relationship(
|
||||
'ShippingOrderReviewStream', back_populates='cases', foreign_keys=[stream_id],
|
||||
)
|
||||
supersedes_case: Mapped[Optional['ShippingOrderReviewCase']] = relationship(
|
||||
'ShippingOrderReviewCase', foreign_keys=[supersedes_case_id], remote_side='ShippingOrderReviewCase.id',
|
||||
)
|
||||
superseded_by_case: Mapped[Optional['ShippingOrderReviewCase']] = relationship(
|
||||
'ShippingOrderReviewCase', foreign_keys=[superseded_by_case_id], remote_side='ShippingOrderReviewCase.id',
|
||||
)
|
||||
unit: Mapped['ShippingOrderProcessingUnit'] = relationship('ShippingOrderProcessingUnit', back_populates='review_case')
|
||||
current_draft: Mapped[Optional['ShippingOrderReviewDraft']] = relationship(
|
||||
'ShippingOrderReviewDraft', foreign_keys=[current_draft_id], post_update=True,
|
||||
|
||||
@@ -33,14 +33,14 @@ class ShippingOrderReviewLineDecision(Base):
|
||||
CheckConstraint(
|
||||
"decision_code IN ("
|
||||
"'wait_inventory', 'use_new_inventory_file', 'change_inventory_source', "
|
||||
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen'"
|
||||
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_inventory_shortage'"
|
||||
")",
|
||||
name='ck_shipping_review_line_decisions_code',
|
||||
),
|
||||
CheckConstraint(
|
||||
"line_status IN ("
|
||||
"'pending_decision', 'waiting_inventory', 'ready_to_fulfill', "
|
||||
"'task_created', 'fulfilled', 'closed_unfulfillable', 'reopened'"
|
||||
"'task_created', 'fulfilled', 'closed_unfulfillable', 'reopened', 'released_shortage'"
|
||||
")",
|
||||
name='ck_shipping_review_line_decisions_status',
|
||||
),
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
"""
|
||||
收料报表 RPA 的配置、运行、归档与通知投递持久化模型。
|
||||
|
||||
用途:为独立收料排程保存站点级配置、每站点/仓库执行单元、原样归档文件及企微投递事实。
|
||||
依赖:库存站点、排程运行、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。
|
||||
逻辑:模型只复用库存站点的连接资料,通过独立外键与唯一约束隔离库存快照、匹配和旧 RPA Worker 链路。
|
||||
"""
|
||||
|
||||
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, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingReceiptReportConfig(Base):
|
||||
"""库存站点的一对一收料报表配置;路径和条件始终独立于库存配置。"""
|
||||
|
||||
__tablename__ = 'shipping_receipt_report_configs'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('inventory_source_id', name='uq_shipping_receipt_report_configs_source'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
inventory_source_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True,
|
||||
)
|
||||
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
|
||||
report_path_json: Mapped[dict[str, Any]] = mapped_column(
|
||||
JSON, default=dict, server_default=text("'{}'"), nullable=False,
|
||||
)
|
||||
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
||||
JSON, default=list, server_default=text("'[]'"), nullable=False,
|
||||
)
|
||||
# DBS 可包含多个 Warehouse;Crane 固定 Inbound Details,保留空数组。
|
||||
warehouse_ids_json: Mapped[list[str]] = mapped_column(
|
||||
JSON, default=list, server_default=text("'[]'"), nullable=False,
|
||||
)
|
||||
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.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)
|
||||
|
||||
inventory_source: Mapped['ShippingInventorySource'] = relationship(back_populates='receipt_report_config')
|
||||
|
||||
|
||||
class ShippingReceiptRpaUnitRun(Base):
|
||||
"""一次收料排程内的站点或站点-Warehouse 不可重复执行单元。"""
|
||||
|
||||
__tablename__ = 'shipping_receipt_rpa_unit_runs'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('callback_id', name='uq_shipping_receipt_rpa_unit_runs_callback'),
|
||||
CheckConstraint(
|
||||
"status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')",
|
||||
name='ck_shipping_receipt_rpa_unit_runs_status',
|
||||
),
|
||||
Index('ix_shipping_receipt_unit_run_schedule_status', 'schedule_run_id', 'status'),
|
||||
Index('ix_shipping_receipt_unit_run_source_created', 'inventory_source_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schedule_run_id: Mapped[int] = mapped_column(ForeignKey('schedule_runs.id'), nullable=False, index=True)
|
||||
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
|
||||
retry_of_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
callback_id: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||
config_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
trigger_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
schedule_run: Mapped['ScheduleRun'] = relationship(foreign_keys=[schedule_run_id])
|
||||
inventory_source: Mapped['ShippingInventorySource'] = relationship()
|
||||
retry_of: Mapped[Optional['ShippingReceiptRpaUnitRun']] = relationship(remote_side=[id])
|
||||
files: Mapped[list['ShippingReceiptReportFile']] = relationship(
|
||||
back_populates='unit_run', cascade='all, delete-orphan',
|
||||
)
|
||||
|
||||
|
||||
class ShippingReceiptReportFile(Base):
|
||||
"""收料原样归档文件;保留文件身份和对象清理事实,不关联库存快照。"""
|
||||
|
||||
__tablename__ = 'shipping_receipt_report_files'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('unit_run_id', 'sha256', name='uq_shipping_receipt_report_files_unit_sha256'),
|
||||
CheckConstraint("file_size >= 0", name='ck_shipping_receipt_report_files_size'),
|
||||
Index('ix_shipping_receipt_report_files_unit', 'unit_run_id'),
|
||||
Index('ix_shipping_receipt_report_files_expires', 'archive_expires_at', 'archive_deleted_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
unit_run_id: Mapped[int] = mapped_column(ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=False, index=True)
|
||||
storage_provider: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
storage_key: Mapped[str] = mapped_column(String(1024), nullable=False)
|
||||
original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
content_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
archive_delete_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
unit_run: Mapped[ShippingReceiptRpaUnitRun] = relationship(back_populates='files')
|
||||
deliveries: Mapped[list['ShippingReceiptNotificationDelivery']] = relationship(
|
||||
back_populates='report_file', cascade='all, delete-orphan',
|
||||
)
|
||||
|
||||
|
||||
class ShippingReceiptNotificationDelivery(Base):
|
||||
"""收料文件或汇总企微消息的幂等投递事实,响应仅保存脱敏摘要。"""
|
||||
|
||||
__tablename__ = 'shipping_receipt_notification_deliveries'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('idempotency_key', name='uq_shipping_receipt_notification_deliveries_idempotency'),
|
||||
CheckConstraint("message_type IN ('file', 'summary')", name='ck_shipping_receipt_notification_deliveries_type'),
|
||||
CheckConstraint(
|
||||
"status IN ('pending', 'sending', 'success', 'failed')",
|
||||
name='ck_shipping_receipt_notification_deliveries_status',
|
||||
),
|
||||
Index('ix_shipping_receipt_delivery_file_recipient', 'report_file_id', 'recipient_user_id'),
|
||||
Index('ix_shipping_receipt_delivery_unit_created', 'unit_run_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
unit_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
report_file_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_receipt_report_files.id'), nullable=True, index=True,
|
||||
)
|
||||
recipient_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
|
||||
message_type: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
idempotency_key: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='pending', server_default='pending')
|
||||
response_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
sent_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)
|
||||
|
||||
unit_run: Mapped[Optional[ShippingReceiptRpaUnitRun]] = relationship(foreign_keys=[unit_run_id])
|
||||
report_file: Mapped[Optional[ShippingReceiptReportFile]] = relationship(back_populates='deliveries')
|
||||
@@ -21,7 +21,9 @@ from app.models import (
|
||||
ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventorySourceParsingBindingAudit,
|
||||
ShippingReceiptReportConfig,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.credential_crypto import encrypt_credential
|
||||
from app.services.shipping_notice.inventory_source_repository import validate_source_profile
|
||||
from app.services.shipping_notice.routing_operators import ALLOWED_OPERATORS
|
||||
@@ -245,6 +247,94 @@ def _source_payload(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _receipt_report_config_payload(config: ShippingReceiptReportConfig) -> dict[str, Any]:
|
||||
"""序列化独立收料配置,禁止把库存路径或凭据透传至管理端。"""
|
||||
return {
|
||||
'id': config.id, 'inventory_source_id': config.inventory_source_id, 'enabled': bool(config.enabled),
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': config.query_parameters_json or [],
|
||||
'warehouse_ids_json': config.warehouse_ids_json or [], 'config_version': config.config_version,
|
||||
'created_at': _iso(config.created_at), 'updated_at': _iso(config.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _validate_receipt_report_config(
|
||||
source: ShippingInventorySource, data: dict[str, Any],
|
||||
) -> tuple[bool, dict[str, str], list[dict[str, Any]], list[str]]:
|
||||
"""规范收料配置,确保日期保持空值、DBS/Crane 路径与仓库拆分规则不混用。"""
|
||||
enabled = _bool(data, 'enabled', True)
|
||||
try:
|
||||
parameters = _validate_query_parameters(data)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc
|
||||
# 报表日期不筛选,避免管理端误传日期使跨日排程导出产生漏数。
|
||||
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
|
||||
raise ValidationError('Receipt report date filtering is not supported', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
raw_warehouses = _json_string_list(data, 'warehouse_ids_json')
|
||||
raw_path = _json_object(data, 'report_path_json')
|
||||
if source.connector_type == 'dbs':
|
||||
try:
|
||||
path = _validate_report_path('dbs', raw_path)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc
|
||||
if enabled and not raw_warehouses:
|
||||
raise ValidationError('DBS receipt report requires warehouse_ids_json', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
return enabled, path, parameters, raw_warehouses
|
||||
if source.connector_type == 'crane':
|
||||
if raw_warehouses:
|
||||
raise ValidationError('Crane receipt report does not support Warehouse split', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'):
|
||||
raise ValidationError('Crane receipt report is fixed to Inbound Details', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
if parameters:
|
||||
raise ValidationError(
|
||||
'Crane receipt report does not support query parameters',
|
||||
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
|
||||
)
|
||||
return enabled, {'report_name': 'Inbound Details'}, [], []
|
||||
raise ValidationError('Unsupported receipt connector type', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
|
||||
|
||||
def get_receipt_report_config(source_id: int) -> dict[str, Any] | None:
|
||||
"""读取站点的收料配置;不存在时返回空,供抽屉初始化而非创建库存配置。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).one_or_none()
|
||||
return _receipt_report_config_payload(config) if config else None
|
||||
|
||||
|
||||
def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""保存站点内独立收料配置并追加配置前后快照审计,不写入库存 Source 字段。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
enabled, path, parameters, warehouses = _validate_receipt_report_config(source, data)
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).one_or_none()
|
||||
before = _receipt_report_config_payload(config) if config else None
|
||||
is_new = config is None
|
||||
if config is None:
|
||||
config = ShippingReceiptReportConfig(inventory_source_id=source.id)
|
||||
config.created_by = actor_id
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.config_version += 1
|
||||
config.enabled = enabled
|
||||
config.report_path_json = path
|
||||
config.query_parameters_json = parameters
|
||||
config.warehouse_ids_json = warehouses
|
||||
config.updated_by = actor_id
|
||||
db.session.flush()
|
||||
after = _receipt_report_config_payload(config)
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_report_config_saved', aggregate_type='shipping_receipt_report_config',
|
||||
aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update',
|
||||
result='success', before=before, after=after,
|
||||
metadata={'inventory_source_id': source.id, 'connector_type': source.connector_type},
|
||||
)
|
||||
db.session.commit()
|
||||
return after
|
||||
|
||||
|
||||
def _binding_snapshot(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
"""冻结解析绑定变更的最小站点上下文,避免审计依赖后续可变主数据。"""
|
||||
return {
|
||||
|
||||
@@ -23,7 +23,7 @@ class TurnInput:
|
||||
Args:
|
||||
type: 输入类型;第一阶段仅开放 action / form_submit。
|
||||
display_text: 写入 ChatLog.query 与前端 user 气泡的可见文案。
|
||||
action_type: action / form_submit 时的全局唯一动作标识,如 shipping.submit_decision。
|
||||
action_type: action / form_submit 时的全局唯一动作标识,如 shipping.create_order_extraction。
|
||||
text: type=text 时的原始问题。
|
||||
payload: 业务动作参数,由各领域 handler 自行解析。
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
"""独立收料 RPA 排程等待态收口辅助。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule import normalize_platform_api_path
|
||||
from app.services.schedule.freight_receipt_rpa_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, RECEIPT_RPA_JOB_KEY
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def should_defer_receipt_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool:
|
||||
"""仅当独立收料 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。"""
|
||||
return bool(
|
||||
task.schedule_type == 'platform_job'
|
||||
and normalize_platform_api_path(task.platform_api_path) == RECEIPT_RPA_JOB_KEY
|
||||
and any(isinstance(row, dict) and row.get('status') == AWAITING_RECEIPT_RPA_CALLBACK_STATUS for row in step_logs or [])
|
||||
)
|
||||
|
||||
|
||||
def is_awaiting_receipt_rpa_schedule_run(run: ScheduleRun | None) -> bool:
|
||||
"""判断 run 是否为独立收料 callback 等待态,供 worker 启动恢复时保护。"""
|
||||
summary = run.response_summary_json if run is not None and isinstance(run.response_summary_json, dict) else {}
|
||||
return bool(run is not None and run.status == 'running' and summary.get('awaiting_receipt_rpa'))
|
||||
|
||||
|
||||
def apply_deferred_receipt_schedule_run_state(
|
||||
run: ScheduleRun, task: ScheduleTask, *, total_count: int, details: list[dict], errors: list[str], step_logs: list[dict],
|
||||
) -> ScheduleRun:
|
||||
"""将收料 run 保持为 awaiting callback,终态由所有收料单元回调完成后专用服务写入。"""
|
||||
run.status = 'running'
|
||||
run.started_at = run.started_at or datetime.utcnow()
|
||||
run.total_count = total_count
|
||||
run.success_count = 0
|
||||
run.failed_count = 0
|
||||
run.skipped_count = 0
|
||||
run.finished_at = None
|
||||
run.step_logs = step_logs
|
||||
run.response_summary_json = {'awaiting_receipt_rpa': True, 'pending_details': details, 'errors': errors[:20]}
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
|
||||
def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
|
||||
"""当收料 run 的全部单元已回调后写入独立排程终态,不读取库存回调结果。"""
|
||||
run = db.session.get(ScheduleRun, schedule_run_id)
|
||||
if run is None:
|
||||
return {'finalized': False, 'reason': 'schedule_run_not_found'}
|
||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||
if not summary.get('awaiting_receipt_rpa'):
|
||||
return {'finalized': False, 'reason': 'not_awaiting_receipt_callback'}
|
||||
units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all()
|
||||
terminal = {'success', 'empty', 'failed', 'cancelled'}
|
||||
if any(unit.status not in terminal for unit in units):
|
||||
return {'finalized': False, 'reason': 'units_pending'}
|
||||
success_count = sum(unit.status == 'success' for unit in units)
|
||||
skipped_count = sum(unit.status == 'empty' for unit in units)
|
||||
failed_count = sum(unit.status in {'failed', 'cancelled'} for unit in units)
|
||||
run.total_count = len(units)
|
||||
run.success_count = success_count
|
||||
run.skipped_count = skipped_count
|
||||
run.failed_count = failed_count
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000) if run.started_at else 0
|
||||
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
|
||||
run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None
|
||||
run.response_summary_json = {**summary, 'awaiting_receipt_rpa': False, 'success_count': success_count, 'empty_count': skipped_count, 'failed_count': failed_count}
|
||||
db.session.commit()
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_schedule_receipt_summary
|
||||
deliver_schedule_receipt_summary(run.id)
|
||||
return {'finalized': True, 'status': run.status}
|
||||
|
||||
|
||||
def _receipt_timeout_seconds() -> int:
|
||||
"""读取收料回调等待上限;超时只标记失败,不会自动重试或重发。"""
|
||||
try:
|
||||
return max(60, int(current_app.config.get('SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
|
||||
except (TypeError, ValueError):
|
||||
return 900
|
||||
|
||||
|
||||
def is_freight_receipt_rpa_task(task: ScheduleTask | None) -> bool:
|
||||
"""识别独立收料 RPA 排程,避免超时回收影响库存或其他平台任务。"""
|
||||
return bool(
|
||||
task
|
||||
and task.schedule_type == 'platform_job'
|
||||
and normalize_platform_api_path(task.platform_api_path) == RECEIPT_RPA_JOB_KEY
|
||||
)
|
||||
|
||||
|
||||
def _recover_stale_receipt_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool:
|
||||
"""将无回调的独立收料运行收口为失败,保留其单元与触发审计事实。"""
|
||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||
if not summary.get('awaiting_receipt_rpa') or run.status != 'running' or not run.started_at or run.started_at > cutoff:
|
||||
return False
|
||||
task = run.task or db.session.get(ScheduleTask, run.schedule_task_id)
|
||||
if not is_freight_receipt_rpa_task(task):
|
||||
return False
|
||||
now = datetime.utcnow()
|
||||
pending = ShippingReceiptRpaUnitRun.query.filter(
|
||||
ShippingReceiptRpaUnitRun.schedule_run_id == run.id,
|
||||
ShippingReceiptRpaUnitRun.status.in_({'queued', 'awaiting_rpa', 'processing'}),
|
||||
).all()
|
||||
for unit in pending:
|
||||
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
|
||||
unit.status = 'failed'
|
||||
unit.error_code = 'RPA.RECEIPT_CALLBACK_TIMEOUT'
|
||||
unit.error_message = f'Receipt RPA callback timed out after {timeout_seconds} seconds'
|
||||
unit.finished_at = now
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_rpa_callback_timeout', aggregate_type='shipping_receipt_unit',
|
||||
aggregate_id=str(unit.id), run_no=run.run_no, actor_type='worker', actor_id='schedule-recovery',
|
||||
unit_id=unit.id, result='failure', before=before,
|
||||
after={'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message},
|
||||
metadata={'timeout_seconds': timeout_seconds},
|
||||
)
|
||||
run.status = 'failed'
|
||||
run.finished_at = now
|
||||
run.duration_ms = int((now - run.started_at).total_seconds() * 1000)
|
||||
run.failed_count = len(pending) or max(1, int(run.failed_count or 0))
|
||||
run.error_message = f'收料 RPA 回调等待超时({timeout_seconds} 秒)'
|
||||
run.step_logs = [*(run.step_logs or []), {
|
||||
'step': 'freight_receipt_rpa', 'status': 'failed',
|
||||
'detail': {'message': run.error_message, 'timeout_seconds': timeout_seconds},
|
||||
}]
|
||||
run.response_summary_json = {**summary, 'awaiting_receipt_rpa': False, 'recovered_reason': 'receipt_rpa_callback_timeout'}
|
||||
return True
|
||||
|
||||
|
||||
def recover_stale_receipt_rpa_schedule_runs(task: ScheduleTask) -> int:
|
||||
"""在同一收料排程开始前回收超时运行,解除后续 Cron/手动执行的互斥。"""
|
||||
if not is_freight_receipt_rpa_task(task):
|
||||
return 0
|
||||
timeout_seconds = _receipt_timeout_seconds()
|
||||
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
|
||||
recovered = sum(
|
||||
_recover_stale_receipt_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
|
||||
for run in ScheduleRun.query.filter_by(schedule_task_id=task.id, status='running').all()
|
||||
)
|
||||
if recovered:
|
||||
db.session.commit()
|
||||
return recovered
|
||||
|
||||
|
||||
def recover_all_stale_receipt_rpa_schedule_runs() -> int:
|
||||
"""Worker 启动时扫描全部超时收料回调,避免重启后运行永久卡住。"""
|
||||
timeout_seconds = _receipt_timeout_seconds()
|
||||
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
|
||||
recovered = sum(
|
||||
_recover_stale_receipt_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
|
||||
for run in ScheduleRun.query.filter_by(status='running').all()
|
||||
)
|
||||
if recovered:
|
||||
db.session.commit()
|
||||
return recovered
|
||||
@@ -0,0 +1,113 @@
|
||||
"""独立收料 RPA 排程:冻结站点配置并按 DBS Warehouse 展开执行单元。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
|
||||
RECEIPT_RPA_JOB_KEY = 'freight-receipt-rpa'
|
||||
AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback'
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
|
||||
|
||||
def _wanted_source_codes(task: ScheduleTask) -> set[str]:
|
||||
"""提取结构化 source_codes;留空代表全部具备有效收料配置的站点。"""
|
||||
params = task.job_params if isinstance(task.job_params, dict) else {}
|
||||
values = params.get('source_codes') or []
|
||||
if isinstance(values, str):
|
||||
values = [values]
|
||||
return {str(value).strip().upper() for value in values if str(value).strip()}
|
||||
|
||||
|
||||
def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource, ShippingReceiptReportConfig]]:
|
||||
"""读取已启用且收料配置已启用的站点,不依赖库存报表路径或解析绑定。"""
|
||||
wanted = _wanted_source_codes(task)
|
||||
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
|
||||
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
|
||||
).filter(ShippingInventorySource.enabled.is_(True), ShippingReceiptReportConfig.enabled.is_(True)).all()
|
||||
return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted]
|
||||
|
||||
|
||||
def _build_unit(source: ShippingInventorySource, config: ShippingReceiptReportConfig, warehouse_id: str | None) -> ShippingReceiptRpaUnitRun:
|
||||
"""冻结可审计的收料执行单元;DBS 日期字段不进入查询快照。"""
|
||||
callback_id = f'receipt:{uuid.uuid4().hex}'
|
||||
snapshot = {
|
||||
'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type,
|
||||
'report_path_json': config.report_path_json or {}, 'query_parameters_json': config.query_parameters_json or [],
|
||||
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
|
||||
}
|
||||
return ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=0, inventory_source_id=source.id, source_code=source.source_code,
|
||||
connector_type=source.connector_type, warehouse_id=warehouse_id, callback_id=callback_id,
|
||||
status='awaiting_rpa', config_snapshot_json=snapshot,
|
||||
)
|
||||
|
||||
|
||||
def _serialize_trigger_unit(unit: ShippingReceiptRpaUnitRun) -> dict[str, Any]:
|
||||
"""生成 Worker 唯一可见的冻结执行载荷;密文凭据只随 receipt trigger 下发。"""
|
||||
source = unit.inventory_source
|
||||
profile = source.rpa_profile if source is not None else None
|
||||
if source is None or profile is None or not profile.enabled:
|
||||
raise RuntimeError(f'receipt source profile unavailable: {unit.source_code}')
|
||||
snapshot = dict(unit.config_snapshot_json or {})
|
||||
return {
|
||||
'unit_run_id': unit.id,
|
||||
'callback_id': unit.callback_id,
|
||||
'source_code': unit.source_code,
|
||||
'connector_type': unit.connector_type,
|
||||
'warehouse_id': unit.warehouse_id,
|
||||
'rpa_profile_id': profile.id,
|
||||
'rpa_profile_code': profile.profile_code,
|
||||
'login_url': profile.login_url,
|
||||
'login_config': dict(profile.login_config_json or {}),
|
||||
'credential_envelope': {
|
||||
'username_ciphertext': profile.username_ciphertext,
|
||||
'password_ciphertext': profile.password_ciphertext,
|
||||
},
|
||||
'report_path_json': dict(snapshot.get('report_path_json') or {}),
|
||||
'query_parameters_json': list(snapshot.get('query_parameters_json') or []),
|
||||
'config_snapshot': snapshot,
|
||||
}
|
||||
|
||||
|
||||
def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""写独立收料 trigger;一个 DBS Warehouse 或一个 Crane 站点对应一个单元。"""
|
||||
units: list[ShippingReceiptRpaUnitRun] = []
|
||||
for source, config in _eligible_sources(task):
|
||||
warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None]
|
||||
for warehouse_id in warehouses:
|
||||
unit = _build_unit(source, config, str(warehouse_id) if warehouse_id else None)
|
||||
unit.schedule_run_id = run.id
|
||||
units.append(unit)
|
||||
if not units:
|
||||
return 0, 0, 0, 1, [], ['no enabled receipt report sources'], [{'step': 'freight_receipt_rpa', 'status': 'skipped'}]
|
||||
db.session.add_all(units)
|
||||
db.session.flush()
|
||||
try:
|
||||
trigger_units = [_serialize_trigger_unit(unit) for unit in units]
|
||||
except RuntimeError as exc:
|
||||
for unit in units:
|
||||
unit.status = 'failed'; unit.error_code = 'RPA.RECEIPT_PROFILE_UNAVAILABLE'; unit.error_message = str(exc)
|
||||
db.session.commit()
|
||||
return len(units), 0, len(units), 0, [], [str(exc)], [{'step': 'freight_receipt_rpa', 'status': 'failed'}]
|
||||
for unit, trigger_unit in zip(units, trigger_units):
|
||||
unit.trigger_snapshot_json = trigger_unit
|
||||
trigger_path = write_receipt_export_batch_trigger(run.run_no, trigger_units, {
|
||||
'schedule_run_id': run.id, 'schedule_task_id': task.id, 'schema_version': 'shipping_receipt_rpa.v1',
|
||||
})
|
||||
if not trigger_path:
|
||||
for unit in units:
|
||||
unit.status = 'failed'; unit.error_code = 'RPA.RECEIPT_TRIGGER_UNAVAILABLE'; unit.error_message = 'receipt trigger directory unavailable'
|
||||
db.session.commit()
|
||||
return len(units), 0, len(units), 0, [], ['receipt trigger directory unavailable'], [{'step': 'freight_receipt_rpa', 'status': 'failed'}]
|
||||
details = [{'source_code': unit.source_code, 'warehouse_id': unit.warehouse_id, 'callback_id': unit.callback_id} for unit in units]
|
||||
run.api_request_json = {'run_no': run.run_no, 'trigger_path': trigger_path, 'source_codes': sorted({unit.source_code for unit in units})}
|
||||
db.session.commit()
|
||||
return len(units), 0, 0, 0, details, [], [{
|
||||
'step': 'freight_receipt_rpa', 'status': AWAITING_RECEIPT_RPA_CALLBACK_STATUS,
|
||||
'detail': {'trigger_path': trigger_path, 'unit_count': len(units)},
|
||||
}]
|
||||
@@ -0,0 +1,49 @@
|
||||
"""收料原样归档三年到期对象清理。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def run_freight_receipt_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
|
||||
"""仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。"""
|
||||
limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000))
|
||||
now = datetime.utcnow()
|
||||
rows = ShippingReceiptReportFile.query.filter(
|
||||
ShippingReceiptReportFile.archive_expires_at.is_not(None),
|
||||
ShippingReceiptReportFile.archive_expires_at <= now,
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
).order_by(ShippingReceiptReportFile.id).limit(limit).all()
|
||||
success = failed = 0
|
||||
errors: list[str] = []
|
||||
for report_file in rows:
|
||||
try:
|
||||
file_asset_storage.delete_object(report_file.storage_key)
|
||||
report_file.archive_deleted_at = now
|
||||
report_file.archive_delete_result_json = {'status': 'deleted', 'deleted_at': now.isoformat()}
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_report_archive_deleted', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
|
||||
unit_id=report_file.unit_run_id, result='success',
|
||||
before={'status': 'archived'}, after={'status': 'archive_deleted'},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
)
|
||||
success += 1
|
||||
except Exception as exc:
|
||||
errors.append(f'{report_file.id}: {exc}')
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_report_archive_delete_attempted', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
|
||||
unit_id=report_file.unit_run_id, result='failed',
|
||||
before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
)
|
||||
failed += 1
|
||||
db.session.commit()
|
||||
return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'receipt_retention', 'status': 'completed'}]
|
||||
@@ -11,6 +11,8 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
def _agent_apps_options() -> list[dict[str, Any]]:
|
||||
"""启用中的 Agent 应用列表(value=agents.id)。"""
|
||||
@@ -49,10 +51,24 @@ def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
|
||||
]
|
||||
|
||||
|
||||
def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
|
||||
"""已启用且已配置收料报表的站点,供独立收料排程选择。"""
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
|
||||
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
|
||||
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
|
||||
).filter(ShippingInventorySource.enabled.is_(True), ShippingReceiptReportConfig.enabled.is_(True)).all()
|
||||
return [{
|
||||
'label': source.display_name or source.source_code, 'value': source.source_code,
|
||||
'description': f'{source.connector_type} · 收料已配置',
|
||||
} for source, _config in rows]
|
||||
|
||||
|
||||
# options_source 注册表:新增来源只需在此登记 provider,不动 API 层
|
||||
_OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
|
||||
"agent_apps": _agent_apps_options,
|
||||
"shipping_inventory_sources": _shipping_inventory_sources_options,
|
||||
"shipping_receipt_sources": _shipping_receipt_sources_options,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -133,6 +133,8 @@ def _register_builtin_platform_jobs() -> None:
|
||||
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
|
||||
from app.services.schedule.shipping_audit_retention_job import run_shipping_audit_retention_schedule
|
||||
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule
|
||||
from app.services.schedule.freight_receipt_rpa_retention_job import run_freight_receipt_rpa_retention_schedule
|
||||
from app.services.schedule.shipping_order_extraction_progress_cleanup_job import run_shipping_order_extraction_progress_cleanup_schedule
|
||||
from app.services.schedule.shipping_post_ot_auto_fulfill_compensation_job import (
|
||||
run_shipping_post_ot_auto_fulfill_compensation_schedule,
|
||||
@@ -233,6 +235,25 @@ def _register_builtin_platform_jobs() -> None:
|
||||
),
|
||||
defaults={"source_codes": []},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="freight-receipt-rpa",
|
||||
label="货代收料 RPA",
|
||||
handler=run_freight_receipt_rpa_schedule,
|
||||
description="按计划从已配置收料报表的站点导出并归档收料文件。",
|
||||
category="shipping",
|
||||
params_schema=({
|
||||
"key": "source_codes", "type": "multi_select", "label": "收料站点", "required": False,
|
||||
"default": [], "options_source": "shipping_receipt_sources",
|
||||
"help": "选择需要执行的收料站点;留空则执行所有已启用收料配置。",
|
||||
},),
|
||||
defaults={"source_codes": []},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key='freight-receipt-rpa-retention', label='货代收料归档到期清理',
|
||||
handler=run_freight_receipt_rpa_retention_schedule,
|
||||
description='仅删除已过三年保留期的收料对象,保留运行、文件事实和审计记录。', category='shipping',
|
||||
params_schema=({'key': 'limit', 'type': 'number', 'label': '单批上限', 'required': False, 'default': 100},), defaults={'limit': 100},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="faq-aggregate-hot",
|
||||
label="FAQ 热点聚合",
|
||||
|
||||
@@ -20,6 +20,11 @@ from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
recover_all_stale_awaiting_rpa_schedule_runs,
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
recover_all_stale_receipt_rpa_schedule_runs,
|
||||
recover_stale_receipt_rpa_schedule_runs,
|
||||
is_awaiting_receipt_rpa_schedule_run,
|
||||
)
|
||||
from app.services.schedule.timezone_util import compute_next_run_at, utc_now_naive
|
||||
|
||||
_worker_initialized = False
|
||||
@@ -126,6 +131,7 @@ def enqueue_manual_schedule_run(
|
||||
if task is None:
|
||||
raise LookupError(f"schedule task {task_id} not found")
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
recover_stale_receipt_rpa_schedule_runs(task)
|
||||
active = _active_run(task.id)
|
||||
if active is not None:
|
||||
job = (
|
||||
@@ -180,6 +186,10 @@ def enqueue_due_schedule_runs(*, limit: int = 5) -> int:
|
||||
|
||||
created = 0
|
||||
for task in tasks:
|
||||
# 每轮都回收当前任务已超时的外部 RPA 回调,不能仅依赖 worker 启动时扫一次;
|
||||
# 这只是终态化失败,不会自动重新导出。
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
recover_stale_receipt_rpa_schedule_runs(task)
|
||||
if _active_run(task.id) is None:
|
||||
_create_queued_run(task, trigger_type="cron", triggered_by_user_id=None)
|
||||
_advance_next_run(task)
|
||||
@@ -229,7 +239,7 @@ def prepare_schedule_queue() -> int:
|
||||
legacy_running = db.session.query(ScheduleRun).filter(ScheduleRun.status == "running").all()
|
||||
interrupted = 0
|
||||
for run in legacy_running:
|
||||
if is_awaiting_rpa_schedule_run(run):
|
||||
if is_awaiting_rpa_schedule_run(run) or is_awaiting_receipt_rpa_schedule_run(run):
|
||||
continue
|
||||
active_job = (
|
||||
db.session.query(Job.id)
|
||||
@@ -254,6 +264,9 @@ def prepare_schedule_queue() -> int:
|
||||
recovered = recover_all_stale_awaiting_rpa_schedule_runs()
|
||||
if recovered:
|
||||
current_app.logger.info("[schedule-worker] recovered %d stale awaiting RPA runs", recovered)
|
||||
receipt_recovered = recover_all_stale_receipt_rpa_schedule_runs()
|
||||
if receipt_recovered:
|
||||
current_app.logger.info("[schedule-worker] recovered %d stale receipt RPA runs", receipt_recovered)
|
||||
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
|
||||
recover_pending_rpa_callback_cleanup_jobs,
|
||||
)
|
||||
|
||||
@@ -28,6 +28,11 @@ from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
should_defer_schedule_run_finalization,
|
||||
)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
apply_deferred_receipt_schedule_run_state,
|
||||
recover_stale_receipt_rpa_schedule_runs,
|
||||
should_defer_receipt_schedule_run,
|
||||
)
|
||||
from app.services.schedule.job_params import normalize_job_params_for_contract
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||
from app.services.schedule.timezone_util import compute_next_run_at, normalize_schedule_timezone
|
||||
@@ -489,6 +494,7 @@ def enable_task(task: ScheduleTask, *, commit: bool = True, check_options: bool
|
||||
|
||||
def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: int | None, run: ScheduleRun | None = None) -> ScheduleRun:
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
recover_stale_receipt_rpa_schedule_runs(task)
|
||||
|
||||
if run is None:
|
||||
existing = db.session.query(ScheduleRun).filter(
|
||||
@@ -550,6 +556,10 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
errors=errors,
|
||||
step_logs=step_logs,
|
||||
)
|
||||
if should_defer_receipt_schedule_run(task, step_logs):
|
||||
return apply_deferred_receipt_schedule_run_state(
|
||||
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
|
||||
)
|
||||
|
||||
duration_ms = int((time.time() - start_ts) * 1000)
|
||||
if current_app:
|
||||
|
||||
@@ -4,7 +4,7 @@ services/shipping_notice/attachment_selection.py
|
||||
用途:基于 Intake 快览事实生成可审计的附件选择计划。
|
||||
依赖:ShippingOrderIntake、标准库正则与哈希;只读取 structured_result_json,不回读 Document/布局结果。
|
||||
逻辑:发送阶段调用本文件,把当前批次附件目录转换为“为何选择/为何跳过”的稳定计划;
|
||||
后续深度解析、预算扩展与审计都应复用这份快照,而不是重新猜测附件优先级。
|
||||
所有预算内附件先物化为同一 Run 的 Unit,Worker 再按并发预算执行,避免把排队误建模为扩批。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -150,8 +150,8 @@ def build_attachment_selection_snapshot(
|
||||
|
||||
Args:
|
||||
intakes: 当前发送批次的 Intake;必须已经通过上传快览。
|
||||
max_initial_attachments: 首轮自动选择上限。
|
||||
max_initial_concurrency: 首轮并发上限。
|
||||
max_initial_attachments: 兼容旧快照的首轮附件字段;新计划不以它限制 Unit 创建。
|
||||
max_initial_concurrency: Worker 最大并发,仅限制执行,不限制 Unit 创建。
|
||||
expansion_batch_size: 后续每轮扩展的附件上限。
|
||||
max_total_attachments: 单次邮件深度解析总附件预算上限。
|
||||
|
||||
@@ -232,17 +232,13 @@ def build_attachment_selection_snapshot(
|
||||
if byte_budget and planned_bytes + size > byte_budget:
|
||||
row['skip_reason_codes'] = ['budget_total_bytes']
|
||||
continue
|
||||
if index < max_initial_attachments:
|
||||
# [STEP 1] 同一发送批次内的预算内附件必须全部创建 Unit。执行并发由
|
||||
# max_initial_concurrency 在物化/Worker 层控制,不能借“首轮选择”延迟附件身份。
|
||||
if index < max_total_attachments:
|
||||
row['selected'] = True
|
||||
row['selection_batch'] = 1
|
||||
planned_bytes += size
|
||||
continue
|
||||
if index < max_total_attachments:
|
||||
row['planned_selection_batch'] = (
|
||||
2 + ((index - max_initial_attachments) // max(1, int(expansion_batch_size or 1)))
|
||||
)
|
||||
planned_bytes += size
|
||||
continue
|
||||
row['skip_reason_codes'] = ['budget_total_limit']
|
||||
|
||||
group_counts: dict[str, int] = defaultdict(int)
|
||||
|
||||
@@ -51,15 +51,6 @@ from app.services.shipping_notice.progress_audit_contract import (
|
||||
)
|
||||
|
||||
# XFA 视觉绑定 / 拆分 / 统一迁移相关审计事件(管理端筛选分组)。
|
||||
XFA_VISUAL_BINDING_AUDIT_EVENT_TYPES: frozenset[str] = frozenset({
|
||||
'xfa_visual_binding_suggested',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
'xfa_ocr_started',
|
||||
'xfa_ocr_completed',
|
||||
'xfa_ocr_failed',
|
||||
})
|
||||
XFA_SPLIT_AUDIT_EVENT_TYPES: frozenset[str] = frozenset({
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_split_rule_previewed',
|
||||
@@ -71,12 +62,10 @@ XFA_SPLIT_AUDIT_EVENT_TYPES: frozenset[str] = frozenset({
|
||||
'xfa_segment_mapping_updated',
|
||||
})
|
||||
XFA_UNIFIED_AUDIT_EVENT_TYPES: frozenset[str] = (
|
||||
XFA_VISUAL_BINDING_AUDIT_EVENT_TYPES
|
||||
| XFA_SPLIT_AUDIT_EVENT_TYPES
|
||||
XFA_SPLIT_AUDIT_EVENT_TYPES
|
||||
| frozenset({
|
||||
'order_profile_unified_migration_dry_run',
|
||||
'order_profile_unified_migration_executed',
|
||||
'xfa_profile_draft_saved',
|
||||
'xfa_mapping_saved',
|
||||
'xfa_structure_analysis_reused',
|
||||
'xfa_structure_analysis_reuse_rejected',
|
||||
@@ -407,10 +396,6 @@ def _apply_filters(query, *, filters: dict[str, Any]):
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(ORDER_EMAIL_ADJUDICATION_AUDIT_EVENT_TYPES))
|
||||
)
|
||||
elif event_type_group in {'xfa_visual', 'xfa_visual_binding', 'visual_binding'}:
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(XFA_VISUAL_BINDING_AUDIT_EVENT_TYPES))
|
||||
)
|
||||
elif event_type_group in {'xfa_split', 'xfa_split_rule', 'split_rule'}:
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(XFA_SPLIT_AUDIT_EVENT_TYPES))
|
||||
|
||||
@@ -20,6 +20,7 @@ from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job, ShippingNotice, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
|
||||
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
|
||||
from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate
|
||||
from app.services.shipping_notice.tool_common import log_task_event
|
||||
|
||||
|
||||
@@ -68,13 +69,14 @@ def _recover_stale_active_job(job: Job) -> bool:
|
||||
在用户触发入口原子回收超时的 AutoProgress running Job。
|
||||
|
||||
核心逻辑:仅处理 started_at 已超过通用发货 Job 超时的 running 行;旧 Job
|
||||
终态保留审计,关联 running/queued Gate 改为 blocked_retryable,使当前事务可重新入队。
|
||||
终态保留审计,关联 running/queued Gate 改为 blocked_manual。超时不会自动续跑;
|
||||
用户必须在当前 Gate 选择明确的恢复动作。
|
||||
|
||||
Args:
|
||||
job: 已由 submit_auto_progress 锁定的活动 Job。
|
||||
|
||||
Returns:
|
||||
True 表示旧 Job 已回收,调用方应继续创建新 Job;False 表示仍有效并复用。
|
||||
True 表示旧 Job 已回收,调用方不得据此自动创建新 Job;False 表示仍有效并复用。
|
||||
"""
|
||||
if str(job.status or '') != 'running' or job.started_at is None:
|
||||
return False
|
||||
@@ -85,7 +87,7 @@ def _recover_stale_active_job(job: Job) -> bool:
|
||||
return False
|
||||
now = _utc_now()
|
||||
job.status = 'failed'
|
||||
job.message = f'自动推进任务执行超时(超过 {int(timeout_seconds)}s),已允许重新入队'
|
||||
job.message = f'自动推进任务执行超时(超过 {int(timeout_seconds)}s),已停止,等待用户选择下一步动作'
|
||||
job.error_message = 'shipping_auto_progress_timeout'
|
||||
job.finished_at = now
|
||||
job.locked_by = None
|
||||
@@ -93,8 +95,8 @@ def _recover_stale_active_job(job: Job) -> bool:
|
||||
job.updated_at = now
|
||||
gate = db.session.get(ShippingProcessGate, int(job.gate_id)) if job.gate_id else None
|
||||
if gate is not None and gate.status in {'queued', 'running'}:
|
||||
gate.status = 'blocked_retryable'
|
||||
gate.blocking_reason_code = 'technical_retry_exhausted'
|
||||
gate.status = 'blocked_manual'
|
||||
gate.blocking_reason_code = 'technical_failure_present'
|
||||
gate.updated_at = now
|
||||
db.session.flush()
|
||||
return True
|
||||
@@ -363,20 +365,22 @@ def submit_auto_progress(
|
||||
).with_for_update().order_by(Job.id.desc()).first()
|
||||
)
|
||||
if active is not None:
|
||||
if not _recover_stale_active_job(active):
|
||||
if _recover_stale_active_job(active):
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'queued' if active.status == 'queued' else 'running',
|
||||
'status': 'blocked_manual',
|
||||
'job_id': int(active.id), 'execution_id': active.execution_id,
|
||||
'gate_code': (active.payload_json or {}).get('gate_code'), 'reused': True,
|
||||
'gate_code': (active.payload_json or {}).get('gate_code'), 'reused': False,
|
||||
'stopped_reason': 'shipping_auto_progress_timeout',
|
||||
}
|
||||
log_task_event(locked_task, 'auto_progress_stale_job_recovered', {
|
||||
'stale_job_id': int(active.id),
|
||||
'execution_id': active.execution_id,
|
||||
'gate_id': active.gate_id,
|
||||
'trigger': trigger,
|
||||
}, actor_id=operator_id, source=trigger)
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'queued' if active.status == 'queued' else 'running',
|
||||
'job_id': int(active.id), 'execution_id': active.execution_id,
|
||||
'gate_code': (active.payload_json or {}).get('gate_code'), 'reused': True,
|
||||
}
|
||||
candidate = get_active_candidate_set(locked_task)
|
||||
candidate_set_id = int(candidate.id) if candidate is not None else None
|
||||
execution = _active_execution_for_task(locked_task, candidate_set_id=candidate_set_id)
|
||||
@@ -435,6 +439,7 @@ def submit_auto_progress(
|
||||
if (
|
||||
gate is not None
|
||||
and action_code
|
||||
and action_belongs_to_gate(gate_code=str(gate.gate_code), action_code=action_code)
|
||||
and not is_navigation_action(action_code)
|
||||
and is_technical_gate_party(execution.responsible_party)
|
||||
):
|
||||
|
||||
@@ -21,15 +21,15 @@ CANDIDATE_QUALIFICATION_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
})
|
||||
|
||||
# 资格评估器版本;快照持久化时写入 evaluator_version。
|
||||
# 变更点:2026-08-08 引入 VC 三来源门禁,版本 bump。
|
||||
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION: Final[str] = 'candidate-qualification.v2.1-vc'
|
||||
# 变更点:模板值源改为内部证据适配,资格不再按 XFA/坐标模板分叉。
|
||||
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION: Final[str] = 'candidate-qualification.v3.0-unified-profile'
|
||||
|
||||
# 统一检查顺序(不可重排):后置项依赖前置放行语义由服务层解释。
|
||||
# XFA 专属门禁对非 XFA Candidate 恒为 True(N/A 放行)。
|
||||
# VC 门禁 vc_source_merged_clean 放在 field_conflicts_resolved 之后,
|
||||
# 以便冲突项先被 PDF 优先裁决,剩余 needs_review 项再由本门禁拦截。
|
||||
CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = (
|
||||
'auto_create_enabled',
|
||||
'route_stp_eligible',
|
||||
'classification_confidence',
|
||||
'required_fields_complete',
|
||||
'key_fields_minimum_confidence',
|
||||
@@ -39,16 +39,12 @@ 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',
|
||||
'xfa_unified_profile_snapshot',
|
||||
)
|
||||
|
||||
# 检查项失败 → 稳定用户原因码(对话 / Process Gate / 复核摘要共用)。
|
||||
CANDIDATE_QUALIFICATION_GATE_REASON_CODES: Final[dict[str, str]] = {
|
||||
'auto_create_enabled': 'auto_create_disabled',
|
||||
'route_stp_eligible': 'review_required',
|
||||
'classification_confidence': 'classification_low_confidence',
|
||||
'required_fields_complete': 'final_required_field_missing',
|
||||
'key_fields_minimum_confidence': 'field_low_confidence',
|
||||
@@ -58,15 +54,11 @@ 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',
|
||||
'xfa_unified_profile_snapshot': 'xfa_visual_coverage_insufficient',
|
||||
}
|
||||
|
||||
# 偏向「需人工轻量确认」而非硬阻断的原因码。
|
||||
CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'review_required',
|
||||
'customer_confirmation_required',
|
||||
'customer_ambiguous',
|
||||
'customer_unresolved',
|
||||
|
||||
@@ -10,8 +10,7 @@ services/shipping_notice/candidate_qualification_service.py
|
||||
模板 Profile 批准仅写入 parser_trace;LLM 路径不再天然阻断;
|
||||
分类/LLM 字段置信度缺失 fail-closed;阈值来源写入 confidence_policy;
|
||||
duplicate unchecked 与关键字段证据缺失均 fail-closed;
|
||||
XFA 硬门禁:shadow 阻断、盲测批准、客户/checksum/场景白名单(自动建单总开关走 Schema/CQ);
|
||||
另要求 evidence 计数与四项 cross-check 齐全且仅为 matched/passed/skipped;
|
||||
XFA datasets 的身份/交叉校验结果作为统一证据门禁输入,不新增模板类型专属放行规则;
|
||||
PDF 优先关键冲突(conflicts_json.reason=pdf_preferred_critical_conflict)
|
||||
映射为 review_required,阻断 can_auto_create。
|
||||
硬冻结 2026-08-07:不再叠加 XFA_AUTO_CREATE / flatten / 审计补偿等模板类型特例到 can_auto_create。
|
||||
@@ -41,16 +40,7 @@ from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts
|
||||
collect_vc_candidate_conflicts,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
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,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import extraction_emergency_stop_enabled
|
||||
|
||||
|
||||
def _candidate_field(candidate: Any, key: str, default: Any = None) -> Any:
|
||||
@@ -345,6 +335,10 @@ def evaluate_candidate_qualification(
|
||||
emergency_stop = True
|
||||
|
||||
auto_create_enabled = bool(schema_auto_create_enabled) and not emergency_stop
|
||||
route = _route_decision(unit=unit, run=run)
|
||||
# 路由已明确 needs_review 时,候选字段再完整也不能重获自动建单资格。
|
||||
# 缺省保持历史候选兼容;所有新 Worker 路由都会持久化该裁决。
|
||||
route_stp_eligible = str(route.get('route_decision') or '').strip() != 'needs_review'
|
||||
|
||||
min_confidence, confidence_source = _resolve_minimum_confidence(candidate)
|
||||
classification_ok = _classification_confidence_ok(
|
||||
@@ -364,19 +358,9 @@ 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,
|
||||
'route_stp_eligible': route_stp_eligible,
|
||||
'classification_confidence': classification_ok,
|
||||
'required_fields_complete': required_ok,
|
||||
'key_fields_minimum_confidence': key_confidence_ok,
|
||||
@@ -386,23 +370,15 @@ 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']),
|
||||
'xfa_unified_profile_snapshot': bool(xfa_eval['gates'].get('xfa_unified_profile_snapshot', True)),
|
||||
}
|
||||
failed = [key for key in CANDIDATE_QUALIFICATION_GATE_KEYS if not gates.get(key)]
|
||||
|
||||
# [STEP 3] 映射原因码;客户细因 / XFA 细因 / PDF 关键冲突细因 / VC 细因覆盖默认码。
|
||||
# [STEP 3] 映射原因码;客户细因 / PDF 关键冲突细因 / VC 细因覆盖默认码。
|
||||
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:
|
||||
@@ -429,8 +405,6 @@ def evaluate_candidate_qualification(
|
||||
# [STEP 3b] 证据快照追加 VC 合并概览(脱敏,仅计数)—— 注意:必须在 STEP 4 status
|
||||
# 计算之后执行,因为 status 不依赖 evidence_snapshot,保证零回归。
|
||||
evidence_snapshot = _evidence_snapshot(candidate)
|
||||
if xfa_eval.get('evidence_extra'):
|
||||
evidence_snapshot = {**evidence_snapshot, **xfa_eval['evidence_extra']}
|
||||
try:
|
||||
vc_items = collect_vc_candidate_conflicts(candidate)
|
||||
except Exception: # noqa: BLE001
|
||||
@@ -468,7 +442,7 @@ def evaluate_candidate_qualification(
|
||||
'evidence_snapshot': evidence_snapshot,
|
||||
'qualification_score': score,
|
||||
'can_auto_create': can_auto_create,
|
||||
'shadow_would_auto_create': bool(xfa_eval.get('shadow_would_auto_create')),
|
||||
'shadow_would_auto_create': False,
|
||||
'evaluator_version': CANDIDATE_QUALIFICATION_EVALUATOR_VERSION,
|
||||
'confidence_policy': confidence_policy,
|
||||
}
|
||||
@@ -655,308 +629,8 @@ def _route_decision(*, unit: Any | None, run: Any | None) -> dict[str, Any]:
|
||||
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,
|
||||
'xfa_unified_profile_snapshot': 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'
|
||||
|
||||
# [STEP 6] 统一 Profile 快照指标:视觉/证据/镜像须 100%,checksum 须与路由一致。
|
||||
# 指标来源优先 route.xfa_unified_metrics,其次 structured / parser_trace 顶层率字段。
|
||||
unified_metrics = route.get('xfa_unified_metrics')
|
||||
if not isinstance(unified_metrics, dict):
|
||||
structured = getattr(candidate, 'structured_result_json', None)
|
||||
if isinstance(structured, dict):
|
||||
nested = structured.get('_hxops_xfa_unified_metrics')
|
||||
unified_metrics = nested if isinstance(nested, dict) else None
|
||||
if not isinstance(unified_metrics, dict):
|
||||
# 兼容 parser_trace 直接携带 visual/evidence 率(阶段 6 契约)。
|
||||
trace_metrics = {
|
||||
key: parser_trace.get(key)
|
||||
for key in (
|
||||
'visual_coverage_rate',
|
||||
'evidence_retention_rate',
|
||||
'mirror_consistency_rate',
|
||||
'profile_checksum',
|
||||
)
|
||||
if parser_trace.get(key) is not None
|
||||
}
|
||||
if any(k.endswith('_rate') for k in trace_metrics):
|
||||
unified_metrics = trace_metrics
|
||||
unified_ok = True
|
||||
unified_reason = None
|
||||
if isinstance(unified_metrics, dict):
|
||||
for metric_key, reason_code in (
|
||||
('visual_coverage_rate', 'xfa_visual_coverage_insufficient'),
|
||||
('evidence_retention_rate', 'xfa_evidence_retention_insufficient'),
|
||||
('mirror_consistency_rate', 'xfa_mirror_consistency_insufficient'),
|
||||
):
|
||||
raw_rate = unified_metrics.get(metric_key)
|
||||
if raw_rate is not None and float(raw_rate) < 1.0:
|
||||
unified_ok = False
|
||||
unified_reason = reason_code
|
||||
break
|
||||
metrics_checksum = str(unified_metrics.get('profile_checksum') or '').strip()
|
||||
if unified_ok and metrics_checksum and checksum and metrics_checksum != checksum:
|
||||
unified_ok = False
|
||||
unified_reason = 'xfa_profile_checksum_mismatch'
|
||||
|
||||
gates = {
|
||||
'xfa_auto_create_policy': policy_ok,
|
||||
'xfa_profile_blind_approved': blind_ok,
|
||||
'xfa_pilot_allowlist': allowlist_ok,
|
||||
'xfa_evidence_integrity': evidence_ok,
|
||||
'xfa_unified_profile_snapshot': unified_ok,
|
||||
}
|
||||
reason_by_gate = {
|
||||
'xfa_auto_create_policy': policy_reason,
|
||||
'xfa_profile_blind_approved': blind_reason,
|
||||
'xfa_pilot_allowlist': allowlist_reason,
|
||||
'xfa_evidence_integrity': evidence_reason,
|
||||
'xfa_unified_profile_snapshot': unified_reason,
|
||||
}
|
||||
|
||||
# shadow:在其余试点门禁(除真实建单开关外)满足时记录 would_auto_create。
|
||||
shadow_base_ok = (
|
||||
blind_ok and allowlist_ok and evidence_ok and unified_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()),
|
||||
'xfa_visual_coverage_rate': (
|
||||
float(unified_metrics.get('visual_coverage_rate'))
|
||||
if isinstance(unified_metrics, dict) and unified_metrics.get('visual_coverage_rate') is not None
|
||||
else None
|
||||
),
|
||||
'xfa_evidence_retention_rate': (
|
||||
float(unified_metrics.get('evidence_retention_rate'))
|
||||
if isinstance(unified_metrics, dict) and unified_metrics.get('evidence_retention_rate') is not None
|
||||
else None
|
||||
),
|
||||
'xfa_mirror_consistency_rate': (
|
||||
float(unified_metrics.get('mirror_consistency_rate'))
|
||||
if isinstance(unified_metrics, dict) and unified_metrics.get('mirror_consistency_rate') is not None
|
||||
else None
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _build_parser_trace(*, candidate: Any, run: Any | None, unit: Any | None) -> dict[str, Any]:
|
||||
"""组装解析链路痕迹;坐标模板批准仅作治理信息,XFA 另有硬门禁。"""
|
||||
"""组装解析链路痕迹;模板取值 adapter 不改变统一资格门禁。"""
|
||||
route = _route_decision(unit=unit, run=run)
|
||||
|
||||
extraction_source = str(getattr(candidate, 'extraction_source', '') or '').strip().lower()
|
||||
|
||||
@@ -1,253 +0,0 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/case_retry_auto_progress_service.py
|
||||
|
||||
用途:单个 Case 精确自动推进恢复(Case 级 retry-auto-progress API 服务层)。
|
||||
依赖:reconciliation_service.assert_case_not_blocked_manual、
|
||||
order_review_auto_progress_coordinator.reconcile_single_case_for_auto_progress、
|
||||
order_review_service.get_review_case_visible_to_user(兜底 soft_load_review_case_for_audit)、
|
||||
fulfillment_audit.record_fulfillment_audit、order_review_projection.serialize_review_case。
|
||||
逻辑:可见性 → 业务阻断双校验 → 终态检查(幂等)→ reconcile_single_case → 审计 → 返回摘要。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError
|
||||
from app.models import ShippingOrderReviewCase
|
||||
|
||||
|
||||
def case_retry_auto_progress(
|
||||
*,
|
||||
user_id: int,
|
||||
case_no: str,
|
||||
is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
单个 Case 精确自动推进恢复入口。
|
||||
|
||||
用途(第一层):为单个指定 Review Case 执行「客户协调 + Draft 校验 + STP 入队」
|
||||
全链路自动推进,适用于 Projection primary_action.code = retry_auto_progress。
|
||||
禁止 duplicate 等业务阻断对象调用;assert_case_not_blocked_manual 前置双校验,
|
||||
防止用技术重试绕过人工裁决门禁。
|
||||
|
||||
依赖(第二层):
|
||||
- reconciliation_service.assert_case_not_blocked_manual:业务阻断前置双校验。
|
||||
- order_review_auto_progress_coordinator.reconcile_single_case_for_auto_progress:
|
||||
客户协调 + validate_draft + ensure_stp_auto_create_for_case 统一执行。
|
||||
- order_review_service.get_review_case_visible_to_user(兜底:
|
||||
order_review_draft_service.soft_load_review_case_for_audit):Case 可见性校验。
|
||||
- fulfillment_audit.record_fulfillment_audit:写 case_retry_auto_progress_invoked 审计。
|
||||
- order_review_projection.serialize_review_case:返回体附带 Case 安全投影。
|
||||
|
||||
逻辑(第三层):
|
||||
STEP 1 可见性校验 → STEP 2 业务阻断前置校验 → STEP 3 终态幂等检查
|
||||
→ STEP 4 调用 reconcile_single_case_for_auto_progress(trigger=case_api_retry_auto_progress)
|
||||
→ STEP 5 审计 → STEP 6 返回统一摘要结构。
|
||||
|
||||
Args:
|
||||
user_id: 操作人(必须为 Case owner 或 admin)。
|
||||
case_no: 目标复核 Case 编号。
|
||||
is_admin: 是否管理员(影响可见性与 serialize 投影粒度)。
|
||||
|
||||
Returns:
|
||||
``{success, operation, case_no, customer_step_status, validate_status,
|
||||
enqueue_status, job_id, idempotency_key, error, case}``。
|
||||
已终态时返回 success=True + already_confirmed=True + enqueue_status=already_confirmed,
|
||||
不抛错(幂等友好)。
|
||||
|
||||
Raises:
|
||||
NotFoundError: Case 不存在或当前用户越权。
|
||||
ConflictError (SHIPPING.RETRY_STP_BLOCKED_MANUAL): 命中 duplicate 等业务阻断,
|
||||
禁止用 retry API 绕过,引导走 reconcile-and-progress。
|
||||
"""
|
||||
import logging as _rt_logging
|
||||
_rt_log = _rt_logging.getLogger(__name__)
|
||||
|
||||
normalized_case_no = str(case_no or '').strip().upper()
|
||||
user_id_int = int(user_id or 0)
|
||||
fallback = {
|
||||
'success': False,
|
||||
'operation': 'retry_auto_progress',
|
||||
'case_no': normalized_case_no,
|
||||
'already_confirmed': False,
|
||||
'customer_step_status': 'failed',
|
||||
'validate_status': 'failed',
|
||||
'enqueue_status': 'not_eligible',
|
||||
'job_id': None,
|
||||
'idempotency_key': None,
|
||||
'error': 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED',
|
||||
'reconcile_result': {},
|
||||
'case': None,
|
||||
}
|
||||
|
||||
# ========================================================================
|
||||
# [STEP 0] 模块级 delay import 统一包 try/except,与路由/协调器双层防护对齐。
|
||||
# 任一依赖模块 SyntaxError/ImportError → 返回结构化 fallback,
|
||||
# 不冒泡为 HTTP 500 或整批拖死协调器循环。
|
||||
# ========================================================================
|
||||
try:
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
|
||||
reconcile_single_case_for_auto_progress,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
from app.services.shipping_notice.reconciliation_service import (
|
||||
assert_case_not_blocked_manual,
|
||||
)
|
||||
except (SyntaxError, ImportError) as mod_err:
|
||||
_rt_log.exception(
|
||||
'case_retry_auto_progress module import error case_no=%s err=%s',
|
||||
normalized_case_no, type(mod_err).__name__,
|
||||
)
|
||||
fallback['error'] = 'SHIPPING.MODULE_IMPORT_ERROR'
|
||||
fallback['import_error'] = type(mod_err).__name__
|
||||
return fallback
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_rt_log.exception(
|
||||
'case_retry_auto_progress import unexpected error case_no=%s',
|
||||
normalized_case_no,
|
||||
)
|
||||
fallback['error_type'] = type(exc).__name__
|
||||
return fallback
|
||||
|
||||
try:
|
||||
# ====================================================================
|
||||
# [STEP 1] 可见性校验:优先 get_review_case_visible_to_user,
|
||||
# ImportError 兜底走 soft_load_review_case_for_audit(写审计场景同款门禁)。
|
||||
# ====================================================================
|
||||
try:
|
||||
from app.services.shipping_notice.order_review_service import (
|
||||
get_review_case_visible_to_user,
|
||||
)
|
||||
|
||||
case: ShippingOrderReviewCase = get_review_case_visible_to_user(
|
||||
normalized_case_no,
|
||||
user_id_int,
|
||||
is_admin=bool(is_admin),
|
||||
)
|
||||
except AppError:
|
||||
raise
|
||||
except Exception:
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
soft_load_review_case_for_audit,
|
||||
)
|
||||
|
||||
case = soft_load_review_case_for_audit(
|
||||
user_id=user_id_int,
|
||||
case_no=normalized_case_no,
|
||||
)
|
||||
if case is None:
|
||||
from app.core.errors import NotFoundError
|
||||
|
||||
raise NotFoundError(
|
||||
'Order review case not found',
|
||||
code='SHIPPING.REVIEW_CASE_NOT_FOUND',
|
||||
)
|
||||
|
||||
# ====================================================================
|
||||
# [STEP 2] 业务阻断前置校验:duplicate 类必须走 reconcile-and-progress。
|
||||
# 若命中 → 抛 409 ConflictError,明确 alternative_api 指向。
|
||||
# ====================================================================
|
||||
assert_case_not_blocked_manual(case_no=normalized_case_no, case=case)
|
||||
|
||||
# ====================================================================
|
||||
# [STEP 3] 终态检查:confirmed_task_id 或 status=confirmed/终态 → 幂等返回。
|
||||
# 不抛错,保留 already_confirmed 标识让前端区分「本次执行」与「原本已终态」。
|
||||
# ====================================================================
|
||||
_TERMINAL = frozenset({
|
||||
'confirmed', 'confirming', 'non_order', 'superseded', 'quality_issue', 'reparse_pending',
|
||||
})
|
||||
already_confirmed = (
|
||||
bool(getattr(case, 'confirmed_task_id', None))
|
||||
or str(getattr(case, 'status', '') or '') in _TERMINAL
|
||||
)
|
||||
if already_confirmed:
|
||||
return {
|
||||
'success': True,
|
||||
'operation': 'retry_auto_progress',
|
||||
'case_no': normalized_case_no,
|
||||
'already_confirmed': True,
|
||||
'customer_step_status': 'skipped',
|
||||
'validate_status': 'skipped',
|
||||
'enqueue_status': 'already_confirmed_or_terminal',
|
||||
'job_id': None,
|
||||
'idempotency_key': None,
|
||||
'error': None,
|
||||
'reconcile_result': {},
|
||||
'case': serialize_review_case(case, is_admin=bool(is_admin)),
|
||||
}
|
||||
|
||||
# ====================================================================
|
||||
# [STEP 4] 核心执行:reconcile_single_case_for_auto_progress(统一协调器)。
|
||||
# trigger=case_api_retry_auto_progress,refresh_validation=True 重跑校验。
|
||||
# ====================================================================
|
||||
reconcile_result: dict[str, Any] = reconcile_single_case_for_auto_progress(
|
||||
case=case,
|
||||
trigger='case_api_retry_auto_progress',
|
||||
refresh_validation=True,
|
||||
)
|
||||
|
||||
# ====================================================================
|
||||
# [STEP 5] 审计:case_retry_auto_progress_invoked。
|
||||
# metadata 附带 reconcile_result 全量摘要,strict=False 降级不阻断。
|
||||
# ====================================================================
|
||||
try:
|
||||
record_fulfillment_audit(
|
||||
event_type='case_retry_auto_progress_invoked',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=normalized_case_no,
|
||||
action='retry_auto_progress',
|
||||
actor_type='user',
|
||||
actor_id=user_id_int,
|
||||
review_case_no=normalized_case_no,
|
||||
owner_user_id=int(getattr(case, 'owner_user_id', 0) or 0),
|
||||
result=(
|
||||
'success'
|
||||
if not reconcile_result.get('error')
|
||||
and str(reconcile_result.get('enqueue_status') or '') in {
|
||||
'queued', 'reused', 'already_queued', 'already_running', 'enqueued',
|
||||
}
|
||||
else 'failed'
|
||||
),
|
||||
metadata={'reconcile_result': dict(reconcile_result or {})},
|
||||
source='case_retry_auto_progress_service',
|
||||
strict=False,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ====================================================================
|
||||
# [STEP 6] 统一返回:success + operation + case_no + reconcile_result 平铺字段
|
||||
# + serialized case 投影。
|
||||
# ====================================================================
|
||||
return {
|
||||
'success': True,
|
||||
'operation': 'retry_auto_progress',
|
||||
'case_no': normalized_case_no,
|
||||
'already_confirmed': False,
|
||||
'customer_step_status': reconcile_result.get('customer_step_status'),
|
||||
'validate_status': reconcile_result.get('validate_status'),
|
||||
'enqueue_status': reconcile_result.get('enqueue_status'),
|
||||
'job_id': reconcile_result.get('job_id'),
|
||||
'idempotency_key': reconcile_result.get('idempotency_key'),
|
||||
'error': reconcile_result.get('error'),
|
||||
'reconcile_result': dict(reconcile_result or {}),
|
||||
'case': serialize_review_case(case, is_admin=bool(is_admin)),
|
||||
}
|
||||
except (AppError, ConflictError):
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_rt_log.exception(
|
||||
'case_retry_auto_progress execution error case_no=%s', normalized_case_no,
|
||||
)
|
||||
fallback['error_type'] = type(exc).__name__
|
||||
try:
|
||||
fallback['case'] = (
|
||||
serialize_review_case(case, is_admin=bool(is_admin))
|
||||
if 'case' in locals() and case is not None else None
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return fallback
|
||||
@@ -2,7 +2,7 @@
|
||||
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、
|
||||
依赖: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。
|
||||
@@ -10,89 +10,11 @@ backend/app/services/shipping_notice/chat_action_handlers.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Iterator
|
||||
from typing import Iterator
|
||||
|
||||
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.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_task_ui_state_event as _shipping_ui_state_event,
|
||||
stream_text_events as _stream_text_events,
|
||||
tool_result_message as _tool_result_message,
|
||||
)
|
||||
|
||||
|
||||
def _payload_str(payload: dict[str, Any], *keys: str) -> str:
|
||||
for key in keys:
|
||||
value = str(payload.get(key) or "").strip()
|
||||
if value:
|
||||
return value
|
||||
return ""
|
||||
|
||||
|
||||
def _require_task(ctx: TurnContext):
|
||||
task_no = resolve_shipping_task_no(ctx)
|
||||
if not task_no:
|
||||
raise ValidationError("task_no is required")
|
||||
user_id = ctx.user_id
|
||||
if user_id is None:
|
||||
raise ValidationError("user context is required")
|
||||
task = get_task_for_user(task_no, user_id)
|
||||
if task is None:
|
||||
raise NotFoundError(f"Task not found: {task_no}")
|
||||
return task
|
||||
|
||||
|
||||
_CHAT_FULFILLMENT_WRITE_DISABLED_MSG = (
|
||||
"该操作已迁移至工作台「我的待办」任务处理页,请从侧栏进入任务处理后再操作。"
|
||||
)
|
||||
_CHAT_FULFILLMENT_WRITE_DISABLED_CODE = "SHIPPING.CHAT_FULFILLMENT_WRITE_DISABLED"
|
||||
|
||||
|
||||
def _reject_chat_fulfillment_write() -> None:
|
||||
"""
|
||||
拒绝 Chat Turn 履约写路径,引导用户改走任务工作台。
|
||||
|
||||
核心逻辑:STP 验收要求货代上传、Excel 生成、库存匹配等写操作仅在工作台执行。
|
||||
"""
|
||||
raise ValidationError(
|
||||
_CHAT_FULFILLMENT_WRITE_DISABLED_MSG,
|
||||
code=_CHAT_FULFILLMENT_WRITE_DISABLED_CODE,
|
||||
)
|
||||
|
||||
|
||||
def _format_decision_message(decision: str, result: dict[str, Any], task_no: str) -> str:
|
||||
"""对齐前端 shippingDecisionFormat.ts 的助手摘要格式。"""
|
||||
lines = [_tool_result_message(result) or "操作已完成。"]
|
||||
if decision == "reparse_inventory":
|
||||
lines.extend(["", "请点击「选择库存文件」重新上传。"])
|
||||
lines.extend(["", f"任务编号:{task_no}"])
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _match_result_payload(task_no: str, result: dict[str, Any]) -> dict[str, Any]:
|
||||
"""构建匹配结果展示 payload;按钮统一来自后端 ui_state.actions。"""
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
line_results = data.get("line_results") if isinstance(data.get("line_results"), list) else []
|
||||
shortage = data.get("shortage") if isinstance(data.get("shortage"), dict) else {}
|
||||
shortage_lines = shortage.get("lines") if isinstance(shortage.get("lines"), list) else []
|
||||
ui_state = result.get("ui_state") if isinstance(result.get("ui_state"), dict) else {}
|
||||
actions = ui_state.get("actions") if isinstance(ui_state.get("actions"), dict) else {
|
||||
"primary": None,
|
||||
"secondary": [],
|
||||
}
|
||||
return {
|
||||
"taskId": task_no,
|
||||
"match_status": data.get("match_status"),
|
||||
"line_results": line_results,
|
||||
"shortage_lines": shortage_lines,
|
||||
"actions": actions,
|
||||
}
|
||||
|
||||
|
||||
class ShippingCreateBatchFromNoticesAction:
|
||||
@@ -133,167 +55,9 @@ class ShippingCreateBatchFromIntakesAction:
|
||||
yield TurnEvent(event='step.started', data={})
|
||||
|
||||
|
||||
class ShippingSubmitDecisionAction:
|
||||
"""提交人工决策:confirm / reject / rematch / retry_rpa 等。"""
|
||||
|
||||
action_type = "shipping.submit_decision"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
task = _require_task(ctx)
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
decision = _payload_str(payload, "decision").lower()
|
||||
if not decision:
|
||||
raise ValidationError("decision is required")
|
||||
yield TurnEvent(event="step.started", data={"step_id": "submit_decision", "label": "提交决策..."})
|
||||
result = submit_decision({
|
||||
"task_id": task.task_no,
|
||||
"decision": decision,
|
||||
"comment": _payload_str(payload, "comment"),
|
||||
"event_source": "chat_turn",
|
||||
})
|
||||
if not isinstance(result, dict):
|
||||
raise ValidationError("invalid submit_decision response")
|
||||
if str(result.get("status") or "").lower() == "failed":
|
||||
raise ValidationError(_tool_result_message(result) or "submit_decision failed")
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield _shipping_ui_state_event(refreshed)
|
||||
content = _format_decision_message(decision, result, task.task_no)
|
||||
yield TurnEvent(
|
||||
event="message.completed",
|
||||
data={
|
||||
"content": content,
|
||||
"message_type": "text",
|
||||
"payload": {
|
||||
"decision": decision,
|
||||
"task_no": task.task_no,
|
||||
"tool_result": result,
|
||||
},
|
||||
},
|
||||
)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "submit_decision"})
|
||||
|
||||
|
||||
class ShippingGenerateExcelAction:
|
||||
action_type = "shipping.generate_excel"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
_require_task(ctx)
|
||||
_reject_chat_fulfillment_write()
|
||||
return
|
||||
yield # pragma: no cover — satisfies Generator type; unreachable after reject
|
||||
|
||||
|
||||
class ShippingFreezeOrderAction:
|
||||
"""冻结已复核订单,使后续履约只读取不可变 Snapshot。
|
||||
|
||||
AI 触发时机:订单字段和订购客户已在对话中确认、界面显示“冻结订单”时调用。
|
||||
必须携带用户看到订单时的 expected_order_data_version;版本变化由乐观锁拒绝,要求刷新后重试。
|
||||
"""
|
||||
|
||||
action_type = "shipping.freeze_order"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
task = _require_task(ctx)
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
try:
|
||||
expected_version = int(payload.get("expected_order_data_version"))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError("expected_order_data_version is required") from exc
|
||||
yield TurnEvent(event="step.started", data={"step_id": "freeze_order", "label": "冻结订单..."})
|
||||
from app import db
|
||||
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
|
||||
|
||||
snapshot = freeze_order_snapshot(
|
||||
task,
|
||||
actor_id=int(ctx.user_id),
|
||||
expected_order_data_version=expected_version,
|
||||
)
|
||||
db.session.commit()
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield _shipping_ui_state_event(refreshed)
|
||||
yield from _stream_text_events(
|
||||
f"订单已冻结为履约快照 #{snapshot.id}。接下来可以继续库存处理。\n\n任务编号:{task.task_no}",
|
||||
message_type="text",
|
||||
payload={"task_no": task.task_no, "snapshot_id": snapshot.id},
|
||||
)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "freeze_order"})
|
||||
|
||||
|
||||
class ShippingRetryUploadAction:
|
||||
action_type = "shipping.retry_upload"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
_require_task(ctx)
|
||||
_reject_chat_fulfillment_write()
|
||||
return
|
||||
yield # pragma: no cover — satisfies Generator type; unreachable after reject
|
||||
|
||||
|
||||
class ShippingMatchInventoryAction:
|
||||
action_type = "shipping.match_inventory"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
_require_task(ctx)
|
||||
_reject_chat_fulfillment_write()
|
||||
return
|
||||
yield # pragma: no cover — satisfies Generator type; unreachable after reject
|
||||
|
||||
|
||||
class ShippingConfirmInventorySourceAction:
|
||||
action_type = "shipping.confirm_inventory_source"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
task = _require_task(ctx)
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
source_code = _payload_str(payload, "source_code", "sourceCode").upper()
|
||||
if not source_code:
|
||||
raise ValidationError("source_code is required")
|
||||
yield TurnEvent(event="step.started", data={"step_id": "confirm_inventory_source", "label": "确认库存源..."})
|
||||
result = shipping_tools.confirm_inventory_source({
|
||||
"task_id": task.task_no,
|
||||
"source_code": source_code,
|
||||
"event_source": "chat_turn",
|
||||
"_trusted_user_id": ctx.user_id,
|
||||
})
|
||||
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
|
||||
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "confirm_inventory_source failed")
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield _shipping_ui_state_event(refreshed)
|
||||
content = _tool_result_message(result) or f"已确认库存源 {source_code}。"
|
||||
yield TurnEvent(event="message.completed", data={"content": content, "message_type": "text"})
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "confirm_inventory_source"})
|
||||
|
||||
|
||||
class ShippingMarkManualUploadedAction:
|
||||
"""以 Chat 中上传的截图或回执确认人工货代上传。
|
||||
|
||||
AI 触发时机:用户明确已在货代系统上传并已通过 Chat 选择回执文件时调用。
|
||||
payload 必须含 evidence_asset_no;操作者只从当前 Chat 用户上下文取得,不能由客户端伪造。
|
||||
"""
|
||||
|
||||
action_type = "shipping.mark_manual_uploaded"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
task = _require_task(ctx)
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
evidence_asset_no = str(payload.get("evidence_asset_no") or "").strip()
|
||||
if not evidence_asset_no:
|
||||
raise ValidationError("evidence_asset_no is required", code="SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED")
|
||||
_reject_chat_fulfillment_write()
|
||||
return
|
||||
yield # pragma: no cover — satisfies Generator type; unreachable after reject
|
||||
|
||||
|
||||
_HANDLERS = (
|
||||
ShippingCreateBatchFromNoticesAction(),
|
||||
ShippingCreateBatchFromIntakesAction(),
|
||||
ShippingSubmitDecisionAction(),
|
||||
ShippingFreezeOrderAction(),
|
||||
ShippingGenerateExcelAction(),
|
||||
ShippingRetryUploadAction(),
|
||||
ShippingMatchInventoryAction(),
|
||||
ShippingConfirmInventorySourceAction(),
|
||||
ShippingMarkManualUploadedAction(),
|
||||
)
|
||||
|
||||
for _handler in _HANDLERS:
|
||||
|
||||
@@ -1,38 +1,14 @@
|
||||
"""
|
||||
services/shipping_notice/chat_actions.py
|
||||
|
||||
用途:发货通知状态机旧模块名的向后兼容 re-export 入口。
|
||||
依赖:state_machine(ACTION_SPECS、CHECKPOINT_REGISTRY、apply_task_transition 等)、ui_state。
|
||||
逻辑:历史代码 import chat_actions;新代码应直接引用 state_machine.py / ui_state.py,本模块仅保留兼容导出。
|
||||
用途:发货通知聊天只读状态适配。
|
||||
依赖:state_machine(checkpoint 与内部状态迁移)、ui_state。
|
||||
逻辑:Chat 不再拥有动作目录或写入口;仅输出 Gate 已裁决的只读 UI State。
|
||||
"""
|
||||
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
ACTION_SPECS,
|
||||
ALL_ACTION_IDS,
|
||||
ALL_CHECKPOINT_IDS,
|
||||
CHECKPOINT_REGISTRY,
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
TaskTransition,
|
||||
TaskUiState,
|
||||
action_buttons_for_checkpoint,
|
||||
apply_task_transition,
|
||||
build_action_buttons,
|
||||
build_checkpoint_catalog,
|
||||
checkpoint_for_task,
|
||||
human_options_for_checkpoint,
|
||||
human_options_for_task,
|
||||
human_options_for_task_or_checkpoint,
|
||||
inventory_source_action_buttons,
|
||||
resolve_task_ui_state,
|
||||
ui_state_for_checkpoint,
|
||||
upload_req_options_for_task,
|
||||
validate_registry,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, checkpoint_for_task, resolve_task_ui_state, validate_registry
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
# Legacy alias
|
||||
CHECKPOINT_OPTIONS = CHECKPOINT_REGISTRY
|
||||
|
||||
|
||||
def build_chat_actions_payload(task) -> dict:
|
||||
"""
|
||||
@@ -63,24 +39,10 @@ def build_chat_actions_payload(task) -> dict:
|
||||
}
|
||||
|
||||
__all__ = [
|
||||
"ACTION_SPECS",
|
||||
"ALL_ACTION_IDS",
|
||||
"ALL_CHECKPOINT_IDS",
|
||||
"CHECKPOINT_OPTIONS",
|
||||
"CHECKPOINT_REGISTRY",
|
||||
"TaskTransition",
|
||||
"TaskUiState",
|
||||
"action_buttons_for_checkpoint",
|
||||
"apply_task_transition",
|
||||
"build_action_buttons",
|
||||
"build_chat_actions_payload",
|
||||
"build_checkpoint_catalog",
|
||||
"checkpoint_for_task",
|
||||
"human_options_for_checkpoint",
|
||||
"human_options_for_task",
|
||||
"human_options_for_task_or_checkpoint",
|
||||
"resolve_task_ui_state",
|
||||
"ui_state_for_checkpoint",
|
||||
"upload_req_options_for_task",
|
||||
"validate_registry",
|
||||
]
|
||||
@@ -544,6 +544,19 @@ def _resolve_workflow_no(run: ShippingOrderProcessingRun) -> str | None:
|
||||
return str(getattr(workflow, 'workflow_no', None) or '').strip() or None
|
||||
|
||||
|
||||
def _has_current_non_terminal_review_case(run: ShippingOrderProcessingRun) -> bool:
|
||||
"""判断该 Run 是否仍承载文件 Stream 的当前非终态 Case;历史 Case 不得影响任务入口。"""
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewStream
|
||||
|
||||
return db.session.query(ShippingOrderReviewCase.id).join(
|
||||
ShippingOrderReviewStream,
|
||||
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
|
||||
).filter(
|
||||
ShippingOrderReviewCase.run_id == int(run.id),
|
||||
ShippingOrderReviewCase.status.notin_(('superseded', 'non_order')),
|
||||
).first() is not None
|
||||
|
||||
|
||||
def _resolve_task_actions(run: ShippingOrderProcessingRun) -> tuple[str | None, list[str]]:
|
||||
"""
|
||||
聚合任务级权威操作;前端禁止自行按状态推导按钮。
|
||||
@@ -578,8 +591,7 @@ def _resolve_task_actions(run: ShippingOrderProcessingRun) -> tuple[str | None,
|
||||
|
||||
# 当前 Run 已有可见 Review Case 时,任务卡不能再提供“打开订单复核”导航;
|
||||
# 用户已经位于该工作台,继续动作必须由 Case/当前 Gate 投影提供。
|
||||
review_cases = list(getattr(run, 'review_cases', None) or [])
|
||||
if any(str(getattr(case, 'status', '') or '') not in {'superseded', 'non_order'} for case in review_cases):
|
||||
if _has_current_non_terminal_review_case(run):
|
||||
actions = [action for action in actions if action not in {
|
||||
'open_review', 'enter_manual_review', 'open_order_review',
|
||||
}]
|
||||
@@ -595,6 +607,7 @@ def _resolve_task_actions(run: ShippingOrderProcessingRun) -> tuple[str | None,
|
||||
'retry_failed_documents',
|
||||
'retry_failed_attachments',
|
||||
'retry_parse',
|
||||
'reparse_batch',
|
||||
):
|
||||
if candidate in actions:
|
||||
primary = candidate
|
||||
|
||||
@@ -1,997 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/conversation_retry_auto_progress_service.py
|
||||
|
||||
用途:对话级「重试自动推进」投影与批量执行(Case STP / 正式 OT 统一决策器)。
|
||||
依赖:order_review_projection、order_stp_auto_create_service、task_retry_decision_service、
|
||||
fulfillment_audit、ShippingOrderReviewCase / ShippingOrderProcessingRun / ShippingNotice。
|
||||
逻辑:eligible 唯一依据 automation.retryable=true;建单前 Case→retry_stp_auto_create,
|
||||
正式 OT→task_retry_decision_service(与任务级 /retry 同源);不批量行库存;
|
||||
写 conversation_retry_auto_progress 汇总审计,对象级审计由既有链路写入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
Job,
|
||||
ShippingNotice,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewDraft,
|
||||
)
|
||||
from app.services.shipping_notice.recovery_contract import should_general_retry_be_removed
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
ACTION_RETRY_AUTO_PROGRESS = 'retry_auto_progress'
|
||||
ACTION_RETRY_STP = 'retry_stp_auto_create'
|
||||
OBJECT_REVIEW_CASE = 'review_case'
|
||||
OBJECT_FORMAL_TASK = 'formal_task'
|
||||
|
||||
# [STEP P1-13] 业务阻断黑名单:duplicate 类命中即禁止对话级重试,需走 reconcile-and-progress
|
||||
_DUPLICATE_BLOCKING_CODES = frozenset({
|
||||
'duplicate_decision_required',
|
||||
'SHIPPING.NOTICE_EXACT_DUPLICATE',
|
||||
'NOTICE_EXACT_DUPLICATE',
|
||||
})
|
||||
|
||||
# [STEP P1-13-d] 允许强制重试的 manual_fallback 原因码(不含 duplicate 类)
|
||||
_FORCE_RETRYABLE_BLOCKING_CODES = frozenset({
|
||||
'STP_NOT_ELIGIBLE',
|
||||
'SHIPPING.STP_NOT_ELIGIBLE',
|
||||
'profile_schema_mismatch',
|
||||
'SHIPPING.profile_schema_mismatch',
|
||||
})
|
||||
|
||||
# needs_human 并不总是终止态:库存快照/RPA 暂态失败仍可由统一重试决策器
|
||||
# 重新触发库存准备;重复、短缺、冲突等业务裁决原因不得自动放行。
|
||||
_INVENTORY_RETRYABLE_HUMAN_CODES = frozenset({
|
||||
'inventory_snapshot_prepare_failed',
|
||||
'inventory_snapshots_pending',
|
||||
'inventory_rpa_failed',
|
||||
'inventory_rpa_exhausted',
|
||||
'inventory_file_missing',
|
||||
'rpa_failed',
|
||||
'trigger_not_claimed_missing',
|
||||
'trigger_not_claimed_timeout',
|
||||
'inventory_trigger_missing',
|
||||
'inventory_trigger_write_failed',
|
||||
# 库存门禁/匹配阻断属于可重新检查的技术中间态;对话级重试不得直接跳过。
|
||||
'inventory_candidates_required',
|
||||
'inventory_candidates_frozen_required',
|
||||
'inventory_snapshot_prepare_failed',
|
||||
'inventory_snapshots_pending',
|
||||
'inventory_match_not_ready',
|
||||
'inventory_match_incomplete',
|
||||
})
|
||||
_BUSINESS_HUMAN_CODES = frozenset({
|
||||
'inventory_shortage',
|
||||
'inventory_source_conflict',
|
||||
'inventory_source_candidates_need_human',
|
||||
'duplicate_decision_required',
|
||||
})
|
||||
|
||||
|
||||
def project_conversation_allowed_actions(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
投影对话级可执行动作(当前仅重试自动推进)。
|
||||
|
||||
核心逻辑:扫描会话下 Case;automation.retryable=true 计入 eligible_count;
|
||||
无合格对象时返回空列表(前端不渲染禁用空按钮)。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户。
|
||||
conversation_id: 会话 ID。
|
||||
|
||||
Returns:
|
||||
``[{code, eligible_count}]`` 或 ``[]``。
|
||||
"""
|
||||
normalized = str(conversation_id or '').strip()
|
||||
if not normalized or not user_id:
|
||||
return []
|
||||
eligible = _list_eligible_targets(user_id=int(user_id), conversation_id=normalized)
|
||||
if not eligible:
|
||||
return []
|
||||
return [{
|
||||
'code': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'eligible_count': len(eligible),
|
||||
}]
|
||||
|
||||
|
||||
def retry_auto_progress_for_conversation(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str,
|
||||
reason: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
对话级批量重试自动推进。
|
||||
|
||||
核心逻辑:按 conversation_id 服务端扫描;逐对象重读最新 automation 后执行;
|
||||
Case→STP(内部 refresh_validation);正式 OT→auto_progress;不批量行库存。
|
||||
|
||||
Args:
|
||||
user_id: 操作人。
|
||||
conversation_id: 会话 ID。
|
||||
reason: 可选原因(写入审计 metadata)。
|
||||
|
||||
Returns:
|
||||
``{conversation_id, summary, items}``。
|
||||
|
||||
Raises:
|
||||
ValidationError: conversation_id 为空。
|
||||
NotFoundError: 会话下无可访问对象且会话不存在于用户范围。
|
||||
"""
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
normalized = str(conversation_id or '').strip()
|
||||
if not normalized:
|
||||
raise ValidationError('conversation_id is required')
|
||||
|
||||
cases = _list_conversation_cases(user_id=int(user_id), conversation_id=normalized)
|
||||
if not cases and not _conversation_has_any_asset(user_id=int(user_id), conversation_id=normalized):
|
||||
raise NotFoundError('Conversation not found')
|
||||
|
||||
items: list[dict[str, Any]] = []
|
||||
for case in cases:
|
||||
items.append(_retry_one_case(user_id=int(user_id), case=case))
|
||||
|
||||
summary = _summarize_items(items)
|
||||
record_fulfillment_audit(
|
||||
event_type='conversation_retry_auto_progress',
|
||||
aggregate_type='shipping_conversation',
|
||||
aggregate_id=normalized,
|
||||
action='retry_auto_progress',
|
||||
actor_id=int(user_id),
|
||||
conversation_id=normalized,
|
||||
owner_user_id=int(user_id),
|
||||
result='success' if summary['failed'] == 0 else 'failure',
|
||||
metadata={
|
||||
'reason': str(reason or 'user_retry_auto_progress')[:200],
|
||||
'summary': summary,
|
||||
'items': items,
|
||||
},
|
||||
source='api',
|
||||
)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception: # noqa: BLE001
|
||||
db.session.rollback()
|
||||
_LOGGER.exception('conversation retry audit commit failed conversation_id=%s', normalized)
|
||||
|
||||
return {
|
||||
'conversation_id': normalized,
|
||||
'summary': summary,
|
||||
'items': items,
|
||||
}
|
||||
|
||||
|
||||
def _conversation_has_any_asset(*, user_id: int, conversation_id: str) -> bool:
|
||||
"""会话是否存在属于当前用户的 Run / 正式任务(用于 404 判定)。"""
|
||||
run_exists = (
|
||||
ShippingOrderProcessingRun.query
|
||||
.filter_by(user_id=int(user_id), conversation_id=conversation_id)
|
||||
.limit(1)
|
||||
.first()
|
||||
)
|
||||
if run_exists is not None:
|
||||
return True
|
||||
notice_exists = (
|
||||
ShippingNotice.query
|
||||
.filter_by(user_id=int(user_id), conversation_id=conversation_id)
|
||||
.limit(1)
|
||||
.first()
|
||||
)
|
||||
return notice_exists is not None
|
||||
|
||||
|
||||
def _list_conversation_cases(*, user_id: int, conversation_id: str) -> list[ShippingOrderReviewCase]:
|
||||
"""
|
||||
列出会话下全部复核 Case(按 id 升序,稳定执行顺序)。
|
||||
|
||||
核心逻辑:经 ProcessingRun.conversation_id + user_id 关联,禁止跨会话/跨用户。
|
||||
"""
|
||||
return (
|
||||
db.session.query(ShippingOrderReviewCase)
|
||||
.join(
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderReviewCase.run_id == ShippingOrderProcessingRun.id,
|
||||
)
|
||||
.filter(
|
||||
ShippingOrderProcessingRun.conversation_id == conversation_id,
|
||||
ShippingOrderProcessingRun.user_id == int(user_id),
|
||||
)
|
||||
.order_by(ShippingOrderReviewCase.id.asc())
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def _automation_for_case(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
"""投影 Case automation(与工作台同源)。"""
|
||||
from app.services.shipping_notice.order_review_projection import (
|
||||
_project_case_automation_status,
|
||||
_project_post_confirm_auto_progress,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
enrich_automation_status,
|
||||
resolve_formal_ot,
|
||||
)
|
||||
|
||||
draft = case.current_draft
|
||||
validation = dict(draft.validation_result_json or {}) if draft is not None else None
|
||||
post_confirm = _project_post_confirm_auto_progress(case)
|
||||
automation = _project_case_automation_status(
|
||||
case,
|
||||
validation=validation,
|
||||
post_confirm=post_confirm,
|
||||
)
|
||||
formal_ot = resolve_formal_ot(case)
|
||||
return enrich_automation_status(
|
||||
automation if isinstance(automation, dict) else {},
|
||||
formal_ot=formal_ot,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
|
||||
def _formal_task_no(case: ShippingOrderReviewCase, automation: dict[str, Any]) -> str | None:
|
||||
"""解析正式 OT 编号(有则走 auto-progress,无则走 STP)。"""
|
||||
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
|
||||
|
||||
formal = resolve_formal_ot(case)
|
||||
if formal.get('task_missing'):
|
||||
return None
|
||||
if not formal.get('has_formal_ot'):
|
||||
return None
|
||||
task_no = str(
|
||||
automation.get('task_no')
|
||||
or getattr(case, 'confirmed_task_no', None)
|
||||
or ''
|
||||
).strip()
|
||||
return task_no or None
|
||||
|
||||
|
||||
def _list_eligible_targets(*, user_id: int, conversation_id: str) -> list[dict[str, Any]]:
|
||||
"""
|
||||
扫描可重试对象(P1-13 扩展三类 c / d / e,OR 语义)。
|
||||
|
||||
目标候选扩展说明(文档 Q8 合同测试要求):
|
||||
[STEP P1-13-e] 原有:automation.retryable=true 且未命中业务阻断(保留,不删)。
|
||||
|
||||
[STEP P1-13-c] stp_enqueue_missing:
|
||||
• Case.status IN ('unreviewed','draft','ready')
|
||||
• confirmed_task_id IS NULL
|
||||
• Draft.validation.status = 'ready' 且 can_auto_create = true
|
||||
• 最近 Job(若有)的 retryable != false
|
||||
或 blocking_reason 非 duplicate_decision_required / NOTICE_EXACT_DUPLICATE
|
||||
• 当前无 queued/running STP Job
|
||||
→ 这类对象 Draft 校验就绪但从未成功入队 STP,可通过 retry_auto_progress 自动推进。
|
||||
|
||||
[STEP P1-13-d] manual_fallback 且允许强制重试:
|
||||
• 最近 STP Job.result_json.status = failed
|
||||
• result_json.blocking_reason 非 duplicate 类
|
||||
• retryable_flag = False 但 blocking_reason 命中允许
|
||||
retry_stp_auto_create_for_case 强制重试的类型
|
||||
(如 STP_NOT_ELIGIBLE / profile_schema_mismatch,不含 duplicate)
|
||||
→ 这类对象标记了 manual_fallback,但实际是技术可恢复的原因,允许批量重试。
|
||||
|
||||
除上述条件外,全部对象必须通过 should_general_retry_be_removed 二次门禁。
|
||||
"""
|
||||
targets: list[dict[str, Any]] = []
|
||||
for case in _list_conversation_cases(user_id=user_id, conversation_id=conversation_id):
|
||||
automation = _automation_for_case(case)
|
||||
retryable_flag = bool(automation.get('retryable'))
|
||||
blocking_reason = (
|
||||
automation.get('blocking_reason')
|
||||
if isinstance(automation.get('blocking_reason'), dict)
|
||||
else None
|
||||
)
|
||||
br_code = (
|
||||
str(blocking_reason.get('code') or '')
|
||||
if isinstance(blocking_reason, dict)
|
||||
else str(blocking_reason or '')
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 取 Case 维度最近一条 STP Job(用于 c / d 条件判断)
|
||||
# 说明:Job 模型没有 reference_type / reference_key,通过 business_ref 前缀匹配。
|
||||
# STP business_ref = stp-auto:{run_no}:doc-{document_id}:v{draft_version},
|
||||
# 按 run_no+document_id 前缀可覆盖同一 Case 的所有 draft_version。
|
||||
# ------------------------------------------------------------------
|
||||
_run_no = str(getattr(getattr(case, 'run', None), 'run_no', '') or '').strip()
|
||||
_doc_id = getattr(case, 'document_id', None)
|
||||
_stp_prefix = None
|
||||
if _run_no and _doc_id is not None:
|
||||
_stp_prefix = f'stp-auto:{_run_no}:doc-{int(_doc_id)}:'
|
||||
|
||||
latest_stp_job: Job | None = None
|
||||
running_stp_exists = False
|
||||
if _stp_prefix is not None:
|
||||
latest_stp_job = (
|
||||
Job.query
|
||||
.filter(
|
||||
Job.domain == 'shipping_notice',
|
||||
Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value,
|
||||
Job.business_ref.like(f"{_stp_prefix}%"),
|
||||
)
|
||||
.order_by(Job.created_at.desc())
|
||||
.first()
|
||||
)
|
||||
running_stp_exists = (
|
||||
Job.query
|
||||
.filter(
|
||||
Job.domain == 'shipping_notice',
|
||||
Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value,
|
||||
Job.business_ref.like(f"{_stp_prefix}%"),
|
||||
Job.status.in_(['queued', 'running']),
|
||||
)
|
||||
.limit(1)
|
||||
.first()
|
||||
) is not None
|
||||
|
||||
latest_rj: dict[str, Any] = (
|
||||
dict(latest_stp_job.result_json)
|
||||
if latest_stp_job is not None and isinstance(latest_stp_job.result_json, dict)
|
||||
else {}
|
||||
)
|
||||
latest_retryable_flag: bool = bool(latest_rj.get('retryable', True))
|
||||
latest_br_raw = latest_rj.get('blocking_reason')
|
||||
latest_br_code = (
|
||||
str(latest_br_raw.get('code') or '')
|
||||
if isinstance(latest_br_raw, dict)
|
||||
else str(latest_br_raw or '')
|
||||
)
|
||||
latest_status: str = str(latest_rj.get('status') or '').strip().lower()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Draft 校验:status=ready + can_auto_create(c 条件需要)
|
||||
# ------------------------------------------------------------------
|
||||
draft: ShippingOrderReviewDraft | None = case.current_draft
|
||||
validation: dict[str, Any] = (
|
||||
dict(draft.validation_result_json)
|
||||
if draft is not None and isinstance(draft.validation_result_json, dict)
|
||||
else {}
|
||||
)
|
||||
draft_ready_ok = (
|
||||
draft is not None
|
||||
and str(validation.get('status') or '') == 'ready'
|
||||
and bool(validation.get('can_auto_create'))
|
||||
)
|
||||
case_status_ok = str(case.status or '') in {'unreviewed', 'draft', 'ready'}
|
||||
no_confirmed_task = not bool(case.confirmed_task_id)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# P1-13:三类候选 OR 判定
|
||||
# ------------------------------------------------------------------
|
||||
# [STEP P1-13-e] 原有 automation.retryable=true(保留,不删)
|
||||
eligible_e = retryable_flag and not should_general_retry_be_removed(
|
||||
retryable_flag=retryable_flag,
|
||||
blocking_reason=blocking_reason,
|
||||
)
|
||||
|
||||
# [STEP P1-13-c] stp_enqueue_missing:Draft 校验就绪但从未入队或可恢复
|
||||
eligible_c = (
|
||||
case_status_ok
|
||||
and no_confirmed_task
|
||||
and draft_ready_ok
|
||||
and not running_stp_exists
|
||||
and (
|
||||
latest_stp_job is None
|
||||
or latest_retryable_flag
|
||||
or latest_br_code not in _DUPLICATE_BLOCKING_CODES
|
||||
)
|
||||
)
|
||||
|
||||
# [STEP P1-13-d] manual_fallback 允许强制重试:最近失败、非 duplicate、命中允许码
|
||||
eligible_d = (
|
||||
no_confirmed_task
|
||||
and latest_stp_job is not None
|
||||
and latest_status == 'failed'
|
||||
and latest_br_code not in _DUPLICATE_BLOCKING_CODES
|
||||
and (
|
||||
latest_br_code in _FORCE_RETRYABLE_BLOCKING_CODES
|
||||
or br_code in _FORCE_RETRYABLE_BLOCKING_CODES
|
||||
)
|
||||
)
|
||||
|
||||
is_eligible = eligible_e or eligible_c or eligible_d
|
||||
if not is_eligible:
|
||||
continue
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 二次门禁:should_general_retry_be_removed(duplicate 类再次拦截)
|
||||
# ------------------------------------------------------------------
|
||||
if eligible_e and should_general_retry_be_removed(
|
||||
retryable_flag=retryable_flag,
|
||||
blocking_reason=blocking_reason,
|
||||
):
|
||||
continue
|
||||
|
||||
task_no = _formal_task_no(case, automation)
|
||||
if task_no:
|
||||
targets.append({
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'case_no': case.case_no,
|
||||
'category': (
|
||||
'e_retryable_true' if eligible_e
|
||||
else 'c_stp_enqueue_missing' if eligible_c
|
||||
else 'd_manual_fallback_force'
|
||||
),
|
||||
})
|
||||
elif not case.confirmed_task_id:
|
||||
targets.append({
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'case_no': case.case_no,
|
||||
'category': (
|
||||
'e_retryable_true' if eligible_e
|
||||
else 'c_stp_enqueue_missing' if eligible_c
|
||||
else 'd_manual_fallback_force'
|
||||
),
|
||||
})
|
||||
return targets
|
||||
|
||||
|
||||
def _skip_reason_from_automation(automation: dict[str, Any], *, task_missing: bool) -> str | None:
|
||||
"""
|
||||
根据最新 automation 返回跳过原因;可执行时返回 None。
|
||||
|
||||
核心逻辑:queued/running/completed/task_missing 跳过;needs_human 跳过;
|
||||
manual_fallback 的 owner_type=human 仍可 retryable,不得误判为人工阻断跳过。
|
||||
"""
|
||||
if task_missing:
|
||||
return 'task_missing'
|
||||
status = str(automation.get('status') or '').strip().lower()
|
||||
if status in {'queued', 'running'}:
|
||||
return 'already_running'
|
||||
if status in {'completed', 'succeeded'}:
|
||||
return 'already_completed'
|
||||
if status == 'needs_human':
|
||||
# 库存准备失败是“需要人工关注但仍可技术重试”的中间态;只有
|
||||
# retryable=true 且原因码在白名单内才允许继续到正式 OT 决策器。
|
||||
reason_candidates = (
|
||||
automation.get('reason_code'),
|
||||
automation.get('blocking_reason_code'),
|
||||
automation.get('error_code'),
|
||||
)
|
||||
reason_codes = {
|
||||
str(item or '').strip().lower()
|
||||
for item in reason_candidates
|
||||
if str(item or '').strip()
|
||||
}
|
||||
if reason_codes & _DUPLICATE_BLOCKING_CODES:
|
||||
return 'human_blocking'
|
||||
if reason_codes & _BUSINESS_HUMAN_CODES:
|
||||
return 'human_blocking'
|
||||
if bool(automation.get('retryable')) and reason_codes & _INVENTORY_RETRYABLE_HUMAN_CODES:
|
||||
return None
|
||||
# 正式 OT 的 needs_human 可能只是上一轮匹配/门禁结果;对话级“重试自动推进”
|
||||
# 的职责是重新读取当前库存事实并重新检查。只有重复订单等明确业务裁决才跳过。
|
||||
return None
|
||||
if not bool(automation.get('retryable')):
|
||||
return 'not_retryable'
|
||||
return None
|
||||
|
||||
|
||||
def _formal_task_has_retryable_inventory_trigger_failure(task_no: str) -> bool:
|
||||
"""读取正式 OT 最新逐源 Attempt,识别 Trigger 缺失等可强制重发的技术失败。"""
|
||||
try:
|
||||
from app.services.shipping_notice.task_retry_decision_service import (
|
||||
summarize_inventory_rpa_latest_attempts,
|
||||
)
|
||||
task = ShippingNotice.query.filter_by(task_no=str(task_no).strip()).first()
|
||||
if task is None:
|
||||
return False
|
||||
summary = summarize_inventory_rpa_latest_attempts(task, include_gate_status=True)
|
||||
technical_codes = {
|
||||
'trigger_not_claimed_missing',
|
||||
'trigger_not_claimed_timeout',
|
||||
'inventory_trigger_missing',
|
||||
'inventory_trigger_write_failed',
|
||||
}
|
||||
return any(
|
||||
str((item or {}).get('error_code') or '').strip().lower() in technical_codes
|
||||
and str((item or {}).get('status') or '').strip().lower() in {'failed', 'exhausted'}
|
||||
for item in (summary.get('latest_attempts') or {}).values()
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
_LOGGER.exception('inventory trigger failure lookup failed task_no=%s', task_no)
|
||||
return False
|
||||
|
||||
|
||||
def _formal_task_has_active_attempt(task_no: str) -> bool:
|
||||
"""按正式 Attempt + Job 双重事实判断任务是否真的仍在执行。"""
|
||||
try:
|
||||
from app.services.shipping_notice.task_retry_decision_service import (
|
||||
summarize_inventory_rpa_latest_attempts,
|
||||
)
|
||||
task = ShippingNotice.query.filter_by(task_no=str(task_no).strip()).first()
|
||||
if task is None:
|
||||
return False
|
||||
summary = summarize_inventory_rpa_latest_attempts(task, include_gate_status=True)
|
||||
return int(summary.get('active_attempt_count') or 0) > 0
|
||||
except Exception: # noqa: BLE001
|
||||
_LOGGER.exception('active attempt lookup failed task_no=%s', task_no)
|
||||
# 状态无法确认时 fail-closed,禁止重复执行。
|
||||
return True
|
||||
|
||||
|
||||
def _retry_one_case(*, user_id: int, case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
"""
|
||||
对单个 Case 执行重试或跳过。
|
||||
|
||||
核心逻辑(P1-13 升级):
|
||||
[STEP 1] 重新读最新 DB 状态(禁止信任传入 case 为可信快照)
|
||||
[STEP 2] 调 assert_case_not_blocked_manual 双校验;业务阻断 → skipped(而非失败)
|
||||
[STEP 3] 正式 OT → auto_progress(保持不变);
|
||||
建单前 Case → 统一调 case_retry_auto_progress(复用客户协调 + Draft 校验 + STP 入队)
|
||||
[STEP 4] 保留原有 items 返回契约(不 break 前端),新增 P1-13 分类字段放入 metadata。
|
||||
"""
|
||||
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
|
||||
from app.services.shipping_notice.reconciliation_service import (
|
||||
assert_case_not_blocked_manual,
|
||||
)
|
||||
from app.core.errors import ConflictError
|
||||
|
||||
# ====================================================================
|
||||
# [STEP 1 P1-13] 重新读最新 DB 状态(不信任调用方传入的 case 对象,避免前端竞态脏读)
|
||||
# ====================================================================
|
||||
fresh_case: ShippingOrderReviewCase | None = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(id=int(case.id))
|
||||
.first()
|
||||
)
|
||||
if fresh_case is None:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': 'case_missing',
|
||||
'metadata': {'p13_category': None},
|
||||
}
|
||||
|
||||
automation = _automation_for_case(fresh_case)
|
||||
formal = resolve_formal_ot(fresh_case)
|
||||
task_missing = bool(formal.get('task_missing'))
|
||||
task_no = _formal_task_no(fresh_case, automation)
|
||||
|
||||
if task_no:
|
||||
skip = _skip_reason_from_automation(automation, task_missing=task_missing)
|
||||
# Automation 是展示投影,可能滞后于正式 Job。只有 Attempt 与 Job 都仍活动时
|
||||
# 才能返回 already_running;Job 已失败的 queued Attempt 是待恢复残留。
|
||||
if skip == 'already_running' and not _formal_task_has_active_attempt(task_no):
|
||||
skip = None
|
||||
# Trigger 缺失/未领取是库存 RPA 的正式技术失败事实;不得被
|
||||
# automation 投影中的历史 completed/not_retryable/human_blocking 覆盖。
|
||||
# 只要当前没有 queued/running Attempt,就必须重新进入 retry_rpa。
|
||||
if skip not in {None, 'already_running', 'task_missing'} and _formal_task_has_retryable_inventory_trigger_failure(task_no):
|
||||
# Automation 可能仍被历史 Job 的错误码污染;逐源 Attempt 是库存 Trigger
|
||||
# 的正式事实,技术领取失败必须重新进入 retry_rpa,而不是继续 skipped。
|
||||
skip = None
|
||||
if skip:
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': skip,
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
return _execute_formal_task_retry(user_id=user_id, task_no=task_no)
|
||||
|
||||
if task_missing or fresh_case.confirmed_task_id:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': fresh_case.case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': 'task_missing' if task_missing else 'already_confirmed',
|
||||
'metadata': {'p13_category': None},
|
||||
}
|
||||
|
||||
skip = _skip_reason_from_automation(automation, task_missing=False)
|
||||
if skip:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': fresh_case.case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': skip,
|
||||
'metadata': {'p13_category': None},
|
||||
}
|
||||
|
||||
# ====================================================================
|
||||
# [STEP 2 P1-13] assert_case_not_blocked_manual 二次校验;业务阻断 → skipped(不回滚整批)
|
||||
# [DUPLICATE-GUARD-3] 第三道:对话级批量重试单条执行前双校验 —
|
||||
# 命中 duplicate 等阻断时单条标记 skipped,不影响其他 Case
|
||||
# ====================================================================
|
||||
try:
|
||||
assert_case_not_blocked_manual(case_no=str(fresh_case.case_no), case=fresh_case)
|
||||
except ConflictError as blocked_err:
|
||||
code = str(getattr(blocked_err, 'code', None) or 'SHIPPING.RETRY_STP_BLOCKED_MANUAL')
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': fresh_case.case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': code,
|
||||
'metadata': {
|
||||
'p13_category': None,
|
||||
'blocked_by': 'assert_case_not_blocked_manual',
|
||||
'blocking_details': getattr(blocked_err, 'details', None),
|
||||
},
|
||||
}
|
||||
|
||||
# ====================================================================
|
||||
# [STEP 3 P1-13] 统一调 case_retry_auto_progress 核心服务
|
||||
# (不再复制 STP 入队逻辑,复用客户协调 + validate + STP)
|
||||
# ====================================================================
|
||||
return _execute_case_retry_auto_progress(user_id=user_id, case=fresh_case)
|
||||
|
||||
|
||||
def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]:
|
||||
"""调用既有 STP retry;捕获业务错误为逐对象 outcome。(保留为兼容降级路径)"""
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
retry_stp_auto_create_for_case,
|
||||
)
|
||||
|
||||
result = retry_stp_auto_create_for_case(user_id=user_id, case_no=case_no)
|
||||
status = str(result.get('status') or '').strip().lower()
|
||||
if status in {'queued', 'reused', 'enqueued'}:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': ACTION_RETRY_STP,
|
||||
'outcome': 'queued',
|
||||
'reason_code': None,
|
||||
'metadata': {'p13_category': 'legacy_stp_retry'},
|
||||
}
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': ACTION_RETRY_STP,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': status or 'not_retryable',
|
||||
'metadata': {'p13_category': 'legacy_stp_retry'},
|
||||
}
|
||||
except AppError as err:
|
||||
code = str(getattr(err, 'code', None) or 'SHIPPING.STP_ENQUEUE_FAILED')
|
||||
if 'ALREADY_CONFIRMED' in code:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': 'already_confirmed',
|
||||
'metadata': {'p13_category': 'legacy_stp_retry'},
|
||||
}
|
||||
if 'NOT_ELIGIBLE' in code:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': ACTION_RETRY_STP,
|
||||
'outcome': 'failed',
|
||||
'reason_code': code,
|
||||
'metadata': {'p13_category': 'legacy_stp_retry'},
|
||||
}
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': ACTION_RETRY_STP,
|
||||
'outcome': 'failed',
|
||||
'reason_code': code,
|
||||
'metadata': {'p13_category': 'legacy_stp_retry'},
|
||||
}
|
||||
except (SyntaxError, ImportError) as mod_err:
|
||||
_LOGGER.exception(
|
||||
'conversation STP retry module import error case_no=%s err=%s',
|
||||
case_no, type(mod_err).__name__,
|
||||
)
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': ACTION_RETRY_STP,
|
||||
'outcome': 'failed',
|
||||
'reason_code': 'SHIPPING.MODULE_IMPORT_ERROR',
|
||||
'metadata': {
|
||||
'p13_category': 'legacy_stp_retry',
|
||||
'import_error': type(mod_err).__name__,
|
||||
},
|
||||
}
|
||||
except Exception: # noqa: BLE001
|
||||
_LOGGER.exception('conversation STP retry failed case_no=%s', case_no)
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': ACTION_RETRY_STP,
|
||||
'outcome': 'failed',
|
||||
'reason_code': 'SHIPPING.STP_ENQUEUE_FAILED',
|
||||
'metadata': {'p13_category': 'legacy_stp_retry'},
|
||||
}
|
||||
|
||||
|
||||
def _execute_case_retry_auto_progress(
|
||||
*,
|
||||
user_id: int,
|
||||
case: ShippingOrderReviewCase,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
P1-13 统一执行入口:调 case_retry_auto_progress 核心服务(客户协调 + validate + STP)。
|
||||
|
||||
保留原有 items 返回契约(object_type / object_ref / action / outcome / reason_code),
|
||||
新增 P1-13 分类字段与执行摘要放入 metadata,不 break 前端。
|
||||
"""
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.case_retry_auto_progress_service import (
|
||||
case_retry_auto_progress,
|
||||
)
|
||||
|
||||
result = case_retry_auto_progress(
|
||||
user_id=int(user_id),
|
||||
case_no=str(case.case_no),
|
||||
is_admin=False,
|
||||
)
|
||||
except AppError as err:
|
||||
code = str(getattr(err, 'code', None) or 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED')
|
||||
if 'ALREADY_CONFIRMED' in code:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': 'already_confirmed',
|
||||
'metadata': {'p13_category': None, 'error': code},
|
||||
}
|
||||
if 'BLOCKED_MANUAL' in code or 'RECONCILE' in code:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': code,
|
||||
'metadata': {
|
||||
'p13_category': None,
|
||||
'blocked_by': 'case_retry_auto_progress_assertion',
|
||||
'details': getattr(err, 'details', None),
|
||||
},
|
||||
}
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'failed',
|
||||
'reason_code': code,
|
||||
'metadata': {'p13_category': None, 'error': code},
|
||||
}
|
||||
except (SyntaxError, ImportError) as mod_err:
|
||||
_LOGGER.exception(
|
||||
'conversation case_retry_auto_progress module import error case_no=%s err=%s',
|
||||
case.case_no, type(mod_err).__name__,
|
||||
)
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'failed',
|
||||
'reason_code': 'SHIPPING.MODULE_IMPORT_ERROR',
|
||||
'metadata': {
|
||||
'p13_category': None,
|
||||
'import_error': type(mod_err).__name__,
|
||||
},
|
||||
}
|
||||
except Exception: # noqa: BLE001
|
||||
_LOGGER.exception('conversation case_retry_auto_progress failed case_no=%s', case.case_no)
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'failed',
|
||||
'reason_code': 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED',
|
||||
'metadata': {'p13_category': None, 'error': 'unexpected_exception'},
|
||||
}
|
||||
|
||||
# 解析执行结果:success + enqueue_status → outcome
|
||||
enqueue_status = str(result.get('enqueue_status') or '').strip().lower()
|
||||
if result.get('already_confirmed'):
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': 'already_confirmed',
|
||||
'metadata': {
|
||||
'p13_category': None,
|
||||
'enqueue_status': enqueue_status,
|
||||
'already_confirmed': True,
|
||||
},
|
||||
}
|
||||
queued_set = {
|
||||
'queued', 'reused', 'already_queued', 'already_running', 'enqueued',
|
||||
}
|
||||
if enqueue_status in queued_set:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'queued',
|
||||
'reason_code': None,
|
||||
'metadata': {
|
||||
'p13_category': result.get('case_no'),
|
||||
'customer_step_status': result.get('customer_step_status'),
|
||||
'validate_status': result.get('validate_status'),
|
||||
'enqueue_status': enqueue_status,
|
||||
'job_id': result.get('job_id'),
|
||||
'idempotency_key': result.get('idempotency_key'),
|
||||
},
|
||||
}
|
||||
if enqueue_status in {'already_confirmed_or_terminal', 'not_eligible'}:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': enqueue_status,
|
||||
'metadata': {
|
||||
'p13_category': None,
|
||||
'enqueue_status': enqueue_status,
|
||||
'error': result.get('error'),
|
||||
},
|
||||
}
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'failed' if result.get('error') else 'skipped',
|
||||
'reason_code': enqueue_status or (result.get('error') and 'execution_error') or 'not_retryable',
|
||||
'metadata': {
|
||||
'p13_category': None,
|
||||
'enqueue_status': enqueue_status,
|
||||
'error': result.get('error'),
|
||||
'customer_step_status': result.get('customer_step_status'),
|
||||
'validate_status': result.get('validate_status'),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
|
||||
"""正式 OT 重试:委托统一决策器(与任务级 /retry 同源)。metadata 追加 P1-13 分类不 break 前端。"""
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision
|
||||
|
||||
result = retry_task_with_decision(
|
||||
task_no=str(task_no),
|
||||
user_id=int(user_id),
|
||||
scope='task',
|
||||
reason='conversation_retry_auto_progress',
|
||||
trigger='conversation_retry',
|
||||
continue_auto_progress=False,
|
||||
)
|
||||
except AppError as err:
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'failed',
|
||||
'reason_code': str(getattr(err, 'code', None) or 'SHIPPING.AUTO_PROGRESS_FAILED'),
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
except (SyntaxError, ImportError) as mod_err:
|
||||
_LOGGER.exception(
|
||||
'conversation task retry module import error task_no=%s err=%s',
|
||||
task_no, type(mod_err).__name__,
|
||||
)
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'failed',
|
||||
'reason_code': 'SHIPPING.MODULE_IMPORT_ERROR',
|
||||
'metadata': {
|
||||
'p13_category': 'e_formal_ot',
|
||||
'import_error': type(mod_err).__name__,
|
||||
},
|
||||
}
|
||||
except Exception: # noqa: BLE001
|
||||
_LOGGER.exception('conversation task retry failed task_no=%s', task_no)
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'failed',
|
||||
'reason_code': 'SHIPPING.AUTO_PROGRESS_FAILED',
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
|
||||
status = str((result or {}).get('status') or '').strip().lower()
|
||||
action = str((result or {}).get('action') or '') or ACTION_RETRY_AUTO_PROGRESS
|
||||
if status == 'needs_human':
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
# 对话级重试已实际重新检查;门禁仍阻断时应归为失败/需处理,
|
||||
# 不能计入“已跳过”,否则用户无法区分未执行与执行后被阻断。
|
||||
'outcome': 'failed',
|
||||
'reason_code': str((result or {}).get('reason_code') or 'human_blocking'),
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
if status == 'failed':
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
'outcome': 'failed',
|
||||
'reason_code': str((result or {}).get('reason_code') or status),
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
if action == 'noop' and str((result or {}).get('reason_code') or '') == 'already_running':
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': 'already_running',
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
if action == 'noop' and status == 'completed':
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': str((result or {}).get('reason_code') or 'already_completed'),
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
if status in {'running', 'completed', 'queued'}:
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
'outcome': 'queued',
|
||||
'reason_code': None,
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': str((result or {}).get('reason_code') or status or 'not_retryable'),
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
|
||||
|
||||
def _summarize_items(items: list[dict[str, Any]]) -> dict[str, int]:
|
||||
"""汇总逐对象结果。"""
|
||||
retried = skipped = failed = blocked = 0
|
||||
for item in items:
|
||||
outcome = str(item.get('outcome') or '').strip().lower()
|
||||
if outcome == 'queued':
|
||||
retried += 1
|
||||
elif outcome == 'failed':
|
||||
failed += 1
|
||||
elif outcome == 'blocked':
|
||||
blocked += 1
|
||||
else:
|
||||
skipped += 1
|
||||
return {
|
||||
'total': len(items),
|
||||
'retried': retried,
|
||||
'skipped': skipped,
|
||||
'failed': failed,
|
||||
'blocked': blocked,
|
||||
}
|
||||
@@ -182,7 +182,6 @@ def customer_gate_tool_response(task: ShippingNotice, *, operation: str) -> dict
|
||||
task=task,
|
||||
message='标准客户尚未确认,请先选择正式客户后再继续。',
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=['confirm_customer'],
|
||||
checkpoint='customer_review',
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=[
|
||||
@@ -216,7 +215,6 @@ def confirm_customer(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task=task,
|
||||
message='请选择标准客户。',
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=['confirm_customer'],
|
||||
checkpoint='customer_review',
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
@@ -152,7 +152,6 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
message="当前库存已解除关联,请重新选择库存文件。系统将按库存站点已发布的解析方案校验并解析。",
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint="upload_req",
|
||||
human_options=["upload_inventory_file", "retry_rpa"],
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
@@ -282,7 +281,6 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task=task,
|
||||
message="库存源尚未确定,请先完成库存源确认。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
@@ -332,7 +330,6 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"destination_candidates": adjudication.destination_candidates,
|
||||
},
|
||||
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
|
||||
human_options=resolve_task_ui_state(task).human_options,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
if not task.inventory_lines_json:
|
||||
|
||||
@@ -15,7 +15,8 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
@@ -24,6 +25,7 @@ from app.models import (
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderProcessingUnit,
|
||||
)
|
||||
from app.services.file_assets.service import (
|
||||
create_derived_file_asset_from_bytes,
|
||||
@@ -49,6 +51,25 @@ from app.services.shipping_notice.order_candidate_builder import (
|
||||
BODY_ATTACHMENT_KEY = 'body'
|
||||
|
||||
|
||||
def _json_safe_value(value: Any) -> Any:
|
||||
"""将动态订单字段结果归一化为 SQLAlchemy JSON 可持久化的原生值。
|
||||
|
||||
邮件正文补充表会按冻结 Schema 将日期/金额转换为 ``date``/``Decimal``;
|
||||
这些类型可参与业务裁决,但不能直接写入 PostgreSQL JSON 字段。
|
||||
"""
|
||||
if value is None or isinstance(value, (str, int, float, bool)):
|
||||
return value
|
||||
if isinstance(value, (date, datetime)):
|
||||
return value.isoformat()
|
||||
if isinstance(value, Decimal):
|
||||
return format(value, 'f')
|
||||
if isinstance(value, dict):
|
||||
return {str(key): _json_safe_value(item) for key, item in value.items()}
|
||||
if isinstance(value, (list, tuple)):
|
||||
return [_json_safe_value(item) for item in value]
|
||||
raise TypeError(f'Unsupported JSON value: {type(value).__name__}')
|
||||
|
||||
|
||||
def generate_candidate_no() -> str:
|
||||
"""生成 SNC-YYYYMMDD-XXXXXXXX 格式候选编号。"""
|
||||
return f"SNC-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
@@ -567,7 +588,9 @@ def persist_documents_and_candidates(
|
||||
schema_definition=definition,
|
||||
)
|
||||
supplement['document_id'] = int(body_doc.id)
|
||||
body_doc.order_extraction_result_json = {'email_supplement': supplement}
|
||||
body_doc.order_extraction_result_json = _json_safe_value({
|
||||
'email_supplement': supplement,
|
||||
})
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
append_shipping_audit_event(
|
||||
event_type='email_supplement_parsed',
|
||||
@@ -757,13 +780,31 @@ def persist_documents_and_candidates(
|
||||
)
|
||||
.all()
|
||||
)
|
||||
stale_ids = {int(d.id) for d in stale_docs}
|
||||
# 已冻结的 Processing Unit 以 Document 为不可变输入锚点。重物化时附件目录可能
|
||||
# 已变化,但在该 Unit 完成、取消或由后继 Run 接管前,不能删除其 Document;否则
|
||||
# 会破坏 Run 审计并触发 document/intake 复合外键,导致整个 Candidate 阶段回滚。
|
||||
referenced_document_ids = {
|
||||
int(row.document_id)
|
||||
for row in (
|
||||
db.session.query(ShippingOrderProcessingUnit.document_id)
|
||||
.filter(
|
||||
ShippingOrderProcessingUnit.intake_id == int(intake.id),
|
||||
ShippingOrderProcessingUnit.document_id.in_([int(doc.id) for doc in stale_docs]),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
}
|
||||
deletable_stale_docs = [
|
||||
document for document in stale_docs
|
||||
if int(document.id) not in referenced_document_ids
|
||||
]
|
||||
stale_ids = {int(d.id) for d in deletable_stale_docs}
|
||||
if 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:
|
||||
for doc in deletable_stale_docs:
|
||||
_release_document_asset(int(doc.asset_id) if doc.asset_id else None)
|
||||
db.session.delete(doc)
|
||||
|
||||
|
||||
@@ -54,10 +54,11 @@ ON_DEMAND_COORDINATE_COMPACTION_ISSUES = frozenset({
|
||||
|
||||
|
||||
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'
|
||||
"""判断布局快照是否可直接使用,或可由原 PDF 在订单识别时按需恢复。
|
||||
|
||||
所有 PDF 一律以共同坐标证据判断;没有视觉 Layout 的历史快照会安全重解析,
|
||||
不能因其曾携带某个值源 capability 而被当成可复用的业务路径。
|
||||
"""
|
||||
if Path(str(document.filename or '')).suffix.lower() != '.pdf':
|
||||
return True
|
||||
evidence = payload.get('coordinate_evidence') if isinstance(payload.get('coordinate_evidence'), dict) else {}
|
||||
@@ -209,6 +210,99 @@ def current_layout_snapshot(document: ShippingOrderDocument) -> dict[str, Any] |
|
||||
return dict(version.payload_json)
|
||||
|
||||
|
||||
def _bind_inline_xfa_structure_analysis(
|
||||
*,
|
||||
document: ShippingOrderDocument,
|
||||
version: ShippingDocumentLayoutVersion,
|
||||
) -> None:
|
||||
"""本地化派生 Layout 的 XFA Analysis,禁止新快照引用旧 Layout 的分析主键。
|
||||
|
||||
坐标/OCR 补证会从现有 Layout 派生一个新版本。XFA Analysis 是
|
||||
``document_id + layout_version_id`` 共同冻结的正式值源证据,不能把旧版本的
|
||||
``structure_analysis_id`` 原样带到新版本;否则样本重新冻结时会因身份不一致
|
||||
fail-closed。首次写入(Analysis 尚未绑定 Layout)只回填本身,派生写入则
|
||||
克隆安全摘要并将新 ID 写回该 Layout。
|
||||
"""
|
||||
payload = version.payload_json if isinstance(version.payload_json, dict) else {}
|
||||
capability = payload.get('xfa_capability') if isinstance(payload.get('xfa_capability'), dict) else {}
|
||||
raw_analysis_id = capability.get('structure_analysis_id')
|
||||
if raw_analysis_id in (None, ''):
|
||||
return
|
||||
try:
|
||||
analysis = db.session.get(ShippingXfaStructureAnalysis, int(raw_analysis_id))
|
||||
except (TypeError, ValueError):
|
||||
return
|
||||
if analysis is None or int(analysis.document_id) != int(document.id):
|
||||
return
|
||||
if str(analysis.analysis_status or '') != 'ready':
|
||||
return
|
||||
if str(analysis.source_content_hash or '').lower() != str(document.content_hash or '').lower():
|
||||
return
|
||||
if analysis.layout_version_id in (None, ''):
|
||||
analysis.layout_version_id = int(version.id)
|
||||
return
|
||||
if int(analysis.layout_version_id) == int(version.id):
|
||||
return
|
||||
|
||||
# [STEP 1] 派生 Layout 不能窃取旧 Analysis 的 Layout 身份;复制的仅是脱敏结构摘要。
|
||||
localized = ShippingXfaStructureAnalysis(
|
||||
document_id=int(document.id),
|
||||
layout_version_id=int(version.id),
|
||||
source_content_hash=str(document.content_hash or '').lower(),
|
||||
document_kind=analysis.document_kind,
|
||||
analysis_status='ready',
|
||||
template_packet_checksum=analysis.template_packet_checksum,
|
||||
datasets_packet_checksum=analysis.datasets_packet_checksum,
|
||||
dataset_structure_fingerprint=analysis.dataset_structure_fingerprint,
|
||||
packet_checksums_json=dict(analysis.packet_checksums_json or {}),
|
||||
stats_json=dict(analysis.stats_json or {}),
|
||||
security_summary_json=dict(analysis.security_summary_json or {}),
|
||||
tree_summary_json=dict(analysis.tree_summary_json or {}),
|
||||
error_code=None,
|
||||
route_reason=analysis.route_reason,
|
||||
encrypted_snapshot_ref=None,
|
||||
parser_identity=analysis.parser_identity,
|
||||
contract_version=analysis.contract_version,
|
||||
finished_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(localized)
|
||||
db.session.flush()
|
||||
|
||||
# [STEP 2] 重算 checksum,保证 Layout 载荷和结构分析 ID 仍是同一不可变身份。
|
||||
localized_capability = dict(capability)
|
||||
localized_capability['structure_analysis_id'] = int(localized.id)
|
||||
localized_payload = dict(payload)
|
||||
localized_payload['xfa_capability'] = localized_capability
|
||||
if isinstance(localized_payload.get('capability'), dict):
|
||||
localized_payload['capability'] = {
|
||||
**dict(localized_payload['capability']),
|
||||
'structure_analysis_id': int(localized.id),
|
||||
}
|
||||
checksum, payload_size = canonical_layout_payload(localized_payload)
|
||||
version.payload_json = localized_payload
|
||||
version.payload_checksum = checksum
|
||||
version.payload_size_bytes = payload_size
|
||||
version.quality_json = (
|
||||
dict(localized_payload['capability'])
|
||||
if isinstance(localized_payload.get('capability'), dict) else version.quality_json
|
||||
)
|
||||
|
||||
|
||||
def ensure_inline_xfa_structure_analysis_identity(
|
||||
*,
|
||||
document: ShippingOrderDocument,
|
||||
version: ShippingDocumentLayoutVersion,
|
||||
) -> ShippingDocumentLayoutVersion:
|
||||
"""确保当前 inline Layout 的 XFA Analysis 与其自身版本号一致。
|
||||
|
||||
Profile 冻结会直接读取当前 ready Layout;历史坐标补证版本即使已存在,也必须
|
||||
在该正式冻结边界完成 analysis identity 本地化,不能依赖再次生成同一快照。
|
||||
"""
|
||||
if str(version.status or '') in CURRENT_LAYOUT_STATUSES:
|
||||
_bind_inline_xfa_structure_analysis(document=document, version=version)
|
||||
return version
|
||||
|
||||
|
||||
def record_inline_layout_snapshot(
|
||||
document: ShippingOrderDocument,
|
||||
snapshot: dict[str, Any],
|
||||
@@ -248,6 +342,9 @@ def record_inline_layout_snapshot(
|
||||
)
|
||||
if existing is not None:
|
||||
if existing.status in CURRENT_LAYOUT_STATUSES:
|
||||
# 历史坐标补证快照可能在 XFA Analysis 身份本地化修复前已经落库;
|
||||
# 复用时补齐同一 Layout 的 Analysis,避免冻结样本永久卡在旧 identity。
|
||||
ensure_inline_xfa_structure_analysis_identity(document=document, version=existing)
|
||||
document.current_layout_version_id = existing.id
|
||||
return existing
|
||||
|
||||
@@ -289,6 +386,8 @@ def record_inline_layout_snapshot(
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
if status in CURRENT_LAYOUT_STATUSES:
|
||||
ensure_inline_xfa_structure_analysis_identity(document=document, version=version)
|
||||
if status in CURRENT_LAYOUT_STATUSES:
|
||||
document.current_layout_version_id = version.id
|
||||
return version
|
||||
@@ -411,7 +510,11 @@ def _clone_reusable_layout_for_document(
|
||||
target_analysis: ShippingXfaStructureAnalysis | None = None
|
||||
source_analysis: ShippingXfaStructureAnalysis | None = None
|
||||
reject_reason: str | None = None
|
||||
if str(copied_payload.get('provider') or '') == 'xfa':
|
||||
# XFA structure analysis is document-scoped evidence. Both the retired
|
||||
# XFA-only snapshot format and the current shared visual Layout carry it in
|
||||
# xfa_capability, so reuse must localize it by capability rather than by
|
||||
# the layout provider.
|
||||
if isinstance(copied_payload.get('xfa_capability'), dict):
|
||||
capability = (
|
||||
copied_payload.get('xfa_capability')
|
||||
if isinstance(copied_payload.get('xfa_capability'), dict)
|
||||
|
||||
@@ -38,7 +38,7 @@ class OrderFieldExtraction(BaseModel):
|
||||
scope: Literal['header']
|
||||
value: Any = None
|
||||
status: Literal['confirmed', 'needs_review', 'unavailable']
|
||||
source: Literal['pdf_coordinate', 'ocr_coordinate'] | None = None
|
||||
source: Literal['pdf_coordinate', 'ocr_coordinate', 'acroform_widget'] | None = None
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
anchor_bbox: LayoutBBox | None = None
|
||||
value_bbox: LayoutBBox | None = None
|
||||
@@ -48,7 +48,7 @@ class OrderFieldExtraction(BaseModel):
|
||||
|
||||
def extract_order_fields(
|
||||
*, profile: OrderCoordinateProfile, schema_fields: dict[str, dict[str, Any]],
|
||||
coordinate_evidence: dict[str, Any],
|
||||
coordinate_evidence: dict[str, Any], allow_ocr_preview_fallback: bool = False,
|
||||
) -> list[OrderFieldExtraction]:
|
||||
"""
|
||||
用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。
|
||||
@@ -57,18 +57,26 @@ def extract_order_fields(
|
||||
profile: Run 冻结的坐标模板,不得包含待重新绑定字段。
|
||||
schema_fields: 以 stable field_id 为键的冻结启用 Schema 字段。
|
||||
coordinate_evidence: 冻结页尺寸、page_glyphs 与来源;不接受表格内 glyph 兜底。
|
||||
allow_ocr_preview_fallback: 仅管理端视觉样本值预览可启用。它允许已确认的
|
||||
PDF 坐标字段临时读取 OCR 候选,但结果仍固定为 needs_review,不能用于正式运行时取值。
|
||||
|
||||
Returns:
|
||||
每个已绑定布局对应一个候选,按模板声明顺序返回。
|
||||
"""
|
||||
return [
|
||||
_extract_layout(layout=layout, schema_fields=schema_fields, coordinate_evidence=coordinate_evidence)
|
||||
_extract_layout(
|
||||
layout=layout,
|
||||
schema_fields=schema_fields,
|
||||
coordinate_evidence=coordinate_evidence,
|
||||
allow_ocr_preview_fallback=allow_ocr_preview_fallback,
|
||||
)
|
||||
for layout in profile.order_field_layouts
|
||||
]
|
||||
|
||||
|
||||
def _extract_layout(
|
||||
*, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any],
|
||||
allow_ocr_preview_fallback: bool = False,
|
||||
) -> OrderFieldExtraction:
|
||||
"""处理一个订单字段布局,并把任何不确定性保留为 Review/Unavailable 而非猜测。"""
|
||||
config = schema_fields.get(layout.field_id)
|
||||
@@ -104,7 +112,12 @@ def _extract_layout(
|
||||
|
||||
results: list[OrderFieldExtraction] = []
|
||||
for page_no, glyphs, width, height, source in candidates:
|
||||
if not _source_allowed(layout, config=config, source=source):
|
||||
if not _source_allowed(
|
||||
layout,
|
||||
config=config,
|
||||
source=source,
|
||||
allow_ocr_preview_fallback=allow_ocr_preview_fallback,
|
||||
):
|
||||
results.append(_unavailable(layout, 'order_field_coordinate_source_not_allowed', page_no=page_no, source=source))
|
||||
continue
|
||||
if layout.anchor is None:
|
||||
@@ -441,8 +454,16 @@ def _layout_applies_to_page(layout: OrderFieldLayout, page_no: int) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _source_allowed(layout: OrderFieldLayout, *, config: dict[str, Any], source: str) -> bool:
|
||||
"""同时满足布局和 Schema 的坐标来源授权,OCR 永远不提升为 confirmed。"""
|
||||
def _source_allowed(
|
||||
layout: OrderFieldLayout,
|
||||
*,
|
||||
config: dict[str, Any],
|
||||
source: str,
|
||||
allow_ocr_preview_fallback: bool = False,
|
||||
) -> bool:
|
||||
"""同时满足布局和 Schema 的坐标来源授权;仅样本预览可临时展示 OCR 候选。"""
|
||||
if source == 'ocr_coordinate' and allow_ocr_preview_fallback:
|
||||
return True
|
||||
allowed = set(config.get('allowed_sources') or [])
|
||||
if source not in allowed:
|
||||
return False
|
||||
|
||||
@@ -254,6 +254,11 @@ class TableRegionProfile(OrderProfileModel):
|
||||
line_start_field_code: str = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
# 默认沿用既有固定物理子行;自适应模式仅在模板显式选择时允许字段跨视觉行匹配。
|
||||
row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows'
|
||||
# 人工确认本表区自动标注时采用的视觉几何来源;仅用于审计、盲测和冲突复核,
|
||||
# 不参与普通 PDF/XFA 的正式字段取值,更不能替代 XFA datasets。
|
||||
visual_evidence_source: Literal[
|
||||
'pdf_coordinate', 'ocr_coordinate', 'opencv_geometry', 'acroform_widget_geometry',
|
||||
] | None = None
|
||||
header_layouts: list[HeaderLayout] = Field(default_factory=list)
|
||||
line_layouts: list[LineLayout] = Field(default_factory=list)
|
||||
continuation_rule: ContinuationRule = Field(default_factory=ContinuationRule)
|
||||
|
||||
@@ -4,7 +4,8 @@ services/shipping_notice/document_layout/order_profile_extractors.py
|
||||
用途:执行订单坐标 Profile v2 的有限注册字段解析器。
|
||||
依赖:订单料号复合解析与数值解析。
|
||||
逻辑:坐标重建先取得管理员框选的原文,本模块再将其安全拆成固定业务字段;任何拆分失败均不返回部分字段。
|
||||
另提供 XFA/坐标共用的 ``unit_price / price_unit``(如 ``898.72 / 1``)确定性拆分。
|
||||
单价、价格单位等业务字段必须由管理员分别框选,或通过 XFA 显式拆分规则映射;
|
||||
本模块不按值形态隐式生成 Schema 字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,44 +20,9 @@ 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()
|
||||
@@ -92,8 +58,6 @@ 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 {}
|
||||
|
||||
|
||||
@@ -109,6 +73,4 @@ 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()
|
||||
@@ -672,24 +672,11 @@ def _observe_layout_features(
|
||||
if width > 0 and height > 0:
|
||||
aspect_ratio = width / height
|
||||
|
||||
primary_bbox = None
|
||||
if tables:
|
||||
bbox = tables[0].get('bbox') if isinstance(tables[0].get('bbox'), dict) else None
|
||||
if isinstance(bbox, dict):
|
||||
try:
|
||||
primary_bbox = [
|
||||
float(bbox.get('x0', 0)), float(bbox.get('y0', 0)),
|
||||
float(bbox.get('x1', 1)), float(bbox.get('y1', 1)),
|
||||
]
|
||||
if max(primary_bbox) > 1 and isinstance(first_page, dict):
|
||||
page_width, page_height = float(first_page.get('width') or 0), float(first_page.get('height') or 0)
|
||||
if page_width > 0 and page_height > 0:
|
||||
primary_bbox = [
|
||||
primary_bbox[0] / page_width, primary_bbox[1] / page_height,
|
||||
primary_bbox[2] / page_width, primary_bbox[3] / page_height,
|
||||
]
|
||||
except (TypeError, ValueError):
|
||||
primary_bbox = None
|
||||
# [STEP 1] 与签名生成一致,按签名表区选择实际业务表;MinerU 的 tables[0]
|
||||
# 可能是抬头/元数据表,不能作为运行时默认主表。
|
||||
primary_bbox = _select_signature_primary_table_bbox(
|
||||
tables=tables, pages=pages, signature=signature,
|
||||
)
|
||||
|
||||
header_tokens, column_centers, column_width_ratios = _observe_primary_table_header(
|
||||
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
@@ -712,6 +699,60 @@ def _observe_layout_features(
|
||||
}
|
||||
|
||||
|
||||
def _select_signature_primary_table_bbox(
|
||||
*, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None,
|
||||
) -> list[float] | None:
|
||||
"""按签名表区选取重叠最大的实际表;无可用签名时才保持首表兼容行为。"""
|
||||
normalized_tables: list[list[float]] = []
|
||||
for table in tables:
|
||||
page = pages.get(str(table.get('page_no') or 1)) or pages.get(table.get('page_no') or 1)
|
||||
bbox = table.get('bbox') if isinstance(table.get('bbox'), dict) else None
|
||||
if not isinstance(page, dict) or not isinstance(bbox, dict):
|
||||
continue
|
||||
try:
|
||||
raw = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')]
|
||||
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if raw[2] <= raw[0] or raw[3] <= raw[1] or width <= 0 or height <= 0:
|
||||
continue
|
||||
normalized_tables.append(raw if max(raw) <= 1 else [
|
||||
raw[0] / width, raw[1] / height, raw[2] / width, raw[3] / height,
|
||||
])
|
||||
if not normalized_tables:
|
||||
return None
|
||||
patterns = [
|
||||
item for item in ((signature or {}).get('table_patterns') or [])
|
||||
if isinstance(item, dict)
|
||||
and isinstance(item.get('bbox'), dict)
|
||||
and isinstance(item['bbox'].get('median'), list)
|
||||
and len(item['bbox']['median']) == 4
|
||||
]
|
||||
if not patterns:
|
||||
return normalized_tables[0]
|
||||
best_bbox = normalized_tables[0]
|
||||
best_overlap = -1.0
|
||||
for candidate in normalized_tables:
|
||||
for pattern in patterns:
|
||||
try:
|
||||
expected = [float(value) for value in pattern['bbox']['median']]
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
overlap = _bbox_overlap(expected, candidate)
|
||||
if overlap > best_overlap:
|
||||
best_overlap, best_bbox = overlap, candidate
|
||||
return best_bbox
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
_HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+')
|
||||
|
||||
|
||||
|
||||
@@ -43,53 +43,6 @@ 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
|
||||
@@ -124,16 +77,6 @@ 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:
|
||||
_record_xfa_page_count(xfa_snapshot, diagnostics=diagnostics)
|
||||
return xfa_snapshot
|
||||
native_pages: list[Any] | None = None
|
||||
if extension == '.pdf' and document_id and content_hash:
|
||||
try:
|
||||
@@ -408,32 +351,6 @@ def _diagnostics_from_maps(
|
||||
)
|
||||
|
||||
|
||||
def _record_xfa_page_count(
|
||||
snapshot: dict[str, Any],
|
||||
*,
|
||||
diagnostics: LayoutJobDiagnostics | None,
|
||||
) -> None:
|
||||
"""
|
||||
XFA 早退路径仅回填可安全取得的 page_count,不引入 OCR/OpenCV 逻辑。
|
||||
|
||||
Args:
|
||||
snapshot: XFA layout 快照。
|
||||
diagnostics: 可选诊断上下文。
|
||||
"""
|
||||
if diagnostics is None:
|
||||
return
|
||||
capability = snapshot.get('xfa_capability') if isinstance(snapshot.get('xfa_capability'), dict) else {}
|
||||
page_count = capability.get('page_count')
|
||||
if page_count is None:
|
||||
pages = snapshot.get('pages')
|
||||
if isinstance(pages, list):
|
||||
page_count = len(pages)
|
||||
try:
|
||||
diagnostics.counts['page_count'] = int(page_count or 0)
|
||||
except (TypeError, ValueError):
|
||||
diagnostics.counts['page_count'] = 0
|
||||
|
||||
|
||||
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,
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/document_layout/xfa_acroform.py
|
||||
|
||||
用途:读取 AcroForm 字段值/Widget 几何,并生成与 datasets 叶子节点的对账与路径候选。
|
||||
依赖:pypdf、xfa_dataset.XfaDatasetAnalysis、xfa_contract.hash_data_path。
|
||||
逻辑:由 xfa_analysis、xfa_visual_binding、xfa_validation 调用;按短名聚合多实例值
|
||||
逻辑:由 xfa_analysis、datasets 末端映射和 xfa_validation 调用;按短名聚合多实例值
|
||||
供行对齐对账;Widget 摘要含页码与归一化 bbox,供统一视觉绑定评分。
|
||||
"""
|
||||
|
||||
|
||||
@@ -307,6 +307,23 @@ def persist_xfa_structure_analysis(
|
||||
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)
|
||||
# [STEP 2] Layout 与 datasets identity 必须落在同一冻结快照;仅更新 outcome
|
||||
# 会导致后续 Profile/盲测按 Layout 重放时找不到本次 structure analysis。
|
||||
if layout_version_id:
|
||||
layout_version = db.session.get(ShippingDocumentLayoutVersion, int(layout_version_id))
|
||||
if layout_version is not None:
|
||||
payload = dict(layout_version.payload_json or {})
|
||||
capability_payload = payload.get('xfa_capability')
|
||||
if not isinstance(capability_payload, dict):
|
||||
capability_payload = dict(payload.get('capability') or {})
|
||||
capability_payload['structure_analysis_id'] = int(record.id)
|
||||
payload['xfa_capability'] = capability_payload
|
||||
if isinstance(payload.get('capability'), dict):
|
||||
payload['capability'] = {
|
||||
**dict(payload['capability']),
|
||||
'structure_analysis_id': int(record.id),
|
||||
}
|
||||
layout_version.payload_json = payload
|
||||
outcome.analysis_record = record
|
||||
return record
|
||||
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
services/shipping_notice/document_layout/xfa_contract.py
|
||||
|
||||
用途:冻结 XFA 数据路径 Profile 契约——template_mode、受控路径语法、结构指纹、
|
||||
统一字段 binding(value_binding + visual_binding)、鉴别联合 definition、
|
||||
统一字段 binding(共同视觉 field_layout_id + value_binding)、鉴别联合 definition、
|
||||
evidence 与安全投影、合成预览审计事件与错误码注册。
|
||||
依赖:Pydantic 2、标准库 hashlib/json/re/unicodedata;被 order_extraction_route_contract、
|
||||
Profile 校验、拆分契约、xfa_preview_* 与后续 xfa_*.py 解析器引用。
|
||||
逻辑:本模块只定义契约与纯函数校验,不读 PDF/XML、不执行脚本、不接正式流量;
|
||||
禁止混入 coordinate 表区键,但允许 visual_binding 归一化框作为视觉证据。
|
||||
共同视觉布局与末端 datasets 映射分层,历史 visual_binding 仅兼容读取。
|
||||
header_mappings / line_mapping.fields 仅作**迁移输入**解析(order_profile_unified_migration);
|
||||
正式 validate/save/extract 须 bindings-only,legacy-only 或 dual-source 均 fail-closed。
|
||||
"""
|
||||
@@ -28,9 +28,9 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida
|
||||
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'
|
||||
# Historical ``xfa_structure_signature`` Run records remain readable through the
|
||||
# ORM enum/migration compatibility path. New code must use the common
|
||||
# ``layout_signature`` lifecycle and must not introduce a second XFA signature.
|
||||
|
||||
OrderProfileTemplateMode = Literal['coordinate', 'xfa_dataset']
|
||||
ORDER_PROFILE_TEMPLATE_MODES: Final[frozenset[str]] = frozenset({
|
||||
@@ -144,12 +144,6 @@ XFA_ERROR_CODES: Final[frozenset[str]] = frozenset({
|
||||
'XFA_SPLIT_RULE_INVALID',
|
||||
'XFA_SPLIT_FIELD_CONFLICT',
|
||||
'XFA_SPLIT_MIRROR_MISMATCH',
|
||||
# 合成预览(阶段 1 POC)
|
||||
'XFA_PREVIEW_STALE',
|
||||
'XFA_PREVIEW_FAILED',
|
||||
'XFA_PREVIEW_UNAVAILABLE',
|
||||
'XFA_PREVIEW_PAGE_INCONSISTENT',
|
||||
'XFA_PREVIEW_VALUE_MISMATCH',
|
||||
})
|
||||
|
||||
XFA_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
@@ -176,22 +170,13 @@ XFA_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_split_field_conflict',
|
||||
'xfa_split_mirror_mismatch',
|
||||
# 统一视觉绑定 / 发布门禁 / 运行时再验(阶段 5–6)
|
||||
'xfa_visual_bindings_required',
|
||||
'xfa_visual_binding_incomplete',
|
||||
'xfa_mapping_required',
|
||||
'xfa_visual_coverage_insufficient',
|
||||
'xfa_evidence_retention_insufficient',
|
||||
'xfa_mirror_consistency_insufficient',
|
||||
'xfa_profile_checksum_mismatch',
|
||||
'xfa_visual_not_publishable',
|
||||
'xfa_split_rule_unconfirmed',
|
||||
# 合成预览发布门禁(阶段 5)
|
||||
'xfa_synthetic_preview_not_ready',
|
||||
'xfa_preview_render_checksum_missing',
|
||||
'xfa_preview_pages_incomplete',
|
||||
'xfa_preview_page_box_invalid',
|
||||
'xfa_ocr_unresolved_mismatch',
|
||||
'xfa_preview_checksum_drift',
|
||||
'xfa_preview_renderer_version_mismatch',
|
||||
})
|
||||
|
||||
XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
@@ -221,11 +206,6 @@ XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_cross_check_completed',
|
||||
'xfa_structure_signature_frozen',
|
||||
'xfa_audit_snapshot_viewed',
|
||||
# 统一视觉绑定(阶段 2)
|
||||
'xfa_visual_binding_suggested',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
# 字段拆分映射审计(阶段 3/7)
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_split_rule_previewed',
|
||||
@@ -235,26 +215,16 @@ XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'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_value_adapter_extracted',
|
||||
'profile_value_adapter_needs_review',
|
||||
# 统一 binding 一次性迁移(阶段 7)
|
||||
'order_profile_unified_migration_dry_run',
|
||||
'order_profile_unified_migration_executed',
|
||||
# 合成预览(阶段 1 POC)
|
||||
'xfa_preview_requested',
|
||||
'xfa_preview_generated',
|
||||
'xfa_preview_failed',
|
||||
'xfa_preview_viewed',
|
||||
'xfa_preview_stale',
|
||||
# OCR 自动标记建议(阶段 3)
|
||||
'xfa_ocr_started',
|
||||
'xfa_ocr_completed',
|
||||
'xfa_ocr_failed',
|
||||
})
|
||||
|
||||
# Profile / Run / 分析 DTO 禁止键(大小写不敏感);完整 XML / PDF bytes / 存储地址不得外泄。
|
||||
@@ -314,22 +284,29 @@ class XfaContractModel(BaseModel):
|
||||
|
||||
|
||||
class XfaSourceContract(XfaContractModel):
|
||||
"""冻结 XFA 模板结构身份:packet checksum + 结构指纹 + 权威集合路径。"""
|
||||
"""冻结 XFA 模板结构身份;权威集合在草稿的末端值映射阶段才配置。"""
|
||||
|
||||
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)
|
||||
authoritative_line_collection_path: str | None = Field(default=None, 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:
|
||||
"""校验必填受控路径语法。"""
|
||||
"""校验 datasets 根路径语法。"""
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
@field_validator('authoritative_line_collection_path', mode='before')
|
||||
@classmethod
|
||||
def validate_optional_authoritative_path(cls, value: Any) -> str | None:
|
||||
"""草稿允许未配置 datasets 行集合;发布前由统一门禁 fail-closed。"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
@field_validator('mirror_collection_paths', mode='before')
|
||||
@@ -395,13 +372,15 @@ class XfaLineMapping(XfaContractModel):
|
||||
Execute 后须为空,正式值绑定仅经 bindings[]。
|
||||
"""
|
||||
|
||||
row_path: str = Field(min_length=1, max_length=512)
|
||||
row_path: str | None = Field(default=None, 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:
|
||||
"""行集合路径必须通过受控语法。"""
|
||||
def validate_row_path(cls, value: Any) -> str | None:
|
||||
"""草稿可暂未配置行集合,正式提取前必须由发布门禁补齐。"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
|
||||
@@ -418,6 +397,9 @@ class XfaCrossChecks(XfaContractModel):
|
||||
# 统一字段绑定(value_binding + visual_binding)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# ``bindings[]`` 是所有 Profile 共用的末端取值 DTO;具体 adapter 的 Profile
|
||||
# 契约再收紧允许类型。这样坐标/OCR 与 datasets 共用编辑、审计和迁移结构,
|
||||
# 同时 XFA 不会把视觉证据误作正式值。
|
||||
XfaValueBindingType = Literal['xfa_dataset', 'pdf_coordinate', 'ocr_coordinate']
|
||||
XfaVisualBindingSource = Literal[
|
||||
'acroform_widget',
|
||||
@@ -456,7 +438,7 @@ class XfaNormalizedBBox(XfaContractModel):
|
||||
|
||||
|
||||
class XfaValueBinding(XfaContractModel):
|
||||
"""正式值绑定:XFA 仅允许 datasets 路径;普通 PDF 允许坐标/OCR。"""
|
||||
"""共同正式值绑定;XFA Profile 的上层契约仍只允许 datasets 路径。"""
|
||||
|
||||
type: XfaValueBindingType
|
||||
path_id: str | None = Field(default=None, max_length=128)
|
||||
@@ -485,7 +467,7 @@ class XfaValueBinding(XfaContractModel):
|
||||
|
||||
|
||||
class XfaVisualBinding(XfaContractModel):
|
||||
"""视觉绑定:页码 + 归一化框 + 确认状态;正式字段发布前须 confirmed。
|
||||
"""视觉绑定:页码 + 归一化框 + 确认状态;正式字段发布前须原生页 confirmed。
|
||||
|
||||
合成预览确认证据(阶段 4+):confirmed 时须携带 preview_render_checksum /
|
||||
render_mode=xfa_dataset_preview / confirmed_on=xfa_dataset_preview。
|
||||
@@ -516,21 +498,23 @@ class XfaUnifiedFieldBinding(XfaContractModel):
|
||||
"""
|
||||
统一字段绑定:同一 Schema 字段在同一作用域最多一个正式来源。
|
||||
|
||||
核心逻辑:value_binding 决定正式取值;visual_binding 决定页面证据;
|
||||
split_rule_ref 可选指向已确认拆分段。
|
||||
核心逻辑:value_binding 决定正式取值;field_layout_id 指向共同订单字段标签
|
||||
(order_field_layouts),不重复保存或确认一套 XFA 专属值框;split_rule_ref
|
||||
可选指向已确认拆分段。visual_binding 仅用于读取历史草稿,禁止新保存依赖它。
|
||||
"""
|
||||
|
||||
binding_id: str = Field(min_length=8, max_length=64)
|
||||
field_id: str = Field(min_length=1, max_length=64)
|
||||
field_code: str = Field(min_length=1, max_length=128)
|
||||
scope: XfaBindingScope
|
||||
field_layout_id: str | None = Field(default=None, min_length=1, max_length=128)
|
||||
value_binding: XfaValueBinding
|
||||
visual_binding: XfaVisualBinding
|
||||
visual_binding: XfaVisualBinding | None = None
|
||||
split_rule_ref: XfaSplitRuleRef | None = None
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_xfa_scope_value_type(self) -> 'XfaUnifiedFieldBinding':
|
||||
"""同模板允许字段级混合数据源;具体约束由 value_binding / 发布门禁执行。"""
|
||||
def validate_shared_scope_value_type(self) -> 'XfaUnifiedFieldBinding':
|
||||
"""统一 binding 本身不判模板类型;XFA Profile 上层单独拒绝坐标取值。"""
|
||||
return self
|
||||
|
||||
|
||||
@@ -539,9 +523,8 @@ def is_formal_binding_publishable(binding: XfaUnifiedFieldBinding) -> bool:
|
||||
判断统一绑定是否满足发布门禁(字段级混合数据源口径)。
|
||||
|
||||
核心逻辑:
|
||||
- xfa_dataset:正式 path 已配置即可发布(视觉框可选);
|
||||
- pdf_coordinate / ocr_coordinate:必须视觉 confirmed;
|
||||
- 旧合成预览确认(confirmed_on/render_mode=xfa_dataset_preview)视为未重确认。
|
||||
- xfa_dataset:正式 path 配置完毕;视觉存在性由共同 order_field_layouts 门禁处理;
|
||||
- 历史 visual_binding 不再作为新草稿的发布前提。
|
||||
|
||||
Args:
|
||||
binding: 统一字段绑定。
|
||||
@@ -550,17 +533,9 @@ def is_formal_binding_publishable(binding: XfaUnifiedFieldBinding) -> bool:
|
||||
满足对应类型发布条件时为 True。
|
||||
"""
|
||||
value_type = binding.value_binding.type
|
||||
visual = binding.visual_binding
|
||||
confirmed_on = str(visual.confirmed_on or '').strip()
|
||||
render_mode = str(visual.render_mode or '').strip()
|
||||
# 旧 flatten/synthetic 坐标系确认框须在原生 PDF 画布重确认。
|
||||
if visual.status == 'confirmed' and (
|
||||
confirmed_on == 'xfa_dataset_preview' or render_mode == 'xfa_dataset_preview'
|
||||
):
|
||||
return False
|
||||
if value_type == 'xfa_dataset':
|
||||
return bool(binding.value_binding.path_id and binding.value_binding.data_path)
|
||||
return visual.status == 'confirmed'
|
||||
return value_type in {'pdf_coordinate', 'ocr_coordinate'} and bool(binding.value_binding.region_id)
|
||||
|
||||
|
||||
def canonical_unified_bindings_payload(
|
||||
@@ -591,10 +566,20 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
xfa_dataset 模式的鉴别联合 definition。
|
||||
|
||||
核心逻辑:header_mappings / line_mapping.fields 仅迁移输入(须 bindings-only 正式运行);
|
||||
validate 拒绝 legacy-only 与 dual-source;拒绝 coordinate 表区键;可选 split_rules。
|
||||
validate 拒绝 legacy-only 与 dual-source;保留共同视觉匹配契约;可选 split_rules。
|
||||
"""
|
||||
|
||||
template_mode: Literal['xfa_dataset'] = 'xfa_dataset'
|
||||
# 统一视觉 Layout 的主表身份;正式明细模板必须先冻结该身份,
|
||||
# datasets 只负责字段最终取值,不再替代视觉表格建模。
|
||||
# 历史已发布版本在迁移前可能没有该键;创建/发布入口分别负责拒绝未补齐的草稿,
|
||||
# 契约层保持可读,避免历史冻结快照无法审计。
|
||||
main_table_id: str | None = Field(default=None, min_length=1, max_length=128)
|
||||
# 所有模板共享的视觉候选选择契约。它只决定“哪个 Profile”,绝不参与 XFA 最终取值。
|
||||
document_match: dict[str, Any] | None = None
|
||||
table_regions: list[dict[str, Any]] = Field(default_factory=list)
|
||||
order_field_layouts: list[dict[str, Any]] = Field(default_factory=list)
|
||||
draft_unbound_order_field_layouts: list[dict[str, Any]] = Field(default_factory=list)
|
||||
source_contract: XfaSourceContract
|
||||
# 迁移输入兼容:禁止正式运行时单独携带非空 legacy mappings(须 bindings-only)。
|
||||
header_mappings: list[XfaHeaderMapping] = Field(default_factory=list)
|
||||
@@ -602,26 +587,21 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
bindings: list[XfaUnifiedFieldBinding] = Field(default_factory=list)
|
||||
cross_checks: XfaCrossChecks = Field(default_factory=XfaCrossChecks)
|
||||
split_rules: list[dict[str, Any]] = Field(default_factory=list)
|
||||
# 合成预览摘要(可选;发布门禁优先读取 status / preview_render_checksum)
|
||||
# 仅为读取已存历史草稿而保留;运行时、确认和发布均不读取此字段。
|
||||
xfa_preview: dict[str, Any] | None = None
|
||||
# OCR 自动标记摘要(可选;未解决 mismatch 计数供发布门禁读取)
|
||||
xfa_ocr_automark: dict[str, Any] | None = None
|
||||
|
||||
@model_validator(mode='before')
|
||||
@classmethod
|
||||
def reject_coordinate_keys(cls, data: Any) -> Any:
|
||||
"""
|
||||
拒绝 coordinate 表区 / layout 键混入 XFA definition。
|
||||
拒绝已废弃 coordinate 重建键混入 XFA definition。
|
||||
|
||||
注意:不拒绝 visual_binding / normalized_bbox(统一绑定的视觉证据)。
|
||||
注意:共同视觉 matcher 的 document_match/table_regions 是合法键;
|
||||
共同视觉布局字段是合法键;历史 visual_binding 仅兼容读取。
|
||||
"""
|
||||
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',
|
||||
@@ -654,13 +634,81 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
mapping_ids.append(item.mapping_id)
|
||||
binding_ids: list[str] = []
|
||||
binding_field_keys: list[tuple[str, str]] = []
|
||||
rule_sets = parse_split_rule_sets(self.split_rules)
|
||||
split_segments = {
|
||||
str(rule.segment.segment_id): {
|
||||
'source_path_id': str(rule_set.source_path_id),
|
||||
'target_field_code': str(rule.segment.target_field_code or ''),
|
||||
}
|
||||
for rule_set in rule_sets
|
||||
for rule in rule_set.rules
|
||||
if rule.segment.handling == 'mapped'
|
||||
}
|
||||
shared_layouts = {
|
||||
str(item.get('layout_id') or '').strip(): item
|
||||
for item in self.order_field_layouts
|
||||
if isinstance(item, dict) and str(item.get('layout_id') or '').strip()
|
||||
}
|
||||
for table in self.table_regions:
|
||||
if not isinstance(table, dict):
|
||||
continue
|
||||
for line in table.get('line_layouts') or []:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
for field in line.get('field_regions') or []:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
layout_id = str(
|
||||
field.get('region_id')
|
||||
or field.get('layout_id')
|
||||
or f"{line.get('layout_id') or ''}:{field.get('field_code') or ''}"
|
||||
).strip(':')
|
||||
if layout_id:
|
||||
shared_layouts[layout_id] = {**field, 'scope': 'line'}
|
||||
for binding in self.bindings:
|
||||
# 硬冻结(2026-08-07):同模板允许 xfa_dataset / pdf_coordinate / ocr_coordinate 混用。
|
||||
if binding.value_binding.type not in {'xfa_dataset', 'pdf_coordinate', 'ocr_coordinate'}:
|
||||
raise ValueError(
|
||||
'OrderXfaDatasetProfile bindings must use value_binding.type in '
|
||||
'xfa_dataset|pdf_coordinate|ocr_coordinate',
|
||||
)
|
||||
if binding.value_binding.type != 'xfa_dataset':
|
||||
raise ValueError('XFA value bindings must use xfa_dataset')
|
||||
# 新定义以共同 Editor 的 order_field_layouts 为唯一视觉字段模型。
|
||||
# 没有共同布局的历史草稿仍可读取,保存与发布会在 adapter 门禁 fail-closed。
|
||||
if shared_layouts:
|
||||
layout_id = str(binding.field_layout_id or '').strip()
|
||||
if not layout_id:
|
||||
raise ValueError('field_layout_id is required when order_field_layouts are present')
|
||||
layout = shared_layouts.get(layout_id)
|
||||
if layout is None:
|
||||
raise ValueError('field_layout_id must reference an order_field_layouts entry')
|
||||
layout_field_code = str(layout.get('field_code') or '')
|
||||
if layout_field_code != binding.field_code:
|
||||
# 一个多行源值(MATNR)可以通过已确认拆分规则产出多个行字段。
|
||||
# 每个目标仍指向同一个真实 MATNR 框,避免伪造重叠视觉框。
|
||||
split_ref = binding.split_rule_ref
|
||||
segment = split_segments.get(str(split_ref.segment_id)) if split_ref else None
|
||||
is_split_target_visual_reuse = bool(
|
||||
binding.scope == 'line'
|
||||
and str(layout.get('scope') or '') == 'line'
|
||||
and binding.value_binding.type == 'xfa_dataset'
|
||||
and segment
|
||||
and segment['target_field_code'] == binding.field_code
|
||||
and segment['source_path_id'] == str(binding.value_binding.path_id or '')
|
||||
)
|
||||
if not is_split_target_visual_reuse:
|
||||
raise ValueError('field_layout_id field_code must match binding field_code')
|
||||
layout_scope = str(layout.get('scope') or 'header')
|
||||
if layout_scope != binding.scope:
|
||||
# 全单 Header 值(例如 Reservation)可被显式投影至每条明细。
|
||||
# 此时共同视觉证据必须保留其真实 Header 框,不能伪造表格内框;
|
||||
# 保存 adapter 仍会校验该 path 是当前 XFA 分析确认的 Header 叶子。
|
||||
authoritative_prefix = self.source_contract.authoritative_line_collection_path.rstrip('/') if self.source_contract.authoritative_line_collection_path else ''
|
||||
is_line_header_visual_inheritance = bool(
|
||||
binding.scope == 'line'
|
||||
and layout_scope == 'header'
|
||||
and binding.value_binding.type == 'xfa_dataset'
|
||||
and authoritative_prefix
|
||||
and binding.value_binding.data_path
|
||||
and not binding.value_binding.data_path.startswith(f'{authoritative_prefix}/')
|
||||
)
|
||||
if not is_line_header_visual_inheritance:
|
||||
raise ValueError('field_layout_id scope must match binding scope')
|
||||
binding_ids.append(binding.binding_id)
|
||||
binding_field_keys.append((binding.scope, binding.field_id))
|
||||
field_ids.append(binding.field_id)
|
||||
@@ -668,12 +716,22 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
raise ValueError('duplicate binding_id values are not allowed')
|
||||
if len(binding_field_keys) != len(set(binding_field_keys)):
|
||||
raise ValueError('duplicate Schema field_id bindings in the same scope are not allowed')
|
||||
rule_sets = parse_split_rule_sets(self.split_rules)
|
||||
split_target_field_ids: list[str] = []
|
||||
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)
|
||||
split_target_field_ids.append(rule.segment.target_field_id)
|
||||
has_legacy_mappings = bool(self.header_mappings) or bool(self.line_mapping.fields)
|
||||
if not self.source_contract.authoritative_line_collection_path and (
|
||||
self.bindings
|
||||
or has_legacy_mappings
|
||||
or self.line_mapping.row_path
|
||||
or rule_sets
|
||||
):
|
||||
raise ValueError(
|
||||
'authoritative_line_collection_required: XFA value mappings and split rules '
|
||||
'require an authoritative datasets line collection',
|
||||
)
|
||||
if self.bindings and has_legacy_mappings:
|
||||
raise ValueError(
|
||||
'xfa_dual_binding_source: bindings cannot coexist with '
|
||||
@@ -686,9 +744,17 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
)
|
||||
if len(field_ids) != len(set(field_ids)):
|
||||
raise ValueError('duplicate Schema field_id bindings are not allowed')
|
||||
# 拆分段的字段目标独立于 bindings[] 去重:同一字段的 binding 正是其共享
|
||||
# 视觉源框引用,不能被误判为双重正式取值;两个拆分段映射同一字段仍不允许。
|
||||
if len(split_target_field_ids) != len(set(split_target_field_ids)):
|
||||
raise ValueError('duplicate Schema field_id split targets 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:
|
||||
if (
|
||||
self.line_mapping.row_path
|
||||
and self.source_contract.authoritative_line_collection_path
|
||||
and self.line_mapping.row_path != self.source_contract.authoritative_line_collection_path
|
||||
):
|
||||
raise ValueError('line_mapping.row_path must equal authoritative_line_collection_path')
|
||||
object.__setattr__(
|
||||
self,
|
||||
|
||||
@@ -565,7 +565,7 @@ def serialize_tree_node(node: XfaDatasetNode, *, include_values: bool = False) -
|
||||
|
||||
Args:
|
||||
node: 数据集树节点。
|
||||
include_values: 是否包含当前管理端使用的完整样本值。
|
||||
include_values: 是否包含受控的样本展示值;不得暴露 raw_value。
|
||||
|
||||
Returns:
|
||||
安全 DTO 字典。
|
||||
@@ -583,10 +583,12 @@ def serialize_tree_node(node: XfaDatasetNode, *, include_values: bool = False) -
|
||||
'children': [serialize_tree_node(child, include_values=include_values) for child in node.children],
|
||||
}
|
||||
if include_values and node.is_leaf:
|
||||
payload['sample_value_masked'] = str(node.raw_value or '')
|
||||
payload['sample_value_display'] = str(node.raw_value or '')
|
||||
payload['display_policy'] = 'full'
|
||||
payload['can_reveal'] = False
|
||||
# 字段树是批量 DTO:即使管理端需要映射辅助,也绝不能把 datasets
|
||||
# 原文放入可缓存/可下载的树响应。完整值只能经单值受控读取与审计接口取得。
|
||||
payload['sample_value_masked'] = str(node.sample_value_masked or '')
|
||||
payload['sample_value_display'] = str(node.sample_value_display or '')
|
||||
payload['display_policy'] = str(node.display_policy or 'empty')
|
||||
payload['can_reveal'] = bool(node.can_reveal)
|
||||
payload['line_count'] = len(node.lines or [])
|
||||
return payload
|
||||
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_preview_cache.py
|
||||
|
||||
用途:XFA 合成预览进程内缓存(Phase 1 POC);按身份指纹键存取预览结果。
|
||||
依赖:threading、xfa_preview_contract.build_preview_identity_fingerprint。
|
||||
逻辑:由预览编排层调用;可选后续替换为 Redis;本模块不做 IO/渲染。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_contract import (
|
||||
PreviewIdentityContext,
|
||||
build_preview_identity_fingerprint,
|
||||
)
|
||||
|
||||
_LOCK = threading.RLock()
|
||||
_CACHE: dict[str, tuple[float, dict[str, Any]]] = {}
|
||||
_DEFAULT_TTL_SECONDS = 30 * 60
|
||||
|
||||
|
||||
def build_preview_cache_key(
|
||||
*,
|
||||
structure_analysis_id: int | str | None,
|
||||
template_packet_checksum: str,
|
||||
datasets_packet_checksum: str,
|
||||
dataset_structure_fingerprint: str,
|
||||
source_content_hash: str,
|
||||
renderer_version: str,
|
||||
) -> str:
|
||||
"""
|
||||
构造预览缓存键(analysis_id + checksums + renderer_version)。
|
||||
|
||||
核心逻辑:委托 PreviewIdentityContext 指纹,page_count/preview_render_checksum 置空
|
||||
以便在渲染前即可定位缓存槽。
|
||||
|
||||
Args:
|
||||
structure_analysis_id: 冻结结构分析 ID。
|
||||
template_packet_checksum: template packet 校验和。
|
||||
datasets_packet_checksum: datasets packet 校验和。
|
||||
dataset_structure_fingerprint: datasets 结构指纹。
|
||||
source_content_hash: 源 PDF 内容哈希。
|
||||
renderer_version: 合成器版本。
|
||||
|
||||
Returns:
|
||||
稳定十六进制缓存键。
|
||||
"""
|
||||
ctx = PreviewIdentityContext(
|
||||
document_id=None,
|
||||
layout_version_id=None,
|
||||
structure_analysis_id=structure_analysis_id,
|
||||
source_content_hash=str(source_content_hash or ''),
|
||||
template_packet_checksum=str(template_packet_checksum or ''),
|
||||
datasets_packet_checksum=str(datasets_packet_checksum or ''),
|
||||
dataset_structure_fingerprint=str(dataset_structure_fingerprint or ''),
|
||||
preview_render_checksum='',
|
||||
renderer_version=str(renderer_version or ''),
|
||||
page_count=0,
|
||||
)
|
||||
return build_preview_identity_fingerprint(ctx)
|
||||
|
||||
|
||||
def get_preview_cache(key: str) -> dict[str, Any] | None:
|
||||
"""
|
||||
读取预览缓存条目。
|
||||
|
||||
核心逻辑:持锁检查 TTL;过期则删除并返回 None。
|
||||
|
||||
Args:
|
||||
key: build_preview_cache_key 结果。
|
||||
|
||||
Returns:
|
||||
缓存的预览结果字典;未命中或过期时为 None。
|
||||
"""
|
||||
text = str(key or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
now = time.time()
|
||||
with _LOCK:
|
||||
item = _CACHE.get(text)
|
||||
if item is None:
|
||||
return None
|
||||
expires_at, payload = item
|
||||
if expires_at <= now:
|
||||
_CACHE.pop(text, None)
|
||||
return None
|
||||
return dict(payload)
|
||||
|
||||
|
||||
def set_preview_cache(
|
||||
key: str,
|
||||
value: dict[str, Any],
|
||||
*,
|
||||
ttl_seconds: int = _DEFAULT_TTL_SECONDS,
|
||||
) -> None:
|
||||
"""
|
||||
写入预览缓存条目。
|
||||
|
||||
Args:
|
||||
key: 缓存键。
|
||||
value: 可浅拷贝的预览结果字典(调用方勿放入不可序列化巨型对象以外的副作用状态)。
|
||||
ttl_seconds: 存活秒数;最小 1。
|
||||
"""
|
||||
text = str(key or '').strip()
|
||||
if not text or not isinstance(value, dict):
|
||||
return
|
||||
expires_at = time.time() + max(1, int(ttl_seconds))
|
||||
with _LOCK:
|
||||
_CACHE[text] = (expires_at, dict(value))
|
||||
|
||||
|
||||
def invalidate_preview_cache(key: str | None = None) -> None:
|
||||
"""
|
||||
使预览缓存失效。
|
||||
|
||||
核心逻辑:key 为空时清空全部;否则仅删除指定键。
|
||||
|
||||
Args:
|
||||
key: 可选缓存键;None/空串表示清空。
|
||||
"""
|
||||
with _LOCK:
|
||||
if not key:
|
||||
_CACHE.clear()
|
||||
return
|
||||
_CACHE.pop(str(key), None)
|
||||
|
||||
|
||||
def clear_preview_cache() -> None:
|
||||
"""清空全部预览缓存(测试辅助)。"""
|
||||
invalidate_preview_cache(None)
|
||||
@@ -1,185 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_preview_contract.py
|
||||
|
||||
用途:冻结 XFA 自研静态合成预览(Phase 1 POC)契约——render_mode、预览状态、
|
||||
错误码、身份上下文、审计事件名与确定性指纹辅助。
|
||||
依赖:标准库 dataclasses/hashlib/json;被 xfa_preview_renderer / xfa_preview_cache /
|
||||
后续预览 API 与审计接线引用。
|
||||
逻辑:本模块只定义纯数据与纯函数,不读 PDF、不渲染、不落库;身份字段与
|
||||
preview_render_checksum 必须与合成器输出一致,供 stale 判定与发布证据绑定。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import asdict, dataclass
|
||||
from typing import Any, Final, Literal
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 渲染模式 / 预览状态
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
RENDER_MODE: Final[str] = 'xfa_dataset_preview'
|
||||
|
||||
XfaPreviewStatus = Literal['ready', 'needs_review', 'failed', 'stale']
|
||||
XFA_PREVIEW_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'ready',
|
||||
'needs_review',
|
||||
'failed',
|
||||
'stale',
|
||||
})
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 稳定错误码(短码;AppError 层可映射为 SHIPPING.ORDER_DOCUMENT_PROFILE_*)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
XFA_PREVIEW_STALE: Final[str] = 'XFA_PREVIEW_STALE'
|
||||
XFA_PREVIEW_FAILED: Final[str] = 'XFA_PREVIEW_FAILED'
|
||||
XFA_PREVIEW_UNAVAILABLE: Final[str] = 'XFA_PREVIEW_UNAVAILABLE'
|
||||
XFA_PREVIEW_PAGE_INCONSISTENT: Final[str] = 'XFA_PREVIEW_PAGE_INCONSISTENT'
|
||||
XFA_PREVIEW_VALUE_MISMATCH: Final[str] = 'XFA_PREVIEW_VALUE_MISMATCH'
|
||||
|
||||
XFA_PREVIEW_ERROR_CODES: Final[frozenset[str]] = frozenset({
|
||||
XFA_PREVIEW_STALE,
|
||||
XFA_PREVIEW_FAILED,
|
||||
XFA_PREVIEW_UNAVAILABLE,
|
||||
XFA_PREVIEW_PAGE_INCONSISTENT,
|
||||
XFA_PREVIEW_VALUE_MISMATCH,
|
||||
})
|
||||
|
||||
# AppError / i18n 完整码(与 SHIPPING.ORDER_DOCUMENT_PROFILE_* 风格对齐)
|
||||
SHIPPING_XFA_PREVIEW_STALE: Final[str] = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_STALE'
|
||||
SHIPPING_XFA_PREVIEW_FAILED: Final[str] = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_FAILED'
|
||||
SHIPPING_XFA_PREVIEW_UNAVAILABLE: Final[str] = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_UNAVAILABLE'
|
||||
SHIPPING_XFA_PREVIEW_PAGE_INCONSISTENT: Final[str] = (
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_PAGE_INCONSISTENT'
|
||||
)
|
||||
SHIPPING_XFA_PREVIEW_VALUE_MISMATCH: Final[str] = (
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_VALUE_MISMATCH'
|
||||
)
|
||||
|
||||
XFA_PREVIEW_SHIPPING_ERROR_BY_CODE: Final[dict[str, str]] = {
|
||||
XFA_PREVIEW_STALE: SHIPPING_XFA_PREVIEW_STALE,
|
||||
XFA_PREVIEW_FAILED: SHIPPING_XFA_PREVIEW_FAILED,
|
||||
XFA_PREVIEW_UNAVAILABLE: SHIPPING_XFA_PREVIEW_UNAVAILABLE,
|
||||
XFA_PREVIEW_PAGE_INCONSISTENT: SHIPPING_XFA_PREVIEW_PAGE_INCONSISTENT,
|
||||
XFA_PREVIEW_VALUE_MISMATCH: SHIPPING_XFA_PREVIEW_VALUE_MISMATCH,
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 审计事件(预览生命周期)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
XFA_PREVIEW_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_preview_requested',
|
||||
'xfa_preview_generated',
|
||||
'xfa_preview_failed',
|
||||
'xfa_preview_viewed',
|
||||
'xfa_preview_stale',
|
||||
})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PreviewIdentityContext:
|
||||
"""
|
||||
合成预览身份上下文:发布视觉证据与 stale 判定的冻结字段集合。
|
||||
|
||||
任一关键校验和/指纹变化即视为预览身份漂移,不得继续当作 ready 证据。
|
||||
"""
|
||||
|
||||
document_id: int | None
|
||||
layout_version_id: int | None
|
||||
structure_analysis_id: int | str | None
|
||||
source_content_hash: str
|
||||
template_packet_checksum: str
|
||||
datasets_packet_checksum: str
|
||||
dataset_structure_fingerprint: str
|
||||
preview_render_checksum: str
|
||||
render_mode: str = RENDER_MODE
|
||||
renderer_version: str = ''
|
||||
page_count: int = 0
|
||||
|
||||
|
||||
def shipping_error_code_for_preview(error_code: str | None) -> str | None:
|
||||
"""
|
||||
将预览短错误码映射为 SHIPPING.ORDER_DOCUMENT_PROFILE_* AppError 码。
|
||||
|
||||
核心逻辑:查 XFA_PREVIEW_SHIPPING_ERROR_BY_CODE;未知码原样返回。
|
||||
|
||||
Args:
|
||||
error_code: 预览短错误码或已是完整 SHIPPING.* 码。
|
||||
|
||||
Returns:
|
||||
完整业务错误码;输入为空时返回 None。
|
||||
"""
|
||||
text = str(error_code or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
if text.startswith('SHIPPING.'):
|
||||
return text
|
||||
return XFA_PREVIEW_SHIPPING_ERROR_BY_CODE.get(text, text)
|
||||
|
||||
|
||||
def preview_identity_to_dict(ctx: PreviewIdentityContext) -> dict[str, Any]:
|
||||
"""
|
||||
将 PreviewIdentityContext 序列化为可审计/可缓存的普通字典。
|
||||
|
||||
Args:
|
||||
ctx: 预览身份上下文。
|
||||
|
||||
Returns:
|
||||
字段字典(不含额外派生键)。
|
||||
"""
|
||||
return asdict(ctx)
|
||||
|
||||
|
||||
def build_preview_identity_fingerprint(ctx: PreviewIdentityContext) -> str:
|
||||
"""
|
||||
计算预览身份指纹(不含 preview_render_checksum 本身,避免循环依赖)。
|
||||
|
||||
核心逻辑:对 document/layout/analysis/内容哈希/packet/结构指纹/render_mode/
|
||||
renderer_version/page_count 做稳定 JSON 序列化后 SHA-256。
|
||||
|
||||
Args:
|
||||
ctx: 预览身份上下文。
|
||||
|
||||
Returns:
|
||||
64 位十六进制指纹字符串。
|
||||
"""
|
||||
payload = {
|
||||
'document_id': ctx.document_id,
|
||||
'layout_version_id': ctx.layout_version_id,
|
||||
'structure_analysis_id': ctx.structure_analysis_id,
|
||||
'source_content_hash': str(ctx.source_content_hash or ''),
|
||||
'template_packet_checksum': str(ctx.template_packet_checksum or ''),
|
||||
'datasets_packet_checksum': str(ctx.datasets_packet_checksum or ''),
|
||||
'dataset_structure_fingerprint': str(ctx.dataset_structure_fingerprint or ''),
|
||||
'render_mode': str(ctx.render_mode or RENDER_MODE),
|
||||
'renderer_version': str(ctx.renderer_version or ''),
|
||||
'page_count': int(ctx.page_count or 0),
|
||||
}
|
||||
raw = json.dumps(payload, sort_keys=True, separators=(',', ':'), ensure_ascii=True)
|
||||
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def is_preview_identity_stale(
|
||||
*,
|
||||
expected: PreviewIdentityContext,
|
||||
actual: PreviewIdentityContext,
|
||||
) -> bool:
|
||||
"""
|
||||
判断实际预览身份是否相对期望身份已过期(stale)。
|
||||
|
||||
核心逻辑:比较身份指纹与 preview_render_checksum;任一不等即 stale。
|
||||
|
||||
Args:
|
||||
expected: 期望/冻结身份(例如绑定证据快照)。
|
||||
actual: 当前重新计算的身份。
|
||||
|
||||
Returns:
|
||||
True 表示应标记 stale 并重新生成/重确认。
|
||||
"""
|
||||
if build_preview_identity_fingerprint(expected) != build_preview_identity_fingerprint(actual):
|
||||
return True
|
||||
return str(expected.preview_render_checksum or '') != str(actual.preview_render_checksum or '')
|
||||
@@ -1,200 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_preview_renderer.py
|
||||
|
||||
用途:XFA 离线完整 flatten 入口(硬冻结 §0)。当前未接入可复现 flatten 引擎时
|
||||
一律 fail-closed 返回 needs_review;禁止静态 overlay / 壳图充当 ready。
|
||||
依赖:xfa_preview_contract;未来真实引擎须离线、禁不受控脚本、输出可复现 checksum。
|
||||
逻辑:由预览编排服务调用 compose_xfa_dataset_preview_pages;settings
|
||||
SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY=true 且引擎实现就绪后才可返回 ready。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_contract import (
|
||||
RENDER_MODE,
|
||||
XFA_PREVIEW_FAILED,
|
||||
XFA_PREVIEW_UNAVAILABLE,
|
||||
XfaPreviewStatus,
|
||||
)
|
||||
|
||||
# 版本号:v0_pending 表示尚未交付完整 flatten;不得与历史 overlay checksum 混用。
|
||||
RENDERER_VERSION = 'hxops.xfa_flatten.v0_pending'
|
||||
|
||||
|
||||
@dataclass
|
||||
class DrawnFieldEcho:
|
||||
"""单页上 flatten 回显痕迹(完整引擎就绪后使用)。"""
|
||||
|
||||
path_id: str
|
||||
value: str
|
||||
normalized_bbox: dict[str, float]
|
||||
page_no: int = 1
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaPreviewComposeResult:
|
||||
"""flatten / 预览文档级结果;status!=ready 时 pages 为空。"""
|
||||
|
||||
status: XfaPreviewStatus
|
||||
error_code: str | None
|
||||
render_mode: str
|
||||
renderer_version: str
|
||||
page_count: int
|
||||
preview_render_checksum: str | None
|
||||
pages: list[dict[str, Any]] = field(default_factory=list)
|
||||
diagnostics: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""序列化为普通字典。"""
|
||||
return {
|
||||
'status': self.status,
|
||||
'error_code': self.error_code,
|
||||
'render_mode': self.render_mode,
|
||||
'renderer_version': self.renderer_version,
|
||||
'page_count': self.page_count,
|
||||
'preview_render_checksum': self.preview_render_checksum,
|
||||
'pages': self.pages,
|
||||
'diagnostics': self.diagnostics,
|
||||
}
|
||||
|
||||
|
||||
def compute_preview_render_checksum(
|
||||
*,
|
||||
renderer_version: str,
|
||||
pages: list[dict[str, Any]],
|
||||
) -> str:
|
||||
"""
|
||||
计算可复现的预览渲染校验和。
|
||||
|
||||
核心逻辑:串联 renderer_version 与各页宽高/回显指纹/图像哈希后 SHA-256。
|
||||
|
||||
Args:
|
||||
renderer_version: 合成器版本。
|
||||
pages: 含 width/height/drawn_field_echoes/png_bytes 的页列表。
|
||||
|
||||
Returns:
|
||||
hex digest 字符串。
|
||||
"""
|
||||
parts: list[str] = [str(renderer_version or '')]
|
||||
for page in pages:
|
||||
page_no = int(page.get('page_no') or 0)
|
||||
width = float(page.get('width') or 0)
|
||||
height = float(page.get('height') or 0)
|
||||
echoes = page.get('drawn_field_echoes') if isinstance(page.get('drawn_field_echoes'), list) else []
|
||||
echo_fp = '|'.join(
|
||||
f"{item.get('path_id')}:{item.get('value')}"
|
||||
for item in echoes
|
||||
if isinstance(item, dict)
|
||||
)
|
||||
png = page.get('png_bytes')
|
||||
img_hash = ''
|
||||
if isinstance(png, (bytes, bytearray)) and png:
|
||||
img_hash = hashlib.sha256(bytes(png)).hexdigest()
|
||||
parts.append(f'{page_no}:{width}x{height}:{echo_fp}:{img_hash}')
|
||||
return hashlib.sha256('\n'.join(parts).encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def is_xfa_flatten_engine_ready() -> bool:
|
||||
"""
|
||||
完整离线 flatten 引擎是否已启用且可对外返回 ready。
|
||||
|
||||
核心逻辑:读取 settings.SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY;默认 false。
|
||||
引擎实现与人眼一致性完成前必须保持关闭。
|
||||
|
||||
Returns:
|
||||
True 仅当显式开启(当前仍无真实引擎实现,开启也不会 ready)。
|
||||
"""
|
||||
try:
|
||||
from app.core.config.settings import Settings
|
||||
|
||||
return bool(getattr(Settings, 'SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY', False))
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def attempt_offline_xfa_flatten(
|
||||
*,
|
||||
pdf_bytes: bytes,
|
||||
analysis_or_nodes: Any,
|
||||
page_boxes: list[dict[str, Any]] | None = None,
|
||||
template_bytes: bytes | None = None,
|
||||
) -> XfaPreviewComposeResult:
|
||||
"""
|
||||
尝试离线完整 XFA flatten(template + datasets → 有效 PDF/PNG)。
|
||||
|
||||
核心逻辑:硬冻结要求删除 overlay;真实引擎未交付前一律 needs_review。
|
||||
不得用 PDFium 壳图或黄框叠加冒充 ready。
|
||||
|
||||
Args:
|
||||
pdf_bytes: 源 XFA PDF 字节。
|
||||
analysis_or_nodes: datasets 分析或叶子映射(预留)。
|
||||
page_boxes: 可选期望页框(预留)。
|
||||
template_bytes: 可选 template packet(预留)。
|
||||
|
||||
Returns:
|
||||
当前恒为 needs_review / failed;未来引擎就绪后返回 ready + pages。
|
||||
"""
|
||||
del analysis_or_nodes, page_boxes, template_bytes # 真实引擎接入时启用
|
||||
if not pdf_bytes:
|
||||
return XfaPreviewComposeResult(
|
||||
status='failed',
|
||||
error_code=XFA_PREVIEW_FAILED,
|
||||
render_mode=RENDER_MODE,
|
||||
renderer_version=RENDERER_VERSION,
|
||||
page_count=0,
|
||||
preview_render_checksum=None,
|
||||
pages=[],
|
||||
diagnostics={'reason': 'empty_pdf_bytes'},
|
||||
)
|
||||
# [STEP] 完整 flatten 未交付:fail-closed(禁止 overlay ready)
|
||||
return XfaPreviewComposeResult(
|
||||
status='needs_review',
|
||||
error_code=XFA_PREVIEW_UNAVAILABLE,
|
||||
render_mode=RENDER_MODE,
|
||||
renderer_version=RENDERER_VERSION,
|
||||
page_count=0,
|
||||
preview_render_checksum=None,
|
||||
pages=[],
|
||||
diagnostics={
|
||||
'reason': 'flatten_engine_unavailable',
|
||||
'message': (
|
||||
'Offline reproducible XFA flatten is not available; '
|
||||
'shell PDF / PDFium shell / overlay must not be used as canvas source'
|
||||
),
|
||||
'flatten_engine_ready_flag': is_xfa_flatten_engine_ready(),
|
||||
'operational_status': 'OPERATIONAL_PENDING',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def compose_xfa_dataset_preview_pages(
|
||||
*,
|
||||
pdf_bytes: bytes,
|
||||
analysis_or_nodes: Any,
|
||||
page_boxes: list[dict[str, Any]] | None = None,
|
||||
template_bytes: bytes | None = None,
|
||||
) -> XfaPreviewComposeResult:
|
||||
"""
|
||||
XFA 标注图源编排入口(对外保持原函数名以兼容调用方)。
|
||||
|
||||
核心逻辑:委托 attempt_offline_xfa_flatten;未完成完整 flatten 前不得返回 ready。
|
||||
|
||||
Args:
|
||||
pdf_bytes: 源 PDF 字节。
|
||||
analysis_or_nodes: datasets 分析或叶子映射。
|
||||
page_boxes: 可选期望页框。
|
||||
template_bytes: 可选 template packet。
|
||||
|
||||
Returns:
|
||||
XfaPreviewComposeResult;当前预期 status=needs_review。
|
||||
"""
|
||||
return attempt_offline_xfa_flatten(
|
||||
pdf_bytes=pdf_bytes,
|
||||
analysis_or_nodes=analysis_or_nodes,
|
||||
page_boxes=page_boxes,
|
||||
template_bytes=template_bytes,
|
||||
)
|
||||
@@ -18,9 +18,6 @@ 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,
|
||||
@@ -47,6 +44,21 @@ from app.services.shipping_notice.order_schema.field_rules import (
|
||||
)
|
||||
|
||||
|
||||
# 引擎保留命中集合用于可审计诊断;这些信息本身不表示歧义,不能污染行级门禁。
|
||||
_SPLIT_INFORMATIONAL_DIAGNOSTIC_CODES = frozenset({
|
||||
'line_match_candidates',
|
||||
})
|
||||
|
||||
|
||||
def _split_blocking_issue_codes(split_result: Any) -> list[str]:
|
||||
"""只将会影响正式取值可信度的拆分诊断投影为业务 issue。"""
|
||||
return [
|
||||
f'xfa_split:{item.code}'
|
||||
for item in split_result.diagnostics
|
||||
if item.code and item.code not in _SPLIT_INFORMATIONAL_DIAGNOSTIC_CODES
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaExtractedField:
|
||||
"""单字段提取结果(含内部原始值,对外投影时剥离)。"""
|
||||
@@ -354,9 +366,7 @@ def _apply_split_rules_for_header(
|
||||
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
|
||||
)
|
||||
issues.extend(_split_blocking_issue_codes(split_result))
|
||||
for segment in split_result.evidence_only_segments:
|
||||
evidence.append({
|
||||
'segment_id': segment.segment_id,
|
||||
@@ -441,9 +451,7 @@ def _apply_split_rules_for_row(
|
||||
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}')
|
||||
issues.extend(_split_blocking_issue_codes(split_result))
|
||||
for segment in split_result.evidence_only_segments:
|
||||
split_evidence.append({
|
||||
'segment_id': segment.segment_id,
|
||||
@@ -507,7 +515,7 @@ def extract_xfa_profile(
|
||||
|
||||
核心逻辑:校验 definition → 要求 bindings-only(拒绝 legacy mappings)→
|
||||
按 scope 迭代 bindings → 读权威集合行 → 从 schema_fields 标准化;
|
||||
无 bindings → xfa_visual_bindings_required;双源 → xfa_dual_binding_source。
|
||||
无 bindings → xfa_mapping_required;双源 → xfa_dual_binding_source。
|
||||
|
||||
Args:
|
||||
raw_profile: 冻结 Profile 快照(含 definition / checksum)。
|
||||
@@ -531,7 +539,7 @@ def extract_xfa_profile(
|
||||
if not has_bindings:
|
||||
return XfaExtractionResult(
|
||||
status='failed',
|
||||
reason_codes=['xfa_visual_bindings_required'],
|
||||
reason_codes=['xfa_mapping_required'],
|
||||
packet_checksum=packet_checksum,
|
||||
dataset_structure_fingerprint=dataset_structure_fingerprint,
|
||||
profile_checksum=str(raw_profile.get('checksum') or '') or None,
|
||||
@@ -690,32 +698,30 @@ def extract_xfa_profile(
|
||||
'evidence_ref': header.evidence,
|
||||
'highlight_source': 'xfa_dataset',
|
||||
})
|
||||
pending_price_unit_raw: str | None = None
|
||||
pending_price_unit_path: str | None = None
|
||||
for binding in line_bindings:
|
||||
if str(binding.field_code or '') in split_produced_codes:
|
||||
continue
|
||||
if str(binding.value_binding.path_id or '') in split_source_path_ids:
|
||||
continue
|
||||
data_path = str(binding.value_binding.data_path or '')
|
||||
raw_value = row_values.get(data_path)
|
||||
extract_raw = raw_value
|
||||
# 业务字段属于 line 不代表 datasets 值必须物理存放在每条 DATA 中。
|
||||
# 部分供应商 XFA 将整单 Reservation 放在 Header;该 binding 仍须由管理员
|
||||
# 显式确认到共同明细字段框,随后把同一份 datasets 正式证据投影到每行。
|
||||
inherited_from_header = bool(
|
||||
data_path and not data_path.startswith(f'{normalized_auth_path}/')
|
||||
)
|
||||
raw_value = (
|
||||
read_dataset_value(dataset_analysis, data_path)
|
||||
if inherited_from_header
|
||||
else row_values.get(data_path)
|
||||
)
|
||||
value_type, normalizer_key, validator_key = _schema_metadata_for_field(
|
||||
schema_fields=schema_fields,
|
||||
field_id=binding.field_id,
|
||||
field_code=binding.field_code,
|
||||
)
|
||||
# [STEP] NETPR 复合值:拆出单价;价格单位若无独立 binding 则稍后补齐。
|
||||
if str(binding.field_code or '') == 'unit_price':
|
||||
composite = parse_unit_price_with_price_unit(
|
||||
None if raw_value is None else str(raw_value)
|
||||
)
|
||||
if composite:
|
||||
extract_raw = composite['unit_price']
|
||||
pending_price_unit_raw = composite['price_unit']
|
||||
pending_price_unit_path = data_path
|
||||
extracted = _extract_one_field(
|
||||
raw_value=extract_raw if extract_raw is not None else raw_value,
|
||||
raw_value=raw_value,
|
||||
mapping_id=binding.binding_id,
|
||||
field_id=binding.field_id,
|
||||
field_code=binding.field_code,
|
||||
@@ -727,24 +733,6 @@ def extract_xfa_profile(
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
)
|
||||
# 保留原文 quote(含 ``898.72 / 1``)便于审计对账。
|
||||
if (
|
||||
str(binding.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:
|
||||
@@ -759,52 +747,9 @@ def extract_xfa_profile(
|
||||
'evidence_ref': extracted.evidence,
|
||||
'highlight_source': 'xfa_dataset',
|
||||
'row_index': index,
|
||||
**({'inherited_from_header': True} if inherited_from_header else {}),
|
||||
})
|
||||
|
||||
# 仅映射 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',
|
||||
@@ -817,6 +762,8 @@ def extract_xfa_profile(
|
||||
if has_unconfirmed_split_rules:
|
||||
reason_codes.append('xfa_split_rule_unconfirmed')
|
||||
source_mapping_incomplete = bool(required_missing)
|
||||
if source_mapping_incomplete:
|
||||
reason_codes.append('xfa_source_mapping_incomplete')
|
||||
|
||||
evidence_summary = sanitize_xfa_dto({
|
||||
'header_field_count': len(header_fields),
|
||||
|
||||
@@ -1,191 +0,0 @@
|
||||
"""
|
||||
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=[],
|
||||
)
|
||||
@@ -156,10 +156,21 @@ def compile_safe_regex(
|
||||
flags = 0 if case_sensitive else re.IGNORECASE
|
||||
if _HAS_RE2 and _re2 is not None:
|
||||
try:
|
||||
re2_flags = _re2.Flags(0)
|
||||
if not case_sensitive:
|
||||
re2_flags = _re2.Flags.CASE_INSENSITIVE # type: ignore[attr-defined]
|
||||
compiled_re2 = _re2.compile(str(pattern), re2_flags)
|
||||
# google-re2 bindings have two public shapes: older bindings expose
|
||||
# Flags, while current pybind bindings accept an Options instance.
|
||||
# Keep RE2 linear-time execution in both cases; never silently fall
|
||||
# through to in-process Python ``re`` merely because the API changed.
|
||||
if hasattr(_re2, 'Flags'):
|
||||
re2_flags = _re2.Flags(0)
|
||||
if not case_sensitive:
|
||||
re2_flags = _re2.Flags.CASE_INSENSITIVE # type: ignore[attr-defined]
|
||||
compiled_re2 = _re2.compile(str(pattern), re2_flags)
|
||||
elif hasattr(_re2, 'Options'):
|
||||
options = _re2.Options()
|
||||
options.case_sensitive = bool(case_sensitive)
|
||||
compiled_re2 = _re2.compile(str(pattern), options)
|
||||
else:
|
||||
raise SafeRegexError('unsupported re2 binding API')
|
||||
group_count = compiled_re2.groups if hasattr(compiled_re2, 'groups') else 0
|
||||
if int(group_count or 0) > max_groups:
|
||||
raise SafeRegexError('regex capture groups exceed limit')
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
backend/app/services/shipping_notice/document_layout/xfa_signature.py
|
||||
|
||||
用途:计算 XFA template packet checksum、datasets 结构指纹、统一 binding/拆分
|
||||
内容指纹与治理用 structure signature。
|
||||
内容指纹,供 xfa_dataset value adapter 身份复验。
|
||||
依赖:xfa_contract、xfa_dataset.XfaDatasetNode、标准库 hashlib/json。
|
||||
逻辑:由 xfa_analysis / 验证服务调用;指纹忽略业务值与行数;structure signature
|
||||
与 definition checksum 覆盖视觉绑定与拆分规则业务字段。
|
||||
逻辑:由 xfa_analysis / 验证服务调用;指纹忽略业务值与行数;共同 Profile
|
||||
视觉身份只使用 layout_signature,XFA 仅提供末端取值 adapter 证据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,7 +15,6 @@ import json
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_STRUCTURE_SIGNATURE_ID,
|
||||
XfaStructureNodeSpec,
|
||||
XfaUnifiedFieldBinding,
|
||||
canonical_unified_bindings_payload,
|
||||
@@ -100,56 +99,6 @@ def build_signature_summary(
|
||||
}
|
||||
|
||||
|
||||
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),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def compute_unified_bindings_checksum(
|
||||
bindings: list[XfaUnifiedFieldBinding] | list[dict[str, Any]],
|
||||
) -> str:
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/document_layout/xfa_split_preview_token.py
|
||||
|
||||
用途:签发与校验 XFA 拆分规则预览确认令牌,防止客户端自行声明 confirmed。
|
||||
依赖:Flask current_app.SECRET_KEY、hmac、hashlib、time、secrets、redis_client。
|
||||
逻辑:由 preview_xfa_split_rules 签发;save_draft / 确认接口经 verify_and_consume 原子消费 jti;
|
||||
逻辑:由 datasets adapter 的拆分预览签发;共同保存流经 adapter 原子消费 jti;
|
||||
生产/预发/多 Worker:Redis 不可用时 fail-closed(STORE_UNAVAILABLE);
|
||||
仅 TESTING 或单进程 development(ALLOW_MEMORY_JTI)允许进程内兜底。
|
||||
"""
|
||||
|
||||
@@ -371,6 +371,9 @@ def split_rule_content_fingerprint(rule_set: XfaSplitRuleSet | dict[str, Any]) -
|
||||
payload.pop('requires_confirmation', None)
|
||||
payload.pop('rule_version', None)
|
||||
payload.pop('rule_id', None)
|
||||
# 指纹排除映射语义,但不得原地修改 definition_json 中的规则;调用者还会
|
||||
# 将同一规则对象交给 normalize/save,原地 pop 会使已确认草稿不可再次编辑。
|
||||
payload = json.loads(json.dumps(payload))
|
||||
for rule in payload.get('rules') or []:
|
||||
segment = rule.get('segment') if isinstance(rule, dict) else None
|
||||
if not isinstance(segment, dict):
|
||||
|
||||
@@ -1,294 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_template_parser.py
|
||||
|
||||
用途:防御性解析 XFA template packet,提取 field/draw 节点的 bind 引用与近似几何
|
||||
(x/y/w/h 属性),供自研静态合成预览定位回显文本。
|
||||
依赖:lxml、xfa_packets.preflight_xml_bytes、xfa_dataset._hardened_parser 模式。
|
||||
逻辑:由 xfa_preview_renderer 调用;不执行 JS/FormCalc、不联网;解析失败返回空列表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from lxml import etree
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_packets import XfaPacketError, preflight_xml_bytes
|
||||
|
||||
_DIMENSION_RE = re.compile(
|
||||
r'^\s*(?P<value>-?\d+(?:\.\d+)?)\s*(?P<unit>pt|mm|in|cm|px)?\s*$',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
# 常见页面参考尺寸(Letter pt),仅用于将绝对单位粗略归一化。
|
||||
_DEFAULT_PAGE_WIDTH_PT = 612.0
|
||||
_DEFAULT_PAGE_HEIGHT_PT = 792.0
|
||||
_FIELD_DRAW_LOCAL_NAMES = frozenset({'field', 'draw'})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class XfaTemplateFieldGeometry:
|
||||
"""
|
||||
template 中可定位的 field/draw 摘要。
|
||||
|
||||
坐标为页面相对归一化框(左上原点 0..1);无法可靠归一化时 normalized_bbox 为空。
|
||||
"""
|
||||
|
||||
name: str
|
||||
bind_ref: str
|
||||
page_no: int
|
||||
raw_x: float | None
|
||||
raw_y: float | None
|
||||
raw_w: float | None
|
||||
raw_h: float | None
|
||||
normalized_bbox: dict[str, float] | None
|
||||
local_name: str
|
||||
|
||||
|
||||
def _local_name(tag: str) -> str:
|
||||
"""提取 XML localName,忽略命名空间前缀。"""
|
||||
return str(tag or '').rsplit('}', 1)[-1].lower()
|
||||
|
||||
|
||||
def _hardened_parser() -> etree.XMLParser:
|
||||
"""
|
||||
构造禁用外部实体与 DTD 的 lxml 解析器。
|
||||
|
||||
Returns:
|
||||
与 datasets 解析同策略的安全 XMLParser。
|
||||
"""
|
||||
return etree.XMLParser(
|
||||
resolve_entities=False,
|
||||
load_dtd=False,
|
||||
no_network=True,
|
||||
huge_tree=False,
|
||||
)
|
||||
|
||||
|
||||
def _parse_dimension(raw: str | None) -> float | None:
|
||||
"""
|
||||
解析 XFA 尺寸属性(可带 pt/mm/in/cm/px 后缀)为浮点数。
|
||||
|
||||
核心逻辑:无单位时原样返回数值;有单位时统一换算为 pt(近似)。
|
||||
|
||||
Args:
|
||||
raw: 属性字符串,如 ``36pt``、``10mm``、``0.25``。
|
||||
|
||||
Returns:
|
||||
数值(pt 或无单位原值);无法解析时返回 None。
|
||||
"""
|
||||
text = str(raw or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
match = _DIMENSION_RE.match(text)
|
||||
if not match:
|
||||
return None
|
||||
try:
|
||||
value = float(match.group('value'))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
unit = (match.group('unit') or '').lower()
|
||||
if not unit or unit == 'pt' or unit == 'px':
|
||||
return value
|
||||
if unit == 'in':
|
||||
return value * 72.0
|
||||
if unit == 'mm':
|
||||
return value * 72.0 / 25.4
|
||||
if unit == 'cm':
|
||||
return value * 72.0 / 2.54
|
||||
return value
|
||||
|
||||
|
||||
def _attr(element: etree._Element, *names: str) -> str:
|
||||
"""按候选属性名读取第一个非空值(忽略命名空间前缀)。"""
|
||||
for name in names:
|
||||
for key, value in element.attrib.items():
|
||||
local = str(key).rsplit('}', 1)[-1]
|
||||
if local.lower() == name.lower() and str(value or '').strip():
|
||||
return str(value).strip()
|
||||
return ''
|
||||
|
||||
|
||||
def _extract_bind_ref(element: etree._Element) -> str:
|
||||
"""
|
||||
从 field/draw 或其 bind 子节点提取 dataRef。
|
||||
|
||||
核心逻辑:优先读子节点 ``bind`` 的 ref/dataRef;否则读自身 bind/ref 属性。
|
||||
"""
|
||||
direct = _attr(element, 'bind', 'ref', 'dataRef')
|
||||
if direct:
|
||||
return direct
|
||||
for child in element:
|
||||
if not isinstance(child.tag, str):
|
||||
continue
|
||||
if _local_name(child.tag) != 'bind':
|
||||
continue
|
||||
ref = _attr(child, 'ref', 'dataRef', 'match')
|
||||
if ref and ref.lower() not in {'none', 'dataref', 'once', 'global', 'dataRef'.lower()}:
|
||||
return ref
|
||||
# match="dataRef" 时真正路径常在 ref
|
||||
ref2 = _attr(child, 'ref', 'dataRef')
|
||||
if ref2:
|
||||
return ref2
|
||||
return ''
|
||||
|
||||
|
||||
def _normalize_bbox_from_raw(
|
||||
*,
|
||||
x: float | None,
|
||||
y: float | None,
|
||||
w: float | None,
|
||||
h: float | None,
|
||||
page_width: float,
|
||||
page_height: float,
|
||||
) -> dict[str, float] | None:
|
||||
"""
|
||||
将 template 原始 x/y/w/h 粗略归一化为左上原点 0..1 框。
|
||||
|
||||
核心逻辑:若数值均落在 0..1 则视为已归一化;否则按 page pt 尺寸换算。
|
||||
XFA 模板常以左下为原点,此处按「y 为距底边」尝试翻转;若翻转后越界则按左上解释。
|
||||
|
||||
Args:
|
||||
x/y/w/h: 原始尺寸(pt 或相对)。
|
||||
page_width/page_height: 参考页尺寸(pt)。
|
||||
|
||||
Returns:
|
||||
``{x0,y0,x1,y1}``;无法构成有效框时返回 None。
|
||||
"""
|
||||
if x is None or y is None or w is None or h is None:
|
||||
return None
|
||||
if w <= 0 or h <= 0:
|
||||
return None
|
||||
if page_width <= 0 or page_height <= 0:
|
||||
return None
|
||||
|
||||
# [STEP 1] 已是相对坐标
|
||||
if 0.0 <= x <= 1.0 and 0.0 <= y <= 1.0 and 0.0 < w <= 1.0 and 0.0 < h <= 1.0:
|
||||
x0, y0, x1, y1 = x, y, x + w, y + h
|
||||
else:
|
||||
# [STEP 2] 绝对 pt:优先按 PDF 左下原点翻转
|
||||
x0 = x / page_width
|
||||
x1 = (x + w) / page_width
|
||||
y0_flip = 1.0 - ((y + h) / page_height)
|
||||
y1_flip = 1.0 - (y / page_height)
|
||||
y0_top = y / page_height
|
||||
y1_top = (y + h) / page_height
|
||||
if 0.0 <= y0_flip <= 1.0 and 0.0 <= y1_flip <= 1.0 and y1_flip > y0_flip:
|
||||
y0, y1 = y0_flip, y1_flip
|
||||
else:
|
||||
y0, y1 = y0_top, y1_top
|
||||
|
||||
x0 = max(0.0, min(1.0, x0))
|
||||
x1 = max(0.0, min(1.0, x1))
|
||||
y0 = max(0.0, min(1.0, y0))
|
||||
y1 = max(0.0, min(1.0, y1))
|
||||
if x1 <= x0 or y1 <= y0:
|
||||
return None
|
||||
return {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1}
|
||||
|
||||
|
||||
def _resolve_page_no(element: etree._Element, default_page: int = 1) -> int:
|
||||
"""从节点或其祖先读取 page/pageNum 属性;非法时回退 default_page。"""
|
||||
current: etree._Element | None = element
|
||||
while current is not None:
|
||||
raw = _attr(current, 'page', 'pageNum', 'page_no')
|
||||
if raw:
|
||||
try:
|
||||
value = int(float(raw))
|
||||
if value >= 1:
|
||||
return value
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
parent = current.getparent()
|
||||
current = parent if isinstance(parent, etree._Element) else None
|
||||
return max(1, int(default_page))
|
||||
|
||||
|
||||
def parse_xfa_template_field_geometries(
|
||||
template_bytes: bytes,
|
||||
*,
|
||||
page_width: float = _DEFAULT_PAGE_WIDTH_PT,
|
||||
page_height: float = _DEFAULT_PAGE_HEIGHT_PT,
|
||||
) -> list[XfaTemplateFieldGeometry]:
|
||||
"""
|
||||
解析 XFA template packet,提取带 bind 与近似位置的 field/draw 节点。
|
||||
|
||||
核心逻辑:preflight → hardened lxml 解析 → 遍历 field/draw;读取 name/bind 与
|
||||
x/y/w/h;失败或不可解析时返回空列表(不抛给调用方)。
|
||||
|
||||
Args:
|
||||
template_bytes: template packet XML 字节。
|
||||
page_width: 用于绝对坐标归一化的参考页宽(pt)。
|
||||
page_height: 用于绝对坐标归一化的参考页高(pt)。
|
||||
|
||||
Returns:
|
||||
几何摘要列表;不可解析时为空列表。
|
||||
"""
|
||||
if not template_bytes:
|
||||
return []
|
||||
try:
|
||||
preflight_xml_bytes(template_bytes)
|
||||
root = etree.fromstring(template_bytes, parser=_hardened_parser())
|
||||
except (XfaPacketError, etree.XMLSyntaxError, ValueError, TypeError, OSError):
|
||||
return []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
results: list[XfaTemplateFieldGeometry] = []
|
||||
for element in root.iter():
|
||||
if not isinstance(element.tag, str):
|
||||
continue
|
||||
local = _local_name(element.tag)
|
||||
if local not in _FIELD_DRAW_LOCAL_NAMES:
|
||||
continue
|
||||
name = _attr(element, 'name') or local
|
||||
bind_ref = _extract_bind_ref(element)
|
||||
x = _parse_dimension(_attr(element, 'x'))
|
||||
y = _parse_dimension(_attr(element, 'y'))
|
||||
w = _parse_dimension(_attr(element, 'w', 'width'))
|
||||
h = _parse_dimension(_attr(element, 'h', 'height'))
|
||||
page_no = _resolve_page_no(element)
|
||||
bbox = _normalize_bbox_from_raw(
|
||||
x=x, y=y, w=w, h=h, page_width=page_width, page_height=page_height,
|
||||
)
|
||||
results.append(XfaTemplateFieldGeometry(
|
||||
name=name,
|
||||
bind_ref=bind_ref,
|
||||
page_no=page_no,
|
||||
raw_x=x,
|
||||
raw_y=y,
|
||||
raw_w=w,
|
||||
raw_h=h,
|
||||
normalized_bbox=bbox,
|
||||
local_name=local,
|
||||
))
|
||||
return results
|
||||
|
||||
|
||||
def serialize_template_field_geometries(
|
||||
items: list[XfaTemplateFieldGeometry],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
将 template 几何摘要序列化为普通字典列表(测试/诊断用)。
|
||||
|
||||
Args:
|
||||
items: parse_xfa_template_field_geometries 结果。
|
||||
|
||||
Returns:
|
||||
可 JSON 化的字典列表。
|
||||
"""
|
||||
return [
|
||||
{
|
||||
'name': item.name,
|
||||
'bind_ref': item.bind_ref,
|
||||
'page_no': item.page_no,
|
||||
'raw_x': item.raw_x,
|
||||
'raw_y': item.raw_y,
|
||||
'raw_w': item.raw_w,
|
||||
'raw_h': item.raw_h,
|
||||
'normalized_bbox': item.normalized_bbox,
|
||||
'local_name': item.local_name,
|
||||
}
|
||||
for item in items
|
||||
]
|
||||
@@ -74,7 +74,7 @@ def _normalize_comparable(value: Any, *, value_type: str | None = None) -> str |
|
||||
"""
|
||||
将 datasets / AcroForm 展示值收敛为可比较的标准化字符串。
|
||||
|
||||
核心逻辑:金额去千分位;日期接受 ISO 与 DD/MM/YYYY;数量去尾随零。
|
||||
核心逻辑:金额去千分位;日期接受 ISO、数字日期及明确英文月份;数量去尾随零。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
@@ -83,7 +83,10 @@ def _normalize_comparable(value: Any, *, value_type: str | None = None) -> str |
|
||||
return None
|
||||
lowered_type = str(value_type or '').strip().lower()
|
||||
# 日期优先:避免把 14/07/2026 误判为数值。
|
||||
date_patterns = ('%Y-%m-%d', '%Y/%m/%d', '%d/%m/%Y', '%m/%d/%Y', '%d-%m-%Y', '%Y%m%d')
|
||||
date_patterns = (
|
||||
'%Y-%m-%d', '%Y/%m/%d', '%d/%m/%Y', '%m/%d/%Y', '%d-%m-%Y', '%Y%m%d',
|
||||
'%d-%b-%Y', '%d-%B-%Y',
|
||||
)
|
||||
if lowered_type in {'date', 'datetime'} or any(sep in text for sep in ('/', '-')) and text.count('/') + text.count('-') >= 2:
|
||||
for pattern in date_patterns:
|
||||
try:
|
||||
@@ -115,8 +118,10 @@ def _normalize_comparable(value: Any, *, value_type: str | None = None) -> str |
|
||||
return text.casefold()
|
||||
|
||||
|
||||
def _field_map_from_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""从提取行中收集 field_code → value 映射(按行)。"""
|
||||
def _field_map_from_rows(
|
||||
rows: list[dict[str, Any]], *, registered_field_codes: set[str] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""从提取行中收集已正式绑定的 field_code → value 映射(按行)。"""
|
||||
result: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
mapping: dict[str, Any] = {}
|
||||
@@ -124,24 +129,39 @@ def _field_map_from_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
code = str(item.get('field_code') or '').strip()
|
||||
if code:
|
||||
if code and (registered_field_codes is None or code in registered_field_codes):
|
||||
mapping[code] = item.get('value')
|
||||
result.append(mapping)
|
||||
return result
|
||||
|
||||
|
||||
def _line_amount_operands(mapping: dict[str, Any]) -> tuple[Any, Any, Any]:
|
||||
"""读取通用金额恒等式的数量、单价与金额字段。"""
|
||||
return (
|
||||
mapping.get('quantity', mapping.get('qty')),
|
||||
mapping.get('unit_price'),
|
||||
mapping.get('amount', mapping.get('line_amount_with_tax')),
|
||||
)
|
||||
|
||||
|
||||
def _line_amount_expected(*, quantity: Decimal, unit_price: Decimal) -> Decimal:
|
||||
"""计算通用金额恒等式的预期值:数量 × 已归一化单价。"""
|
||||
return quantity * unit_price
|
||||
|
||||
|
||||
def _validate_line_amount_formula(line_maps: list[dict[str, Any]]) -> bool:
|
||||
"""校验 quantity × unit_price / price_unit == amount。"""
|
||||
"""校验通用金额恒等式:数量 × 已归一化单价 == 金额。"""
|
||||
for mapping in line_maps:
|
||||
quantity = _to_decimal(mapping.get('quantity'))
|
||||
unit_price = _to_decimal(mapping.get('unit_price'))
|
||||
amount = _to_decimal(mapping.get('amount'))
|
||||
quantity_value, unit_price_value, amount_value = _line_amount_operands(mapping)
|
||||
quantity = _to_decimal(quantity_value)
|
||||
unit_price = _to_decimal(unit_price_value)
|
||||
amount = _to_decimal(amount_value)
|
||||
if quantity is None or unit_price is None or amount is None:
|
||||
return False
|
||||
price_unit = _to_decimal(mapping.get('price_unit')) or Decimal('1')
|
||||
if price_unit == 0:
|
||||
return False
|
||||
expected = (quantity * unit_price) / price_unit
|
||||
expected = _line_amount_expected(
|
||||
quantity=quantity,
|
||||
unit_price=unit_price,
|
||||
)
|
||||
if expected.quantize(Decimal('0.01')) != amount.quantize(Decimal('0.01')):
|
||||
# 允许未量化的精确相等。
|
||||
if expected != amount:
|
||||
@@ -150,30 +170,35 @@ def _validate_line_amount_formula(line_maps: list[dict[str, Any]]) -> bool:
|
||||
|
||||
|
||||
def _line_amount_failures(line_maps: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""返回明细金额校验失败的具体行和值,供模板管理员定位映射或数据问题。"""
|
||||
"""返回通用金额恒等式校验失败的具体行和值。"""
|
||||
failures: list[dict[str, Any]] = []
|
||||
for row_index, mapping in enumerate(line_maps, start=1):
|
||||
quantity = _to_decimal(mapping.get('quantity'))
|
||||
unit_price = _to_decimal(mapping.get('unit_price'))
|
||||
amount = _to_decimal(mapping.get('amount'))
|
||||
price_unit = _to_decimal(mapping.get('price_unit')) or Decimal('1')
|
||||
if quantity is None or unit_price is None or amount is None or price_unit == 0:
|
||||
quantity_value, unit_price_value, amount_value = _line_amount_operands(mapping)
|
||||
quantity = _to_decimal(quantity_value)
|
||||
unit_price = _to_decimal(unit_price_value)
|
||||
amount = _to_decimal(amount_value)
|
||||
expected = (
|
||||
_line_amount_expected(
|
||||
quantity=quantity,
|
||||
unit_price=unit_price,
|
||||
)
|
||||
if quantity is not None and unit_price is not None
|
||||
else None
|
||||
)
|
||||
if quantity is None or unit_price is None or amount is None or expected is None:
|
||||
failures.append({
|
||||
'row_index': row_index,
|
||||
'quantity': mapping.get('quantity'),
|
||||
'unit_price': mapping.get('unit_price'),
|
||||
'price_unit': mapping.get('price_unit'),
|
||||
'amount': mapping.get('amount'),
|
||||
'quantity': quantity_value,
|
||||
'unit_price': unit_price_value,
|
||||
'amount': amount_value,
|
||||
'reason': 'missing_or_invalid_operand',
|
||||
})
|
||||
continue
|
||||
expected = (quantity * unit_price) / price_unit
|
||||
if expected.quantize(Decimal('0.01')) != amount.quantize(Decimal('0.01')) and expected != amount:
|
||||
failures.append({
|
||||
'row_index': row_index,
|
||||
'quantity': str(quantity),
|
||||
'unit_price': str(unit_price),
|
||||
'price_unit': str(price_unit),
|
||||
'amount': str(amount),
|
||||
'expected_amount': str(expected),
|
||||
'reason': 'amount_mismatch',
|
||||
@@ -421,6 +446,10 @@ def _validate_acroform(
|
||||
)
|
||||
if not dataset_values:
|
||||
continue
|
||||
# 只有明确指向已确认拆分段的 binding 才能跳过原始 Widget 全文对账;
|
||||
# 不再按字段名猜测“单价/价格单位”复合语义。
|
||||
if binding.split_rule_ref is not None:
|
||||
continue
|
||||
if not acro_values:
|
||||
missing_counterpart += len(dataset_values)
|
||||
continue
|
||||
@@ -719,11 +748,19 @@ def validate_xfa_extraction(
|
||||
summary['acroform_status'] = acro_status
|
||||
summary['acroform_mismatches'] = acro_mismatches
|
||||
|
||||
line_maps = _field_map_from_rows(extraction.rows)
|
||||
registered_line_field_codes = {
|
||||
str(binding.field_code or '') for binding in profile.bindings
|
||||
if binding.scope == 'line' and str(binding.field_code or '').strip()
|
||||
}
|
||||
line_maps = _field_map_from_rows(
|
||||
extraction.rows, registered_field_codes=registered_line_field_codes,
|
||||
)
|
||||
|
||||
# [STEP 3] 明细金额公式
|
||||
if profile.cross_checks.line_amount_formula == 'quantity_times_unit_price':
|
||||
line_amount_failures = _line_amount_failures(line_maps)
|
||||
line_amount_failures = _line_amount_failures(
|
||||
line_maps,
|
||||
)
|
||||
if line_amount_failures:
|
||||
reason_codes.append('xfa_business_validation_failed')
|
||||
summary['line_amount_status'] = 'failed'
|
||||
|
||||
@@ -1,336 +0,0 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_visual_binding.py
|
||||
|
||||
用途:XFA 统一视觉绑定的候选评分、歧义诊断与建议结果组装(纯函数,不写数据库)。
|
||||
依赖:xfa_acroform、xfa_dataset、xfa_contract(归一化框与 path 哈希)。
|
||||
逻辑:由 order_document_profile_visual_binding_service 调用;画框或 Widget 命中后
|
||||
返回 suggested 候选列表与 diagnostics;高置信也不得自动 confirmed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Literal
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_acroform import (
|
||||
XfaAcroformWidget,
|
||||
build_widget_path_candidates,
|
||||
read_acroform_widgets,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import hash_data_path
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import XfaDatasetAnalysis
|
||||
|
||||
|
||||
VisualCandidateStatus = Literal['suggested']
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VisualPathCandidate:
|
||||
"""datasets 路径候选摘要(不含完整 XPath 明文时可仅含 hash)。"""
|
||||
|
||||
path_id: str
|
||||
data_path_hash: str
|
||||
dataset_value_masked: str
|
||||
match_hint: str
|
||||
confidence: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class VisualBindingCandidate:
|
||||
"""单个 Widget/区域视觉绑定候选;status 恒为 suggested,禁止自动 confirmed。"""
|
||||
|
||||
candidate_id: str
|
||||
widget_id: str
|
||||
page_no: int
|
||||
normalized_bbox: dict[str, float]
|
||||
acroform_field_name_tail: str
|
||||
display_value_masked: str
|
||||
path_candidates: list[VisualPathCandidate] = field(default_factory=list)
|
||||
overlap_score: float = 0.0
|
||||
value_match_score: float = 0.0
|
||||
confidence: float = 0.0
|
||||
status: VisualCandidateStatus = 'suggested'
|
||||
|
||||
|
||||
@dataclass
|
||||
class VisualBindingDiagnostics:
|
||||
"""歧义与覆盖诊断;供管理员确认前展示。"""
|
||||
|
||||
candidate_count: int = 0
|
||||
ambiguous: bool = False
|
||||
ambiguity_reason: str | None = None
|
||||
top_confidence: float = 0.0
|
||||
second_confidence: float = 0.0
|
||||
auto_confirm_blocked: bool = True
|
||||
notes: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def _bbox_area(bbox: dict[str, float]) -> float:
|
||||
"""计算归一化框面积;非法框返回 0。"""
|
||||
x0 = float(bbox.get('x0') or 0)
|
||||
y0 = float(bbox.get('y0') or 0)
|
||||
x1 = float(bbox.get('x1') or 0)
|
||||
y1 = float(bbox.get('y1') or 0)
|
||||
if x1 <= x0 or y1 <= y0:
|
||||
return 0.0
|
||||
return (x1 - x0) * (y1 - y0)
|
||||
|
||||
|
||||
def _bbox_intersection_area(a: dict[str, float], b: dict[str, float]) -> float:
|
||||
"""两框交集面积。"""
|
||||
x0 = max(float(a.get('x0') or 0), float(b.get('x0') or 0))
|
||||
y0 = max(float(a.get('y0') or 0), float(b.get('y0') or 0))
|
||||
x1 = min(float(a.get('x1') or 0), float(b.get('x1') or 0))
|
||||
y1 = min(float(a.get('y1') or 0), float(b.get('y1') or 0))
|
||||
if x1 <= x0 or y1 <= y0:
|
||||
return 0.0
|
||||
return (x1 - x0) * (y1 - y0)
|
||||
|
||||
|
||||
def _bbox_overlap_score(region: dict[str, float], widget_bbox: dict[str, float]) -> float:
|
||||
"""
|
||||
区域与 Widget 框重叠得分(IoU 优先,退化时为交集占区域面积比)。
|
||||
|
||||
Args:
|
||||
region: 用户画框或查询区域(0..1)。
|
||||
widget_bbox: AcroForm Widget 归一化框。
|
||||
|
||||
Returns:
|
||||
0..1 重叠得分。
|
||||
"""
|
||||
intersection = _bbox_intersection_area(region, widget_bbox)
|
||||
if intersection <= 0:
|
||||
return 0.0
|
||||
region_area = _bbox_area(region)
|
||||
widget_area = _bbox_area(widget_bbox)
|
||||
union = region_area + widget_area - intersection
|
||||
if union > 0:
|
||||
return intersection / union
|
||||
return intersection / region_area if region_area > 0 else 0.0
|
||||
|
||||
|
||||
def _normalize_compare_value(value: str) -> str:
|
||||
"""值对账用的空白无关规范化。"""
|
||||
return ''.join(str(value or '').casefold().split())
|
||||
|
||||
|
||||
def _value_match_score(display_value: str, dataset_value: str) -> float:
|
||||
"""
|
||||
页面展示值与 datasets 叶子值的标准化匹配分。
|
||||
|
||||
Returns:
|
||||
1.0 精确匹配;0.5 包含关系;0 不匹配。
|
||||
"""
|
||||
left = _normalize_compare_value(display_value)
|
||||
right = _normalize_compare_value(dataset_value)
|
||||
if not left or not right:
|
||||
return 0.0
|
||||
if left == right:
|
||||
return 1.0
|
||||
if left in right or right in left:
|
||||
return 0.5
|
||||
return 0.0
|
||||
|
||||
|
||||
def _candidate_id(widget_id: str, path_id: str) -> str:
|
||||
"""生成稳定的候选 ID(不含敏感明文)。"""
|
||||
digest = hashlib.sha256(f'{widget_id}:{path_id}'.encode('utf-8')).hexdigest()[:16]
|
||||
return f'vbc-{digest}'
|
||||
|
||||
|
||||
def _diagnose_ambiguity(candidates: list[VisualBindingCandidate]) -> VisualBindingDiagnostics:
|
||||
"""
|
||||
诊断候选歧义;同分或接近时标记 ambiguous,且始终阻断自动确认。
|
||||
|
||||
Args:
|
||||
candidates: 已按 confidence 降序排列的候选。
|
||||
|
||||
Returns:
|
||||
诊断摘要。
|
||||
"""
|
||||
diagnostics = VisualBindingDiagnostics(candidate_count=len(candidates))
|
||||
if not candidates:
|
||||
diagnostics.notes.append('no_widget_overlap')
|
||||
return diagnostics
|
||||
diagnostics.top_confidence = float(candidates[0].confidence)
|
||||
if len(candidates) > 1:
|
||||
diagnostics.second_confidence = float(candidates[1].confidence)
|
||||
# [STEP 1] 高置信接近时视为歧义,禁止自动确认
|
||||
if len(candidates) >= 2 and abs(diagnostics.top_confidence - diagnostics.second_confidence) < 0.05:
|
||||
diagnostics.ambiguous = True
|
||||
diagnostics.ambiguity_reason = 'top_candidates_too_close'
|
||||
elif len(candidates) >= 2 and diagnostics.top_confidence >= 0.85 and diagnostics.second_confidence >= 0.75:
|
||||
diagnostics.ambiguous = True
|
||||
diagnostics.ambiguity_reason = 'multiple_high_confidence'
|
||||
top_paths = candidates[0].path_candidates
|
||||
if len(top_paths) > 1:
|
||||
diagnostics.ambiguous = True
|
||||
diagnostics.ambiguity_reason = diagnostics.ambiguity_reason or 'multiple_path_candidates'
|
||||
diagnostics.auto_confirm_blocked = True
|
||||
return diagnostics
|
||||
|
||||
|
||||
def suggest_visual_binding_candidates(
|
||||
*,
|
||||
page_no: int,
|
||||
normalized_bbox: dict[str, float],
|
||||
dataset_analysis: XfaDatasetAnalysis,
|
||||
pdf_bytes: bytes | None = None,
|
||||
widgets: list[XfaAcroformWidget] | None = None,
|
||||
min_overlap: float = 0.05,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为指定页面区域生成 AcroForm Widget → datasets 路径的视觉绑定候选。
|
||||
|
||||
核心逻辑:按框重叠筛选 Widget → 为每个 Widget 生成路径候选 → 综合重叠与值匹配
|
||||
评分;所有候选 status 恒为 suggested,歧义写入 diagnostics。
|
||||
|
||||
Args:
|
||||
page_no: 目标 PDF 页码(1-based)。
|
||||
normalized_bbox: 用户画框或查询区域(0..1,左上原点)。
|
||||
dataset_analysis: 已解析的 datasets 结构。
|
||||
pdf_bytes: 原始 PDF;widgets 未传入时用于读取 AcroForm Widget。
|
||||
widgets: 可选预读 Widget 列表(测试/mock 用)。
|
||||
min_overlap: 最小 IoU/重叠阈值。
|
||||
|
||||
Returns:
|
||||
{candidates, diagnostics, page_no, normalized_bbox} 安全 DTO。
|
||||
"""
|
||||
region = {
|
||||
'x0': float(normalized_bbox.get('x0') or 0),
|
||||
'y0': float(normalized_bbox.get('y0') or 0),
|
||||
'x1': float(normalized_bbox.get('x1') or 0),
|
||||
'y1': float(normalized_bbox.get('y1') or 0),
|
||||
}
|
||||
if _bbox_area(region) <= 0:
|
||||
return {
|
||||
'page_no': int(page_no),
|
||||
'normalized_bbox': region,
|
||||
'candidates': [],
|
||||
'diagnostics': VisualBindingDiagnostics(
|
||||
candidate_count=0,
|
||||
notes=['invalid_region_bbox'],
|
||||
).__dict__,
|
||||
}
|
||||
|
||||
widget_list = list(widgets or [])
|
||||
if not widget_list and pdf_bytes:
|
||||
widget_list = read_acroform_widgets(pdf_bytes)
|
||||
|
||||
candidates: list[VisualBindingCandidate] = []
|
||||
for widget in widget_list:
|
||||
if int(widget.page_no) != int(page_no):
|
||||
continue
|
||||
overlap = _bbox_overlap_score(region, widget.normalized_bbox)
|
||||
if overlap < float(min_overlap):
|
||||
continue
|
||||
path_items = build_widget_path_candidates(
|
||||
widget=widget,
|
||||
dataset_analysis=dataset_analysis,
|
||||
)
|
||||
path_candidates: list[VisualPathCandidate] = []
|
||||
best_value_score = 0.0
|
||||
for item in path_items:
|
||||
value_score = _value_match_score(widget.value, item.get('raw_value') or '')
|
||||
best_value_score = max(best_value_score, value_score)
|
||||
path_candidates.append(VisualPathCandidate(
|
||||
path_id=str(item.get('path_id') or ''),
|
||||
data_path_hash=str(item.get('data_path_hash') or ''),
|
||||
dataset_value_masked=str(item.get('dataset_value_masked') or ''),
|
||||
match_hint=str(item.get('match_hint') or 'unmatched'),
|
||||
confidence=round(min(1.0, overlap * 0.6 + value_score * 0.4), 4),
|
||||
))
|
||||
confidence = round(min(1.0, overlap * 0.55 + best_value_score * 0.45), 4)
|
||||
top_path_id = path_candidates[0].path_id if path_candidates else ''
|
||||
candidates.append(VisualBindingCandidate(
|
||||
candidate_id=_candidate_id(widget.widget_id, top_path_id or widget.widget_id),
|
||||
widget_id=widget.widget_id,
|
||||
page_no=int(widget.page_no),
|
||||
normalized_bbox=dict(widget.normalized_bbox),
|
||||
acroform_field_name_tail=widget.short_name,
|
||||
display_value_masked=widget.value_masked,
|
||||
path_candidates=path_candidates,
|
||||
overlap_score=round(overlap, 4),
|
||||
value_match_score=round(best_value_score, 4),
|
||||
confidence=confidence,
|
||||
status='suggested',
|
||||
))
|
||||
|
||||
candidates.sort(key=lambda item: (-item.confidence, item.widget_id))
|
||||
diagnostics = _diagnose_ambiguity(candidates)
|
||||
|
||||
return {
|
||||
'page_no': int(page_no),
|
||||
'normalized_bbox': region,
|
||||
'candidates': [
|
||||
{
|
||||
'candidate_id': item.candidate_id,
|
||||
'widget_id': item.widget_id,
|
||||
'page_no': item.page_no,
|
||||
'normalized_bbox': item.normalized_bbox,
|
||||
'acroform_field_name_tail': item.acroform_field_name_tail,
|
||||
'display_value_masked': item.display_value_masked,
|
||||
'path_candidates': [
|
||||
{
|
||||
'path_id': path.path_id,
|
||||
'data_path_hash': path.data_path_hash,
|
||||
'dataset_value_masked': path.dataset_value_masked,
|
||||
'match_hint': path.match_hint,
|
||||
'confidence': path.confidence,
|
||||
}
|
||||
for path in item.path_candidates
|
||||
],
|
||||
'overlap_score': item.overlap_score,
|
||||
'value_match_score': item.value_match_score,
|
||||
'confidence': item.confidence,
|
||||
'status': item.status,
|
||||
}
|
||||
for item in candidates
|
||||
],
|
||||
'diagnostics': {
|
||||
'candidate_count': diagnostics.candidate_count,
|
||||
'ambiguous': diagnostics.ambiguous,
|
||||
'ambiguity_reason': diagnostics.ambiguity_reason,
|
||||
'top_confidence': diagnostics.top_confidence,
|
||||
'second_confidence': diagnostics.second_confidence,
|
||||
'auto_confirm_blocked': diagnostics.auto_confirm_blocked,
|
||||
'notes': list(diagnostics.notes),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def visual_binding_audit_snapshot(binding: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
"""
|
||||
提取视觉绑定审计摘要(before/after 用),不含 datasets 明文路径。
|
||||
|
||||
Args:
|
||||
binding: 统一 binding 字典或 None。
|
||||
|
||||
Returns:
|
||||
含 status、bbox、page_no、confidence 的摘要;None 表示无绑定。
|
||||
"""
|
||||
if not isinstance(binding, dict):
|
||||
return None
|
||||
visual = binding.get('visual_binding') if isinstance(binding.get('visual_binding'), dict) else {}
|
||||
if not visual:
|
||||
return None
|
||||
bbox = visual.get('normalized_bbox') if isinstance(visual.get('normalized_bbox'), dict) else {}
|
||||
value = binding.get('value_binding') if isinstance(binding.get('value_binding'), dict) else {}
|
||||
return {
|
||||
'binding_id': binding.get('binding_id'),
|
||||
'field_id': binding.get('field_id'),
|
||||
'field_code': binding.get('field_code'),
|
||||
'status': visual.get('status'),
|
||||
'page_no': visual.get('page_no'),
|
||||
'normalized_bbox': {
|
||||
'x0': bbox.get('x0'),
|
||||
'y0': bbox.get('y0'),
|
||||
'x1': bbox.get('x1'),
|
||||
'y1': bbox.get('y1'),
|
||||
},
|
||||
'source': visual.get('source'),
|
||||
'confidence': visual.get('confidence'),
|
||||
'path_id': value.get('path_id'),
|
||||
'data_path_hash': hash_data_path(str(value.get('data_path') or '')) if value.get('data_path') else None,
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -14,27 +14,50 @@ from app.services.shipping_notice.email_supplement_contract import (
|
||||
EMAIL_SUPPLEMENT_VERSION,
|
||||
empty_email_supplement_result,
|
||||
)
|
||||
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 normalize_table_header
|
||||
from app.services.shipping_notice.po_number import normalize_po_number
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
|
||||
_STATIC_HEADERS = {
|
||||
'allocation_id': {'allocation id', 'allocation'},
|
||||
'source_from_party': {'source from party', 'source from', 'from party', 'supplier'},
|
||||
'allocated_entity': {'allocated entity', 'allocation entity'},
|
||||
'allocated_qty': {'allocated qty', 'allocated quantity', 'allocation qty', 'allocation quantity'},
|
||||
}
|
||||
_NORMALIZED_STATIC_HEADERS = {
|
||||
field: {normalize_table_header(item).casefold() for item in aliases}
|
||||
for field, aliases in _STATIC_HEADERS.items()
|
||||
}
|
||||
_SCHEMA_FIELD_TO_SUPPLEMENT_FIELD = {
|
||||
'customer_po_number': 'po_number',
|
||||
'part_number': 'mpn',
|
||||
'reservation_id': 'reservation_id',
|
||||
'inventory_source_hint': 'source_type',
|
||||
}
|
||||
def _schema_configs(schema_definition: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
||||
"""返回冻结 Schema 的启用字段配置,EML 只可产生其中声明的订单字段。"""
|
||||
return {
|
||||
str(item.get('field_code') or ''): item
|
||||
for item in schema_definition.get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True) and str(item.get('field_code') or '')
|
||||
}
|
||||
|
||||
|
||||
def _normalize_schema_row(
|
||||
values: dict[str, str], *, schema_definition: dict[str, Any], issues: list[str],
|
||||
) -> dict[str, Any] | None:
|
||||
"""按冻结 Schema 规范化并校验 EML 单元格;非法字段不参与任何补充裁决。"""
|
||||
configs = _schema_configs(schema_definition)
|
||||
normalized: dict[str, Any] = {}
|
||||
for field_code, raw_value in values.items():
|
||||
config = configs.get(field_code)
|
||||
if config is None:
|
||||
normalized[field_code] = raw_value
|
||||
continue
|
||||
try:
|
||||
value = normalize_order_field_value(raw_value, config)
|
||||
except Exception:
|
||||
issues.append('email_supplement_field_invalid')
|
||||
return None
|
||||
if value is None or not validate_order_field_value(value, config):
|
||||
issues.append('email_supplement_field_invalid')
|
||||
return None
|
||||
normalized[field_code] = value
|
||||
po_code = 'customer_po_number' if 'customer_po_number' in normalized else 'po_number'
|
||||
po_number = normalize_po_number(normalized.get(po_code))
|
||||
if not po_number:
|
||||
issues.append('email_supplement_row_po_missing')
|
||||
return None
|
||||
normalized[po_code] = po_number
|
||||
return normalized
|
||||
|
||||
|
||||
def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[int, str], list[str]]:
|
||||
@@ -45,8 +68,7 @@ def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[in
|
||||
for column, slot in enumerate(grid.rows[0]):
|
||||
normalized = normalize_table_header(slot.text if slot is not None else '').casefold()
|
||||
schema_field = schema_headers.get(normalized)
|
||||
static_hits = [field for field, aliases in _NORMALIZED_STATIC_HEADERS.items() if normalized in aliases]
|
||||
hits = ([schema_field] if schema_field else []) + static_hits
|
||||
hits = [schema_field] if schema_field else []
|
||||
if len(hits) == 1:
|
||||
if hits[0] in mapped.values():
|
||||
issues.append('email_supplement_duplicate_header')
|
||||
@@ -54,7 +76,7 @@ def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[in
|
||||
mapped[column] = hits[0]
|
||||
elif len(hits) > 1:
|
||||
issues.append('email_supplement_header_ambiguous')
|
||||
if 'po_number' not in mapped.values():
|
||||
if not ({'customer_po_number', 'po_number'} & set(mapped.values())):
|
||||
issues.append('email_supplement_po_header_missing')
|
||||
return mapped, sorted(set(issues))
|
||||
|
||||
@@ -65,15 +87,15 @@ def _schema_headers(schema_definition: dict[str, Any]) -> dict[str, str | None]:
|
||||
for raw in schema_definition.get('fields') or []:
|
||||
if not isinstance(raw, dict) or not raw.get('enabled', True):
|
||||
continue
|
||||
supplement_field = _SCHEMA_FIELD_TO_SUPPLEMENT_FIELD.get(str(raw.get('field_code') or ''))
|
||||
if not supplement_field:
|
||||
field_code = str(raw.get('field_code') or '').strip()
|
||||
if not field_code:
|
||||
continue
|
||||
for value in (raw.get('display_name'), *(raw.get('aliases') or [])):
|
||||
for value in (field_code, raw.get('display_name'), *(raw.get('aliases') or [])):
|
||||
normalized = normalize_table_header(value).casefold()
|
||||
if normalized:
|
||||
if normalized not in headers:
|
||||
headers[normalized] = supplement_field
|
||||
elif headers[normalized] != supplement_field:
|
||||
headers[normalized] = field_code
|
||||
elif headers[normalized] != field_code:
|
||||
headers[normalized] = None
|
||||
return headers
|
||||
|
||||
@@ -107,19 +129,13 @@ def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str,
|
||||
'column_index': column, 'cell_id': slot.cell_id,
|
||||
'raw_value': value,
|
||||
}
|
||||
po_number = normalize_po_number(values.get('po_number'))
|
||||
if not po_number:
|
||||
issues.append('email_supplement_row_po_missing')
|
||||
normalized = _normalize_schema_row(
|
||||
values, schema_definition=schema_definition, issues=issues,
|
||||
)
|
||||
if normalized is None:
|
||||
continue
|
||||
values['po_number'] = po_number
|
||||
if values.get('reservation_id'):
|
||||
normalized = validated_reservation_id(values['reservation_id'])
|
||||
if normalized:
|
||||
values['reservation_id'] = normalized
|
||||
else:
|
||||
issues.append('email_supplement_reservation_invalid')
|
||||
rows.append({
|
||||
**values, 'evidence': evidence, 'table_index': table_index,
|
||||
**normalized, 'evidence': evidence, 'table_index': table_index,
|
||||
'row_index': row_index,
|
||||
})
|
||||
result.update({'rows': rows, 'issues': sorted(set(issues))})
|
||||
@@ -134,28 +150,20 @@ def parse_email_allocation_text(*, body_text: str, content_hash: str, schema_def
|
||||
"""
|
||||
result = empty_email_supplement_result()
|
||||
tokens = [line.strip() for line in str(body_text or '').splitlines() if line.strip()]
|
||||
expected = [
|
||||
'allocation_id', 'reservation_id', 'source_from_party', 'source_type',
|
||||
'allocated_entity', 'mpn', 'allocated_qty', 'po_number',
|
||||
]
|
||||
normalized = [normalize_table_header(token) for token in tokens]
|
||||
schema_headers = _schema_headers(schema_definition)
|
||||
aliases: dict[str, set[str]] = {
|
||||
field: {header for header, mapped_field in schema_headers.items() if mapped_field == field}
|
||||
for field in _SCHEMA_FIELD_TO_SUPPLEMENT_FIELD.values()
|
||||
}
|
||||
aliases.update(_NORMALIZED_STATIC_HEADERS)
|
||||
casefold_aliases = {
|
||||
field: {value.casefold() for value in values}
|
||||
for field, values in aliases.items()
|
||||
}
|
||||
start = next((
|
||||
index for index in range(0, len(tokens) - len(expected) + 1)
|
||||
if all(normalized[index + offset].casefold() in casefold_aliases[field] for offset, field in enumerate(expected))
|
||||
), None)
|
||||
header_map = dict(schema_headers)
|
||||
start = next((index for index, value in enumerate(normalized) if header_map.get(value.casefold())), None)
|
||||
if start is None:
|
||||
return result
|
||||
|
||||
expected: list[str] = []
|
||||
for value in normalized[start:]:
|
||||
field = header_map.get(value.casefold())
|
||||
if not field or field in expected:
|
||||
break
|
||||
expected.append(field)
|
||||
if not ({'customer_po_number', 'po_number'} & set(expected)):
|
||||
return result
|
||||
column_count = len(expected)
|
||||
rows: list[dict[str, Any]] = []
|
||||
seen_rows: set[tuple[str, ...]] = set()
|
||||
@@ -163,8 +171,11 @@ def parse_email_allocation_text(*, body_text: str, content_hash: str, schema_def
|
||||
values = tokens[offset:offset + column_count]
|
||||
if len(values) != column_count:
|
||||
break
|
||||
po_number = normalize_po_number(values[-1])
|
||||
if not po_number:
|
||||
row = _normalize_schema_row(
|
||||
{field: value for field, value in zip(expected, values)},
|
||||
schema_definition=schema_definition, issues=result['issues'],
|
||||
)
|
||||
if row is None:
|
||||
# 正文表结束后的普通段落不得作为一条不完整记录继续吞入。
|
||||
break
|
||||
identity = tuple(values)
|
||||
@@ -172,13 +183,6 @@ def parse_email_allocation_text(*, body_text: str, content_hash: str, schema_def
|
||||
if identity in seen_rows:
|
||||
continue
|
||||
seen_rows.add(identity)
|
||||
row = {field: value for field, value in zip(expected, values)}
|
||||
row['po_number'] = po_number
|
||||
reservation_id = validated_reservation_id(row.get('reservation_id'))
|
||||
if not reservation_id:
|
||||
result['issues'].append('email_supplement_reservation_invalid')
|
||||
continue
|
||||
row['reservation_id'] = reservation_id
|
||||
row['evidence'] = {
|
||||
field: {
|
||||
'table_index': None, 'row_index': len(rows) + 1, 'column_index': column,
|
||||
|
||||
@@ -11,7 +11,7 @@ from typing import Any
|
||||
|
||||
EMAIL_SUPPLEMENT_VERSION = 'email-supplement.v1'
|
||||
SUPPLEMENT_FIELDS = (
|
||||
'po_number', 'mpn', 'reservation_id', 'allocation_id', 'source_type',
|
||||
'po_number', 'mpn', 'ampn', 'reservation_id', 'allocation_id', 'source_type',
|
||||
'source_from_party', 'allocated_entity', 'allocated_qty',
|
||||
)
|
||||
|
||||
|
||||
@@ -33,6 +33,19 @@ _SIGNATURE_LOGO_NAME_RE = re.compile(
|
||||
)
|
||||
_HTML_TABLE_TAGS = frozenset({'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td'})
|
||||
_HTML_DROP_TAGS = frozenset({'script', 'style', 'img', 'svg', 'object', 'embed', 'iframe', 'template'})
|
||||
_EML_PREVIEW_TAGS = frozenset({
|
||||
'html', 'body', 'div', 'p', 'span', 'br', 'hr', 'blockquote', 'pre',
|
||||
'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td',
|
||||
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'strong', 'b', 'em', 'i', 'u',
|
||||
})
|
||||
_EML_PREVIEW_STYLE_PROPERTIES = frozenset({
|
||||
'background',
|
||||
'background-color', 'border', 'border-bottom', 'border-collapse', 'border-color', 'border-style',
|
||||
'border-width', 'color', 'font-family', 'font-size', 'font-style', 'font-weight', 'line-height',
|
||||
'margin', 'margin-bottom', 'margin-left', 'margin-right', 'margin-top', 'padding', 'padding-bottom',
|
||||
'padding-left', 'padding-right', 'padding-top', 'text-align', 'text-decoration', 'vertical-align',
|
||||
'white-space', 'width',
|
||||
})
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -260,6 +273,11 @@ def _part_as_text(part: Message) -> str:
|
||||
return text.strip()
|
||||
|
||||
|
||||
def _part_as_raw_html(part: Message) -> str:
|
||||
"""按 MIME charset 解码 HTML 原文,供视觉预览使用;不得经过 HTML 转文本。"""
|
||||
return _decode_part_text(part, _read_part_payload(part))
|
||||
|
||||
|
||||
def _is_attached_multipart(part: Message) -> bool:
|
||||
"""
|
||||
判定 multipart 是否应视为「文件附件容器」(而非可选正文结构)。
|
||||
@@ -380,6 +398,86 @@ def _extract_body_html_tables(msg: Message) -> list[str]:
|
||||
return result
|
||||
|
||||
|
||||
def sanitize_eml_preview_html(html: str) -> str:
|
||||
"""
|
||||
清洗 EML 正文 HTML 为可在 sandbox iframe 中展示的有限视觉快照。
|
||||
|
||||
核心逻辑:仅保留邮件阅读必需的文字/表格标签与有限内联样式;图片、链接、脚本、
|
||||
事件属性和定位/URL 样式全部剥离,避免邮件主动内容影响 HXOPS 页面。
|
||||
|
||||
Args:
|
||||
html: EML 的单个 text/html 正文部件,不得传入附件或嵌套邮件正文。
|
||||
|
||||
Returns:
|
||||
安全 HTML 片段;没有可展示内容时返回空字符串。
|
||||
"""
|
||||
soup = BeautifulSoup(str(html or ''), 'html.parser')
|
||||
for comment in soup.find_all(string=lambda value: isinstance(value, Comment)):
|
||||
comment.extract()
|
||||
for tag in list(soup.find_all(True)):
|
||||
name = str(tag.name or '').lower()
|
||||
if name == 'style':
|
||||
css = str(tag.string or '')
|
||||
css = re.sub(r'(?is)@import[^;]*;', '', css)
|
||||
css = re.sub(r'(?is)url\s*\([^)]*\)', '', css)
|
||||
css = re.sub(r'(?is)expression\s*\([^)]*\)', '', css)
|
||||
tag.string = css
|
||||
continue
|
||||
if name in _HTML_DROP_TAGS or name in {'form', 'input', 'button', 'textarea', 'select', 'option', 'base'}:
|
||||
tag.decompose()
|
||||
continue
|
||||
# 邮件 CSS 由隔离 iframe 自己消费;只禁止外部资源和主动导航,不重写布局属性。
|
||||
for key in list(tag.attrs):
|
||||
key_name = str(key).lower()
|
||||
if key_name.startswith('on') or key_name in {'action', 'formaction', 'src', 'srcset', 'href', 'xlink:href'}:
|
||||
tag.attrs.pop(key, None)
|
||||
if name == 'meta' and str(tag.attrs.get('http-equiv') or '').lower() == 'refresh':
|
||||
tag.decompose()
|
||||
continue
|
||||
inline_styles = [
|
||||
f'{property_name}: {value}'
|
||||
for property_name, value in _parse_inline_style(str(tag.attrs.get('style') or ''))
|
||||
if property_name in _EML_PREVIEW_STYLE_PROPERTIES
|
||||
]
|
||||
if inline_styles:
|
||||
tag.attrs['style'] = '; '.join(inline_styles)
|
||||
else:
|
||||
tag.attrs.pop('style', None)
|
||||
return str(soup).strip()
|
||||
|
||||
|
||||
def _parse_inline_style(value: str) -> list[tuple[str, str]]:
|
||||
"""解析有限 CSS 声明,拒绝 URL、表达式与控制字符等主动样式值。"""
|
||||
result: list[tuple[str, str]] = []
|
||||
for item in str(value or '').split(';'):
|
||||
property_name, separator, raw_value = item.partition(':')
|
||||
name = property_name.strip().lower()
|
||||
normalized = re.sub(r'\s+', ' ', raw_value).strip()
|
||||
if not separator or not name or not normalized:
|
||||
continue
|
||||
if any(token in normalized.lower() for token in ('url(', 'expression(', '@import', '\x00')):
|
||||
continue
|
||||
result.append((name, normalized[:256]))
|
||||
return result
|
||||
|
||||
|
||||
def extract_eml_preview_html(data: bytes) -> str:
|
||||
"""
|
||||
从原始 EML 提取根消息首个 HTML 正文并生成安全视觉快照。
|
||||
|
||||
Args:
|
||||
data: 原始 EML 字节;禁止传入附件展开后的任意子文件。
|
||||
|
||||
Returns:
|
||||
已清洗 HTML;邮件无 HTML 正文时返回空字符串。
|
||||
"""
|
||||
message = BytesParser(policy=policy.default).parsebytes(data or b'')
|
||||
for part in _iter_local_body_candidates(message):
|
||||
if str(part.get_content_type() or '').lower() == 'text/html':
|
||||
return sanitize_eml_preview_html(_part_as_raw_html(part))
|
||||
return ''
|
||||
|
||||
|
||||
def _is_collectible_text_leaf(msg: Message) -> bool:
|
||||
"""判定部件是否可作为附件容器内的可落库文本叶子(非 filename 附件)。"""
|
||||
ctype = str(msg.get_content_type() or "").lower()
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
"""
|
||||
services/shipping_notice/eml_preview_service.py
|
||||
|
||||
用途:按内容身份生成并复用 EML 安全 HTML 预览快照。
|
||||
依赖:FileAsset、ShippingOrderDocument/Intake、eml_parse、file_assets.service。
|
||||
逻辑:复核证据服务在 Case 鉴权后调用;原始 EML 仅在快照缺失时读取,失败由调用方回退纯文本。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
|
||||
from bs4 import BeautifulSoup, NavigableString
|
||||
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.models import FileAsset, ShippingEmlPreviewSnapshot, ShippingOrderDocument, ShippingOrderIntake
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.eml_parse import extract_eml_preview_html, sanitize_eml_preview_html
|
||||
from app.services.shipping_notice.preview_grant_store import preview_grant_store
|
||||
|
||||
EML_PREVIEW_SANITIZER_VERSION = 'eml-preview-v3'
|
||||
EML_PREVIEW_MAX_BYTES = 500_000
|
||||
EML_PREVIEW_GRANT_TTL_SECONDS = 120
|
||||
EML_PREVIEW_GRANT_KEY_PREFIX = 'shipping:eml-preview:'
|
||||
|
||||
|
||||
def highlight_eml_preview_html(html: str, quote: str | None) -> str:
|
||||
"""
|
||||
在安全 EML 快照中标出唯一命中的字段证据引文。
|
||||
|
||||
核心逻辑:仅在单个可见文本节点中恰好命中一次时插入无行为的 mark;
|
||||
缺失、跨节点或多处命中均原样返回,禁止按字段值猜测高亮位置。
|
||||
|
||||
Args:
|
||||
html: 已由 sanitize_eml_preview_html 生成的安全 HTML。
|
||||
quote: 当前字段 Observation 的独立引文,不得传机器字段值作为替代。
|
||||
|
||||
Returns:
|
||||
安全 HTML;可靠唯一定位时含 data-hxops-evidence-mark 的 mark 标签。
|
||||
"""
|
||||
needle = str(quote or '').strip()
|
||||
if not needle:
|
||||
return str(html or '')
|
||||
soup = BeautifulSoup(str(html or ''), 'html.parser')
|
||||
matches: list[tuple[NavigableString, int]] = []
|
||||
for node in soup.find_all(string=True):
|
||||
text = str(node)
|
||||
start = text.find(needle)
|
||||
if start < 0:
|
||||
continue
|
||||
if text.find(needle, start + len(needle)) >= 0:
|
||||
return str(html or '')
|
||||
matches.append((node, start))
|
||||
if len(matches) > 1:
|
||||
return str(html or '')
|
||||
if len(matches) != 1:
|
||||
return str(html or '')
|
||||
node, start = matches[0]
|
||||
text = str(node)
|
||||
mark = soup.new_tag('mark')
|
||||
mark['data-hxops-evidence-mark'] = 'true'
|
||||
mark['style'] = 'background: #fde047; color: inherit; outline: 2px solid #ca8a04; outline-offset: 1px;'
|
||||
mark.string = needle
|
||||
node.replace_with(NavigableString(text[:start]), mark, NavigableString(text[start + len(needle):]))
|
||||
return str(soup)
|
||||
|
||||
|
||||
def _eml_preview_grant_store():
|
||||
"""返回 EML iframe 单用途预览令牌存储;生产必须使用 Redis。"""
|
||||
return preview_grant_store()
|
||||
|
||||
|
||||
def issue_eml_preview_grant(*, user_id: int, case_no: str, document_id: int, html: str) -> str:
|
||||
"""签发绑定用户、Case 与正文 Document 的短时单用途 iframe 预览令牌。"""
|
||||
token = secrets.token_urlsafe(32)
|
||||
payload = json.dumps({
|
||||
'user_id': int(user_id), 'case_no': str(case_no), 'document_id': int(document_id), 'html': str(html),
|
||||
}, separators=(',', ':'))
|
||||
_eml_preview_grant_store().setex(
|
||||
f'{EML_PREVIEW_GRANT_KEY_PREFIX}{token}', EML_PREVIEW_GRANT_TTL_SECONDS, payload,
|
||||
)
|
||||
return token
|
||||
|
||||
|
||||
def consume_eml_preview_grant(*, token: str, user_id: int | None = None, case_no: str, document_id: int | None = None) -> str:
|
||||
"""消费单用途令牌并只返回匹配当前用户/Case 的安全 HTML。"""
|
||||
raw = _eml_preview_grant_store().getdel(f'{EML_PREVIEW_GRANT_KEY_PREFIX}{str(token or "").strip()}')
|
||||
if not raw:
|
||||
return ''
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
except (TypeError, ValueError):
|
||||
return ''
|
||||
if (
|
||||
(user_id is not None and int(payload.get('user_id') or 0) != int(user_id))
|
||||
or str(payload.get('case_no') or '') != str(case_no)
|
||||
or (document_id is not None and int(payload.get('document_id') or 0) != int(document_id))
|
||||
):
|
||||
return ''
|
||||
return str(payload.get('html') or '')
|
||||
|
||||
|
||||
def get_or_create_eml_preview_html(*, document: ShippingOrderDocument) -> str:
|
||||
"""
|
||||
读取或生成邮件正文安全 HTML 快照。
|
||||
|
||||
核心逻辑:以正文 Document 内容哈希和清洗器版本唯一定位;未命中时才读取其 Intake 根 EML,
|
||||
生成成功后写入快照。调用者已负责 Case 属主鉴权,本函数绝不返回存储地址。
|
||||
|
||||
Args:
|
||||
document: 同 Intake 的 email_body Document;其它类型调用返回空字符串。
|
||||
|
||||
Returns:
|
||||
可嵌入 sandbox iframe 的已清洗 HTML;无 HTML 正文或读取失败时为空字符串。
|
||||
"""
|
||||
if str(document.document_type or '') != 'email_body':
|
||||
return ''
|
||||
intake = db.session.get(ShippingOrderIntake, int(document.intake_id))
|
||||
asset = db.session.get(FileAsset, int(intake.asset_id)) if intake and intake.asset_id else None
|
||||
if asset is None:
|
||||
return ''
|
||||
# [STEP 1] 视觉快照按原始 EML 哈希隔离,不能使用只覆盖文本/表格的 Document 哈希。
|
||||
source_hash = str(asset.content_hash or '').strip().lower()
|
||||
if len(source_hash) != 64:
|
||||
return ''
|
||||
existing = ShippingEmlPreviewSnapshot.query.filter_by(
|
||||
document_id=int(document.id), source_content_hash=source_hash,
|
||||
sanitizer_version=EML_PREVIEW_SANITIZER_VERSION,
|
||||
).one_or_none()
|
||||
if existing is not None:
|
||||
return str(existing.html or '')
|
||||
try:
|
||||
html = extract_eml_preview_html(read_asset_bytes(asset))
|
||||
except Exception: # noqa: BLE001 - 预览失败必须回退文本,不能影响复核主链。
|
||||
return ''
|
||||
if not html:
|
||||
return ''
|
||||
encoded = html.encode('utf-8')
|
||||
if len(encoded) > EML_PREVIEW_MAX_BYTES:
|
||||
return ''
|
||||
snapshot = ShippingEmlPreviewSnapshot(
|
||||
document_id=int(document.id), source_content_hash=source_hash,
|
||||
sanitizer_version=EML_PREVIEW_SANITIZER_VERSION, html=html,
|
||||
html_checksum=hashlib.sha256(encoded).hexdigest(), html_size_bytes=len(encoded),
|
||||
)
|
||||
try:
|
||||
# [STEP 2] 并发首次预览只竞争本快照,不能 rollback 当前 Case 读取事务。
|
||||
with db.session.begin_nested():
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
except IntegrityError:
|
||||
reused = ShippingEmlPreviewSnapshot.query.filter_by(
|
||||
document_id=int(document.id), source_content_hash=source_hash,
|
||||
sanitizer_version=EML_PREVIEW_SANITIZER_VERSION,
|
||||
).one_or_none()
|
||||
return str(reused.html or '') if reused is not None else ''
|
||||
return html
|
||||
|
||||
|
||||
__all__ = [
|
||||
'EML_PREVIEW_MAX_BYTES', 'EML_PREVIEW_SANITIZER_VERSION', 'EML_PREVIEW_GRANT_TTL_SECONDS',
|
||||
'consume_eml_preview_grant', 'get_or_create_eml_preview_html', 'issue_eml_preview_grant',
|
||||
'sanitize_eml_preview_html', 'highlight_eml_preview_html',
|
||||
]
|
||||
@@ -90,7 +90,16 @@ DOCUMENT_PARSE_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_profile_checksum_not_allowlisted',
|
||||
'xfa_scenario_not_allowlisted',
|
||||
'xfa_evidence_incomplete',
|
||||
'xfa_fallback_requires_review',
|
||||
'xfa_cross_check_failed',
|
||||
# adapter 证据与统一视觉发布门禁:均须进入同一 Review / Gate 投影契约。
|
||||
'xfa_mapping_required',
|
||||
'xfa_visual_coverage_insufficient',
|
||||
'xfa_evidence_retention_insufficient',
|
||||
'xfa_mirror_consistency_insufficient',
|
||||
'xfa_profile_checksum_mismatch',
|
||||
'xfa_visual_not_publishable',
|
||||
'xfa_split_rule_unconfirmed',
|
||||
})
|
||||
|
||||
# 字段抽取、客户与订单校验
|
||||
@@ -217,13 +226,14 @@ EXPLAINABILITY_REASON_ALIASES: Final[dict[str, str]] = {
|
||||
'document_profile_not_matched': 'profile_not_matched',
|
||||
'document_profile_ambiguous': 'profile_ambiguous',
|
||||
'document_profile_drifted': 'profile_drift',
|
||||
# Job 历史误写 → 跨门禁技术重试耗尽
|
||||
'technical_failure': 'technical_retry_exhausted',
|
||||
# 历史“重试耗尽”不再对用户暴露;统一为停止后的中性技术失败。
|
||||
'technical_failure': 'technical_failure_present',
|
||||
'technical_retry_exhausted': 'technical_failure_present',
|
||||
# 订单识别 Run.error_code(DOMAIN.SUBTYPE)→ 稳定业务原因码
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_FAILED': 'layout_parse_failed',
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_SCHEDULING_FAILED': 'layout_parse_failed',
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT': 'extraction_incomplete',
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_JOB_FAILED': 'technical_retry_exhausted',
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_JOB_FAILED': 'technical_failure_present',
|
||||
# 抽取失败 / 取消必须可区分,禁止一并降级为 unknown_business_failure
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED': 'order_extraction_failed',
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_CANCELLED': 'order_extraction_cancelled',
|
||||
@@ -437,10 +447,10 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'xfa_evidence_retention_insufficient': _meta('owner', 'open_order_review', 'XFA 证据留存不足,请进入复核补充证据'),
|
||||
'xfa_mirror_consistency_insufficient': _meta('owner', 'open_order_review', 'XFA 镜像明细一致性不足,请进入复核'),
|
||||
'xfa_profile_checksum_mismatch': _meta('admin', 'open_profile_review', 'XFA 模板校验和不一致,请联系管理员检查模板版本'),
|
||||
'xfa_visual_binding_incomplete': _meta('owner', 'open_profile_review', 'XFA 可视化字段绑定不完整,请补充模板绑定'),
|
||||
'xfa_visual_bindings_required': _meta('owner', 'open_profile_review', 'XFA 尚未完成可视化字段绑定'),
|
||||
'xfa_mapping_required': _meta('owner', 'open_profile_review', '末端值源映射不完整,请补充字段映射'),
|
||||
'xfa_visual_coverage_insufficient': _meta('owner', 'open_profile_review', 'XFA 可视化字段覆盖不足,请补充模板映射'),
|
||||
'xfa_visual_not_publishable': _meta('admin', 'open_profile_review', 'XFA 可视化模板未达到发布条件,请检查模板质量'),
|
||||
'xfa_split_rule_unconfirmed': _meta('owner', 'open_profile_review', 'XFA 字段拆分规则尚未完成确认,请复核后保存模板'),
|
||||
# 附件
|
||||
'attachment_format_unsupported': _meta('owner', 'rematerialize_document', '附件格式不支持'),
|
||||
'attachment_size_exceeded': _meta('owner', 'rematerialize_document', '附件超过系统大小限制'),
|
||||
@@ -491,6 +501,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'xfa_profile_checksum_not_allowlisted': _meta('admin', 'open_profile_review', 'Profile checksum 不在 XFA 试点白名单'),
|
||||
'xfa_scenario_not_allowlisted': _meta('admin', 'open_order_review', '业务场景不在 XFA 试点白名单'),
|
||||
'xfa_evidence_incomplete': _meta('owner', 'open_order_review', 'XFA 证据不完整'),
|
||||
'xfa_fallback_requires_review': _meta('owner', 'open_order_review', 'XFA datasets 未能产值,已使用 PDF 证据链,请人工复核'),
|
||||
'xfa_cross_check_failed': _meta('owner', 'open_order_review', 'XFA 对账或业务恒等式未通过'),
|
||||
# Gate 既有阻断码
|
||||
'document_unavailable': _meta('system', 'rematerialize_document', '发货通知文档不可用,请重新上传或物化文档'),
|
||||
@@ -536,20 +547,20 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'task_already_exists': _meta('owner', 'open_order_review', '已存在相同订单任务'),
|
||||
'task_state_not_creatable': _meta('owner', 'open_order_review', '当前任务状态不允许重复创建'),
|
||||
# 库存源路由
|
||||
'no_inventory_source_candidates': _meta('owner', 'open_inventory_source_review', '未匹配到库存源规则'),
|
||||
'inventory_source_unavailable': _meta('admin', 'open_inventory_source_review', '规则命中的库存源当前不可用'),
|
||||
'require_manual_review': _meta('owner', 'open_inventory_source_review', '库存源规则冲突或要求人工确认'),
|
||||
'manual_inventory_source_reason_required': _meta('owner', 'open_inventory_source_review', '须填写人工选源原因'),
|
||||
'manual_inventory_source_invalid': _meta('owner', 'open_inventory_source_review', '所选库存源无效或未启用'),
|
||||
'source_not_found': _meta('admin', 'open_inventory_source_review', '规则命中的库存源不存在'),
|
||||
'source_disabled': _meta('admin', 'open_inventory_source_review', '规则命中的库存源未启用'),
|
||||
'source_runtime_unavailable': _meta('admin', 'open_inventory_source_review', '库存源 RPA 运行配置不可用'),
|
||||
'source_profile_disabled': _meta('admin', 'open_inventory_source_review', '库存源对应的 RPA Profile 未启用'),
|
||||
'parsing_profile_unavailable': _meta('admin', 'open_inventory_source_review', '库存解析 Profile 未发布'),
|
||||
'source_excel_template_unavailable': _meta('admin', 'open_inventory_source_review', '库存 Excel 模板未发布'),
|
||||
'inventory_source_conflicted': _meta('owner', 'open_inventory_source_review', '多条规则产生冲突,需要人工确认'),
|
||||
'inventory_source_changed': _meta('owner', 'open_inventory_source_review', '原已确认库存源配置已变化'),
|
||||
'inventory_source_identity_mismatch': _meta('owner', 'open_inventory_source_review', '当前任务与库存源/仓库身份不一致'),
|
||||
'no_inventory_source_candidates': _meta('system', 'retry_with_latest_rules', '未匹配到库存源规则'),
|
||||
'inventory_source_unavailable': _meta('admin', 'retry_with_latest_rules', '规则命中的库存源当前不可用'),
|
||||
'require_manual_review': _meta('system', 'retry_with_latest_rules', '库存源规则冲突,需修复规则后自动重新裁决'),
|
||||
'manual_inventory_source_reason_required': _meta('system', 'retry_with_latest_rules', '历史人工选源请求已下线,请修复路由规则'),
|
||||
'manual_inventory_source_invalid': _meta('system', 'retry_with_latest_rules', '历史人工选源无效,请修复路由规则'),
|
||||
'source_not_found': _meta('admin', 'retry_with_latest_rules', '规则命中的库存源不存在'),
|
||||
'source_disabled': _meta('admin', 'retry_with_latest_rules', '规则命中的库存源未启用'),
|
||||
'source_runtime_unavailable': _meta('admin', 'retry_with_latest_rules', '库存源 RPA 运行配置不可用'),
|
||||
'source_profile_disabled': _meta('admin', 'retry_with_latest_rules', '库存源对应的 RPA Profile 未启用'),
|
||||
'parsing_profile_unavailable': _meta('admin', 'retry_with_latest_rules', '库存解析 Profile 未发布'),
|
||||
'source_excel_template_unavailable': _meta('admin', 'retry_with_latest_rules', '库存 Excel 模板未发布'),
|
||||
'inventory_source_conflicted': _meta('system', 'retry_with_latest_rules', '多条规则产生冲突,需修复规则后自动重新裁决'),
|
||||
'inventory_source_changed': _meta('system', 'retry_with_latest_rules', '库存源配置已变化,系统将重新裁决'),
|
||||
'inventory_source_identity_mismatch': _meta('system', 'retry_with_latest_rules', '当前任务与库存源身份不一致,需修复规则或订单事实'),
|
||||
'effective_reservation_missing': _meta('owner', 'edit_reservation', '缺少有效的预约单号'),
|
||||
# 库存准备 / RPA / 匹配 / Excel / 上传
|
||||
'inventory_preparation_waiting': _meta('worker', 'poll_inventory_preparation', '库存文件准备中,请稍后刷新'),
|
||||
@@ -560,13 +571,13 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'inventory_rpa_export_failed': _meta('worker', 'retry_inventory_preparation', '库存报表导出失败'),
|
||||
'inventory_rpa_exhausted': _meta('owner', 'upload_inventory_file', '库存源重试次数已耗尽'),
|
||||
'inventory_file_missing': _meta('owner', 'upload_inventory_file', '未生成库存文件'),
|
||||
'inventory_candidates_missing': _meta('owner', 'open_inventory_source_review', '正式库存候选版本缺失'),
|
||||
'inventory_candidate_data_incomplete': _meta('owner', 'open_inventory_source_review', '库存候选事实不完整'),
|
||||
'inventory_candidate_version_stale': _meta('owner', 'open_inventory_source_review', '库存候选版本已切换'),
|
||||
'inventory_match_out_of_candidate_scope': _meta('owner', 'open_inventory_source_review', '库存命中超出当前候选范围'),
|
||||
'inventory_candidates_missing': _meta('system', 'retry_with_latest_rules', '正式库存候选版本缺失'),
|
||||
'inventory_candidate_data_incomplete': _meta('system', 'retry_with_latest_rules', '库存候选事实不完整'),
|
||||
'inventory_candidate_version_stale': _meta('system', 'retry_with_latest_rules', '库存候选版本已切换'),
|
||||
'inventory_match_out_of_candidate_scope': _meta('system', 'retry_with_latest_rules', '库存命中超出当前候选范围'),
|
||||
'inventory_file_identity_mismatch': _meta('owner', 'retry_inventory_preparation', '返回文件与所选库存源不一致'),
|
||||
'inventory_file_empty': _meta('owner', 'retry_inventory_preparation', '库存文件为空或没有有效库存记录'),
|
||||
'inventory_mapping_required': _meta('owner', 'confirm_inventory_field_mapping', '库存字段映射待确认'),
|
||||
'inventory_mapping_required': _meta('system', 'retry_inventory_field_mapping', '库存字段映射待自动校验'),
|
||||
'inventory_match_failed': _meta('owner', 'open_inventory_match_review', '库存匹配失败'),
|
||||
'inventory_insufficient': _meta('owner', 'open_shortage_review', '库存不足'),
|
||||
'inventory_shortage_review_required': _meta('owner', 'open_shortage_review', '存在库存缺口,需要人工处理'),
|
||||
@@ -581,11 +592,6 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'review_required': _meta('owner', 'open_order_review', '需要人工复核后才能继续'),
|
||||
'gate_invalidated': _meta('system', 'recheck_freeze_readiness', '上游结果已变化,当前门禁需重新评估'),
|
||||
'technical_failure_present': _meta('system', 'open_order_review', '存在技术失败,需处理后继续'),
|
||||
'technical_retry_exhausted': _meta(
|
||||
'system',
|
||||
'open_order_review',
|
||||
'系统自动重试已耗尽,请打开订单复核或联系管理员处理',
|
||||
),
|
||||
'order_extraction_failed': _meta('worker', 'retry_order_extraction', '订单字段抽取失败,请重试或进入复核'),
|
||||
'order_extraction_cancelled': _meta('owner', 'open_order_review', '订单抽取已取消'),
|
||||
# 关闭 / 作废 / 访问审计动作码
|
||||
@@ -601,8 +607,8 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'excel_template_missing': _meta('admin', 'recheck_excel_readiness', '发货 Excel 模板缺失'),
|
||||
'excel_input_incomplete': _meta('owner', 'recheck_excel_readiness', '生成 Excel 所需输入不完整'),
|
||||
'artifact_validation_failed': _meta('system', 'regenerate_excel_artifact', 'Excel 产物校验失败'),
|
||||
'inventory_required_column_missing': _meta('owner', 'confirm_inventory_field_mapping', '库存文件缺少必填列'),
|
||||
'inventory_column_ambiguous': _meta('owner', 'confirm_inventory_field_mapping', '库存列映射存在歧义'),
|
||||
'inventory_required_column_missing': _meta('system', 'retry_inventory_field_mapping', '库存文件缺少必填列'),
|
||||
'inventory_column_ambiguous': _meta('system', 'retry_inventory_field_mapping', '库存列映射存在歧义'),
|
||||
'inventory_sku_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 SKU'),
|
||||
'inventory_reservation_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 Reservation'),
|
||||
'inventory_warehouse_mismatch': _meta('owner', 'open_inventory_match_review', '仓库与订单要求不一致'),
|
||||
|
||||
@@ -116,6 +116,21 @@ def _system_fact(
|
||||
return values.get(key)
|
||||
|
||||
|
||||
def _template_requires_system_warehouse_id(mappings: list[dict[str, Any]]) -> bool:
|
||||
"""判断发布模板是否实际消费任务级 ``system_fact:warehouse_id``。
|
||||
|
||||
模板将库位作为 ``inventory_field`` 消费时,值来自库存快照或已审计的
|
||||
短缺放行补录字段;不得额外要求任务级 Warehouse ID。只有模板显式引用
|
||||
系统事实时才保留该 fail-closed 门禁。
|
||||
"""
|
||||
return any(
|
||||
isinstance(mapping, dict)
|
||||
and str(mapping.get('source_kind') or '').strip() == 'system_fact'
|
||||
and str(mapping.get('source_key') or '').strip() == 'warehouse_id'
|
||||
for mapping in mappings
|
||||
)
|
||||
|
||||
|
||||
def _format_value(value: Any, formatter: str) -> Any:
|
||||
"""应用发布契约允许的确定性格式化器。"""
|
||||
if value is None:
|
||||
@@ -227,26 +242,40 @@ def _inventory_field_user_label(field_id: str) -> str:
|
||||
return f'库存字段(编号 {normalized or "未知"})'
|
||||
|
||||
|
||||
def _collapse_inventory_matches(rows: list[dict[str, Any]], required_fields: set[str]) -> dict[str, Any]:
|
||||
"""多库存行仅在模板所需字段值一致时合并,避免任意选择第一行。"""
|
||||
def _collapse_inventory_matches(
|
||||
rows: list[dict[str, Any]],
|
||||
required_fields: set[str],
|
||||
*,
|
||||
release_overrides: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""多库存行仅在模板所需字段值一致时合并;短缺放行仅可覆盖该行已审计字段。"""
|
||||
if not rows:
|
||||
return {}
|
||||
resolved = dict(rows[0])
|
||||
for field in required_fields:
|
||||
values = {_match_text(row.get(field)) for row in rows if _match_text(row.get(field))}
|
||||
override = str((release_overrides or {}).get(field) or '').strip()
|
||||
if len(values) > 1:
|
||||
if override:
|
||||
resolved[field] = override
|
||||
continue
|
||||
label = _inventory_field_user_label(field)
|
||||
raise ValueError(f'订单行匹配到多个库存记录,库存字段“{label}”的值不一致,请检查库存映射或库存文件')
|
||||
if values:
|
||||
resolved[field] = next(row.get(field) for row in rows if _match_text(row.get(field)))
|
||||
elif override:
|
||||
resolved[field] = override
|
||||
return resolved
|
||||
|
||||
|
||||
def _match_inventory_lines(
|
||||
order_lines: list[dict[str, Any]], inventory_lines: list[dict[str, Any]],
|
||||
match_keys: list[dict[str, str]], required_fields: set[str],
|
||||
*,
|
||||
release_overrides_by_line: dict[int, dict[str, Any]] | None = None,
|
||||
released_export_line_indexes: set[int] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""按 published 解析 Profile 的稳定字段匹配键解析每条订单行对应库存投影。"""
|
||||
"""按发布匹配键解析库存投影;已审计短缺放行可在导出时使用订单与补录事实。"""
|
||||
if not order_lines:
|
||||
return []
|
||||
if not match_keys:
|
||||
@@ -287,11 +316,60 @@ def _match_inventory_lines(
|
||||
if all(_match_text(row.get(inventory_field)) == value for value, inventory_field in expected)
|
||||
]
|
||||
if not matched:
|
||||
# 短缺放行不改写或伪造库存匹配事实。它只授权导出阶段在匹配键
|
||||
# (例如 Reservation ID)未命中时,以冻结订单字段及已审计补录值
|
||||
# 写模板;模板不消费库存字段时,空映射也是完整、可审计的输入。
|
||||
overrides = (release_overrides_by_line or {}).get(position - 1) or {}
|
||||
resolved_overrides = {
|
||||
field: value
|
||||
for field, value in overrides.items()
|
||||
if field in required_fields and _match_text(value)
|
||||
}
|
||||
is_released = (position - 1) in (released_export_line_indexes or set())
|
||||
if is_released and set(resolved_overrides) == required_fields:
|
||||
result.append(resolved_overrides)
|
||||
continue
|
||||
raise ValueError(f'第 {position} 条订单行没有匹配的库存记录')
|
||||
result.append(_collapse_inventory_matches(matched, required_fields))
|
||||
result.append(_collapse_inventory_matches(
|
||||
matched,
|
||||
required_fields,
|
||||
release_overrides=(release_overrides_by_line or {}).get(position - 1),
|
||||
))
|
||||
return result
|
||||
|
||||
|
||||
def _release_overrides_for_export_lines(
|
||||
*,
|
||||
line_values: list[dict[str, Any]],
|
||||
release_overrides_by_source_line: dict[int, dict[str, Any]],
|
||||
) -> dict[int, dict[str, Any]]:
|
||||
"""
|
||||
将冻结订单原始行索引映射为本次 Excel 连续行索引。
|
||||
|
||||
核心逻辑:原始首行索引 ``0`` 是有效业务值,不能以 ``or`` 回退为缺失值;
|
||||
仅传递该行已审计的短缺放行字段,其他行不受影响。
|
||||
|
||||
Args:
|
||||
line_values: 已按本次可导出集合筛选的订单行,含 ``__order_line_index``。
|
||||
release_overrides_by_source_line: 原始冻结订单行索引 → 放行补录字段。
|
||||
|
||||
Returns:
|
||||
Excel 连续行索引 → 放行补录字段。
|
||||
"""
|
||||
overrides: dict[int, dict[str, Any]] = {}
|
||||
for export_index, row in enumerate(line_values):
|
||||
source_index = row.get('__order_line_index')
|
||||
if isinstance(source_index, bool):
|
||||
continue
|
||||
try:
|
||||
normalized_source_index = int(source_index)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if normalized_source_index in release_overrides_by_source_line:
|
||||
overrides[export_index] = release_overrides_by_source_line[normalized_source_index]
|
||||
return overrides
|
||||
|
||||
|
||||
def _header_inventory_values(
|
||||
matched_lines: list[dict[str, Any]], required_fields: set[str],
|
||||
) -> dict[str, Any]:
|
||||
@@ -373,8 +451,8 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
if not task_is_active(task):
|
||||
raise ValueError('已作废或归档的任务不能生成发货 Excel')
|
||||
assert_task_not_supersession_blocked(task)
|
||||
# [T6 E2 硬门禁] 生成 Excel 前强制断言所有当前行匹配结果均为 matched;
|
||||
# 即使单源任务有明确 inventory_source_code,行级短缺/冲突仍须先处理,避免导出不完整数据。
|
||||
# [T6 E2 硬门禁] 生成 Excel 前复用库存满足性判定:每行须库存充足,
|
||||
# 或为带原因的正式短缺放行;未匹配/冲突绝不能用放行绕过。
|
||||
if task.id is not None:
|
||||
pending_rows = db.session.query(
|
||||
ShippingNoticeLineInventoryMatch.line_key,
|
||||
@@ -385,14 +463,13 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
).filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == task.id,
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
ShippingNoticeLineInventoryMatch.match_result != 'matched',
|
||||
).limit(20).all()
|
||||
pending_count = db.session.query(func.count(ShippingNoticeLineInventoryMatch.id)).filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == task.id,
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
ShippingNoticeLineInventoryMatch.match_result != 'matched',
|
||||
).scalar() or 0
|
||||
if pending_count > 0:
|
||||
# 行级库存事实是当前正式放行 Gate 的真相。历史导出任务可能只有
|
||||
# Reservation 核验轮次;这类任务继续由下方 Reservation 选择保护,不能因
|
||||
# 缺少新表事实被误判为“未匹配”。
|
||||
has_line_match_facts = bool(pending_rows)
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_completed
|
||||
if has_line_match_facts and not match_completed(task):
|
||||
details = [
|
||||
{
|
||||
'line_key': r[0],
|
||||
@@ -404,12 +481,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
for r in pending_rows
|
||||
]
|
||||
raise AppError(
|
||||
error_code='excel_not_ready',
|
||||
status_code=409,
|
||||
blocking_reason_code='inventory_match_incomplete',
|
||||
message=f'存在 {pending_count} 行库存未完全匹配,禁止生成发货 Excel(请先处理短缺或冲突)。',
|
||||
code='SHIPPING.EXCEL_NOT_READY',
|
||||
message='存在未满足或未放行的库存行,禁止生成发货 Excel(请先处理短缺或冲突)。',
|
||||
http_status=409,
|
||||
details={
|
||||
'pending_count': int(pending_count),
|
||||
'blocking_reason_code': 'inventory_match_incomplete',
|
||||
'pending_count': len(pending_rows),
|
||||
'pending_rows_preview': details,
|
||||
'resume_suggestion': '调用 match_inventory 重匹配或人工逐行确认短缺/冲突后再导出。',
|
||||
},
|
||||
@@ -429,15 +506,20 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code_candidate, enabled=True).first() if source_code_candidate else None
|
||||
if source is None:
|
||||
raise ValueError('库存源不存在或已停用,不能生成发货 Excel')
|
||||
# Fixed Sources receive this value from configuration; dynamic Sources receive it
|
||||
# only after Reservation ID + Part Number resolves a unique inventory Warehouse.
|
||||
if not str(task.inventory_warehouse_id or '').strip():
|
||||
raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel')
|
||||
template = source.excel_template
|
||||
if template is None or template.status != 'published':
|
||||
raise ValueError('库存源未绑定已发布的发货 Excel 模板')
|
||||
if source.parsing_profile is None or source.parsing_profile.status != 'published':
|
||||
raise ValueError('库存源未绑定已发布的库存解析模板')
|
||||
definition = template.definition_json or {}
|
||||
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
|
||||
if not mappings:
|
||||
raise ValueError('发货 Excel 模板没有已发布的字段映射')
|
||||
# Fixed Sources receive task Warehouse ID from configuration; dynamic Sources
|
||||
# resolve it only after Reservation ID + Part Number matches. This requirement
|
||||
# applies only when the published template actually consumes that system fact.
|
||||
if _template_requires_system_warehouse_id(mappings) and not str(task.inventory_warehouse_id or '').strip():
|
||||
raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel')
|
||||
active_artifact = ShippingExportArtifact.query.filter(
|
||||
ShippingExportArtifact.task_id == task.id,
|
||||
ShippingExportArtifact.status.in_({'ready', 'uploading'}),
|
||||
@@ -454,30 +536,76 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
current_available_snapshot_line_ids,
|
||||
reserve_available_for_artifact,
|
||||
)
|
||||
verification, available_line_ids = current_available_snapshot_line_ids(task)
|
||||
# [STEP 1] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。
|
||||
profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {}
|
||||
match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else []
|
||||
line_inventory_fields = _inventory_fields_by_mode(mappings, 'line')
|
||||
header_inventory_fields = _inventory_fields_by_mode(mappings, 'header')
|
||||
# [STEP 1] 短缺放行的人工字段仅从该行的活动决定审计快照读取,
|
||||
# 只能补模板行级库存字段,不能污染快照或任务级库存输入。
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
|
||||
release_overrides_by_source_line: dict[int, dict[str, Any]] = {}
|
||||
released_source_line_indexes: set[int] = set()
|
||||
if task.id is not None:
|
||||
release_rows = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage',
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for decision in release_rows:
|
||||
values = dict(decision.snapshot_json or {}).get('release_field_values')
|
||||
if isinstance(values, dict) and decision.line_index is not None:
|
||||
source_line_index = int(decision.line_index)
|
||||
released_source_line_indexes.add(source_line_index)
|
||||
release_overrides_by_source_line[source_line_index] = {
|
||||
str(key): value for key, value in values.items()
|
||||
}
|
||||
released_snapshot_line_ids = {
|
||||
int(line.id)
|
||||
for source_index, line in enumerate(snapshot.lines)
|
||||
if source_index in release_overrides_by_source_line
|
||||
}
|
||||
verification, available_line_ids = current_available_snapshot_line_ids(
|
||||
task,
|
||||
released_snapshot_line_ids=released_snapshot_line_ids,
|
||||
)
|
||||
# [STEP 2] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。
|
||||
line_values = []
|
||||
for line, values in zip(snapshot.lines, all_line_values, strict=True):
|
||||
for source_index, (line, values) in enumerate(zip(snapshot.lines, all_line_values, strict=True)):
|
||||
if line.id not in available_line_ids:
|
||||
continue
|
||||
row = dict(values)
|
||||
row['__order_line_index'] = source_index
|
||||
line_values.append(row)
|
||||
for index, row in enumerate(line_values, start=1):
|
||||
row['__export_sequence'] = index
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
|
||||
|
||||
# [STEP 2] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。
|
||||
# [STEP 3] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。
|
||||
inventory_lines = resolve_inventory_lines_for_execution(task)
|
||||
definition = template.definition_json or {}
|
||||
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
|
||||
if not mappings:
|
||||
raise ValueError('发货 Excel 模板没有已发布的字段映射')
|
||||
profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {}
|
||||
match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else []
|
||||
line_inventory_fields = _inventory_fields_by_mode(mappings, 'line')
|
||||
header_inventory_fields = _inventory_fields_by_mode(mappings, 'header')
|
||||
release_overrides_by_line = _release_overrides_for_export_lines(
|
||||
line_values=line_values,
|
||||
release_overrides_by_source_line=release_overrides_by_source_line,
|
||||
)
|
||||
released_export_line_indexes = {
|
||||
export_index
|
||||
for export_index, row in enumerate(line_values)
|
||||
if isinstance(row.get('__order_line_index'), int)
|
||||
and not isinstance(row.get('__order_line_index'), bool)
|
||||
and int(row['__order_line_index']) in released_source_line_indexes
|
||||
}
|
||||
matched_inventory_lines = _match_inventory_lines(
|
||||
line_values, inventory_lines, match_keys, line_inventory_fields | header_inventory_fields,
|
||||
line_values,
|
||||
inventory_lines,
|
||||
match_keys,
|
||||
line_inventory_fields | header_inventory_fields,
|
||||
release_overrides_by_line=release_overrides_by_line,
|
||||
released_export_line_indexes=released_export_line_indexes,
|
||||
) if (line_inventory_fields or header_inventory_fields) else [{} for _item in line_values]
|
||||
header_inventory = _header_inventory_values(matched_inventory_lines, header_inventory_fields)
|
||||
|
||||
@@ -540,7 +668,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
)
|
||||
db.session.add(artifact)
|
||||
db.session.flush()
|
||||
reserve_available_for_artifact(task, artifact=artifact, verification=verification)
|
||||
reserve_available_for_artifact(
|
||||
task,
|
||||
artifact=artifact,
|
||||
verification=verification,
|
||||
released_snapshot_line_ids=released_snapshot_line_ids,
|
||||
)
|
||||
return str(path), filename, artifact
|
||||
except Exception:
|
||||
if path.is_file():
|
||||
|
||||
@@ -146,6 +146,22 @@ def _heuristic_extract(
|
||||
warnings,
|
||||
)
|
||||
|
||||
# Schema 已明确时,表格没有通过冻结表头契约就不能再退回固定正则猜字段。
|
||||
if schema_definition:
|
||||
warnings.append("schema_table_no_lines")
|
||||
return (
|
||||
{
|
||||
"customer_name": customer_name,
|
||||
"customer_code": "",
|
||||
"ship_to": "",
|
||||
"required_date": "",
|
||||
"lines": [],
|
||||
"confidence": 0.0,
|
||||
},
|
||||
0.0,
|
||||
warnings,
|
||||
)
|
||||
|
||||
lines = []
|
||||
for m in re.finditer(r"([A-Za-z0-9\-_]{3,})\s*[xX×*]\s*(\d+(?:\.\d+)?)", text):
|
||||
lines.append({"part_number": m.group(1), "qty": float(m.group(2))})
|
||||
|
||||
@@ -21,6 +21,7 @@ from __future__ import annotations
|
||||
from pathlib import Path
|
||||
|
||||
from datetime import datetime
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
@@ -43,6 +44,14 @@ from app.services.shipping_notice.query_service import (
|
||||
)
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.order_field_purposes import task_line_purpose_values
|
||||
|
||||
|
||||
def _line_shortage_qty(value: Any) -> Decimal:
|
||||
"""将行短缺数量安全归一;非法值不得被误判为已放行。"""
|
||||
try:
|
||||
return Decimal(str(value or '0'))
|
||||
except (InvalidOperation, ValueError):
|
||||
return Decimal('0')
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
|
||||
from app.services.shipping_notice.upload_attempt_service import (
|
||||
@@ -623,16 +632,35 @@ def match_completed(task: ShippingNotice) -> bool:
|
||||
|
||||
核心逻辑:禁止 partial / 任意一行短缺、冲突、未命中进入自动制单或 Excel 门禁。
|
||||
"""
|
||||
if str(task.match_status or '').strip() != 'fulfillable':
|
||||
from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
|
||||
if task.id is None:
|
||||
return False
|
||||
lines = task.line_results_json
|
||||
if not isinstance(lines, list) or not lines:
|
||||
rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
|
||||
if not rows:
|
||||
return False
|
||||
return all(
|
||||
isinstance(item, dict)
|
||||
and str(item.get('line_status') or item.get('disposition') or '').strip() == 'ok'
|
||||
for item in lines
|
||||
)
|
||||
released_keys = {
|
||||
str(row.line_key)
|
||||
for row in (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage',
|
||||
)
|
||||
.all()
|
||||
)
|
||||
}
|
||||
for row in rows:
|
||||
result = str(row.match_result or '').strip()
|
||||
shortage = _line_shortage_qty(getattr(row, 'shortage_qty', None))
|
||||
if result == 'matched' and shortage <= 0:
|
||||
continue
|
||||
if str(row.line_key) in released_keys and shortage > 0:
|
||||
continue
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _match_step_progress_fields(
|
||||
@@ -760,7 +788,6 @@ def try_auto_chain_after_match(
|
||||
or "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。"
|
||||
),
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
@@ -2035,7 +2062,6 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
message=t("workflow.fulfillment.manual_done_message", lang=lang).format(task_no=task.task_no),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOADED if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
|
||||
human_options=[] if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
|
||||
)
|
||||
|
||||
|
||||
@@ -2195,7 +2221,6 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
message=t("workflow.fulfillment.rpa_uploaded_done", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOADED if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
|
||||
human_options=[] if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
|
||||
)
|
||||
|
||||
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
|
||||
@@ -2271,7 +2296,6 @@ def run_auto_progress_fulfillment_steps(
|
||||
task=task,
|
||||
message="Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
|
||||
@@ -13,6 +13,18 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _runtime_value_source(source: Any) -> str:
|
||||
"""将 layout 内部来源收敛为运行时 observation 的稳定值源枚举。"""
|
||||
normalized = str(source or '').strip().lower()
|
||||
if normalized in {'acroform_widget', 'widget', 'widget_template'}:
|
||||
return 'acroform_widget'
|
||||
if normalized in {'ocr', 'ocr_glyph', 'ocr_coordinate'}:
|
||||
return 'ocr'
|
||||
if normalized.startswith('native') or normalized in {'pdf_coordinate', 'native_glyph'}:
|
||||
return 'native_pdf'
|
||||
return 'unknown'
|
||||
|
||||
|
||||
def build_field_observation(
|
||||
*,
|
||||
field: dict[str, Any],
|
||||
@@ -79,6 +91,7 @@ def build_field_observation(
|
||||
layout_evidence[key] = field.get(key)
|
||||
return {
|
||||
'value': value,
|
||||
'value_source': _runtime_value_source(field.get('source')),
|
||||
'document_id': int(document_id),
|
||||
'quote': quote,
|
||||
'confidence': 1.0,
|
||||
|
||||
@@ -551,7 +551,7 @@ def sync_intake_after_parse_job_recovery(job: Any) -> None:
|
||||
if job_status == 'queued':
|
||||
if intake_status not in {'parsing', 'parse_failed'}:
|
||||
return
|
||||
# Handler 可能已先提交 parse_failed;Job 自动重试时恢复为 queued 同一语义
|
||||
# Handler 可能已先提交 parse_failed;失败即停止,后续只能由用户明确重新识别。
|
||||
locked.parse_status = 'queued'
|
||||
locked.parse_lease = None
|
||||
locked.error_code = None
|
||||
|
||||
@@ -284,8 +284,8 @@ def build_inventory_candidate_blocking_reason(
|
||||
}
|
||||
|
||||
|
||||
def build_inventory_candidate_primary_action(code: str = 'open_inventory_source_review') -> dict[str, Any]:
|
||||
"""构造统一主动作 DTO。"""
|
||||
def build_inventory_candidate_primary_action(code: str = 'retry_with_latest_rules') -> dict[str, Any]:
|
||||
"""构造库存源规则自动重算动作 DTO,不提供人工选源入口。"""
|
||||
return {
|
||||
'code': code,
|
||||
'i18n_key': f'workspace.shippingNotice.processGate.actionCodes.{code}',
|
||||
|
||||
@@ -91,6 +91,22 @@ def inventory_loaded_response(
|
||||
for linked_task in linked_tasks:
|
||||
if linked_task.id != task.id:
|
||||
apply_task_transition(linked_task, TaskTransition.INVENTORY_READY)
|
||||
# [STEP] 库存回调已改变 Notice 履约事实;同步所有受影响 OT,令统一 Projection
|
||||
# 的 progress_version 与库存文件/库存匹配 Gate 同事务前进。
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
sync_order_task_stage_for_notice,
|
||||
)
|
||||
|
||||
affected_tasks: list[ShippingNotice] = []
|
||||
affected_task_ids: set[int] = set()
|
||||
for affected_task in [task, *linked_tasks]:
|
||||
affected_task_id = int(affected_task.id)
|
||||
if affected_task_id in affected_task_ids:
|
||||
continue
|
||||
affected_task_ids.add(affected_task_id)
|
||||
affected_tasks.append(affected_task)
|
||||
for affected_task in affected_tasks:
|
||||
sync_order_task_stage_for_notice(affected_task)
|
||||
log_task_event(
|
||||
task,
|
||||
event_type,
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_rpa_workflow.py
|
||||
|
||||
用途:发货通知库存 RPA 编排(触发导出、等待/超时、回调落盘)与库存源人工确认。
|
||||
用途:发货通知库存 RPA 编排(触发导出、等待/超时、回调落盘)。
|
||||
依赖:customer_identity_gate、reservation_gate、rpa、rpa_attempts、inventory_snapshot、
|
||||
inventory_mapping_workflow、query_service、动态订单字段、tool_common、state_machine、tool_response。
|
||||
逻辑:inventory_workflow.ensure_inventory 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新;
|
||||
confirm_inventory_source 写入操作人与前后生命周期快照(TaskEvent 双写统一审计);
|
||||
Reservation 门禁从当前 Extraction 的动态 FieldValue 读取。
|
||||
库存源始终由规则 Gate 自动裁决;Reservation 门禁从当前 Extraction 的动态 FieldValue 读取。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,18 +21,13 @@ from typing import Any
|
||||
from app import db
|
||||
from app.core.errors import AppError, ServiceUnavailableError
|
||||
from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_PARSE_OK,
|
||||
CP_UPLOAD_REQ,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
PH_RPA_PENDING,
|
||||
)
|
||||
from app.services.shipping_notice.constants import CP_UPLOAD_REQ, PH_RPA_PENDING
|
||||
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
|
||||
from app.services.shipping_notice.inventory_snapshot_store import (
|
||||
find_latest_ready_snapshot,
|
||||
get_or_create_rpa_inventory_snapshot,
|
||||
link_snapshot_to_task,
|
||||
link_snapshot_to_task_for_preparation,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_upload import (
|
||||
delete_staged_task_inventory_file,
|
||||
@@ -51,7 +45,6 @@ from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
assert_inventory_source_gate,
|
||||
confirm_task_inventory_source,
|
||||
inventory_identities_match,
|
||||
is_inventory_source_stable,
|
||||
)
|
||||
@@ -74,7 +67,6 @@ from app.services.shipping_notice.rpa import (
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
|
||||
from app.services.shipping_notice.rpa_attempts import (
|
||||
inventory_rpa_attempts,
|
||||
max_rpa_inventory_attempts,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
@@ -102,14 +94,12 @@ def _inventory_rpa_attempt_label(*, attempt_no: int, max_attempts: int, manual_r
|
||||
生成库存 RPA 尝试状态文案。
|
||||
【AI 触发时机】:需要向前台说明当前 RPA 库存获取已触发或仍在等待时调用。
|
||||
|
||||
核心逻辑:前台不展示“第 N 次”这类内部排障指标,避免用户误解自动重试策略;
|
||||
真正的 attempt 仍保留在 ShippingTaskEvent.detail 里供运维排查。
|
||||
核心逻辑:前台不展示尝试计数或自动重试策略;一次 RPA 执行失败即停止,
|
||||
后续只能由用户点击明确的重新获取库存动作触发。
|
||||
"""
|
||||
if manual_retry_round:
|
||||
return "已手动重新触发库存获取"
|
||||
if max_attempts <= 1:
|
||||
return "当前配置为单次自动尝试"
|
||||
return "库存获取自动尝试中"
|
||||
return "已触发库存获取"
|
||||
|
||||
|
||||
def _inventory_rpa_running_prefix(*, attempt_no: int, max_attempts: int) -> str:
|
||||
@@ -124,13 +114,6 @@ def _inventory_rpa_triggered_prefix(*, attempt_no: int, max_attempts: int, manua
|
||||
return "已触发库存获取。"
|
||||
|
||||
|
||||
def _inventory_rpa_exhausted_message(attempts: int) -> str:
|
||||
"""生成库存 RPA 已耗尽时的用户文案;单次模式明确提示“已尝试一次”。"""
|
||||
if max_rpa_inventory_attempts() <= 1:
|
||||
return "已尝试 1 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。"
|
||||
return f"已尝试 {attempts} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。"
|
||||
|
||||
|
||||
def _try_reuse_inventory_snapshot(
|
||||
task: ShippingNotice,
|
||||
rpa_source: dict[str, Any],
|
||||
@@ -255,7 +238,7 @@ def _inventory_rpa_triggered_message(*, attempt_no: int, max_attempts: int, manu
|
||||
max_attempts=max_attempts,
|
||||
manual_retry_round=manual_retry_round,
|
||||
)
|
||||
return f"{prefix}若长时间无结果,可手动重试,或上传库存 Excel。"
|
||||
return f"{prefix}若本次失败,请选择重新获取库存或上传库存 Excel。"
|
||||
|
||||
|
||||
def inventory_rpa_wait_seconds(task: ShippingNotice) -> tuple[int | None, int | None, int | None]:
|
||||
@@ -299,7 +282,8 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor
|
||||
对已超时的库存 RPA 等待态做一次幂等复查。
|
||||
【AI 触发时机】:工作台查询发现任务仍卡在 RPA 等待且已超过超时时间时调用;常规链路仍由 worker 调度。
|
||||
|
||||
核心逻辑:未超时立即返回 None;已超时则复用 ensure_inventory_via_rpa,让既有状态机负责失败事件、自动重试和耗尽转人工。
|
||||
核心逻辑:未超时立即返回 None;已超时只记录失败并停在 Gate,
|
||||
不会自动再次触发 RPA。
|
||||
Args:
|
||||
task: 当前发货通知任务。
|
||||
source: 复查来源,用于审计排障。
|
||||
@@ -318,7 +302,16 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor
|
||||
{"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
|
||||
)
|
||||
db.session.flush()
|
||||
return ensure_inventory_via_rpa(task, mode="auto")
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
task.error_message = "RPA 库存导出等待超时,请选择重新获取库存或上传库存 Excel"
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=task.error_message,
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
)
|
||||
|
||||
|
||||
def _expected_snapshot_identity_from_task(task: ShippingNotice) -> tuple[str, str]:
|
||||
@@ -979,221 +972,29 @@ def _batch_snapshot_verify_warehouse_id(
|
||||
def _validate_batch_callback_worker_identity(item: dict[str, Any], source: dict[str, Any]) -> str | None:
|
||||
"""
|
||||
校验批量回调 Worker 返回的 Source/Warehouse 身份与启用配置一致。
|
||||
核心逻辑:定时/无任务成功项必须显式携带 source/warehouse;动态仓接受库存文件返回的 Warehouse。
|
||||
核心逻辑:固定仓成功项必须显式携带 source/warehouse;动态仓文件在库存行
|
||||
解析后才按订单键得出 Warehouse,因此回调层允许 warehouse_id 为空。
|
||||
"""
|
||||
callback_source = str(item.get("source_code") or "").strip().upper()
|
||||
callback_wh = str(item.get("warehouse_id") or "").strip().upper()
|
||||
if not callback_source:
|
||||
return "source_code_missing"
|
||||
if not callback_wh:
|
||||
return "warehouse_id_missing"
|
||||
|
||||
cfg_source = str(source.get("source_code") or "").strip().upper()
|
||||
cfg_wh = str(source.get("fixed_warehouse_id") or source.get("warehouse_id") or "").strip().upper()
|
||||
if callback_source != cfg_source:
|
||||
return "source_code_mismatch"
|
||||
if str(source.get('warehouse_resolution_mode') or '') == 'inventory_match':
|
||||
if str(source.get('warehouse_resolution_mode') or '').strip().lower() == 'inventory_match':
|
||||
return None
|
||||
|
||||
if not callback_wh:
|
||||
return "warehouse_id_missing"
|
||||
|
||||
if callback_wh != cfg_wh:
|
||||
return "warehouse_id_mismatch"
|
||||
return None
|
||||
|
||||
|
||||
def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
确认当前任务的库存来源;库存源门禁或匹配多源阻断均可调用。
|
||||
|
||||
【AI 触发时机】:用户在库存源检查点或匹配多源冲突待办中选择 source_code 后调用。
|
||||
核心逻辑:原门禁路径确认后进入库存准备;shortage + 多源/多文件冲突路径写入
|
||||
forced_match_source_code 并立即重匹配,消除多源 Excel 阻断。
|
||||
"""
|
||||
from app.services.shipping_notice.constants import PH_SHORTAGE, RS_SHORTAGE_REVIEW
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.stp_line_inventory_match import (
|
||||
multi_source_recovery_source_codes,
|
||||
needs_multi_source_manual_recovery,
|
||||
)
|
||||
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
source_code = str(payload.get("source_code") or "").strip().upper()
|
||||
if not source_code:
|
||||
return tool_response(status="failed", task=task, message="请提供库存源编码 source_code")
|
||||
|
||||
from app.services.shipping_notice.tool_common import task_lifecycle_audit_snapshot
|
||||
|
||||
pending = str(task.pending_human_reason or "").strip()
|
||||
on_source_gate = pending == PH_INVENTORY_SOURCE_UNRESOLVED
|
||||
on_multi_source_block = (
|
||||
(task.review_status == RS_SHORTAGE_REVIEW or pending == PH_SHORTAGE)
|
||||
and needs_multi_source_manual_recovery(task)
|
||||
)
|
||||
if not on_source_gate and not on_multi_source_block:
|
||||
return tool_response(status="failed", task=task, message="当前任务不在库存源确认节点")
|
||||
|
||||
before_snapshot = task_lifecycle_audit_snapshot(task)
|
||||
|
||||
if on_multi_source_block:
|
||||
allowed = set(multi_source_recovery_source_codes(task))
|
||||
if source_code not in allowed:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
message=f"库存源 {source_code} 不在可指定候选内:{', '.join(sorted(allowed)) or '-'}",
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
source = get_database_inventory_source(source_code)
|
||||
if source is None:
|
||||
return tool_response(status="failed", task=task, message=f"库存源配置不存在:{source_code}")
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
step_payload['forced_match_source_code'] = source_code
|
||||
step_payload['multi_source_excel_block'] = False
|
||||
step_payload['resolved_ok_source_codes'] = [source_code]
|
||||
step_payload['inventory_source_resolution'] = {
|
||||
'status': 'resolved',
|
||||
'candidates': [{'source_code': source_code, 'display_name': source.get('display_name') or source_code}],
|
||||
'selected_source_code': source_code,
|
||||
'reason': 'manual_multi_source_resolve',
|
||||
}
|
||||
task.step_payload_json = step_payload
|
||||
task.inventory_source_code = source_code
|
||||
task.inventory_connector_type = str(source.get('connector_type') or '') or None
|
||||
if str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed':
|
||||
task.inventory_warehouse_id = str(source.get('fixed_warehouse_id') or '').upper() or None
|
||||
# 与门禁确认路径对齐:resolved 属 STABLE;保留既有 fingerprint/config_version。
|
||||
task.inventory_source_status = 'resolved'
|
||||
task.inventory_source_method = 'manual_multi_source_resolve'
|
||||
task.inventory_source_confirmed_by = payload.get('_trusted_user_id')
|
||||
task.inventory_source_confirmed_at = datetime.now(timezone.utc)
|
||||
task.pending_human_reason = None
|
||||
task.review_status = None
|
||||
task.error_message = None
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_source_confirmed",
|
||||
{
|
||||
"source_code": source_code,
|
||||
"connector_type": task.inventory_connector_type,
|
||||
"warehouse_id": task.inventory_warehouse_id,
|
||||
"confirmed_by": payload.get("_trusted_user_id") or "integration_tool",
|
||||
"reason_code": "manual_multi_source_resolve",
|
||||
"resolved_ok_source_codes": [source_code],
|
||||
},
|
||||
actor_id=payload.get("_trusted_user_id") or payload.get("operator_id") or payload.get("actor_id"),
|
||||
source='workspace_api' if (
|
||||
payload.get("_trusted_user_id") or payload.get("operator_id") or payload.get("actor_id")
|
||||
) else 'system',
|
||||
before=before_snapshot,
|
||||
after=task_lifecycle_audit_snapshot(task),
|
||||
)
|
||||
apply_task_transition(task, TaskTransition.REMATCH_REQUESTED)
|
||||
task.current_step = "step5_match_inventory"
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_inventory
|
||||
trusted_uid = payload.get("_trusted_user_id")
|
||||
# [T6 选择性重匹] 默认只重匹 match_result≠matched 行;force_full_rematch=true 才全量重匹。
|
||||
# 实现:非全量模式先把 line_matches 中 is_current=true 且 match_result≠matched 的条目
|
||||
# 置为 is_current=false,待 match_inventory 补齐;已 matched 的保留不覆盖,避免稳定证据哈希失效。
|
||||
force_full = False
|
||||
if isinstance(payload, dict):
|
||||
force_flag = payload.get('force_full_rematch') or payload.get('force_full') or payload.get('full_rematch')
|
||||
force_full = bool(force_flag and str(force_flag).lower() not in {'0', 'false', 'no', 'none', ''})
|
||||
if not force_full and task.id is not None:
|
||||
from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch
|
||||
cleared = (
|
||||
db.session.query(ShippingNoticeLineInventoryMatch)
|
||||
.filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
ShippingNoticeLineInventoryMatch.match_result != 'matched',
|
||||
)
|
||||
.update(
|
||||
{
|
||||
'is_current': False,
|
||||
'updated_at': datetime.now(timezone.utc),
|
||||
},
|
||||
synchronize_session=False,
|
||||
)
|
||||
)
|
||||
log_task_event(
|
||||
task,
|
||||
'match_inventory_selective_reset',
|
||||
{
|
||||
'cleared_pending_count': int(cleared or 0),
|
||||
'force_full_rematch': False,
|
||||
},
|
||||
actor_id=trusted_uid,
|
||||
source='workspace_api' if trusted_uid else 'system',
|
||||
)
|
||||
rematch_payload = {
|
||||
"task_id": task.task_no,
|
||||
"_trusted_user_id": trusted_uid,
|
||||
"operator_id": trusted_uid,
|
||||
"actor_id": trusted_uid,
|
||||
"event_source": "workspace_api" if trusted_uid else "system",
|
||||
"force_full_rematch": force_full,
|
||||
}
|
||||
return match_inventory(rematch_payload)
|
||||
|
||||
adjudication = confirm_task_inventory_source(
|
||||
task,
|
||||
source_code,
|
||||
user_id=payload.get("_trusted_user_id"),
|
||||
)
|
||||
if not is_inventory_source_stable(task):
|
||||
apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
|
||||
task.current_step = "step2_parse_confirm"
|
||||
task.error_message = adjudication.reason or "库存源确认失败"
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="库存源确认未通过,请重新选择或检查配置。",
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"inventory_source_candidates": adjudication.candidates,
|
||||
"inventory_source_status": adjudication.status,
|
||||
"inventory_source_reason": adjudication.reason,
|
||||
},
|
||||
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
confirmed_by = payload.get("_trusted_user_id") or payload.get("operator_id") or payload.get("actor_id")
|
||||
apply_task_transition(task, TaskTransition.PARSED)
|
||||
task.pending_human_reason = None
|
||||
task.review_status = None
|
||||
task.error_message = None
|
||||
task.current_step = "step3_inventory_prepare"
|
||||
# [STEP] 状态变更后再写事件,保证 after 快照含确认后的领域事实 / phase。
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_source_confirmed",
|
||||
{
|
||||
"source_code": task.inventory_source_code,
|
||||
"connector_type": task.inventory_connector_type,
|
||||
"warehouse_id": task.inventory_warehouse_id,
|
||||
"confirmed_by": confirmed_by or "integration_tool",
|
||||
"reason_code": "inventory_source_confirmed",
|
||||
},
|
||||
actor_id=confirmed_by,
|
||||
source='workspace_api' if confirmed_by else 'system',
|
||||
before=before_snapshot,
|
||||
after=task_lifecycle_audit_snapshot(task),
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message="库存源已确认;将使用该来源已导出的有效库存文件。",
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_PARSE_OK,
|
||||
)
|
||||
|
||||
|
||||
def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, Any]:
|
||||
"""触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。"""
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
@@ -1256,20 +1057,33 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
|
||||
|
||||
rpa_source = task_rpa_inventory_source(task) or {}
|
||||
|
||||
# retry_rpa 使用逐源 Attempt 编排,确保 Trigger 携带 source_run_no/lease_token,
|
||||
# Worker 回调后可以精确绑定到本次 Attempt;自动模式继续使用下方旧兼容路径。
|
||||
if manual_retry_round:
|
||||
# 首次自动与人工重试都必须创建逐源 Attempt。只有该路径会冻结
|
||||
# source_run_no/lease_token/candidate_set/execution/gate 身份,Worker 回调才可精确收口。
|
||||
# 下方保留的旧单票逻辑仅用于历史代码阅读,所有受支持 mode 均在这里返回。
|
||||
if mode in {'auto', 'retry_rpa'}:
|
||||
from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared
|
||||
|
||||
prepared = ensure_all_required_sources_prepared(task, mode='retry_rpa')
|
||||
prepared = ensure_all_required_sources_prepared(task, mode=mode)
|
||||
db.session.flush()
|
||||
if prepared.pending_source_codes:
|
||||
apply_task_transition(task, TaskTransition.RPA_PENDING)
|
||||
task.error_message = None
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key='step3_inventory_prepare',
|
||||
step_title='获取库存',
|
||||
status='running',
|
||||
message='已重新触发库存获取,等待各库存源回调。' if manual_retry_round else '已触发库存获取,等待各库存源回调。',
|
||||
progress_percent=60,
|
||||
current=len(prepared.prepared_source_codes),
|
||||
total=len(prepared.prepared_source_codes) + len(prepared.pending_source_codes),
|
||||
detail='等待库存 RPA 回调',
|
||||
extra={'manual_retry_round': manual_retry_round, 'source_attempts': prepared.source_attempts},
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status='running', task_id=task.task_no,
|
||||
message='已重新触发库存获取,等待各库存源回调。',
|
||||
message='已重新触发库存获取,等待各库存源回调。' if manual_retry_round else '已触发库存获取,等待各库存源回调。',
|
||||
data={**serialize_task_for_tool(task), 'rpa': {
|
||||
'pending_source_codes': prepared.pending_source_codes,
|
||||
'source_attempts': prepared.source_attempts,
|
||||
@@ -1277,6 +1091,19 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
|
||||
)
|
||||
if prepared.all_prepared:
|
||||
return tool_response(status='completed', task=task, message='库存快照已准备完成。')
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key='step3_inventory_prepare',
|
||||
step_title='获取库存',
|
||||
status='needs_human',
|
||||
message='库存 RPA 未能为全部库存源生成结果。',
|
||||
progress_percent=100,
|
||||
current=len(prepared.prepared_source_codes),
|
||||
total=len(prepared.prepared_source_codes) + len(prepared.failed_source_codes),
|
||||
detail='请重新获取库存或上传库存 Excel。',
|
||||
extra={'source_attempts': prepared.source_attempts},
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status='needs_human', task=task,
|
||||
message='库存 RPA 未能为全部库存源生成结果。',
|
||||
@@ -1302,24 +1129,20 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
|
||||
if last_trigger and isinstance(last_trigger.created_at, datetime):
|
||||
elapsed = int((datetime.utcnow() - last_trigger.created_at).total_seconds())
|
||||
if elapsed < timeout_seconds:
|
||||
max_attempts = max_rpa_inventory_attempts()
|
||||
attempts = inventory_rpa_attempts(task)
|
||||
remaining = max(timeout_seconds - elapsed, 1)
|
||||
return tool_response(
|
||||
status="running",
|
||||
task_id=task.task_no,
|
||||
message=_inventory_rpa_running_message(
|
||||
attempt_no=max(attempts, 1),
|
||||
max_attempts=max_attempts,
|
||||
max_attempts=max(attempts, 1),
|
||||
),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"rpa": {
|
||||
"attempts": max(attempts, 1),
|
||||
"max_attempts": max_attempts,
|
||||
"elapsed_seconds": elapsed,
|
||||
"timeout_seconds": timeout_seconds,
|
||||
"retry_after_seconds": remaining,
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -1336,21 +1159,20 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
|
||||
},
|
||||
)
|
||||
db.session.flush( )
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
task.error_message = "RPA 库存导出等待超时,请选择重新获取库存或上传库存 Excel"
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=task.error_message,
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
)
|
||||
|
||||
# [STEP 2] 处理重试上限;禁止消费全局 drop 目录未校验文件,必须等待 RPA 回调或复用正式快照。
|
||||
# [STEP 2] 仅本次用户或系统明确触发可创建一次 RPA 尝试。
|
||||
# 禁止消费全局 drop 目录未校验文件,必须等待 RPA 回调或复用正式快照。
|
||||
attempts = inventory_rpa_attempts(task)
|
||||
max_attempts = max_rpa_inventory_attempts()
|
||||
if attempts >= max_attempts and not task.inventory_lines_json and not manual_retry_round:
|
||||
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
|
||||
task.error_message = "已多次尝试仍无法通过 RPA 获取库存"
|
||||
log_task_event(task, "inventory_rpa_exhausted", {"attempts": attempts})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=_inventory_rpa_exhausted_message(attempts),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
# [STEP 3] 触发下一次 RPA 导出或给出人工兜底提示。
|
||||
# 触发成功则推进到 pending;触发失败则明确要求用户改走手工上传。
|
||||
@@ -1378,7 +1200,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
|
||||
)
|
||||
progress_detail = _inventory_rpa_attempt_label(
|
||||
attempt_no=attempt_no,
|
||||
max_attempts=max_attempts,
|
||||
max_attempts=attempt_no,
|
||||
manual_retry_round=manual_retry_round,
|
||||
)
|
||||
set_task_step_progress(
|
||||
@@ -1389,7 +1211,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
|
||||
message=progress_message,
|
||||
progress_percent=60,
|
||||
current=attempt_no,
|
||||
total=max(attempt_no, max_attempts),
|
||||
total=attempt_no,
|
||||
detail=progress_detail,
|
||||
extra={"manual_retry_round": manual_retry_round} if manual_retry_round else None,
|
||||
)
|
||||
@@ -1410,14 +1232,13 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
|
||||
task_id=task.task_no,
|
||||
message=_inventory_rpa_triggered_message(
|
||||
attempt_no=attempt_no,
|
||||
max_attempts=max_attempts,
|
||||
max_attempts=attempt_no,
|
||||
manual_retry_round=manual_retry_round,
|
||||
),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"rpa": {
|
||||
"attempts": attempt_no,
|
||||
"max_attempts": max_attempts,
|
||||
"timeout_seconds": timeout_seconds,
|
||||
},
|
||||
},
|
||||
@@ -1629,7 +1450,7 @@ def _handle_rpa_inventory_failed(
|
||||
*,
|
||||
commit: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""处理 failed 回调:记录稳定失败码、累计尝试并在耗尽后转人工上传兜底。"""
|
||||
"""处理 failed 回调:记录失败事实并保留用户可重试/上传的恢复入口。"""
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
task.error_message = str(payload.get("error_message") or "RPA inventory export failed")[:500]
|
||||
log_task_event(task, "inventory_rpa_failed", {
|
||||
@@ -1637,24 +1458,17 @@ def _handle_rpa_inventory_failed(
|
||||
"error_code": str(payload.get("error_code") or "rpa_export_failed"),
|
||||
"rpa_runtime": runtime,
|
||||
})
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key='step3_inventory_prepare',
|
||||
step_title='获取库存',
|
||||
status='needs_human',
|
||||
message=task.error_message,
|
||||
progress_percent=100,
|
||||
detail='请重新获取库存或上传库存 Excel。',
|
||||
extra={'error_code': str(payload.get('error_code') or 'rpa_export_failed')},
|
||||
)
|
||||
db.session.flush()
|
||||
attempts = inventory_rpa_attempts(task)
|
||||
if attempts >= max_rpa_inventory_attempts():
|
||||
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
|
||||
task.error_message = "已多次尝试仍无法通过 RPA 获取库存"
|
||||
log_task_event(task, "inventory_rpa_exhausted", {"attempts": attempts})
|
||||
_mark_inventory_rpa_run_no_consumed(task, _resolve_effective_callback_run_no(task, payload))
|
||||
if commit:
|
||||
db.session.commit()
|
||||
else:
|
||||
db.session.flush()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=_inventory_rpa_exhausted_message(attempts),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
_mark_inventory_rpa_run_no_consumed(task, _resolve_effective_callback_run_no(task, payload))
|
||||
if commit:
|
||||
db.session.commit()
|
||||
@@ -1917,7 +1731,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
item_savepoint = db.session.begin_nested()
|
||||
response: dict[str, Any] | None = None
|
||||
try:
|
||||
link = link_snapshot_to_task(
|
||||
link = link_snapshot_to_task_for_preparation(
|
||||
task,
|
||||
inv_file,
|
||||
reason="rpa_callback",
|
||||
@@ -2424,7 +2238,13 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
'error': 'RPA callback identity does not match the active preparation attempt.',
|
||||
})
|
||||
continue
|
||||
if per_source_code not in {'validated', 'not_found'}:
|
||||
# trigger_identity_invalid 是 Worker 对已领取 trigger 的明确失败事实。
|
||||
# per_source handler 已收口 Attempt;仍须继续到下面的 Task/Gate 收口,
|
||||
# 不能像普通身份不匹配一样只记回调审计后等待 900 秒超时。
|
||||
if not (
|
||||
per_source_code == 'failed'
|
||||
and str(merged_item.get('error_code') or '').strip() == 'trigger_identity_invalid'
|
||||
) and per_source_code not in {'validated', 'not_found'}:
|
||||
failed.append({
|
||||
'source_code': source_code,
|
||||
'warehouse_id': warehouse_id,
|
||||
@@ -2465,6 +2285,23 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
"message": merged_item.get("message") or merged_item.get("error_message") or "",
|
||||
})
|
||||
else:
|
||||
# [STEP] 结构化逐源 Attempt 是库存准备轮次的正式事实。失败回调
|
||||
# 必须先收口 Attempt/SourceAttempt;否则 Task 虽已记录失败,
|
||||
# PreparationAttempt 仍会停在 waiting_external,页面会错误显示
|
||||
# “等待外部系统回执”。
|
||||
if source_run_no_item and structured_attempt:
|
||||
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
|
||||
|
||||
per_source_callback_handler(
|
||||
task,
|
||||
source_code=source_code,
|
||||
run_no=source_run_no_item,
|
||||
callback_payload={
|
||||
**dict(merged_item),
|
||||
'error_code': str(merged_item.get('error_code') or 'rpa_export_failed'),
|
||||
'error_message': str(merged_item.get('error_message') or 'RPA inventory export failed'),
|
||||
},
|
||||
)
|
||||
_handle_rpa_inventory_failed(task, merged_item, runtime, commit=False)
|
||||
# 失败回调已把 Task 从 rpa_pending 还原为库存不可用;必须立即同步正式 Gate,
|
||||
# 否则 Execution 仍是 waiting_external,前端会错误停在“系统处理中”。
|
||||
@@ -2533,64 +2370,6 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
continue
|
||||
|
||||
if raw_status == "success":
|
||||
# 定时批量成功项必须显式携带 Warehouse 身份;先做身份校验,
|
||||
# 避免缺 Warehouse 被后续文件路径错误遮蔽。
|
||||
if not warehouse_id:
|
||||
# [STEP] RPA 声称导出成功但缺少仓库身份时,文件绝不能成为可匹配
|
||||
# 快照;同时必须终态化本次逐源 Attempt/准备轮次,避免前端永久显示
|
||||
# “处理中”或允许重复触发同一运行中的 Attempt。
|
||||
if task and source_run_no_item and structured_attempt:
|
||||
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
|
||||
|
||||
per_source_callback_handler(
|
||||
task,
|
||||
source_code=source_code,
|
||||
run_no=source_run_no_item,
|
||||
callback_payload={
|
||||
**dict(merged_item),
|
||||
'error_code': 'warehouse_id_missing',
|
||||
'error_message': 'RPA 回调缺少 warehouse_id,无法确认库存归属。',
|
||||
},
|
||||
)
|
||||
if task:
|
||||
runtime = _save_last_inventory_rpa_runtime(task, merged_item)
|
||||
_handle_rpa_inventory_failed(
|
||||
task,
|
||||
{
|
||||
**dict(merged_item),
|
||||
'error_code': 'warehouse_id_missing',
|
||||
'error_message': 'RPA 回调缺少 warehouse_id,无法确认库存归属。',
|
||||
},
|
||||
runtime,
|
||||
commit=False,
|
||||
)
|
||||
# 与显式 failed 回调保持相同的 Gate 收口语义:Task 已从
|
||||
# rpa_pending 转为可重试失败,正式 Execution 不能继续停在
|
||||
# waiting_external,否则右侧页面会显示过期的“处理中”。
|
||||
if task.active_process_execution_id:
|
||||
from app.models import ShippingProcessExecution
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
|
||||
execution = db.session.get(
|
||||
ShippingProcessExecution,
|
||||
int(task.active_process_execution_id),
|
||||
)
|
||||
if (
|
||||
execution is not None
|
||||
and int(getattr(execution, 'task_id', 0) or 0) == int(task.id)
|
||||
and str(getattr(execution, 'status', '') or '').strip().lower() != 'superseded'
|
||||
):
|
||||
sync_fulfillment_gates_from_task(
|
||||
execution=execution,
|
||||
actor_type='system',
|
||||
)
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"warehouse_id": warehouse_id,
|
||||
"task_no": task_no or None,
|
||||
"error": "warehouse_id_missing",
|
||||
})
|
||||
continue
|
||||
file_path = str(merged_item.get("file_path") or "").strip()
|
||||
path = _received_batch_callback_file_path(
|
||||
file_path,
|
||||
@@ -2709,7 +2488,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
batch_new_storage_paths.append(item_orphan_path)
|
||||
|
||||
if task_no and task:
|
||||
link = link_snapshot_to_task(
|
||||
link = link_snapshot_to_task_for_preparation(
|
||||
task,
|
||||
inv_file,
|
||||
reason="rpa_batch_callback",
|
||||
|
||||
@@ -402,7 +402,8 @@ def create_empty_rpa_inventory_snapshot(
|
||||
share_mode='warehouse_pool', line_count=0, inventory_lines_json=[], warehouse_id=warehouse_id,
|
||||
warehouse_code=warehouse_id, source_code=source_code or None,
|
||||
source_type=str(source.get('connector_type') or '').strip() or None,
|
||||
source_config_version=inventory_sources_runtime_version(), identity_status='not_applicable',
|
||||
# 空快照没有可验证的行级身份;使用数据库枚举中的 unknown,避免审计入库失败。
|
||||
source_config_version=inventory_sources_runtime_version(), identity_status='unknown',
|
||||
snapshot_status=_SNAPSHOT_STATUS_EMPTY, exported_at=exported_at, expires_at=snapshot_expires_at(exported_at),
|
||||
rpa_run_no=run_no, schedule_run_id=schedule_run_id,
|
||||
source_query_json={'trigger_type': trigger_type, 'export_result': 'empty'},
|
||||
@@ -454,7 +455,13 @@ def link_snapshot_to_task(
|
||||
fallback_warehouse_id=inv_file.warehouse_id,
|
||||
)
|
||||
if not resolution.warehouse_id:
|
||||
inv_file.identity_status = resolution.reason
|
||||
# identity_status 受数据库枚举约束,仅保存状态;具体动态仓解析原因
|
||||
# 属于审计信息,不能写入该字段,否则会使已导出的快照整体回滚。
|
||||
inv_file.identity_status = 'pending'
|
||||
inv_file.schema_preview_json = {
|
||||
**(inv_file.schema_preview_json or {}),
|
||||
'identity_resolution_reason': resolution.reason,
|
||||
}
|
||||
return None
|
||||
resolved_warehouse_id = resolution.warehouse_id
|
||||
|
||||
@@ -510,6 +517,55 @@ def link_snapshot_to_task(
|
||||
return link
|
||||
|
||||
|
||||
def link_snapshot_to_task_for_preparation(
|
||||
task: ShippingNotice,
|
||||
inv_file: ShippingInventoryFile,
|
||||
*,
|
||||
reason: str,
|
||||
audit_payload: dict[str, Any] | None = None,
|
||||
) -> ShippingTaskInventoryLink | None:
|
||||
"""将 RPA 已准备快照关联任务;动态仓身份待匹配时保留文件事实。
|
||||
|
||||
动态仓的 Warehouse 只能由下一阶段用订单键匹配库存行得出。若该匹配尚无结论,
|
||||
本函数保留已通过结构校验的快照并标记 pending_matching,禁止回滚导出文件;
|
||||
fixed 仓仍完全沿用正式身份校验,不得降级关联。
|
||||
"""
|
||||
link = link_snapshot_to_task(
|
||||
task,
|
||||
inv_file,
|
||||
reason=reason,
|
||||
audit_payload=audit_payload,
|
||||
)
|
||||
if link is not None:
|
||||
return link
|
||||
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
|
||||
source = get_database_inventory_source(task.inventory_source_code)
|
||||
if (
|
||||
source is None
|
||||
or str(source.get('warehouse_resolution_mode') or '').strip().lower() != 'inventory_match'
|
||||
or not _can_relink_inventory(task)
|
||||
or not is_snapshot_fresh(inv_file)
|
||||
):
|
||||
return None
|
||||
|
||||
from app.services.shipping_notice.inventory_file_store import replace_task_inventory_link
|
||||
|
||||
link = replace_task_inventory_link(task, inv_file)
|
||||
link.link_reason = f'{reason}_pending_matching'
|
||||
link.matched_source_code = inv_file.source_code
|
||||
link.identity_check_status = 'pending_matching'
|
||||
link.audit_payload_json = {
|
||||
**(audit_payload or {}),
|
||||
'source_code': inv_file.source_code,
|
||||
'inventory_file_no': inv_file.inventory_file_no,
|
||||
'identity_status': inv_file.identity_status,
|
||||
}
|
||||
task.inventory_snapshot_id = inv_file.id
|
||||
return link
|
||||
|
||||
|
||||
def serialize_inventory_snapshot_link(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
"""序列化任务当前 active 库存快照摘要,供工作台/Tool 展示。"""
|
||||
if task.id is None:
|
||||
|
||||
@@ -9,7 +9,6 @@ services/shipping_notice/inventory_source_gate.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
@@ -17,7 +16,6 @@ from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
InventorySourceAdjudication,
|
||||
adjudicate_inventory_source,
|
||||
confirm_inventory_source_by_code,
|
||||
compute_routing_fingerprint,
|
||||
extract_routing_context,
|
||||
resolve_ambiguous_source_from_ready_snapshots,
|
||||
@@ -31,14 +29,13 @@ from app.services.shipping_notice.inventory_source_repository import (
|
||||
)
|
||||
|
||||
|
||||
STABLE_INVENTORY_SOURCE_STATUSES = frozenset({"resolved", "user_confirmed", "candidates_frozen"})
|
||||
STABLE_INVENTORY_SOURCE_STATUSES = frozenset({"resolved", "candidates_frozen"})
|
||||
|
||||
INVENTORY_SOURCE_ERROR_CODES = {
|
||||
"unresolved": "SHIPPING.INVENTORY_SOURCE_UNRESOLVED",
|
||||
"ambiguous": "SHIPPING.INVENTORY_SOURCE_AMBIGUOUS",
|
||||
"invalid": "SHIPPING.INVENTORY_SOURCE_INVALID",
|
||||
"conflicted": "SHIPPING.INVENTORY_SOURCE_CONFLICTED",
|
||||
"confirmation_required": "SHIPPING.INVENTORY_SOURCE_CONFIRMATION_REQUIRED",
|
||||
"changed": "SHIPPING.INVENTORY_SOURCE_CHANGED",
|
||||
"identity_mismatch": "SHIPPING.INVENTORY_IDENTITY_MISMATCH",
|
||||
"gate_blocked": "SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED",
|
||||
@@ -102,7 +99,7 @@ def is_inventory_source_stable(task: ShippingNotice) -> bool:
|
||||
|
||||
|
||||
def routing_fingerprint_changed(task: ShippingNotice, context: dict[str, Any]) -> bool:
|
||||
"""比较当前路由上下文与任务已存指纹,判断人工确认是否因重解析或配置变更失效。"""
|
||||
"""比较当前路由上下文与任务已存指纹,判断库存源裁决是否因事实变化失效。"""
|
||||
previous = str(task.inventory_routing_fingerprint or "").strip()
|
||||
if not previous:
|
||||
return False
|
||||
@@ -110,7 +107,7 @@ def routing_fingerprint_changed(task: ShippingNotice, context: dict[str, Any]) -
|
||||
|
||||
|
||||
def inventory_source_config_changed(task: ShippingNotice) -> bool:
|
||||
"""配置版本变化会使已确认库存源失效。"""
|
||||
"""配置版本变化会使已有库存源裁决失效。"""
|
||||
stored = str(task.inventory_source_config_version or "").strip()
|
||||
if not stored:
|
||||
return bool(str(task.inventory_source_status or "").strip())
|
||||
@@ -126,7 +123,7 @@ def apply_destination_fields(task: ShippingNotice, context: dict[str, Any]) -> N
|
||||
|
||||
|
||||
def clear_inventory_source_confirmation(task: ShippingNotice) -> None:
|
||||
"""路由指纹或配置版本变化时清除旧人工确认信息及过期 RPA 参数。"""
|
||||
"""路由指纹或配置版本变化时清除历史人工确认信息及过期 RPA 参数。"""
|
||||
task.inventory_source_confirmed_by = None
|
||||
task.inventory_source_confirmed_at = None
|
||||
if str(task.inventory_source_status or "").strip() == "user_confirmed":
|
||||
@@ -137,27 +134,9 @@ def clear_inventory_source_confirmation(task: ShippingNotice) -> None:
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def _adjudication_from_stable_task(task: ShippingNotice) -> InventorySourceAdjudication:
|
||||
"""从已稳定任务字段重建裁决结果,供跳过重复裁决时使用。"""
|
||||
context = extract_routing_context(task)
|
||||
return InventorySourceAdjudication(
|
||||
status=str(task.inventory_source_status or "").strip(),
|
||||
method=str(task.inventory_source_method or "").strip() or None,
|
||||
source_code=str(task.inventory_source_code or "").strip().upper() or None,
|
||||
connector_type=str(task.inventory_connector_type or "").strip() or None,
|
||||
warehouse_id=str(task.inventory_warehouse_id or "").strip().upper() or None,
|
||||
config_version=str(task.inventory_source_config_version or "").strip() or None,
|
||||
routing_fingerprint=str(task.inventory_routing_fingerprint or "").strip()
|
||||
or compute_routing_fingerprint(context),
|
||||
destination_candidates=context.get("destination_candidates") or [],
|
||||
)
|
||||
|
||||
|
||||
def apply_inventory_source_adjudication(
|
||||
task: ShippingNotice,
|
||||
adjudication: InventorySourceAdjudication,
|
||||
*,
|
||||
confirmed_by_user_id: int | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
将裁决结果写入任务独立字段,并同步候选/证据到 step_payload_json。
|
||||
@@ -176,9 +155,6 @@ def apply_inventory_source_adjudication(
|
||||
task.inventory_source_code = adjudication.source_code
|
||||
task.inventory_connector_type = adjudication.connector_type
|
||||
task.inventory_warehouse_id = adjudication.warehouse_id or None
|
||||
if adjudication.status == "user_confirmed" and confirmed_by_user_id:
|
||||
task.inventory_source_confirmed_by = confirmed_by_user_id
|
||||
task.inventory_source_confirmed_at = datetime.utcnow()
|
||||
elif adjudication.status not in STABLE_INVENTORY_SOURCE_STATUSES:
|
||||
task.inventory_source_code = None
|
||||
task.inventory_connector_type = None
|
||||
@@ -219,43 +195,14 @@ def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySour
|
||||
if inventory_source_config_changed(task) or routing_fingerprint_changed(task, context):
|
||||
clear_inventory_source_confirmation(task)
|
||||
|
||||
if (
|
||||
str(task.inventory_source_status or "").strip() == "user_confirmed"
|
||||
and is_inventory_source_stable(task)
|
||||
and not routing_fingerprint_changed(task, context)
|
||||
and not inventory_source_config_changed(task)
|
||||
):
|
||||
return _adjudication_from_stable_task(task)
|
||||
|
||||
adjudication = adjudicate_inventory_source(task)
|
||||
# Multiple routing candidates may be resolved only from already-exported
|
||||
# snapshots; this never starts RPA or uses inventory quantity as a signal.
|
||||
adjudication = resolve_ambiguous_source_from_ready_snapshots(task, adjudication)
|
||||
if (
|
||||
str(task.inventory_source_status or "").strip() == "user_confirmed"
|
||||
and adjudication.status == "resolved"
|
||||
and adjudication.source_code
|
||||
and str(adjudication.source_code).strip().upper() == str(task.inventory_source_code or "").strip().upper()
|
||||
and is_inventory_source_stable(task)
|
||||
):
|
||||
adjudication = InventorySourceAdjudication(
|
||||
status="user_confirmed",
|
||||
method="user_confirmed",
|
||||
source_code=adjudication.source_code,
|
||||
connector_type=adjudication.connector_type,
|
||||
warehouse_id=adjudication.warehouse_id,
|
||||
config_version=adjudication.config_version,
|
||||
routing_fingerprint=adjudication.routing_fingerprint,
|
||||
candidates=adjudication.candidates,
|
||||
destination_candidates=adjudication.destination_candidates,
|
||||
evidence=adjudication.evidence,
|
||||
reason=adjudication.reason,
|
||||
)
|
||||
|
||||
# [T3: 决策 A1 + C1] ambiguous 且有候选时,不再进入 inventory_source_review 人工阻断;
|
||||
# 多库存源是合法自动链路,直接冻结到 Set/Source/Line 结构化表 + Snapshot JSON 副本,
|
||||
# 状态升级为 candidates_frozen(属于 STABLE_INVENTORY_SOURCE_STATUSES,可进入库存准备)。
|
||||
# 零候选 / conflicted / unresolved 等情况仍保持旧逻辑进入人工复核。
|
||||
# 零候选 / conflicted / unresolved 仅进入自动规则重算 Gate,不产生人工选源入口。
|
||||
if (
|
||||
adjudication.status == "ambiguous"
|
||||
and getattr(task, "id", None) is not None
|
||||
@@ -293,7 +240,7 @@ def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySour
|
||||
)
|
||||
except ValueError:
|
||||
# 冻结服务抛 ValueError = 候选集合为空(保护分支,正常应命中不进入),
|
||||
# 保留原 ambiguous 让下游 is_inventory_source_stable 正确进入人工阻断。
|
||||
# 保留原 ambiguous 让下游 is_inventory_source_stable 正确进入规则重算阻断。
|
||||
pass
|
||||
|
||||
apply_inventory_source_adjudication(task, adjudication)
|
||||
@@ -307,9 +254,9 @@ def transition_task_to_inventory_source_review(
|
||||
error_message: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
将任务持久化到库存源人工复核检查点,并写入候选裁决信息。
|
||||
将任务持久化到库存源规则重算检查点,并写入候选裁决信息。
|
||||
|
||||
核心逻辑:统一状态机转换 + current_step + step_payload 候选,供 UI 展示确认按钮。
|
||||
核心逻辑:保留 checkpoint 作为内部恢复事实,但不产生人工选源按钮;
|
||||
解析复核必须在进入本检查点前完成,不保存延后复核标记。
|
||||
"""
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
@@ -334,10 +281,10 @@ def transition_task_to_inventory_source_review(
|
||||
|
||||
def ensure_inventory_source_review_state(task: ShippingNotice) -> InventorySourceAdjudication:
|
||||
"""
|
||||
对已通过解析确认但库存源仍不稳定的任务,补做裁决并落库到 inventory_source_review。
|
||||
对已通过解析确认但库存源仍不稳定的任务,补做规则裁决并落库到内部恢复检查点。
|
||||
|
||||
【AI 触发时机】:confirm_parse / auto_progress / ensure_inventory 等入口发现门禁未通过时调用。
|
||||
核心逻辑:新业务顺序固定为先完成解析复核,再进入库存源确认。
|
||||
核心逻辑:新业务顺序固定为先完成解析复核,再进入库存源自动裁决。
|
||||
"""
|
||||
adjudication = adjudicate_and_apply_inventory_source(task)
|
||||
if not is_inventory_source_stable(task):
|
||||
@@ -345,21 +292,6 @@ def ensure_inventory_source_review_state(task: ShippingNotice) -> InventorySourc
|
||||
return adjudication
|
||||
|
||||
|
||||
def confirm_task_inventory_source(
|
||||
task: ShippingNotice,
|
||||
source_code: str,
|
||||
*,
|
||||
user_id: int | None = None,
|
||||
) -> InventorySourceAdjudication:
|
||||
"""
|
||||
用户选择 source_code 后由后端重新校验并写入正式库存源。
|
||||
核心逻辑:前端只提交 source_code;站点与库位始终从配置生成。
|
||||
"""
|
||||
adjudication = confirm_inventory_source_by_code(task, source_code)
|
||||
apply_inventory_source_adjudication(task, adjudication, confirmed_by_user_id=user_id)
|
||||
return adjudication
|
||||
|
||||
|
||||
def assert_inventory_source_gate(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
|
||||
@@ -71,7 +71,7 @@ def compute_routing_fingerprint(context: dict[str, Any]) -> str:
|
||||
|
||||
|
||||
def _candidate(source: dict[str, Any]) -> dict[str, Any]:
|
||||
"""构造不泄露凭据的人工确认候选。"""
|
||||
"""构造不泄露凭据的规则裁决候选。"""
|
||||
return {
|
||||
'source_code': source['source_code'],
|
||||
'display_name': source['display_name'],
|
||||
@@ -82,7 +82,7 @@ def _candidate(source: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _from_source(*, status: str, source: dict[str, Any], method: str, context: dict[str, Any], evidence: list[dict[str, Any]] | None = None) -> InventorySourceAdjudication:
|
||||
"""由数据库 Source 生成 resolved/user_confirmed 裁决。"""
|
||||
"""由数据库 Source 生成规则裁决。"""
|
||||
resolution = resolve_inventory_source_identity(source, context)
|
||||
if not resolution.ok or not resolution.identity:
|
||||
return InventorySourceAdjudication('invalid', reason=resolution.reason, config_version=inventory_sources_runtime_version())
|
||||
@@ -245,18 +245,6 @@ def adjudicate_inventory_source(task: ShippingNotice) -> InventorySourceAdjudica
|
||||
return _result_to_adjudication(task_result, context)
|
||||
|
||||
|
||||
def confirm_inventory_source_by_code(task: ShippingNotice, source_code: str) -> InventorySourceAdjudication:
|
||||
"""人工从已启用数据库 Source 中选择来源;不要求预先确定动态 Warehouse。"""
|
||||
context = extract_routing_context(task)
|
||||
source = get_database_inventory_source(source_code)
|
||||
if not source:
|
||||
return InventorySourceAdjudication(
|
||||
'invalid', config_version=inventory_sources_runtime_version(), routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=[_candidate(item) for item in list_database_inventory_sources()], reason='source_code_not_found',
|
||||
)
|
||||
return _from_source(status='user_confirmed', source=source, method='user_confirmed', context=context)
|
||||
|
||||
|
||||
def resolve_inventory_source(task: ShippingNotice) -> InventorySourceAdjudication:
|
||||
"""兼容调用名,委托当前通用规则裁决。"""
|
||||
return adjudicate_inventory_source(task)
|
||||
@@ -277,15 +265,16 @@ def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
|
||||
|
||||
def save_task_rpa_inventory_source(task: ShippingNotice, source: dict[str, Any], *, resolution: InventorySourceAdjudication | None = None) -> None:
|
||||
"""兼容旧入口,将确认结果委托库存源门禁持久化。"""
|
||||
"""持久化规则裁决结果;禁止根据调用方传入 source_code 人工覆盖。"""
|
||||
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
|
||||
|
||||
selected = resolution or confirm_inventory_source_by_code(task, str(source.get('source_code') or ''))
|
||||
del source
|
||||
selected = resolution or adjudicate_inventory_source(task)
|
||||
apply_inventory_source_adjudication(task, selected)
|
||||
|
||||
|
||||
def mark_inventory_source_review(task: ShippingNotice, resolution: InventorySourceAdjudication) -> None:
|
||||
"""兼容旧入口,写入待人工确认的 Source 候选。"""
|
||||
"""兼容旧入口,写入规则裁决候选;不触发人工库存源确认。"""
|
||||
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
|
||||
|
||||
apply_inventory_source_adjudication(task, resolution)
|
||||
@@ -126,7 +126,6 @@ def _inventory_source_gate_response(task: ShippingNotice, *, operation: str, lan
|
||||
task=task,
|
||||
message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
@@ -320,7 +319,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
**serialize_task_for_tool(task),
|
||||
'blocking_reason': {
|
||||
'code': prep.get('error_code'),
|
||||
'primary_action': 'open_inventory_source_review',
|
||||
'primary_action': 'retry_with_latest_rules',
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
@@ -64,10 +64,28 @@ LIFECYCLE_STAGE_RANGES: tuple[tuple[str, set[str]], ...] = (
|
||||
)
|
||||
|
||||
|
||||
def lifecycle_entries(*, lifecycle_stage: str | None, has_candidate_context: bool) -> list[dict[str, str]]:
|
||||
"""返回只读生命周期入口;无有效 Candidate/正式任务时不开放任何订单生命周期面。"""
|
||||
if not has_candidate_context or lifecycle_stage not in LIFECYCLE_STAGE_CODES:
|
||||
def lifecycle_entries(
|
||||
*,
|
||||
lifecycle_stage: str | None,
|
||||
has_candidate_context: bool,
|
||||
has_intake_parse_context: bool = False,
|
||||
) -> list[dict[str, str]]:
|
||||
"""返回只读生命周期入口;空 Case 仅允许停留在接收解析阶段。"""
|
||||
if lifecycle_stage not in LIFECYCLE_STAGE_CODES:
|
||||
return []
|
||||
if not has_candidate_context:
|
||||
# 接收解析 Case 是已持久化的受控对象,允许在批次页展示其当前阶段;
|
||||
# 但不能借此开放订单复核及后续阶段。
|
||||
if not has_intake_parse_context or lifecycle_stage != 'intake_parse':
|
||||
return []
|
||||
return [
|
||||
{
|
||||
'code': code,
|
||||
'state': 'current' if code == 'intake_parse' else 'unavailable',
|
||||
'target_surface': 'order_lifecycle_workbench',
|
||||
}
|
||||
for code in LIFECYCLE_STAGE_CODES
|
||||
]
|
||||
current_index = LIFECYCLE_STAGE_CODES.index(str(lifecycle_stage))
|
||||
return [
|
||||
{
|
||||
@@ -85,6 +103,7 @@ def project_lifecycle(
|
||||
blocking_reason: dict[str, Any] | None,
|
||||
legacy_stage: str | None,
|
||||
has_candidate_context: bool,
|
||||
has_intake_parse_context: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""按 Gate → 阻断归属 → 历史阶段的固定优先级裁决生命周期和入口。
|
||||
|
||||
@@ -114,6 +133,7 @@ def project_lifecycle(
|
||||
'lifecycle_entries': lifecycle_entries(
|
||||
lifecycle_stage=lifecycle_stage,
|
||||
has_candidate_context=has_candidate_context,
|
||||
has_intake_parse_context=has_intake_parse_context,
|
||||
),
|
||||
'lifecycle_authority': authority,
|
||||
}
|
||||
@@ -15,6 +15,7 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingNotice,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderReviewCase,
|
||||
@@ -102,6 +103,12 @@ def persist_line_inventory_match_facts(
|
||||
snap_id = inventory_snapshot_id
|
||||
if snap_id is None and getattr(task, 'inventory_snapshot_id', None) is not None:
|
||||
snap_id = int(task.inventory_snapshot_id)
|
||||
# 匹配器结果可能未回填 inventory_file_no,但当前快照本身已是行匹配的
|
||||
# 正式文件身份。持久化必须补齐,避免“有快照却无行级下载证据”。
|
||||
snapshot_file_no = None
|
||||
if snap_id is not None:
|
||||
snapshot = ShippingInventoryFile.query.get(int(snap_id))
|
||||
snapshot_file_no = str(getattr(snapshot, 'inventory_file_no', '') or '').strip() or None
|
||||
|
||||
line_results = [
|
||||
item for item in list(match_payload.get('line_results') or []) if isinstance(item, dict)
|
||||
@@ -213,7 +220,7 @@ def persist_line_inventory_match_facts(
|
||||
)
|
||||
# [T6 E1] 行级证据哈希:SHA256(source_code|file_no|row_index|reservation_id|part_number)
|
||||
src_code = str(result.get('resolved_inventory_source_code') or '')[:64] or None
|
||||
file_no = str(result.get('inventory_file_no') or '')[:128] or None
|
||||
file_no = str(result.get('inventory_file_no') or snapshot_file_no or '')[:128] or None
|
||||
row_index_raw = result.get('inventory_row_index') or result.get('inventory_row_ref')
|
||||
try:
|
||||
row_index = int(row_index_raw) if row_index_raw is not None and str(row_index_raw).strip() else None
|
||||
@@ -295,7 +302,7 @@ def persist_line_inventory_match_facts(
|
||||
else:
|
||||
# [T6 E1] 更新分支:同样重算 evidence_ref、matched_file_no、matched_row_index
|
||||
src_code = str(result.get('resolved_inventory_source_code') or '')[:64] or None
|
||||
file_no = str(result.get('inventory_file_no') or '')[:128] or None
|
||||
file_no = str(result.get('inventory_file_no') or snapshot_file_no or '')[:128] or None
|
||||
row_index_raw = result.get('inventory_row_index') or result.get('inventory_row_ref')
|
||||
try:
|
||||
row_index = int(row_index_raw) if row_index_raw is not None and str(row_index_raw).strip() else None
|
||||
|
||||
@@ -36,6 +36,7 @@ STATUS_INVALID_KEY = 'invalid_key'
|
||||
ACTION_RETRY_PREPARATION = 'retry_inventory_preparation'
|
||||
ACTION_RETRY_MATCHING = 'retry_inventory_matching'
|
||||
ACTION_CLOSE = 'close_unfulfillable'
|
||||
ACTION_RELEASE_SHORTAGE = 'release_inventory_shortage'
|
||||
ACTION_VIEW_FULFILLMENT = 'view_fulfillment_detail' # 已下线:不得再下发 UI
|
||||
|
||||
|
||||
@@ -238,6 +239,8 @@ def project_user_line_status(
|
||||
stored = str(stored_line_status or '').strip()
|
||||
if stored in {'closed_unfulfillable'}:
|
||||
return 'closed'
|
||||
if stored in {'released_shortage'}:
|
||||
return 'released_shortage'
|
||||
if stored in {'fulfilled'}:
|
||||
return 'fulfilled'
|
||||
if stored in {'task_created'}:
|
||||
@@ -294,8 +297,8 @@ def resolve_inventory_allowed_actions(
|
||||
user_status = str(user_line_status or '').strip()
|
||||
if not has_formal_ot:
|
||||
return []
|
||||
if stored in {'task_created', 'fulfilled', 'closed_unfulfillable'} or user_status in {
|
||||
'wave_created', 'fulfilled', 'closed',
|
||||
if stored in {'task_created', 'fulfilled', 'closed_unfulfillable', 'released_shortage'} or user_status in {
|
||||
'wave_created', 'fulfilled', 'closed', 'released_shortage',
|
||||
}:
|
||||
return []
|
||||
if inventory_rpa_running or user_status == 'acquiring_inventory':
|
||||
@@ -310,7 +313,12 @@ def resolve_inventory_allowed_actions(
|
||||
return []
|
||||
|
||||
if is_shortage or result == MATCH_NOT_FOUND or user_status == 'shortage':
|
||||
return [ACTION_RETRY_PREPARATION]
|
||||
# 短缺既可能需要重新取最新库存,也可能仅需用当前有效快照重匹;
|
||||
# 两种意图并列下发,前端不得因已有快照隐藏刷新库存入口。
|
||||
actions = [ACTION_RETRY_PREPARATION]
|
||||
if has_usable_snapshot:
|
||||
actions.append(ACTION_RETRY_MATCHING)
|
||||
return actions
|
||||
|
||||
if (
|
||||
status == STATUS_MAPPING_FAILED
|
||||
@@ -351,7 +359,7 @@ def resolve_line_allowed_actions(
|
||||
user_line_status: str | None,
|
||||
) -> list[str]:
|
||||
"""
|
||||
行生命周期动作;仅 close_unfulfillable。
|
||||
行生命周期动作;短缺行可关闭或填写原因放行。
|
||||
|
||||
核心逻辑:已完成/已关闭/已入波次不开放行动作;彻底移除 view_fulfillment_detail。
|
||||
"""
|
||||
@@ -359,11 +367,14 @@ def resolve_line_allowed_actions(
|
||||
return []
|
||||
stored = str(stored_line_status or '').strip()
|
||||
user_status = str(user_line_status or '').strip()
|
||||
if stored in {'task_created', 'fulfilled', 'closed_unfulfillable'} or user_status in {
|
||||
'wave_created', 'fulfilled', 'closed',
|
||||
if stored in {'task_created', 'fulfilled', 'closed_unfulfillable', 'released_shortage'} or user_status in {
|
||||
'wave_created', 'fulfilled', 'closed', 'released_shortage',
|
||||
}:
|
||||
return []
|
||||
return [ACTION_CLOSE]
|
||||
actions = [ACTION_CLOSE]
|
||||
if user_status == 'shortage':
|
||||
actions.append(ACTION_RELEASE_SHORTAGE)
|
||||
return actions
|
||||
|
||||
|
||||
def resolve_allowed_actions(
|
||||
@@ -491,7 +502,7 @@ def project_line_inventory_view(
|
||||
|
||||
Args:
|
||||
fallback_inventory_source: Task 级回退库存源事实(行级匹配缺失时使用)。
|
||||
支持:resolved / user_confirmed / candidates_frozen / resolving 四种语义。
|
||||
支持:resolved / candidates_frozen / resolving 三种语义。
|
||||
仅影响 inventory_source 展示对象,不得污染 inventory_status / match_result /
|
||||
available_qty / shortage_qty / is_shortage / allowed_actions。
|
||||
|
||||
@@ -518,7 +529,6 @@ def project_line_inventory_view(
|
||||
if fallback.get('code') and fallback.get('status') in {
|
||||
SOURCE_STATUS_RESOLVED,
|
||||
'resolved',
|
||||
'user_confirmed',
|
||||
}:
|
||||
pre_source = {
|
||||
'code': fallback.get('code'),
|
||||
@@ -618,7 +628,7 @@ def project_line_inventory_view(
|
||||
fb_code = str(fallback.get('code') or '').strip().upper() or None
|
||||
fb_status = str(fallback.get('status') or '').strip()
|
||||
if not line_source_code and fallback:
|
||||
if fb_code and fb_status in {'resolved', 'user_confirmed', SOURCE_STATUS_RESOLVED}:
|
||||
if fb_code and fb_status in {'resolved', SOURCE_STATUS_RESOLVED}:
|
||||
label_val = str(fallback.get('label') or '').strip() or (
|
||||
(source_labels or {}).get(fb_code)
|
||||
)
|
||||
|
||||
@@ -20,7 +20,7 @@ NOTICE_LINE_FIELDS = (
|
||||
"customer_part_number",
|
||||
"aws_part_number",
|
||||
"uom",
|
||||
"remark",
|
||||
"line_remark",
|
||||
"po_number",
|
||||
"allocation_id",
|
||||
"inventory_source_hint",
|
||||
@@ -40,4 +40,5 @@ NOTICE_FIELD_LABELS = {
|
||||
"po_number": "PO Number",
|
||||
"allocation_id": "Allocation ID",
|
||||
"inventory_source_hint": "库存来源提示 / Hub Code",
|
||||
"line_remark": "行备注",
|
||||
}
|
||||
@@ -130,7 +130,7 @@ def parse_notice_row(
|
||||
|
||||
for field in (
|
||||
'currency', 'uom', 'required_date', 'po_number', 'inventory_source_hint',
|
||||
'customer_part_number', 'aws_part_number',
|
||||
'customer_part_number', 'aws_part_number', 'line_remark',
|
||||
):
|
||||
idx = columns.get(field)
|
||||
if idx is None:
|
||||
|
||||
@@ -87,7 +87,7 @@ def resolve_notice_columns(
|
||||
核心逻辑:逐列匹配冻结契约;同一字段命中多个列时记录歧义并清空该映射。
|
||||
"""
|
||||
columns: dict[str, int | list[str] | None] = {
|
||||
field: None for field in NOTICE_LINE_FIELDS if field not in {"uom", "remark"}
|
||||
field: None for field in NOTICE_LINE_FIELDS if field not in {"uom", "line_remark"}
|
||||
}
|
||||
ambiguous: set[str] = set()
|
||||
for i, header in enumerate(headers):
|
||||
|
||||
@@ -103,6 +103,61 @@ def non_atomic_part_number_field(raw: dict[str, Any] | None) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def _canonicalize_schema_line_aliases(
|
||||
raw: dict[str, Any], *, schema_definition: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
以本次冻结 Schema 的明细字段别名将输入键归一化为 field_code。
|
||||
|
||||
核心逻辑:字段代码优先于别名;同一原始行的多个别名同时映射一个字段时不静默选值,
|
||||
仅保留已存在的字段代码。无 Schema 时只接受调用方提供的正式字段代码。
|
||||
Args:
|
||||
raw: 原始订单行,键可能为邮件/PDF 表头或正式字段代码。
|
||||
schema_definition: 本次 Run 冻结的完整订单 Schema。
|
||||
Returns:
|
||||
使用正式 field_code 作为键的订单行副本。
|
||||
"""
|
||||
canonical = dict(raw)
|
||||
if not schema_definition:
|
||||
return canonical
|
||||
|
||||
aliases: dict[str, str] = {}
|
||||
ambiguous_aliases: set[str] = set()
|
||||
for field in schema_definition.get('fields') or []:
|
||||
if not isinstance(field, dict) or not field.get('enabled', True):
|
||||
continue
|
||||
if str(field.get('scope') or 'line').strip().lower() != 'line':
|
||||
continue
|
||||
field_code = str(field.get('field_code') or '').strip()
|
||||
if not field_code:
|
||||
continue
|
||||
for name in (field_code, field.get('display_name'), *(field.get('aliases') or [])):
|
||||
normalized = norm_header(name)
|
||||
if not normalized:
|
||||
continue
|
||||
previous = aliases.get(normalized)
|
||||
if previous is None:
|
||||
aliases[normalized] = field_code
|
||||
elif previous != field_code:
|
||||
ambiguous_aliases.add(normalized)
|
||||
|
||||
mapped_values: dict[str, Any] = {}
|
||||
ambiguous_codes: set[str] = set()
|
||||
for name, value in raw.items():
|
||||
normalized_name = norm_header(name)
|
||||
field_code = None if normalized_name in ambiguous_aliases else aliases.get(normalized_name)
|
||||
if not field_code or field_code in canonical:
|
||||
continue
|
||||
if field_code in mapped_values:
|
||||
ambiguous_codes.add(field_code)
|
||||
continue
|
||||
mapped_values[field_code] = value
|
||||
for field_code, value in mapped_values.items():
|
||||
if field_code not in ambiguous_codes:
|
||||
canonical[field_code] = value
|
||||
return canonical
|
||||
|
||||
|
||||
def normalize_notice_line(
|
||||
raw: dict[str, Any] | None,
|
||||
*,
|
||||
@@ -121,6 +176,7 @@ def normalize_notice_line(
|
||||
"""
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
raw = _canonicalize_schema_line_aliases(raw, schema_definition=schema_definition)
|
||||
if non_atomic_part_number_field(raw):
|
||||
return None
|
||||
|
||||
@@ -130,7 +186,7 @@ def normalize_notice_line(
|
||||
if not part_number or "/" in part_number:
|
||||
return None
|
||||
|
||||
qty = parse_number(raw.get("qty") if raw.get("qty") is not None else raw.get("quantity"))
|
||||
qty = parse_number(raw.get("qty"))
|
||||
if qty is None or qty <= 0:
|
||||
return None
|
||||
|
||||
@@ -145,89 +201,51 @@ def normalize_notice_line(
|
||||
if raw_uom and field_enabled("uom"):
|
||||
line["uom"] = raw_uom
|
||||
|
||||
line_no = normalize_line_no(
|
||||
raw.get("line_no")
|
||||
or raw.get("lineNo")
|
||||
or raw.get("item")
|
||||
or raw.get("item_no")
|
||||
or raw.get("itemNo")
|
||||
or raw.get("Item")
|
||||
or raw.get("Item No")
|
||||
)
|
||||
line_no = normalize_line_no(raw.get("line_no"))
|
||||
if line_no and field_enabled("line_no"):
|
||||
line["line_no"] = line_no
|
||||
|
||||
reservation_id = extract_reservation_id(
|
||||
raw.get("reservation_id")
|
||||
or raw.get("reservationId")
|
||||
or raw.get("com_id")
|
||||
or raw.get("reservation_order")
|
||||
or raw.get("pr_number")
|
||||
or raw.get("prNumber")
|
||||
or raw.get("PR Number")
|
||||
)
|
||||
reservation_id = extract_reservation_id(raw.get("reservation_id"))
|
||||
if reservation_id and field_enabled("reservation_id"):
|
||||
line["reservation_id"] = reservation_id
|
||||
evidence = raw.get("reservation_id_evidence")
|
||||
if isinstance(evidence, dict) and field_enabled("reservation_id"):
|
||||
line["reservation_id_evidence"] = dict(evidence)
|
||||
|
||||
unit_price = parse_number(raw.get("unit_price") if raw.get("unit_price") is not None else raw.get("price"))
|
||||
unit_price = parse_number(raw.get("unit_price"))
|
||||
if unit_price is not None and field_enabled("unit_price"):
|
||||
line["unit_price"] = unit_price
|
||||
|
||||
amount = parse_number(raw.get("amount") if raw.get("amount") is not None else raw.get("total"))
|
||||
amount = parse_number(raw.get("amount"))
|
||||
if amount is not None and field_enabled("amount"):
|
||||
line["amount"] = amount
|
||||
elif unit_price is not None and field_enabled("amount"):
|
||||
line["amount"] = round(unit_price * qty, 4)
|
||||
|
||||
currency = normalize_currency(raw.get("currency") or raw.get("Currency"))
|
||||
currency = normalize_currency(raw.get("currency"))
|
||||
if not currency:
|
||||
currency = extract_currency(
|
||||
raw.get("unit_price"),
|
||||
raw.get("price"),
|
||||
raw.get("amount"),
|
||||
raw.get("total"),
|
||||
raw.get("unit_price"), raw.get("amount"),
|
||||
)
|
||||
if currency and field_enabled("currency"):
|
||||
line["currency"] = currency
|
||||
|
||||
required_date = normalize_required_date(
|
||||
raw.get("required_date")
|
||||
or raw.get("delivery_date")
|
||||
or raw.get("deliveryDate")
|
||||
or raw.get("eta")
|
||||
or raw.get("ETA")
|
||||
)
|
||||
required_date = normalize_required_date(raw.get("required_date"))
|
||||
if required_date and field_enabled("required_date"):
|
||||
line["required_date"] = required_date
|
||||
|
||||
optional_aliases = {
|
||||
"po_number": ("po_number", "poNumber", "PO", "PO Number"),
|
||||
"allocation_id": ("allocation_id", "allocationId", "Allocation ID"),
|
||||
"inventory_source_hint": (
|
||||
"inventory_source_hint",
|
||||
"Source Type",
|
||||
"Hub Code",
|
||||
"Hub",
|
||||
"HUB",
|
||||
),
|
||||
"customer_part_number": ("customer_part_number", "Customer Part Number", "Customer PN", "Allocated HHPN"),
|
||||
"aws_part_number": ("aws_part_number", "AWS Sku", "AWS SKU"),
|
||||
}
|
||||
optional_fields = (
|
||||
"po_number", "allocation_id", "inventory_source_hint",
|
||||
"customer_part_number", "aws_part_number", "line_remark",
|
||||
)
|
||||
if composite.get('customer_part_number'):
|
||||
if field_enabled('customer_part_number'):
|
||||
line['customer_part_number'] = composite['customer_part_number']
|
||||
for field, aliases in optional_aliases.items():
|
||||
value = next((str(raw.get(alias) or "").strip() for alias in aliases if raw.get(alias)), "")
|
||||
for field in optional_fields:
|
||||
value = str(raw.get(field) or "").strip()
|
||||
if value and field_enabled(field):
|
||||
line[field] = value
|
||||
|
||||
remark = str(raw.get("remark") or raw.get("note") or "").strip()
|
||||
if remark and field_enabled("remark"):
|
||||
line["remark"] = remark
|
||||
|
||||
return line
|
||||
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ def _post_op(
|
||||
"200": {
|
||||
"description": (
|
||||
"Tool response (status: ok|running|needs_human|failed). "
|
||||
"May include checkpoint and human_options; business buttons are exposed only by ui_state.actions."
|
||||
"May include checkpoint; business buttons are exposed only by ui_state.actions."
|
||||
),
|
||||
"content": {
|
||||
"application/json": {
|
||||
@@ -86,7 +86,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"paths": {
|
||||
"/tools/get_task_status": _post_op(
|
||||
"get_task_status",
|
||||
"查询任务当前状态与 human_options;响应含库存连接器独立字段与候选结构",
|
||||
"查询任务当前状态;响应含库存连接器独立字段与候选结构",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"conversation_id": _str_prop("Dify 会话 ID"),
|
||||
@@ -96,9 +96,8 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
description=(
|
||||
"返回 inventory_source_code、inventory_connector_type、"
|
||||
"inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|"
|
||||
"user_confirmed|invalid|conflicted)、inventory_source_method、"
|
||||
"candidates_frozen|invalid|conflicted)、inventory_source_method、"
|
||||
"inventory_source_config_version、inventory_routing_fingerprint、"
|
||||
"inventory_source_confirmed_by、inventory_source_confirmed_at,"
|
||||
"以及 step_payload.inventory_source_resolution.candidates。"
|
||||
),
|
||||
),
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
services/shipping_notice/order_auto_freeze_policy.py
|
||||
|
||||
用途:统一生成订单抽取 Run 的自动冻结门禁摘要,不让各处各自拼 policy JSON。
|
||||
依赖:Run/Unit/RouteDecision/Qualification 模型;tool_common 紧急停止与分路径/XFA 开关;
|
||||
依赖:Run/Unit/RouteDecision/Qualification 模型;tool_common 紧急停止与通用开关;
|
||||
process_gate_contract(原因唯一归属 order_freeze_readiness)。
|
||||
逻辑:Run 创建时冻结初始人工确认策略;结果落库后按解析路径、技术失败、预算停止、
|
||||
紧急停止和复核状态刷新 Run 级摘要。
|
||||
模板 Profile 批准写入 parser / qualification 痕迹,不再作为唯一放行条件;
|
||||
LLM 路径可进入 Candidate Qualification,不再天然追加 llm_path_cannot_auto_freeze;
|
||||
XFA 写入 shadow/可选观测白名单痕迹;真实自动建单与坐标共用统一 Candidate Qualification。
|
||||
XFA datasets 仅写入值源身份痕迹;真实自动建单与坐标共用统一 Candidate Qualification。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -30,10 +30,6 @@ from app.services.shipping_notice.process_gate_contract import (
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
extraction_emergency_stop_enabled,
|
||||
generic_auto_freeze_enabled,
|
||||
xfa_customer_allowlist,
|
||||
xfa_profile_checksum_allowlist,
|
||||
xfa_scenario_allowlist,
|
||||
xfa_shadow_mode_enabled,
|
||||
)
|
||||
|
||||
_DEFAULT_BUSINESS_SCENARIO = 'shipping_notice_order'
|
||||
@@ -80,7 +76,7 @@ def evaluate_run_auto_freeze_policy(
|
||||
'profile_auto_create_approved': False,
|
||||
'llm_route_present': _has_llm_assisted_route(run),
|
||||
'note': 'template_quality_only_not_auto_create_gate',
|
||||
'xfa': _xfa_policy_trace(run),
|
||||
'value_adapter': _value_adapter_trace(run),
|
||||
}
|
||||
|
||||
# [STEP 1] 全局紧急停止:新 Run 自动冻结立即为 0。
|
||||
@@ -215,33 +211,20 @@ def evaluate_run_auto_freeze_policy(
|
||||
return policy
|
||||
|
||||
|
||||
def _xfa_policy_trace(run: ShippingOrderProcessingRun) -> dict[str, Any]:
|
||||
def _value_adapter_trace(run: ShippingOrderProcessingRun) -> dict[str, Any]:
|
||||
"""
|
||||
汇总 Run 级 XFA 策略痕迹(真实放行仍由 CQ/STP 硬门禁裁决)。
|
||||
汇总 Run 级末端取值 adapter 身份痕迹。
|
||||
|
||||
核心逻辑:记录 shadow 与白名单规模,供审计对账;空白名单在 CQ 层 fail-closed。
|
||||
核心逻辑:仅记录数据集 adapter 是否参与,不能读取或冻结模板类型专属放行策略。
|
||||
"""
|
||||
has_xfa = any(
|
||||
str(_route_contract(route).get('capability_kind') or '').strip() == 'xfa_dataset'
|
||||
or bool(_route_contract(route).get('xfa_evidence_summary'))
|
||||
for route in (run.route_decisions or [])
|
||||
)
|
||||
try:
|
||||
shadow = bool(xfa_shadow_mode_enabled())
|
||||
customers = list(xfa_customer_allowlist())
|
||||
checksums = list(xfa_profile_checksum_allowlist())
|
||||
scenarios = list(xfa_scenario_allowlist())
|
||||
except RuntimeError:
|
||||
shadow = False
|
||||
customers, checksums, scenarios = [], [], ['shipping_notice_order']
|
||||
return {
|
||||
'xfa_route_present': has_xfa,
|
||||
'hard_gates_enabled': True,
|
||||
'shadow_mode': shadow,
|
||||
'customer_allowlist_count': len(customers),
|
||||
'profile_checksum_allowlist_count': len(checksums),
|
||||
'scenario_allowlist': scenarios,
|
||||
'emergency_stop_blocks_auto_create': bool(extraction_emergency_stop_enabled()),
|
||||
'adapter_kind': 'xfa_dataset' if has_xfa else 'coordinate_ocr',
|
||||
'datasets_adapter_present': has_xfa,
|
||||
}
|
||||
|
||||
|
||||
|
||||
Loaded 100 of 466 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user