Merge branch 'hugo-shipping-notice' into dev
This commit is contained in:
commit
3985b34dda
606 files changed
+52167
-36839
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,7 @@ 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
|
||||
from app.services.shipping_notice import order_document_profile_service as service
|
||||
@@ -34,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:
|
||||
@@ -56,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)
|
||||
@@ -243,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,
|
||||
))
|
||||
@@ -427,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(
|
||||
@@ -533,6 +554,31 @@ 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>/pdf-preview', methods=['POST'])
|
||||
@require_admin
|
||||
def authorize_order_document_profile_pdf_preview(profile_id: int):
|
||||
"""签发坐标 PDF 与 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>/pdf-preview', methods=['GET'])
|
||||
@require_admin
|
||||
def get_order_document_profile_pdf_preview(profile_id: int):
|
||||
"""消费统一画布令牌返回原 PDF 字节,禁止缓存、下载和重放。"""
|
||||
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>/samples/<int:sample_binding_id>/preview-pages', methods=['POST'])
|
||||
@require_admin
|
||||
def authorize_order_document_profile_frozen_sample_preview_pages(profile_id: int, sample_binding_id: int):
|
||||
@@ -643,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)
|
||||
|
||||
@@ -759,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 返回样本值投影。
|
||||
|
||||
@@ -794,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,
|
||||
@@ -803,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(),
|
||||
@@ -889,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,
|
||||
@@ -940,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')
|
||||
@@ -976,167 +948,46 @@ 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',
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/pdf-automark',
|
||||
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>/xfa/automark',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def enqueue_order_document_profile_xfa_ocr_automark(profile_id: int):
|
||||
"""
|
||||
入队 XFA OCR 自动标记异步 Job。
|
||||
|
||||
核心逻辑:body.document_id 必填;可选 force 强制重生成合成预览后入队。
|
||||
"""
|
||||
def enqueue_order_document_profile_pdf_automark(profile_id: int):
|
||||
"""入队统一 PDF 自动标记;客户端不得按 XFA/普通 PDF 选择接口。"""
|
||||
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(
|
||||
raise ValidationError('document_id is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
return _private_ok(pdf_automark_service.enqueue_pdf_automark(
|
||||
profile_id,
|
||||
document_id=int(document_id),
|
||||
table_id=str(data.get('table_id') or '').strip() or None,
|
||||
schema_version_id=int(data['schema_version_id']) if data.get('schema_version_id') not in (None, '') else None,
|
||||
page_no=int(data['page_no']) if data.get('page_no') not in (None, '') else None,
|
||||
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>',
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/pdf-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,
|
||||
))
|
||||
def get_order_document_profile_pdf_automark_job(profile_id: int, job_id: int):
|
||||
"""轮询统一 PDF 自动标记 Job 的 candidates/diagnostics 契约。"""
|
||||
return _private_ok(pdf_automark_service.get_pdf_automark_job(job_id, profile_id=profile_id))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
|
||||
@@ -301,12 +301,54 @@ def _record_run_bind(run: ScheduleRun, data: dict) -> None:
|
||||
attach_run_to_turn(turn_id, int(run.id))
|
||||
|
||||
|
||||
def _build_no_data_response(task: ScheduleTask) -> dict:
|
||||
"""无待检资料时直接返回提示,不创建批次也不绑定 run_id。"""
|
||||
def _bind_queried_run_to_turn(run: ScheduleRun, data: dict) -> None:
|
||||
"""
|
||||
将已有检核批次关联到本轮查询对话,不改写批次原始执行上下文。
|
||||
|
||||
查询最近批次时触发;仅更新 chat_tool_runs 与内存 turn registry,
|
||||
使 message_end 可以把既有 ScheduleRun.id 写入当前 ChatLog.run_id。
|
||||
"""
|
||||
from app.services.file_check_tools.chat_tool_run_binding import bind_schedule_run
|
||||
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
|
||||
|
||||
turn_id = str(data.get("hxops_turn_id") or "").strip()
|
||||
session_id = str(data.get("conversation_id") or "").strip() or None
|
||||
user_message = str(data.get("user_message") or "").strip() or None
|
||||
if not turn_id:
|
||||
return
|
||||
|
||||
bound = bind_schedule_run(
|
||||
schedule_run_id=int(run.id),
|
||||
turn_id=turn_id,
|
||||
session_id=session_id,
|
||||
user_message=user_message,
|
||||
schedule_task_id=int(run.schedule_task_id),
|
||||
bind_source="tool_query_latest",
|
||||
)
|
||||
if bound:
|
||||
attach_run_to_turn(turn_id, int(run.id))
|
||||
|
||||
|
||||
def _build_no_data_response(task: ScheduleTask, run: ScheduleRun) -> dict:
|
||||
"""
|
||||
组装无待检资料的 Tool 响应,并返回本轮已完成的空批次。
|
||||
|
||||
【AI 触发时机】:用户要求立即执行文件检核,但预检未发现待检资料时调用。
|
||||
核心逻辑:保留 no_data_to_check 供 Chatflow 回复无资料提示,同时携带已绑定的 Run,
|
||||
使前端能在该轮消息下展示总数 0、进度 100% 的完成进度卡。
|
||||
|
||||
Args:
|
||||
task: 当前检核任务。
|
||||
run: 已持久化并绑定当前对话的成功空批次。
|
||||
|
||||
Returns:
|
||||
dict: 包含 no_data_to_check、任务信息和 Run 摘要的 HTTP 200 响应体。
|
||||
"""
|
||||
return {
|
||||
"ok": False,
|
||||
"error_code": "no_data_to_check",
|
||||
"message": "目前没有资料需要检核",
|
||||
"run": _serialize_tool_run(run),
|
||||
"task": {
|
||||
"task_id": task.id,
|
||||
"task_name": task.name,
|
||||
@@ -336,8 +378,8 @@ def _precheck_no_data(task: ScheduleTask) -> dict | None:
|
||||
"""
|
||||
启动前预检当前任务是否存在待检资料。
|
||||
|
||||
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则直接返回 no_data_to_check,
|
||||
避免创建空批次并向 ChatLog 回写 run_id。数据源连接失败时抛 503 data_source_unavailable。
|
||||
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则返回 no_data_to_check 标识,
|
||||
由启动入口创建并绑定完成态的 0 笔 Run。数据源连接失败时抛 503 data_source_unavailable。
|
||||
"""
|
||||
if str(getattr(task, "data_source_type", "") or "database").lower() != "database":
|
||||
return None
|
||||
@@ -361,7 +403,52 @@ def _precheck_no_data(task: ScheduleTask) -> dict | None:
|
||||
|
||||
if rows:
|
||||
return None
|
||||
return _build_no_data_response(task)
|
||||
return {
|
||||
"ok": False,
|
||||
"error_code": "no_data_to_check",
|
||||
"message": "目前没有资料需要检核",
|
||||
}
|
||||
|
||||
|
||||
def _create_no_data_run(task: ScheduleTask, data: dict) -> ScheduleRun:
|
||||
"""
|
||||
为预检为空的立即执行请求创建并绑定已完成的 0 笔检核批次。
|
||||
|
||||
【AI 触发时机】:run_file_check 收到 no_data_to_check 预检结果时调用。
|
||||
核心逻辑:不启动后台 worker,仅写入 success Run 与对话绑定;完成态空批次由工作区进度接口
|
||||
序列化为 100%,让用户明确知道本次检核已经结束且没有待处理资料。
|
||||
|
||||
Args:
|
||||
task: 已解析的文件检核任务。
|
||||
data: Tool 请求及对话绑定上下文。
|
||||
|
||||
Returns:
|
||||
ScheduleRun: 已提交且已绑定当前对话的成功空批次。
|
||||
"""
|
||||
finished_at = datetime.utcnow()
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type="dify_chatflow",
|
||||
started_at=finished_at,
|
||||
finished_at=finished_at,
|
||||
duration_ms=0,
|
||||
status="success",
|
||||
total_count=0,
|
||||
success_count=0,
|
||||
failed_count=0,
|
||||
skipped_count=0,
|
||||
api_request_json={
|
||||
"trigger_source": data.get("trigger_source") or "dify_chatflow",
|
||||
"conversation_id": data.get("conversation_id"),
|
||||
},
|
||||
response_summary_json={"errors": [], "no_data": True},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
_record_run_bind(run, data)
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
|
||||
@@ -411,16 +498,18 @@ def run_file_check():
|
||||
|
||||
no_data_response = _precheck_no_data(task)
|
||||
if no_data_response:
|
||||
run = _create_no_data_run(task, data)
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=no_data resolve_ms=%s lock_ms=%s total_ms=%s task_id=%s",
|
||||
"[file-check-tool-perf] run_file_check outcome=no_data resolve_ms=%s lock_ms=%s total_ms=%s task_id=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
task.id,
|
||||
run.id,
|
||||
)
|
||||
return jsonify(no_data_response)
|
||||
return jsonify(_build_no_data_response(task, run))
|
||||
|
||||
# [STEP] 解析运行选项:优先顶层 mode/invoice_no(Dify Tool 表单对嵌套 object 常不展示),
|
||||
# 再与 run_options 对象合并;立账凭证检核读取,普通文件检核忽略。
|
||||
@@ -534,10 +623,16 @@ def download_file_check_run_excel(run_id: int):
|
||||
|
||||
@file_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
|
||||
def get_latest_file_check_run(task_id: int):
|
||||
"""查询任务最近批次;可绑定本轮对话以展示该批次进度。"""
|
||||
task = _resolve_check_task(task_id=task_id)
|
||||
run = ScheduleRun.query.filter_by(schedule_task_id=task.id).order_by(ScheduleRun.id.desc()).first()
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
_bind_queried_run_to_turn(run, {
|
||||
"hxops_turn_id": request.args.get("hxops_turn_id"),
|
||||
"conversation_id": request.args.get("conversation_id"),
|
||||
"user_message": request.args.get("user_message"),
|
||||
})
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
|
||||
@@ -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/action_buttons。"""
|
||||
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 执行阶段。"""
|
||||
|
||||
@@ -89,7 +89,12 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
|
||||
failed = int(payload.get('failed_count') or 0)
|
||||
skipped = int(payload.get('skipped_count') or 0)
|
||||
processed = success + failed + skipped
|
||||
percent = int(round(processed / total * 100)) if total > 0 else 0
|
||||
if total > 0:
|
||||
percent = int(round(processed / total * 100))
|
||||
elif payload.get('status') == 'success':
|
||||
percent = 100
|
||||
else:
|
||||
percent = 0
|
||||
percent = max(0, min(percent, 100))
|
||||
return {
|
||||
'run_id': payload['id'],
|
||||
@@ -180,4 +185,4 @@ def workspace_file_check_run_excel(run_id: int):
|
||||
raise NotFoundError('run_not_found')
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError('excel_not_found')
|
||||
return send_file(BytesIO(run.excel_file_data), as_attachment=True, download_name=run.excel_file_name or f'{run.run_no}.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
return send_file(BytesIO(run.excel_file_data), as_attachment=True, download_name=run.excel_file_name or f'{run.run_no}.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
@@ -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 归属一致。
|
||||
@@ -124,7 +151,6 @@ def workspace_shipping_tasks():
|
||||
"""分页列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
|
||||
user = _require_user()
|
||||
batch_no = str(request.args.get('batch_no') or '').strip() or None
|
||||
process_status = str(request.args.get('process_status') or '').strip() or None
|
||||
lifecycle_status = str(request.args.get('lifecycle_status') or '').strip() or None
|
||||
try:
|
||||
page = int(request.args.get('page') or 1)
|
||||
@@ -136,7 +162,6 @@ def workspace_shipping_tasks():
|
||||
return _ok(list_tasks_page_for_user(
|
||||
user.id,
|
||||
batch_no=batch_no,
|
||||
process_status=process_status,
|
||||
lifecycle_status=lifecycle_status,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
@@ -493,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,
|
||||
)
|
||||
@@ -510,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:
|
||||
@@ -535,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,再交给后台编排器。"""
|
||||
@@ -647,8 +601,7 @@ def workspace_create_shipping_task_from_notice():
|
||||
task_no=task_id,
|
||||
)
|
||||
if not intake.accepted:
|
||||
# 旧 action_buttons 业务调用清零:仅保留 human_options 文案提示,不再下发可点击恢复按钮。
|
||||
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': []})
|
||||
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
|
||||
@@ -697,7 +650,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
返回指定任务的详情快照与内嵌 UI State。
|
||||
|
||||
核心逻辑:详情接口直接内嵌 `ui_state`,让页面首屏读取任务详情时即可拿到
|
||||
checkpoint / action_buttons / steps,减少前端二次推导与竞态刷新。
|
||||
checkpoint / actions / steps,减少前端二次推导与竞态刷新。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
@@ -707,7 +660,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
raise NotFoundError('Not found')
|
||||
return _ok({
|
||||
**serialize_task_detail(task, viewer_user_id=user.id, is_admin=is_admin),
|
||||
'ui_state': build_task_ui_state(task),
|
||||
'ui_state': build_task_ui_state(task, include_stage_context=True),
|
||||
})
|
||||
|
||||
|
||||
@@ -755,7 +708,7 @@ def workspace_shipping_task_ui_state(task_no: str):
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_task_ui_state(task))
|
||||
return _ok(build_task_ui_state(task, include_stage_context=True))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
|
||||
def workspace_shipping_task_chat_actions(task_no: str):
|
||||
@@ -820,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):
|
||||
"""更新发货通知单头字段。"""
|
||||
@@ -902,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):
|
||||
@@ -1124,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):
|
||||
"""
|
||||
@@ -1200,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;写入统一访问审计。"""
|
||||
@@ -1242,6 +1055,80 @@ def workspace_shipping_task_export(task_no: str):
|
||||
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/inventory-file', methods=['GET'])
|
||||
def workspace_shipping_task_inventory_file(task_no: str):
|
||||
"""下载当前任务实际关联的库存快照;无 active link 或托管文件时 fail-closed。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download
|
||||
|
||||
resolved = resolve_task_inventory_download(task)
|
||||
if resolved is None:
|
||||
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND')
|
||||
path, download_name = resolved
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
record_access_audit(
|
||||
action='download_task_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},
|
||||
)
|
||||
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():
|
||||
"""列出当前会话下未消费的活跃接入记录。"""
|
||||
@@ -1495,7 +1382,8 @@ def workspace_list_shipping_order_extraction_progress_events(run_no: str):
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_extraction_run_service import list_user_order_extraction_progress_events
|
||||
|
||||
items = list_user_order_extraction_progress_events(user_id=user.id, run_no=run_no)
|
||||
batch_id = str(request.args.get('upload_batch_id') or '').strip() or None
|
||||
items = list_user_order_extraction_progress_events(user_id=user.id, run_no=run_no, batch_id=batch_id)
|
||||
record_access_audit(
|
||||
action='view_order_extraction_timeline',
|
||||
aggregate_type='order_extraction_run',
|
||||
@@ -1514,7 +1402,8 @@ def workspace_list_shipping_order_extraction_documents(run_no: str):
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_extraction_run_service import list_user_order_extraction_documents
|
||||
|
||||
items = list_user_order_extraction_documents(user_id=user.id, run_no=run_no)
|
||||
batch_id = str(request.args.get('upload_batch_id') or '').strip() or None
|
||||
items = list_user_order_extraction_documents(user_id=user.id, run_no=run_no, batch_id=batch_id)
|
||||
record_access_audit(
|
||||
action='view_order_extraction_documents',
|
||||
aggregate_type='order_extraction_run',
|
||||
@@ -1546,6 +1435,29 @@ def workspace_get_shipping_order_review_run(run_no: str):
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-queue/<run_no>', methods=['GET'])
|
||||
def workspace_get_shipping_order_review_queue(run_no: str):
|
||||
"""读取当前会话的有效订单队列;不改变单 Run 复核摘要 API 语义。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_queue
|
||||
from app.services.shipping_notice.order_review_service import get_review_queue_visible_to_user
|
||||
|
||||
runs = get_review_queue_visible_to_user(run_no, user.id, is_admin=is_admin)
|
||||
payload = serialize_review_queue(runs)
|
||||
record_access_audit(
|
||||
action='view_order_review_queue',
|
||||
aggregate_type='conversation',
|
||||
aggregate_id=str(payload.get('conversation_id') or ''),
|
||||
actor_id=user.id,
|
||||
conversation_id=str(payload.get('conversation_id') or '') or None,
|
||||
run_no=str(run_no),
|
||||
metadata={'item_count': len(payload.get('items') or [])},
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>', methods=['GET'])
|
||||
def workspace_get_shipping_order_review_case(case_no: str):
|
||||
"""读取当前用户的一份 PDF 复核完整快照;Case 编号不能跨 owner 越权访问;访问留痕。"""
|
||||
@@ -1608,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'],
|
||||
@@ -1991,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 与幂等键。
|
||||
"""
|
||||
@@ -2046,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'],
|
||||
@@ -2205,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 {}
|
||||
@@ -2220,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,
|
||||
)
|
||||
@@ -2580,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 的安全证据摘要;不泄露全文、对象存储位置或模型响应;访问留痕。"""
|
||||
@@ -2839,6 +2579,76 @@ def workspace_preview_shipping_order_review_document(case_no: str):
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/intake-parse-context', methods=['GET'],
|
||||
)
|
||||
def workspace_get_shipping_order_review_intake_parse_context(case_no: str):
|
||||
"""
|
||||
返回当前 Case 所属 Intake 的受控解析上下文,并记录敏感读取访问审计。
|
||||
|
||||
核心逻辑:只委托 Case 边界服务构造附件/同 Intake 邮件正文 DTO;PDF 二进制仍必须通过
|
||||
document-preview 代理读取,禁止把对象存储地址或资产内部定位下发至浏览器。
|
||||
"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_evidence_service import get_case_intake_parse_context
|
||||
|
||||
payload = get_case_intake_parse_context(user_id=user.id, case_no=case_no)
|
||||
attachment = payload['attachment']
|
||||
record_access_audit(
|
||||
action='view_order_review_intake_parse_context',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(case_no),
|
||||
actor_id=user.id,
|
||||
document_id=attachment['document_id'],
|
||||
review_case_no=str(case_no),
|
||||
metadata={
|
||||
'access_action': 'view_order_review_intake_parse_context',
|
||||
'workbench_event': 'intake_parse_context_viewed',
|
||||
'attachment_preview_kind': attachment['preview_kind'],
|
||||
'has_email_context': payload['email'] is not None,
|
||||
},
|
||||
)
|
||||
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 邮件正文的受控 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,
|
||||
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'])
|
||||
def workspace_mark_shipping_order_extraction_run_seen(run_no: str):
|
||||
"""确认当前用户已加载终态订单识别卡片;写入已读状态变更审计。"""
|
||||
@@ -2959,7 +2769,8 @@ def workspace_shipping_order_extraction_timeline(run_no: str):
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_extraction_run_service import list_user_order_extraction_progress_events
|
||||
|
||||
items = list_user_order_extraction_progress_events(user_id=user.id, run_no=run_no)
|
||||
batch_id = str(request.args.get('upload_batch_id') or '').strip() or None
|
||||
items = list_user_order_extraction_progress_events(user_id=user.id, run_no=run_no, batch_id=batch_id)
|
||||
record_access_audit(
|
||||
action='view_order_extraction_timeline',
|
||||
aggregate_type='order_extraction_run',
|
||||
@@ -3001,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():
|
||||
"""
|
||||
|
||||
Reference in new issue
Block a user