feat(shipping-notice): 新增发货通知自动上传功能与候选资格评估

- 在环境配置中新增 SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 选项,默认关闭,需显式开启以支持自动上传。
- 引入新的 pytest.ini 文件,增加测试标记以支持自动化测试。
- 删除不再使用的 seed_shipping_notice_agents.py 文件,简化代码库。
- 更新相关 API,增强发货通知与候选资格评估功能,支持多种筛选条件。
- 增强文档与代码注释,反映新的业务逻辑与功能要求。
This commit is contained in:
hugo committed 2026-08-02 19:26:35 +08:00
1 parent cef3d5b26a
commit 3a9fbac2fc
226 files changed
+24683 -1771

No files matched your search

+2
View File
@@ -182,6 +182,8 @@ SHIPPING_NOTICE_LLM_REVIEW_ENABLED=false
SHIPPING_NOTICE_EXTRACTION_EMERGENCY_STOP=false SHIPPING_NOTICE_EXTRACTION_EMERGENCY_STOP=false
# 货代统一审计默认保留天数(三年);到期由 shipping-audit-retention Job 清理。 # 货代统一审计默认保留天数(三年);到期由 shipping-audit-retention Job 清理。
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095 SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
# 货代上传 RPA:默认关闭;具备 Worker/凭据/共享目录与隔离校验后再在环境文件显式设 true。
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
# Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs. # Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs.
SHIPPING_NOTICE_RPA_WORKER_MOCK=false SHIPPING_NOTICE_RPA_WORKER_MOCK=false
# 企微心跳告警总开关(默认关闭;需要时在环境文件改为 true) # 企微心跳告警总开关(默认关闭;需要时在环境文件改为 true)
+10 -1
View File
@@ -4,7 +4,8 @@ backend/app/__init__.py
用途:应用工厂:创建 Flask 应用、挂载全局异常与响应处理。 用途:应用工厂:创建 Flask 应用、挂载全局异常与响应处理。
依赖:app.extensions(db、migrate)、app.api.register_blueprints、app.core.config。 依赖:app.extensions(db、migrate)、app.api.register_blueprints、app.core.config。
逻辑:create_app 初始化扩展后委托 api 层集中注册 Blueprint;启动时 load_context_adapters 注册 Dify 上下文 adapter; 逻辑:create_app 初始化扩展后委托 api 层集中注册 Blueprint;启动时 load_context_adapters 注册 Dify 上下文 adapter;
并幂等补建 file-asset-cleanup 默认排程(覆盖空库先迁移后建用户)。 并幂等补建 file-asset-cleanup 默认排程(覆盖空库先迁移后建用户);
AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA 就绪(仅告警不阻断启动)。
""" """
import logging import logging
import uuid import uuid
@@ -81,6 +82,14 @@ def create_app(config_name='default'):
logger.warning('Failed to ensure file-asset-cleanup schedule: %s', exc) logger.warning('Failed to ensure file-asset-cleanup schedule: %s', exc)
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
FixedAssetsSnapshotService.start_worker(app) FixedAssetsSnapshotService.start_worker(app)
# AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。
try:
from app.services.shipping_notice.rpa_worker_heartbeat import (
log_auto_upload_readiness_at_startup,
)
log_auto_upload_readiness_at_startup(app)
except Exception as exc: # pragma: no cover - 启动容忍
logger.warning('Failed to check freight upload RPA readiness at startup: %s', exc)
@app.before_request @app.before_request
def _sync_persisted_settings(): def _sync_persisted_settings():
@@ -246,8 +246,9 @@ def _audit_filters_from_request() -> dict:
if not isinstance(source, dict): if not isinstance(source, dict):
raise ValidationError('filters must be an object') raise ValidationError('filters must be an object')
keys = ( keys = (
'event_type', 'actor_type', 'actor_id', 'run_no', 'task_no', 'document_id', 'event_type', 'event_type_group', 'actor_type', 'actor_id', 'run_no', 'task_no', 'document_id',
'operation_id', 'request_id', 'aggregate_type', 'aggregate_id', 'result', 'operation_id', 'request_id', 'aggregate_type', 'aggregate_id', 'candidate_no',
'gate_code', 'node_code', 'result', 'reason_code',
'conversation_id', 'workflow_id', 'workflow_item_id', 'review_case_no', 'case_no', 'conversation_id', 'workflow_id', 'workflow_item_id', 'review_case_no', 'case_no',
'owner_user_id', 'created_from', 'created_to', 'q', 'owner_user_id', 'created_from', 'created_to', 'q',
) )
+479 -50
View File
@@ -2,17 +2,18 @@
backend/app/api/workspace/shipping_notice.py backend/app/api/workspace/shipping_notice.py
用途:HXOPS 工作台发货通知用户态 API(任务处理工作台为履约写操作入口;Chat 仅通知/上传)。 用途:HXOPS 工作台发货通知用户态 API(任务处理工作台为履约写操作入口;Chat 仅通知/上传)。
依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload / ui_state、 依赖:app.core.auth.jwt、app.core.errors、app.core.response.ok、shipping_notice.query_service /
workflow_progress_projection / workflow_ledger_service(Workflow 只读与取消)。 tools / notice_upload / ui_state、workflow_progress_projection / workflow_ledger_service。
逻辑:薄路由层鉴权与参数校验;写接口保留乐观锁、幂等键与统一 AppError; 逻辑:薄路由层鉴权与参数校验;成功响应统一走 `_ok`/`ok` envelope;写接口保留乐观锁、幂等键与
人工上传强制证据资产;Chat Turn 履约写路径已废弃,请改走本 Blueprint。 统一 AppError;人工上传强制证据资产;Chat Turn 履约写路径已废弃,请改走本 Blueprint。
""" """
from __future__ import annotations from __future__ import annotations
import uuid import uuid
from io import BytesIO from io import BytesIO
from typing import Any
from flask import Blueprint, g, jsonify, request, send_file from flask import Blueprint, g, request, send_file
from app import db from app import db
from app.core.auth.jwt import get_current_user from app.core.auth.jwt import get_current_user
@@ -75,9 +76,20 @@ def _require_user():
return user return user
def _ok(payload: dict): def _ok(payload: Any, *, status: int = 200):
"""返回带 request_id 的成功 envelope,供工作台读接口复用。""" """
return ok(payload, request_id=getattr(g, 'request_id', None)) 返回带 request_id 的成功 envelope,供工作台读写接口复用。
核心逻辑:委托 `app.core.response.ok`,统一 `{success, data, request_id, timestamp}`。
Args:
payload: 业务数据(dict / list / 其他可 JSON 序列化对象)。
status: HTTP 状态码,默认 200;异步受理可用 202。
Returns:
Flask `(Response, status)` 元组。
"""
return ok(payload, request_id=getattr(g, 'request_id', None), status=status)
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET']) @workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
@@ -94,7 +106,7 @@ def workspace_shipping_tasks():
raise ValidationError('page and page_size must be integers') from exc raise ValidationError('page and page_size must be integers') from exc
if page < 1 or not 1 <= page_size <= 100: if page < 1 or not 1 <= page_size <= 100:
raise ValidationError('page must be positive and page_size must be between 1 and 100') raise ValidationError('page must be positive and page_size must be between 1 and 100')
return jsonify(list_tasks_page_for_user( return _ok(list_tasks_page_for_user(
user.id, user.id,
batch_no=batch_no, batch_no=batch_no,
process_status=process_status, process_status=process_status,
@@ -250,7 +262,7 @@ def workspace_shipping_batches():
"""列出当前用户的发货批次摘要。""" """列出当前用户的发货批次摘要。"""
user = _require_user() user = _require_user()
limit = int(request.args.get('limit') or 100) limit = int(request.args.get('limit') or 100)
return jsonify(list_batches_for_user(user.id, limit=limit)) return _ok(list_batches_for_user(user.id, limit=limit))
@workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST'])
@@ -279,7 +291,7 @@ def workspace_shipping_customers():
limit = int(request.args.get('limit') or 100) limit = int(request.args.get('limit') or 100)
except (TypeError, ValueError) as exc: except (TypeError, ValueError) as exc:
raise ValidationError('Invalid customer limit') from exc raise ValidationError('Invalid customer limit') from exc
return jsonify(list_customer_options(query=query, limit=limit)) return _ok(list_customer_options(query=query, limit=limit))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-customer', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-customer', methods=['POST'])
@@ -299,7 +311,7 @@ def workspace_confirm_shipping_customer(task_no: str):
details={'field': 'customer_id'}, details={'field': 'customer_id'},
) from exc ) from exc
updated = confirm_task_customer(task, customer_id=customer_id, actor_id=user.id) updated = confirm_task_customer(task, customer_id=customer_id, actor_id=user.id)
return jsonify(serialize_task_detail(updated)) return _ok(serialize_task_detail(updated))
@workspace_shipping_notice_bp.route( @workspace_shipping_notice_bp.route(
@@ -427,7 +439,7 @@ def workspace_shipping_batch_tasks(batch_no: str):
batch = get_batch_for_user(batch_no, user.id) batch = get_batch_for_user(batch_no, user.id)
if not batch: if not batch:
raise NotFoundError('Not found') raise NotFoundError('Not found')
return jsonify(list_tasks_for_batch(batch_no, user.id)) return _ok(list_tasks_for_batch(batch_no, user.id))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET']) @workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET'])
def workspace_shipping_batch_focus_task(batch_no: str): def workspace_shipping_batch_focus_task(batch_no: str):
@@ -439,7 +451,7 @@ def workspace_shipping_batch_focus_task(batch_no: str):
focus_task = get_focus_task_for_batch(batch_no, user.id) focus_task = get_focus_task_for_batch(batch_no, user.id)
if not focus_task: if not focus_task:
raise NotFoundError('Focus task not found') raise NotFoundError('Focus task not found')
return jsonify(serialize_task_summary(focus_task)) return _ok(serialize_task_summary(focus_task))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['POST'])
def workspace_switch_shipping_batch_focus_task(batch_no: str): def workspace_switch_shipping_batch_focus_task(batch_no: str):
@@ -464,7 +476,7 @@ def workspace_switch_shipping_batch_focus_task(batch_no: str):
extra={'actor_user_id': user.id}, extra={'actor_user_id': user.id},
) )
db.session.commit() db.session.commit()
return jsonify({'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}) return _ok({'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)})
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks', methods=['POST'])
def workspace_create_shipping_task(): def workspace_create_shipping_task():
@@ -482,7 +494,7 @@ def workspace_create_shipping_task():
if raw_content: if raw_content:
payload['raw_content'] = raw_content payload['raw_content'] = raw_content
from app.services.shipping_notice import tools as shipping_tools from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.create_task(payload)) return _ok(shipping_tools.create_task(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
def workspace_create_shipping_task_from_notice(): def workspace_create_shipping_task_from_notice():
@@ -514,7 +526,7 @@ def workspace_create_shipping_task_from_notice():
) )
if not intake.accepted: if not intake.accepted:
# 旧 action_buttons 业务调用清零:仅保留 human_options 文案提示,不再下发可点击恢复按钮。 # 旧 action_buttons 业务调用清零:仅保留 human_options 文案提示,不再下发可点击恢复按钮。
return jsonify({'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()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': []})
task = ShippingTask.query.filter_by(task_no=task_id).first() task = ShippingTask.query.filter_by(task_no=task_id).first()
if task: if task:
task.raw_content = intake.text task.raw_content = intake.text
@@ -523,7 +535,7 @@ def workspace_create_shipping_task_from_notice():
db.session.commit() db.session.commit()
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
orchestrator_started = start_task_orchestrator(task_id) orchestrator_started = start_task_orchestrator(task_id)
return jsonify({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}}) return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
def workspace_replace_shipping_task_notice(task_no: str): def workspace_replace_shipping_task_notice(task_no: str):
@@ -598,26 +610,40 @@ def workspace_shipping_task_chat_actions(task_no: str):
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
return jsonify(build_chat_actions_payload(task)) return _ok(build_chat_actions_payload(task))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry', methods=['POST'])
def workspace_retry_shipping_task(task_no: str): def workspace_retry_shipping_task(task_no: str):
"""重试当前任务,适用于超时、解析失败或自动推进中断后的恢复。""" """
重试当前任务,适用于超时、解析失败或自动推进中断后的恢复。
核心逻辑:注入当前用户为操作人,保证 TaskEvent / 统一审计可追溯。
"""
user = _require_user() user = _require_user()
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
from app.services.shipping_notice import tools as shipping_tools from app.services.shipping_notice import tools as shipping_tools
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
payload = {'task_id': task.task_no} payload = {
'task_id': task.task_no,
'operator_id': user.id,
'actor_id': user.id,
'_trusted_user_id': user.id,
'event_source': 'workspace_api',
}
comment = str(data.get('comment') or '').strip() comment = str(data.get('comment') or '').strip()
if comment: if comment:
payload['comment'] = comment payload['comment'] = comment
return jsonify(shipping_tools.retry_task(payload)) return _ok(shipping_tools.retry_task(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-inventory-source', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-inventory-source', methods=['POST'])
def workspace_confirm_shipping_inventory_source(task_no: str): def workspace_confirm_shipping_inventory_source(task_no: str):
"""确认当前任务的库存 RPA 来源,并继续触发库存导出。""" """
确认当前任务的库存 RPA 来源,并继续触发库存导出。
核心逻辑:注入可信操作人 ID,供库存源确认事件与统一审计双写。
"""
user = _require_user() user = _require_user()
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
@@ -627,15 +653,22 @@ def workspace_confirm_shipping_inventory_source(task_no: str):
if not source_code: if not source_code:
raise ValidationError('source_code is required') raise ValidationError('source_code is required')
from app.services.shipping_notice import tools as shipping_tools from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.confirm_inventory_source({ return _ok(shipping_tools.confirm_inventory_source({
'task_id': task.task_no, 'task_id': task.task_no,
'source_code': source_code, 'source_code': source_code,
'operator_id': user.id,
'actor_id': user.id,
'_trusted_user_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']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/submit-decision', methods=['POST'])
def workspace_submit_shipping_decision(task_no: str): def workspace_submit_shipping_decision(task_no: str):
"""以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。""" """
以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。
核心逻辑:注入操作人与 event_source=workspace_api,保证决策审计非匿名。
"""
user = _require_user() user = _require_user()
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
@@ -645,11 +678,20 @@ def workspace_submit_shipping_decision(task_no: str):
if not decision: if not decision:
raise ValidationError('decision is required') raise ValidationError('decision is required')
from app.services.shipping_notice import tools as shipping_tools 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'} 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() comment = str(data.get('comment') or '').strip()
if comment: if comment:
payload['comment'] = comment payload['comment'] = comment
return jsonify(shipping_tools.submit_decision(payload)) return _ok(shipping_tools.submit_decision(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-fields', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-fields', methods=['POST'])
def workspace_update_shipping_notice_fields(task_no: str): def workspace_update_shipping_notice_fields(task_no: str):
@@ -674,7 +716,7 @@ def workspace_update_shipping_notice_fields(task_no: str):
idem = str(data.get('idempotency_key') or '').strip() idem = str(data.get('idempotency_key') or '').strip()
if idem: if idem:
payload['idempotency_key'] = idem payload['idempotency_key'] = idem
return jsonify(shipping_tools.update_notice_fields(payload)) return _ok(shipping_tools.update_notice_fields(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/freeze-order', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/freeze-order', methods=['POST'])
@@ -752,7 +794,7 @@ def workspace_update_shipping_notice_line(task_no: str):
idem = str(data.get('idempotency_key') or '').strip() idem = str(data.get('idempotency_key') or '').strip()
if idem: if idem:
payload['idempotency_key'] = idem payload['idempotency_key'] = idem
return jsonify(shipping_tools.update_notice_line(payload)) return _ok(shipping_tools.update_notice_line(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/field-conflicts', methods=['GET']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/field-conflicts', methods=['GET'])
@@ -836,7 +878,7 @@ def workspace_add_shipping_notice_line(task_no: str):
idem = str(data.get('idempotency_key') or '').strip() idem = str(data.get('idempotency_key') or '').strip()
if idem: if idem:
payload['idempotency_key'] = idem payload['idempotency_key'] = idem
return jsonify(shipping_tools.add_notice_line(payload)) return _ok(shipping_tools.add_notice_line(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/remove-notice-line', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/remove-notice-line', methods=['POST'])
def workspace_remove_shipping_notice_line(task_no: str): def workspace_remove_shipping_notice_line(task_no: str):
@@ -862,29 +904,40 @@ def workspace_remove_shipping_notice_line(task_no: str):
idem = str(data.get('idempotency_key') or '').strip() idem = str(data.get('idempotency_key') or '').strip()
if idem: if idem:
payload['idempotency_key'] = idem payload['idempotency_key'] = idem
return jsonify(shipping_tools.remove_notice_line(payload)) return _ok(shipping_tools.remove_notice_line(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/auto-progress', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/auto-progress', methods=['POST'])
def workspace_auto_progress_shipping_task(task_no: str): def workspace_auto_progress_shipping_task(task_no: str):
"""用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。""" """
用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。
核心逻辑:标记 source=workspace_api 并注入操作人,避免用户触发被记成匿名 system。
"""
user = _require_user() user = _require_user()
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
from app.services.shipping_notice import tools as shipping_tools from app.services.shipping_notice import tools as shipping_tools
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
payload: dict = {'task_id': task.task_no} payload: dict = {
'task_id': task.task_no,
'source': 'workspace_api',
'operator_id': user.id,
'actor_id': user.id,
'_trusted_user_id': user.id,
}
for key in ('lang', 'locale', 'language'): for key in ('lang', 'locale', 'language'):
if data.get(key): if data.get(key):
payload[key] = data[key] payload[key] = data[key]
break break
result = shipping_tools.auto_progress(payload) result = shipping_tools.auto_progress(payload)
if isinstance(result, dict) and result.get('status') == 'ok': if isinstance(result, dict) and result.get('status') == 'ok':
gen_data = result.get('data') gen_data = result.get('data')
if isinstance(gen_data, dict) and gen_data.get('export_file_path'): if isinstance(gen_data, dict) and gen_data.get('export_file_path'):
gen_data = {**gen_data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'} gen_data = {**gen_data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}
result = {**result, 'data': gen_data} result = {**result, 'data': gen_data}
return jsonify(result) return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/match-inventory', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/match-inventory', methods=['POST'])
def workspace_match_shipping_inventory(task_no: str): def workspace_match_shipping_inventory(task_no: str):
@@ -903,7 +956,7 @@ def workspace_match_shipping_inventory(task_no: str):
'event_source': 'workspace_api', 'event_source': 'workspace_api',
}) })
if not isinstance(matched, dict): if not isinstance(matched, dict):
return jsonify(matched) return _ok(matched)
data = matched.get('data') data = matched.get('data')
if isinstance(data, dict) and data.get('export_file_path'): if isinstance(data, dict) and data.get('export_file_path'):
matched = {**matched, 'data': {**data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}} matched = {**matched, 'data': {**data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}}
@@ -926,7 +979,7 @@ def workspace_match_shipping_inventory(task_no: str):
buttons = action_buttons_for_checkpoint(checkpoint) buttons = action_buttons_for_checkpoint(checkpoint)
if buttons: if buttons:
matched['action_buttons'] = buttons matched['action_buttons'] = buttons
return jsonify(matched) return _ok(matched)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST'])
@@ -944,7 +997,7 @@ def workspace_generate_shipping_excel(task_no: str):
data = {} data = {}
result['data'] = data result['data'] = data
data['download_url'] = f'/api/workspace/shipping-tasks/{task.task_no}/export' data['download_url'] = f'/api/workspace/shipping-tasks/{task.task_no}/export'
return jsonify(result) return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
@@ -964,11 +1017,14 @@ def workspace_mark_manual_uploaded(task_no: str):
'task_id': task.task_no, 'task_id': task.task_no,
'mode': 'manual_confirm', 'mode': 'manual_confirm',
'operator_id': user.id, 'operator_id': user.id,
'actor_id': user.id,
'_trusted_user_id': user.id,
'event_source': 'workspace_api',
'evidence_asset_no': data.get('evidence_asset_no'), 'evidence_asset_no': data.get('evidence_asset_no'),
'freight_ref_no': data.get('freight_ref_no'), 'freight_ref_no': data.get('freight_ref_no'),
'artifact_id': data.get('artifact_id'), 'artifact_id': data.get('artifact_id'),
} }
return jsonify(shipping_tools.upload_to_freight(payload)) return _ok(shipping_tools.upload_to_freight(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST'])
@@ -999,6 +1055,7 @@ def workspace_shipping_task_export(task_no: str):
aggregate_id=str(task.task_no), aggregate_id=str(task.task_no),
actor_id=user.id, actor_id=user.id,
task_no=str(task.task_no), task_no=str(task.task_no),
reason_code='excel_downloaded',
metadata={'export': 'excel'}, metadata={'export': 'excel'},
) )
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE) return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
@@ -1176,6 +1233,98 @@ def workspace_get_shipping_order_review_case(case_no: str):
return _ok(payload) return _ok(payload)
@workspace_shipping_notice_bp.route(
'/shipping-notice/order-review-cases/<case_no>/access/version-history',
methods=['POST'],
)
def workspace_audit_shipping_order_review_version_history(case_no: str):
"""
记录打开版本历史抽屉的访问审计。
核心逻辑:先做 Case 可见性校验,再写入 access + 工作台语义事件,禁止仅改本地 UI 状态而不留痕。
"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.fulfillment_audit import record_access_audit, record_fulfillment_audit
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
case = get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin)
run_no = str(case.run.run_no) if getattr(case, 'run', None) is not None else None
record_access_audit(
action='view_order_review_version_history',
aggregate_type='order_review_case',
aggregate_id=str(case.case_no),
actor_id=user.id,
review_case_no=str(case.case_no),
run_no=run_no,
metadata={
'access_action': 'view_order_review_version_history',
'workbench_event': 'review_version_history_viewed',
},
)
record_fulfillment_audit(
event_type='review_version_history_viewed',
aggregate_type='order_review_case',
aggregate_id=str(case.case_no),
action='view_order_review_version_history',
actor_type='user',
actor_id=user.id,
review_case_no=str(case.case_no),
run_no=run_no,
metadata={'panel': 'version_history'},
source='workspace_api',
sensitivity_level='sensitive',
)
db.session.commit()
return _ok({'audited': True, 'case_no': str(case.case_no)})
@workspace_shipping_notice_bp.route(
'/shipping-notice/order-review-cases/<case_no>/access/eligibility-details',
methods=['POST'],
)
def workspace_audit_shipping_order_review_eligibility_details(case_no: str):
"""
记录打开完整建单检查抽屉的访问审计。
核心逻辑:先做 Case 可见性校验,再写入 access + 工作台语义事件。
"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.fulfillment_audit import record_access_audit, record_fulfillment_audit
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
case = get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin)
run_no = str(case.run.run_no) if getattr(case, 'run', None) is not None else None
record_access_audit(
action='view_order_review_eligibility_details',
aggregate_type='order_review_case',
aggregate_id=str(case.case_no),
actor_id=user.id,
review_case_no=str(case.case_no),
run_no=run_no,
metadata={
'access_action': 'view_order_review_eligibility_details',
'workbench_event': 'review_eligibility_details_viewed',
},
)
record_fulfillment_audit(
event_type='review_eligibility_details_viewed',
aggregate_type='order_review_case',
aggregate_id=str(case.case_no),
action='view_order_review_eligibility_details',
actor_type='user',
actor_id=user.id,
review_case_no=str(case.case_no),
run_no=run_no,
metadata={'panel': 'eligibility_details'},
source='workspace_api',
sensitivity_level='sensitive',
)
db.session.commit()
return _ok({'audited': True, 'case_no': str(case.case_no)})
def _review_draft_payload( def _review_draft_payload(
*, *,
user_id: int, user_id: int,
@@ -1399,13 +1548,160 @@ def workspace_keep_shipping_order_review_inventory_routing_manual(case_no: str,
return _ok(result) return _ok(result)
@workspace_shipping_notice_bp.route(
'/shipping-notice/order-review-cases/<case_no>/customer-resolution/retry',
methods=['POST'],
)
def workspace_retry_shipping_order_review_customer_resolution(case_no: str):
"""
重新识别客户(不重解析 PDF),供复核工作台「重新识别客户」按钮调用。
"""
user = _require_user()
from app.services.shipping_notice.order_review_customer_service import (
retry_review_case_customer_resolution,
)
return _ok(retry_review_case_customer_resolution(user_id=user.id, case_no=case_no))
@workspace_shipping_notice_bp.route(
'/shipping-notice/order-review-cases/<case_no>/customer-resolution/confirm',
methods=['POST'],
)
def workspace_confirm_shipping_order_review_customer(case_no: str):
"""
建单前确认标准客户;写 Bill-to match 并刷新建单资格。
"""
user = _require_user()
data = request.get_json(silent=True) or {}
try:
customer_id = int(data.get('customer_id'))
except (TypeError, ValueError) as exc:
raise ValidationError(
'Customer id is required',
code='SHIPPING.CUSTOMER_CONFIRMATION_CUSTOMER_REQUIRED',
details={'field': 'customer_id'},
) from exc
from app.services.shipping_notice.order_review_customer_service import (
confirm_review_case_customer,
)
return _ok(confirm_review_case_customer(
user_id=user.id,
case_no=case_no,
customer_id=customer_id,
reason=str(data.get('reason') or '').strip() or None,
))
@workspace_shipping_notice_bp.route(
'/shipping-notice/order-review-cases/<case_no>/duplicate-refresh',
methods=['POST'],
)
def workspace_refresh_shipping_order_review_duplicate(case_no: str):
"""重新检测建单前重复订单(复核工作台)。"""
user = _require_user()
from app.services.shipping_notice.order_review_duplicate_service import (
refresh_review_case_duplicate,
)
return _ok(refresh_review_case_duplicate(user_id=user.id, case_no=case_no))
@workspace_shipping_notice_bp.route(
'/shipping-notice/order-review-cases/<case_no>/duplicate-resolution',
methods=['POST'],
)
def workspace_resolve_shipping_order_review_duplicate(case_no: str):
"""
裁决建单前重复订单:open_existing | create_revision | force_create。
Body: action, target_task_no?, reason?
"""
user = _require_user()
data = request.get_json(silent=True) or {}
from app.services.shipping_notice.order_review_duplicate_service import (
resolve_review_case_duplicate,
)
return _ok(resolve_review_case_duplicate(
user_id=user.id,
case_no=case_no,
action=str(data.get('action') or '').strip(),
target_task_no=str(data.get('target_task_no') or '').strip() or None,
reason=str(data.get('reason') or '').strip() or None,
))
@workspace_shipping_notice_bp.route(
'/shipping-notice/order-review-cases/<case_no>/field-conflicts',
methods=['GET'],
)
def workspace_list_shipping_order_review_field_conflicts(case_no: str):
"""列出建单前 Candidate 字段冲突(复核工作台集中裁决区)。"""
user = _require_user()
from app.services.shipping_notice.order_review_field_conflict_service import (
list_review_case_field_conflicts,
)
return _ok(list_review_case_field_conflicts(user_id=user.id, case_no=case_no))
@workspace_shipping_notice_bp.route(
'/shipping-notice/order-review-cases/<case_no>/field-conflicts/<path:conflict_key>/resolve',
methods=['POST'],
)
def workspace_resolve_shipping_order_review_field_conflict(case_no: str, conflict_key: str):
"""
裁决建单前字段冲突:写入 Draft 人工值并清除 Candidate 冲突项。
Body: resolution=adopt_option|custom, option_index?, custom_value?,
expected_draft_version, reason?
"""
user = _require_user()
data = request.get_json(silent=True) or {}
from app.services.shipping_notice.order_review_field_conflict_service import (
resolve_review_case_field_conflict,
)
option_index = data.get('option_index')
if option_index is not None:
try:
option_index = int(option_index)
except (TypeError, ValueError) as exc:
raise ValidationError(
'option_index is invalid',
code='SHIPPING.REVIEW_FIELD_CONFLICT_OPTION_INVALID',
details={'field': 'option_index'},
) from exc
result = resolve_review_case_field_conflict(
user_id=user.id,
case_no=case_no,
conflict_key=conflict_key,
resolution=str(data.get('resolution') or '').strip(),
option_index=option_index,
custom_value=data.get('custom_value'),
expected_draft_version=data.get('expected_draft_version'),
reason=str(data.get('reason') or '').strip() or None,
)
db.session.commit()
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/confirm', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/confirm', methods=['POST'])
def workspace_confirm_shipping_order_review_case(case_no: str): def workspace_confirm_shipping_order_review_case(case_no: str):
"""确认一份 PDF 草稿并独立建单;提交后复用 auto_progress 自动推进。""" """
确认一份 PDF 草稿并独立建单;与确认同事务入队自动推进 Job。
契约:HTTP 200 + confirm_ok 仅表示建单成功;自动推进看 confirm_outcome /
auto_progress.status(enqueue_failed 等为可恢复失败,不是建单回滚)。
"""
user = _require_user() user = _require_user()
from app.services.shipping_notice.order_review_confirmation_service import ( from app.services.shipping_notice.order_review_confirmation_service import (
confirm_review_case, confirm_review_case,
trigger_auto_progress_after_review_confirm, finalize_sync_auto_progress_after_commit,
resolve_confirm_outcome,
schedule_auto_progress_after_review_confirm,
) )
payload = _review_draft_payload( payload = _review_draft_payload(
@@ -1416,24 +1712,42 @@ def workspace_confirm_shipping_order_review_case(case_no: str):
case_no=case_no, case_no=case_no,
expected_draft_version=payload.get('expected_draft_version'), expected_draft_version=payload.get('expected_draft_version'),
idempotency_key=request.headers.get('Idempotency-Key') or payload.get('idempotency_key'), idempotency_key=request.headers.get('Idempotency-Key') or payload.get('idempotency_key'),
warning_acknowledgements=payload.get('warning_acknowledgements'),
confirm_note=payload.get('confirm_note'), confirm_note=payload.get('confirm_note'),
warning_acknowledgements=payload.get('warning_acknowledgements'),
) )
db.session.commit() # [STEP] 与建单同事务写入 shipping_notice_run,避免「已建单、推进失败不可恢复」。
# [STEP] 事务提交后再走与 STP 直通相同的 auto_progress,避免未提交任务被推进。 progress = schedule_auto_progress_after_review_confirm(
progress = trigger_auto_progress_after_review_confirm(
task_no=result.get('task_no'), task_no=result.get('task_no'),
idempotent_replay=bool(result.get('idempotent_replay')), idempotent_replay=bool(result.get('idempotent_replay')),
created_by_id=int(user.id),
commit=False,
) )
if progress is not None: db.session.commit()
# [STEP] sync 执行失败不得变成 HTTP 500,须返回「确认成功 + 推进态」字段。
progress = finalize_sync_auto_progress_after_commit(progress)
result = dict(result) result = dict(result)
result.pop('trigger_auto_progress', None) result.pop('trigger_auto_progress', None)
result['confirm_ok'] = True
if progress is None:
result['auto_progress_started'] = False
result['auto_progress'] = {
'status': 'not_scheduled',
'message': '无需调度自动推进,或任务已离开待推进态',
}
else:
result['auto_progress_started'] = bool(progress.get('auto_progress_started'))
result['auto_progress'] = { result['auto_progress'] = {
'status': progress.get('status'), 'status': progress.get('status'),
'message': progress.get('message'), 'message': progress.get('message'),
'enqueue_result': progress.get('enqueue_result'),
'checkpoint': progress.get('checkpoint'), 'checkpoint': progress.get('checkpoint'),
} }
result['auto_progress_started'] = True result['confirm_outcome'] = resolve_confirm_outcome(
{
'status': (result.get('auto_progress') or {}).get('status'),
'auto_progress_started': result.get('auto_progress_started'),
}
)
return _ok(result) return _ok(result)
@@ -1523,12 +1837,24 @@ def workspace_list_shipping_order_review_evidence(case_no: str):
from app.services.shipping_notice.order_review_evidence_service import list_case_evidence from app.services.shipping_notice.order_review_evidence_service import list_case_evidence
payload = list_case_evidence(user_id=user.id, case_no=case_no) payload = list_case_evidence(user_id=user.id, case_no=case_no)
quality_counts: dict[str, int] = {}
for item in payload.get('items') or []:
if not isinstance(item, dict):
continue
key = str(item.get('highlight_quality') or 'unavailable')
quality_counts[key] = quality_counts.get(key, 0) + 1
record_access_audit( record_access_audit(
action='view_order_review_evidence_list', action='view_order_review_evidence_list',
aggregate_type='order_review_case', aggregate_type='order_review_case',
aggregate_id=str(case_no), aggregate_id=str(case_no),
actor_id=user.id, actor_id=user.id,
review_case_no=str(case_no), review_case_no=str(case_no),
metadata={
'access_action': 'view_order_review_evidence_list',
'workbench_event': 'review_evidence_list_viewed',
'item_count': len(payload.get('items') or []),
'highlight_quality_counts': quality_counts,
},
) )
return _ok(payload) return _ok(payload)
@@ -1538,7 +1864,10 @@ def workspace_get_shipping_order_review_evidence(case_no: str, evidence_id: str)
"""读取当前用户的一条字段证据,用于问题导航;evidence_id 不可跨 Case 使用;访问留痕。""" """读取当前用户的一条字段证据,用于问题导航;evidence_id 不可跨 Case 使用;访问留痕。"""
user = _require_user() user = _require_user()
from app.services.shipping_notice.fulfillment_audit import record_access_audit from app.services.shipping_notice.fulfillment_audit import record_access_audit
from app.services.shipping_notice.order_review_evidence_service import get_case_evidence from app.services.shipping_notice.order_review_evidence_service import (
build_highlight_audit_summary,
get_case_evidence,
)
payload = get_case_evidence(user_id=user.id, case_no=case_no, evidence_id=evidence_id) payload = get_case_evidence(user_id=user.id, case_no=case_no, evidence_id=evidence_id)
record_access_audit( record_access_audit(
@@ -1547,11 +1876,107 @@ def workspace_get_shipping_order_review_evidence(case_no: str, evidence_id: str)
aggregate_id=str(case_no), aggregate_id=str(case_no),
actor_id=user.id, actor_id=user.id,
review_case_no=str(case_no), review_case_no=str(case_no),
metadata={'evidence_id': str(evidence_id)[:64]}, metadata={
'access_action': 'view_order_review_evidence',
'workbench_event': 'review_evidence_focused',
'highlight': build_highlight_audit_summary(payload),
},
) )
return _ok(payload) return _ok(payload)
@workspace_shipping_notice_bp.route(
'/shipping-notice/order-review-cases/<case_no>/evidence/<evidence_id>/highlight-diagnostic',
methods=['POST'],
)
def workspace_view_shipping_order_review_highlight_diagnostic(case_no: str, evidence_id: str):
"""
记录坐标诊断面板查看审计;不返回 PDF 正文,不改变业务状态。
核心逻辑:复用 get_case_evidence 鉴权;写入 review_highlight_diagnostic_viewed。
"""
user = _require_user()
from app.services.shipping_notice.fulfillment_audit import record_access_audit
from app.services.shipping_notice.order_review_evidence_service import (
build_highlight_audit_summary,
get_case_evidence,
)
payload = get_case_evidence(user_id=user.id, case_no=case_no, evidence_id=evidence_id)
summary = build_highlight_audit_summary(payload)
record_access_audit(
action='view_order_review_highlight_diagnostic',
aggregate_type='order_review_case',
aggregate_id=str(case_no),
actor_id=user.id,
review_case_no=str(case_no),
metadata={
'access_action': 'view_order_review_highlight_diagnostic',
'workbench_event': 'review_highlight_diagnostic_viewed',
'highlight': summary,
},
)
return _ok({'case_no': case_no, 'highlight': summary})
@workspace_shipping_notice_bp.route(
'/shipping-notice/order-review-cases/<case_no>/field-locate',
methods=['POST'],
)
def workspace_attempt_shipping_order_review_field_locate(case_no: str):
"""
记录字段「定位原文」点击审计(含无 evidence 的红色诊断入口)。
核心逻辑:鉴权 Case owner;不返回 PDF 正文;写入 review_field_locate_attempted。
"""
user = _require_user()
from app.services.shipping_notice.fulfillment_audit import record_access_audit
from app.services.shipping_notice.order_review_service import get_user_review_case
body = request.get_json(silent=True) or {}
field_id = str(body.get('field_id') or '').strip()[:128]
if not field_id:
from app.core.errors import ValidationError
raise ValidationError('field_id is required')
# 鉴权:确认 Case 归属当前用户
get_user_review_case(user_id=user.id, case_no=case_no)
line_index = body.get('line_index')
try:
line_index = int(line_index) if line_index is not None else None
except (TypeError, ValueError):
line_index = None
quality = str(body.get('highlight_quality') or 'unavailable').strip()[:32]
evidence_id = str(body.get('evidence_id') or '').strip()[:160] or None
has_evidence = bool(body.get('has_evidence'))
pdf_located = bool(body.get('pdf_located'))
issue_codes = body.get('coordinate_issue_codes') if isinstance(body.get('coordinate_issue_codes'), list) else []
record_access_audit(
action='attempt_order_review_field_locate',
aggregate_type='order_review_case',
aggregate_id=str(case_no),
actor_id=user.id,
review_case_no=str(case_no),
metadata={
'access_action': 'attempt_order_review_field_locate',
'workbench_event': 'review_field_locate_attempted',
'field_id': field_id,
'line_index': line_index,
'highlight_quality': quality,
'has_evidence': has_evidence,
'evidence_id': evidence_id,
'pdf_located': pdf_located,
'coordinate_issue_codes': [str(code)[:64] for code in issue_codes[:20]],
},
)
return _ok({
'case_no': case_no,
'field_id': field_id,
'highlight_quality': quality,
'has_evidence': has_evidence,
'pdf_located': pdf_located,
})
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/llm-suggestions', methods=['GET']) @workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/llm-suggestions', methods=['GET'])
def workspace_list_shipping_order_review_llm_suggestions(case_no: str): def workspace_list_shipping_order_review_llm_suggestions(case_no: str):
"""列出 Case 下 Dify 最小证据建议记录。""" """列出 Case 下 Dify 最小证据建议记录。"""
@@ -1621,7 +2046,11 @@ def workspace_preview_shipping_order_review_document(case_no: str):
aggregate_id=str(case_no), aggregate_id=str(case_no),
actor_id=user.id, actor_id=user.id,
review_case_no=str(case_no), review_case_no=str(case_no),
metadata={'preview': 'pdf'}, metadata={
'preview': 'pdf',
'access_action': 'preview_order_review_document',
'workbench_event': 'sensitive_evidence_viewed',
},
) )
return send_file( return send_file(
BytesIO(content), mimetype='application/pdf', as_attachment=False, download_name=filename, BytesIO(content), mimetype='application/pdf', as_attachment=False, download_name=filename,
@@ -2199,4 +2628,4 @@ def workspace_retry_shipping_batch_pending(batch_no: str):
if not batch: if not batch:
raise NotFoundError('Not found') raise NotFoundError('Not found')
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
return jsonify(retry_batch_pending_tasks(batch.batch_no)) return _ok(retry_batch_pending_tasks(batch.batch_no))
+4 -3
View File
@@ -318,9 +318,10 @@ class Config:
'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN', 'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN',
'shipment_{task_no}_{ts}.xlsx', 'shipment_{task_no}_{ts}.xlsx',
) )
# Phase 设计禁止自动货代上传:强制 False,忽略环境变量布尔值(仍可读 env 仅供运维对照)。 # 货代上传 RPA:默认关闭(生产安全);须环境变量显式 true 才自动触发上传。
_SHIPPING_NOTICE_AUTO_UPLOAD_ENV = os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'false') SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = (
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = False os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'false').lower() == 'true'
)
# Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback) # Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true' SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true'
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3') SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
@@ -160,6 +160,7 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
'issues': ['shipping_document_layout_input_unsupported'], 'issues': ['shipping_document_layout_input_unsupported'],
} }
if complete_layout_version(version.id, lease_token=lease, snapshot=snapshot): if complete_layout_version(version.id, lease_token=lease, snapshot=snapshot):
final_status = str(db.session.get(ShippingDocumentLayoutVersion, version.id).status or 'failed')
record_layout_document_progress(document_id=int(document.id), event_code='layout_parsing_completed') record_layout_document_progress(document_id=int(document.id), event_code='layout_parsing_completed')
_layout_job_audit( _layout_job_audit(
event_type='document_layout_job_completed', event_type='document_layout_job_completed',
@@ -172,7 +173,10 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
'status': str(snapshot.get('status') or 'failed'), 'status': str(snapshot.get('status') or 'failed'),
'timings': {key: int(value) for key, value in timings.items()}, 'timings': {key: int(value) for key, value in timings.items()},
}, },
message='文档版面解析完成', owned_attempt=owned_attempt, message=(
'文档版面解析完成' if final_status in {'ready', 'needs_review'}
else '文档版面解析失败'
), owned_attempt=owned_attempt,
) )
from app.services.shipping_notice.order_extraction_run_service import resume_runs_waiting_for_layout from app.services.shipping_notice.order_extraction_run_service import resume_runs_waiting_for_layout
@@ -4,8 +4,9 @@ backend/app/jobs/handlers/shipping_process_gate.py
用途:消费门禁恢复 Attempt Job,领取租约并执行 process_gate_executor。 用途:消费门禁恢复 Attempt Job,领取租约并执行 process_gate_executor。
依赖:JobContext、process_gate_job_service、process_gate_service、jobs.queue finish/fail、 依赖:JobContext、process_gate_job_service、process_gate_service、jobs.queue finish/fail、
process_gate_error_sanitizer。 process_gate_error_sanitizer。
逻辑:由 shipping worker 领取;技术失败按 Attempt 累计次数 + 5s/30s/120s 退避重新入队; 逻辑:由 shipping worker 领取;技术失败按该 Attempt 下 failed Job 累计次数 + 5s/30s/120s 退避重新入队;
次数耗尽时 fail_job 并 complete_gate_attempt(failed_terminal); 次数耗尽时 fail_job 并 complete_gate_attempt(failed_terminal);
不修改 input_snapshot_json,以保持 input_snapshot_hash 与正文一致;
waiting_external 先结束当前 Job 再延迟入队新 Job; waiting_external 先结束当前 Job 再延迟入队新 Job;
healthcheck_probe 载荷用于部署探针,不依赖真实 Attempt。 healthcheck_probe 载荷用于部署探针,不依赖真实 Attempt。
""" """
@@ -13,6 +14,7 @@ backend/app/jobs/handlers/shipping_process_gate.py
from __future__ import annotations from __future__ import annotations
from flask import current_app from flask import current_app
from sqlalchemy import or_
from app import db from app import db
from app.jobs.context import JobContext from app.jobs.context import JobContext
@@ -22,33 +24,57 @@ from app.jobs.types import JobType
from app.models import Job, ShippingProcessGate, ShippingProcessGateAttempt from app.models import Job, ShippingProcessGate, ShippingProcessGateAttempt
from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text
from app.services.shipping_notice.process_gate_job_service import ( from app.services.shipping_notice.process_gate_job_service import (
SHIPPING_PROCESS_GATE_JOB_DOMAIN,
claim_and_run_gate_attempt, claim_and_run_gate_attempt,
enqueue_gate_attempt_job, enqueue_gate_attempt_job,
schedule_waiting_external_poll,
) )
from app.services.shipping_notice.process_gate_service import complete_gate_attempt from app.services.shipping_notice.process_gate_service import complete_gate_attempt
# 方案规定的技术重试退避(秒):第 1/2/3 次失败后延迟。 # 方案规定的技术重试退避(秒):第 1/2/3 次失败后延迟。
_TECHNICAL_RETRY_BACKOFF_SECONDS: tuple[int, ...] = (5, 30, 120) _TECHNICAL_RETRY_BACKOFF_SECONDS: tuple[int, ...] = (5, 30, 120)
_TECH_RETRY_KEY = 'technical_retry_count'
def _technical_retry_count(attempt: ShippingProcessGateAttempt) -> int: def _count_failed_technical_jobs(attempt_id: int) -> int:
"""读取 Attempt 上累计的技术失败次数(跨 force_new Job 保留)。""" """
snap = attempt.input_snapshot_json if isinstance(attempt.input_snapshot_json, dict) else {} 统计某 Attempt 已失败的技术 Job 数(含 force_new 的 business_ref 变体)。
try:
return max(int(snap.get(_TECH_RETRY_KEY) or 0), 0) 核心逻辑:按 business_ref=`attempt:{id}` 或 `attempt:{id}:...` 过滤 failed Job,
except (TypeError, ValueError): 作为跨 Job 累计重试次数,避免写入 input_snapshot 破坏 Hash。
return 0
Args:
attempt_id: ShippingProcessGateAttempt 主键。
Returns:
已处于 failed 状态的相关 Job 数量。
"""
prefix = f'attempt:{int(attempt_id)}'
return (
Job.query
.filter(
Job.domain == SHIPPING_PROCESS_GATE_JOB_DOMAIN,
Job.job_type == JobType.SHIPPING_PROCESS_GATE.value,
Job.status == 'failed',
or_(
Job.business_ref == prefix,
Job.business_ref.like(f'{prefix}:%'),
),
)
.count()
)
def _bump_technical_retry_count(attempt: ShippingProcessGateAttempt) -> int: def _strip_legacy_retry_count_from_input_snapshot(attempt: ShippingProcessGateAttempt) -> None:
"""递增并回写技术失败次数,返回递增后的值。""" """
snap = dict(attempt.input_snapshot_json) if isinstance(attempt.input_snapshot_json, dict) else {} 清理历史误写入 input_snapshot 的 technical_retry_count,避免污染业务输入快照。
next_count = _technical_retry_count(attempt) + 1
snap[_TECH_RETRY_KEY] = next_count 核心逻辑:若键存在则删除;不重算 Hash(Hash 应对创建时的业务快照;遗留键本身已破坏一致性,
attempt.input_snapshot_json = snap 删除后正文与创建 Hash 仍可能不一致,但后续不再写入新的运行元数据)。
return next_count """
snap = attempt.input_snapshot_json
if not isinstance(snap, dict) or 'technical_retry_count' not in snap:
return
cleaned = {k: v for k, v in snap.items() if k != 'technical_retry_count'}
attempt.input_snapshot_json = cleaned
def _finalize_attempt_after_retry_exhausted( def _finalize_attempt_after_retry_exhausted(
@@ -68,8 +94,13 @@ def _finalize_attempt_after_retry_exhausted(
complete_gate_attempt( complete_gate_attempt(
attempt_id=int(attempt.id), attempt_id=int(attempt.id),
outcome='failed_terminal', outcome='failed_terminal',
blocking_reason_code='technical_failure', # 与 error_explainability_contract / PROCESS_GATE_BLOCKING 对齐,禁止写未登记的 technical_failure
blocking_reason_json={'message': safe, 'technical_retry_exhausted': True}, blocking_reason_code='technical_retry_exhausted',
blocking_reason_json={
'reason_code': 'technical_retry_exhausted',
'message': safe,
'technical_retry_exhausted': True,
},
effective_result_json={'findings': [], 'error': 'technical_retry_exhausted'}, effective_result_json={'findings': [], 'error': 'technical_retry_exhausted'},
output_snapshot={'error': safe, 'technical_retry_exhausted': True}, output_snapshot={'error': safe, 'technical_retry_exhausted': True},
error_code='TECHNICAL_RETRY_EXHAUSTED', error_code='TECHNICAL_RETRY_EXHAUSTED',
@@ -132,15 +163,16 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
db.session.commit() db.session.commit()
return return
# [STEP] 技术失败:按 Attempt 累计次数判定,禁止因 force_new Job.attempts=0 无限重试。 # [STEP] 技术失败:按 Attempt 下 failed Job 累计判定,禁止因 force_new 无限重试。
max_attempts = max( max_attempts = max(
int(current_app.config.get('SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES', 3) or 3), int(current_app.config.get('SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES', 3) or 3),
1, 1,
) )
retries_done = _technical_retry_count(attempt) if attempt is not None else max_attempts failed_already = _count_failed_technical_jobs(attempt_id) if attempt is not None else max_attempts
safe_error = sanitize_gate_error_text(exc, max_len=1000) or 'technical_failure' safe_error = sanitize_gate_error_text(exc, max_len=1000) or 'technical_failure'
if attempt is not None and retries_done + 1 < max_attempts: # 本次 fail_job 后累计 = failed_already + 1;未达上限则退避重入队。
delay_idx = min(retries_done, len(_TECHNICAL_RETRY_BACKOFF_SECONDS) - 1) if attempt is not None and failed_already + 1 < max_attempts:
delay_idx = min(failed_already, len(_TECHNICAL_RETRY_BACKOFF_SECONDS) - 1)
delay = _TECHNICAL_RETRY_BACKOFF_SECONDS[delay_idx] delay = _TECHNICAL_RETRY_BACKOFF_SECONDS[delay_idx]
fail_job( fail_job(
job.id, job.id,
@@ -148,7 +180,7 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
retryable=False, retryable=False,
owned_attempt=owned_attempt, owned_attempt=owned_attempt,
) )
_bump_technical_retry_count(attempt) _strip_legacy_retry_count_from_input_snapshot(attempt)
attempt.status = 'queued' attempt.status = 'queued'
attempt.job_id = None attempt.job_id = None
attempt.worker_id = None attempt.worker_id = None
@@ -167,16 +199,9 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
fail_job(job.id, error=safe_error, retryable=False, owned_attempt=owned_attempt) fail_job(job.id, error=safe_error, retryable=False, owned_attempt=owned_attempt)
if attempt is not None: if attempt is not None:
_strip_legacy_retry_count_from_input_snapshot(attempt)
_finalize_attempt_after_retry_exhausted(attempt=attempt, exc=exc) _finalize_attempt_after_retry_exhausted(attempt=attempt, exc=exc)
db.session.commit() db.session.commit()
return return
finish_job(job.id, result=result, owned_attempt=owned_attempt) finish_job(job.id, result=result if isinstance(result, dict) else {'status': 'ok'}, owned_attempt=owned_attempt)
# [STEP] 成功落入 waiting_external:调度下一次 poll Attempt(含超时判定)。
if str((result or {}).get('gate_status') or '') == 'waiting_external':
schedule_waiting_external_poll(
attempt_id=int(attempt_id),
gate_code=str((result or {}).get('gate_code') or ''),
)
db.session.commit()
+2
View File
@@ -101,6 +101,7 @@ from app.models.shipping_document_profile_quality import (
ShippingDocumentProfileTestSuite, ShippingDocumentProfileTestSuite,
) )
from app.models.shipping_document_profile_auto_freeze import ShippingDocumentProfileAutoFreezeQualification from app.models.shipping_document_profile_auto_freeze import ShippingDocumentProfileAutoFreezeQualification
from app.models.shipping_order_candidate_qualification import ShippingOrderCandidateQualification
from app.models.shipping_freight_cancellation import ShippingFreightCancellation from app.models.shipping_freight_cancellation import ShippingFreightCancellation
from app.models.shipping_document_layout import ShippingDocumentLayoutVersion from app.models.shipping_document_layout import ShippingDocumentLayoutVersion
from app.models.shipping_inventory_config import ( from app.models.shipping_inventory_config import (
@@ -223,6 +224,7 @@ __all__ = [
'ShippingDocumentProfileTestSample', 'ShippingDocumentProfileTestSample',
'ShippingDocumentProfileTestRun', 'ShippingDocumentProfileTestRun',
'ShippingDocumentProfileAutoFreezeQualification', 'ShippingDocumentProfileAutoFreezeQualification',
'ShippingOrderCandidateQualification',
'ShippingFreightCancellation', 'ShippingFreightCancellation',
'ShippingDocumentLayoutVersion', 'ShippingDocumentLayoutVersion',
'ShippingCustomer', 'ShippingCustomer',
@@ -0,0 +1,70 @@
"""
models/shipping_order_candidate_qualification.py
用途:持久化 Candidate 级统一自动建单资格评估快照(追加式历史)。
依赖:SQLAlchemy Base、shipping_notice_candidates / shipping_order_extraction_runs / users。
逻辑:每次评估追加一行;is_current 标记最新;模板质量信息仅出现在 parser_trace_json。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import Boolean, CheckConstraint, DateTime, Float, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingOrderCandidateQualification(Base):
"""Candidate 自动建单资格快照;同一 Candidate 可有多条历史评估。"""
__tablename__ = 'shipping_order_candidate_qualifications'
__table_args__ = (
UniqueConstraint(
'candidate_id',
'evaluation_seq',
name='ix_ship_order_cand_qual_candidate_seq',
),
CheckConstraint(
"status IN ('eligible', 'review_required', 'blocked', 'rejected')",
name='ck_shipping_order_candidate_qualifications_status',
),
Index(
'ix_ship_order_cand_qual_status_evaluated',
'status', 'evaluated_at',
),
Index(
'ix_ship_order_cand_qual_candidate_current',
'candidate_id', 'is_current',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
candidate_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_candidates.id'),
nullable=False,
index=True,
)
run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_extraction_runs.id'),
nullable=True,
index=True,
)
evaluation_seq: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
is_current: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
qualification_score: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)
gate_results_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
blocking_reason_codes_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
parser_trace_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
evidence_snapshot_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
evaluator_version: Mapped[str] = mapped_column(String(64), nullable=False)
evaluated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
evaluated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
request_id: Mapped[Optional[str]] = mapped_column(String(64), 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,
)
+19 -10
View File
@@ -134,6 +134,23 @@ class DifyService:
return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。" return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。"
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。" return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。"
@staticmethod
def _friendly_stream_request_failure_message(error: requests.exceptions.RequestException) -> str:
"""
将对话连接异常转换成可安全展示的业务提示。
Args:
error: requests 抛出的上游连接异常;原始内容只用于服务端日志。
Returns:
不包含服务名称、地址、密钥或异常正文的用户提示。
"""
if isinstance(error, requests.exceptions.ReadTimeout):
return "回答生成时间较长,本次请求未能完成,请稍后重试。"
if isinstance(error, requests.exceptions.ConnectTimeout):
return "当前服务连接超时,请稍后重试。"
return "当前服务暂时无法完成回答,请稍后重试。"
@staticmethod @staticmethod
def _merge_stream_answer_text( def _merge_stream_answer_text(
streamed_text: str, streamed_text: str,
@@ -1187,20 +1204,12 @@ class DifyService:
if not is_timeout and attempt < max_retries: if not is_timeout and attempt < max_retries:
time.sleep(attempt * 2) time.sleep(attempt * 2)
continue continue
if isinstance(e, requests.exceptions.ReadTimeout): message = DifyService._friendly_stream_request_failure_message(e)
message = (
f"Dify 在 {int(getattr(Config, 'DIFY_CHAT_READ_TIMEOUT_SECONDS', 30) or 30)} 秒内没有返回响应。"
"请检查 Dify 应用地址/API Key、Chatflow 是否发布,以及 Dify 服务是否能正常执行。"
)
elif isinstance(e, requests.exceptions.ConnectTimeout):
message = "连接 Dify 超时,请检查 Dify API Base URL 和网络连通性。"
else:
message = str(e)
# [STEP 4] 错误事件与持久化对象必须是同一个 dict,确保 chat_log_id 能继续传给 relay/领域 Handler。 # [STEP 4] 错误事件与持久化对象必须是同一个 dict,确保 chat_log_id 能继续传给 relay/领域 Handler。
error_event = { error_event = {
'event': 'error', 'event': 'error',
'conversation_id': normalized_conversation_id, 'conversation_id': normalized_conversation_id,
'answer': f"[Error: {message}]", 'answer': message,
'message': message, 'message': message,
'metadata': {}, 'metadata': {},
} }
@@ -2,16 +2,22 @@
services/shipping_notice/attachment_integrity.py services/shipping_notice/attachment_integrity.py
用途:判定 Intake 的 EML/附件解析是否完整,供建批门禁与重试资格复用。 用途:判定 Intake 的 EML/附件解析是否完整,供建批门禁与重试资格复用。
依赖:仅标准库(与 structured_result_json / parse_summary 形状对齐)。 依赖:error_explainability_contract(warning→稳定原因码)、标准库。
逻辑:由 batch_from_intakes、intake_service.retry_intake_parse 调用; 逻辑:由 batch_from_intakes、intake_service.retry_intake_parse 调用;
BLOCKING_WARNING_PREFIXES 与前端 shippingNoticeAttachmentIntegrity.ts 契约一致 BLOCKING_WARNING_PREFIXES 与前端 shippingNoticeAttachmentIntegrity.ts 契约一致
(由 tests 校验两端前缀集合)。 (由 tests 校验两端前缀集合);可投影 attachment_reason_codes 供审计/UI。
""" """
from __future__ import annotations from __future__ import annotations
from typing import Any from typing import Any
from app.services.shipping_notice.error_explainability_contract import (
build_explainability_reason,
map_attachment_warning_to_reason_code,
primary_attachment_reason_from_warnings,
)
# 顶层 / 附件行 warnings 前缀:出现任一即视为不完整(与前端门禁契约对齐) # 顶层 / 附件行 warnings 前缀:出现任一即视为不完整(与前端门禁契约对齐)
BLOCKING_WARNING_PREFIXES: tuple[str, ...] = ( BLOCKING_WARNING_PREFIXES: tuple[str, ...] = (
'eml_nesting_depth_exceeded:', 'eml_nesting_depth_exceeded:',
@@ -86,3 +92,98 @@ def is_attachment_parse_incomplete(structured: dict[str, Any] | None) -> bool:
return True return True
return False return False
def collect_attachment_reason_codes(structured: dict[str, Any] | None) -> list[str]:
"""
从 structured_result / parse_summary 收集已映射的附件稳定原因码(去重保序)。
Args:
structured: Intake structured_result_json 或 parse_summary。
Returns:
稳定原因码列表;无映射时为空。
"""
if not isinstance(structured, dict):
return []
codes: list[str] = []
seen: set[str] = set()
def _push(warning: str) -> None:
code = map_attachment_warning_to_reason_code(warning)
if code and code not in seen:
seen.add(code)
codes.append(code)
for item in structured.get('warnings') or []:
_push(str(item or ''))
for row in structured.get('attachments') or []:
if not isinstance(row, dict):
continue
for item in row.get('warnings') or []:
_push(str(item or ''))
return codes
def primary_attachment_reason_code(structured: dict[str, Any] | None) -> str | None:
"""
取附件解析的主稳定原因码(首个可映射 warning)。
Args:
structured: Intake structured_result_json 或 parse_summary。
Returns:
稳定原因码或 None。
"""
codes = collect_attachment_reason_codes(structured)
if codes:
return codes[0]
if not isinstance(structured, dict):
return None
return primary_attachment_reason_from_warnings(list(structured.get('warnings') or []))
def attachment_incomplete_error_details(
structured: dict[str, Any] | None,
*,
intake_nos: list[str] | None = None,
reason: str | None = None,
extra: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
构造 INTAKE_ATTACHMENTS_INCOMPLETE 的可解释 details。
核心逻辑:从 structured 投影 attachment_reason_codes 与统一 explainability;
无 warning 映射时回落 attachment_corrupted,保证调用方始终带稳定 reason_code。
Args:
structured: Intake structured_result_json / parse_summary。
intake_nos: 相关 Intake 编号。
reason: 调用点细分原因(如 no_eligible_selected_attachment)。
extra: 额外业务事实(如 missing_attachment_keys)。
Returns:
供 ConflictError.details 使用的字典。
"""
codes = collect_attachment_reason_codes(structured)
primary = primary_attachment_reason_code(structured) or 'attachment_corrupted'
details: dict[str, Any] = {
'reason_code': primary,
'attachment_reason_codes': codes,
'explainability': build_explainability_reason(
reason_code=primary,
details={
'attachment_reason_codes': codes,
**({'reason': reason} if reason else {}),
},
),
}
if intake_nos:
details['intake_nos'] = [str(item) for item in intake_nos if str(item or '').strip()]
if reason:
details['reason'] = str(reason)[:128]
if isinstance(extra, dict):
for key, value in extra.items():
if value is not None and key not in details:
details[key] = value
return details
@@ -6,6 +6,8 @@ services/shipping_notice/audit_query_service.py
progress_audit_contract、SQLAlchemy。 progress_audit_contract、SQLAlchemy。
逻辑:由 admin API 调用;列表/详情/导出/关联链均做管理员访问审计(失败阻断查询); 逻辑:由 admin API 调用;列表/详情/导出/关联链均做管理员访问审计(失败阻断查询);
敏感 before/after/diff 仅当调用方具备 shipping_notice.audit_sensitive_read; 敏感 before/after/diff 仅当调用方具备 shipping_notice.audit_sensitive_read;
支持 event_type_group=review_workbench|chat_workbench|process_gate|
candidate_qualification|workflow_node;支持 candidate_no / gate_code 筛选;
PostgreSQL 清理前在同事务 set_config('hxops.shipping_audit_purge','1'), PostgreSQL 清理前在同事务 set_config('hxops.shipping_audit_purge','1'),
以便 DB 触发器仅放行已到期行的 DELETE;SQLite/测试仍用 Core DELETE + ORM 守卫。 以便 DB 触发器仅放行已到期行的 DELETE;SQLite/测试仍用 Core DELETE + ORM 守卫。
""" """
@@ -26,7 +28,14 @@ from app.models import ShippingAuditEvent
from app.services.shipping_notice.audit_service import append_shipping_audit_event from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.audit_snapshot_service import verify_event_hash_chain from app.services.shipping_notice.audit_snapshot_service import verify_event_hash_chain
from app.services.shipping_notice.fulfillment_audit import resolve_request_audit_context from app.services.shipping_notice.fulfillment_audit import resolve_request_audit_context
from app.services.shipping_notice.progress_audit_contract import AUDIT_SNAPSHOT_ALLOWED_KEYS from app.services.shipping_notice.progress_audit_contract import (
AUDIT_SNAPSHOT_ALLOWED_KEYS,
CANDIDATE_QUALIFICATION_AUDIT_EVENT_TYPES,
CHAT_WORKBENCH_AUDIT_EVENT_TYPES,
PROCESS_GATE_AUDIT_EVENT_TYPES,
REVIEW_WORKBENCH_AUDIT_EVENT_TYPES,
WORKFLOW_NODE_AUDIT_EVENT_TYPES,
)
# 关联链可追溯的稳定业务键(与前端审计中心筛选对齐)。 # 关联链可追溯的稳定业务键(与前端审计中心筛选对齐)。
_ASSOCIATION_KEYS = ( _ASSOCIATION_KEYS = (
@@ -175,6 +184,20 @@ def serialize_shipping_audit_event(
def _apply_filters(query, *, filters: dict[str, Any]): def _apply_filters(query, *, filters: dict[str, Any]):
"""按管理员筛选条件收窄查询;禁止自由文本全文检索正文。""" """按管理员筛选条件收窄查询;禁止自由文本全文检索正文。"""
event_type_group = str(filters.get('event_type_group') or '').strip().lower()
# [STEP] 事件分组:与 progress_audit_contract 各字典一一对齐,禁止前端私造分组名。
if event_type_group in {'review_workbench', 'order_review_workbench'}:
query = query.filter(ShippingAuditEvent.event_type.in_(sorted(REVIEW_WORKBENCH_AUDIT_EVENT_TYPES)))
elif event_type_group in {'chat_workbench', 'chat'}:
query = query.filter(ShippingAuditEvent.event_type.in_(sorted(CHAT_WORKBENCH_AUDIT_EVENT_TYPES)))
elif event_type_group in {'process_gate', 'process_gates'}:
query = query.filter(ShippingAuditEvent.event_type.in_(sorted(PROCESS_GATE_AUDIT_EVENT_TYPES)))
elif event_type_group in {'candidate_qualification', 'qualification'}:
query = query.filter(
ShippingAuditEvent.event_type.in_(sorted(CANDIDATE_QUALIFICATION_AUDIT_EVENT_TYPES))
)
elif event_type_group in {'workflow_node', 'workflow_nodes'}:
query = query.filter(ShippingAuditEvent.event_type.in_(sorted(WORKFLOW_NODE_AUDIT_EVENT_TYPES)))
if filters.get('event_type'): if filters.get('event_type'):
query = query.filter(ShippingAuditEvent.event_type == str(filters['event_type'])[:64]) query = query.filter(ShippingAuditEvent.event_type == str(filters['event_type'])[:64])
if filters.get('actor_type'): if filters.get('actor_type'):
@@ -195,6 +218,15 @@ def _apply_filters(query, *, filters: dict[str, Any]):
query = query.filter(ShippingAuditEvent.aggregate_type == str(filters['aggregate_type'])[:64]) query = query.filter(ShippingAuditEvent.aggregate_type == str(filters['aggregate_type'])[:64])
if filters.get('aggregate_id'): if filters.get('aggregate_id'):
query = query.filter(ShippingAuditEvent.aggregate_id == str(filters['aggregate_id'])[:128]) query = query.filter(ShippingAuditEvent.aggregate_id == str(filters['aggregate_id'])[:128])
# Candidate 编号写入 aggregate_id(aggregate_type=shipping_notice_candidate)。
candidate_no = str(filters.get('candidate_no') or '').strip()
if candidate_no:
query = query.filter(ShippingAuditEvent.aggregate_id == candidate_no[:128])
# Process Gate / 节点码:常见写入 aggregate_id 形如 execution_no:gate_code。
gate_code = str(filters.get('gate_code') or filters.get('node_code') or '').strip()
if gate_code:
like = f'%:{gate_code[:64]}'
query = query.filter(ShippingAuditEvent.aggregate_id.ilike(like))
if filters.get('result'): if filters.get('result'):
query = query.filter(ShippingAuditEvent.result == str(filters['result'])[:16]) query = query.filter(ShippingAuditEvent.result == str(filters['result'])[:16])
if filters.get('conversation_id'): if filters.get('conversation_id'):
@@ -207,6 +239,8 @@ def _apply_filters(query, *, filters: dict[str, Any]):
query = query.filter(ShippingAuditEvent.review_case_no == str(filters['review_case_no'])[:64]) query = query.filter(ShippingAuditEvent.review_case_no == str(filters['review_case_no'])[:64])
if filters.get('owner_user_id'): if filters.get('owner_user_id'):
query = query.filter(ShippingAuditEvent.owner_user_id == str(filters['owner_user_id'])[:64]) query = query.filter(ShippingAuditEvent.owner_user_id == str(filters['owner_user_id'])[:64])
if filters.get('reason_code'):
query = query.filter(ShippingAuditEvent.reason_code == str(filters['reason_code'])[:128])
created_from = _parse_iso(filters.get('created_from')) created_from = _parse_iso(filters.get('created_from'))
created_to = _parse_iso(filters.get('created_to')) created_to = _parse_iso(filters.get('created_to'))
if created_from is not None: if created_from is not None:
@@ -31,7 +31,10 @@ from app.models import (
ShippingOrderExtraction, ShippingOrderExtraction,
ShippingTask, ShippingTask,
) )
from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete from app.services.shipping_notice.attachment_integrity import (
attachment_incomplete_error_details,
is_attachment_parse_incomplete,
)
from app.services.shipping_notice.batch_create_idempotency import ( from app.services.shipping_notice.batch_create_idempotency import (
build_existing_batch_tool_response, build_existing_batch_tool_response,
find_batch_by_create_idempotency, find_batch_by_create_idempotency,
@@ -609,6 +612,11 @@ def create_shipping_batch_from_candidates(
raise ConflictError( raise ConflictError(
code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE',
message='发货通知附件解析不完整,请重试解析或移除后重新上传', message='发货通知附件解析不完整,请重试解析或移除后重新上传',
details=attachment_incomplete_error_details(
structured_intake,
intake_nos=[str(intake.intake_no or '')],
reason='attachment_parse_incomplete',
),
) )
if intake.expires_at and intake.expires_at < now: if intake.expires_at and intake.expires_at < now:
raise ConflictError(code='SHIPPING_NOTICE.INTAKE_EXPIRED', message='接入记录已过期') raise ConflictError(code='SHIPPING_NOTICE.INTAKE_EXPIRED', message='接入记录已过期')
@@ -990,6 +998,11 @@ def create_shipping_batch_from_intakes(
raise ConflictError( raise ConflictError(
f'接入记录 {intake.intake_no} 附件解析不完整,请重试解析或移除后重新上传', f'接入记录 {intake.intake_no} 附件解析不完整,请重试解析或移除后重新上传',
code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE',
details=attachment_incomplete_error_details(
structured,
intake_nos=[str(intake.intake_no or '')],
reason='attachment_parse_incomplete',
),
) )
if intake.expires_at and intake.expires_at < now: if intake.expires_at and intake.expires_at < now:
raise ConflictError( raise ConflictError(
@@ -3,7 +3,8 @@ services/shipping_notice/batch_orchestrator.py
用途:发货通知批次/单票后台编排器。 用途:发货通知批次/单票后台编排器。
依赖:query_service、task_workflow、shipping_notice.tools、tool_common。 依赖:query_service、task_workflow、shipping_notice.tools、tool_common。
逻辑:批次线程只推进已由订单抽取 Run 建立的正式 Task;created 旧壳任务安全停止,不再进入普通 Dify Chatflow。 逻辑:批次线程只推进已由订单抽取 Run 建立的正式 Task;无抽取的 created 旧壳任务安全停止;
复核/STP 确认后已挂 current_order_extraction_id 的 created 任务走 auto_progress。
""" """
from __future__ import annotations from __future__ import annotations
@@ -125,8 +126,14 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
""" """
后台执行单票任务的一轮推进。 后台执行单票任务的一轮推进。
仅推进已完成订单抽取的正式 Task;created 表示历史未抽取壳任务,必须重新上传创建 Intake/Run。 核心逻辑:已挂 current_order_extraction_id 的 created 任务(复核/STP 确认后)走 auto_progress;
一旦进入人工检查点或等待外部回执状态,本轮自动停止,等待用户或外部系统回写。 无抽取的 created 壳任务停在人工;进入人工检查点或等待外部回执时本轮停止。
Args:
task_no: 发货任务号。
Returns:
含 status/message 的推进结果摘要。
""" """
normalized_task_no = _normalize_ref(task_no) normalized_task_no = _normalize_ref(task_no)
if not normalized_task_no: if not normalized_task_no:
@@ -193,6 +200,13 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
str(result.get("message") or "")[:300], str(result.get("message") or "")[:300],
) )
elif process_status == "created": elif process_status == "created":
# [STEP] 复核/STP 确认建单后任务仍为 created,但已挂正式 Extraction;须走 auto_progress。
# 无抽取的历史壳任务仍停在人工,避免误入 Chatflow。
if getattr(task, "current_order_extraction_id", None):
payload["mode"] = "auto"
payload.setdefault("source", "system")
result = auto_progress(payload)
else:
result = { result = {
"status": "needs_human", "status": "needs_human",
"message": "任务尚未完成订单抽取,请重新上传原始发货通知创建后台识别 Run。", "message": "任务尚未完成订单抽取,请重新上传原始发货通知创建后台识别 Run。",
@@ -0,0 +1,69 @@
"""
services/shipping_notice/candidate_qualification_contract.py
用途:冻结 Candidate 级统一自动建单资格的状态、检查项与阻断原因码。
依赖:无(纯常量契约);与前端 CandidateQualificationStatus 对齐。
逻辑:模板质量资格(Profile 盲测)不得映射为本契约状态;独立模板 /
通用解析 / Dify LLM 三种解析来源共用同一套检查顺序与原因码。
权威界面边界见 docs/features/shipping-notice/review-workbench-layout-plan.md §0。
"""
from __future__ import annotations
from typing import Final
# 与前端 CandidateQualificationStatus 对齐。
CANDIDATE_QUALIFICATION_STATUSES: Final[frozenset[str]] = frozenset({
'eligible',
'review_required',
'blocked',
'rejected',
})
# 资格评估器版本;快照持久化时写入 evaluator_version。
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION: Final[str] = 'candidate-qualification.v1'
# 统一检查顺序(不可重排):后置项依赖前置放行语义由服务层解释。
CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = (
'auto_create_enabled',
'classification_confidence',
'required_fields_complete',
'key_fields_minimum_confidence',
'evidence_complete',
'field_conflicts_resolved',
'duplicate_resolved',
'customer_confirmed',
'idempotency_ok',
)
# 检查项失败 → 稳定用户原因码(对话 / Process Gate / 复核摘要共用)。
CANDIDATE_QUALIFICATION_GATE_REASON_CODES: Final[dict[str, str]] = {
'auto_create_enabled': 'auto_create_disabled',
'classification_confidence': 'classification_low_confidence',
'required_fields_complete': 'required_field_missing',
'key_fields_minimum_confidence': 'field_low_confidence',
'evidence_complete': 'evidence_missing',
'field_conflicts_resolved': 'field_conflict',
'duplicate_resolved': 'duplicate_unresolved',
'customer_confirmed': 'customer_confirmation_required',
'idempotency_ok': 'task_already_exists',
}
# 偏向「需人工轻量确认」而非硬阻断的原因码。
CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES: Final[frozenset[str]] = frozenset({
'customer_confirmation_required',
'customer_ambiguous',
'customer_unresolved',
'duplicate_unresolved',
'classification_low_confidence',
'field_low_confidence',
})
# 解析来源(写入 parser_trace,不直接决定资格)。
CANDIDATE_PARSER_SOURCES: Final[frozenset[str]] = frozenset({
'profile_deterministic',
'generic_deterministic',
'llm_assisted',
'manual_review',
'unknown',
})
@@ -0,0 +1,857 @@
"""
services/shipping_notice/candidate_qualification_service.py
用途:评估并追加持久化 Candidate 级统一自动建单资格快照。
依赖:candidate_qualification_contract、order_schema.service(自动建单开关 / minimum_confidence)、
ShippingNoticeCandidate / ShippingOrderCandidateQualification、fulfillment_audit。
逻辑:由抽取收尾、建单资格与 STP 自动建单调用;三种解析来源统一门禁;
每次评估追加不可变历史行并写统一审计 before/after;
模板 Profile 批准仅写入 parser_trace;LLM 路径不再天然阻断;
分类/LLM 字段置信度缺失 fail-closed;阈值来源写入 confidence_policy;
duplicate unchecked 与关键字段证据缺失均 fail-closed。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app.core.errors import ConflictError
from app.extensions import db
from app.models import (
ShippingNoticeCandidate,
ShippingOrderCandidateQualification,
ShippingOrderCustomerMatch,
ShippingOrderExtraction,
)
from app.services.shipping_notice.candidate_qualification_contract import (
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION,
CANDIDATE_QUALIFICATION_GATE_KEYS,
CANDIDATE_QUALIFICATION_GATE_REASON_CODES,
CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES,
)
from app.services.shipping_notice.order_schema import service as order_schema_service
from app.services.shipping_notice.tool_common import extraction_emergency_stop_enabled
# 分类置信度默认下限;仅当 Schema auto_creation_policy 未配置 minimum_confidence 时回退。
# 回退来源会写入评估结果 confidence_policy,供管理端核对,禁止静默偏离界面配置。
_DEFAULT_CLASSIFICATION_MIN_CONFIDENCE = 0.85
_CONFIDENCE_SOURCE_SCHEMA_POLICY = 'schema_auto_creation_policy'
_CONFIDENCE_SOURCE_KEY_FIELD_MIN = 'key_field_minimum_confidence'
_CONFIDENCE_SOURCE_DEFAULT_FALLBACK = 'default_fallback_0_85'
def resolve_candidate_customer_resolved(
*,
candidate: Any | None = None,
extraction_id: int | None = None,
) -> bool:
"""
判定 Candidate/Extraction 的 Bill-to 客户是否已确认。
核心逻辑:优先读 ShippingOrderCustomerMatch(bill_to)=confirmed;
其次读 Candidate.structured_result_json.customer.resolution_status。
Args:
candidate: 可选 Candidate。
extraction_id: 可选 Extraction 主键(优先于 Candidate.order_extraction_id)。
Returns:
True 表示客户已确认,可用于建单资格评估。
"""
ext_id = extraction_id
if ext_id is None and candidate is not None:
raw = getattr(candidate, 'order_extraction_id', None)
if raw is not None:
try:
ext_id = int(raw)
except (TypeError, ValueError):
ext_id = None
if ext_id is not None:
row = ShippingOrderCustomerMatch.query.filter_by(
extraction_id=int(ext_id),
role='bill_to',
status='confirmed',
).first()
if row is not None and row.customer_id is not None:
return True
if candidate is None:
return False
ok, _reason = _customer_ok(candidate, customer_resolved=None)
return bool(ok)
def resolve_confirmed_bill_to_customer_id(
*,
candidate: Any | None = None,
extraction_id: int | None = None,
) -> int | None:
"""
返回已确认 Bill-to 标准客户主键;未确认时为 None。
核心逻辑:与 resolve_candidate_customer_resolved 同源,额外取出 customer_id 供建单绑定。
"""
ext_id = extraction_id
if ext_id is None and candidate is not None:
raw = getattr(candidate, 'order_extraction_id', None)
if raw is not None:
try:
ext_id = int(raw)
except (TypeError, ValueError):
ext_id = None
if ext_id is not None:
row = ShippingOrderCustomerMatch.query.filter_by(
extraction_id=int(ext_id),
role='bill_to',
status='confirmed',
).first()
if row is not None and row.customer_id is not None:
return int(row.customer_id)
return None
def assert_customer_confirmed_before_task_create(
*,
shipping_case: Any | None = None,
candidate: Any | None = None,
customer_id: int | None = None,
extraction_id: int | None = None,
) -> None:
"""
建 Task 前强制客户已确认(fail-closed)。
核心逻辑:业务单已绑定客户、显式传入 customer_id、或 Candidate/Extraction
Bill-to 已 confirmed 三者任一即可;否则拒绝创建,禁止落入 customer_review。
Raises:
ConflictError: SHIPPING.CUSTOMER_REQUIRED_BEFORE_TASK
"""
if shipping_case is not None and getattr(shipping_case, 'customer_id', None) is not None:
return
if customer_id is not None:
return
if resolve_candidate_customer_resolved(candidate=candidate, extraction_id=extraction_id):
return
raise ConflictError(
'Customer must be confirmed before creating a shipping task',
code='SHIPPING.CUSTOMER_REQUIRED_BEFORE_TASK',
details={
'message': '客户确认必须发生在创建 Task 之前,不能先建单再进入 customer_review',
},
)
def resolve_review_case_customer_resolved(
*,
case: Any,
candidate: Any | None = None,
) -> bool:
"""
判定复核 Case 关联客户是否已确认(建单前 fail-closed)。
核心逻辑:Candidate/Extraction 确认优先;否则查同 Run 已确认 Bill-to。
Args:
case: ShippingOrderReviewCase。
candidate: 可选已加载 Candidate。
Returns:
True 表示客户已确认。
"""
if resolve_candidate_customer_resolved(candidate=candidate):
return True
run_id = getattr(case, 'run_id', None)
if run_id is None:
return False
row = (
ShippingOrderCustomerMatch.query
.join(
ShippingOrderExtraction,
ShippingOrderExtraction.id == ShippingOrderCustomerMatch.extraction_id,
)
.filter(
ShippingOrderExtraction.run_id == int(run_id),
ShippingOrderCustomerMatch.role == 'bill_to',
ShippingOrderCustomerMatch.status == 'confirmed',
ShippingOrderCustomerMatch.customer_id.isnot(None),
)
.first()
)
return row is not None
def evaluate_candidate_qualification(
*,
candidate: Any,
run: Any | None = None,
unit: Any | None = None,
fields_complete: bool | None = None,
customer_resolved: bool | None = None,
schema_auto_create_enabled: bool | None = None,
) -> dict[str, Any]:
"""
评估单个 Candidate 的统一自动建单资格(不写库)。
核心逻辑:按冻结检查顺序生成 gate_results;模板批准与 LLM 路由只进 parser_trace;
汇总 blocking_reason_codes 后映射 eligible / review_required / blocked / rejected。
Args:
candidate: ShippingNoticeCandidate 或兼容 SimpleNamespace。
run: 可选 Run(读取紧急停止 / auto_freeze_policy)。
unit: 可选 Unit(读取路由摘要,仅 parser_trace)。
fields_complete: 调用方已汇总的必填完整标志;缺省时读 missing_fields_json。
customer_resolved: 调用方客户确认结果;缺省时按未确认处理。
schema_auto_create_enabled: Schema 自动建单总开关;缺省时读已发布策略。
Returns:
status、gates、failed_gates、blocking_reason_codes、parser_trace、
evidence_snapshot、qualification_score、can_auto_create。
"""
# [STEP 1] 解析来源与模板质量痕迹(不影响放行)。
parser_trace = _build_parser_trace(candidate=candidate, run=run, unit=unit)
# [STEP 2] 逐项评估统一门禁。
if schema_auto_create_enabled is None:
schema_auto_create_enabled = bool(
(order_schema_service.get_auto_creation_policy() or {}).get('enabled')
)
emergency_stop = False
if run is not None:
policy = getattr(run, 'auto_freeze_policy_json', None)
if isinstance(policy, dict) and bool(policy.get('emergency_stop')):
emergency_stop = True
elif extraction_emergency_stop_enabled():
emergency_stop = True
auto_create_enabled = bool(schema_auto_create_enabled) and not emergency_stop
min_confidence, confidence_source = _resolve_minimum_confidence(candidate)
classification_ok = _classification_confidence_ok(
candidate,
minimum_confidence=min_confidence,
)
required_ok = _required_fields_ok(candidate, fields_complete=fields_complete)
key_confidence_ok = _key_fields_confidence_ok(
candidate,
parser_source=str(parser_trace.get('parser_source') or ''),
minimum_confidence=min_confidence,
)
evidence_ok = _evidence_ok(candidate)
conflicts_ok = _conflicts_ok(candidate)
duplicate_ok = _duplicate_ok(candidate)
customer_ok, customer_reason = _customer_ok(candidate, customer_resolved=customer_resolved)
idempotency_ok = _idempotency_ok(candidate)
gates = {
'auto_create_enabled': auto_create_enabled,
'classification_confidence': classification_ok,
'required_fields_complete': required_ok,
'key_fields_minimum_confidence': key_confidence_ok,
'evidence_complete': evidence_ok,
'field_conflicts_resolved': conflicts_ok,
'duplicate_resolved': duplicate_ok,
'customer_confirmed': customer_ok,
'idempotency_ok': idempotency_ok,
}
failed = [key for key in CANDIDATE_QUALIFICATION_GATE_KEYS if not gates.get(key)]
# [STEP 3] 映射原因码;客户细因覆盖默认码。
blocking_reason_codes: list[str] = []
for key in failed:
if key == 'customer_confirmed' and customer_reason:
blocking_reason_codes.append(customer_reason)
continue
blocking_reason_codes.append(
CANDIDATE_QUALIFICATION_GATE_REASON_CODES.get(key, 'order_freeze_not_ready')
)
if emergency_stop and 'auto_create_disabled' not in blocking_reason_codes:
blocking_reason_codes.insert(0, 'extraction_emergency_stop')
# [STEP 4] 状态归类。
status = _map_status(
candidate=candidate,
failed_gates=failed,
blocking_reason_codes=blocking_reason_codes,
)
evidence_snapshot = _evidence_snapshot(candidate)
score = _qualification_score(gates)
confidence_policy = {
'minimum_confidence': float(min_confidence),
'source': confidence_source,
'default_fallback': _DEFAULT_CLASSIFICATION_MIN_CONFIDENCE,
}
parser_trace = {
**parser_trace,
'confidence_policy': confidence_policy,
}
return {
'status': status,
'gates': gates,
'failed_gates': failed,
'blocking_reason_codes': blocking_reason_codes,
'parser_trace': parser_trace,
'evidence_snapshot': evidence_snapshot,
'qualification_score': score,
'can_auto_create': status == 'eligible',
'evaluator_version': CANDIDATE_QUALIFICATION_EVALUATOR_VERSION,
'confidence_policy': confidence_policy,
}
def build_qualification_snapshot(evaluation: dict[str, Any]) -> dict[str, Any]:
"""
将评估结果规范为可持久化不可变快照字段。
Args:
evaluation: evaluate_candidate_qualification 返回值。
Returns:
供 ShippingOrderCandidateQualification 写入的字段字典。
"""
return {
'status': str(evaluation.get('status') or 'blocked'),
'qualification_score': float(evaluation.get('qualification_score') or 0.0),
'gate_results_json': dict(evaluation.get('gates') or {}),
'blocking_reason_codes_json': list(evaluation.get('blocking_reason_codes') or []),
'parser_trace_json': dict(evaluation.get('parser_trace') or {}),
'evidence_snapshot_json': dict(evaluation.get('evidence_snapshot') or {}),
'evaluator_version': str(
evaluation.get('evaluator_version') or CANDIDATE_QUALIFICATION_EVALUATOR_VERSION
),
}
def recalculate_candidate_qualification(
*,
candidate: ShippingNoticeCandidate,
run: Any | None = None,
unit: Any | None = None,
fields_complete: bool | None = None,
customer_resolved: bool | None = None,
evaluated_by_id: int | None = None,
request_id: str | None = None,
persist: bool = True,
) -> dict[str, Any]:
"""
重新评估 Candidate 资格,可选追加不可变历史快照并写统一审计。
核心逻辑:先 evaluate;persist 时将旧 is_current 置 False,插入新行(evaluation_seq+1),
并写入 before/after 审计事件;审计 result 为 success(可自动建单)或 rejected(未达自动建单),
禁止使用非契约枚举 blocked。
Args:
candidate: 持久化 Candidate。
run / unit / fields_complete / customer_resolved: 同 evaluate。
evaluated_by_id: 人工触发评估时的操作人;系统评估为 None。
request_id: 请求关联 ID。
persist: 为 False 时只返回评估结果。
Returns:
评估结果;persist 时额外含 qualification_id / evaluation_seq。
"""
evaluation = evaluate_candidate_qualification(
candidate=candidate,
run=run,
unit=unit,
fields_complete=fields_complete,
customer_resolved=customer_resolved,
)
if not persist:
return evaluation
snapshot = build_qualification_snapshot(evaluation)
now = datetime.utcnow()
previous = (
ShippingOrderCandidateQualification.query
.filter_by(candidate_id=int(candidate.id), is_current=True)
.order_by(ShippingOrderCandidateQualification.evaluation_seq.desc())
.first()
)
before_snap = None
next_seq = 1
if previous is not None:
before_snap = {
'qualification_id': int(previous.id),
'evaluation_seq': int(previous.evaluation_seq or 1),
'status': str(previous.status or ''),
'blocking_reason_codes': list(previous.blocking_reason_codes_json or []),
'qualification_score': float(previous.qualification_score or 0.0),
}
next_seq = int(previous.evaluation_seq or 1) + 1
previous.is_current = False
previous.updated_at = now
# 兼容旧数据:同 candidate 可能仍有其他 is_current=True 行。
(
ShippingOrderCandidateQualification.query
.filter(
ShippingOrderCandidateQualification.candidate_id == int(candidate.id),
ShippingOrderCandidateQualification.id != int(previous.id),
ShippingOrderCandidateQualification.is_current.is_(True),
)
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
)
row = ShippingOrderCandidateQualification(
candidate_id=int(candidate.id),
run_id=int(getattr(candidate, 'order_extraction_run_id', 0) or 0) or None,
evaluation_seq=next_seq,
is_current=True,
status=snapshot['status'],
qualification_score=snapshot['qualification_score'],
gate_results_json=snapshot['gate_results_json'],
blocking_reason_codes_json=snapshot['blocking_reason_codes_json'],
parser_trace_json=snapshot['parser_trace_json'],
evidence_snapshot_json=snapshot['evidence_snapshot_json'],
evaluator_version=snapshot['evaluator_version'],
evaluated_at=now,
evaluated_by_id=evaluated_by_id,
request_id=(str(request_id).strip() or None) if request_id else None,
created_at=now,
updated_at=now,
)
db.session.add(row)
db.session.flush()
evaluation['qualification_id'] = int(row.id)
evaluation['evaluation_seq'] = int(row.evaluation_seq)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
# 审计 result 仅允许 success/failure/rejected/ignored;资格未达自动建单用 rejected(非系统 failure)。
record_fulfillment_audit(
event_type='candidate_qualification_evaluated',
aggregate_type='shipping_notice_candidate',
aggregate_id=str(getattr(candidate, 'candidate_no', None) or candidate.id),
action='recalculate_candidate_qualification',
actor_type='user' if evaluated_by_id is not None else 'system',
actor_id=evaluated_by_id,
result='success' if evaluation.get('can_auto_create') else 'rejected',
before=before_snap,
after={
'qualification_id': int(row.id),
'evaluation_seq': int(row.evaluation_seq),
'status': snapshot['status'],
'blocking_reason_codes': list(snapshot['blocking_reason_codes_json'] or []),
'qualification_score': float(snapshot['qualification_score'] or 0.0),
'can_auto_create': bool(evaluation.get('can_auto_create')),
'qualification_status': snapshot['status'],
},
metadata={
'request_id': row.request_id,
'evaluator_version': snapshot['evaluator_version'],
'run_id': row.run_id,
'audit_result_reason': (
'auto_create_eligible' if evaluation.get('can_auto_create') else 'auto_create_not_eligible'
),
},
source='candidate_qualification',
)
return evaluation
def _build_parser_trace(*, candidate: Any, run: Any | None, unit: Any | None) -> dict[str, Any]:
"""组装解析链路痕迹;模板批准仅作治理信息。"""
route: dict[str, Any] = {}
if unit is not None and isinstance(getattr(unit, 'route_decision_json', None), dict):
route = dict(unit.route_decision_json or {})
extraction_source = str(getattr(candidate, 'extraction_source', '') or '').strip().lower()
route_type = str(route.get('route_type') or '').strip()
if route_type in {'llm_assisted_review', 'llm', 'dify'}:
route_type = 'llm_assisted'
elif not route_type:
if extraction_source in {'llm', 'dify', 'llm_assisted'}:
route_type = 'llm_assisted'
elif extraction_source in {'generic', 'generic_deterministic'}:
route_type = 'generic_deterministic'
elif extraction_source in {'profile', 'template', 'profile_deterministic'}:
route_type = 'profile_deterministic'
else:
route_type = 'unknown'
profile_approved = bool(route.get('auto_create_approved'))
policy_profile_status = None
if run is not None:
policy = getattr(run, 'auto_freeze_policy_json', None)
if isinstance(policy, dict):
policy_profile_status = policy.get('qualification_status')
if policy.get('selected_profile_id') and not route.get('selected_profile_id'):
route = {
**route,
'selected_profile_id': policy.get('selected_profile_id'),
'selected_profile_code': policy.get('selected_profile_code'),
'selected_profile_checksum': policy.get('selected_profile_checksum'),
}
return {
'parser_source': route_type,
'extraction_source': extraction_source or None,
'profile_id': route.get('selected_profile_id'),
'profile_code': route.get('selected_profile_code'),
'profile_checksum': route.get('selected_profile_checksum'),
'profile_auto_create_approved': profile_approved,
'profile_qualification_status': policy_profile_status,
'note': 'template_quality_only_not_auto_create_gate',
}
def _resolve_minimum_confidence(candidate: Any | None = None) -> tuple[float, str]:
"""
解析统一置信度下限及其来源。
核心逻辑:优先 Schema auto_creation_policy.minimum_confidence,
其次关键字段声明的 minimum_confidence 最小值,最后回退默认值(来源可观测)。
Returns:
(阈值, 来源码)
"""
policy = order_schema_service.get_auto_creation_policy() or {}
if policy.get('minimum_confidence') is not None:
try:
return float(policy['minimum_confidence']), _CONFIDENCE_SOURCE_SCHEMA_POLICY
except (TypeError, ValueError):
pass
thresholds: list[float] = []
raw = getattr(candidate, 'field_confidence_json', None) if candidate is not None else None
if isinstance(raw, dict):
for item in raw.values():
if not isinstance(item, dict):
continue
if item.get('auto_create_key_field') is not True and item.get('key_field') is not True:
continue
if item.get('minimum_confidence') is None:
continue
try:
thresholds.append(float(item['minimum_confidence']))
except (TypeError, ValueError):
continue
if thresholds:
return min(thresholds), _CONFIDENCE_SOURCE_KEY_FIELD_MIN
return _DEFAULT_CLASSIFICATION_MIN_CONFIDENCE, _CONFIDENCE_SOURCE_DEFAULT_FALLBACK
def _classification_human_confirmed(candidate: Any) -> bool:
"""是否存在可信的人工分类确认(允许分类置信度缺失时放行)。"""
if bool(getattr(candidate, 'classification_human_confirmed', False)):
return True
mode = str(getattr(candidate, 'acceptance_mode', '') or '').strip().lower()
if mode in {'human_confirmed', 'manual_confirmed', 'review_confirmed'}:
return True
structured = getattr(candidate, 'structured_result_json', None)
if isinstance(structured, dict):
classification = structured.get('classification')
if isinstance(classification, dict):
status = str(
classification.get('resolution_status')
or classification.get('confirmation_status')
or ''
).strip().lower()
if status in {'confirmed', 'user_confirmed', 'human_confirmed'}:
return True
return False
def _classification_confidence_ok(
candidate: Any,
*,
minimum_confidence: float,
) -> bool:
"""
订单分类置信度是否达统一 minimum_confidence。
核心逻辑:缺失数值 fail-closed;仅人工明确确认分类时可放行。
"""
value = getattr(candidate, 'classification_confidence', None)
if value is None:
value = getattr(candidate, 'confidence', None)
if value is None:
return _classification_human_confirmed(candidate)
try:
return float(value) >= float(minimum_confidence)
except (TypeError, ValueError):
return False
def _is_llm_parser_source(parser_source: str, candidate: Any) -> bool:
"""判定是否 LLM / Dify 解析路径(须强制字段置信度)。"""
source = str(parser_source or '').strip().lower()
if source in {'llm_assisted', 'llm', 'dify', 'llm_assisted_review'}:
return True
extraction = str(getattr(candidate, 'extraction_source', '') or '').strip().lower()
return extraction in {'llm', 'dify', 'llm_assisted', 'llm_assisted_review'}
def _required_fields_ok(candidate: Any, *, fields_complete: bool | None) -> bool:
"""必填字段是否完整。"""
if fields_complete is not None:
return bool(fields_complete)
missing = getattr(candidate, 'missing_fields_json', None)
if isinstance(missing, list):
return len(missing) == 0
return str(getattr(candidate, 'validation_status', '') or '') in {
'ready', 'valid', 'passed', 'ok',
}
def _deterministic_field_rules_ready(candidate: Any) -> bool:
"""
确定性解析器在无字段置信度时的前置强校验。
核心逻辑:validation_status 须就绪,且 missing_fields 为空;
证据完整性由独立 evidence_complete 门禁继续校验。
"""
status = str(getattr(candidate, 'validation_status', '') or '').strip().lower()
if status not in {'ready', 'valid', 'passed', 'ok'}:
return False
missing = getattr(candidate, 'missing_fields_json', None)
if isinstance(missing, list) and len(missing) > 0:
return False
return True
def _key_fields_confidence_ok(
candidate: Any,
*,
parser_source: str = '',
minimum_confidence: float,
) -> bool:
"""
关键字段 minimum_confidence 是否满足。
核心逻辑:
- LLM 路径:必须有字段级置信度;关键字段缺置信度或低于阈值均阻断。
- 确定性解析器:有声明则逐项比较;无字段置信度时须通过「字段规则就绪」强校验
(validation_status 就绪且无缺失必填),不得隐式空放行。
"""
raw = getattr(candidate, 'field_confidence_json', None)
is_llm = _is_llm_parser_source(parser_source, candidate)
if not isinstance(raw, dict) or not raw:
if is_llm:
return False
# 确定性无置信度:强制字段规则就绪,避免“无置信度=默认通过”。
return _deterministic_field_rules_ready(candidate)
default_threshold = float(minimum_confidence)
key_fields_seen = 0
for _field, item in raw.items():
if not isinstance(item, dict):
continue
if item.get('auto_create_key_field') is not True and item.get('key_field') is not True:
continue
key_fields_seen += 1
if item.get('confidence', item.get('value')) is None:
return False
try:
value = float(item.get('confidence', item.get('value')))
threshold = float(item.get('minimum_confidence', default_threshold))
except (TypeError, ValueError):
return False
if value < threshold:
return False
# LLM 且未标注关键字段:要求每条置信度声明均可解析且达阈值。
if is_llm and key_fields_seen == 0:
numeric_only = all(not isinstance(v, dict) for v in raw.values())
if numeric_only:
for value in raw.values():
try:
if float(value) < default_threshold:
return False
except (TypeError, ValueError):
return False
return True
for item in raw.values():
if not isinstance(item, dict):
return False
if item.get('confidence', item.get('value')) is None:
return False
try:
if float(item.get('confidence', item.get('value'))) < default_threshold:
return False
except (TypeError, ValueError):
return False
return True
numeric_only = all(not isinstance(v, dict) for v in raw.values())
if numeric_only:
for value in raw.values():
try:
if float(value) < default_threshold:
return False
except (TypeError, ValueError):
return False
return True
def _key_evidence_fields(candidate: Any) -> list[str]:
"""提取需要逐项证据覆盖的关键字段编码。"""
required: list[str] = []
raw = getattr(candidate, 'field_confidence_json', None)
if isinstance(raw, dict):
for field, item in raw.items():
code = str(field or '').strip()
if not code:
continue
if isinstance(item, dict) and (
item.get('auto_create_key_field') is True or item.get('key_field') is True
):
required.append(code)
if required:
return required
# 无 Schema 关键字段声明时,要求证据条目本身绑定字段,避免“一条无关证据放行”。
return []
def _evidence_ok(candidate: Any) -> bool:
"""
证据门禁:必须有证据,且关键字段逐项有绑定证据。
核心逻辑:evidence_json 每项需含 field/field_code;若声明了关键字段,
则每个关键字段至少一条证据;未声明关键字段时,全部证据条目必须带字段绑定。
"""
evidence = getattr(candidate, 'evidence_json', None)
if not isinstance(evidence, list) or not evidence:
return False
covered: set[str] = set()
for item in evidence:
if not isinstance(item, dict):
return False
code = str(
item.get('field')
or item.get('field_code')
or item.get('field_id')
or ''
).strip()
if not code:
return False
covered.add(code)
required = _key_evidence_fields(candidate)
if required:
return all(field in covered for field in required)
return True
def _conflicts_ok(candidate: Any) -> bool:
"""字段冲突是否已清空。"""
conflicts = getattr(candidate, 'conflicts_json', None)
if not conflicts:
return True
if isinstance(conflicts, list):
return len(conflicts) == 0
return False
def _duplicate_ok(candidate: Any) -> bool:
"""
重复检测是否完成且无需阻断。
核心逻辑:unchecked/空状态 fail-closed;明确 none 或已决议处置
(含 open_existing / create_revision / force_create)才放行。
"""
dup_status = str(getattr(candidate, 'duplicate_status', '') or '').strip().lower()
dup_resolution = str(getattr(candidate, 'duplicate_resolution', '') or '').strip().lower()
if dup_status in {'unchecked', ''}:
return False
if dup_status in {'none', 'not_duplicate', 'clear'}:
return True
# create_revision / force_create 为复核工作台合法裁决,须计入已解决。
if dup_resolution in {
'open_existing',
'create_revision',
'force_create',
'create_new',
'ignored',
'not_duplicate',
}:
return True
return False
def _customer_ok(
candidate: Any,
*,
customer_resolved: bool | None,
) -> tuple[bool, str | None]:
"""
客户是否已确认。
Returns:
(通过?, 细粒度原因码)
"""
if customer_resolved is True:
return True, None
if customer_resolved is False:
return False, 'customer_unresolved'
structured = getattr(candidate, 'structured_result_json', None)
if isinstance(structured, dict):
customer = structured.get('customer') if isinstance(structured.get('customer'), dict) else {}
status = str(
customer.get('resolution_status')
or structured.get('customer_resolution_status')
or ''
).strip().lower()
if status in {'resolved', 'user_confirmed', 'confirmed', 'auto_confirmed'}:
return True, None
if status in {'ambiguous', 'multiple'}:
return False, 'customer_ambiguous'
if status in {'unresolved', 'invalid', 'conflicted'}:
return False, 'customer_unresolved'
# 缺省:未提供客户状态时要求确认(fail-closed)。
return False, 'customer_confirmation_required'
def _idempotency_ok(candidate: Any) -> bool:
"""尚未消费为 Task 才允许新建。"""
return getattr(candidate, 'consumed_task_id', None) is None
def _map_status(
*,
candidate: Any,
failed_gates: list[str],
blocking_reason_codes: list[str],
) -> str:
"""将失败集合映射为资格状态。"""
candidate_status = str(getattr(candidate, 'candidate_status', '') or '')
if candidate_status in {'rejected', 'expired'}:
return 'rejected'
if not failed_gates:
return 'eligible'
if all(code in CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES for code in blocking_reason_codes):
return 'review_required'
if set(failed_gates) <= {
'customer_confirmed', 'duplicate_resolved', 'classification_confidence',
'key_fields_minimum_confidence',
}:
return 'review_required'
return 'blocked'
def _evidence_snapshot(candidate: Any) -> dict[str, Any]:
"""脱敏证据摘要(仅计数与字段引用,不含原文/URL)。"""
evidence = getattr(candidate, 'evidence_json', None)
count = len(evidence) if isinstance(evidence, list) else 0
field_refs: list[str] = []
if isinstance(evidence, list):
for item in evidence[:50]:
if isinstance(item, dict):
ref = str(item.get('field') or item.get('field_code') or item.get('field_id') or '')
if ref:
field_refs.append(ref)
return {
'evidence_count': count,
'field_refs': field_refs,
'missing_fields': list(getattr(candidate, 'missing_fields_json', None) or [])
if isinstance(getattr(candidate, 'missing_fields_json', None), list) else [],
}
def _qualification_score(gates: dict[str, bool]) -> float:
"""按通过检查项占比计算 0–1 分数。"""
total = len(CANDIDATE_QUALIFICATION_GATE_KEYS)
if total == 0:
return 0.0
passed = sum(1 for key in CANDIDATE_QUALIFICATION_GATE_KEYS if gates.get(key))
return round(passed / total, 4)
@@ -4,7 +4,8 @@ backend/app/services/shipping_notice/candidate_service.py
用途:提供订单候选的用户态查询、选择与重复决策能力;含 STP 严格建单门禁。 用途:提供订单候选的用户态查询、选择与重复决策能力;含 STP 严格建单门禁。
依赖:ShippingNoticeCandidate/Document/Intake、duplicate_detection、business_fingerprint。 依赖:ShippingNoticeCandidate/Document/Intake、duplicate_detection、business_fingerprint。
逻辑:workspace API 调用本模块;所有写操作锁定 Candidate,并在字段变化后重算双指纹和重复状态; 逻辑:workspace API 调用本模块;所有写操作锁定 Candidate,并在字段变化后重算双指纹和重复状态;
仅严格门禁通过的 Candidate 可物化 Task(缺字段/低置信/缺证据/重复冲突 → 拒绝)。 仅严格门禁通过且客户已确认的 Candidate 可物化 Task
(缺字段/低置信/缺证据/重复冲突/客户未确认 → 拒绝)。
""" """
from __future__ import annotations from __future__ import annotations
@@ -65,10 +66,11 @@ def evaluate_candidate_stp_gate(candidate: ShippingNoticeCandidate) -> tuple[boo
def ensure_candidate_fulfillment_ready(candidate: ShippingNoticeCandidate) -> None: def ensure_candidate_fulfillment_ready(candidate: ShippingNoticeCandidate) -> None:
""" """
统一履约门禁:已接受、当前、无阻断;automatic 候选额外通过 STP 严格门禁。 统一履约门禁:已接受、当前、无阻断;建 Task 前客户必须已确认;
automatic 候选额外通过 STP 严格门禁。
Raises: Raises:
ConflictError: 接受态、选中态、版本、消费态或 STP 严格门禁失败。 ConflictError: 接受态、选中态、版本、消费态、客户未确认或 STP 严格门禁失败。
""" """
if str(candidate.candidate_status or '') != 'accepted': if str(candidate.candidate_status or '') != 'accepted':
raise ConflictError( raise ConflictError(
@@ -86,6 +88,12 @@ def ensure_candidate_fulfillment_ready(candidate: ShippingNoticeCandidate) -> No
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED', code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
message='订单候选仍有字段冲突或未完成审核', message='订单候选仍有字段冲突或未完成审核',
) )
# [STEP] 客户确认必须在创建 Task 之前,禁止依赖建单后 customer_review。
from app.services.shipping_notice.candidate_qualification_service import (
assert_customer_confirmed_before_task_create,
)
assert_customer_confirmed_before_task_create(candidate=candidate)
# [STEP] STP 严格门禁仅约束自动直通;人工确认建单已由复核草稿校验背书。 # [STEP] STP 严格门禁仅约束自动直通;人工确认建单已由复核草稿校验背书。
passed, reason_codes = evaluate_candidate_stp_gate(candidate) passed, reason_codes = evaluate_candidate_stp_gate(candidate)
if not passed: if not passed:
@@ -237,7 +245,7 @@ def reject_candidate(*, user_id: int, candidate_no: str, reason: str | None = No
actor_type='user', actor_type='user',
actor_id=user_id, actor_id=user_id,
run_no=getattr(candidate, 'run_no', None) or None, run_no=getattr(candidate, 'run_no', None) or None,
reason_code='manual_rejected', reason_code='task_rejected_by_user',
before={'status': 'provisional'}, before={'status': 'provisional'},
after={'status': 'rejected'}, after={'status': 'rejected'},
) )
@@ -38,14 +38,14 @@ def build_chat_actions_payload(task) -> dict:
""" """
构建聊天气泡侧动作按钮兼容 payload。 构建聊天气泡侧动作按钮兼容 payload。
核心逻辑:复用统一 UI State 读模型,只抽取聊天侧需要的 checkpoint/action_buttons/summary, 核心逻辑:复用统一 UI State 读模型,抽取聊天侧 checkpoint/summary/process_gate;
避免 workspace 路由继续依赖已删除的旧读模型实现。 action_buttons 已由 ui_state 在存在 ProcessExecution 时按 Gate 规则收缩(阻断清零)。
Args: Args:
task: ShippingTask 模型实例。 task: ShippingTask 模型实例。
Returns: Returns:
包含 task_no、checkpoint、action_buttons 与摘要的字典。 包含 task_no、checkpoint、process_gate、action_buttons 与摘要的字典。
""" """
state = build_task_ui_state(task) state = build_task_ui_state(task)
return { return {
@@ -58,6 +58,7 @@ def build_chat_actions_payload(task) -> dict:
"match_status": state.get("match_status"), "match_status": state.get("match_status"),
"current_step": state.get("current_step"), "current_step": state.get("current_step"),
"summary": state.get("summary"), "summary": state.get("summary"),
"process_gate": state.get("process_gate"),
"action_buttons": state.get("action_buttons") or [], "action_buttons": state.get("action_buttons") or [],
"updated_at": state.get("updated_at"), "updated_at": state.get("updated_at"),
} }
@@ -1,13 +1,38 @@
""" """
services/shipping_notice/constants.py services/shipping_notice/constants.py
用途:发货通知 API 字段名、checkpoint / review_status / pending_human_reason 的规范常量。 用途:发货通知 API 字段名、checkpoint / review_status / pending_human_reason 的规范常量;
依赖:无(纯常量模块);state_machine.py 引用 CP_*/PH_*/RS_* 注册按钮与状态迁移。 并再导出错误可解释性分层原因码集合,供 Tool/Workspace 与门禁投影对齐。
逻辑:tools.py、tool_response、workspace API 统一读本模块,避免 checkpoint id 漂移。 依赖:error_explainability_contract(分层原因码冻结集);state_machine.py 引用 CP_*/PH_*/RS_*。
逻辑:tools.py、tool_response、workspace API 统一读本模块,避免 checkpoint id 漂移;
细粒度 reason_code 以 error_explainability_contract 为准,本文件仅再导出。
""" """
from __future__ import annotations from __future__ import annotations
from app.services.shipping_notice.error_explainability_contract import (
ATTACHMENT_REASON_CODES,
ATTACHMENT_REASON_CODES_EMITTED,
DOCUMENT_PARSE_REASON_CODES,
DOCUMENT_PARSE_REASON_CODES_EMITTED,
ERROR_EXPLAINABILITY_CONTRACT_VERSION,
EXCEL_UPLOAD_REASON_CODES,
EXCEL_UPLOAD_REASON_CODES_EMITTED,
INVENTORY_MATCH_REASON_CODES,
INVENTORY_MATCH_REASON_CODES_EMITTED,
INVENTORY_PREP_REASON_CODES,
INVENTORY_PREP_REASON_CODES_EMITTED,
INVENTORY_SOURCE_LINE_BLOCK_REASON_CODES,
INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES,
ORDER_BUILD_REASON_CODES,
ORDER_BUILD_REASON_CODES_EMITTED,
ORDER_FIELD_REASON_CODES,
ORDER_FIELD_REASON_CODES_EMITTED,
TASK_CLOSE_REASON_CODES,
TASK_CLOSE_REASON_CODES_EMITTED,
UNKNOWN_BUSINESS_FAILURE_REASON_CODE,
)
# Workspace / Hxops chat fallback only — Dify 正式路径不直接调用主推进 Tool;人工确认后由后端 worker 续跑 # Workspace / Hxops chat fallback only — Dify 正式路径不直接调用主推进 Tool;人工确认后由后端 worker 续跑
AUTO_CHAIN_FALLBACK = "auto_chain_fallback" AUTO_CHAIN_FALLBACK = "auto_chain_fallback"
@@ -53,3 +78,64 @@ PH_NOTICE_TEXT_EXTRACTION_FAILED = CP_NOTICE_TEXT_EXTRACTION_FAILED
PH_UPLOAD_RPA_FAILED = "upload_rpa_failed" PH_UPLOAD_RPA_FAILED = "upload_rpa_failed"
PH_UPLOAD_RPA_PENDING = "upload_rpa_pending" PH_UPLOAD_RPA_PENDING = "upload_rpa_pending"
PH_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown" PH_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
# 错误可解释性契约再导出(阶段 0 冻结;接线见 error_explainability_contract / 契约文档)
__all__ = (
'AUTO_CHAIN_FALLBACK',
'CP_UPLOAD_REQ',
'CP_PARSE_OK',
'CP_PARSE_REVIEW',
'CP_CUSTOMER_REVIEW',
'CP_TASK_EXISTS',
'CP_RSV_REQ',
'CP_UPLOAD_FAILED',
'CP_UPLOAD_RESULT_UNKNOWN',
'CP_WAITING_UPLOAD',
'CP_REJECTED',
'CP_INVENTORY_PENDING',
'CP_READY_MATCH',
'CP_READY_EXPORT',
'CP_EXPORT_READY',
'CP_NOTICE_TEXT_EXTRACTION_FAILED',
'CP_INVENTORY_SOURCE_REVIEW',
'CP_ORDER_FREEZE',
'CP_EXPORT_GENERATED',
'CP_UPLOADED',
'CP_COMPLETED',
'RS_PARSE_REVIEW',
'RS_SHORTAGE_REVIEW',
'RS_RSV_REQ',
'RS_REJECTED',
'RS_CONFIRMED',
'PH_LOW_CONF',
'PH_RSV_REQ',
'PH_SHORTAGE',
'PH_RPA_EXHAUSTED',
'PH_RPA_PENDING',
'PH_INV_UNAVAIL',
'PH_INVENTORY_SOURCE_UNRESOLVED',
'PH_NOTICE_TEXT_EXTRACTION_FAILED',
'PH_UPLOAD_RPA_FAILED',
'PH_UPLOAD_RPA_PENDING',
'PH_UPLOAD_RESULT_UNKNOWN',
'ERROR_EXPLAINABILITY_CONTRACT_VERSION',
'UNKNOWN_BUSINESS_FAILURE_REASON_CODE',
'ATTACHMENT_REASON_CODES',
'ATTACHMENT_REASON_CODES_EMITTED',
'DOCUMENT_PARSE_REASON_CODES',
'DOCUMENT_PARSE_REASON_CODES_EMITTED',
'ORDER_FIELD_REASON_CODES',
'ORDER_FIELD_REASON_CODES_EMITTED',
'ORDER_BUILD_REASON_CODES',
'ORDER_BUILD_REASON_CODES_EMITTED',
'INVENTORY_SOURCE_LINE_BLOCK_REASON_CODES',
'INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES',
'INVENTORY_PREP_REASON_CODES',
'INVENTORY_PREP_REASON_CODES_EMITTED',
'INVENTORY_MATCH_REASON_CODES',
'INVENTORY_MATCH_REASON_CODES_EMITTED',
'EXCEL_UPLOAD_REASON_CODES',
'EXCEL_UPLOAD_REASON_CODES_EMITTED',
'TASK_CLOSE_REASON_CODES',
'TASK_CLOSE_REASON_CODES_EMITTED',
)
@@ -2,8 +2,10 @@
services/shipping_notice/decision_workflow.py services/shipping_notice/decision_workflow.py
用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配和重解析。 用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配和重解析。
依赖:state_machine、tool_response、query_service、库存源 Gate、fulfillment_workflow、动态订单字段编辑器。 依赖:state_machine、tool_response、query_service、库存源 Gate、fulfillment_workflow、
逻辑:由 task_workflow 对外转调本文件;本文件在当前任务上下文内执行决策分支,并在必要时回调后端 orchestrator。 tool_common(操作人/生命周期快照)、fulfillment_audit。
逻辑:由 task_workflow / workspace API 转调;决策事件必须带操作人与前后快照,
reject/close/confirm 同步写入 ShippingAuditEvent。
""" """
from __future__ import annotations from __future__ import annotations
@@ -38,6 +40,8 @@ from app.services.shipping_notice.tool_common import (
log_task_event, log_task_event,
merge_tool_payload, merge_tool_payload,
payload_wants_auto_chain_fallback, payload_wants_auto_chain_fallback,
resolve_workspace_actor_id,
task_lifecycle_audit_snapshot,
prepend_tool_message, prepend_tool_message,
) )
from app.services.shipping_notice.tool_response import tool_response from app.services.shipping_notice.tool_response import tool_response
@@ -90,9 +94,10 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。 提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。
【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“重新上传库存”“关闭任务”等决策类指令时调用。 【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“重新上传库存”“关闭任务”等决策类指令时调用。
核心逻辑:先解析 decision,再按状态机规则分发到解析确认、库存重置、重匹配或重解析等分支;rematch 会同步调用 match_inventory 完成重算。 核心逻辑:先解析 decision,再按状态机规则分发到解析确认、库存重置、重匹配或重解析等分支;
rematch 会同步调用 match_inventory 完成重算;工作台入口须注入 operator_id 以保证审计非匿名。
Args: Args:
payload: 必须包含任务定位信息与 decision,可选 comment、lang 等上下文。 payload: 必须包含任务定位信息与 decision;可选 comment、lang、operator_id/actor_id。
Returns: Returns:
dict[str, Any]: Tool 标准响应,返回决策后的任务阶段和下一步动作。 dict[str, Any]: Tool 标准响应,返回决策后的任务阶段和下一步动作。
@@ -108,6 +113,8 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
comment = str(payload.get("comment") or "").strip() comment = str(payload.get("comment") or "").strip()
lang = resolve_lang(payload) lang = resolve_lang(payload)
event_source = str(payload.get("event_source") or "").strip() or "decision_workflow" event_source = str(payload.get("event_source") or "").strip() or "decision_workflow"
actor_id = resolve_workspace_actor_id(payload)
before_snapshot = task_lifecycle_audit_snapshot(task)
# Published parsing profiles are the only production mapping contract. # Published parsing profiles are the only production mapping contract.
# Reject legacy task-level mapping decisions instead of reopening a manual # Reject legacy task-level mapping decisions instead of reopening a manual
@@ -128,6 +135,9 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
action="reparse_inventory", action="reparse_inventory",
source=event_source, source=event_source,
comment=comment, comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
) )
db.session.commit() db.session.commit()
return tool_response( return tool_response(
@@ -144,12 +154,16 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
# reject / close 会直接结束当前任务,不再继续进入库存或出货链路。 # reject / close 会直接结束当前任务,不再继续进入库存或出货链路。
if decision == "reject": if decision == "reject":
apply_task_transition(task, TaskTransition.REJECTED) apply_task_transition(task, TaskTransition.REJECTED)
after_snapshot = task_lifecycle_audit_snapshot(task)
log_task_action_event( log_task_action_event(
task, task,
"decision_rejected", "decision_rejected",
action="reject", action="reject",
source=event_source, source=event_source,
comment=comment, comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=after_snapshot,
) )
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit( record_fulfillment_audit(
@@ -157,11 +171,12 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
aggregate_type='shipping_task', aggregate_type='shipping_task',
aggregate_id=task.task_no, aggregate_id=task.task_no,
action='reject', action='reject',
actor_id=payload.get('user_id') or payload.get('actor_id'), actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=task.task_no, task_no=task.task_no,
conversation_id=task.conversation_id, conversation_id=task.conversation_id,
before={'status': 'active'}, before=before_snapshot or {'status': 'active'},
after={'status': 'rejected'}, after=after_snapshot or {'status': 'rejected'},
metadata={'decision': 'reject'}, metadata={'decision': 'reject'},
source=event_source, source=event_source,
) )
@@ -175,12 +190,16 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
if decision in {"close", "closed"}: if decision in {"close", "closed"}:
apply_task_transition(task, TaskTransition.CLOSED) apply_task_transition(task, TaskTransition.CLOSED)
after_snapshot = task_lifecycle_audit_snapshot(task)
log_task_action_event( log_task_action_event(
task, task,
"decision_closed", "decision_closed",
action="close", action="close",
source=event_source, source=event_source,
comment=comment, comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=after_snapshot,
) )
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit( record_fulfillment_audit(
@@ -188,11 +207,12 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
aggregate_type='shipping_task', aggregate_type='shipping_task',
aggregate_id=task.task_no, aggregate_id=task.task_no,
action='close', action='close',
actor_id=payload.get('user_id') or payload.get('actor_id'), actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=task.task_no, task_no=task.task_no,
conversation_id=task.conversation_id, conversation_id=task.conversation_id,
before={'status': 'active'}, before=before_snapshot or {'status': 'active'},
after={'status': 'closed'}, after=after_snapshot or {'status': 'closed'},
metadata={'decision': 'close'}, metadata={'decision': 'close'},
source=event_source, source=event_source,
) )
@@ -267,12 +287,31 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
task.match_status = None task.match_status = None
task.shortage_json = None task.shortage_json = None
task.line_results_json = None task.line_results_json = None
after_snapshot = task_lifecycle_audit_snapshot(task)
log_task_action_event( log_task_action_event(
task, task,
"parse_confirmed", "parse_confirmed",
action="confirm", action="confirm",
source=event_source, source=event_source,
comment=comment, comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=after_snapshot,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_decision',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='confirm_parse',
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=task.task_no,
conversation_id=task.conversation_id,
before=before_snapshot,
after=after_snapshot,
metadata={'decision': decision},
source=event_source,
) )
db.session.commit() db.session.commit()
if not is_inventory_source_stable(task): if not is_inventory_source_stable(task):
@@ -316,12 +355,31 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
if match_completed(task): if match_completed(task):
apply_task_transition(task, TaskTransition.CONFIRM_MATCHED) apply_task_transition(task, TaskTransition.CONFIRM_MATCHED)
after_snapshot = task_lifecycle_audit_snapshot(task)
log_task_action_event( log_task_action_event(
task, task,
"decision_confirmed", "decision_confirmed",
action="confirm", action="confirm",
source=event_source, source=event_source,
comment=comment, comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=after_snapshot,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_decision',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='confirm_matched',
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=task.task_no,
conversation_id=task.conversation_id,
before=before_snapshot,
after=after_snapshot,
metadata={'decision': decision},
source=event_source,
) )
db.session.commit() db.session.commit()
return tool_response( return tool_response(
@@ -367,6 +425,10 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
task, task,
"decision_retry_rpa", "decision_retry_rpa",
{"comment": comment, "force_refresh": True}, {"comment": comment, "force_refresh": True},
actor_id=actor_id,
source=event_source,
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
) )
db.session.flush() db.session.flush()
retry_payload = merge_tool_payload( retry_payload = merge_tool_payload(
@@ -387,6 +449,9 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
action="rematch", action="rematch",
source=event_source, source=event_source,
comment=comment, comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
) )
# flush 即可:清状态与 match_inventory 的最终 commit 同属一次连续写入,避免中间态落库。 # flush 即可:清状态与 match_inventory 的最终 commit 同属一次连续写入,避免中间态落库。
db.session.flush() db.session.flush()
@@ -417,6 +482,9 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
log_task_action_event( log_task_action_event(
task, "notice_reparse_requested", action="reparse", source=event_source, comment=comment, task, "notice_reparse_requested", action="reparse", source=event_source, comment=comment,
extra={"source_run_no": run.run_no, "replacement_run_no": replacement.run_no, "reused": reused}, extra={"source_run_no": run.run_no, "replacement_run_no": replacement.run_no, "reused": reused},
actor_id=actor_id,
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
) )
db.session.commit() db.session.commit()
return tool_response( return tool_response(
@@ -64,6 +64,7 @@ from app.services.shipping_notice.document_layout.ocr_pdf import (
OcrTableEvidence, OcrTableEvidence,
build_ocr_table_evidence, build_ocr_table_evidence,
extract_ocr_lines, extract_ocr_lines,
page_bbox_to_normalized,
) )
from app.services.shipping_notice.document_layout.schema_mapping import ( from app.services.shipping_notice.document_layout.schema_mapping import (
layout_table_to_grid, layout_table_to_grid,
@@ -104,6 +105,7 @@ __all__ = [
'OcrTableEvidence', 'OcrTableEvidence',
'build_ocr_table_evidence', 'build_ocr_table_evidence',
'extract_ocr_lines', 'extract_ocr_lines',
'page_bbox_to_normalized',
'layout_table_to_grid', 'layout_table_to_grid',
'map_layout_document_to_schema', 'map_layout_document_to_schema',
'align_html_cells_from_positioned_text', 'align_html_cells_from_positioned_text',
@@ -0,0 +1,110 @@
"""
backend/app/services/shipping_notice/document_layout/cell_coordinate_status.py
用途:阶段 3 — 按 cell 来源分级坐标质量,供 Schema 映射与复核高亮投影共用。
依赖:field_highlight_contract 冻结枚举(逻辑对齐,不反向依赖布局解析)。
逻辑:原生唯一 glyph → verified 候选;OCR/OpenCV → candidate;仅 HTML 行列 → unavailable;
禁止跨页合并 bbox(由调用方保证单页绑定)。
"""
from __future__ import annotations
from typing import Any, Literal
CellCoordinateStatus = Literal['verified', 'candidate', 'unavailable', 'invalid']
# 高风险字段:坐标错绑代价最高,OpenCV/OCR 路径必须文本独立验收(由上游保证)。
HIGH_RISK_FIELD_CODES: frozenset[str] = frozenset({
'part_number',
'customer_part_number',
'qty',
'reservation_id',
})
def classify_cell_coordinate_status(
*,
source: str | None,
has_bbox: bool,
has_token_ids: bool,
confidence: float | None = None,
field_code: str | None = None,
) -> dict[str, Any]:
"""
按来源与证据完备性裁决 cell/字段坐标状态。
Args:
source: native_text / native_glyph / ocr / html / opencv 等。
has_bbox: 是否已有可绘制几何。
has_token_ids: 是否绑定 token/glyph。
confidence: 可选置信度。
field_code: 可选字段码;高风险字段在证据不足时更严。
Returns:
highlight_quality / coordinate_status / highlight_source / coordinate_issue_codes。
"""
normalized_source = str(source or '').strip().lower()
conf = float(confidence if confidence is not None else 0)
high_risk = str(field_code or '').strip() in HIGH_RISK_FIELD_CODES
if normalized_source in {'html', 'html_only'} or (not has_bbox and not has_token_ids):
return {
'highlight_quality': 'unavailable',
'coordinate_status': 'unavailable',
'highlight_source': 'unknown' if not normalized_source else 'machine_extraction',
'coordinate_issue_codes': ['html_only_no_pdf_bbox'] if normalized_source.startswith('html') or not has_bbox else ['cell_token_unbound'],
}
if not has_bbox:
return {
'highlight_quality': 'unavailable',
'coordinate_status': 'unavailable',
'highlight_source': 'native_glyph' if 'native' in normalized_source else 'ocr' if 'ocr' in normalized_source else 'machine_extraction',
'coordinate_issue_codes': ['coordinate_missing'],
}
if normalized_source in {'native_text', 'native_glyph', 'pdfium'} and has_token_ids and conf >= 1.0:
return {
'highlight_quality': 'verified',
'coordinate_status': 'verified',
'highlight_source': 'native_glyph',
'coordinate_issue_codes': [],
}
if 'ocr' in normalized_source:
if conf < 0.8:
return {
'highlight_quality': 'unavailable',
'coordinate_status': 'unavailable',
'highlight_source': 'ocr',
'coordinate_issue_codes': ['ocr_confidence_insufficient'],
}
return {
'highlight_quality': 'candidate',
'coordinate_status': 'candidate',
'highlight_source': 'ocr',
'coordinate_issue_codes': [],
}
# OpenCV 几何共识 + 文本验收后仍只给 candidate;高风险缺 token 直接不可用
if 'opencv' in normalized_source or (normalized_source == 'native_text' and not has_token_ids):
if high_risk and not has_token_ids:
return {
'highlight_quality': 'unavailable',
'coordinate_status': 'unavailable',
'highlight_source': 'pdf_coordinate',
'coordinate_issue_codes': ['cell_token_unbound'],
}
return {
'highlight_quality': 'candidate',
'coordinate_status': 'candidate',
'highlight_source': 'pdf_coordinate',
'coordinate_issue_codes': [],
}
return {
'highlight_quality': 'candidate' if has_bbox else 'unavailable',
'coordinate_status': 'candidate' if has_bbox else 'unavailable',
'highlight_source': 'pdf_coordinate',
'coordinate_issue_codes': [] if has_bbox else ['coordinate_missing'],
}
@@ -2,8 +2,10 @@
backend/app/services/shipping_notice/document_layout/contracts.py backend/app/services/shipping_notice/document_layout/contracts.py
用途:定义解析器无关的 shipping_document_layout.v1 契约、稳定标识和完整性校验。 用途:定义解析器无关的 shipping_document_layout.v1 契约、稳定标识和完整性校验。
依赖:Pydantic 2、标准库 hashlib/json/unicodedata。 依赖:Pydantic 2、标准库 hashlib/json/unicodedata;字段高亮质量枚举与
逻辑:PDF/OCR/HTML 解析器先构造 LayoutDocument;持久化、Schema 映射和评测只接受通过本模块校验的结果。 field_highlight_contract 对齐(本模块只声明可挂载到 LayoutCell 的状态字面量)。
逻辑:PDF/OCR/HTML 解析器先构造 LayoutDocument;持久化、Schema 映射和评测只接受通过
本模块校验的结果;复核高亮投影消费 cell/token 坐标,但不在本契约内裁决绘制质量。
""" """
from __future__ import annotations from __future__ import annotations
@@ -18,6 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida
LAYOUT_SCHEMA_VERSION = 'shipping_document_layout.v1' LAYOUT_SCHEMA_VERSION = 'shipping_document_layout.v1'
# 与 field_highlight_contract.HIGHLIGHT_QUALITY_VALUES 对齐;Cell 可选挂载,禁止自创同义状态。
LAYOUT_COORDINATE_STATUS = Literal['verified', 'candidate', 'unavailable', 'invalid']
_ID_PART_RE = re.compile(r'[^a-z0-9._-]+') _ID_PART_RE = re.compile(r'[^a-z0-9._-]+')
@@ -114,6 +118,8 @@ class LayoutCell(LayoutContractModel):
source: Literal['native_text', 'ocr', 'html'] source: Literal['native_text', 'ocr', 'html']
confidence: float = Field(ge=0, le=1) confidence: float = Field(ge=0, le=1)
role: Literal['header', 'data', 'summary', 'deleted', 'footer', 'unknown'] role: Literal['header', 'data', 'summary', 'deleted', 'footer', 'unknown']
# coordinate_status 不挂载到 Cell 模型,避免改变冻结布局 checksum;
# 运行时分级见 cell_coordinate_status.classify_cell_coordinate_status(阶段 3)。
@model_validator(mode='after') @model_validator(mode='after')
def validate_text_and_tokens(self) -> 'LayoutCell': def validate_text_and_tokens(self) -> 'LayoutCell':
@@ -171,6 +171,48 @@ def canonical_layout_payload(payload: dict[str, Any]) -> tuple[str, int]:
return hashlib.sha256(encoded).hexdigest(), len(encoded) return hashlib.sha256(encoded).hexdigest(), len(encoded)
def _fit_layout_payload_to_budget(
payload: dict[str, Any], *, max_bytes: int,
) -> tuple[dict[str, Any] | None, list[str], int]:
"""按证据优先级压缩布局快照,避免可重建证据阻断业务表保存。
核心逻辑:表格 HTML/结构是模板建模的核心;整页 glyph、文本块和页面尺寸
属于可选证据。压缩过程只删除可重建字段,并返回最终大小与诊断码。
"""
candidate = json.loads(json.dumps(payload, ensure_ascii=True))
issues: list[str] = []
_, size = canonical_layout_payload(candidate)
if size <= max_bytes:
return candidate, issues, size
evidence = candidate.get('coordinate_evidence')
if isinstance(evidence, dict):
if evidence.pop('page_glyphs', None) is not None:
issues.append('shipping_document_layout_page_glyphs_compacted')
if evidence.pop('pages', None) is not None:
issues.append('shipping_document_layout_page_metadata_compacted')
_, size = canonical_layout_payload(candidate)
if size <= max_bytes:
return candidate, issues, size
if candidate.pop('text_blocks', None) is not None:
issues.append('shipping_document_layout_text_blocks_compacted')
_, size = canonical_layout_payload(candidate)
if size <= max_bytes:
return candidate, issues, size
layout_candidate = candidate.get('layout_candidate')
if isinstance(layout_candidate, dict):
if layout_candidate.pop('page_glyphs', None) is not None:
issues.append('shipping_document_layout_candidate_glyphs_compacted')
if layout_candidate.pop('pages', None) is not None:
issues.append('shipping_document_layout_candidate_page_metadata_compacted')
_, size = canonical_layout_payload(candidate)
if size <= max_bytes:
return candidate, issues, size
return None, issues + ['shipping_document_layout_snapshot_size_exceeded'], size
def current_layout_snapshot(document: ShippingNoticeDocument) -> dict[str, Any] | None: def current_layout_snapshot(document: ShippingNoticeDocument) -> dict[str, Any] | None:
"""读取 Document 当前可用冻结 payload;失败历史版本永不作为运行输入。""" """读取 Document 当前可用冻结 payload;失败历史版本永不作为运行输入。"""
version = document.current_layout_version version = document.current_layout_version
@@ -196,7 +238,14 @@ def record_inline_layout_snapshot(
""" """
payload = dict(snapshot) payload = dict(snapshot)
parser_key = str(parser_key or current_layout_parser_key()) parser_key = str(parser_key or current_layout_parser_key())
checksum, payload_size = canonical_layout_payload(payload) max_bytes = max(int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000,
)), 1)
fitted_payload, compact_issues, payload_size = _fit_layout_payload_to_budget(
payload, max_bytes=max_bytes,
)
stored_for_identity = fitted_payload if fitted_payload is not None else payload
checksum, _ = canonical_layout_payload(stored_for_identity)
source_hash = str(document.content_hash or '').strip().lower() source_hash = str(document.content_hash or '').strip().lower()
if len(source_hash) != 64: if len(source_hash) != 64:
source_hash = hashlib.sha256( source_hash = hashlib.sha256(
@@ -226,15 +275,10 @@ def record_inline_layout_snapshot(
status = provider_status if provider_status in { status = provider_status if provider_status in {
'ready', 'needs_review', 'failed', 'unsupported', 'ready', 'needs_review', 'failed', 'unsupported',
} else 'failed' } else 'failed'
max_bytes = max(int(current_app.config.get( issues = sorted({str(item) for item in (payload.get('issues') or []) if str(item)} | set(compact_issues))
'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000, stored_payload: dict[str, Any] | None = fitted_payload
)), 1) if stored_payload is None:
issues = sorted({str(item) for item in (payload.get('issues') or []) if str(item)})
stored_payload: dict[str, Any] | None = payload
if payload_size > max_bytes:
status = 'failed' status = 'failed'
stored_payload = None
issues.append('shipping_document_layout_snapshot_size_exceeded')
version = ShippingDocumentLayoutVersion( version = ShippingDocumentLayoutVersion(
document_id=int(document.id), document_id=int(document.id),
version=version_no, version=version_no,
@@ -536,18 +580,20 @@ def complete_layout_version(
if version is None or version.status != 'running' or version.lease_token != lease_token: if version is None or version.status != 'running' or version.lease_token != lease_token:
db.session.rollback() db.session.rollback()
return False return False
checksum, payload_size = canonical_layout_payload(snapshot)
max_bytes = max(int(current_app.config.get( max_bytes = max(int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000, 'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000,
)), 1) )), 1)
issues = sorted({str(item) for item in (snapshot.get('issues') or []) if str(item)}) fitted_snapshot, compact_issues, payload_size = _fit_layout_payload_to_budget(
snapshot, max_bytes=max_bytes,
)
stored_for_identity = fitted_snapshot if fitted_snapshot is not None else snapshot
checksum, _ = canonical_layout_payload(stored_for_identity)
issues = sorted({str(item) for item in (snapshot.get('issues') or []) if str(item)} | set(compact_issues))
provider_status = str(snapshot.get('status') or 'failed') provider_status = str(snapshot.get('status') or 'failed')
status = provider_status if provider_status in TERMINAL_LAYOUT_STATUSES else 'failed' status = provider_status if provider_status in TERMINAL_LAYOUT_STATUSES else 'failed'
stored_payload: dict[str, Any] | None = dict(snapshot) stored_payload: dict[str, Any] | None = fitted_snapshot
if payload_size > max_bytes: if stored_payload is None:
status = 'failed' status = 'failed'
stored_payload = None
issues.append('shipping_document_layout_snapshot_size_exceeded')
now = datetime.utcnow() now = datetime.utcnow()
version.status = status version.status = status
version.parser_version = str(snapshot.get('provider_version') or '')[:64] or None version.parser_version = str(snapshot.get('provider_version') or '')[:64] or None
@@ -3,7 +3,8 @@ backend/app/services/shipping_notice/document_layout/native_pdf.py
用途:用项目既有 PDFium 提取原生 PDF 字符坐标、页面渲染,并组装保守的 layout.v1 表格候选。 用途:用项目既有 PDFium 提取原生 PDF 字符坐标、页面渲染,并组装保守的 layout.v1 表格候选。
依赖:pypdfium2、MinerU 页面/HTML 候选、OpenCV 网格、严格文本对齐和布局契约。 依赖:pypdfium2、MinerU 页面/HTML 候选、OpenCV 网格、严格文本对齐和布局契约。
逻辑:MinerU 提供整表与 HTML;PDFium提供独立字符/图像证据;只有严格匹配的 cell 才写入候选,整体仍固定 needs_review。 逻辑:MinerU 提供整表与 HTML;PDFium 提供独立字符/图像证据;阶段 1 优先唯一 glyph
对齐写入真实 cell bbox/token;部分唯一匹配可落盘;整体 layout 仍可 needs_review。
""" """
from __future__ import annotations from __future__ import annotations
@@ -100,6 +101,7 @@ def extract_native_pdf_pages(
if right <= left or top <= bottom: if right <= left or top <= bottom:
continue continue
try: try:
# 不修改 PDFium 原始坐标;仅转为左上原点页面坐标。
characters.append(PositionedCharacter( characters.append(PositionedCharacter(
text=text, text=text,
bbox=LayoutBBox( bbox=LayoutBBox(
@@ -109,6 +111,7 @@ def extract_native_pdf_pages(
)) ))
except ValueError: except ValueError:
continue continue
characters = _assign_page_line_ids(characters, page_no=page_index + 1)
rotation = int(getattr(page, 'get_rotation', lambda: 0)() or 0) % 360 rotation = int(getattr(page, 'get_rotation', lambda: 0)() or 0) % 360
pages.append(NativePdfPage( pages.append(NativePdfPage(
page_no=page_index + 1, page_no=page_index + 1,
@@ -391,15 +394,10 @@ def build_native_pdf_layout_candidate(
) )
def _candidate_cells( def _cells_from_text_alignment(
*, native: NativePdfPage, grid: HtmlGrid, table_bbox: LayoutBBox, *, native: NativePdfPage, alignment: Any,
) -> tuple[dict[str, dict[str, Any]], list[str]]: ) -> dict[str, dict[str, Any]]:
"""优先唯一文本对齐,失败后仅对严格有框表使用 OpenCV 双门禁。""" """将唯一 glyph 对齐结果转为 cell 证据;保留 status 供高亮契约投影。"""
alignment = align_html_cells_from_positioned_text(
grid, characters=native.characters, table_bbox=table_bbox,
page_width=native.width, page_height=native.height,
)
if alignment.complete:
return { return {
item.cell_id: { item.cell_id: {
'bbox': item.bbox, 'bbox': item.bbox,
@@ -407,12 +405,36 @@ def _candidate_cells(
_native_layout_token(native=native, glyph_index=index, content_hash='pending') _native_layout_token(native=native, glyph_index=index, content_hash='pending')
for index in item.glyph_indices for index in item.glyph_indices
], ],
'source': 'native_text', 'confidence': 1, 'source': 'native_text',
'confidence': 1.0 if item.status == 'verified' else 0.8,
'highlight_quality': item.status,
'line_id': item.line_id,
} }
for item in alignment.cells for item in alignment.cells
}, ['native_pdf_cells_from_unique_text_candidate'] }
def _candidate_cells(
*, native: NativePdfPage, grid: HtmlGrid, table_bbox: LayoutBBox,
) -> tuple[dict[str, dict[str, Any]], list[str]]:
"""
优先唯一文本对齐;完整失败时有框表才走 OpenCV;快速路径允许部分唯一匹配落盘。
核心逻辑:禁止在多候选重复文本上猜第 N 个;OpenCV 全表失败时回退已对齐的部分 native cell。
"""
alignment = align_html_cells_from_positioned_text(
grid, characters=native.characters, table_bbox=table_bbox,
page_width=native.width, page_height=native.height,
)
text_cells = _cells_from_text_alignment(native=native, alignment=alignment)
if alignment.complete and text_cells:
return text_cells, ['native_pdf_cells_from_unique_text_candidate']
if native.image is None: if native.image is None:
# 快速路径只允许原生文字的严格唯一对齐;不足时由调用方回退完整 MinerU/图像链路。 # 快速路径:部分唯一匹配仍可写入,供复核高亮;不足时由调用方回退 MinerU/图像链路。
if text_cells:
return text_cells, sorted(set(
list(alignment.issues) + ['native_pdf_cells_from_partial_unique_text'],
))
return {}, sorted(set(alignment.issues + ['native_pdf_render_deferred'])) return {}, sorted(set(alignment.issues + ['native_pdf_render_deferred']))
geometry = reconstruct_opencv_table_geometry( geometry = reconstruct_opencv_table_geometry(
native.image, page_width=native.width, page_height=native.height, native.image, page_width=native.width, page_height=native.height,
@@ -430,6 +452,11 @@ def _candidate_cells(
table_bbox=table_bbox, grid=grid, table_bbox=table_bbox, grid=grid,
) )
if not ocr.ready: if not ocr.ready:
if text_cells:
return text_cells, sorted(set(
alignment.issues + geometry.issues + validation.issues + ocr.issues
+ ['native_pdf_cells_from_partial_unique_text'],
))
return {}, sorted(set( return {}, sorted(set(
alignment.issues + geometry.issues + validation.issues + ocr.issues, alignment.issues + geometry.issues + validation.issues + ocr.issues,
)) ))
@@ -447,6 +474,7 @@ def _candidate_cells(
'confidence': min( 'confidence': min(
(ocr_lines[index].confidence for index in item.line_indices), default=0, (ocr_lines[index].confidence for index in item.line_indices), default=0,
), ),
'highlight_quality': 'candidate',
} }
for item in ocr.cells for item in ocr.cells
}, ['ocr_pdf_cells_from_grid_candidate'] }, ['ocr_pdf_cells_from_grid_candidate']
@@ -455,6 +483,10 @@ def _candidate_cells(
indices = _glyph_indices_within(native.characters, item.bbox) indices = _glyph_indices_within(native.characters, item.bbox)
expected = next(cell for cell in grid.cells if cell.cell_id == item.cell_id) expected = next(cell for cell in grid.cells if cell.cell_id == item.cell_id)
if expected.text.strip() and not indices: if expected.text.strip() and not indices:
if text_cells:
return text_cells, sorted(set(
alignment.issues + ['native_pdf_opencv_cell_tokens_missing', 'native_pdf_cells_from_partial_unique_text'],
))
return {}, ['native_pdf_opencv_cell_tokens_missing'] return {}, ['native_pdf_opencv_cell_tokens_missing']
cells[item.cell_id] = { cells[item.cell_id] = {
'bbox': item.bbox, 'bbox': item.bbox,
@@ -462,13 +494,16 @@ def _candidate_cells(
_native_layout_token(native=native, glyph_index=index, content_hash='pending') _native_layout_token(native=native, glyph_index=index, content_hash='pending')
for index in indices for index in indices
], ],
'source': 'native_text', 'confidence': 1, 'source': 'native_text',
# OpenCV 路径置信度不满 1.0,防止被分级为 verified(阶段 3)。
'confidence': 0.95,
'highlight_quality': 'candidate',
} }
return cells, ['native_pdf_cells_from_opencv_candidate'] return cells, ['native_pdf_cells_from_opencv_candidate']
def _native_layout_token(*, native: NativePdfPage, glyph_index: int, content_hash: str) -> LayoutToken: def _native_layout_token(*, native: NativePdfPage, glyph_index: int, content_hash: str) -> LayoutToken:
"""把表格区域内单个 PDF glyph 转为稳定、可引用的 LayoutToken。""" """把表格区域内单个 PDF glyph 转为稳定、可引用的 LayoutToken(含视觉行 ID)。"""
glyph = native.characters[glyph_index] glyph = native.characters[glyph_index]
return LayoutToken( return LayoutToken(
token_id=stable_layout_id('token', content_hash, native.page_no, glyph_index), token_id=stable_layout_id('token', content_hash, native.page_no, glyph_index),
@@ -476,7 +511,7 @@ def _native_layout_token(*, native: NativePdfPage, glyph_index: int, content_has
normalized_text=normalize_layout_text(glyph.text), normalized_text=normalize_layout_text(glyph.text),
bbox=glyph.bbox, bbox=glyph.bbox,
normalized_bbox=_normalized_bbox(glyph.bbox, native.width, native.height), normalized_bbox=_normalized_bbox(glyph.bbox, native.width, native.height),
source='native_text', confidence=1, line_id=None, source='native_text', confidence=1, line_id=glyph.line_id,
) )
@@ -488,7 +523,9 @@ def _ocr_layout_token(*, native: NativePdfPage, line: Any, line_index: int) -> L
normalized_text=normalize_layout_text(line.text), normalized_text=normalize_layout_text(line.text),
bbox=line.bbox, bbox=line.bbox,
normalized_bbox=_normalized_bbox(line.bbox, native.width, native.height), normalized_bbox=_normalized_bbox(line.bbox, native.width, native.height),
source='ocr', confidence=line.confidence, line_id=None, source='ocr',
confidence=line.confidence,
line_id=str(getattr(line, 'line_id', None) or f'ocr-line-{line_index}'),
) )
@@ -496,10 +533,17 @@ def _layout_table(
*, native: NativePdfPage, grid: HtmlGrid, table_bbox: LayoutBBox, content_hash: str, *, native: NativePdfPage, grid: HtmlGrid, table_bbox: LayoutBBox, content_hash: str,
table_index: int, cells: dict[str, dict[str, Any]], page_tokens: dict[str, LayoutToken], table_index: int, cells: dict[str, dict[str, Any]], page_tokens: dict[str, LayoutToken],
) -> LayoutTable: ) -> LayoutTable:
"""按 HTML row/column/span 组装具有真实 bbox 和 token 引用的 needs_review 表格。""" """
按 HTML row/column/span 组装具有真实 bbox 和 token 引用的表格。
核心逻辑:仅写入已通过唯一对齐/OpenCV 门禁的 cell;缺失坐标的 cell 跳过,禁止均分猜框。
"""
rows: list[LayoutRow] = [] rows: list[LayoutRow] = []
for row_index in range(grid.row_count): for row_index in range(grid.row_count):
source_cells = [item for item in grid.cells if item.row_index == row_index] source_cells = [
item for item in grid.cells
if item.row_index == row_index and item.cell_id in cells
]
if not source_cells: if not source_cells:
continue continue
role = 'header' if source_cells and all(item.is_header for item in source_cells) else 'data' role = 'header' if source_cells and all(item.is_header for item in source_cells) else 'data'
@@ -528,12 +572,14 @@ def _layout_table(
bbox=evidence['bbox'], bbox=evidence['bbox'],
normalized_bbox=_normalized_bbox(evidence['bbox'], native.width, native.height), normalized_bbox=_normalized_bbox(evidence['bbox'], native.width, native.height),
token_ids=[token.token_id for token in tokens], token_ids=[token.token_id for token in tokens],
source=evidence['source'], confidence=evidence['confidence'], role=role, source=evidence['source'], confidence=float(evidence['confidence']), role=role,
)) ))
rows.append(LayoutRow( rows.append(LayoutRow(
row_id=stable_layout_id('row', content_hash, native.page_no, table_index, row_index), row_id=stable_layout_id('row', content_hash, native.page_no, table_index, row_index),
row_index=row_index, cells=layout_cells, role=role, row_index=row_index, cells=layout_cells, role=role,
)) ))
if not rows:
raise ValueError('layout table requires at least one resolved cell row')
return LayoutTable( return LayoutTable(
table_id=stable_layout_id('table', content_hash, native.page_no, table_index), table_id=stable_layout_id('table', content_hash, native.page_no, table_index),
bbox=table_bbox, bbox=table_bbox,
@@ -544,6 +590,44 @@ def _layout_table(
) )
def _assign_page_line_ids(
characters: list[PositionedCharacter], *, page_no: int,
) -> list[PositionedCharacter]:
"""
为页面 glyph 分配稳定视觉行 ID,供同行门禁与 token.line_id 使用。
核心逻辑:按 y 中心聚类;不改动原始 bbox。
"""
if not characters:
return characters
ordered = sorted(
enumerate(characters),
key=lambda pair: ((pair[1].bbox.y0 + pair[1].bbox.y1) / 2, pair[1].bbox.x0),
)
assigned: list[PositionedCharacter | None] = [None] * len(characters)
current_line: list[int] = []
current_center: float | None = None
line_seq = 0
for original_index, glyph in ordered:
center_y = (glyph.bbox.y0 + glyph.bbox.y1) / 2
if current_center is None or abs(center_y - current_center) > 3:
if current_line:
line_id = f'p{page_no}-vline-{line_seq}'
line_seq += 1
for index in current_line:
assigned[index] = characters[index].model_copy(update={'line_id': line_id})
current_line = [original_index]
current_center = center_y
else:
current_line.append(original_index)
current_center = (current_center * (len(current_line) - 1) + center_y) / len(current_line)
if current_line:
line_id = f'p{page_no}-vline-{line_seq}'
for index in current_line:
assigned[index] = characters[index].model_copy(update={'line_id': line_id})
return [item if item is not None else characters[index] for index, item in enumerate(assigned)]
def _glyph_indices_within(characters: list[PositionedCharacter], bbox: LayoutBBox) -> list[int]: def _glyph_indices_within(characters: list[PositionedCharacter], bbox: LayoutBBox) -> list[int]:
"""返回中心点落在 bbox 内的 glyph 索引,保持 PDF 文本顺序。""" """返回中心点落在 bbox 内的 glyph 索引,保持 PDF 文本顺序。"""
return [ return [
@@ -1,15 +1,16 @@
""" """
backend/app/services/shipping_notice/document_layout/ocr_pdf.py backend/app/services/shipping_notice/document_layout/ocr_pdf.py
用途:保留 RapidOCR 文本行多边形坐标,并为扫描 PDF 表格提供严格 cell 候选。 用途:保留 RapidOCR 文本行多边形坐标,并为扫描 PDF 表格提供严格 cell 候选(阶段 2)。
依赖:RapidOCR、OpenCV 网格、MinerU HTML、布局契约。 依赖:RapidOCR、OpenCV 网格、MinerU HTML、布局契约;高亮质量对齐 field_highlight_contract。
逻辑:OCR 只提供独立文本坐标;必须与多参数有框网格及全部非空 cell 文本一致才输出,结果仍需人工真值。 逻辑:OCR 只提供独立文本坐标与 candidate 级高亮;必须与多参数有框网格及全部非空 cell
文本一致才输出;OCR 结果不得自动升为 verified。
""" """
from __future__ import annotations from __future__ import annotations
from functools import lru_cache from functools import lru_cache
from typing import Any from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field from pydantic import BaseModel, ConfigDict, Field
@@ -20,6 +21,11 @@ from app.services.shipping_notice.document_layout.opencv_table import (
validate_opencv_cell_text, validate_opencv_cell_text,
) )
# 与 field_highlight_contract 对齐。
OCR_CONFIDENCE_FLOOR = 0.8
ISSUE_OCR_CONFIDENCE = 'ocr_confidence_insufficient'
ISSUE_OCR_MULTI = 'ocr_multi_candidate'
class OcrLayoutModel(BaseModel): class OcrLayoutModel(BaseModel):
"""为 OCR 坐标结果启用严格字段校验。""" """为 OCR 坐标结果启用严格字段校验。"""
@@ -28,19 +34,26 @@ class OcrLayoutModel(BaseModel):
class OcrLine(OcrLayoutModel): class OcrLine(OcrLayoutModel):
"""保存一条 RapidOCR 文本行、页面坐标和置信度。""" """保存一条 RapidOCR 文本行、像素多边形、页面坐标、置信度与行 ID。"""
text: str = Field(min_length=1) text: str = Field(min_length=1)
bbox: LayoutBBox bbox: LayoutBBox
confidence: float = Field(ge=0, le=1) confidence: float = Field(ge=0, le=1)
line_id: str
polygon: list[list[float]] = Field(default_factory=list)
image_width: int = Field(ge=1)
image_height: int = Field(ge=1)
class OcrCellEvidence(OcrLayoutModel): class OcrCellEvidence(OcrLayoutModel):
"""保存经几何和文本双门禁确认的 OCR cell 候选。""" """保存经几何和文本双门禁确认的 OCR cell 候选;质量最高为 candidate。"""
cell_id: str cell_id: str
bbox: LayoutBBox bbox: LayoutBBox
normalized_bbox: LayoutBBox | None = None
line_indices: list[int] = Field(default_factory=list) line_indices: list[int] = Field(default_factory=list)
confidence: float = Field(default=0, ge=0, le=1)
status: Literal['candidate', 'unavailable', 'invalid'] = 'candidate'
class OcrTableEvidence(OcrLayoutModel): class OcrTableEvidence(OcrLayoutModel):
@@ -50,6 +63,8 @@ class OcrTableEvidence(OcrLayoutModel):
lines: list[OcrLine] = Field(default_factory=list) lines: list[OcrLine] = Field(default_factory=list)
cells: list[OcrCellEvidence] = Field(default_factory=list) cells: list[OcrCellEvidence] = Field(default_factory=list)
issues: list[str] = Field(default_factory=list) issues: list[str] = Field(default_factory=list)
image_width: int | None = None
image_height: int | None = None
@lru_cache(maxsize=1) @lru_cache(maxsize=1)
@@ -61,15 +76,18 @@ def _ocr_engine() -> Any:
def extract_ocr_lines( def extract_ocr_lines(
image: Any, *, page_width: float, page_height: float, minimum_confidence: float = 0.8, image: Any, *, page_width: float, page_height: float, minimum_confidence: float = OCR_CONFIDENCE_FLOOR,
) -> list[OcrLine]: ) -> list[OcrLine]:
""" """
将 RapidOCR 图像像素多边形映射为 PDF 页面坐标。 将 RapidOCR 图像像素多边形映射为 PDF 页面坐标。
核心逻辑:像素坐标 → 页面坐标(按渲染宽高比例);低置信度行丢弃;保留 polygon 供审计。
Args: Args:
image: PDFium 渲染的页面 ndarray。 image: PDFium 渲染的页面 ndarray。
page_width/page_height: PDF 页面单位尺寸。 page_width/page_height: PDF 页面单位尺寸。
minimum_confidence: OCR 行最低可信度;低于阈值完全丢弃。 minimum_confidence: OCR 行最低可信度;低于阈值完全丢弃。
Returns: Returns:
保持 OCR 返回顺序的文本行坐标。 保持 OCR 返回顺序的文本行坐标。
""" """
@@ -80,17 +98,21 @@ def extract_ocr_lines(
raise ValueError('OCR page dimensions must be positive') raise ValueError('OCR page dimensions must be positive')
result, _elapsed = _ocr_engine()(image) result, _elapsed = _ocr_engine()(image)
lines: list[OcrLine] = [] lines: list[OcrLine] = []
for item in result or []: for index, item in enumerate(result or []):
if len(item) < 3: if len(item) < 3:
continue continue
polygon, raw_text, raw_confidence = item[0], item[1], item[2] polygon, raw_text, raw_confidence = item[0], item[1], item[2]
text = str(raw_text or '').strip() text = str(raw_text or '').strip()
confidence = float(raw_confidence or 0) confidence = float(raw_confidence or 0)
if not text or not normalize_layout_text(text) or confidence < minimum_confidence: if not text or not normalize_layout_text(text):
continue
if confidence < minimum_confidence:
continue continue
try: try:
xs = [float(point[0]) for point in polygon] points = [[float(point[0]), float(point[1])] for point in polygon]
ys = [float(point[1]) for point in polygon] xs = [point[0] for point in points]
ys = [point[1] for point in points]
# 像素 → 页面坐标;不做额外平移猜测
bbox = LayoutBBox( bbox = LayoutBBox(
x0=min(xs) * page_width / width, x0=min(xs) * page_width / width,
y0=min(ys) * page_height / height, y0=min(ys) * page_height / height,
@@ -99,23 +121,68 @@ def extract_ocr_lines(
) )
if bbox.x1 > page_width or bbox.y1 > page_height: if bbox.x1 > page_width or bbox.y1 > page_height:
continue continue
lines.append(OcrLine(text=text, bbox=bbox, confidence=confidence)) lines.append(OcrLine(
text=text,
bbox=bbox,
confidence=confidence,
line_id=f'ocr-line-{index}',
polygon=points,
image_width=int(width),
image_height=int(height),
))
except (TypeError, ValueError, IndexError): except (TypeError, ValueError, IndexError):
continue continue
return lines return lines
def page_bbox_to_normalized(bbox: LayoutBBox, *, page_width: float, page_height: float) -> LayoutBBox:
"""
将页面坐标转为 0..1 归一化 bbox,供 PDF.js viewport 绘制。
Args:
bbox: 页面单位矩形。
page_width/page_height: 页面尺寸。
Returns:
归一化 LayoutBBox。
Raises:
ValueError: 页面尺寸非法或归一化结果越界。
"""
if page_width <= 0 or page_height <= 0:
raise ValueError('page dimensions must be positive')
normalized = LayoutBBox(
x0=bbox.x0 / page_width,
y0=bbox.y0 / page_height,
x1=bbox.x1 / page_width,
y1=bbox.y1 / page_height,
)
if normalized.x1 > 1 or normalized.y1 > 1 or normalized.x0 < 0 or normalized.y0 < 0:
raise ValueError('normalized OCR bbox must stay within 0..1')
return normalized
def build_ocr_table_evidence( def build_ocr_table_evidence(
*, image: Any, page_width: float, page_height: float, *, image: Any, page_width: float, page_height: float,
table_bbox: LayoutBBox, grid: HtmlGrid, table_bbox: LayoutBBox, grid: HtmlGrid,
) -> OcrTableEvidence: ) -> OcrTableEvidence:
"""对扫描表执行 OCR 行坐标、OpenCV 网格和全部非空 cell 文本三重门禁。""" """
对扫描表执行 OCR 行坐标、OpenCV 网格和全部非空 cell 文本三重门禁。
核心逻辑:通过后 cell.status 固定为 candidate;置信度不足/多候选/文本不一致不准入。
"""
try: try:
height, width = image.shape[:2]
lines = extract_ocr_lines(image, page_width=page_width, page_height=page_height) lines = extract_ocr_lines(image, page_width=page_width, page_height=page_height)
except Exception: except Exception:
return OcrTableEvidence(ready=False, issues=['ocr_engine_unavailable']) return OcrTableEvidence(ready=False, issues=['ocr_engine_unavailable'])
if not lines: if not lines:
return OcrTableEvidence(ready=False, issues=['ocr_text_missing']) return OcrTableEvidence(
ready=False,
issues=['ocr_text_missing', ISSUE_OCR_CONFIDENCE],
image_width=int(width) if width else None,
image_height=int(height) if height else None,
)
geometry = reconstruct_opencv_table_geometry( geometry = reconstruct_opencv_table_geometry(
image, page_width=page_width, page_height=page_height, image, page_width=page_width, page_height=page_height,
table_bbox=table_bbox, grid=grid, table_bbox=table_bbox, grid=grid,
@@ -128,16 +195,70 @@ def build_ocr_table_evidence(
) )
if not validation.accepted: if not validation.accepted:
return OcrTableEvidence( return OcrTableEvidence(
ready=False, issues=sorted(set(geometry.issues + validation.issues)), ready=False,
lines=lines,
issues=sorted(set(geometry.issues + validation.issues)),
image_width=int(width),
image_height=int(height),
) )
cells = [] cells: list[OcrCellEvidence] = []
issues: set[str] = set()
for item in geometry.cells: for item in geometry.cells:
indices = _line_indices_within(lines, item.bbox) indices = _line_indices_within(lines, item.bbox)
expected = next(cell for cell in grid.cells if cell.cell_id == item.cell_id) expected = next(cell for cell in grid.cells if cell.cell_id == item.cell_id)
if expected.text.strip() and not indices: if expected.text.strip() and not indices:
return OcrTableEvidence(ready=False, issues=['ocr_cell_tokens_missing']) return OcrTableEvidence(
cells.append(OcrCellEvidence(cell_id=item.cell_id, bbox=item.bbox, line_indices=indices)) ready=False, lines=lines, issues=['ocr_cell_tokens_missing'],
return OcrTableEvidence(ready=True, lines=lines, cells=cells, issues=[]) image_width=int(width), image_height=int(height),
)
if len(indices) > 1 and _ambiguous_ocr_lines(lines, indices, expected.text):
issues.add(ISSUE_OCR_MULTI)
continue
confidences = [lines[index].confidence for index in indices] or [0.0]
confidence = min(confidences)
if confidence < OCR_CONFIDENCE_FLOOR:
issues.add(ISSUE_OCR_CONFIDENCE)
continue
try:
normalized = page_bbox_to_normalized(item.bbox, page_width=page_width, page_height=page_height)
except ValueError:
issues.add('coordinate_bbox_invalid')
continue
cells.append(OcrCellEvidence(
cell_id=item.cell_id,
bbox=item.bbox,
normalized_bbox=normalized,
line_indices=indices,
confidence=confidence,
status='candidate',
))
if not cells:
return OcrTableEvidence(
ready=False, lines=lines, issues=sorted(issues or {'ocr_cells_unavailable'}),
image_width=int(width), image_height=int(height),
)
# 非空 cell 必须全部拿到 OCR 候选,否则不宣称 ready
required = {cell.cell_id for cell in grid.cells if cell.text.strip()}
if required - {cell.cell_id for cell in cells}:
return OcrTableEvidence(
ready=False, lines=lines, cells=cells,
issues=sorted(issues | {'ocr_cells_incomplete'}),
image_width=int(width), image_height=int(height),
)
return OcrTableEvidence(
ready=True, lines=lines, cells=cells, issues=sorted(issues),
image_width=int(width), image_height=int(height),
)
def _ambiguous_ocr_lines(lines: list[OcrLine], indices: list[int], expected_text: str) -> bool:
"""同一 cell 内多条 OCR 行且规范化文本无法唯一对上期望值时视为多候选。"""
expected = normalize_layout_text(expected_text).casefold()
matched = [
index for index in indices
if normalize_layout_text(lines[index].text).casefold() == expected
]
return len(matched) != 1 and len(indices) > 1
def _line_indices_within(lines: list[OcrLine], bbox: LayoutBBox) -> list[int]: def _line_indices_within(lines: list[OcrLine], bbox: LayoutBBox) -> list[int]:
@@ -3,7 +3,8 @@ backend/app/services/shipping_notice/document_layout/opencv_table.py
用途:在 MinerU 整表区域内用 OpenCV 恢复严格有框表网格,生成待评测的 HTML cell 几何候选。 用途:在 MinerU 整表区域内用 OpenCV 恢复严格有框表网格,生成待评测的 HTML cell 几何候选。
依赖:opencv-python-headless、numpy、document_layout.html_table/contracts。 依赖:opencv-python-headless、numpy、document_layout.html_table/contracts。
逻辑:多组形态学参数独立检测 cell 轮廓;仅当至少两组结果与 HTML 网格完全一致且边界共识稳定时输出 ready。 逻辑:多组形态学参数独立检测 cell 轮廓;仅当至少两组结果与 HTML 网格完全一致且边界
共识稳定时输出 ready;还必须经独立 PDF 文本验收,不得仅凭几何轮廓接受 cell(阶段 3)。
""" """
from __future__ import annotations from __future__ import annotations
@@ -3,7 +3,8 @@ backend/app/services/shipping_notice/document_layout/runtime.py
用途:在独立布局 Job 中调用 MinerU,并生成可持久化的紧凑文本、表格及原生 PDF 候选快照。 用途:在独立布局 Job 中调用 MinerU,并生成可持久化的紧凑文本、表格及原生 PDF 候选快照。
依赖:Flask 配置、MinerUClient、MinerU pipeline 候选契约、native_pdf。 依赖:Flask 配置、MinerUClient、MinerU pipeline 候选契约、native_pdf。
逻辑:保存受字符预算限制的分页文本块、整表 HTML 和保守 layout.v1 候选;Provider 错误安全降级,不保存原始响应。 逻辑:保存受字符预算限制的分页文本块、整表 HTML 和保守 layout.v1 候选;阶段 1 在
layout_candidate 写入真实 cell bbox 后回填 capability.cell_bbox_count,禁止长期假报 0。
""" """
from __future__ import annotations from __future__ import annotations
@@ -238,6 +239,9 @@ def build_mineru_table_snapshot(
if timings is not None: if timings is not None:
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000) timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
snapshot['layout_candidate'] = layout.model_dump(mode='json') snapshot['layout_candidate'] = layout.model_dump(mode='json')
snapshot['capability'] = _capability_with_layout_cells(
snapshot.get('capability'), layout_payload=snapshot['layout_candidate'],
)
# 冻结表格与整页字符坐标:明细重建只消费前者,订单级字段只能消费后者。 # 冻结表格与整页字符坐标:明细重建只消费前者,订单级字段只能消费后者。
evidence_started = perf_counter() evidence_started = perf_counter()
snapshot['coordinate_evidence'] = _table_coordinate_evidence( snapshot['coordinate_evidence'] = _table_coordinate_evidence(
@@ -325,28 +329,40 @@ def _native_pdf_fast_snapshot(
) )
if timings is not None: if timings is not None:
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000) timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
layout_payload_preview = layout.model_dump(mode='json')
capability = _capability_with_layout_cells(
candidate.capability.model_dump(mode='json'),
layout_payload=layout_payload_preview,
)
evidence_started = perf_counter() evidence_started = perf_counter()
evidence = _table_coordinate_evidence(pages=native_pages, tables=tables) # Fallback snapshots only need table-local glyphs for template modeling. Keeping
# every page glyph can exceed the persisted snapshot budget on text-heavy PDFs.
evidence = _table_coordinate_evidence(
pages=native_pages, tables=tables, include_page_glyphs=False,
)
if timings is not None: if timings is not None:
timings['coordinate_evidence_ms'] = round((perf_counter() - evidence_started) * 1000) timings['coordinate_evidence_ms'] = round((perf_counter() - evidence_started) * 1000)
return { return {
'snapshot_version': LAYOUT_SNAPSHOT_VERSION, 'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
'provider': 'pdfium', 'provider_version': 'native-text-v1', 'backend': 'native_pdf', 'provider': 'pdfium', 'provider_version': 'native-text-v1', 'backend': 'native_pdf',
'status': 'ready', 'text_blocks': [], 'tables': tables, 'status': 'ready', 'text_blocks': [], 'tables': tables,
'capability': candidate.capability.model_dump(mode='json'), 'capability': capability,
'layout_candidate': layout.model_dump(mode='json'), 'layout_candidate': layout_payload_preview,
'coordinate_evidence': evidence, 'coordinate_evidence': evidence,
'issues': ['native_pdf_text_table_fallback_used'], 'issues': ['native_pdf_text_table_fallback_used'],
} }
def _table_coordinate_evidence(*, pages: list[Any], tables: list[dict[str, Any]]) -> dict[str, Any]: def _table_coordinate_evidence(
*, pages: list[Any], tables: list[dict[str, Any]], include_page_glyphs: bool = True,
) -> dict[str, Any]:
""" """
从已提取页面保存表内及整页字符证据,避免同一 PDF 重复解析和渲染。 从已提取页面保存表内及整页字符证据,避免同一 PDF 重复解析和渲染。
Args: Args:
pages: 本轮已提取的 NativePdfPage 列表。 pages: 本轮已提取的 NativePdfPage 列表。
tables: MinerU 或原生文字回退生成的表格摘要。 tables: MinerU 或原生文字回退生成的表格摘要。
include_page_glyphs: 是否保留表格外整页字符证据;fallback 只保留表内证据。
Returns: Returns:
供明细重建与订单字段重放的坐标证据。 供明细重建与订单字段重放的坐标证据。
""" """
@@ -373,7 +389,7 @@ def _table_coordinate_evidence(*, pages: list[Any], tables: list[dict[str, Any]]
evidence[table_id] = glyphs evidence[table_id] = glyphs
page_glyphs: dict[str, list[dict[str, Any]]] = {} page_glyphs: dict[str, list[dict[str, Any]]] = {}
page_sources: dict[str, str] = {} page_sources: dict[str, str] = {}
for page_no, page in pages.items(): for page_no, page in pages.items() if include_page_glyphs else []:
native_glyphs = [item.model_dump(mode='json') for item in page.characters] native_glyphs = [item.model_dump(mode='json') for item in page.characters]
if native_glyphs: if native_glyphs:
page_glyphs[str(page_no)] = native_glyphs page_glyphs[str(page_no)] = native_glyphs
@@ -407,6 +423,52 @@ def _table_coordinate_evidence(*, pages: list[Any], tables: list[dict[str, Any]]
} }
def _count_layout_cell_bboxes(layout_payload: dict[str, Any] | None) -> int:
"""统计 layout_candidate 中带有效 bbox 的 cell 数量。"""
if not isinstance(layout_payload, dict):
return 0
count = 0
for page in layout_payload.get('pages') or []:
if not isinstance(page, dict):
continue
for table in page.get('tables') or []:
if not isinstance(table, dict):
continue
for row in table.get('rows') or []:
if not isinstance(row, dict):
continue
for cell in row.get('cells') or []:
if not isinstance(cell, dict):
continue
bbox = cell.get('bbox') if isinstance(cell.get('bbox'), dict) else None
if bbox and all(key in bbox for key in ('x0', 'y0', 'x1', 'y1')):
count += 1
return count
def _capability_with_layout_cells(
capability: dict[str, Any] | None,
*,
layout_payload: dict[str, Any] | None,
) -> dict[str, Any]:
"""
用 layout_candidate 真实 cell bbox 回填 capability,避免假报 cell_bbox_count=0。
核心逻辑:has_cell_coordinates 仅在 cell 覆盖达到 html_cell_count 时为 True;
部分唯一匹配只更新计数,不宣称确定性 cell 证据已就绪。
"""
base = dict(capability) if isinstance(capability, dict) else {}
cell_bbox_count = _count_layout_cell_bboxes(layout_payload)
html_cell_count = int(base.get('html_cell_count') or 0)
has_page = bool(base.get('has_page_coordinates'))
has_table = bool(base.get('has_table_structure'))
has_cells = cell_bbox_count > 0 and (html_cell_count <= 0 or cell_bbox_count >= html_cell_count)
base['cell_bbox_count'] = cell_bbox_count
base['has_cell_coordinates'] = has_cells
base['deterministic_cell_evidence_ready'] = has_page and has_table and has_cells
return base
def _ocr_page_characters(lines: list[Any]) -> list[dict[str, Any]]: def _ocr_page_characters(lines: list[Any]) -> list[dict[str, Any]]:
"""把整页 OCR 行均匀拆成字符证据;仅服务订单字段锚点,不参与表格 cell 自动接受。""" """把整页 OCR 行均匀拆成字符证据;仅服务订单字段锚点,不参与表格 cell 自动接受。"""
result: list[dict[str, Any]] = [] result: list[dict[str, Any]] = []
@@ -2,15 +2,26 @@
backend/app/services/shipping_notice/document_layout/schema_mapping.py backend/app/services/shipping_notice/document_layout/schema_mapping.py
用途:将 shipping_document_layout.v1 的真实 cell/token 证据映射到 Run 冻结订单 Schema。 用途:将 shipping_document_layout.v1 的真实 cell/token 证据映射到 Run 冻结订单 Schema。
依赖:布局契约、HTML 网格统一映射器、TableHeaderContract。 依赖:布局契约、HTML 网格统一映射器、TableHeaderContract;坐标字段对齐 field_highlight_contract。
逻辑:只消费契约已验证行列和显式 continuation;不猜跨页、不提升质量状态、不接受无 cell 证据字段。 逻辑:只消费契约已验证行列和显式 continuation;不猜跨页;字段候选分离 cell_bbox 与
token 并集 value_bbox;quote/bbox_text 取自 layout 文本,禁止回写 machine value。
""" """
from __future__ import annotations from __future__ import annotations
from typing import Any from typing import Any
from app.services.shipping_notice.document_layout.contracts import LayoutDocument, LayoutTable, validate_layout_document from app.services.shipping_notice.document_layout.cell_coordinate_status import (
classify_cell_coordinate_status,
)
from app.services.shipping_notice.document_layout.contracts import (
LayoutBBox,
LayoutCell,
LayoutDocument,
LayoutTable,
LayoutToken,
validate_layout_document,
)
from app.services.shipping_notice.document_layout.html_table import ( from app.services.shipping_notice.document_layout.html_table import (
HtmlGrid, HtmlGrid,
HtmlGridCell, HtmlGridCell,
@@ -28,7 +39,7 @@ def map_layout_document_to_schema(
ignorable_column_headers: list[str] | None = None, ignorable_column_headers: list[str] | None = None,
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:
""" """
映射完整布局文档,并输出保留 cell/token 证据的安全候选。 映射完整布局文档,并输出保留 cell/token/坐标证据的安全候选。
Args: Args:
layout: 必须通过 shipping_document_layout.v1 完整校验。 layout: 必须通过 shipping_document_layout.v1 完整校验。
@@ -40,13 +51,14 @@ def map_layout_document_to_schema(
document = validate_layout_document(layout) document = validate_layout_document(layout)
result: list[dict[str, Any]] = [] result: list[dict[str, Any]] = []
for page in document.pages: for page in document.pages:
tokens_by_id = {token.token_id: token for token in page.tokens}
for table in page.tables: for table in page.tables:
grid = layout_table_to_grid(table) grid = layout_table_to_grid(table)
mapped = map_html_grid_to_schema( mapped = map_html_grid_to_schema(
grid, page_no=page.page_no, table_id=table.table_id, contract=contract, grid, page_no=page.page_no, table_id=table.table_id, contract=contract,
) )
token_ids_by_cell = { cells_by_id = {
cell.cell_id: list(cell.token_ids) cell.cell_id: cell
for row in table.rows for cell in row.cells for row in table.rows for cell in row.cells
} }
row_payloads = [] row_payloads = []
@@ -55,14 +67,17 @@ def map_layout_document_to_schema(
row_payloads.append({ row_payloads.append({
**row.model_dump(mode='json'), **row.model_dump(mode='json'),
'cells': row_cells, 'cells': row_cells,
'fields': [{ 'fields': [
**field.model_dump(mode='json'), _field_with_coordinate_evidence(
'token_ids': token_ids_by_cell.get(field.cell_id, []), field=field,
'evidence_ref': ( cell=cells_by_id.get(field.cell_id),
f'layout:{document.document_id}:p{page.page_no}:' tokens_by_id=tokens_by_id,
f'{table.table_id}:{field.cell_id}' document_id=document.document_id,
), page_no=page.page_no,
} for field in row.fields], table_id=table.table_id,
)
for field in row.fields
],
}) })
unmapped_nonempty = collect_unmapped_nonempty_columns( unmapped_nonempty = collect_unmapped_nonempty_columns(
grid, grid,
@@ -145,3 +160,97 @@ def _row_cell_snapshots(grid: HtmlGrid, *, row_index: int) -> list[dict[str, str
'text': slot.text.strip(), 'text': slot.text.strip(),
}) })
return snapshots return snapshots
def _union_layout_bbox(boxes: list[LayoutBBox]) -> LayoutBBox | None:
"""合并多个 bbox 为最小外接矩形;空列表返回 None。"""
if not boxes:
return None
return LayoutBBox(
x0=min(item.x0 for item in boxes),
y0=min(item.y0 for item in boxes),
x1=max(item.x1 for item in boxes),
y1=max(item.y1 for item in boxes),
)
def _field_with_coordinate_evidence(
*,
field: Any,
cell: LayoutCell | None,
tokens_by_id: dict[str, LayoutToken],
document_id: int,
page_no: int,
table_id: str,
) -> dict[str, Any]:
"""
为 Schema 字段候选挂载可回溯坐标证据,供 generic_order_evidence 透传。
核心逻辑:保留 cell_bbox;有 token 时 value_bbox=token 并集且 bbox_text=token 文本;
quote 取自 bbox_text/cell.text,禁止写 machine value;质量由来源分级器裁决。
"""
payload = field.model_dump(mode='json')
evidence_ref = f'layout:{document_id}:p{page_no}:{table_id}:{field.cell_id}'
field_code = str(getattr(field, 'field_code', None) or payload.get('field_code') or '')
payload.update({
'page_no': page_no,
'table_id': table_id,
'token_ids': list(cell.token_ids) if cell is not None else [],
'evidence_ref': evidence_ref,
'row_index': getattr(field, 'row_index', None),
'column_index': getattr(field, 'column_index', None),
})
if cell is None:
grade = classify_cell_coordinate_status(
source='html', has_bbox=False, has_token_ids=False, field_code=field_code,
)
payload.update(grade)
return payload
# [STEP 1] 始终保留整格几何,供审计/诊断;高亮优先用更紧的 value_bbox
payload['cell_id'] = cell.cell_id
payload['cell_bbox'] = cell.bbox.model_dump(mode='json')
payload['cell_normalized_bbox'] = cell.normalized_bbox.model_dump(mode='json')
token_objs = [
tokens_by_id[token_id]
for token_id in cell.token_ids
if token_id in tokens_by_id
]
value_bbox = _union_layout_bbox([item.bbox for item in token_objs])
value_normalized = _union_layout_bbox([item.normalized_bbox for item in token_objs])
if value_bbox is not None and value_normalized is not None:
# [STEP 2] native/OCR 有 token:高亮框用 glyph/token 并集,引文取区域文本
bbox_text = ''.join(item.text for item in token_objs)
payload['value_bbox'] = value_bbox.model_dump(mode='json')
payload['normalized_bbox'] = value_normalized.model_dump(mode='json')
payload['bbox_text'] = bbox_text
payload['quote'] = bbox_text[:1000]
payload['quote_source'] = 'bbox_tokens'
payload['has_value_coordinate'] = True
has_value_bbox = True
else:
# [STEP 3] 无 token:value_bbox 必须为 null,仅保留 cell_bbox 供诊断,禁止冒充字段级框
payload['value_bbox'] = None
payload['normalized_bbox'] = None
payload['has_value_coordinate'] = False
cell_text = str(cell.text or '')
payload['bbox_text'] = cell_text
payload['quote'] = cell_text[:1000]
payload['quote_source'] = 'layout_cell_text'
has_value_bbox = False
grade = classify_cell_coordinate_status(
source=cell.source,
has_bbox=has_value_bbox,
has_token_ids=bool(token_objs),
confidence=float(cell.confidence),
field_code=field_code,
)
payload['source'] = (
'native_glyph' if grade['highlight_source'] == 'native_glyph'
else grade['highlight_source'] if grade['highlight_source'] != 'unknown'
else cell.source
)
payload.update(grade)
return payload
@@ -1,22 +1,29 @@
""" """
backend/app/services/shipping_notice/document_layout/text_cell_alignment.py backend/app/services/shipping_notice/document_layout/text_cell_alignment.py
用途:用原生 PDF 字符坐标为 MinerU HTML cell 生成严格、可追溯的几何候选。 用途:用原生 PDF glyph 坐标为 HTML cell 生成严格、可追溯的几何候选(阶段 1)。
依赖:document_layout contracts/html_table、Pydantic。 依赖:document_layout contracts/html_table、Pydantic;issue 码与 field_highlight_contract 对齐。
逻辑:只接受表格区域内唯一且不重叠的规范化文本匹配;重复、空白或冲突 cell 不猜框。 逻辑:只接受表格区域内唯一、连续、同行且不共享的规范化文本匹配;重复/空白/冲突
cell 不猜框;匹配 bbox 为 glyph 并集,且必须落在表格 bbox 内并与引文一致。
""" """
from __future__ import annotations from __future__ import annotations
import re import re
import unicodedata import unicodedata
from typing import Any from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError as PydanticValidationError, model_validator from pydantic import BaseModel, ConfigDict, Field, ValidationError as PydanticValidationError, model_validator
from app.services.shipping_notice.document_layout.contracts import LayoutBBox from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.html_table import HtmlGrid from app.services.shipping_notice.document_layout.html_table import HtmlGrid
# 与 field_highlight_contract.COORDINATE_ISSUE_CODES 对齐的对外稳定码。
ISSUE_DUPLICATE_TEXT = 'duplicate_text_coordinate_ambiguous'
ISSUE_VALUE_MISMATCH = 'value_bbox_text_mismatch'
ISSUE_OUTSIDE_TABLE = 'coordinate_outside_table'
ISSUE_SHARED_TOKEN = 'coordinate_shared_token_conflict'
class TextCellAlignmentModel(BaseModel): class TextCellAlignmentModel(BaseModel):
"""为字符和 cell 候选启用严格字段校验,防止评测辅助结果静默漂移。""" """为字符和 cell 候选启用严格字段校验,防止评测辅助结果静默漂移。"""
@@ -25,15 +32,16 @@ class TextCellAlignmentModel(BaseModel):
class PositionedCharacter(TextCellAlignmentModel): class PositionedCharacter(TextCellAlignmentModel):
"""保存 PDF 原生文本层的单个可见字符及页面坐标。""" """保存 PDF 原生文本层的单个可见字符、页面坐标与视觉行身份。"""
text: str = Field(min_length=1, max_length=8) text: str = Field(min_length=1, max_length=8)
bbox: LayoutBBox bbox: LayoutBBox
source_index: int | None = Field(default=None, ge=0) source_index: int | None = Field(default=None, ge=0)
line_id: str | None = None
class TextAlignedCell(TextCellAlignmentModel): class TextAlignedCell(TextCellAlignmentModel):
"""保存唯一文本匹配得到的 HTML cell 候选框;仍需人工视觉确认。""" """唯一文本匹配得到的 cell 几何;status 供高亮契约投影,不替代业务确认。"""
cell_id: str cell_id: str
row_index: int = Field(ge=0) row_index: int = Field(ge=0)
@@ -41,6 +49,8 @@ class TextAlignedCell(TextCellAlignmentModel):
bbox: LayoutBBox bbox: LayoutBBox
normalized_bbox: LayoutBBox normalized_bbox: LayoutBBox
glyph_indices: list[int] = Field(default_factory=list) glyph_indices: list[int] = Field(default_factory=list)
line_id: str | None = None
status: Literal['verified', 'candidate'] = 'candidate'
class TextCellAlignmentResult(TextCellAlignmentModel): class TextCellAlignmentResult(TextCellAlignmentModel):
@@ -74,13 +84,23 @@ def align_html_cells_from_positioned_text(
""" """
在整表区域内按唯一规范化文本匹配 HTML 原始 cell,并合并字符 bbox。 在整表区域内按唯一规范化文本匹配 HTML 原始 cell,并合并字符 bbox。
核心逻辑(阶段 1 门禁):
1. 单元格文本规范化后在表格区域内唯一匹配;
2. glyph 必须连续且同一视觉行;
3. glyph 不得被其他 cell 共享;
4. cell bbox = glyph 并集,且不得超出表格 bbox;
5. bbox 内文本必须与 cell 文本一致;
6. 多候选 → 不生成框,issue=`duplicate_text_coordinate_ambiguous`;
7. 空 cell 不参与定位。
Args: Args:
grid: 已展开但仍保留原始 cell 身份的 HTML 网格。 grid: 已展开但仍保留原始 cell 身份的 HTML 网格。
characters: PDF 原生文本层字符及左上原点页面坐标。 characters: PDF 原生文本层字符及左上原点页面坐标。
table_bbox: MinerU 整表页面 bbox,仅在该范围内搜索。 table_bbox: 整表页面 bbox,仅在该范围内搜索。
page_width/page_height: 页面尺寸,用于生成 0..1 标准化坐标。 page_width/page_height: 页面尺寸,用于生成 0..1 标准化坐标。
Returns: Returns:
可供人工叠框 Review 的候选;任何歧义都保留 issue,绝不进入生产证据。 可供复核高亮消费的候选;任何歧义都保留 issue,绝不按序号或均分猜框。
""" """
if page_width <= 0 or page_height <= 0: if page_width <= 0 or page_height <= 0:
raise ValueError('text cell alignment page dimensions must be positive') raise ValueError('text cell alignment page dimensions must be positive')
@@ -99,6 +119,7 @@ def align_html_cells_from_positioned_text(
continue continue
glyphs.append(glyph) glyphs.append(glyph)
glyphs = [item for item in glyphs if _bbox_center_within(table_bbox, item.bbox)] glyphs = [item for item in glyphs if _bbox_center_within(table_bbox, item.bbox)]
glyphs = _ensure_visual_line_ids(glyphs)
normalized_stream, stream_to_glyph = _normalized_character_stream(glyphs) normalized_stream, stream_to_glyph = _normalized_character_stream(glyphs)
used_glyphs: set[int] = set() used_glyphs: set[int] = set()
matched: list[TextAlignedCell] = [] matched: list[TextAlignedCell] = []
@@ -106,54 +127,121 @@ def align_html_cells_from_positioned_text(
if invalid_character_bbox: if invalid_character_bbox:
issues.add('text_cell_alignment_invalid_character_bbox') issues.add('text_cell_alignment_invalid_character_bbox')
# 非空 cell 才计入 complete 期望,空 cell 不参与定位也不阻断唯一匹配覆盖率。
alignable_cells = [cell for cell in grid.cells if _normalize_text(cell.text)]
for cell in grid.cells: for cell in grid.cells:
expected = _normalize_text(cell.text) expected = _normalize_text(cell.text)
if not expected: if not expected:
issues.add('text_cell_alignment_empty_cell') issues.add('text_cell_alignment_empty_cell')
continue continue
starts = [match.start() for match in re.finditer(re.escape(expected), normalized_stream)] starts = [match.start() for match in re.finditer(re.escape(expected), normalized_stream)]
if len(starts) != 1: if len(starts) == 0:
issues.add( issues.add('text_cell_alignment_text_not_found')
'text_cell_alignment_text_not_found' continue
if not starts else 'text_cell_alignment_text_not_unique' if len(starts) > 1:
) # 关键风险:短文本/重复值不得按「第 N 个」绑定
issues.add('text_cell_alignment_text_not_unique')
issues.add(ISSUE_DUPLICATE_TEXT)
continue continue
indices = set(stream_to_glyph[starts[0]:starts[0] + len(expected)]) indices = set(stream_to_glyph[starts[0]:starts[0] + len(expected)])
if not indices or indices & used_glyphs: if not indices or indices & used_glyphs:
issues.add('text_cell_alignment_glyph_overlap') issues.add('text_cell_alignment_glyph_overlap')
issues.add(ISSUE_SHARED_TOKEN)
continue continue
matched_glyphs = [glyphs[index] for index in sorted(indices)] matched_glyphs = [glyphs[index] for index in sorted(indices)]
if not _glyphs_form_contiguous_text(matched_glyphs): if not _glyphs_form_contiguous_text(matched_glyphs):
issues.add('text_cell_alignment_geometry_discontinuous') issues.add('text_cell_alignment_geometry_discontinuous')
continue continue
line_ids = {item.line_id for item in matched_glyphs if item.line_id}
if len(line_ids) > 1:
issues.add('text_cell_alignment_geometry_discontinuous')
continue
bbox = _union_bbox([item.bbox for item in matched_glyphs]) bbox = _union_bbox([item.bbox for item in matched_glyphs])
if not _bbox_contains(table_bbox, bbox):
issues.add('text_cell_alignment_bbox_outside_table')
issues.add(ISSUE_OUTSIDE_TABLE)
continue
# [STEP] 引文与 bbox 内文字独立校验;不一致禁止产出框
region_text = _normalize_text(''.join(item.text for item in matched_glyphs))
if region_text != expected:
issues.add('text_cell_alignment_value_mismatch')
issues.add(ISSUE_VALUE_MISMATCH)
continue
normalized = LayoutBBox(
x0=bbox.x0 / page_width,
y0=bbox.y0 / page_height,
x1=bbox.x1 / page_width,
y1=bbox.y1 / page_height,
)
if not _roundtrip_normalized_ok(bbox, normalized, page_width, page_height):
issues.add('text_cell_alignment_coordinate_roundtrip_failed')
continue
used_glyphs.update(indices) used_glyphs.update(indices)
matched.append(TextAlignedCell( matched.append(TextAlignedCell(
cell_id=cell.cell_id, cell_id=cell.cell_id,
row_index=cell.row_index, row_index=cell.row_index,
column_index=cell.column_index, column_index=cell.column_index,
bbox=bbox, bbox=bbox,
normalized_bbox=LayoutBBox( normalized_bbox=normalized,
x0=bbox.x0 / page_width,
y0=bbox.y0 / page_height,
x1=bbox.x1 / page_width,
y1=bbox.y1 / page_height,
),
glyph_indices=sorted( glyph_indices=sorted(
glyphs[index].source_index if glyphs[index].source_index is not None else index glyphs[index].source_index if glyphs[index].source_index is not None else index
for index in indices for index in indices
), ),
line_id=next(iter(line_ids), None),
# 全部硬门禁通过 → verified;供高亮契约使用,不改业务确认。
status='verified',
)) ))
expected_count = len(alignable_cells)
return TextCellAlignmentResult( return TextCellAlignmentResult(
complete=bool(grid.cells) and len(matched) == len(grid.cells), complete=bool(alignable_cells) and len(matched) == expected_count,
expected_cell_count=len(grid.cells), expected_cell_count=expected_count,
matched_cell_count=len(matched), matched_cell_count=len(matched),
cells=matched, cells=matched,
issues=sorted(issues), issues=sorted(issues),
) )
def _ensure_visual_line_ids(characters: list[PositionedCharacter]) -> list[PositionedCharacter]:
"""
为缺少 line_id 的 glyph 按视觉基线聚类分配行 ID。
核心逻辑:已有 line_id 保留;其余按 y 中心邻近归入同一行,保证同行门禁可判定。
"""
if not characters:
return characters
if all(item.line_id for item in characters):
return characters
ordered = sorted(
enumerate(characters),
key=lambda pair: ((pair[1].bbox.y0 + pair[1].bbox.y1) / 2, pair[1].bbox.x0),
)
assigned: list[PositionedCharacter | None] = [None] * len(characters)
current_line: list[int] = []
current_center: float | None = None
line_seq = 0
for original_index, glyph in ordered:
center_y = (glyph.bbox.y0 + glyph.bbox.y1) / 2
if current_center is None or abs(center_y - current_center) > 3:
if current_line:
line_id = f'vline-{line_seq}'
line_seq += 1
for index in current_line:
source = characters[index]
assigned[index] = source if source.line_id else source.model_copy(update={'line_id': line_id})
current_line = [original_index]
current_center = center_y
else:
current_line.append(original_index)
current_center = (current_center * (len(current_line) - 1) + center_y) / len(current_line)
if current_line:
line_id = f'vline-{line_seq}'
for index in current_line:
source = characters[index]
assigned[index] = source if source.line_id else source.model_copy(update={'line_id': line_id})
return [item if item is not None else characters[index] for index, item in enumerate(assigned)]
def _normalized_character_stream( def _normalized_character_stream(
characters: list[PositionedCharacter], characters: list[PositionedCharacter],
) -> tuple[str, list[int]]: ) -> tuple[str, list[int]]:
@@ -180,6 +268,14 @@ def _bbox_center_within(parent: LayoutBBox, child: LayoutBBox) -> bool:
return parent.x0 <= center_x <= parent.x1 and parent.y0 <= center_y <= parent.y1 return parent.x0 <= center_x <= parent.x1 and parent.y0 <= center_y <= parent.y1
def _bbox_contains(parent: LayoutBBox, child: LayoutBBox) -> bool:
"""要求子矩形完整落在父矩形内(值框不得超出表格)。"""
return (
child.x0 >= parent.x0 and child.y0 >= parent.y0
and child.x1 <= parent.x1 and child.y1 <= parent.y1
)
def _union_bbox(boxes: list[LayoutBBox]) -> LayoutBBox: def _union_bbox(boxes: list[LayoutBBox]) -> LayoutBBox:
"""合并唯一匹配字符范围;调用方保证列表非空。""" """合并唯一匹配字符范围;调用方保证列表非空。"""
return LayoutBBox( return LayoutBBox(
@@ -190,6 +286,31 @@ def _union_bbox(boxes: list[LayoutBBox]) -> LayoutBBox:
) )
def _roundtrip_normalized_ok(
absolute: LayoutBBox,
normalized: LayoutBBox,
page_width: float,
page_height: float,
*,
tol: float = 0.51,
) -> bool:
"""归一化与绝对坐标双向换算校验,防止缩放错误进入高亮。"""
if not (0 <= normalized.x0 < normalized.x1 <= 1 and 0 <= normalized.y0 < normalized.y1 <= 1):
return False
restored = LayoutBBox(
x0=normalized.x0 * page_width,
y0=normalized.y0 * page_height,
x1=normalized.x1 * page_width,
y1=normalized.y1 * page_height,
)
return (
abs(restored.x0 - absolute.x0) <= tol
and abs(restored.y0 - absolute.y0) <= tol
and abs(restored.x1 - absolute.x1) <= tol
and abs(restored.y1 - absolute.y1) <= tol
)
def _glyphs_form_contiguous_text(characters: list[PositionedCharacter]) -> bool: def _glyphs_form_contiguous_text(characters: list[PositionedCharacter]) -> bool:
"""要求匹配字符处于同一视觉行且水平间距连续,禁止跨 cell/跨行拼接。""" """要求匹配字符处于同一视觉行且水平间距连续,禁止跨 cell/跨行拼接。"""
if not characters: if not characters:
@@ -703,7 +703,12 @@ def approve_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
def profile_is_auto_create_approved(*, profile_id: int, checksum: str) -> bool: def profile_is_auto_create_approved(*, profile_id: int, checksum: str) -> bool:
"""判断冻结模板版本是否已有独立的自动冻结批准资格。""" """
判断冻结模板版本是否已有独立的模板质量批准资格。
核心逻辑:返回 True 仅表示解析器质量治理通过(parser_trace);
**不得**据此直接放行 Candidate 自动建单——订单级放行见 Candidate Qualification。
"""
qualification = ShippingDocumentProfileAutoFreezeQualification.query.filter_by( qualification = ShippingDocumentProfileAutoFreezeQualification.query.filter_by(
profile_id=int(profile_id), profile_checksum=str(checksum), status='auto_freeze_approved', profile_id=int(profile_id), profile_checksum=str(checksum), status='auto_freeze_approved',
).first() ).first()
@@ -711,7 +716,11 @@ def profile_is_auto_create_approved(*, profile_id: int, checksum: str) -> bool:
def ensure_manual_confirmation_qualification(profile: ShippingOrderDocumentProfile) -> ShippingDocumentProfileAutoFreezeQualification: def ensure_manual_confirmation_qualification(profile: ShippingOrderDocumentProfile) -> ShippingDocumentProfileAutoFreezeQualification:
"""为新发布模板版本建立首版人工确认资格,不因盲测通过而自动升级。""" """
为新发布模板版本建立首版人工确认资格,不因盲测通过而自动升级。
说明:本资格属于模板质量治理;盲测批准不等于订单自动建单放行。
"""
qualification = ShippingDocumentProfileAutoFreezeQualification.query.filter_by( qualification = ShippingDocumentProfileAutoFreezeQualification.query.filter_by(
profile_id=profile.id, profile_version=profile.version, profile_checksum=str(profile.checksum or ''), profile_id=profile.id, profile_version=profile.version, profile_checksum=str(profile.checksum or ''),
).one_or_none() ).one_or_none()
@@ -0,0 +1,921 @@
"""
services/shipping_notice/error_explainability_contract.py
用途:冻结货代发货通知全链路「错误可解释性」契约——分层原因码、责任方、下一步动作与
统一投影结构;作为阶段 0 真相源,后续阶段逐步接线,禁止前端按状态猜原因。
依赖:process_gate_contract(门禁阻断码 / 责任方 / 动作码交叉校验)。
逻辑:本模块只冻结名称与投影规则,不执行业务;与 process_gate_contract 共存:
Gate 阻断码仍以门禁契约为准;本模块补充附件/解析/行级/源级等细粒度码,
以及「规则未命中 ≠ 命中但不可用 ≠ 冲突」的分层语义;
AUDIT_COVERAGE_MATRIX 锁定阶段 4 关键失败/关闭节点的顶层 reason_code 接线源。
"""
from __future__ import annotations
from typing import Any, Final
from app.services.shipping_notice.process_gate_contract import (
PROCESS_GATE_ACTION_CODES,
PROCESS_GATE_BLOCKING_REASON_CODES,
PROCESS_GATE_REASON_OWNING_GATE,
PROCESS_GATE_RESPONSIBLE_PARTIES,
)
# 契约版本;文档、i18n、前端类型与测试必须与此对齐。
ERROR_EXPLAINABILITY_CONTRACT_VERSION: Final[str] = 'shipping-error-explainability-v1'
# 未知业务失败:禁止只展示「系统错误」;必须附 request_id。
UNKNOWN_BUSINESS_FAILURE_REASON_CODE: Final[str] = 'unknown_business_failure'
# ---------------------------------------------------------------------------
# 分层原因码(阶段 0 冻结集合;接线进度见 docs 契约文档)
# ---------------------------------------------------------------------------
# 附件接收与上传
ATTACHMENT_REASON_CODES: Final[frozenset[str]] = frozenset({
'attachment_format_unsupported',
'attachment_size_exceeded',
'attachment_corrupted',
'attachment_duplicate',
'attachment_storage_failed',
'attachment_security_blocked',
'attachment_replaced',
})
# 文档解析与订单识别
DOCUMENT_PARSE_REASON_CODES: Final[frozenset[str]] = frozenset({
'document_text_unavailable',
'document_layout_parse_failed',
'document_password_protected',
'business_table_not_found',
'multiple_business_tables',
'business_table_empty',
'document_profile_not_matched',
'document_profile_ambiguous',
'document_profile_drifted',
'generic_gate_blocked',
'order_extraction_failed',
'order_extraction_cancelled',
})
# 字段抽取、客户与订单校验
ORDER_FIELD_REASON_CODES: Final[frozenset[str]] = frozenset({
'required_field_missing',
'field_value_invalid',
'field_low_confidence',
'classification_low_confidence',
'field_conflict',
'customer_unresolved',
'customer_ambiguous',
'customer_out_of_scope',
'reservation_missing',
'reservation_invalid',
'reservation_duplicate',
'duplicate_unresolved',
})
# 建单与冻结
ORDER_BUILD_REASON_CODES: Final[frozenset[str]] = frozenset({
'profile_not_auto_freeze_approved',
'evidence_missing',
'auto_freeze_not_enabled',
'auto_create_disabled',
'order_freeze_not_ready',
'task_creation_failed',
'task_already_exists',
'task_state_not_creatable',
})
# 库存源路由 — 行级阻断(可同步为 Gate.blocking_reason_code)
#
# 特别处理(禁止混淆):
# no_inventory_source_candidates = 规则未命中(勿用 plan 别名 no_inventory_source_rule_matched)
# inventory_source_unavailable = 规则命中但候选源全部不可用
# require_manual_review = 冲突 / 规则要求人工确认
INVENTORY_SOURCE_LINE_BLOCK_REASON_CODES: Final[frozenset[str]] = frozenset({
'no_inventory_source_candidates',
'inventory_source_unavailable',
'require_manual_review',
'manual_inventory_source_reason_required',
'manual_inventory_source_invalid',
'inventory_source_conflicted',
'inventory_source_changed',
'inventory_source_identity_mismatch',
})
# 库存源路由 — 单源不可用明细(写入 unavailable_reasons[source_code])
INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES: Final[frozenset[str]] = frozenset({
'source_not_found',
'source_disabled',
'source_runtime_unavailable',
'source_profile_disabled',
'parsing_profile_unavailable',
'source_excel_template_unavailable',
})
# 库存准备与 RPA
INVENTORY_PREP_REASON_CODES: Final[frozenset[str]] = frozenset({
'inventory_preparation_waiting',
'inventory_preparation_failed',
'inventory_rpa_queued',
'inventory_rpa_timeout',
'inventory_rpa_login_failed',
'inventory_rpa_export_failed',
'inventory_rpa_exhausted',
'inventory_file_missing',
'inventory_file_identity_mismatch',
'inventory_file_empty',
})
# 库存字段映射、匹配与缺货
INVENTORY_MATCH_REASON_CODES: Final[frozenset[str]] = frozenset({
'inventory_mapping_required',
'inventory_required_column_missing',
'inventory_column_ambiguous',
'inventory_match_failed',
'inventory_sku_not_found',
'inventory_reservation_not_found',
'inventory_warehouse_mismatch',
'inventory_uom_conversion_failed',
'inventory_multi_file_conflict',
'inventory_insufficient',
'inventory_shortage_review_required',
})
# Excel 与货代平台上传
EXCEL_UPLOAD_REASON_CODES: Final[frozenset[str]] = frozenset({
'excel_not_ready',
'excel_template_missing',
'excel_input_incomplete',
'artifact_generation_failed',
'artifact_validation_failed',
'excel_downloaded', # 成功下载/生成:审计顶层动作码(非失败)
'upload_rpa_pending',
'upload_rpa_login_failed',
'upload_rpa_failed',
'upload_platform_rejected',
'upload_result_unknown',
'manual_upload_pending',
})
# 关闭、取消、作废与归档
TASK_CLOSE_REASON_CODES: Final[frozenset[str]] = frozenset({
'task_cancelled_by_user',
'task_rejected_by_user',
'task_voided_for_correction',
'task_closed_after_upload',
'task_archived',
'close_blocked_missing_receipt',
'void_blocked_external_uploaded',
'late_callback_ignored',
})
# 方案别名 → 已接线稳定码(禁止新增并列同义码)
EXPLAINABILITY_REASON_ALIASES: Final[dict[str, str]] = {
# 方案文案「未匹配到库存源规则」在运行时使用既有 Gate 码
'no_inventory_source_rule_matched': 'no_inventory_source_candidates',
# 方案文案 order_freeze_not_ready ↔ 既有 freeze_not_ready
'order_freeze_not_ready': 'freeze_not_ready',
# 方案文档解析码 ↔ 既有 Gate 码
'document_layout_parse_failed': 'layout_parse_failed',
'document_profile_not_matched': 'profile_not_matched',
'document_profile_ambiguous': 'profile_ambiguous',
'document_profile_drifted': 'profile_drift',
# Job 历史误写 → 跨门禁技术重试耗尽
'technical_failure': 'technical_retry_exhausted',
# 订单识别 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',
# 抽取失败 / 取消必须可区分,禁止一并降级为 unknown_business_failure
'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED': 'order_extraction_failed',
'SHIPPING_NOTICE.ORDER_EXTRACTION_CANCELLED': 'order_extraction_cancelled',
'UPSTREAM.TIMEOUT': 'extraction_incomplete',
# 复核草稿内 Reservation 重复 / 缺失 → 冻结稳定码
'reservation_duplicated_in_order': 'reservation_duplicate',
'effective_reservation_missing': 'reservation_missing',
# Candidate 人工驳回历史码 → 关闭类稳定码
'manual_rejected': 'task_rejected_by_user',
}
# 当前已接线、允许出现在 API 投影中的库存源不可用明细码
INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({
'source_not_found',
'source_disabled',
'source_runtime_unavailable',
'source_profile_disabled',
'parsing_profile_unavailable',
'source_excel_template_unavailable',
})
# 当前已接线行级阻断码
INVENTORY_SOURCE_LINE_BLOCK_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({
'no_inventory_source_candidates',
'inventory_source_unavailable',
'require_manual_review',
'manual_inventory_source_reason_required',
'manual_inventory_source_invalid',
'inventory_source_conflicted',
'inventory_source_changed',
'inventory_source_identity_mismatch',
})
# 附件告警已映射并可出现在审计 / Intake 投影中的子集
ATTACHMENT_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({
'attachment_format_unsupported',
'attachment_size_exceeded',
'attachment_corrupted',
'attachment_replaced',
'attachment_duplicate',
'attachment_storage_failed',
'attachment_security_blocked',
})
# 履约库存准备已接线原因码子集
INVENTORY_PREP_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({
'inventory_preparation_waiting',
'inventory_preparation_failed',
'inventory_rpa_queued',
'inventory_rpa_timeout',
'inventory_rpa_login_failed',
'inventory_rpa_export_failed',
'inventory_rpa_exhausted',
'inventory_file_missing',
'inventory_file_empty',
'inventory_file_identity_mismatch',
})
# 库存匹配 / 缺货已接线子集(履约门禁投影)
INVENTORY_MATCH_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({
'inventory_mapping_required',
'inventory_match_failed',
'inventory_insufficient',
'inventory_shortage_review_required',
'inventory_multi_file_conflict',
'inventory_sku_not_found',
'inventory_reservation_not_found',
'inventory_warehouse_mismatch',
'inventory_required_column_missing',
'inventory_column_ambiguous',
})
# Excel / 上传已接线原因码子集
EXCEL_UPLOAD_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({
'excel_not_ready',
'excel_template_missing',
'excel_input_incomplete',
'artifact_generation_failed',
'artifact_validation_failed',
'excel_downloaded',
'upload_rpa_pending',
'upload_rpa_failed',
'upload_result_unknown',
'manual_upload_pending',
'upload_rpa_login_failed',
'upload_platform_rejected',
})
# 关闭/作废已接线原因码子集
TASK_CLOSE_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({
'task_cancelled_by_user',
'task_rejected_by_user',
'task_voided_for_correction',
'task_archived',
'task_closed_after_upload',
'void_blocked_external_uploaded',
'close_blocked_missing_receipt',
'late_callback_ignored',
})
# 客户 / Reservation / 重复订单等已接线订单字段原因码
ORDER_FIELD_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({
'customer_unresolved',
'customer_ambiguous',
'customer_out_of_scope',
'reservation_missing',
'reservation_invalid',
'reservation_duplicate',
'duplicate_unresolved',
'required_field_missing',
'field_value_invalid',
'field_conflict',
'field_low_confidence',
'classification_low_confidence',
})
# 文档解析 / 抽取已接线子集(含方案别名码,运行时经 canonicalize 落到 Gate 码)
DOCUMENT_PARSE_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({
'document_text_unavailable',
'document_layout_parse_failed',
'document_password_protected',
'business_table_empty',
'business_table_not_found',
'multiple_business_tables',
'document_profile_not_matched',
'document_profile_ambiguous',
'document_profile_drifted',
'order_extraction_failed',
'order_extraction_cancelled',
'generic_gate_blocked',
})
# 建单 / 冻结已接线子集(与 Gate 投影共用)
ORDER_BUILD_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({
'profile_not_auto_freeze_approved',
'evidence_missing',
'auto_freeze_not_enabled',
'auto_create_disabled',
'order_freeze_not_ready',
'task_creation_failed',
'task_already_exists',
'task_state_not_creatable',
})
def _meta(party: str, action: str, message_zh: str) -> dict[str, str]:
"""构造 EXPLAINABILITY_REASON_META 条目。"""
return {'responsible_party': party, 'next_action': action, 'message_zh': message_zh}
# 原因码 → 默认责任方 / 下一步动作 / 中文兜底文案(前端优先 i18n)
# next_action 必须属于 PROCESS_GATE_ACTION_CODES,或为空串表示无可执行动作。
EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
UNKNOWN_BUSINESS_FAILURE_REASON_CODE: _meta('system', '', '业务处理失败,请凭请求编号联系管理员'),
# 附件
'attachment_format_unsupported': _meta('owner', 'rematerialize_document', '附件格式不支持'),
'attachment_size_exceeded': _meta('owner', 'rematerialize_document', '附件超过系统大小限制'),
'attachment_corrupted': _meta('owner', 'rematerialize_document', '附件文件损坏,无法读取'),
'attachment_duplicate': _meta('owner', 'open_order_review', '已存在相同内容的附件'),
'attachment_storage_failed': _meta('system', 'rematerialize_document', '附件保存失败'),
'attachment_security_blocked': _meta('owner', 'rematerialize_document', '附件包含被禁止的脚本或宏'),
'attachment_replaced': _meta('owner', 'open_order_review', '已重新上传并覆盖当前发货通知附件'),
# 文档解析 / 订单表
'document_text_unavailable': _meta('owner', 'retry_layout_parsing', '未能从文档中提取可用文本'),
'document_layout_parse_failed': _meta('worker', 'retry_layout_parsing', '文档版面解析失败'),
'document_password_protected': _meta('owner', 'rematerialize_document', '文档受密码保护'),
'business_table_not_found': _meta('owner', 'open_order_review', '未找到订单明细表'),
'multiple_business_tables': _meta('owner', 'open_order_review', '发现多个可能的订单明细表'),
'business_table_empty': _meta('owner', 'open_order_review', '找到订单表,但没有有效业务行'),
'document_profile_not_matched': _meta('owner', 'open_profile_review', '未匹配到适用的订单模板'),
'document_profile_ambiguous': _meta('owner', 'open_profile_review', '同时匹配到多个订单模板'),
'document_profile_drifted': _meta('owner', 'open_profile_review', '文档结构与模板版本不一致'),
'generic_gate_blocked': _meta('owner', 'open_order_review', '通用订单识别门禁未通过,需要人工复核'),
# Gate 既有阻断码
'document_unavailable': _meta('system', 'rematerialize_document', '发货通知文档不可用,请重新上传或物化文档'),
'layout_parse_failed': _meta('worker', 'retry_layout_parsing', 'PDF 版面解析失败,请重试解析'),
'profile_not_matched': _meta('owner', 'open_profile_review', '未能匹配文档模板,请人工确认 Profile'),
'profile_ambiguous': _meta('owner', 'open_profile_review', '文档模板存在歧义,请人工确认 Profile'),
'profile_drift': _meta('owner', 'open_profile_review', '文档结构与模板版本不一致'),
'extraction_incomplete': _meta('worker', 'retry_order_extraction', '订单字段抽取未完成,请重试或进入复核'),
'required_field_missing': _meta('owner', 'edit_order_fields', '缺少创建订单所需字段'),
'field_value_invalid': _meta('owner', 'edit_order_fields', '部分字段格式不正确'),
'field_low_confidence': _meta('owner', 'open_order_review', '部分识别结果置信度较低'),
'classification_low_confidence': _meta('owner', 'open_order_review', '订单分类置信度不足'),
'field_conflict': _meta('owner', 'resolve_field_conflicts', '同一字段存在不同来源值冲突'),
'cross_source_conflict': _meta('owner', 'resolve_field_conflicts', '跨来源字段冲突,请解决冲突后继续'),
'evidence_missing': _meta('owner', 'open_order_review', '关键识别结果缺少有效证据'),
'customer_unresolved': _meta('owner', 'confirm_customer', '未能识别客户'),
'customer_ambiguous': _meta('owner', 'confirm_customer', '匹配到多个客户'),
'customer_out_of_scope': _meta('owner', 'confirm_customer', '客户不在当前业务范围内'),
'reservation_missing': _meta('owner', 'edit_reservation', '缺少有效 Reservation'),
'reservation_invalid': _meta('owner', 'edit_reservation', 'Reservation 格式或规则校验未通过'),
'reservation_duplicate': _meta('owner', 'edit_reservation', 'Reservation 已在其他订单中使用'),
'duplicate_unresolved': _meta('owner', 'adjudicate_duplicate', '疑似重复订单尚未裁定'),
'profile_not_auto_freeze_approved': _meta('owner', 'open_order_review', '当前模板质量未批准(仅解析治理痕迹,不单独否决合格候选)'),
'auto_freeze_not_enabled': _meta('owner', 'open_order_review', '自动建单策略尚未启用'),
'auto_create_disabled': _meta('owner', 'open_order_review', '自动建单开关未启用'),
'freeze_not_ready': _meta('owner', 'open_order_review', '订单尚未满足冻结建单条件'),
'order_freeze_not_ready': _meta('owner', 'open_order_review', '订单尚未满足冻结建单条件'),
'task_creation_failed': _meta('system', 'retry_task_creation', '履约任务创建失败'),
'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', '当前任务与库存源/仓库身份不一致'),
'effective_reservation_missing': _meta('owner', 'edit_reservation', '缺少有效的预约单号'),
# 库存准备 / RPA / 匹配 / Excel / 上传
'inventory_preparation_waiting': _meta('worker', 'poll_inventory_preparation', '库存文件准备中,请稍后刷新'),
'inventory_preparation_failed': _meta('owner', 'retry_inventory_preparation', '库存准备失败,请重试或上传库存文件'),
'inventory_rpa_queued': _meta('worker', 'poll_inventory_preparation', 'RPA 任务已排队等待执行'),
'inventory_rpa_timeout': _meta('worker', 'retry_inventory_preparation', 'RPA 执行超时'),
'inventory_rpa_login_failed': _meta('admin', 'retry_inventory_preparation', '库存平台登录失败'),
'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_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_match_failed': _meta('owner', 'open_inventory_match_review', '库存匹配失败'),
'inventory_insufficient': _meta('owner', 'open_shortage_review', '库存不足'),
'inventory_shortage_review_required': _meta('owner', 'open_shortage_review', '存在库存缺口,需要人工处理'),
'excel_not_ready': _meta('system', 'recheck_excel_readiness', '当前尚不满足 Excel 生成条件'),
'artifact_generation_failed': _meta('system', 'regenerate_excel_artifact', 'Excel 生成失败'),
'manual_upload_pending': _meta('owner', 'regenerate_manual_upload_todo', '请下载 Excel 后在货代平台上传并登记结果'),
'upload_rpa_pending': _meta('worker', 'poll_freight_upload_rpa', '货代平台上传任务等待执行'),
'upload_rpa_failed': _meta('worker', 'retry_freight_upload_rpa', '货代平台上传失败,可重试 RPA'),
'upload_rpa_login_failed': _meta('admin', 'retry_freight_upload_rpa', '货代平台登录失败,请检查凭据后重试'),
'upload_platform_rejected': _meta('owner', 'retry_freight_upload_rpa', '货代平台拒绝上传,请核对文件后重试'),
'upload_result_unknown': _meta('owner', 'regenerate_manual_upload_todo', '上传结果暂时无法确认'),
'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', '订单抽取已取消'),
# 关闭 / 作废 / 访问审计动作码
'task_cancelled_by_user': _meta('owner', '', '任务已由用户取消'),
'task_voided_for_correction': _meta('owner', 'open_order_review', '任务已作废以进行更正'),
'task_archived': _meta('owner', '', '任务已归档'),
'void_blocked_external_uploaded': _meta('owner', '', '已存在外部履约,禁止作废,请归档'),
'task_rejected_by_user': _meta('owner', '', '订单候选/任务已由用户驳回'),
'task_closed_after_upload': _meta('owner', '', '上传完成后任务已关闭'),
'close_blocked_missing_receipt': _meta('owner', 'regenerate_manual_upload_todo', '缺少上传回执,暂不可关闭'),
'late_callback_ignored': _meta('system', '', '迟到的外部回调已忽略'),
'excel_downloaded': _meta('owner', '', '已下载发货 Excel'),
'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 产物校验失败'),
'upload_rpa_login_failed': _meta('admin', 'regenerate_manual_upload_todo', '货代平台登录失败'),
'upload_platform_rejected': _meta('owner', 'regenerate_manual_upload_todo', '货代平台拒绝本次上传'),
'inventory_required_column_missing': _meta('owner', 'confirm_inventory_field_mapping', '库存文件缺少必填列'),
'inventory_column_ambiguous': _meta('owner', 'confirm_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', '仓库与订单要求不一致'),
'inventory_uom_conversion_failed': _meta('owner', 'open_inventory_match_review', '单位换算失败'),
'inventory_multi_file_conflict': _meta('owner', 'open_inventory_match_review', '多库存文件结果冲突'),
}
def canonicalize_reason_code(reason_code: str | None) -> str:
"""
将方案别名或原始原因码规范化为稳定码。
Args:
reason_code: 原始或别名原因码。
Returns:
稳定原因码;空输入返回空串。
"""
code = str(reason_code or '').strip()
if not code:
return ''
return EXPLAINABILITY_REASON_ALIASES.get(code, code)
def classify_excel_generate_error(message: str | None) -> str:
"""
将 generate_shipment_excel 的 ValueError/ConflictError 文案映射为稳定原因码。
Args:
message: 异常消息原文。
Returns:
EXCEL_UPLOAD 稳定码;无法细分时返回 artifact_generation_failed。
"""
text = str(message or '').strip().lower()
if not text:
return 'artifact_generation_failed'
if '模板' in text and ('未绑定' in text or '不存在' in text or '未配置' in text):
return 'excel_template_missing'
if '校验失败' in text or 'checksum' in text or '模板文件缺失' in text:
return 'artifact_validation_failed'
if any(
token in text
for token in (
'缺少', '没有', '未形成', '无法', '空', 'warehouse', '快照', '字段映射',
'匹配键', '订单行', '文件名', '待上传', '停用', '作废', '归档',
)
):
return 'excel_input_incomplete'
return 'artifact_generation_failed'
def classify_inventory_match_reason(
*,
line_results: list[dict[str, Any]] | None = None,
match_status: str | None = None,
) -> str:
"""
由匹配行 disposition / match_status 推导匹配门禁稳定原因码。
核心逻辑:多文件冲突 > Reservation/SKU 未找到 > 泛化 inventory_match_failed。
Args:
line_results: STP/单源匹配行结果。
match_status: 任务 match_status。
Returns:
INVENTORY_MATCH 稳定码。
"""
rows = [item for item in (line_results or []) if isinstance(item, dict)]
dispositions = {str(item.get('disposition') or '').strip() for item in rows}
if 'multi_file_conflict' in dispositions:
return 'inventory_multi_file_conflict'
if any(d in dispositions for d in ('not_found', 'reservation_not_found')):
# 优先 Reservation:行上带 reservation 命中失败语义
if any(
str(item.get('disposition') or '') in {'not_found', 'reservation_not_found'}
and (item.get('reservation_id') or item.get('__display_reservation_id'))
and not (item.get('part_number') or item.get('__display_part_number'))
for item in rows
):
return 'inventory_reservation_not_found'
if any(
str(item.get('disposition') or '') == 'not_found'
and (item.get('part_number') or item.get('__display_part_number'))
for item in rows
):
return 'inventory_sku_not_found'
return 'inventory_reservation_not_found'
status = str(match_status or '').strip().lower()
if status in {'unfulfillable', 'partial'}:
return 'inventory_match_failed'
return 'inventory_match_failed'
def map_attachment_warning_to_reason_code(warning: str | None) -> str | None:
"""
将附件/EML 解析 warning 映射为 ATTACHMENT 稳定原因码。
核心逻辑:按前缀/关键词匹配 size / format / corrupt / duplicate;无法识别返回 None。
Args:
warning: Intake 或 notice_upload 产生的 warning 原文。
Returns:
稳定原因码;无法映射时 None。
"""
text = str(warning or '').strip().lower()
if not text:
return None
# [STEP] 完整性门禁前缀优先映射,保证 INTAKE_ATTACHMENTS_INCOMPLETE 可解释
if 'nesting_depth_exceeded' in text or 'security' in text or 'macro' in text:
return 'attachment_security_blocked'
if (
'total_attachment_size_exceeded' in text
or 'attachment_limit_exceeded' in text
or 'text_budget_exhausted' in text
or 'too_large' in text
or 'size_exceeded' in text
):
return 'attachment_size_exceeded'
if 'unsupported_file_type' in text or text.startswith('unsupported'):
return 'attachment_format_unsupported'
if (
'unreadable' in text
or 'corrupted' in text
or 'corrupt' in text
or 'text_truncated' in text
or 'notice_text_truncated' in text
):
return 'attachment_corrupted'
if 'duplicate' in text:
return 'attachment_duplicate'
if 'storage' in text:
return 'attachment_storage_failed'
return None
def primary_attachment_reason_from_warnings(warnings: list[Any] | None) -> str | None:
"""
从 warnings 列表取首个可映射的附件稳定原因码。
Args:
warnings: warning 字符串列表。
Returns:
首个稳定码;无则 None。
"""
for item in warnings or []:
code = map_attachment_warning_to_reason_code(str(item or ''))
if code:
return code
return None
def message_zh_for_reason(reason_code: str | None) -> str | None:
"""
返回原因码的中文兜底文案;未知或空码返回 None(前端走 i18n/通用提示)。
Args:
reason_code: 稳定原因码或已登记别名。
Returns:
中文文案或 None。
"""
code = canonicalize_reason_code(reason_code)
if not code:
return None
meta = EXPLAINABILITY_REASON_META.get(code)
if not meta:
return None
text = str(meta.get('message_zh') or '').strip()
return text or None
def build_explainability_reason(
*,
reason_code: str,
message: str | None = None,
details: dict[str, Any] | None = None,
responsible_party: str | None = None,
next_action: str | None = None,
request_id: str | None = None,
) -> dict[str, Any]:
"""
构造统一错误可解释性投影。
核心逻辑:reason_code 走别名归一;缺省责任方/动作/文案取自 EXPLAINABILITY_REASON_META;
未知码强制降级为 unknown_business_failure,并要求附 request_id(若调用方未给则写入占位提示)。
Args:
reason_code: 稳定原因码或已登记别名。
message: 用户可见文案;缺省用中文兜底(前端优先 i18n)。
details: 业务事实;禁止堆栈/SQL/密钥。
responsible_party: system|worker|owner|admin|external。
next_action: 前端按钮/导航依据;空串表示无可执行动作。
request_id: 未知失败时必填,便于审计追溯。
Returns:
{reason_code, message, details, responsible_party, next_action[, request_id]}。
"""
# [STEP 1] 归一化原因码;无 meta 时显式降级为 unknown_business_failure
code = canonicalize_reason_code(reason_code)
meta = EXPLAINABILITY_REASON_META.get(code)
if meta is None and code not in _all_frozen_reason_codes():
code = UNKNOWN_BUSINESS_FAILURE_REASON_CODE
meta = EXPLAINABILITY_REASON_META[UNKNOWN_BUSINESS_FAILURE_REASON_CODE]
meta = meta or {}
party = str(responsible_party or meta.get('responsible_party') or 'system').strip()
if party not in PROCESS_GATE_RESPONSIBLE_PARTIES:
party = 'system'
action_raw = next_action if next_action is not None else meta.get('next_action')
action = str(action_raw or '').strip() or None
if action and action not in PROCESS_GATE_ACTION_CODES:
# 未登记动作不暴露给前端,避免按钮死链;细节保留在 details。
details = dict(details or {})
details.setdefault('unregistered_next_action', action)
action = None
text = str(message).strip() if message else str(meta.get('message_zh') or '').strip()
if not text:
text = EXPLAINABILITY_REASON_META[UNKNOWN_BUSINESS_FAILURE_REASON_CODE]['message_zh']
payload: dict[str, Any] = {
'reason_code': code,
'message': text,
'details': dict(details or {}),
'responsible_party': party,
'next_action': action,
}
if code == UNKNOWN_BUSINESS_FAILURE_REASON_CODE:
rid = str(request_id or '').strip()
payload['request_id'] = rid or None
if not rid:
payload['details'] = {
**payload['details'],
'request_id_missing': True,
}
elif request_id:
payload['request_id'] = str(request_id).strip()
return payload
def _all_frozen_reason_codes() -> frozenset[str]:
"""汇总本契约冻结的全部原因码(含别名目标与已接线 Gate 阻断码)。"""
return frozenset().union(
ATTACHMENT_REASON_CODES,
DOCUMENT_PARSE_REASON_CODES,
ORDER_FIELD_REASON_CODES,
ORDER_BUILD_REASON_CODES,
INVENTORY_SOURCE_LINE_BLOCK_REASON_CODES,
INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES,
INVENTORY_PREP_REASON_CODES,
INVENTORY_MATCH_REASON_CODES,
EXCEL_UPLOAD_REASON_CODES,
TASK_CLOSE_REASON_CODES,
PROCESS_GATE_BLOCKING_REASON_CODES,
{UNKNOWN_BUSINESS_FAILURE_REASON_CODE},
frozenset(EXPLAINABILITY_REASON_ALIASES.values()),
)
# ---------------------------------------------------------------------------
# 阶段 4:关键失败/关闭类业务操作 → 统一审计顶层 reason_code(覆盖率举证)
# allow_empty=True 表示生命周期节点允许顶层码为空;其余须在 source_module 出现接线标记。
# ---------------------------------------------------------------------------
AUDIT_COVERAGE_MATRIX: Final[tuple[dict[str, Any], ...]] = (
{
'node': 'task_delete_plain',
'event_type': 'shipping_task_disposition',
'reason_code': 'task_cancelled_by_user',
'source_module': 'task_disposition_service.py',
'wire_marker': "task_cancelled_by_user",
'allow_empty': False,
},
{
'node': 'task_void_and_delete',
'event_type': 'shipping_task_disposition',
'reason_code': 'task_voided_for_correction',
'source_module': 'task_disposition_service.py',
'wire_marker': "task_voided_for_correction",
'allow_empty': False,
},
{
'node': 'task_archive',
'event_type': 'shipping_task_disposition',
'reason_code': 'task_archived',
'source_module': 'task_disposition_service.py',
'wire_marker': "task_archived",
'allow_empty': False,
},
{
'node': 'candidate_reject',
'event_type': 'candidate_rejected',
'reason_code': 'task_rejected_by_user',
'source_module': 'candidate_service.py',
'wire_marker': "reason_code='task_rejected_by_user'",
'allow_empty': False,
},
{
'node': 'excel_generate_success',
'event_type': 'excel_generated',
'reason_code': 'excel_downloaded',
'source_module': 'fulfillment_workflow.py',
'wire_marker': "reason_code='excel_downloaded'",
'allow_empty': False,
},
{
'node': 'upload_manual_confirm',
'event_type': 'upload_manual_confirmed',
'reason_code': 'task_closed_after_upload',
'source_module': 'fulfillment_workflow.py',
'wire_marker': "reason_code='task_closed_after_upload'",
'allow_empty': False,
},
{
'node': 'rpa_upload_success',
'event_type': 'rpa_upload_result',
'reason_code': 'task_closed_after_upload',
'source_module': 'fulfillment_workflow.py',
'wire_marker': "event_type='rpa_upload_result'",
'allow_empty': False,
},
{
'node': 'rpa_upload_triggered',
'event_type': 'upload_rpa_triggered',
'reason_code': '',
'source_module': 'fulfillment_workflow.py',
'wire_marker': "event_type='upload_rpa_triggered'",
'allow_empty': True,
},
{
'node': 'candidate_qualification_evaluated',
'event_type': 'candidate_qualification_evaluated',
'reason_code': '',
'source_module': 'candidate_qualification_service.py',
'wire_marker': "event_type='candidate_qualification_evaluated'",
'allow_empty': True,
},
{
'node': 'process_gate_outcome',
'event_type': 'process_gate_blocked|process_gate_passed',
'reason_code': 'blocking_reason_code',
'source_module': 'process_gate_service.py',
'wire_marker': 'reason_code=gate_reason',
'allow_empty': False,
},
{
'node': 'process_gate_downstream_invalidated',
'event_type': 'process_gate_downstream_invalidated',
'reason_code': 'gate_invalidated',
'source_module': 'process_gate_service.py',
'wire_marker': "reason_code='gate_invalidated'",
'allow_empty': False,
},
{
'node': 'late_rpa_callback_ignored',
'event_type': 'rpa_callback_rejected',
'reason_code': 'late_callback_ignored',
'source_module': 'inventory_rpa_workflow.py',
'wire_marker': '"reason_code": "late_callback_ignored"',
'allow_empty': False,
},
{
'node': 'lifecycle_execution_created',
'event_type': 'process_execution_created',
'reason_code': '',
'source_module': 'process_gate_service.py',
'wire_marker': "event_type='process_execution_created'",
'allow_empty': True,
},
{
'node': 'lifecycle_attempt_started',
'event_type': 'process_gate_attempt_started',
'reason_code': '',
'source_module': 'process_gate_service.py',
'wire_marker': "event_type='process_gate_attempt_started'",
'allow_empty': True,
},
)
def required_audit_coverage_nodes() -> tuple[dict[str, Any], ...]:
"""
返回必须具备顶层 reason_code 的审计覆盖节点(排除 allow_empty 生命周期项)。
Returns:
覆盖矩阵子集,供统一覆盖率测试断言 100%。
"""
return tuple(item for item in AUDIT_COVERAGE_MATRIX if not item.get('allow_empty'))
def assert_error_explainability_contract_integrity() -> None:
"""
校验可解释性契约:集合无交叠冲突、meta 责任方合法、已接线码 ⊆ 冻结集、
与门禁 owning_gate 不冲突。
Raises:
AssertionError: 契约不一致。
"""
# [STEP 1] 别名不得指向自身,目标必须存在于冻结集或门禁阻断集
frozen = _all_frozen_reason_codes()
for alias, target in EXPLAINABILITY_REASON_ALIASES.items():
assert alias != target, f'alias {alias} points to itself'
assert target in frozen, f'alias {alias} target {target} not frozen'
# [STEP 2] 已接线子集必须 ⊆ 冻结集
assert INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES_EMITTED <= INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES
assert INVENTORY_SOURCE_LINE_BLOCK_REASON_CODES_EMITTED <= INVENTORY_SOURCE_LINE_BLOCK_REASON_CODES
assert ATTACHMENT_REASON_CODES_EMITTED <= ATTACHMENT_REASON_CODES
assert INVENTORY_PREP_REASON_CODES_EMITTED <= INVENTORY_PREP_REASON_CODES
assert INVENTORY_MATCH_REASON_CODES_EMITTED <= INVENTORY_MATCH_REASON_CODES
assert EXCEL_UPLOAD_REASON_CODES_EMITTED <= EXCEL_UPLOAD_REASON_CODES
assert TASK_CLOSE_REASON_CODES_EMITTED <= TASK_CLOSE_REASON_CODES
assert ORDER_FIELD_REASON_CODES_EMITTED <= ORDER_FIELD_REASON_CODES
assert DOCUMENT_PARSE_REASON_CODES_EMITTED <= DOCUMENT_PARSE_REASON_CODES
assert ORDER_BUILD_REASON_CODES_EMITTED <= ORDER_BUILD_REASON_CODES
# [STEP 3] 行级已接线阻断码必须能映射到 inventory_source_routing(人工草稿码除外可延后)
for code in (
'no_inventory_source_candidates',
'inventory_source_unavailable',
'require_manual_review',
):
assert PROCESS_GATE_REASON_OWNING_GATE.get(code) == 'inventory_source_routing', (
f'{code} must own inventory_source_routing'
)
# [STEP 4] meta 责任方与动作合法性
for code, meta in EXPLAINABILITY_REASON_META.items():
party = meta.get('responsible_party')
assert party in PROCESS_GATE_RESPONSIBLE_PARTIES, f'{code} invalid party {party}'
action = str(meta.get('next_action') or '').strip()
if action:
assert action in PROCESS_GATE_ACTION_CODES, f'{code} next_action {action} not in gate actions'
assert str(meta.get('message_zh') or '').strip(), f'{code} missing message_zh'
# [STEP 5] 单源不可用码不得进入 Gate owning 映射(避免与行级阻断混层)
for code in INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES:
assert code not in PROCESS_GATE_REASON_OWNING_GATE, (
f'per-source reason {code} must not own a gate; use line block_reason instead'
)
# [STEP 6] 审计覆盖矩阵:失败/关闭类节点须有稳定码(或明确 allow_empty)
frozen = _all_frozen_reason_codes()
seen_nodes: set[str] = set()
for item in AUDIT_COVERAGE_MATRIX:
node = str(item.get('node') or '').strip()
assert node and node not in seen_nodes, f'duplicate/empty audit coverage node: {node!r}'
seen_nodes.add(node)
assert str(item.get('event_type') or '').strip(), f'{node} missing event_type'
assert str(item.get('source_module') or '').endswith('.py'), f'{node} source_module must be .py'
assert str(item.get('wire_marker') or '').strip(), f'{node} missing wire_marker'
allow_empty = bool(item.get('allow_empty'))
code = str(item.get('reason_code') or '').strip()
if allow_empty:
assert not code or code in frozen, f'{node} allow_empty but unknown code {code}'
else:
# blocking_reason_code 为动态透传占位,不要求属于冻结集合
if code != 'blocking_reason_code':
assert code in frozen, f'{node} reason_code {code} not frozen'
@@ -0,0 +1,363 @@
"""
services/shipping_notice/field_highlight_contract.py
用途:冻结复核工作台「字段精确高亮」契约——质量状态、来源、坐标问题码、值匹配状态
与统一投影结构;作为阶段 0 真相源,后续阶段接线坐标生成/OCR/审计时不得漂移。
依赖:无外部 I/O;仅标准库 typing。
逻辑:本模块只冻结名称与投影规则,不执行 PDF 解析;order_review_evidence_service
调用 build_field_highlight_projection 产出前端可消费 DTO;坐标缺失/非法不得
伪造 bbox,且不得耦合自动确认或建单门禁。值匹配必须依赖 bbox/cell 独立引文,
禁止用「quote=machine_value」自证 matched。
"""
from __future__ import annotations
from typing import Any, Final, Literal
# 契约版本;文档、前端类型与测试必须与此对齐。
FIELD_HIGHLIGHT_CONTRACT_VERSION: Final[str] = 'shipping-field-highlight-v1'
HighlightQuality = Literal['verified', 'candidate', 'unavailable', 'invalid']
CoordinateStatus = Literal['verified', 'candidate', 'unavailable', 'invalid']
ValueMatchStatus = Literal['matched', 'mismatched', 'unchecked', 'empty']
# ---------------------------------------------------------------------------
# 冻结枚举集合
# ---------------------------------------------------------------------------
HIGHLIGHT_QUALITY_VALUES: Final[frozenset[str]] = frozenset({
'verified',
'candidate',
'unavailable',
'invalid',
})
# 只要存在合法字段级 bbox,四种质量都允许前端绘制;质量只表达可信度,
# 不再阻止用户查看系统实际取值位置。真正缺少/非法 bbox 时仍返回 null。
DRAWABLE_HIGHLIGHT_QUALITIES: Final[frozenset[str]] = frozenset({
'verified',
'candidate',
'unavailable',
'invalid',
})
HIGHLIGHT_SOURCE_VALUES: Final[frozenset[str]] = frozenset({
'pdf_coordinate',
'frozen_layout_cell',
'native_glyph',
'ocr',
'machine_extraction',
'unknown',
})
VALUE_MATCH_STATUS_VALUES: Final[frozenset[str]] = frozenset({
'matched',
'mismatched',
'unchecked',
'empty',
})
# 独立于 machine_value 的引文来源;仅此类可把 value_match 升为 matched。
INDEPENDENT_QUOTE_SOURCES: Final[frozenset[str]] = frozenset({
'bbox_tokens',
'glyph_region',
'layout_cell_text',
})
# 坐标/高亮专用 issue code(与业务确认门禁码隔离)。
COORDINATE_ISSUE_CODES: Final[frozenset[str]] = frozenset({
'coordinate_missing',
'coordinate_bbox_invalid',
'coordinate_page_missing',
'coordinate_page_out_of_range',
'duplicate_text_coordinate_ambiguous',
'value_bbox_text_mismatch',
'quote_not_independent',
'cell_token_unbound',
'ocr_confidence_insufficient',
'ocr_multi_candidate',
'html_only_no_pdf_bbox',
'coordinate_outside_table',
'coordinate_shared_token_conflict',
})
# 上游已声明的质量状态键(layout_evidence / observation 可选字段)。
_UPSTREAM_STATUS_KEYS: Final[tuple[str, ...]] = (
'highlight_quality',
'coordinate_status',
)
def assert_field_highlight_contract_integrity() -> None:
"""
自检冻结集合与绘制规则一致性。
Raises:
AssertionError: 集合为空或绘制规则与质量枚举冲突。
"""
assert FIELD_HIGHLIGHT_CONTRACT_VERSION.startswith('shipping-field-highlight-')
assert HIGHLIGHT_QUALITY_VALUES == {'verified', 'candidate', 'unavailable', 'invalid'}
assert DRAWABLE_HIGHLIGHT_QUALITIES <= HIGHLIGHT_QUALITY_VALUES
assert COORDINATE_ISSUE_CODES
assert HIGHLIGHT_SOURCE_VALUES
assert VALUE_MATCH_STATUS_VALUES
assert INDEPENDENT_QUOTE_SOURCES
assert 'quote_not_independent' in COORDINATE_ISSUE_CODES
def should_draw_highlight(quality: str | None) -> bool:
"""
判断给定高亮质量是否允许前端绘制 bbox。
Args:
quality: highlight_quality 取值。
Returns:
四种质量均允许绘制;调用方仍须同时检查是否存在合法 bbox。
"""
return str(quality or '') in DRAWABLE_HIGHLIGHT_QUALITIES
def normalize_highlight_source(raw: Any) -> str:
"""
将来源字符串收敛到冻结集合;未知来源降为 unknown,禁止透传任意自由文本。
Args:
raw: 上游 source / highlight_source。
Returns:
冻结集合内的来源码。
"""
text = str(raw or '').strip()[:64]
if text in HIGHLIGHT_SOURCE_VALUES:
return text
if text in {'pdfium', 'native_text', 'pdftotext'}:
return 'native_glyph'
if text.startswith('ocr'):
return 'ocr'
if text:
return 'machine_extraction'
return 'unknown'
def _normalize_compare_text(raw: Any) -> str:
"""轻量规范化:折叠空白,供值/引文比对,不改业务字段。"""
return ' '.join(str(raw if raw is not None else '').split()).strip()
def classify_value_match_status(
*,
machine_value: Any,
quote: str | None,
bbox_text: str | None = None,
quote_source: str | None = None,
upstream: str | None = None,
) -> ValueMatchStatus:
"""
判定值匹配状态;必须依赖 bbox/cell 独立文本,禁止 machine_value 自报 quote。
核心逻辑:优先用 bbox_text;否则仅当 quote_source 属于独立来源时使用 quote;
缺少独立引文时返回 unchecked(不得因 quote==value 升 matched)。
Args:
machine_value: 字段识别值。
quote: 证据引文(可能被错误设为 machine 回声)。
bbox_text: 从 value_bbox 绑定 token/glyph 重读的文本。
quote_source: 引文来源;须为 INDEPENDENT_QUOTE_SOURCES 之一才可比对。
upstream: 上游已声明的 value_match_status。
Returns:
matched / mismatched / unchecked / empty。
"""
if upstream in VALUE_MATCH_STATUS_VALUES:
return upstream # type: ignore[return-value]
value_text = _normalize_compare_text(machine_value)
if not value_text:
return 'empty'
evidence_text = _normalize_compare_text(bbox_text)
source = str(quote_source or '').strip()
if not evidence_text:
if source in INDEPENDENT_QUOTE_SOURCES:
evidence_text = _normalize_compare_text(quote)
else:
return 'unchecked'
if not evidence_text:
return 'unchecked'
if value_text.casefold() == evidence_text.casefold():
return 'matched'
# 引文常含标签噪声;仅做包含关系的弱匹配,不升为 verified。
if value_text.casefold() in evidence_text.casefold() or evidence_text.casefold() in value_text.casefold():
return 'matched'
return 'mismatched'
def _coerce_issue_codes(raw: Any, *, fallback: str | None = None) -> list[str]:
"""裁剪并过滤 issue code 到冻结集合;未知码丢弃,避免污染契约。"""
codes: list[str] = []
if isinstance(raw, (list, tuple, set)):
for item in raw:
code = str(item or '').strip()
if code in COORDINATE_ISSUE_CODES and code not in codes:
codes.append(code)
if not codes and fallback and fallback in COORDINATE_ISSUE_CODES:
codes.append(fallback)
return codes
def _upstream_quality(observation: dict[str, Any], layout_evidence: dict[str, Any]) -> str | None:
"""读取上游已声明质量;非法值忽略,由本模块重新分类。"""
for container in (layout_evidence, observation):
for key in _UPSTREAM_STATUS_KEYS:
value = str(container.get(key) or '').strip()
if value in HIGHLIGHT_QUALITY_VALUES:
return value
return None
def build_field_highlight_projection(
*,
normalized_bbox: dict[str, float] | None,
raw_bbox_present: bool = False,
raw_bbox_invalid: bool = False,
page_no: int | None,
source: Any = None,
machine_value: Any = None,
quote: str | None = None,
bbox_text: str | None = None,
quote_source: str | None = None,
evidence_ref: str | None = None,
token_ids: list[str] | None = None,
coordinate_issue_codes: list[str] | None = None,
observation: dict[str, Any] | None = None,
layout_evidence: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
构建字段级高亮投影 DTO(阶段 0 冻结形状)。
核心逻辑:
- 非法/缺失坐标 → unavailable 或 invalid,highlight_bbox 必为 null;
- 有合法归一化 bbox 但未通过完整质量门禁 → candidate(阶段 0 默认不升 verified);
- 仅当上游显式声明 verified、几何可用且值与独立 bbox/cell 文本 matched 时保留 verified;
- 值文本不一致时降为 invalid,禁止绘制;
- quote 若非独立来源,不得自证 matched;
- 本投影不读取也不写入自动确认/建单门禁字段。
Args:
normalized_bbox: 已通过 0..1 校验的 bbox;None 表示不可绘制。
raw_bbox_present: 上游曾提供 bbox 结构(可能非法)。
raw_bbox_invalid: 上游 bbox 存在但未通过几何校验。
page_no: 证据页码(>=1);缺失时不影响字段值。
source: 坐标/证据来源。
machine_value: 识别值(仅用于值匹配,不回写)。
quote: 引文。
bbox_text: bbox 内独立文本。
quote_source: 引文来源码。
evidence_ref: 稳定证据引用串。
token_ids: glyph/OCR token 标识列表。
coordinate_issue_codes: 上游已收集的 issue code。
observation: 原始 observation(可选,读取上游状态)。
layout_evidence: layout_evidence 子对象(可选)。
Returns:
含 highlight_quality / highlight_bbox / coordinate_* / evidence_ref 等冻结字段的字典。
"""
obs = observation if isinstance(observation, dict) else {}
layout = layout_evidence if isinstance(layout_evidence, dict) else {}
highlight_source = normalize_highlight_source(
layout.get('highlight_source') or layout.get('source') or source or obs.get('source'),
)
resolved_bbox_text = (
bbox_text if bbox_text is not None else layout.get('bbox_text') or obs.get('bbox_text')
)
resolved_quote_source = (
quote_source if quote_source is not None
else layout.get('quote_source') or obs.get('quote_source')
)
value_match = classify_value_match_status(
machine_value=machine_value,
quote=quote,
bbox_text=str(resolved_bbox_text) if resolved_bbox_text is not None else None,
quote_source=str(resolved_quote_source) if resolved_quote_source is not None else None,
upstream=str(layout.get('value_match_status') or obs.get('value_match_status') or '') or None,
)
tokens = [str(item) for item in (token_ids if token_ids is not None else layout.get('token_ids') or []) if str(item)]
ref = str(evidence_ref if evidence_ref is not None else layout.get('evidence_ref') or '')[:256] or None
issues = _coerce_issue_codes(coordinate_issue_codes if coordinate_issue_codes is not None else layout.get('coordinate_issue_codes'))
upstream = _upstream_quality(obs, layout)
quality: HighlightQuality
drawable_bbox = normalized_bbox if isinstance(normalized_bbox, dict) else None
# [STEP 1] 几何非法(归一化候选缺键/倒置/越界)→ invalid,禁止绘制
if raw_bbox_invalid:
quality = 'invalid'
drawable_bbox = None
issues = _coerce_issue_codes(issues, fallback='coordinate_bbox_invalid')
# [STEP 2] 值框文本明确不一致:保留合法 bbox,降为红色诊断高亮,
# 让用户仍可核对系统实际取值位置。
elif value_match == 'mismatched' and drawable_bbox is not None:
quality = 'invalid'
issues = _coerce_issue_codes(issues, fallback='value_bbox_text_mismatch')
# [STEP 3] 无可靠可绘制坐标(含绝对坐标缺页尺寸无法换算)
elif drawable_bbox is None:
quality = 'unavailable' if upstream != 'invalid' else 'invalid'
if quality == 'invalid':
issues = _coerce_issue_codes(issues, fallback='coordinate_bbox_invalid')
elif page_no is None or int(page_no) < 1:
issues = _coerce_issue_codes(
issues,
fallback='coordinate_page_missing' if page_no is None else 'coordinate_page_out_of_range',
)
else:
# 上游给过结构但未能解析为可绘制 bbox,仍按缺失降级,不伪造位置
issues = _coerce_issue_codes(issues, fallback='coordinate_missing')
# [STEP 4] 上游 verified 且几何可用且独立文本 matched 才保留;否则最高为 candidate
elif upstream == 'verified':
if value_match == 'matched':
quality = 'verified'
else:
# 无独立引文证明时不得宣称 verified
quality = 'candidate'
if value_match == 'unchecked':
issues = _coerce_issue_codes(issues, fallback='quote_not_independent')
elif upstream == 'invalid':
quality = 'invalid'
drawable_bbox = None
issues = _coerce_issue_codes(issues, fallback='coordinate_bbox_invalid')
elif upstream == 'unavailable':
quality = 'unavailable'
drawable_bbox = None
issues = _coerce_issue_codes(issues, fallback='coordinate_missing')
else:
quality = 'candidate'
if value_match == 'unchecked' and 'quote_not_independent' not in issues:
issues = _coerce_issue_codes(issues, fallback='quote_not_independent')
# [STEP 5] OCR 坐标不得自动提升为 verified(须经批准标注模板与盲测门禁,阶段 2)
if highlight_source == 'ocr' and quality == 'verified':
quality = 'candidate'
if not should_draw_highlight(quality):
drawable_bbox = None
coordinate_status: CoordinateStatus = quality
drawable = should_draw_highlight(quality)
reliable = quality == 'verified'
return {
'highlight_quality': quality,
'highlight_source': highlight_source,
'highlight_bbox': drawable_bbox,
'coordinate_status': coordinate_status,
'coordinate_issue_codes': issues,
'evidence_ref': ref,
'token_ids': tokens,
'value_match_status': value_match,
'quote_source': str(resolved_quote_source or '')[:64] or None,
'bbox_text': str(resolved_bbox_text)[:1000] if resolved_bbox_text not in (None, '') else None,
# 显式语义,避免调用方自行解释 candidate
'drawable': drawable,
'reliable': reliable,
'requires_review': not reliable,
}
@@ -66,8 +66,48 @@ def complete_freight_cancellation(
if new.lifecycle_status == 'blocked' and new.pending_human_reason == 'freight_cancellation_required': if new.lifecycle_status == 'blocked' and new.pending_human_reason == 'freight_cancellation_required':
new.lifecycle_status = 'active' new.lifecycle_status = 'active'
new.pending_human_reason = None new.pending_human_reason = None
db.session.add(ShippingTaskEvent(task_id=old.id, event_type='freight_cancellation_completed', actor_id=actor_id, detail_json={'cancellation_id': row.id, 'receipt_no': receipt, 'new_task_no': new.task_no})) db.session.add(ShippingTaskEvent(
db.session.add(ShippingTaskEvent(task_id=new.id, event_type='supersession_unblocked', actor_id=actor_id, detail_json={'cancellation_id': row.id, 'old_task_no': old.task_no})) task_id=old.id,
event_type='freight_cancellation_completed',
actor_id=actor_id,
detail_json={
'cancellation_id': row.id,
'receipt_no': receipt,
'new_task_no': new.task_no,
'reason_code': 'task_voided_for_correction',
},
))
db.session.add(ShippingTaskEvent(
task_id=new.id,
event_type='supersession_unblocked',
actor_id=actor_id,
detail_json={'cancellation_id': row.id, 'old_task_no': old.task_no},
))
# 统一审计:货代回执登记必须可按 reason_code 检索
record_fulfillment_audit(
event_type='freight_cancellation_completed',
aggregate_type='shipping_task',
aggregate_id=str(old.task_no),
action='complete_freight_cancellation',
actor_type='user',
actor_id=int(actor_id),
task_no=str(old.task_no),
reason_code='task_voided_for_correction',
result='success',
before={'lifecycle_status': 'active'},
after={
'lifecycle_status': 'voided',
'freight_receipt_no': receipt,
'new_task_no': new.task_no,
'cancellation_id': int(row.id),
},
metadata={
'cancellation_id': int(row.id),
'receipt_asset_id': int(receipt_asset_id),
'new_task_no': str(new.task_no),
},
source='workspace_api',
)
return row return row
@@ -149,10 +189,15 @@ def mark_cancelled_task_readonly(
task_no=str(task.task_no), task_no=str(task.task_no),
workflow_item_id=workflow_item_no, workflow_item_id=workflow_item_no,
conversation_id=task.conversation_id, conversation_id=task.conversation_id,
reason_code='task_cancelled_by_user',
reason=reason_text, reason=reason_text,
before=before, before=before,
after=after, after=after,
metadata={'physical_delete': False, 'excel_readonly': True}, metadata={
'physical_delete': False,
'excel_readonly': True,
'reason_code': 'task_cancelled_by_user',
},
source='workspace_api', source='workspace_api',
) )
db.session.flush() db.session.flush()
@@ -165,13 +165,18 @@ def record_access_audit(
workflow_item_version_id: str | None = None, workflow_item_version_id: str | None = None,
version_no: int | None = None, version_no: int | None = None,
owner_user_id: str | int | None = None, owner_user_id: str | int | None = None,
reason_code: str | None = None,
metadata: dict[str, Any] | None = None, metadata: dict[str, Any] | None = None,
strict: bool = True, strict: bool = True,
) -> bool: ) -> bool:
""" """
记录敏感读取/导出访问审计(无业务正文);每次调用均落库。 记录敏感读取/导出访问审计(无业务正文);每次调用均落库。
核心逻辑:自行提交;失败时回滚并按 strict 抛错,禁止静默丢审计;附带客户端哈希。 核心逻辑:自行提交;失败时回滚并按 strict 抛错,禁止静默丢审计;附带客户端哈希;
可选 reason_code 供审计中心按可解释性码筛选(如 Excel 下载)。
Args:
reason_code: 可选稳定原因/动作码(访问类事件通常为业务动作标识)。
Returns: Returns:
True 表示本次写入了新事件。 True 表示本次写入了新事件。
@@ -180,6 +185,10 @@ def record_access_audit(
request_id = _request_id() request_id = _request_id()
client_ip, user_agent = _client_request_context() client_ip, user_agent = _client_request_context()
resolved_reason = str(reason_code or '').strip() or None
meta = dict(metadata or {'access': True})
if resolved_reason:
meta.setdefault('reason_code', resolved_reason)
try: try:
append_shipping_audit_event( append_shipping_audit_event(
event_type='shipping_resource_accessed', event_type='shipping_resource_accessed',
@@ -202,8 +211,9 @@ def record_access_audit(
owner_user_id=owner_user_id, owner_user_id=owner_user_id,
client_ip=client_ip, client_ip=client_ip,
user_agent=user_agent, user_agent=user_agent,
reason_code=resolved_reason,
result='success', result='success',
metadata=metadata or {'access': True}, metadata=meta,
source='api', source='api',
persist_snapshots=False, persist_snapshots=False,
sensitivity_level='sensitive', sensitivity_level='sensitive',
@@ -1,15 +1,16 @@
""" """
services/shipping_notice/fulfillment_workflow.py services/shipping_notice/fulfillment_workflow.py
用途:发货通知履约阶段 — 库存匹配、Excel 导出、人工上传凭据登记与自动串联编排。 用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传(RPA/人工)与自动串联编排。
依赖:customer_identity_gate、reservation_gate、match、export、query_service、inventory_workflow、 依赖:customer_identity_gate、reservation_gate、match、export、query_service、inventory_workflow、
inventory_mapping_workflow、stp_line_inventory_match、upload_attempt_service、动态订单字段、 inventory_mapping_workflow、stp_line_inventory_match、upload_attempt_service、rpa.write_upload_trigger、
tool_common、tool_response、fulfillment_audit。 tool_common、tool_response、fulfillment_audit。
逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match; 逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match;
STP 多候选:跨文件匹配后仅全部 ok 记 completed+100% 并自动 Excel;partial/冲突记 needs_human; STP 多候选:跨文件匹配后仅全部 ok 记 completed+100% 并自动 Excel;partial/冲突记 needs_human;
STP:auto_progress / try_auto_chain_after_match 止于 Excel 后待人工上传登记(manual_upload_pending); AUTO_UPLOAD 默认 false(须环境显式 true;缺失键 fail-closed 并告警);
开启时 Excel 后先做货代 RPA 就绪校验再触发(stage=upload_rpa_pending);关闭时停于人工上传;
工作台操作人经 operator_id / actor_id / _trusted_user_id 写入匹配与审计事件; 工作台操作人经 operator_id / actor_id / _trusted_user_id 写入匹配与审计事件;
upload_to_freight 仅允许 mode=manual_confirm(工作台 mark-manual-uploaded);禁止 RPA auto/retry。 upload_to_freight 支持 mode=auto|retry_upload(RPA)与 manual_confirm(人工凭据)。
""" """
from __future__ import annotations from __future__ import annotations
@@ -22,7 +23,7 @@ from typing import Any
from flask import current_app from flask import current_app
from app import db from app import db
from app.core.errors import ConflictError, ValidationError from app.core.errors import ConflictError, ServiceUnavailableError, ValidationError
from app.models import ShippingTask from app.models import ShippingTask
from app.services.shipping_notice.constants import CP_UPLOADED from app.services.shipping_notice.constants import CP_UPLOADED
from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values
@@ -41,7 +42,12 @@ from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.order_field_purposes import task_line_purpose_values from app.services.shipping_notice.order_field_purposes import task_line_purpose_values
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues 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.task_field_gate import field_conflict_gate_response
from app.services.shipping_notice.upload_attempt_service import complete_attempt, record_manual_upload from app.services.shipping_notice.upload_attempt_service import (
complete_attempt,
record_manual_upload,
start_rpa_attempt,
)
from app.services.shipping_notice.rpa import write_upload_trigger
from app.services.shipping_notice.rpa_attempts import ( from app.services.shipping_notice.rpa_attempts import (
max_rpa_upload_attempts, max_rpa_upload_attempts,
upload_rpa_attempts, upload_rpa_attempts,
@@ -55,6 +61,15 @@ from app.services.shipping_notice.task_disposition_service import task_execution
def _cfg_bool(key: str, default: bool = False) -> bool: def _cfg_bool(key: str, default: bool = False) -> bool:
"""
读取布尔配置;键缺失时返回 default(调用方须与 settings 默认值对齐)。
Args:
key: Flask config 键。
default: 键缺失时的回退值。
"""
if key not in current_app.config:
return default
val = current_app.config.get(key) val = current_app.config.get(key)
if val is None: if val is None:
return default return default
@@ -151,9 +166,218 @@ def _auto_generate_excel_enabled() -> bool:
return _cfg_bool("SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED", True) return _cfg_bool("SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED", True)
_AUTO_UPLOAD_MISSING_LOGGED = False
def is_auto_upload_enabled() -> bool:
"""
读取货代自动上传 RPA 开关;与 settings 默认 false 对齐(生产安全)。
核心逻辑:键缺失时 fail-closed 为 False 并告警一次;仅显式 true 才自动上传。
Returns:
True 表示 Excel 后应触发货代上传 RPA。
"""
global _AUTO_UPLOAD_MISSING_LOGGED
key = 'SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'
if key not in current_app.config:
if not _AUTO_UPLOAD_MISSING_LOGGED:
current_app.logger.warning(
'Config %s missing; defaulting to False (fail-closed). '
'Set explicitly to true only after freight RPA Worker/credentials/isolation are ready.',
key,
)
_AUTO_UPLOAD_MISSING_LOGGED = True
return False
return _cfg_bool(key, False)
def _auto_upload_enabled() -> bool: def _auto_upload_enabled() -> bool:
"""读取货代自动上传开关;STP 自动链已忽略该开关,仅保留配置探测/兼容读取。""" """内部别名:读取货代自动上传 RPA 开关。"""
return _cfg_bool("SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED", False) return is_auto_upload_enabled()
def _rpa_upload_timeout_seconds() -> int:
"""货代上传 RPA 等待回调超时秒数。"""
try:
return max(int(current_app.config.get('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or 30), 1)
except (TypeError, ValueError):
return 30
def _trigger_freight_upload_rpa(
task: ShippingTask,
*,
payload: dict[str, Any] | None = None,
lang: str | None = None,
) -> dict[str, Any]:
"""
触发货代上传 RPA:创建 Attempt、写 trigger、进入 upload_rpa_pending。
核心逻辑:达最大次数则转人工;trigger 目录不可用时返回失败并允许手工上传。
Args:
task: 已生成 Excel 的任务。
payload: 可选请求体(artifact_id / idempotency_key)。
lang: 文案语言。
Returns:
Tool 响应(running / needs_human / failed)。
"""
lang = lang or resolve_lang(payload or {})
body = dict(payload or {})
attempts = upload_rpa_attempts(task)
max_attempts = max_rpa_upload_attempts()
if attempts >= max_attempts:
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
task.error_message = t('workflow.fulfillment.upload_exhausted', lang=lang).format(attempts=attempts)
log_task_event(task, 'upload_rpa_exhausted', {'attempts': attempts, 'max_attempts': max_attempts})
db.session.commit()
return tool_response(
status='needs_human',
task=task,
message=task.error_message,
data=serialize_task_for_tool(task),
stop_agent_turn=True,
)
if not task.export_file_path:
return tool_response(
status='failed',
task=task,
message=t('workflow.fulfillment.upload_trigger_failed', lang=lang),
data=serialize_task_for_tool(task),
)
# [STEP] 自动上传前强制系统级就绪:Worker / 凭据 / 共享目录 / 环境隔离 / 回调基址。
try:
from app.services.shipping_notice.rpa_worker_heartbeat import assert_freight_upload_rpa_ready
assert_freight_upload_rpa_ready()
except ServiceUnavailableError as exc:
detail = ''
if isinstance(exc.details, dict):
detail = str(exc.details.get('detail_message') or '').strip()
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
task.error_message = detail or str(exc.message or exc)
log_task_event(
task,
'upload_rpa_not_ready',
{'reasons': (exc.details or {}).get('reasons') if isinstance(exc.details, dict) else []},
)
db.session.commit()
return tool_response(
status='needs_human',
task=task,
message=task.error_message,
data=serialize_task_for_tool(task),
stop_agent_turn=True,
next_required_action='货代上传 RPA 未就绪:请启动 Worker、核对凭据与共享目录后重试,或人工上传并登记凭据。',
)
artifact_id = body.get('artifact_id')
try:
artifact_id = int(artifact_id) if artifact_id is not None else None
except (TypeError, ValueError):
return tool_response(status='failed', task=task, message='artifact_id 无效', data=serialize_task_for_tool(task))
try:
attempt = start_rpa_attempt(
task,
artifact_id=artifact_id,
idempotency_key=str(body.get('idempotency_key') or '').strip() or None,
)
except (ConflictError, ValidationError) as exc:
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
queue_path, trigger_path = write_upload_trigger(
task.task_no,
str(task.export_file_path),
payload={
'attempt_id': int(attempt.id),
'artifact_id': int(attempt.artifact_id),
'mode': str(body.get('mode') or 'auto'),
},
)
if not trigger_path:
attempt.status = 'failed'
attempt.error_message = 'upload trigger directory unavailable'
attempt.finished_at = datetime.utcnow()
db.session.flush()
return tool_response(
status='failed',
task=task,
message=t('workflow.fulfillment.upload_trigger_failed', lang=lang),
data=serialize_task_for_tool(task),
stop_agent_turn=True,
next_required_action='请下载 Excel 后人工上传并登记凭据。',
)
apply_task_transition(task, TaskTransition.UPLOAD_RPA_PENDING)
timeout = _rpa_upload_timeout_seconds()
set_task_step_progress(
task,
step_key='step7_upload_freight',
step_title='上传货代',
status='running',
message=t('workflow.fulfillment.upload_triggered_wait', lang=lang),
progress_percent=80,
detail=t('workflow.fulfillment.upload_triggered_detail', lang=lang).format(
attempt=attempts + 1, max_attempts=max_attempts,
),
)
log_task_event(
task,
'upload_rpa_triggered',
{
'attempt_id': int(attempt.id),
'artifact_id': int(attempt.artifact_id),
'queue_path': queue_path,
'trigger_path': trigger_path,
'attempt_no': attempts + 1,
'max_attempts': max_attempts,
},
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='upload_rpa_triggered',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='trigger_freight_upload_rpa',
actor_type='system',
task_no=task.task_no,
conversation_id=task.conversation_id,
before={'process_status': 'waiting_upload'},
after={'process_status': str(task.process_status or ''), 'pending_human_reason': 'upload_rpa_pending'},
metadata={'attempt_id': int(attempt.id), 'artifact_id': int(attempt.artifact_id)},
source='system',
)
# DB 生命周期仍用开放桶 manual_upload_pending(避免迁移 CHECK);投影层须用
# display_lifecycle_status / is_waiting_manual_upload / upload_phase,禁止调用方单靠 lifecycle 推断人工待办。
_sync_workflow_stage(
task,
lifecycle_status='manual_upload_pending',
stage='upload_rpa_pending',
event_code='upload_rpa_triggered',
actor_id=None,
payload={
'task_no': task.task_no,
'attempt_id': int(attempt.id),
'pending_human_reason': 'upload_rpa_pending',
'upload_phase': 'rpa_pending',
'is_waiting_manual_upload': False,
},
)
db.session.commit()
return tool_response(
status='running',
task=task,
message=t('workflow.fulfillment.upload_triggered_message', lang=lang).format(
attempt=attempts + 1, max_attempts=max_attempts, timeout=timeout,
),
data=serialize_task_for_tool(task),
stop_agent_turn=True,
)
def _event_actor_id(payload: dict[str, Any]) -> int | None: def _event_actor_id(payload: dict[str, Any]) -> int | None:
@@ -181,6 +405,7 @@ def _sync_workflow_stage(
actor_id: int | None = None, actor_id: int | None = None,
payload: dict[str, Any] | None = None, payload: dict[str, Any] | None = None,
excel_artifact_no: str | None = None, excel_artifact_no: str | None = None,
stage: str | None = None,
) -> None: ) -> None:
""" """
将任务绑定的 WorkflowItem 推进到履约阶段;未绑定则静默跳过。 将任务绑定的 WorkflowItem 推进到履约阶段;未绑定则静默跳过。
@@ -191,6 +416,7 @@ def _sync_workflow_stage(
event_code: WorkflowEvent 事件码。 event_code: WorkflowEvent 事件码。
actor_id: 可选操作人。 actor_id: 可选操作人。
payload / excel_artifact_no: 可选事件载荷与 Excel 工件号。 payload / excel_artifact_no: 可选事件载荷与 Excel 工件号。
stage: 可选细粒度阶段(如 upload_rpa_pending),可与 lifecycle 不同。
""" """
from app.services.shipping_notice.workflow_ledger_service import sync_workflow_item_stage_for_task from app.services.shipping_notice.workflow_ledger_service import sync_workflow_item_stage_for_task
@@ -202,6 +428,7 @@ def _sync_workflow_stage(
actor_id=actor_id, actor_id=actor_id,
payload=payload, payload=payload,
excel_artifact_no=excel_artifact_no, excel_artifact_no=excel_artifact_no,
stage=stage,
) )
@@ -292,10 +519,11 @@ def try_auto_chain_after_match(
payload: dict[str, Any] | None = None, payload: dict[str, Any] | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
""" """
匹配成功后自动串联 Excel 导出,并停在 wait_manual_upload(待人工上传登记)。 匹配成功后自动串联 Excel 导出;AUTO_UPLOAD 开启时继续触发货代上传 RPA。
核心逻辑:match_result 为 ok 后默认自动生成 Excel;无论 核心逻辑:match_result 为 ok 后默认自动生成 Excel;
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 为何值,硬禁止自动货代 RPA 上传。 SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true 时调用 upload_to_freight(mode=auto);
关闭时停在 wait_manual_upload 待人工登记。
Args: Args:
task: 当前 ShippingTask。 task: 当前 ShippingTask。
@@ -325,13 +553,20 @@ def try_auto_chain_after_match(
return gen return gen
result = prepend_tool_message(gen, str(result.get("message") or "")) result = prepend_tool_message(gen, str(result.get("message") or ""))
# [STEP 2] STP 硬停:Excel 就绪后进入 wait_manual_upload;绝不调用 upload_to_freight。 # [STEP 2] Excel 就绪后:开启 AUTO_UPLOAD 则触发货代 RPA,否则停待人工上传。
# 即便 _auto_upload_enabled() 为 True 也不得突破(首期无货代 RPA 自动上传)。
db.session.refresh(task) db.session.refresh(task)
ui = resolve_task_ui_state(task) ui = resolve_task_ui_state(task)
if ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or ( excel_ready = ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or (
task.export_file_path and task.process_status != "uploaded" task.export_file_path and task.process_status != "uploaded"
): )
if excel_ready and _auto_upload_enabled():
upload_result = upload_to_freight({
**tool_payload,
'task_id': task.task_no,
'mode': 'auto',
})
return prepend_tool_message(upload_result, str(result.get('message') or ''))
if excel_ready:
return tool_response( return tool_response(
status="ok", status="ok",
task=task, task=task,
@@ -784,11 +1019,22 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
try: try:
path, filename, artifact = generate_shipment_excel(task) path, filename, artifact = generate_shipment_excel(task)
except (ConflictError, ValueError) as exc: except (ConflictError, ValueError) as exc:
from app.services.shipping_notice.error_explainability_contract import (
classify_excel_generate_error,
)
reason_code = classify_excel_generate_error(str(exc))
return tool_response( return tool_response(
status="failed", status="failed",
task=task, task=task,
message=str(exc), message=str(exc),
data=serialize_task_for_tool(task), data={
**serialize_task_for_tool(task),
'reason_code': reason_code,
'explainability': {
'reason_code': reason_code,
},
},
forbidden_next_tools=["upload_to_freight"], forbidden_next_tools=["upload_to_freight"],
) )
task.export_file_path = path task.export_file_path = path
@@ -814,6 +1060,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
actor_id=actor_id, actor_id=actor_id,
task_no=task.task_no, task_no=task.task_no,
conversation_id=task.conversation_id, conversation_id=task.conversation_id,
reason_code='excel_downloaded',
before={'status': 'matched'}, before={'status': 'matched'},
after={'status': 'waiting_upload'}, after={'status': 'waiting_upload'},
metadata={'artifact_no': artifact.artifact_no}, metadata={'artifact_no': artifact.artifact_no},
@@ -839,17 +1086,19 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
""" """
登记人工货代上传完成(首期唯一上传收口)。 货代上传入口:RPA 自动/重试,或人工凭据登记。
【AI 触发时机】:禁止调用;仅工作台 mark-manual-uploaded 以 mode=manual_confirm 调用。 【AI 触发时机】:AUTO_UPLOAD 开启且 Excel 就绪时可由 auto_progress 以 mode=auto 调用;
人工接管后使用 mode=manual_confirm。
核心逻辑:硬拒绝 auto/retry_upload(不触发货代 RPA);manual_confirm 校验凭据后标记 UPLOADED, 核心逻辑:mode=auto|retry_upload → 触发 RPA(受 AUTO_UPLOAD 与重试上限约束);
写履约审计并将 WorkflowItem 以 closed_reason=confirmed 收口。 mode=manual_confirm → 校验凭据后标记 UPLOADED 并关闭 WorkflowItem。
Args: Args:
payload: 须含 task_id;mode 必须为 manual_confirm;须含 evidence_asset_no、operator_id。 payload: 须含 task_id;mode=auto|retry_upload|manual_confirm;
manual_confirm 须含 evidence_asset_no、operator_id。
Returns: Returns:
dict[str, Any]: status 可为 ok / failed。 dict[str, Any]: status 可为 ok / running / needs_human / failed。
""" """
lang = resolve_lang(payload) lang = resolve_lang(payload)
task = resolve_task_from_payload(payload) task = resolve_task_from_payload(payload)
@@ -889,7 +1138,6 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
if gen.get("status") != "ok": if gen.get("status") != "ok":
return gen return gen
# [STEP 2] 仅允许 manual_confirm;禁止 auto/retry_upload 触发 RPA。
artifact_id = payload.get('artifact_id') artifact_id = payload.get('artifact_id')
try: try:
artifact_id = int(artifact_id) if artifact_id is not None else None artifact_id = int(artifact_id) if artifact_id is not None else None
@@ -897,18 +1145,31 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(status='failed', task=task, message='artifact_id 无效', data=serialize_task_for_tool(task)) return tool_response(status='failed', task=task, message='artifact_id 无效', data=serialize_task_for_tool(task))
mode = str(payload.get("mode") or "auto").strip().lower() mode = str(payload.get("mode") or "auto").strip().lower()
# [STEP 2] RPA 自动/重试上传。
if mode in {'auto', 'retry_upload', 'retry'}:
if not _auto_upload_enabled() and mode == 'auto':
return tool_response(
status='failed',
task=task,
message='货代自动上传未开启,请人工下载 Excel 并登记上传凭据。',
data=serialize_task_for_tool(task),
forbidden_next_tools=['upload_to_freight'],
stop_agent_turn=True,
next_required_action='请在任务处理工作台使用「登记人工上传」。',
)
return _trigger_freight_upload_rpa(
task,
payload={**payload, 'artifact_id': artifact_id, 'mode': mode},
lang=lang,
)
if mode != "manual_confirm": if mode != "manual_confirm":
return tool_response( return tool_response(
status="failed", status="failed",
task=task, task=task,
message=( message="upload_to_freight mode 须为 auto、retry_upload 或 manual_confirm。",
"首期不支持货代 RPA 自动上传。请下载 Excel,在货代系统人工上传后,"
"于任务处理工作台提交截图/PDF 凭据。"
),
data=serialize_task_for_tool(task), data=serialize_task_for_tool(task),
forbidden_next_tools=["upload_to_freight"], forbidden_next_tools=["upload_to_freight"],
stop_agent_turn=True, stop_agent_turn=True,
next_required_action="请在任务处理工作台使用「登记人工上传」。",
) )
operator_id = payload.get('operator_id') operator_id = payload.get('operator_id')
@@ -943,6 +1204,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
actor_id=attempt.operator_id, actor_id=attempt.operator_id,
task_no=task.task_no, task_no=task.task_no,
conversation_id=task.conversation_id, conversation_id=task.conversation_id,
reason_code='task_closed_after_upload',
before={'process_status': before_status or 'waiting_upload'}, before={'process_status': before_status or 'waiting_upload'},
after={'process_status': str(task.process_status or 'uploaded')}, after={'process_status': str(task.process_status or 'uploaded')},
metadata={ metadata={
@@ -1053,6 +1315,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
actor_type='rpa', actor_type='rpa',
task_no=task.task_no, task_no=task.task_no,
conversation_id=task.conversation_id, conversation_id=task.conversation_id,
reason_code='task_closed_after_upload',
result='success', result='success',
before={'status': 'uploading'}, before={'status': 'uploading'},
after={'status': 'uploaded'}, after={'status': 'uploaded'},
@@ -1103,11 +1366,10 @@ def run_auto_progress_fulfillment_steps(
steps: list[str], steps: list[str],
) -> dict[str, Any] | None: ) -> dict[str, Any] | None:
""" """
auto_progress 中匹配→导出编排;有早停响应时返回 dict,否则返回 None。 auto_progress 中匹配→导出→可选货代上传 RPA;有早停响应时返回 dict,否则返回 None。
核心逻辑:自动匹配与生成 Excel;硬禁止自动货代上传(含 RPA), 核心逻辑:自动匹配与生成 Excel;AUTO_UPLOAD 开启时触发 upload_to_freight(mode=auto);
停在 wait_manual_upload。无论 SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 为何值, 关闭时停在 wait_manual_upload 待人工登记。
本函数永不调用 upload_to_freight;货代 RPA 上传不在自动链范围内。
""" """
from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state
@@ -1125,12 +1387,19 @@ def run_auto_progress_fulfillment_steps(
return gen return gen
steps.append("生成发货 Excel") steps.append("生成发货 Excel")
# [STEP 3] STP 停点:Excel 已生成则进入 wait_manual_upload。 # [STEP 3] Excel 就绪后按开关触发货代 RPA,或停待人工上传。
# AUTO_UPLOAD 分支已硬禁用,绝不 enqueue 货代 RPA。
ui = resolve_task_ui_state(task) ui = resolve_task_ui_state(task)
if ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or ( excel_ready = ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or (
task.export_file_path and task.process_status != "uploaded" task.export_file_path and task.process_status != "uploaded"
): )
if excel_ready and _auto_upload_enabled():
steps.append("触发货代上传 RPA")
return upload_to_freight({
"task_id": task.task_no,
**(payload or {}),
"mode": "auto",
})
if excel_ready:
steps.append("等待人工上传登记") steps.append("等待人工上传登记")
return tool_response( return tool_response(
status="ok", status="ok",
@@ -2,8 +2,10 @@
backend/app/services/shipping_notice/generic_order_evidence.py backend/app/services/shipping_notice/generic_order_evidence.py
用途:将 layout_schema_candidates 中的字段候选链接到 cell/token 级证据引用。 用途:将 layout_schema_candidates 中的字段候选链接到 cell/token 级证据引用。
依赖:无外部 I/O;消费 schema_mapping 产出的 fields 行结构。 依赖:无外部 I/O;消费 schema_mapping 产出的 fields 行结构;高亮质量字段与
逻辑:generic_order_parser 组装订单观测值时调用;每条 observation 必须可回溯到 evidence_ref/token_ids。 field_highlight_contract 对齐(本模块只透传,不裁决绘制质量)。
逻辑:generic_order_parser 组装订单观测值时调用;每条 observation 必须可回溯到
evidence_ref/token_ids;quote/bbox_text 取自 layout 独立文本,禁止用识别值自证。
""" """
from __future__ import annotations from __future__ import annotations
@@ -19,7 +21,8 @@ def build_field_observation(
""" """
把映射字段候选转换为订单字段 observation,并保留 layout 证据链接。 把映射字段候选转换为订单字段 observation,并保留 layout 证据链接。
核心逻辑:quote 取自单元格文本;layout_evidence 写入 page/table/cell/token 身份,禁止丢失 evidence_ref。 核心逻辑:quote 优先 bbox_text / 上游 quote / cell 文本,绝不回退到识别值;
layout_evidence 写入 page/table/cell/token 与 value/cell bbox;坐标质量仅透传。
Args: Args:
field: schema_mapping 产出的单行字段候选(含 value/cell_id/token_ids/evidence_ref)。 field: schema_mapping 产出的单行字段候选(含 value/cell_id/token_ids/evidence_ref)。
@@ -29,13 +32,15 @@ def build_field_observation(
含 value、document_id、quote、confidence 与 layout_evidence 的 observation 字典。 含 value、document_id、quote、confidence 与 layout_evidence 的 observation 字典。
""" """
value = field.get('value') value = field.get('value')
quote = str(value if value not in (None, '') else field.get('quote') or '')[:1000] bbox_text = str(field.get('bbox_text') or '').strip()
return { quote_source = str(field.get('quote_source') or '').strip()
'value': value, # [STEP] 独立引文:禁止 quote=value 自证;缺独立文本时 quote 留空,投影为 unchecked
'document_id': int(document_id), quote = str(field.get('quote') or bbox_text or '')[:1000]
'quote': quote, if quote and not quote_source:
'confidence': 1.0, quote_source = 'bbox_tokens' if bbox_text else 'layout_cell_text'
'layout_evidence': { if not quote:
quote_source = ''
layout_evidence: dict[str, Any] = {
'page_no': field.get('page_no'), 'page_no': field.get('page_no'),
'table_id': field.get('table_id'), 'table_id': field.get('table_id'),
'row_index': field.get('row_index'), 'row_index': field.get('row_index'),
@@ -43,7 +48,44 @@ def build_field_observation(
'cell_id': field.get('cell_id'), 'cell_id': field.get('cell_id'),
'token_ids': list(field.get('token_ids') or []), 'token_ids': list(field.get('token_ids') or []),
'evidence_ref': str(field.get('evidence_ref') or ''), 'evidence_ref': str(field.get('evidence_ref') or ''),
}, }
if quote_source:
layout_evidence['quote_source'] = quote_source
if bbox_text:
layout_evidence['bbox_text'] = bbox_text[:1000]
# [STEP] 显式声明是否具备字段值级坐标,供证据投影禁止根级/整格回退
if 'has_value_coordinate' in field:
layout_evidence['has_value_coordinate'] = bool(field.get('has_value_coordinate'))
elif 'value_bbox' in field:
layout_evidence['has_value_coordinate'] = field.get('value_bbox') is not None
# [STEP] 透传可选坐标字段;value_bbox/normalized_bbox 即使为 None 也写入,避免投影层误回退
for key in (
'value_bbox',
'normalized_bbox',
'cell_bbox',
'cell_normalized_bbox',
'source',
'highlight_source',
'coordinate_status',
'highlight_quality',
'coordinate_issue_codes',
'value_match_status',
):
if key not in field:
continue
if key in {'value_bbox', 'normalized_bbox'}:
layout_evidence[key] = field.get(key)
elif field.get(key) is not None:
layout_evidence[key] = field.get(key)
return {
'value': value,
'document_id': int(document_id),
'quote': quote,
'confidence': 1.0,
'table_id': field.get('table_id'),
'cell_id': field.get('cell_id'),
'page_no': field.get('page_no'),
'layout_evidence': layout_evidence,
} }
@@ -148,7 +148,7 @@ def _map_gate_codes_to_stable(codes: list[str]) -> list[str]:
'continuation_table': 'generic_gate_blocked', 'continuation_table': 'generic_gate_blocked',
'multiple_customer': 'generic_gate_blocked', 'multiple_customer': 'generic_gate_blocked',
'multiple_business_tables': 'multiple_business_tables', 'multiple_business_tables': 'multiple_business_tables',
'missing_data_rows': 'business_table_not_found', 'missing_data_rows': 'business_table_empty',
'html_table_columns_ambiguous': 'generic_gate_blocked', 'html_table_columns_ambiguous': 'generic_gate_blocked',
'html_table_duplicate_field_columns': 'generic_gate_blocked', 'html_table_duplicate_field_columns': 'generic_gate_blocked',
'html_table_header_value_contamination': 'generic_gate_blocked', 'html_table_header_value_contamination': 'generic_gate_blocked',
@@ -120,9 +120,11 @@ def parse_generic_orders(
line_groups.append({'fields': line_fields}) line_groups.append({'fields': line_fields})
if not line_groups: if not line_groups:
# 有表无有效明细行 → business_table_empty;有行但字段未映射 → required_field_missing
return GenericParseResult( return GenericParseResult(
orders=[], business_table_count=1, parsed_table_count=len(usable_tables), orders=[], business_table_count=1, parsed_table_count=len(usable_tables),
data_row_count=data_row_count, reason_code='business_table_not_found', data_row_count=data_row_count,
reason_code='business_table_empty' if data_row_count == 0 else 'required_field_missing',
) )
header_fields = _merge_header_fields(header_values, po_field_ids=po_field_ids) header_fields = _merge_header_fields(header_values, po_field_ids=po_field_ids)
@@ -132,15 +134,6 @@ def parse_generic_orders(
data_row_count=data_row_count, reason_code='required_field_missing', data_row_count=data_row_count, reason_code='required_field_missing',
) )
missing_required = _missing_required_fields(
definition=definition, header_fields=header_fields, line_groups=line_groups,
)
if missing_required:
return GenericParseResult(
orders=[], business_table_count=1, parsed_table_count=len(usable_tables),
data_row_count=data_row_count, reason_code='required_field_missing',
)
base_order = { base_order = {
'schema_version_id': schema.get('schema_version_id'), 'schema_version_id': schema.get('schema_version_id'),
'schema_checksum': schema.get('checksum'), 'schema_checksum': schema.get('checksum'),
@@ -162,6 +155,17 @@ def parse_generic_orders(
data_row_count=data_row_count, reason_code=partition_reason, data_row_count=data_row_count, reason_code=partition_reason,
) )
# PO 字段先按行分区并提升到订单 Header,再检查最终订单的必填完整性。
if any(_missing_required_fields(
definition=definition,
header_fields=list(order.get('header_fields') or []),
line_groups=list(order.get('lines') or []),
) for order in orders):
return GenericParseResult(
orders=[], business_table_count=1, parsed_table_count=len(usable_tables),
data_row_count=data_row_count, reason_code='required_field_missing',
)
document_id = int(unit.document_id) document_id = int(unit.document_id)
finalized: list[dict[str, Any]] = [] finalized: list[dict[str, Any]] = []
for order in orders: for order in orders:
@@ -245,9 +249,9 @@ def _partition_orders_by_po(
source = field.get('_source_field') if isinstance(field.get('_source_field'), dict) else {} source = field.get('_source_field') if isinstance(field.get('_source_field'), dict) else {}
values.add(json.dumps(source.get('value'), ensure_ascii=False, sort_keys=True)) values.add(json.dumps(source.get('value'), ensure_ascii=False, sort_keys=True))
po_field = field po_field = field
if len(values) != 1: if len(values) > 1:
return [], 'multiple_po_detected' return [], 'multiple_po_detected'
if po_field is not None: if len(values) == 1 and po_field is not None:
line_pos.append((next(iter(values)), group, po_field)) line_pos.append((next(iter(values)), group, po_field))
distinct_pos = {item[0] for item in line_pos} distinct_pos = {item[0] for item in line_pos}
@@ -46,7 +46,15 @@ class InventoryRoutingResult:
def block_reason(self) -> str | None: def block_reason(self) -> str | None:
"""建单阻断原因码;可建单时为 None。""" """建单阻断原因码;可建单时为 None。"""
if self.status == 'conflicted': if self.status == 'conflicted':
# require_manual_review 动作保留原码;其余冲突(含非法动作)用专用冲突码
actions = {
str(item.get('action_type') or '')
for item in (self.matched_rules or ())
if isinstance(item, dict)
}
if 'require_manual_review' in actions:
return 'require_manual_review' return 'require_manual_review'
return 'inventory_source_conflicted'
if not self.source_codes: if not self.source_codes:
return 'no_inventory_source_candidates' return 'no_inventory_source_candidates'
return None return None
@@ -1,9 +1,11 @@
""" """
services/shipping_notice/inventory_rpa_workflow.py 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。 依赖:customer_identity_gate、reservation_gate、rpa、rpa_attempts、inventory_snapshot、
逻辑:inventory_workflow.ensure_inventory 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新;tools 门面 re-export rpa_report_inventory; 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 读取。 Reservation 门禁从当前 Extraction 的动态 FieldValue 读取。
""" """
@@ -669,22 +671,42 @@ def _validate_rpa_callback_round(task: ShippingTask, payload: dict[str, Any]) ->
""" """
run_no_error = _validate_rpa_callback_run_no(task, str(payload.get("run_no") or "")) run_no_error = _validate_rpa_callback_run_no(task, str(payload.get("run_no") or ""))
if run_no_error: if run_no_error:
log_task_event(
task,
"rpa_callback_rejected",
{"run_no_error": run_no_error, "reason_code": "late_callback_ignored"},
source="rpa_callback",
)
return tool_response( return tool_response(
status="failed", status="failed",
task=task, task=task,
message="RPA 回调 run_no 无效或已过期,已拒绝处理", message="RPA 回调 run_no 无效或已过期,已拒绝处理",
data={**serialize_task_for_tool(task), "run_no_error": run_no_error}, data={
**serialize_task_for_tool(task),
"run_no_error": run_no_error,
"reason_code": "late_callback_ignored",
},
) )
replay_error = _validate_rpa_callback_not_replayed( replay_error = _validate_rpa_callback_not_replayed(
task, task,
_resolve_effective_callback_run_no(task, payload), _resolve_effective_callback_run_no(task, payload),
) )
if replay_error: if replay_error:
log_task_event(
task,
"rpa_callback_rejected",
{"run_no_error": replay_error, "reason_code": "late_callback_ignored"},
source="rpa_callback",
)
return tool_response( return tool_response(
status="failed", status="failed",
task=task, task=task,
message="RPA 回调轮次已处理,拒绝重复回调", message="RPA 回调轮次已处理,拒绝重复回调",
data={**serialize_task_for_tool(task), "run_no_error": replay_error}, data={
**serialize_task_for_tool(task),
"run_no_error": replay_error,
"reason_code": "late_callback_ignored",
},
) )
return None return None
@@ -924,6 +946,8 @@ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
if not source_code: if not source_code:
return tool_response(status="failed", task=task, message="请提供库存源编码 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() pending = str(task.pending_human_reason or "").strip()
on_source_gate = pending == PH_INVENTORY_SOURCE_UNRESOLVED on_source_gate = pending == PH_INVENTORY_SOURCE_UNRESOLVED
on_multi_source_block = ( on_multi_source_block = (
@@ -933,6 +957,8 @@ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
if not on_source_gate and not on_multi_source_block: if not on_source_gate and not on_multi_source_block:
return tool_response(status="failed", task=task, message="当前任务不在库存源确认节点") return tool_response(status="failed", task=task, message="当前任务不在库存源确认节点")
before_snapshot = task_lifecycle_audit_snapshot(task)
if on_multi_source_block: if on_multi_source_block:
allowed = set(multi_source_recovery_source_codes(task)) allowed = set(multi_source_recovery_source_codes(task))
if source_code not in allowed: if source_code not in allowed:
@@ -979,8 +1005,12 @@ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
"reason_code": "manual_multi_source_resolve", "reason_code": "manual_multi_source_resolve",
"resolved_ok_source_codes": [source_code], "resolved_ok_source_codes": [source_code],
}, },
actor_id=payload.get("_trusted_user_id"), 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") else 'system', 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) apply_task_transition(task, TaskTransition.REMATCH_REQUESTED)
task.current_step = "step5_match_inventory" task.current_step = "step5_match_inventory"
@@ -1019,7 +1049,13 @@ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
stop_agent_turn=True, stop_agent_turn=True,
) )
confirmed_by = payload.get("_trusted_user_id") 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 快照含确认后的 process_status / phase。
log_task_event( log_task_event(
task, task,
"inventory_source_confirmed", "inventory_source_confirmed",
@@ -1028,16 +1064,13 @@ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
"connector_type": task.inventory_connector_type, "connector_type": task.inventory_connector_type,
"warehouse_id": task.inventory_warehouse_id, "warehouse_id": task.inventory_warehouse_id,
"confirmed_by": confirmed_by or "integration_tool", "confirmed_by": confirmed_by or "integration_tool",
"reason_code": "inventory_source_confirmed",
}, },
actor_id=confirmed_by, actor_id=confirmed_by,
source='workspace_api' if confirmed_by else 'system', source='workspace_api' if confirmed_by else 'system',
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
) )
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"
db.session.commit() db.session.commit()
return tool_response( return tool_response(
@@ -329,12 +329,21 @@ def assert_inventory_source_gate(
code=INVENTORY_SOURCE_ERROR_CODES["changed"], code=INVENTORY_SOURCE_ERROR_CODES["changed"],
message="库存源配置已更新,请重新确认库存查询来源", message="库存源配置已更新,请重新确认库存查询来源",
http_status=409, http_status=409,
details={"operation": operation, "task_no": task.task_no}, details={
"operation": operation,
"task_no": task.task_no,
"reason_code": "inventory_source_changed",
},
) )
if is_inventory_source_stable(task): if is_inventory_source_stable(task):
return return
status = str(task.inventory_source_status or "unresolved").strip() status = str(task.inventory_source_status or "unresolved").strip()
code = INVENTORY_SOURCE_ERROR_CODES.get(status, INVENTORY_SOURCE_ERROR_CODES["gate_blocked"]) code = INVENTORY_SOURCE_ERROR_CODES.get(status, INVENTORY_SOURCE_ERROR_CODES["gate_blocked"])
reason_by_status = {
"conflicted": "inventory_source_conflicted",
"changed": "inventory_source_changed",
"identity_mismatch": "inventory_source_identity_mismatch",
}
raise AppError( raise AppError(
code=code, code=code,
message="库存源尚未确定,无法继续后续流程", message="库存源尚未确定,无法继续后续流程",
@@ -343,6 +352,7 @@ def assert_inventory_source_gate(
"operation": operation, "operation": operation,
"inventory_source_status": status, "inventory_source_status": status,
"task_no": task.task_no, "task_no": task.task_no,
"reason_code": reason_by_status.get(status, "require_manual_review"),
}, },
) )
@@ -4,10 +4,11 @@ services/shipping_notice/order_auto_freeze_policy.py
用途:统一生成订单抽取 Run 的自动冻结门禁摘要,不让各处各自拼 policy JSON。 用途:统一生成订单抽取 Run 的自动冻结门禁摘要,不让各处各自拼 policy JSON。
依赖:Run/Unit/RouteDecision/Qualification 模型;tool_common 紧急停止与分路径开关; 依赖:Run/Unit/RouteDecision/Qualification 模型;tool_common 紧急停止与分路径开关;
process_gate_contract(原因唯一归属 order_freeze_readiness)。 process_gate_contract(原因唯一归属 order_freeze_readiness)。
逻辑:Run 创建时冻结初始人工确认策略;结果落库后按模板资格、通用 STP 直通路径、 逻辑:Run 创建时冻结初始人工确认策略;结果落库后按解析路径、技术失败、预算停止、
技术失败、预算停止、紧急停止和复核状态刷新门禁摘要。 紧急停止和复核状态刷新 Run 级摘要。
通用路径仅 route_decision=straight_through 可冻结;禁止任何 LLM 路径自动冻结; 模板 Profile 批准写入 parser / qualification 痕迹,不再作为唯一放行条件;
资格、客户范围、场景范围与紧急停止统一归属 owning_gate=order_freeze_readiness。 LLM 路径可进入 Candidate Qualification,不再天然追加 llm_path_cannot_auto_freeze;
订单是否自动建单以 Candidate Qualification 为准(见 candidate_qualification_service)。
""" """
from __future__ import annotations from __future__ import annotations
@@ -54,8 +55,9 @@ def evaluate_run_auto_freeze_policy(
""" """
按 Run 已知事实计算自动冻结门禁摘要。 按 Run 已知事实计算自动冻结门禁摘要。
核心逻辑:紧急停止优先;禁止 llm_assisted_review; 核心逻辑:紧急停止优先;识别解析路径与模板质量痕迹;
模板路径沿用资格/客户/场景白名单;通用路径依赖 generic_auto_freeze 开关与直通路由。 Run 级 enabled 表示「未因技术/预算/紧急停止关闭」——订单级放行改由 Candidate Qualification 决定。
LLM 路径不再天然阻断;模板未批准仅写入 parser_quality 痕迹,不单独否决。
""" """
current = dict(run.auto_freeze_policy_json or {}) current = dict(run.auto_freeze_policy_json or {})
policy = build_initial_auto_freeze_policy( policy = build_initial_auto_freeze_policy(
@@ -70,6 +72,11 @@ def evaluate_run_auto_freeze_policy(
freeze_source: str | None = None freeze_source: str | None = None
qualification = None qualification = None
selected_route = None selected_route = None
parser_quality: dict[str, Any] = {
'profile_auto_create_approved': False,
'llm_route_present': _has_llm_assisted_route(run),
'note': 'template_quality_only_not_auto_create_gate',
}
# [STEP 1] 全局紧急停止:新 Run 自动冻结立即为 0。 # [STEP 1] 全局紧急停止:新 Run 自动冻结立即为 0。
if extraction_emergency_stop_enabled(): if extraction_emergency_stop_enabled():
@@ -82,45 +89,53 @@ def evaluate_run_auto_freeze_policy(
'owning_gate_code': _OWNING_GATE, 'owning_gate_code': _OWNING_GATE,
'blocking_reason_codes': sorted(set(blocking_reason_codes)), 'blocking_reason_codes': sorted(set(blocking_reason_codes)),
'findings': findings, 'findings': findings,
'parser_quality': parser_quality,
'evaluated_from_run': True, 'evaluated_from_run': True,
}) })
return policy return policy
# [STEP 2] 禁止任何 LLM 建议路径自动冻结。 # [STEP 2] 识别解析路径;LLM 可进入后续 Candidate Qualification(不再硬阻断)。
if _has_llm_assisted_route(run): profile_routes = _profile_routes(run)
blocking_reason_codes.append('llm_path_cannot_auto_freeze') approved_profile_routes = [
route for route in profile_routes if bool(route.auto_create_approved)
profile_routes = _approved_profile_routes(run) ]
generic_routes = _approved_generic_routes(run) generic_routes = _approved_generic_routes(run)
llm_routes = [
route for route in (run.route_decisions or [])
if _route_type(route) == 'llm_assisted_review'
]
if profile_routes: if profile_routes:
freeze_source = 'profile_deterministic' freeze_source = 'profile_deterministic'
selected_route = (approved_profile_routes or profile_routes)[-1]
qualification = _qualification_for_route(selected_route)
parser_quality['profile_auto_create_approved'] = bool(
selected_route.auto_create_approved
)
parser_quality['profile_qualification_status'] = (
str(qualification.status or '') if qualification is not None else None
)
if len({ if len({
(int(route.selected_profile_id or 0), str(route.selected_profile_checksum or '')) (int(route.selected_profile_id or 0), str(route.selected_profile_checksum or ''))
for route in profile_routes for route in profile_routes
if route.selected_profile_id if route.selected_profile_id
}) > 1: }) > 1:
blocking_reason_codes.append('multiple_profiles_detected') blocking_reason_codes.append('multiple_profiles_detected')
else: if qualification is not None and str(qualification.status or '') == 'auto_freeze_suspended':
selected_route = profile_routes[-1] # 管理员显式暂停仍作为 Run 级硬阻断(质量治理紧急手段)。
qualification = _qualification_for_route(selected_route)
if qualification is None:
blocking_reason_codes.append('profile_auto_freeze_qualification_missing')
elif str(qualification.status or '') == 'manual_confirmation':
blocking_reason_codes.append('profile_manual_confirmation_required')
elif str(qualification.status or '') == 'auto_freeze_suspended':
blocking_reason_codes.append('profile_auto_freeze_suspended') blocking_reason_codes.append('profile_auto_freeze_suspended')
confirmed_customer_ids = _confirmed_customer_ids(run) confirmed_customer_ids = _confirmed_customer_ids(run)
customer_scope_status, customer_scope_reason_codes = _evaluate_customer_scope( customer_scope_status, customer_scope_reason_codes = _evaluate_customer_scope(
qualification=qualification, qualification=qualification,
confirmed_customer_ids=confirmed_customer_ids, confirmed_customer_ids=confirmed_customer_ids,
) )
blocking_reason_codes.extend(customer_scope_reason_codes) # 客户/场景范围仅作痕迹与 Candidate 侧输入;未配置不再单独否决 Run.enabled。
business_scenario_status, business_scenario_reason_codes = _evaluate_business_scenario_scope( business_scenario_status, business_scenario_reason_codes = _evaluate_business_scenario_scope(
qualification=qualification, qualification=qualification,
business_scenario=current_business_scenario, business_scenario=current_business_scenario,
) )
blocking_reason_codes.extend(business_scenario_reason_codes) parser_quality['customer_scope_reason_codes'] = list(customer_scope_reason_codes)
parser_quality['business_scenario_reason_codes'] = list(business_scenario_reason_codes)
requires_customer_confirmation = bool( requires_customer_confirmation = bool(
qualification.requires_customer_confirmation qualification.requires_customer_confirmation
) if qualification is not None else True ) if qualification is not None else True
@@ -132,40 +147,38 @@ def evaluate_run_auto_freeze_policy(
if not generic_auto_freeze_enabled(): if not generic_auto_freeze_enabled():
blocking_reason_codes.append('generic_auto_freeze_disabled') blocking_reason_codes.append('generic_auto_freeze_disabled')
selected_route = generic_routes[-1] selected_route = generic_routes[-1]
elif llm_routes:
freeze_source = 'llm_assisted'
requires_customer_confirmation = True
customer_scope_status = 'unconfigured'
business_scenario_status = 'unconfigured'
selected_route = llm_routes[-1]
else: else:
blocking_reason_codes.append('profile_not_auto_freeze_approved') freeze_source = None
# [STEP 3] Run 级技术/预算/状态阻断(与候选资格互补)。
if _has_technical_failure(run): if _has_technical_failure(run):
blocking_reason_codes.append('technical_failure_present') blocking_reason_codes.append('technical_failure_present')
if _has_review_required_unit(run):
blocking_reason_codes.append('unit_review_required')
if _has_budget_stop(run): if _has_budget_stop(run):
blocking_reason_codes.append('budget_stopped') blocking_reason_codes.append('budget_stopped')
if str(run.status or '') in {'review_required', 'partially_completed'}:
blocking_reason_codes.append('review_required')
if str(run.status or '') == 'failed': if str(run.status or '') == 'failed':
blocking_reason_codes.append('run_failed') blocking_reason_codes.append('run_failed')
if str(run.status or '') == 'cancelled': if str(run.status or '') == 'cancelled':
blocking_reason_codes.append('run_cancelled') blocking_reason_codes.append('run_cancelled')
if _has_blocking_pending_orders(submission_result):
blocking_reason_codes.append('pending_orders_present')
if freeze_source == 'profile_deterministic': # Run.enabled:未因紧急/技术/预算/通用开关关闭即可;订单级仍看 Candidate Qualification。
enabled = bool( run_hard_block_codes = {
qualification is not None 'extraction_emergency_stop',
and str(qualification.status or '') == 'auto_freeze_approved' 'technical_failure_present',
and customer_scope_status == 'matched' 'budget_stopped',
and business_scenario_status == 'matched' 'run_failed',
and not requires_customer_confirmation 'run_cancelled',
and not blocking_reason_codes 'generic_auto_freeze_disabled',
) 'profile_auto_freeze_suspended',
elif freeze_source == 'generic_deterministic': 'multiple_profiles_detected',
enabled = bool(not blocking_reason_codes) }
else: hard_blocks = [code for code in blocking_reason_codes if code in run_hard_block_codes]
enabled = False enabled = bool(freeze_source is not None and not hard_blocks)
if requires_customer_confirmation and freeze_source == 'profile_deterministic':
blocking_reason_codes.append('customer_confirmation_required')
unique_codes = sorted(set(code for code in blocking_reason_codes if code)) unique_codes = sorted(set(code for code in blocking_reason_codes if code))
findings = [_freeze_finding(code) for code in unique_codes] findings = [_freeze_finding(code) for code in unique_codes]
@@ -190,6 +203,8 @@ def evaluate_run_auto_freeze_policy(
'customer_confirmation_required': requires_customer_confirmation, 'customer_confirmation_required': requires_customer_confirmation,
'blocking_reason_codes': unique_codes, 'blocking_reason_codes': unique_codes,
'findings': findings, 'findings': findings,
'parser_quality': parser_quality,
'candidate_qualification_required': True,
'evaluated_from_run': True, 'evaluated_from_run': True,
}) })
return policy return policy
@@ -237,15 +252,24 @@ def _route_type(route: ShippingOrderExtractionRouteDecision) -> str:
return '' return ''
def _approved_profile_routes(run: ShippingOrderExtractionRun) -> list[ShippingOrderExtractionRouteDecision]: def _profile_routes(run: ShippingOrderExtractionRun) -> list[ShippingOrderExtractionRouteDecision]:
"""返回声明可自动冻结的模板确定性分流决策。""" """
返回模板确定性分流决策(含未批准模板)。
核心逻辑:Profile 命中即可作为解析路径痕迹;auto_create_approved 只表示模板质量治理。
"""
return [ return [
route for route in (run.route_decisions or []) route for route in (run.route_decisions or [])
if bool(route.auto_create_approved) and route.selected_profile_id if route.selected_profile_id
and _route_type(route) in {'', 'profile_deterministic'} and _route_type(route) in {'', 'profile_deterministic'}
] ]
def _approved_profile_routes(run: ShippingOrderExtractionRun) -> list[ShippingOrderExtractionRouteDecision]:
"""返回模板质量已批准的确定性分流决策(兼容旧调用方)。"""
return [route for route in _profile_routes(run) if bool(route.auto_create_approved)]
def _approved_generic_routes(run: ShippingOrderExtractionRun) -> list[ShippingOrderExtractionRouteDecision]: def _approved_generic_routes(run: ShippingOrderExtractionRun) -> list[ShippingOrderExtractionRouteDecision]:
""" """
返回 STP 直通的通用确定性分流决策。 返回 STP 直通的通用确定性分流决策。
@@ -2,15 +2,18 @@
services/shipping_notice/order_build_eligibility_service.py services/shipping_notice/order_build_eligibility_service.py
用途:汇总建单前资格:客户/订单字段、有效 Reservation、行级库存源候选,以及 用途:汇总建单前资格:客户/订单字段、有效 Reservation、行级库存源候选,以及
自动建单内部检查(批准模板 / 字段完整 / 证据 / 冲突重复 / 质量门禁)。 Candidate Qualification 统一自动建单检查。
依赖:candidate_validation、field_rules、inventory_routing_engine、inventory_source_repository、 依赖:candidate_qualification_service(含 confidence_policy)、candidate_validation、field_rules、
inventory_routing_engine、inventory_source_repository、
ShippingNoticeCandidate / ShippingOrderExtractionUnit / ShippingOrderExtractionRun、 ShippingNoticeCandidate / ShippingOrderExtractionUnit / ShippingOrderExtractionRun、
ShippingInventorySource、process_gate_contract(原因唯一归属)。 ShippingInventorySource、process_gate_contract(原因唯一归属)。
逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核阻断; 逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核阻断;
人工已选候选(含原因)可覆盖规则零候选且优先于自动建议;规则原始候选与当前有效候选分离; 人工已选候选(含原因)可覆盖规则零候选且优先于自动建议;规则原始候选与当前有效候选分离;
停用或无已发布解析 Profile 的 Source 不进入有效候选; 停用 / Profile 未启用 / 无已发布解析 Profile / Excel 模板未发布的 Source 不进入有效候选,
旧五门禁不再平行产生用户阻断,失败映射到唯一 owning_gate Finding; 并写入稳定 unavailable_reasons(码表见 error_explainability_contract);
自动冻结资格/客户范围/场景/紧急停止统一归属 order_freeze_readiness。 投影附带 inventory_source_labels(code→display_name)供复核台业务文案;
模板批准仅保留在 parser_trace;自动建单以 Candidate Qualification 为准;
失败映射到唯一 owning_gate Finding。
""" """
from __future__ import annotations from __future__ import annotations
@@ -18,7 +21,15 @@ from __future__ import annotations
from typing import Any from typing import Any
from app.models import ShippingInventorySource from app.models import ShippingInventorySource
from app.services.shipping_notice.candidate_qualification_contract import (
CANDIDATE_QUALIFICATION_GATE_KEYS,
CANDIDATE_QUALIFICATION_GATE_REASON_CODES,
)
from app.services.shipping_notice.candidate_qualification_service import (
evaluate_candidate_qualification,
)
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
from app.services.shipping_notice.error_explainability_contract import build_explainability_reason
from app.services.shipping_notice.inventory_routing_engine import ( from app.services.shipping_notice.inventory_routing_engine import (
InventoryRoutingResult, InventoryRoutingResult,
evaluate_inventory_source_rules_for_field_values, evaluate_inventory_source_rules_for_field_values,
@@ -31,26 +42,44 @@ from app.services.shipping_notice.order_schema.field_rules import compute_effect
from app.services.shipping_notice.process_gate_contract import ( from app.services.shipping_notice.process_gate_contract import (
AUTO_BUILD_LEGACY_GATE_OWNING_MAP, AUTO_BUILD_LEGACY_GATE_OWNING_MAP,
build_process_finding, build_process_finding,
owning_gate_for_reason,
) )
from app.services.shipping_notice.reservation_id import validated_reservation_id from app.services.shipping_notice.reservation_id import validated_reservation_id
# 自动建单内部检查键(仅用于 can_auto_create);禁止平行投影为五个用户阻断。
AUTO_BUILD_GATE_KEYS: tuple[str, ...] = (
'approved_template',
'fields_complete',
'evidence_passed',
'no_conflict_or_duplicate',
'quality_gate_passed',
)
# 旧五门 → 稳定原因码(用户可见阻断只折叠到冻结就绪一次)。 def _issue_with_explainability(issue: dict[str, Any]) -> dict[str, Any]:
_AUTO_BUILD_GATE_REASON_CODES: dict[str, str] = { """
'approved_template': 'profile_not_auto_freeze_approved', 为建单资格 issue 附加统一 explainability 投影。
'fields_complete': 'required_field_missing',
'evidence_passed': 'evidence_missing', Args:
'no_conflict_or_duplicate': 'duplicate_unresolved', issue: 含 code 与业务定位字段的 issue 字典。
'quality_gate_passed': 'auto_freeze_not_enabled',
} Returns:
附带 explainability / message 的 issue。
"""
# finding_code describes the failed internal check; reason_code is the
# stable user-facing explanation contract and must take precedence.
code = str(issue.get('reason_code') or issue.get('code') or '').strip()
if not code:
return issue
details = {
key: value
for key, value in issue.items()
if key not in {'message', 'explainability', 'severity'} and value is not None
}
explainability = build_explainability_reason(reason_code=code, details=details)
return {
**issue,
'message': explainability.get('message'),
'explainability': explainability,
}
# 自动建单内部检查键:与 Candidate Qualification 门禁对齐;禁止平行投影为多条用户阻断。
# 兼容别名:fields_complete / evidence_passed 等旧键仍可通过评估结果派生。
AUTO_BUILD_GATE_KEYS: tuple[str, ...] = tuple(CANDIDATE_QUALIFICATION_GATE_KEYS)
# 资格门禁 → 稳定原因码(用户可见阻断折叠为唯一 Finding)。
_AUTO_BUILD_GATE_REASON_CODES: dict[str, str] = dict(CANDIDATE_QUALIFICATION_GATE_REASON_CODES)
def _field_id_maps( def _field_id_maps(
@@ -97,8 +126,10 @@ def classify_inventory_source_codes(codes: list[str]) -> dict[str, Any]:
""" """
按最新启停与解析 Profile 状态拆分原始候选。 按最新启停与解析 Profile 状态拆分原始候选。
核心逻辑:仅「已启用 + RPA 可读 + 已发布解析 Profile」进入 available; 核心逻辑:仅「已启用 + RPA Profile 启用 + RPA 可读 + 已发布解析 Profile +
其余进入 unavailable,并给出稳定 reason 码。 已发布 Excel 模板」进入 available;其余进入 unavailable,并给出稳定 reason 码
(见 error_explainability_contract.INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES_EMITTED)。
特别区分:规则未命中由调用方写 no_inventory_source_candidates;本函数只解释「已命中源为何不可用」。
Args: Args:
codes: 规则或人工给出的库存源编码。 codes: 规则或人工给出的库存源编码。
@@ -110,25 +141,41 @@ def classify_inventory_source_codes(codes: list[str]) -> dict[str, Any]:
unavailable: list[str] = [] unavailable: list[str] = []
reasons: dict[str, str] = {} reasons: dict[str, str] = {}
for code in _normalize_manual_codes(codes): for code in _normalize_manual_codes(codes):
# [STEP 1] 源不存在
source = ShippingInventorySource.query.filter_by(source_code=code).first() source = ShippingInventorySource.query.filter_by(source_code=code).first()
if source is None: if source is None:
unavailable.append(code) unavailable.append(code)
reasons[code] = 'source_not_found' reasons[code] = 'source_not_found'
continue continue
# [STEP 2] 源未启用(≠ 规则未命中)
if not bool(source.enabled): if not bool(source.enabled):
unavailable.append(code) unavailable.append(code)
reasons[code] = 'source_disabled' reasons[code] = 'source_disabled'
continue continue
# [STEP 3] RPA Profile 未绑定或未启用(细于 runtime unavailable)
rpa_profile = getattr(source, 'rpa_profile', None)
if rpa_profile is None or not bool(getattr(rpa_profile, 'enabled', False)):
unavailable.append(code)
reasons[code] = 'source_profile_disabled'
continue
# [STEP 4] RPA/运行时配置不可读
runtime = get_database_inventory_source(code, enabled_only=True) runtime = get_database_inventory_source(code, enabled_only=True)
if runtime is None: if runtime is None:
unavailable.append(code) unavailable.append(code)
reasons[code] = 'source_runtime_unavailable' reasons[code] = 'source_runtime_unavailable'
continue continue
# [STEP 5] 解析 Profile 未发布
parsing = source.parsing_profile parsing = source.parsing_profile
if parsing is None or str(getattr(parsing, 'status', '') or '') != 'published': if parsing is None or str(getattr(parsing, 'status', '') or '') != 'published':
unavailable.append(code) unavailable.append(code)
reasons[code] = 'parsing_profile_unavailable' reasons[code] = 'parsing_profile_unavailable'
continue continue
# [STEP 6] Excel 模板未绑定或未发布
excel = getattr(source, 'excel_template', None)
if excel is None or str(getattr(excel, 'status', '') or '') != 'published':
unavailable.append(code)
reasons[code] = 'source_excel_template_unavailable'
continue
available.append(code) available.append(code)
return { return {
'available': available, 'available': available,
@@ -159,11 +206,12 @@ def _rule_suggestion_from_result(rule_result: InventoryRoutingResult) -> dict[st
if rule_result.status == 'conflicted': if rule_result.status == 'conflicted':
suggestion_status = 'conflicted' suggestion_status = 'conflicted'
suggestion_codes = available suggestion_codes = available
block_reason = 'require_manual_review' block_reason = rule_result.block_reason or 'inventory_source_conflicted'
elif not available: elif not available:
suggestion_status = 'unresolved' suggestion_status = 'unresolved'
suggestion_codes = [] suggestion_codes = []
block_reason = 'no_inventory_source_candidates' # Distinguish a rule miss from a rule hit whose sources were filtered out.
block_reason = 'inventory_source_unavailable' if raw_codes else 'no_inventory_source_candidates'
elif len(available) == 1: elif len(available) == 1:
suggestion_status = 'resolved' suggestion_status = 'resolved'
suggestion_codes = available suggestion_codes = available
@@ -320,120 +368,101 @@ def assess_auto_build_gates(
candidate: Any | None = None, candidate: Any | None = None,
unit: Any | None = None, unit: Any | None = None,
run: Any | None = None, run: Any | None = None,
customer_resolved: bool | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
""" """
评估自动建单内部五检查;任一失败则只能进入 Review Case,禁止 STP 自动建单。 评估自动建单内部检查;任一失败则只能进入 Review Case,禁止 STP 自动建单。
核心逻辑:批准模板读 Unit 路由;字段完整由调用方汇总;证据/冲突/重复读 Candidate; 核心逻辑:委托 Candidate Qualification 统一门禁;模板批准仅出现在 parser_trace;
质量门禁读 Run 冻结的 auto_freeze_policy.enabled。 不再将 LLM 路径或 Profile 未批准作为硬必要条件。失败折叠为唯一用户可见 Finding。
返回 findings 按 owning_gate 去重;冻结资格类原因折叠为单一 order_freeze_readiness 用户阻断。
Args: Args:
fields_complete: Schema 必填与建单字段是否已齐备。 fields_complete: Schema 必填与建单字段是否已齐备。
candidate: 可选 ShippingNoticeCandidate。 candidate: 可选 ShippingNoticeCandidate。
unit: 可选 ShippingOrderExtractionUnit(含 route_decision_json)。 unit: 可选 ShippingOrderExtractionUnit(含 route_decision_json,仅 parser_trace)。
run: 可选 ShippingOrderExtractionRun(含 auto_freeze_policy_json)。 run: 可选 ShippingOrderExtractionRun(紧急停止等)。
customer_resolved: 可选客户确认结果,透传给资格评估。
Returns: Returns:
gates、can_auto_create、failed_gates、findings、user_blocking_finding。 gates、can_auto_create、failed_gates、findings、user_blocking_finding、
qualification(完整资格评估)。
""" """
# [STEP 1] 批准模板:Unit 路由 auto_create_approved,或 Candidate 已 automatic 接受。 # [STEP 1] 无 Candidate 时 fail-closed(兼容旧调用)。
route = {} if candidate is None:
if unit is not None and isinstance(getattr(unit, 'route_decision_json', None), dict): gates = {key: False for key in AUTO_BUILD_GATE_KEYS}
route = dict(unit.route_decision_json or {}) gates['required_fields_complete'] = bool(fields_complete)
approved_template = bool(route.get('auto_create_approved'))
if not approved_template and candidate is not None:
approved_template = (
str(getattr(candidate, 'acceptance_mode', '') or '') == 'automatic'
and str(getattr(candidate, 'candidate_status', '') or '') == 'accepted'
)
# [STEP 2] 证据:Candidate 须有非空 evidence_json。
evidence_passed = True
if candidate is not None:
evidence = getattr(candidate, 'evidence_json', None)
evidence_passed = isinstance(evidence, list) and len(evidence) > 0
# [STEP 3] 冲突/重复:阻断冲突或未解决重复均失败。
no_conflict_or_duplicate = True
if candidate is not None:
if getattr(candidate, 'conflicts_json', None):
no_conflict_or_duplicate = False
dup_status = str(getattr(candidate, 'duplicate_status', '') or 'unchecked')
dup_resolution = str(getattr(candidate, 'duplicate_resolution', '') or '')
if dup_status not in {'none', 'unchecked', ''} and dup_resolution != 'open_existing':
no_conflict_or_duplicate = False
# [STEP 4] 质量门禁:Run 冻结策略 enabled=True 才视为通过;缺 Run 时视为未通过。
quality_gate_passed = False
policy_blocking_codes: list[str] = []
if run is not None:
policy = getattr(run, 'auto_freeze_policy_json', None)
if isinstance(policy, dict):
quality_gate_passed = bool(policy.get('enabled'))
policy_blocking_codes = [
str(code).strip()
for code in (policy.get('blocking_reason_codes') or [])
if str(code or '').strip()
]
gates = {
'approved_template': bool(approved_template),
'fields_complete': bool(fields_complete),
'evidence_passed': bool(evidence_passed),
'no_conflict_or_duplicate': bool(no_conflict_or_duplicate),
'quality_gate_passed': bool(quality_gate_passed),
}
failed = [key for key in AUTO_BUILD_GATE_KEYS if not gates.get(key)] failed = [key for key in AUTO_BUILD_GATE_KEYS if not gates.get(key)]
finding = build_process_finding(
finding_code='candidate_qualification_missing',
owning_gate_code='order_freeze_readiness',
severity='blocking',
reason_code='order_freeze_not_ready',
user_visible=True,
blocks_current_action=True,
details={'message': '缺少订单候选,无法评估自动建单资格'},
)
return {
'gates': gates,
'failed_gates': failed,
'can_auto_create': False,
'findings': [finding],
'user_blocking_finding': finding,
'qualification': None,
}
# [STEP 5] 映射到 owning_gate Finding;冻结类折叠为一次用户阻断。 # [STEP 2] 统一资格评估(模板质量只进 parser_trace)。
# 优先使用 Run policy 的具体原因码,避免被通用 auto_freeze_not_enabled 抢占。 qualification = evaluate_candidate_qualification(
candidate=candidate,
run=run,
unit=unit,
fields_complete=fields_complete,
customer_resolved=customer_resolved,
)
gates = dict(qualification.get('gates') or {})
failed = list(qualification.get('failed_gates') or [])
reason_codes = list(qualification.get('blocking_reason_codes') or [])
# [STEP 3] 诊断 Finding + 唯一用户阻断。
findings: list[dict[str, Any]] = [] findings: list[dict[str, Any]] = []
freeze_reasons: list[str] = list(policy_blocking_codes)
for key in failed: for key in failed:
owning = AUTO_BUILD_LEGACY_GATE_OWNING_MAP.get(key, 'order_freeze_readiness') reason = _AUTO_BUILD_GATE_REASON_CODES.get(key, 'order_freeze_not_ready')
reason = _AUTO_BUILD_GATE_REASON_CODES.get(key, 'auto_freeze_not_enabled') if key == 'customer_confirmed' and reason_codes:
if owning == 'order_freeze_readiness': reason = reason_codes[0] if reason_codes[0].startswith('customer_') else reason
freeze_reasons.append(reason) owning = (
continue AUTO_BUILD_LEGACY_GATE_OWNING_MAP.get(key)
or owning_gate_for_reason(reason)
or 'order_freeze_readiness'
)
findings.append(build_process_finding( findings.append(build_process_finding(
finding_code=f'auto_build_{key}_failed', finding_code=f'candidate_qualification_{key}_failed',
owning_gate_code=owning, owning_gate_code=owning,
severity='diagnostic', severity='diagnostic',
reason_code=reason, reason_code=reason,
user_visible=False, user_visible=False,
blocks_current_action=False, blocks_current_action=False,
details={'legacy_auto_build_gate': key}, details={
'qualification_gate': key,
'parser_trace': qualification.get('parser_trace'),
},
)) ))
# 去重保持稳定顺序(policy 原因优先)
seen_freeze: set[str] = set()
freeze_unique: list[str] = []
for code in freeze_reasons:
if code in seen_freeze:
continue
seen_freeze.add(code)
freeze_unique.append(code)
user_blocking_finding: dict[str, Any] | None = None user_blocking_finding: dict[str, Any] | None = None
if freeze_unique or any( if failed:
key in failed for key in ('approved_template', 'quality_gate_passed') primary_reason = reason_codes[0] if reason_codes else 'order_freeze_not_ready'
): owning = owning_gate_for_reason(primary_reason) or 'order_freeze_readiness'
primary_reason = freeze_unique[0] if freeze_unique else 'auto_freeze_not_enabled'
user_blocking_finding = build_process_finding( user_blocking_finding = build_process_finding(
finding_code='auto_freeze_policy_not_approved', finding_code='candidate_qualification_blocked',
owning_gate_code='order_freeze_readiness', owning_gate_code=owning,
severity='blocking', severity='blocking',
reason_code=primary_reason, reason_code=primary_reason,
user_visible=True, user_visible=True,
blocks_current_action=True, blocks_current_action=True,
details={ details={
'blocking_reason_codes': freeze_unique, 'blocking_reason_codes': reason_codes,
'message': '自动建单策略尚未放行', 'qualification_status': qualification.get('status'),
'legacy_failed_gates': [ 'parser_trace': qualification.get('parser_trace'),
key for key in failed 'message': '自动建单资格未通过',
if AUTO_BUILD_LEGACY_GATE_OWNING_MAP.get(key) == 'order_freeze_readiness' 'failed_gates': failed,
],
}, },
) )
findings.append(user_blocking_finding) findings.append(user_blocking_finding)
@@ -441,9 +470,12 @@ def assess_auto_build_gates(
return { return {
'gates': gates, 'gates': gates,
'failed_gates': failed, 'failed_gates': failed,
'can_auto_create': not failed, 'can_auto_create': bool(qualification.get('can_auto_create')),
'findings': findings, 'findings': findings,
'user_blocking_finding': user_blocking_finding, 'user_blocking_finding': user_blocking_finding,
'qualification': qualification,
# 供管理端/复核资格详情直接展示最终阈值与来源,避免只看硬编码默认值。
'confidence_policy': dict(qualification.get('confidence_policy') or {}),
} }
@@ -536,6 +568,8 @@ def assess_order_build_eligibility(
'owning_gate_code': 'inventory_source_routing', 'owning_gate_code': 'inventory_source_routing',
'candidate_inventory_source_codes': routing.get('candidate_inventory_source_codes') or [], 'candidate_inventory_source_codes': routing.get('candidate_inventory_source_codes') or [],
'unavailable_source_codes': routing.get('unavailable_source_codes') or [], 'unavailable_source_codes': routing.get('unavailable_source_codes') or [],
'unavailable_reasons': routing.get('unavailable_reasons') or {},
'raw_rule_source_codes': routing.get('raw_rule_source_codes') or [],
}) })
assessment = assess_candidate_business_summary({**header_by_code, 'lines': enriched_lines}) assessment = assess_candidate_business_summary({**header_by_code, 'lines': enriched_lines})
@@ -580,32 +614,43 @@ def assess_order_build_eligibility(
and not assessment.get('invalid_lines') and not assessment.get('invalid_lines')
and not any(str(item.get('code') or '') == 'required_field_missing' for item in issues) and not any(str(item.get('code') or '') == 'required_field_missing' for item in issues)
) )
# [STEP] 自动建单检查:失败只阻断自动建单;用户投影折叠到唯一 owning_gate。 # [STEP] Candidate Qualification:失败只阻断自动建单;用户投影折叠到唯一 Finding。
gate_result = assess_auto_build_gates( gate_result = assess_auto_build_gates(
fields_complete=fields_complete and can_build, fields_complete=fields_complete and can_build,
candidate=candidate, candidate=candidate,
unit=unit, unit=unit,
run=run, run=run,
customer_resolved=bool(customer_resolved),
) )
can_auto_create = bool(can_build and gate_result.get('can_auto_create')) can_auto_create = bool(can_build and gate_result.get('can_auto_create'))
findings = list(gate_result.get('findings') or []) findings = list(gate_result.get('findings') or [])
# 禁止再写 auto_build_gate_* 平行用户阻断;仅保留一条冻结就绪用户 Finding。
user_finding = gate_result.get('user_blocking_finding') user_finding = gate_result.get('user_blocking_finding')
if user_finding and can_build and not can_auto_create: if user_finding and can_build and not can_auto_create:
issues.append({ issues.append({
'code': 'auto_freeze_policy_not_approved', 'code': 'candidate_qualification_blocked',
'severity': 'auto_create_blocking', 'severity': 'auto_create_blocking',
'owning_gate_code': 'order_freeze_readiness', 'owning_gate_code': user_finding.get('owning_gate_code') or 'order_freeze_readiness',
'reason_code': user_finding.get('reason_code'), 'reason_code': user_finding.get('reason_code'),
'finding_code': user_finding.get('finding_code'), 'finding_code': user_finding.get('finding_code'),
'message': '自动建单策略尚未放行', 'message': '自动建单资格未通过',
}) })
enabled_sources = list_database_inventory_sources(enabled_only=True)
enabled_codes = [ enabled_codes = [
str(item.get('source_code') or '').strip().upper() str(item.get('source_code') or '').strip().upper()
for item in list_database_inventory_sources(enabled_only=True) for item in enabled_sources
if str(item.get('source_code') or '').strip() if str(item.get('source_code') or '').strip()
] ]
# [STEP] 业务显示名目录(含未启用源),供复核台隐藏内部编码。
inventory_source_labels: dict[str, str] = {}
for item in list_database_inventory_sources(enabled_only=False):
code = str(item.get('source_code') or '').strip().upper()
if not code:
continue
label = str(item.get('display_name') or '').strip() or code
inventory_source_labels[code] = label[:120]
# [STEP] 统一附加 explainability,供复核台顶部摘要与 issue 列表共用
explained_issues = [_issue_with_explainability(item) for item in issues]
return { return {
'can_build': can_build, 'can_build': can_build,
'can_auto_create': can_auto_create, 'can_auto_create': can_auto_create,
@@ -613,11 +658,13 @@ def assess_order_build_eligibility(
'failed_gates': list(gate_result.get('failed_gates') or []), 'failed_gates': list(gate_result.get('failed_gates') or []),
'findings': findings, 'findings': findings,
'user_blocking_finding': user_finding, 'user_blocking_finding': user_finding,
'qualification': gate_result.get('qualification'),
'status': 'ready' if can_build else 'needs_review', 'status': 'ready' if can_build else 'needs_review',
'issues': issues, 'issues': explained_issues,
'line_projections': line_projections, 'line_projections': line_projections,
# 零规则候选时供复核台从已启用库存源人工选择(须填原因)。 # 零规则候选时供复核台从已启用库存源人工选择(须填原因)。
'enabled_inventory_source_codes': enabled_codes, 'enabled_inventory_source_codes': enabled_codes,
'inventory_source_labels': inventory_source_labels,
'assessment': { 'assessment': {
'can_create_task': bool(assessment.get('can_create_task')), 'can_create_task': bool(assessment.get('can_create_task')),
'missing_required_fields': list(assessment.get('missing_required_fields') or []), 'missing_required_fields': list(assessment.get('missing_required_fields') or []),
@@ -583,6 +583,34 @@ def list_profile_samples(profile_id: int) -> list[dict[str, Any]]:
).all()] ).all()]
def resolve_profile_sample_table_id(profile: ShippingOrderDocumentProfile, sample: ShippingOrderDocumentProfileSample) -> str:
"""解析并修复历史样本的明细表绑定,保证编辑器、验证和真实解析使用同一表。"""
explicit = str(sample.table_id or '').strip()
if explicit:
return explicit
snapshot = sample.table_identity_snapshot if isinstance(sample.table_identity_snapshot, dict) else {}
frozen = str(snapshot.get('table_id') or '').strip()
if frozen:
sample.table_id = frozen
return frozen
document = db.session.get(ShippingNoticeDocument, int(sample.document_id))
if document is None:
raise ValidationError('Profile sample document is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
layout = _document_layout(document)
tables = [item for item in (layout.get('tables') or []) if isinstance(item, dict) and str(item.get('table_id') or '').strip()]
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
regions = [item for item in (definition.get('table_regions') or []) if isinstance(item, dict) and item.get('line_layouts')]
if len(tables) != 1 or len(regions) != 1:
raise ValidationError(
'Profile sample table binding is missing or ambiguous',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_TABLE_REQUIRED',
details={'table_count': len(tables), 'line_region_count': len(regions)},
)
resolved = str(tables[0]['table_id']).strip()
sample.table_id = resolved
return resolved
def list_preview_pages(profile_id: int, *, document_id: int, actor_id: int | None) -> dict[str, Any]: def list_preview_pages(profile_id: int, *, document_id: int, actor_id: int | None) -> dict[str, Any]:
"""签发当前管理员的单用途页面授权;只返回页号和短时 token,不暴露资产路径。""" """签发当前管理员的单用途页面授权;只返回页号和短时 token,不暴露资产路径。"""
if actor_id is None: if actor_id is None:
@@ -750,6 +778,8 @@ def preview_profile_region(
order_field_layouts=definition['order_field_layouts'], order_field_layouts=definition['order_field_layouts'],
) )
table_id = str(data.get('table_id') or '').strip() table_id = str(data.get('table_id') or '').strip()
if not table_id:
raise ValidationError('Sample table binding is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_TABLE_REQUIRED')
layout = _document_layout(document) layout = _document_layout(document)
raw_table = next(( raw_table = next((
item for item in layout.get('tables') or [] item for item in layout.get('tables') or []
@@ -765,6 +795,7 @@ def preview_profile_region(
page_bbox = {'x0': 0, 'y0': 0, 'x1': float(page['width']), 'y1': float(page['height'])} page_bbox = {'x0': 0, 'y0': 0, 'x1': float(page['width']), 'y1': float(page['height'])}
except (KeyError, TypeError, ValueError) as exc: except (KeyError, TypeError, ValueError) as exc:
raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc
strict = bool(data.get('strict'))
rows = [] rows = []
involved_field_codes: list[str] = [] involved_field_codes: list[str] = []
seen_field_codes: set[str] = set() seen_field_codes: set[str] = set()
@@ -803,14 +834,14 @@ def preview_profile_region(
table_region=table_region.region.model_dump(), table_region=table_region.region.model_dump(),
termination_rules=[item.model_dump() for item in table_region.termination_rules], termination_rules=[item.model_dump() for item in table_region.termination_rules],
exclusion_regions=[item.model_dump() for item in table_region.exclusion_regions], exclusion_regions=[item.model_dump() for item in table_region.exclusion_regions],
# 预览保留删除证据,供管理员核对;正式订单运行仍使用默认排除规则。 # 严格模式与正式订单解析保持一致;普通预览保留删除证据供管理员核对。
include_deleted=True, include_deleted=not strict,
line_start_field_code=table_region.line_start_field_code, line_start_field_code=table_region.line_start_field_code,
row_reconstruction_mode=table_region.row_reconstruction_mode, row_reconstruction_mode=table_region.row_reconstruction_mode,
) )
# Preview must expose coordinate reads for correction even when the current # Preview must expose coordinate reads for correction even when the current
# sample's start marker is missing; the production extraction path remains strict. # sample's start marker is missing; the production extraction path remains strict.
if not reconstructed_rows: if not reconstructed_rows and not strict:
reconstructed_rows = reconstruct_coordinate_profile_rows( reconstructed_rows = reconstruct_coordinate_profile_rows(
characters=[item for item in region_characters if isinstance(item, dict)], table_bbox=page_bbox, characters=[item for item in region_characters if isinstance(item, dict)], table_bbox=page_bbox,
line_layouts=[item.model_dump() for item in table_region.line_layouts], line_layouts=[item.model_dump() for item in table_region.line_layouts],
@@ -823,6 +854,9 @@ def preview_profile_region(
row_reconstruction_mode=table_region.row_reconstruction_mode, row_reconstruction_mode=table_region.row_reconstruction_mode,
) )
rows.extend(reconstructed_rows) rows.extend(reconstructed_rows)
# 严格验证与真实订单解析一致:带重建问题的行不会计入有效明细。
if strict:
rows = [row for row in rows if not getattr(row, 'issues', None)]
# 复合解析器可能生成未显式列在 target_fields 的附加字段,仍需纳入本次候选。 # 复合解析器可能生成未显式列在 target_fields 的附加字段,仍需纳入本次候选。
for row in rows: for row in rows:
for field_code in row.fields: for field_code in row.fields:
@@ -836,6 +870,8 @@ def preview_profile_region(
result = { result = {
'table_id': table_id, 'row_count': len(rows) + (1 if field_codes else 0), 'table_id': table_id, 'row_count': len(rows) + (1 if field_codes else 0),
'column_count': len(field_codes), 'rows': ([field_codes] if field_codes else []) + [[row.fields.get(code, '') for code in field_codes] for row in rows], 'column_count': len(field_codes), 'rows': ([field_codes] if field_codes else []) + [[row.fields.get(code, '') for code in field_codes] for row in rows],
# 验证服务需要明确的字段集合来统计明细字段;不能从 rows 临时反推。
'field_codes': field_codes,
'row_roles': (['header'] if field_codes else []) + [row.role for row in rows], 'row_roles': (['header'] if field_codes else []) + [row.role for row in rows],
'source_row_indices': ([[]] if field_codes else []) + [row.source_row_indices for row in rows], 'source_row_indices': ([[]] if field_codes else []) + [row.source_row_indices for row in rows],
'status': 'needs_review', 'status': 'needs_review',
@@ -2269,6 +2305,36 @@ def save_draft(
profile.customer_ids_json = next_customer_ids profile.customer_ids_json = next_customer_ids
profile.change_note = next_change_note or None profile.change_note = next_change_note or None
db.session.flush() db.session.flush()
# 创建向导先建立 annotation 样本,再由编辑器选择实际明细表;保存草稿时必须
# 将该选择写回样本绑定,否则预览使用浏览器内存 table_id,而验证只能读到 NULL。
sample_document_id = data.get('sample_document_id')
sample_table_id = str(data.get('sample_table_id') or '').strip()
if sample_document_id not in (None, '') and sample_table_id:
try:
sample_document_id = int(sample_document_id)
except (TypeError, ValueError) as exc:
raise ValidationError(
'sample_document_id is invalid',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
) from exc
sample = ShippingOrderDocumentProfileSample.query.filter_by(
profile_id=profile.id, document_id=sample_document_id, sample_role='annotation',
).order_by(ShippingOrderDocumentProfileSample.id.asc()).first()
if sample is None:
raise ValidationError(
'Profile annotation sample is unavailable',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
)
layout = _document_layout(db.session.get(ShippingNoticeDocument, sample_document_id))
if not any(
isinstance(item, dict) and str(item.get('table_id') or '') == sample_table_id
for item in (layout.get('tables') or [])
):
raise ValidationError(
'Selected sample table is unavailable',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
)
sample.table_id = sample_table_id
_refresh_training_sample_count(profile) _refresh_training_sample_count(profile)
audit_summary = _definition_audit_summary(definition) audit_summary = _definition_audit_summary(definition)
if previous_definition is None: if previous_definition is None:
@@ -167,9 +167,11 @@ def run_current_sample(profile_id: int, *, data: dict[str, Any], actor_id: int |
revision, sample = _revision(profile), _sample(profile, data.get('sample_binding_id')) revision, sample = _revision(profile), _sample(profile, data.get('sample_binding_id'))
row = _new_run(profile=profile, revision=revision, run_type='current_sample', sample=sample, actor_id=actor_id, operation_id=operation_id) row = _new_run(profile=profile, revision=revision, run_type='current_sample', sample=sample, actor_id=actor_id, operation_id=operation_id)
try: try:
table_id = profile_service.resolve_profile_sample_table_id(profile, sample)
preview = profile_service.preview_profile_region(profile.id, data={ preview = profile_service.preview_profile_region(profile.id, data={
'document_id': sample.document_id, 'table_id': sample.table_id, 'document_id': sample.document_id, 'table_id': table_id,
'definition': dict(profile.definition_json or {}), 'definition': dict(profile.definition_json or {}),
'strict': True,
}, actor_id=actor_id) }, actor_id=actor_id)
rows = preview.get('rows') if isinstance(preview, dict) else [] rows = preview.get('rows') if isinstance(preview, dict) else []
fields = preview.get('field_codes') if isinstance(preview, dict) else [] fields = preview.get('field_codes') if isinstance(preview, dict) else []
@@ -2,10 +2,12 @@
backend/app/services/shipping_notice/order_extraction.py backend/app/services/shipping_notice/order_extraction.py
用途:持久化后台订单抽取 Run 的结构化结果,完成校验、判重与审计,并收敛至 STP 自动建单。 用途:持久化后台订单抽取 Run 的结构化结果,完成校验、判重与审计,并收敛至 STP 自动建单。
依赖:ChatSession、ShippingNoticeIntake/Document/Candidate、动态 Schema、Review Case STP 建单。 依赖:ChatSession、ShippingNoticeIntake/Document/Candidate、动态 Schema、Review Case STP 建单、
process_gate Finding 归属(Candidate 冲突只投影最终 blocked_fields)。
逻辑:Worker 校验 Run 冻结快照后提交 orders[];HXOPS 逐订单落 Candidate, 逻辑:Worker 校验 Run 冻结快照后提交 orders[];HXOPS 逐订单落 Candidate,
仅模板/通用确定性验收标记可自动接受;权威自动建单入口为 maybe_stp_auto_create_for_run, 仅模板/通用确定性验收标记可自动接受;权威自动建单入口为 maybe_stp_auto_create_for_run,
不再并行调用 Candidate 旧自动冻结建单路径。 不再并行调用 Candidate 旧自动冻结建单路径;
派生前 missing Decision 不得进入 Candidate 冲突;诊断 Finding 不进入用户阻断。
""" """
from __future__ import annotations from __future__ import annotations
@@ -410,18 +412,45 @@ def persist_order_extraction_result(
if summary.get('bill_to_customer'): if summary.get('bill_to_customer'):
summary['customer_name'] = summary['bill_to_customer'] summary['customer_name'] = summary['bill_to_customer']
if dynamic['blocked_fields']: if dynamic['blocked_fields']:
blocking_conflicts.extend([ blocked_set = {
str(code).strip()
for code in dynamic['blocked_fields']
if str(code or '').strip()
}
# [STEP] 只投影最终 blocked_fields 对应的有效 Decision;
# 禁止扫描全部旧的非 accepted Decision(如派生前 line_no missing)。
projected = [
{ {
'field': item.get('field_code'), 'field': item.get('field_code'),
'severity': 'blocking', 'severity': 'blocking',
'reason': item.get('reason_code') or 'dynamic_schema_required_or_evidence_gate', 'reason': item.get('reason_code') or 'dynamic_schema_required_or_evidence_gate',
'owning_gate_code': (
'field_conflict_resolution'
if str(item.get('reason_code') or '') == 'cross_source_conflict'
else 'field_completeness'
if str(item.get('reason_code') or '') in {'required_field_missing', 'evidence_missing'}
and str(item.get('field_code') or '') in blocked_set
else 'order_field_extraction'
),
} }
for item in dynamic['decisions'] for item in dynamic['decisions']
if item.get('status') not in {'accepted', 'corroborated'} if str(item.get('field_code') or '') in blocked_set
] or [{ and item.get('status') not in {'accepted', 'corroborated', 'derived'}
'field': ','.join(dynamic['blocked_fields']), 'severity': 'blocking', ]
# 派生成功后 Decision 可能已是 accepted;若 blocked 仍含该字段,用摘要兜底。
if not projected:
projected = [{
'field': ','.join(sorted(blocked_set)),
'severity': 'blocking',
'reason': 'dynamic_schema_required_or_evidence_gate', 'reason': 'dynamic_schema_required_or_evidence_gate',
}]) 'owning_gate_code': 'field_completeness',
}]
blocking_conflicts.extend(projected)
# 诊断 Finding 不进入 Candidate 用户阻断冲突,仅写入结构化结果供管理员查看。
diagnostic_findings = [
item for item in (dynamic.get('findings') or [])
if isinstance(item, dict) and str(item.get('severity') or '') == 'diagnostic'
]
field_confidence: dict[str, float] = {} field_confidence: dict[str, float] = {}
for decision in dynamic['decisions']: for decision in dynamic['decisions']:
field_code = str(decision.get('field_code') or '') field_code = str(decision.get('field_code') or '')
@@ -527,6 +556,9 @@ def persist_order_extraction_result(
'observations': dynamic['observations'], 'observations': dynamic['observations'],
'decisions': dynamic['decisions'], 'decisions': dynamic['decisions'],
'conflicts': blocking_conflicts, 'conflicts': blocking_conflicts,
'blocked_fields': list(dynamic.get('blocked_fields') or []),
'findings': list(dynamic.get('findings') or []),
'diagnostic_findings': diagnostic_findings,
}, },
'customer_matches': dynamic['customer_matches'], 'customer_matches': dynamic['customer_matches'],
'missing_required_fields': assessment['missing_required_fields'], 'missing_required_fields': assessment['missing_required_fields'],
@@ -1041,7 +1073,8 @@ def submit_order_extraction_unit_result(
""" """
单个 PDF/Unit 完成后立即落 Candidate 并按 STP 门禁建 Task,不等待同 Run 其它 Unit。 单个 PDF/Unit 完成后立即落 Candidate 并按 STP 门禁建 Task,不等待同 Run 其它 Unit。
核心逻辑:仅锁定本 Unit 的 Intake/Document,复用 persist_order_extraction_result; 核心逻辑:仅锁定本 Unit 的 Intake/Document;同 Run 续单元或未产生 Task/Batch 的重识别
可安全复用已消费 Intake;复用 persist_order_extraction_result;
通过门禁的 automatic Candidate 建批后由编排器触发 auto_progress;最后幂等初始化 Review Case。 通过门禁的 automatic Candidate 建批后由编排器触发 auto_progress;最后幂等初始化 Review Case。
Args: Args:
@@ -1140,11 +1173,20 @@ def submit_order_extraction_unit_result(
and intake.consumed_batch_id is None and intake.consumed_batch_id is None
and str(_order_extraction_submission(intake).get('request_id') or '') == str(run.run_no) and str(_order_extraction_submission(intake).get('request_id') or '') == str(run.run_no)
) )
# 重识别沿用原 PDF/Intake;旧版空结果会把 Intake 标记 consumed,但只要未建 Task/Batch,
# 新版仍可落自己的 Candidate。真实业务消费保持 fail-closed。
is_orphaned_reparse = (
run.reparse_of_run_id is not None
and intake.parse_status == 'consumed'
and intake.consumed_at is not None
and intake.consumed_task_id is None
and intake.consumed_batch_id is None
)
current_intakes = _load_intakes( current_intakes = _load_intakes(
session=session, session=session,
intake_nos=[str(intake.intake_no)], intake_nos=[str(intake.intake_no)],
lock=True, lock=True,
allow_consumed=is_same_run_consumed_continuation, allow_consumed=is_same_run_consumed_continuation or is_orphaned_reparse,
) )
current_documents = [row for row in _load_documents(current_intakes, lock=True) if int(row.id) == unit_document_id] current_documents = [row for row in _load_documents(current_intakes, lock=True) if int(row.id) == unit_document_id]
if len(current_intakes) != 1 or len(current_documents) != 1: if len(current_intakes) != 1 or len(current_documents) != 1:
@@ -1184,6 +1226,7 @@ def submit_order_extraction_unit_result(
frozen_layout_candidates_by_document=frozen_layout_candidates_by_document, frozen_layout_candidates_by_document=frozen_layout_candidates_by_document,
frozen_evidence_text_by_document=frozen_evidence_text_by_document, frozen_evidence_text_by_document=frozen_evidence_text_by_document,
auto_create_enabled=False, auto_create_enabled=False,
allow_orphaned_consumed_reparse=is_orphaned_reparse,
allow_same_run_consumed_continuation=is_same_run_consumed_continuation, allow_same_run_consumed_continuation=is_same_run_consumed_continuation,
) )
result['unit_id'] = int(unit.id) result['unit_id'] = int(unit.id)
@@ -2,9 +2,10 @@
services/shipping_notice/order_extraction_materialization.py services/shipping_notice/order_extraction_materialization.py
用途:在点击发送后,按附件选择计划为 Run 物化本次真正需要的输入文档。 用途:在点击发送后,按附件选择计划为 Run 物化本次真正需要的输入文档。
依赖:ShippingNoticeIntake/FileAsset、notice_upload、document_candidate_persist、attachment_selection。 依赖:ShippingNoticeIntake/FileAsset、notice_upload、document_candidate_persist、
attachment_selection、attachment_integrity。
逻辑:上传阶段保持快览轻量;发送阶段只为本次计划选中的附件和邮件正文创建 Document/派生资产, 逻辑:上传阶段保持快览轻量;发送阶段只为本次计划选中的附件和邮件正文创建 Document/派生资产,
不把未选附件偷偷升级成可执行输入。 不把未选附件偷偷升级成可执行输入;附件不完整 ConflictError 附带稳定 reason_code。
""" """
from __future__ import annotations from __future__ import annotations
@@ -20,6 +21,7 @@ from flask import current_app
from app import db from app import db
from app.core.errors import ConflictError from app.core.errors import ConflictError
from app.models import FileAsset, ShippingNoticeDocument, ShippingNoticeIntake from app.models import FileAsset, ShippingNoticeDocument, ShippingNoticeIntake
from app.services.shipping_notice.attachment_integrity import attachment_incomplete_error_details
from app.services.shipping_notice.attachment_selection import build_attachment_selection_snapshot from app.services.shipping_notice.attachment_selection import build_attachment_selection_snapshot
from app.services.shipping_notice.document_candidate_persist import persist_intake_documents from app.services.shipping_notice.document_candidate_persist import persist_intake_documents
from app.services.shipping_notice.eml_parse import pop_attachment_payload from app.services.shipping_notice.eml_parse import pop_attachment_payload
@@ -83,14 +85,20 @@ def _require_selected_document_keys(
missing_keys = sorted(selected_attachment_keys - existing_keys) missing_keys = sorted(selected_attachment_keys - existing_keys)
if not missing_keys: if not missing_keys:
return return
structured = (
intake.structured_result_json
if isinstance(intake.structured_result_json, dict)
else None
)
raise ConflictError( raise ConflictError(
'Selected shipping notice attachments could not be materialized', 'Selected shipping notice attachments could not be materialized',
code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE',
details={ details=attachment_incomplete_error_details(
'intake_nos': [str(intake.intake_no or '')], structured,
'reason': 'selected_attachment_document_missing', intake_nos=[str(intake.intake_no or '')],
'missing_attachment_keys': missing_keys, reason='selected_attachment_document_missing',
}, extra={'missing_attachment_keys': missing_keys},
),
) )
@@ -132,10 +140,19 @@ def _build_selected_eml_result(
retain_payloads=True, retain_payloads=True,
) )
if preview_result.status != 'accepted': if preview_result.status != 'accepted':
structured = (
intake.structured_result_json
if isinstance(intake.structured_result_json, dict)
else None
)
raise ConflictError( raise ConflictError(
'Shipping notice preview is not ready for extraction', 'Shipping notice preview is not ready for extraction',
code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE',
details={'intake_nos': [str(intake.intake_no or '')]}, details=attachment_incomplete_error_details(
structured,
intake_nos=[str(intake.intake_no or '')],
reason='preview_not_ready',
),
) )
meta = dict(preview_result.meta or {}) if isinstance(preview_result.meta, dict) else {} meta = dict(preview_result.meta or {}) if isinstance(preview_result.meta, dict) else {}
selected_rows: list[dict[str, Any]] = [] selected_rows: list[dict[str, Any]] = []
@@ -267,10 +284,19 @@ def ensure_order_extraction_input_documents(
for intake in intakes: for intake in intakes:
parent_asset = db.session.get(FileAsset, int(intake.asset_id)) if intake.asset_id else None parent_asset = db.session.get(FileAsset, int(intake.asset_id)) if intake.asset_id else None
if parent_asset is None: if parent_asset is None:
structured = (
intake.structured_result_json
if isinstance(intake.structured_result_json, dict)
else None
)
raise ConflictError( raise ConflictError(
'Shipping notice asset is unavailable', 'Shipping notice asset is unavailable',
code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE',
details={'intake_nos': [str(intake.intake_no or '')], 'reason': 'parent_asset_missing'}, details=attachment_incomplete_error_details(
structured,
intake_nos=[str(intake.intake_no or '')],
reason='parent_asset_missing',
),
) )
existing_keys = _existing_document_keys(intake) existing_keys = _existing_document_keys(intake)
source_name = str(parent_asset.original_filename or '') source_name = str(parent_asset.original_filename or '')
@@ -290,10 +316,19 @@ def ensure_order_extraction_input_documents(
if required_keys and required_keys.issubset(existing_keys): if required_keys and required_keys.issubset(existing_keys):
continue continue
if not selected_attachment_keys: if not selected_attachment_keys:
structured = (
intake.structured_result_json
if isinstance(intake.structured_result_json, dict)
else None
)
raise ConflictError( raise ConflictError(
'Shipping notice contains no eligible attachments for automatic extraction', 'Shipping notice contains no eligible attachments for automatic extraction',
code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE',
details={'intake_nos': [str(intake.intake_no or '')], 'reason': 'no_eligible_selected_attachment'}, details=attachment_incomplete_error_details(
structured,
intake_nos=[str(intake.intake_no or '')],
reason='no_eligible_selected_attachment',
),
) )
eml_inputs.append((intake, parent_asset, selected_attachment_keys)) eml_inputs.append((intake, parent_asset, selected_attachment_keys))
@@ -78,6 +78,7 @@ STABLE_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({
'profile_auto_create_not_approved', 'profile_auto_create_not_approved',
'acceptance_marker_missing', 'acceptance_marker_missing',
'business_table_not_found', 'business_table_not_found',
'business_table_empty',
'multiple_business_tables', 'multiple_business_tables',
'row_needs_review', 'row_needs_review',
'required_field_missing', 'required_field_missing',
@@ -4,11 +4,13 @@ backend/app/services/shipping_notice/order_extraction_run_service.py
用途:创建、查询和序列化建单前订单抽取领域 Run;Unit 完成后独立触发 Candidate/STP 下游。 用途:创建、查询和序列化建单前订单抽取领域 Run;Unit 完成后独立触发 Candidate/STP 下游。
依赖:Agent/ChatSession、ShippingNoticeIntake/Document、已发布订单 Schema、SQLAlchemy 事务、 依赖:Agent/ChatSession、ShippingNoticeIntake/Document、已发布订单 Schema、SQLAlchemy 事务、
order_extraction.submit_order_extraction_unit_result、progress_workflow.auto_progress、 order_extraction.submit_order_extraction_unit_result、progress_workflow.auto_progress、
workflow_ledger_service(物化后幂等建 WorkflowItem)、process_gate_bridge(Execution 创建)。 workflow_ledger_service(物化后幂等建 WorkflowItem)、process_gate_bridge(Execution 创建)、
error_explainability_contract(Run 失败可解释性投影)。
逻辑:服务端校验用户与会话权限,冻结 Intake/Document/Schema 输入,并以数据库唯一约束保证幂等与单 Intake 单活跃 Run; 逻辑:服务端校验用户与会话权限,冻结 Intake/Document/Schema 输入,并以数据库唯一约束保证幂等与单 Intake 单活跃 Run;
同会话跨上传批次的完整附件内容指纹相同时,复用活跃或待处理 Workflow Item,避免重复 Workflow; 同会话跨上传批次的完整附件内容指纹相同时,复用活跃或待处理 Workflow Item,避免重复 Workflow;
progress_ready_extraction_unit 供 Worker 在每 PDF candidate_ready 后立即落库并推进; progress_ready_extraction_unit 供 Worker 在每 PDF candidate_ready 后立即落库并推进;
Document 物化后立即 ensure WorkflowItem 与 Process Execution,使版面阶段即有 Item 与 Gate。 Document 物化后立即 ensure WorkflowItem 与 Process Execution,使版面阶段即有 Item 与 Gate;
工作区 Run 序列化失败时附带 explainability(责任方/下一步/request_id),禁止只返回技术错误码。
""" """
from __future__ import annotations from __future__ import annotations
@@ -332,13 +334,23 @@ def _build_snapshot(
else _build_attachment_selection_for_run(intakes=intakes) else _build_attachment_selection_for_run(intakes=intakes)
) )
if has_attachment_catalog(selection_snapshot) and not has_selected_attachments(selection_snapshot): if has_attachment_catalog(selection_snapshot) and not has_selected_attachments(selection_snapshot):
from app.services.shipping_notice.attachment_integrity import (
attachment_incomplete_error_details,
)
primary_structured = None
for intake in intakes:
if isinstance(intake.structured_result_json, dict):
primary_structured = intake.structured_result_json
break
raise ConflictError( raise ConflictError(
'Shipping notice contains no eligible attachments for automatic extraction', 'Shipping notice contains no eligible attachments for automatic extraction',
code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE',
details={ details=attachment_incomplete_error_details(
'intake_nos': [str(intake.intake_no or '') for intake in intakes], primary_structured,
'reason': 'no_eligible_selected_attachment', intake_nos=[str(intake.intake_no or '') for intake in intakes],
}, reason='no_eligible_selected_attachment',
),
) )
intake_ids = [intake.id for intake in intakes] intake_ids = [intake.id for intake in intakes]
@@ -455,10 +467,25 @@ def _build_snapshot(
) )
] ]
if incomplete and not allow_unmaterialized: if incomplete and not allow_unmaterialized:
from app.services.shipping_notice.attachment_integrity import (
attachment_incomplete_error_details,
)
primary_structured = None
for intake in intakes:
if str(intake.intake_no or '') in {str(item) for item in incomplete} and isinstance(
intake.structured_result_json, dict
):
primary_structured = intake.structured_result_json
break
raise ConflictError( raise ConflictError(
'Shipping notice documents are incomplete', 'Shipping notice documents are incomplete',
code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE',
details={'intake_nos': incomplete}, details=attachment_incomplete_error_details(
primary_structured,
intake_nos=list(incomplete),
reason='documents_incomplete',
),
) )
return { return {
'snapshot_version': 3, 'snapshot_version': 3,
@@ -1686,6 +1713,49 @@ def _expansion_trigger_reason_codes(run: ShippingOrderExtractionRun, units: list
return sorted(reason_codes) return sorted(reason_codes)
def _current_request_id() -> str | None:
"""读取当前 HTTP 请求 request_id;无请求上下文时返回 None。"""
try:
from flask import g
value = str(getattr(g, 'request_id', '') or '').strip()
return value or None
except RuntimeError:
return None
def _workspace_run_error_projection(run: ShippingOrderExtractionRun) -> dict[str, Any] | None:
"""
将 Run 失败码投影为工作区安全错误结构(含可解释性)。
核心逻辑:保留原始 code 供兼容;通过 build_explainability_reason 输出责任方、
下一步动作与 request_id;未知码降级为 unknown_business_failure。
Args:
run: 订单识别 Run。
Returns:
{code, explainability};无错误码时返回 None。
"""
code = str(run.error_code or '').strip()
if not code:
return None
from app.services.shipping_notice.error_explainability_contract import build_explainability_reason
request_id = _current_request_id()
if not request_id and isinstance(run.result_json, dict):
request_id = str(run.result_json.get('request_id') or '').strip() or None
explainability = build_explainability_reason(
reason_code=code,
details={'source_error_code': code[:64]},
request_id=request_id,
)
return {
'code': code[:64],
'explainability': explainability,
}
def _unit_fact_summary(run: ShippingOrderExtractionRun) -> dict[str, Any] | None: def _unit_fact_summary(run: ShippingOrderExtractionRun) -> dict[str, Any] | None:
"""聚合执行单元的重试、失败和预算事实,供工作台直接展示。""" """聚合执行单元的重试、失败和预算事实,供工作台直接展示。"""
units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else [] units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else []
@@ -1764,9 +1834,8 @@ def serialize_order_extraction_run(run: ShippingOrderExtractionRun) -> dict[str,
'last_activity_at': workspace_projection.get('last_activity_at'), 'last_activity_at': workspace_projection.get('last_activity_at'),
'feature_flags': workspace_projection.get('feature_flags') or {}, 'feature_flags': workspace_projection.get('feature_flags') or {},
'result': run.result_json, 'result': run.result_json,
# Worker/provider error text can contain upstream details. Workspace cards only need a # [STEP] 失败投影必须附带可解释性(责任方/下一步/request_id),禁止只下发技术错误码。
# stable code to select a safe, actionable user hint; full diagnostics stay admin-only. 'error': _workspace_run_error_projection(run),
'error': {'code': run.error_code} if run.error_code else None,
'created_at': run.created_at.isoformat() + 'Z' if run.created_at else None, 'created_at': run.created_at.isoformat() + 'Z' if run.created_at else None,
'updated_at': run.updated_at.isoformat() + 'Z' if run.updated_at else None, 'updated_at': run.updated_at.isoformat() + 'Z' if run.updated_at else None,
'started_at': run.started_at.isoformat() + 'Z' if run.started_at else None, 'started_at': run.started_at.isoformat() + 'Z' if run.started_at else None,
@@ -4,7 +4,9 @@ backend/app/services/shipping_notice/order_extraction_workflow.py
用途:提供冻结订单抽取快照的确定性模板路由及 STP 裁决(straight_through / needs_review)。 用途:提供冻结订单抽取快照的确定性模板路由及 STP 裁决(straight_through / needs_review)。
依赖:MinerU 紧凑快照、订单 Profile、Schema 校验、order_extraction_route_contract、统一错误类型。 依赖:MinerU 紧凑快照、订单 Profile、Schema 校验、order_extraction_route_contract、统一错误类型。
逻辑:Worker 先调用本模块裁决模板或通用 Schema 确定性解析,并输出 route_type/route_decision/reason_codes; 逻辑:Worker 先调用本模块裁决模板或通用 Schema 确定性解析,并输出 route_type/route_decision/reason_codes;
仅严格门禁通过才可直通建单;主链不调用 Dify;LLM 建议由后续阶段接线。 路由产出 Candidate 后由 Candidate Qualification 统一评估自动建单资格;
模板 auto_create_approved 仅作解析器质量痕迹;LLM 路径不再天然禁止自动建单;
主链不调用 Dify;LLM 辅助结果同样进入统一资格评估。
""" """
from __future__ import annotations from __future__ import annotations
@@ -30,7 +32,6 @@ from app.services.shipping_notice.document_layout.coordinate_table_reconstructio
from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields
from app.services.shipping_notice.document_layout.order_profile_matcher import match_frozen_coordinate_profiles from app.services.shipping_notice.document_layout.order_profile_matcher import match_frozen_coordinate_profiles
from app.services.shipping_notice.order_extraction_route_contract import ( from app.services.shipping_notice.order_extraction_route_contract import (
GENERIC_ELIGIBLE_MATCH_STATUSES,
default_policy_versions, default_policy_versions,
normalize_reason_codes, normalize_reason_codes,
route_type_from_profile_path, route_type_from_profile_path,
@@ -67,9 +68,9 @@ def _apply_stp_route_adjudication(
""" """
在路由结果上写入明确的 STP 裁决:straight_through | needs_review。 在路由结果上写入明确的 STP 裁决:straight_through | needs_review。
核心逻辑:严格门禁——缺字段、低置信、缺证据、未批准自动建单、无自动接受标记、 核心逻辑:严格门禁——缺字段/低置信/缺证据/无自动接受标记、或非 deterministic
或非 deterministic 执行态 → needs_review;仅干净直通可 straight_through。 执行态 → needs_review;模板 auto_create_approved 仅作治理痕迹,不参与 STP 裁决。
重复冲突在 Candidate 落库阶段再拦,不在本函数臆造。 是否自动建单由 Candidate Qualification 统一裁决。重复冲突在 Candidate 落库阶段再拦。
Args: Args:
decision: 路由决策字典(就地写入 route_decision / reason_codes)。 decision: 路由决策字典(就地写入 route_decision / reason_codes)。
@@ -80,6 +81,8 @@ def _apply_stp_route_adjudication(
带 STP 字段的 DeterministicRouteResult。 带 STP 字段的 DeterministicRouteResult。
""" """
reason_codes = [str(code) for code in (decision.get('fallback_reason_codes') or []) if str(code).strip()] reason_codes = [str(code) for code in (decision.get('fallback_reason_codes') or []) if str(code).strip()]
# [STEP] 模板审批旧码仅作痕迹,禁止参与 STP 硬门禁。
reason_codes = [code for code in reason_codes if code != 'profile_auto_create_not_approved']
has_acceptance = any( has_acceptance = any(
isinstance(order, dict) and order.get('_hxops_acceptance') in { isinstance(order, dict) and order.get('_hxops_acceptance') in {
'approved_deterministic_profile_v1', 'approved_deterministic_profile_v1',
@@ -98,9 +101,7 @@ def _apply_stp_route_adjudication(
reason_codes=reason_codes, stp_route_decision='needs_review', reason_codes=reason_codes, stp_route_decision='needs_review',
) )
# [STEP 2] 严格门禁:模板未批准 / 已有原因码 / 无自动接受标记 → needs_review。 # [STEP 2] 无自动接受标记或已有业务原因码 → needs_review;模板批准不阻断。
if not is_generic_route and not bool(decision.get('auto_create_approved')) and 'profile_auto_create_not_approved' not in reason_codes:
reason_codes.append('profile_auto_create_not_approved')
if not has_acceptance and not reason_codes: if not has_acceptance and not reason_codes:
reason_codes.append('acceptance_marker_missing') reason_codes.append('acceptance_marker_missing')
if is_generic_route: if is_generic_route:
@@ -109,18 +110,17 @@ def _apply_stp_route_adjudication(
decision, execution_mode='deterministic', orders=_strip_acceptance_markers(orders), decision, execution_mode='deterministic', orders=_strip_acceptance_markers(orders),
reason_codes=reason_codes, stp_route_decision='needs_review', reason_codes=reason_codes, stp_route_decision='needs_review',
) )
# 通用门禁通过即可 STP 直通;自动冻结另由 generic_auto_freeze / 紧急停止控制。
return _finalize_route_result( return _finalize_route_result(
decision, execution_mode='deterministic', orders=orders, decision, execution_mode='deterministic', orders=orders,
reason_codes=[], stp_route_decision='straight_through', reason_codes=[], stp_route_decision='straight_through',
) )
if reason_codes or not has_acceptance or not bool(decision.get('auto_create_approved')): if reason_codes or not has_acceptance:
return _finalize_route_result( return _finalize_route_result(
decision, execution_mode='deterministic', orders=_strip_acceptance_markers(orders), decision, execution_mode='deterministic', orders=_strip_acceptance_markers(orders),
reason_codes=reason_codes, stp_route_decision='needs_review', reason_codes=reason_codes, stp_route_decision='needs_review',
) )
# [STEP 3] 全部严格门禁通过 → 直通。 # [STEP 3] 业务门禁通过 → 直通(自动建单另由 Candidate Qualification 裁决)。
return _finalize_route_result( return _finalize_route_result(
decision, execution_mode='deterministic', orders=orders, decision, execution_mode='deterministic', orders=orders,
reason_codes=[], stp_route_decision='straight_through', reason_codes=[], stp_route_decision='straight_through',
@@ -484,6 +484,7 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
用 Run 冻结 Profile 解析 MinerU HTML,并生成不含坐标/HTML的紧凑字段候选。 用 Run 冻结 Profile 解析 MinerU HTML,并生成不含坐标/HTML的紧凑字段候选。
同一表命中多个 Profile 或命中 unsupported Profile 时设 blocking,调用方不得自动选择。 同一表命中多个 Profile 或命中 unsupported Profile 时设 blocking,调用方不得自动选择。
v2 模板的成功匹配事实随候选一起返回,供路由审计记录实际使用的模板身份。
""" """
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {} schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
@@ -507,6 +508,7 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
'matched': False, 'blocking': False, 'tables': [], 'issues': [], 'matched': False, 'blocking': False, 'tables': [], 'issues': [],
'match': {'status': 'no_special_profile_feature', 'candidates': []}, 'match': {'status': 'no_special_profile_feature', 'candidates': []},
} }
profile_match: dict[str, Any] = {}
v2_profiles = [ v2_profiles = [
item for item in profiles item for item in profiles
if isinstance(item.get('definition'), dict) if isinstance(item.get('definition'), dict)
@@ -526,6 +528,7 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
'issues': [f'order_profile_{match.status}'], 'issues': [f'order_profile_{match.status}'],
'match': match.model_dump(mode='json'), 'match': match.model_dump(mode='json'),
} }
profile_match = match.model_dump(mode='json')
profiles = [ profiles = [
item for item in v2_profiles item for item in v2_profiles
if item.get('profile_code') == match.profile_code and int(item.get('version') or 0) == match.version if item.get('profile_code') == match.profile_code and int(item.get('version') or 0) == match.version
@@ -584,7 +587,12 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
complete_rows = [] complete_rows = []
for row in v2_rows: for row in v2_rows:
region = next((item for item in profile.table_regions if item.region_id == row.get('_coordinate_region_id')), None) region = next((item for item in profile.table_regions if item.region_id == row.get('_coordinate_region_id')), None)
if region is not None and row.get('_coordinate_row_count', 0) < len(region.line_layouts): if (
region is not None
and region.continuation_rule.allow_cross_page
and region.row_reconstruction_mode == 'fixed_subrows'
and row.get('_coordinate_row_count', 0) < len(region.line_layouts)
):
cross_page_carries[(str(raw_profile.get('profile_code') or ''), table_id)] = { cross_page_carries[(str(raw_profile.get('profile_code') or ''), table_id)] = {
'region_id': region.region_id, 'region_id': region.region_id,
'fields': {str(field.get('field_code') or ''): str(field.get('value') or '') for field in row.get('fields') or [] if isinstance(field, dict)}, 'fields': {str(field.get('field_code') or ''): str(field.get('value') or '') for field in row.get('fields') or [] if isinstance(field, dict)},
@@ -684,6 +692,7 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
'blocking': bool(issues), 'blocking': bool(issues),
'tables': result_tables, 'tables': result_tables,
'issues': sorted(set(issues)), 'issues': sorted(set(issues)),
'match': profile_match,
} }
@@ -845,13 +854,14 @@ def _merge_confirmed_profile_order_fields(run: Any, *, unit: Any, orders: list[d
field = by_id.get(field_id) field = by_id.get(field_id)
observation = { observation = {
'value': candidate.get('value'), 'document_id': int(unit.document_id), 'value': candidate.get('value'), 'document_id': int(unit.document_id),
'quote': str(candidate.get('value') or '')[:1000], 'confidence': 1.0, 'quote': '', 'confidence': 1.0,
'layout_evidence': { 'layout_evidence': {
'page_no': candidate.get('page_no'), 'source': candidate.get('source'), 'page_no': candidate.get('page_no'), 'source': candidate.get('source'),
'anchor_bbox': candidate.get('anchor_bbox'), 'value_bbox': candidate.get('value_bbox'), 'anchor_bbox': candidate.get('anchor_bbox'), 'value_bbox': candidate.get('value_bbox'),
'glyph_indices': list(candidate.get('glyph_indices') or []), 'glyph_indices': list(candidate.get('glyph_indices') or []),
}, },
} }
_attach_independent_profile_evidence(run, candidate, observation['layout_evidence'], unit=unit)
if field is None: if field is None:
header_fields.append({ header_fields.append({
'field_id': field_id, 'observations': [observation], 'field_id': field_id, 'observations': [observation],
@@ -939,16 +949,14 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
decision['business_table_count'] = 1 decision['business_table_count'] = 1
decision['matched_table_count'] = 1 decision['matched_table_count'] = 1
decision['document_table_count'] = len(tables) decision['document_table_count'] = len(tables)
if not bool(selected.get('auto_create_approved')): # 模板 auto_create_approved 仅写入决策痕迹;不得剥离验收标记或降级 STP。
for order in orders: decision['auto_create_approved'] = bool(selected.get('auto_create_approved'))
if isinstance(order, dict):
order.pop('_hxops_acceptance', None)
decision['fallback_reason_codes'] = ['profile_auto_create_not_approved']
return _apply_stp_route_adjudication(decision, execution_mode='deterministic', orders=orders) return _apply_stp_route_adjudication(decision, execution_mode='deterministic', orders=orders)
if reason_code == 'row_needs_review': if reason_code == 'row_needs_review':
decision['review_details'] = _profile_row_review_details(selected) decision['review_details'] = _profile_row_review_details(selected)
# [STEP 2] 通用确定性路径:仅 no_special_profile_feature / no_match(无漂移) 且开关开启。 # [STEP 2] 通用确定性路径:模板未命中,或模板命中但模板解析未产出订单时,
# 均尝试通用解析。模板优先级只决定“先试模板”,不应把模板失败变成终态失败。
if _should_attempt_generic_extraction(match_status=match_status, profile_result=profile_result): if _should_attempt_generic_extraction(match_status=match_status, profile_result=profile_result):
if not generic_extraction_enabled(): if not generic_extraction_enabled():
decision['fallback_reason_codes'] = ['generic_extraction_disabled'] decision['fallback_reason_codes'] = ['generic_extraction_disabled']
@@ -958,7 +966,7 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
schema=schema, definition=definition, decision=decision, schema=schema, definition=definition, decision=decision,
) )
# [STEP 3] 模板路径失败且不允许通用降级 → 沿用既有 review 语义。 # [STEP 3] 仅在布局前置条件本身不可用,或通用解析被配置关闭时进入复核。
if profile_result.get('blocking'): if profile_result.get('blocking'):
issues = profile_result.get('issues') if isinstance(profile_result.get('issues'), list) else [] issues = profile_result.get('issues') if isinstance(profile_result.get('issues'), list) else []
decision['fallback_reason_codes'] = [_route_reason_for_issue(str(issue)) for issue in issues] decision['fallback_reason_codes'] = [_route_reason_for_issue(str(issue)) for issue in issues]
@@ -977,21 +985,15 @@ def _should_attempt_generic_extraction(*, match_status: str, profile_result: dic
""" """
判断是否允许进入通用 Schema 确定性解析。 判断是否允许进入通用 Schema 确定性解析。
核心逻辑:layout_drift/ambiguous/evidence_insufficient 永不降级;no_special_profile_feature 核心逻辑:模板命中失败与未命中都必须进入通用解析;模板匹配状态只用于审计,
与无漂移 no_match 在开关开启时可尝试 generic。 不再阻断通用路径。布局是否可解析由 generic gate 依据实际候选证据判断。
""" """
blocked = {'layout_drift', 'ambiguous', 'evidence_insufficient'} # 只要布局快照已 ready,就交给通用门禁判断是否具备足够的表格/字段证据。
if match_status in blocked: # 这样模板解析失败、模板漂移、多个候选以及完全无模板都能统一降级,
return False # 后续由调用方把 generic gate 失败继续交给 LLM/人工复核链路。
issues = profile_result.get('issues') if isinstance(profile_result.get('issues'), list) else [] _ = match_status
if any(str(issue) in {'order_profile_layout_drift', 'order_profile_ambiguous', 'order_profile_evidence_insufficient'} for issue in issues): _ = profile_result
return False
match = profile_result.get('match') if isinstance(profile_result.get('match'), dict) else {}
if str(match.get('status') or '') in blocked:
return False
if match_status in GENERIC_ELIGIBLE_MATCH_STATUSES:
return True return True
return match_status == 'no_match' and str(match.get('status') or match_status) not in blocked
def _route_generic_deterministic_unit( def _route_generic_deterministic_unit(
@@ -1035,6 +1037,9 @@ def _route_generic_deterministic_unit(
reason_codes = list(gate.reason_codes) reason_codes = list(gate.reason_codes)
if gate.parse_result and gate.parse_result.reason_code and gate.parse_result.reason_code not in reason_codes: if gate.parse_result and gate.parse_result.reason_code and gate.parse_result.reason_code not in reason_codes:
reason_codes.insert(0, gate.parse_result.reason_code) reason_codes.insert(0, gate.parse_result.reason_code)
# 通用门禁失败后明确标记 LLM 辅助路由。Worker 仍以 review_required 结束确定性阶段,
# 对话工作台据此提供/触发现有 LLM 解析建议链路,而不是把文档误报为技术失败。
decision['route_type'] = 'llm_assisted_review'
decision['fallback_reason_codes'] = reason_codes or ['generic_gate_blocked'] decision['fallback_reason_codes'] = reason_codes or ['generic_gate_blocked']
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[]) return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
@@ -1137,8 +1142,19 @@ def _build_approved_profile_order_result(
continue continue
observation = { observation = {
'value': raw.get('value'), 'document_id': int(unit.document_id), 'value': raw.get('value'), 'document_id': int(unit.document_id),
'quote': str(raw.get('quote') or raw.get('value') or '')[:1000], 'confidence': 1.0, 'quote': str(raw.get('quote') or '')[:1000], 'confidence': 1.0,
} }
# [STEP] 明细字段沿用 layout candidate 的真实单元格证据;没有 value_bbox 时不伪造字段级坐标。
layout_evidence = {
key: raw.get(key) for key in (
'page_no', 'table_id', 'row_index', 'column_index', 'cell_id', 'evidence_ref',
'token_ids', 'cell_bbox', 'cell_normalized_bbox', 'value_bbox', 'normalized_bbox',
'has_value_coordinate', 'bbox_text', 'quote_source', 'source', 'highlight_source',
'coordinate_status', 'highlight_quality', 'coordinate_issue_codes', 'value_match_status',
) if key in raw
}
if layout_evidence:
observation['layout_evidence'] = layout_evidence
# PO can be configured as a Header field yet appear once per table row. Keep it # PO can be configured as a Header field yet appear once per table row. Keep it
# with the row until PO partitioning proves the association is unambiguous. # with the row until PO partitioning proves the association is unambiguous.
if config.get('scope') == 'header' and field_id not in po_field_ids: if config.get('scope') == 'header' and field_id not in po_field_ids:
@@ -1276,3 +1292,44 @@ def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, An
coordinate_evidence=layout.get('coordinate_evidence') or {}, coordinate_evidence=layout.get('coordinate_evidence') or {},
) )
return [item.model_dump(mode='json') for item in candidates if item.status == 'confirmed'] return [item.model_dump(mode='json') for item in candidates if item.status == 'confirmed']
def _attach_independent_profile_evidence(
run: Any, candidate: dict[str, Any], layout_evidence: dict[str, Any], *, unit: Any,
) -> None:
"""从冻结页字符索引生成独立引文/token 元数据,不回写机器值充当证据。"""
snapshot = getattr(run, 'input_snapshot_json', None)
snapshot = snapshot if isinstance(snapshot, dict) else {}
document_id = int(getattr(unit, 'document_id', 0) or 0)
page_no = int(candidate.get('page_no') or 0)
indices = candidate.get('glyph_indices') if isinstance(candidate.get('glyph_indices'), list) else []
for intake in snapshot.get('intakes') or []:
if not isinstance(intake, dict):
continue
for document in intake.get('documents') or []:
if not isinstance(document, dict) or int(document.get('document_id') or 0) != document_id:
continue
layout = document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {}
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
pages = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
glyphs = pages.get(str(page_no)) or pages.get(page_no)
if not isinstance(glyphs, list) or not indices:
return
chars: list[str] = []
token_ids: list[str] = []
for raw_index in indices:
try:
index = int(raw_index)
glyph = glyphs[index]
except (IndexError, TypeError, ValueError):
return
if not isinstance(glyph, dict):
return
chars.append(str(glyph.get('text') or ''))
token_ids.append(str(glyph.get('token_id') or f'pdf-glyph:{document_id}:{page_no}:{index}'))
quote = ''.join(chars).strip()
if quote:
layout_evidence['bbox_text'] = quote[:1000]
layout_evidence['quote_source'] = 'glyph_region'
layout_evidence['token_ids'] = token_ids
return
@@ -8,7 +8,8 @@ backend/app/services/shipping_notice/order_extraction_workspace_projection.py
与可操作按钮都在这里统一裁剪与组装。阶段 1 起由后端唯一投影 user_visible_stage、 与可操作按钮都在这里统一裁剪与组装。阶段 1 起由后端唯一投影 user_visible_stage、
queue_position、elapsed_seconds、health_tips 与 cancellation;阶段 5 按功能开关裁剪取消动作与健康提示。 queue_position、elapsed_seconds、health_tips 与 cancellation;阶段 5 按功能开关裁剪取消动作与健康提示。
Run 级 handling_items 拆分「待补信息 / 冲突 / 自动冻结受阻 / PDF 复核 / 技术失败 / 预算停扩」, Run 级 handling_items 拆分「待补信息 / 冲突 / 自动冻结受阻 / PDF 复核 / 技术失败 / 预算停扩」,
供聊天卡与右侧「本次处理」按原因展示与跳转,避免仅依赖部分完成/需复核状态码。 供聊天卡与右侧「本次处理」按原因展示与跳转,避免仅依赖部分完成/需复核状态码;
文档级 reason_code 同步投影 explainability(error_explainability_contract)。
""" """
from __future__ import annotations from __future__ import annotations
@@ -24,6 +25,7 @@ from app.models import (
ShippingOrderExtractionRun, ShippingOrderExtractionRun,
ShippingOrderExtractionUnit, ShippingOrderExtractionUnit,
) )
from app.services.shipping_notice.error_explainability_contract import build_explainability_reason
from app.services.shipping_notice.progress_audit_contract import HEALTH_TIP_THRESHOLDS_SECONDS from app.services.shipping_notice.progress_audit_contract import HEALTH_TIP_THRESHOLDS_SECONDS
from app.services.shipping_notice.progress_feature_flags import ( from app.services.shipping_notice.progress_feature_flags import (
order_extraction_cancel_enabled, order_extraction_cancel_enabled,
@@ -1284,6 +1286,17 @@ def serialize_workspace_run_documents(run: ShippingOrderExtractionRun) -> list[d
document = documents.get(int(unit.document_id), {}) document = documents.get(int(unit.document_id), {})
duplicate = duplicates_by_doc.get(int(unit.document_id), {}) duplicate = duplicates_by_doc.get(int(unit.document_id), {})
started_at = getattr(unit, 'started_at', None) or (unit.created_at if unit.status != 'pending' else None) started_at = getattr(unit, 'started_at', None) or (unit.created_at if unit.status != 'pending' else None)
reason_code = _document_reason_code(unit, duplicate=duplicate)
explainability = None
if reason_code:
explainability = build_explainability_reason(
reason_code=str(reason_code),
details={
'document_id': int(unit.document_id),
'unit_id': int(unit.id),
'file_name': document.get('file_name'),
},
)
items.append({ items.append({
'unit_id': int(unit.id), 'unit_id': int(unit.id),
'document_id': int(unit.document_id), 'document_id': int(unit.document_id),
@@ -1311,7 +1324,8 @@ def serialize_workspace_run_documents(run: ShippingOrderExtractionRun) -> list[d
'match_status': _match_status_projection(unit, route_by_unit=route_by_unit), 'match_status': _match_status_projection(unit, route_by_unit=route_by_unit),
'freeze_source': _freeze_source_projection(run, unit, route_by_unit=route_by_unit), 'freeze_source': _freeze_source_projection(run, unit, route_by_unit=route_by_unit),
'email_supplement': _email_supplement_projection(unit, event_map, field_codes=field_codes), 'email_supplement': _email_supplement_projection(unit, event_map, field_codes=field_codes),
'reason_code': _document_reason_code(unit, duplicate=duplicate), 'reason_code': reason_code,
'explainability': explainability,
'review_details': list((unit.result_json or {}).get('review_details') or []), 'review_details': list((unit.result_json or {}).get('review_details') or []),
'duplicate_resolution': duplicate.get('duplicate_resolution'), 'duplicate_resolution': duplicate.get('duplicate_resolution'),
'existing_task_no': duplicate.get('existing_task_no'), 'existing_task_no': duplicate.get('existing_task_no'),
@@ -1436,6 +1450,25 @@ def serialize_workspace_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
} }
def _chat_run_error_explainability(run: ShippingOrderExtractionRun) -> dict[str, Any] | None:
"""
聊天态卡用的 Run 失败可解释性投影。
核心逻辑:调用 build_explainability_reason;不依赖 run_service,避免循环 import。
"""
code = str(run.error_code or '').strip()
if not code:
return None
request_id = None
if isinstance(run.result_json, dict):
request_id = str(run.result_json.get('request_id') or '').strip() or None
return build_explainability_reason(
reason_code=code,
details={'source_error_code': code[:64]},
request_id=request_id,
)
def serialize_workspace_run_chat_state(run: ShippingOrderExtractionRun) -> dict[str, Any]: def serialize_workspace_run_chat_state(run: ShippingOrderExtractionRun) -> dict[str, Any]:
""" """
构建聊天消息使用的订单抽取状态卡。 构建聊天消息使用的订单抽取状态卡。
@@ -1491,6 +1524,8 @@ def serialize_workspace_run_chat_state(run: ShippingOrderExtractionRun) -> dict[
'progressVersion': projection.get('progress_version'), 'progressVersion': projection.get('progress_version'),
'terminal': str(run.status or '') not in {'queued', 'processing'}, 'terminal': str(run.status or '') not in {'queued', 'processing'},
'errorCode': str(run.error_code or '') or None, 'errorCode': str(run.error_code or '') or None,
# [STEP] Run 失败可解释性;与 serialize_order_extraction_run.error.explainability 语义对齐。
'errorExplainability': _chat_run_error_explainability(run),
'startedAt': run.started_at.isoformat() + 'Z' if run.started_at else None, 'startedAt': run.started_at.isoformat() + 'Z' if run.started_at else None,
'finishedAt': run.finished_at.isoformat() + 'Z' if run.finished_at else None, 'finishedAt': run.finished_at.isoformat() + 'Z' if run.finished_at else None,
} }
@@ -3,13 +3,18 @@ backend/app/services/shipping_notice/order_review_confirmation_service.py
用途:按 PDF 确认复核草稿并独立创建发货任务,确认后复用同一 auto_progress 链。 用途:按 PDF 确认复核草稿并独立创建发货任务,确认后复用同一 auto_progress 链。
依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task、stp_inventory_freeze、 依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task、stp_inventory_freeze、
customer_auto_resolution、fulfillment_audit、order_review_progress_bridge、 candidate_qualification_service、customer_auto_resolution、fulfillment_audit、
workflow_ledger_service、progress_workflow.auto_progress、process_gate_bridge。 order_review_progress_bridge、workflow_ledger_service、
queue_service.enqueue_shipping_notice_job、process_gate_bridge。
逻辑:确认在单事务内分别锁定 Case 与 Draft,重跑资格门禁,冻结行级库存源候选与 逻辑:确认在单事务内分别锁定 Case 与 Draft,重跑资格门禁,冻结行级库存源候选与
可自动确认的客户;物化人工 Candidate 与 accepted Extraction(保留派生 field_lineage); 可自动确认的客户;物化人工 Candidate 与 accepted Extraction(保留派生 field_lineage);
建单前再次校验客户确认并持久化 Candidate Qualification 快照;客户未确认拒绝建单;
成功确认镜像 review_confirmed 到订单抽取进度流;校验 WorkflowItem 当前版本后推进至 成功确认镜像 review_confirmed 到订单抽取进度流;校验 WorkflowItem 当前版本后推进至
building_order(不关闭);同步 Process Execution 推进至 task_creation 通过, building_order(不关闭);同步 Process Execution 推进至 task_creation 通过,
避免重复冻结资格阻断;API commit 后触发 auto_progress,止于 manual_upload_pending。 避免重复冻结资格阻断;与确认同事务入队 shipping_notice_run(待推进 Outbox),
Worker/sync 消费后走 auto_progress(库存→匹配→Excel;AUTO_UPLOAD 显式开启且 RPA 就绪时
继续货代上传,否则停于真正待人工上传);幂等回放检查实际推进态后补推;
resolve_confirm_outcome 将推进摘要映射为 confirm_outcome 枚举供 API/前端解耦 success。
""" """
from __future__ import annotations from __future__ import annotations
@@ -811,11 +816,43 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
) )
try: try:
assert_case_is_current_workflow_version(case=case) assert_case_is_current_workflow_version(case=case)
# [STEP] 建单前再次校验客户确认(相对 Draft 校验时刻防并发回退)。
from app.services.shipping_notice.candidate_qualification_service import (
recalculate_candidate_qualification,
resolve_review_case_customer_resolved,
)
pre_candidate = (
db.session.get(ShippingNoticeCandidate, int(case.candidate_id))
if case.candidate_id
else None
)
if not resolve_review_case_customer_resolved(case=case, candidate=pre_candidate):
raise ConflictError(
'Customer is not confirmed',
code='SHIPPING.REVIEW_CUSTOMER_UNRESOLVED',
)
normalized = normalize_candidate_business_summary(summary) normalized = normalize_candidate_business_summary(summary)
extraction = _materialize_extraction(case=case, intake_id=int(intake.id), summary=normalized, actor_id=int(user_id)) extraction = _materialize_extraction(case=case, intake_id=int(intake.id), summary=normalized, actor_id=int(user_id))
candidate = _create_review_candidate( candidate = _create_review_candidate(
case=case, intake=intake, document=document, summary=normalized, extraction=extraction, user_id=int(user_id), case=case, intake=intake, document=document, summary=normalized, extraction=extraction, user_id=int(user_id),
) )
# [STEP] 人工 Candidate 继承 Case 侧已确认客户,供资格快照与下游门禁读取。
structured = dict(candidate.structured_result_json or {})
customer_block = (
dict(structured['customer'])
if isinstance(structured.get('customer'), dict)
else {}
)
customer_block['resolution_status'] = 'confirmed'
customer_block['confirmed_via'] = 'review_case'
structured['customer'] = customer_block
candidate.structured_result_json = structured
recalculate_candidate_qualification(
candidate=candidate,
run=case.run,
customer_resolved=True,
persist=True,
)
except AppError as err: except AppError as err:
_reject_confirmation( _reject_confirmation(
case, case,
@@ -851,9 +888,26 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
task, task,
line_projections=list(validation.get('line_projections') or []), line_projections=list(validation.get('line_projections') or []),
) )
# [STEP] 客户可自动确认时跳过 customer_review,与批次建单路径一致。 # [STEP] 建单前已校验客户确认:立即绑定标准客户,禁止落入 customer_review。
from app.services.shipping_notice.candidate_qualification_service import (
resolve_confirmed_bill_to_customer_id,
)
from app.services.shipping_notice.customer_auto_resolution import try_auto_confirm_task_customer from app.services.shipping_notice.customer_auto_resolution import try_auto_confirm_task_customer
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
bind_customer_id = resolve_confirmed_bill_to_customer_id(
candidate=candidate,
extraction_id=int(extraction.id),
)
if bind_customer_id is not None:
confirm_task_customer(
task,
customer_id=int(bind_customer_id),
actor_id=int(user_id),
resolution_method='review_case_confirmed',
commit=False,
)
else:
try_auto_confirm_task_customer(task) try_auto_confirm_task_customer(task)
revision = ShippingOrderReviewConfirmedRevision( revision = ShippingOrderReviewConfirmedRevision(
case_id=int(case.id), task_id=int(task.id), draft_version=int(case.current_draft.draft_version), case_id=int(case.id), task_id=int(task.id), draft_version=int(case.current_draft.draft_version),
@@ -903,7 +957,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
log_task_event(task, 'task_created_from_review_case', {'case_no': case.case_no, 'confirmed_revision_id': None}) log_task_event(task, 'task_created_from_review_case', {'case_no': case.case_no, 'confirmed_revision_id': None})
db.session.flush() db.session.flush()
workflow_refs = _workflow_refs_for_case(case) workflow_refs = _workflow_refs_for_case(case)
# 调用方须在 commit 后调用 trigger_auto_progress_after_review_confirm。 # 调用方须在同事务内调用 schedule_auto_progress_after_review_confirm(commit=False) 再 commit。
return { return {
'task_no': task.task_no, 'task_no': task.task_no,
'idempotent_replay': False, 'idempotent_replay': False,
@@ -912,20 +966,186 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
**workflow_refs, **workflow_refs,
} }
def trigger_auto_progress_after_review_confirm(*, task_no: str | None, idempotent_replay: bool = False) -> dict[str, Any] | None:
"""
人工复核确认建单并提交事务后,复用与 STP 直通相同的 auto_progress 入口。
核心逻辑:幂等回放不重复推进;系统 source,禁止平行链路。 def _task_needs_post_confirm_auto_progress(task: ShippingTask | None) -> bool:
"""
判断确认建单后的任务是否仍需自动推进。
核心逻辑:仍为 created 且已挂正式 Extraction,视为尚未被 auto_progress 消费的悬挂态。
Args:
task: 发货任务;None 视为不需要。
Returns:
True 表示应入队/补推;False 表示已推进或不可推进。
"""
if task is None:
return False
process_status = str(getattr(task, 'process_status', None) or '').strip().lower()
if process_status != 'created':
return False
return bool(getattr(task, 'current_order_extraction_id', None))
def resolve_confirm_outcome(progress: dict[str, Any] | None) -> str:
"""
将确认建单后的自动推进调度摘要映射为稳定 outcome 枚举。
核心逻辑:HTTP 成功仅表示建单事务成功;调用方须读 confirm_outcome / auto_progress
区分「已入队 / 推进失败可恢复 / 无需调度」,不可只看 success 或 confirm_ok。
Args:
progress: schedule/finalize 返回的推进摘要;None 表示未调度。
Returns:
confirmed_and_auto_progress_started |
confirmed_auto_progress_failed |
confirmed_auto_progress_not_scheduled
"""
if progress is None:
return 'confirmed_auto_progress_not_scheduled'
status = str(progress.get('status') or '').strip().lower()
if status in {'enqueue_failed', 'sync_execution_failed', 'failed'}:
return 'confirmed_auto_progress_failed'
if status == 'not_scheduled':
return 'confirmed_auto_progress_not_scheduled'
if bool(progress.get('auto_progress_started')):
return 'confirmed_and_auto_progress_started'
return 'confirmed_auto_progress_not_scheduled'
def schedule_auto_progress_after_review_confirm(
*,
task_no: str | None,
idempotent_replay: bool = False,
created_by_id: int | None = None,
commit: bool = False,
) -> dict[str, Any] | None:
"""
确认建单后持久化「待推进」后台 Job(shipping_notice_run),由 Worker/sync 幂等消费。
核心逻辑:与确认同事务入队(commit=False)避免建单已提交但推进失败的悬挂态;
幂等回放不无条件跳过,而是检查任务是否仍停在 created+已抽取;已有 active Job 则复用。
Args:
task_no: 新建或回放任务号。
idempotent_replay: 是否幂等回放;为 True 时仅在仍需推进时补推。
created_by_id: Job 创建人。
commit: 入队是否自行提交;确认路径应传 False 与业务同事务。
Returns:
调度摘要(含 auto_progress_started / enqueue_result);无任务或不需推进时返回 None。
"""
normalized = str(task_no or '').strip().upper()
if not normalized:
return None
task = db.session.query(ShippingTask).filter(ShippingTask.task_no == normalized).first()
# [STEP] 首轮与幂等回放共用:仅当仍停在 created+已抽取时入队,避免无条件跳过导致悬挂。
if not _task_needs_post_confirm_auto_progress(task):
return None
from app.services.shipping_notice.queue_service import (
enqueue_shipping_notice_job,
shipping_task_execution_mode,
)
ok, enqueue_result = enqueue_shipping_notice_job(
task_no=normalized,
created_by_id=created_by_id,
commit=commit,
)
if not ok:
return {
'auto_progress_started': False,
'enqueue_result': str(enqueue_result),
'status': 'enqueue_failed',
'message': str(enqueue_result),
'idempotent_replay': bool(idempotent_replay),
}
result_token = str(enqueue_result or '')
return {
'auto_progress_started': True,
'enqueue_result': result_token,
'status': (
'queued'
if result_token.startswith('queued') or result_token in {'queued_for_worker', 'queued_manual'}
else result_token
),
'message': '已入队自动推进',
'idempotent_replay': bool(idempotent_replay),
'execution_mode': shipping_task_execution_mode(),
'sync_pending_job_id': (
int(result_token.split(':', 1)[1])
if result_token.startswith('queued_sync_pending:')
else None
),
}
def finalize_sync_auto_progress_after_commit(schedule: dict[str, Any] | None) -> dict[str, Any] | None:
"""
在确认事务提交后,执行 sync 模式下延后的 shipping_notice_run Job。
核心逻辑:仅处理 schedule.sync_pending_job_id;执行异常不得向上抛出,
以保证「确认已成功」的 HTTP 契约不被推进异常掩盖。
Args:
schedule: schedule_auto_progress_after_review_confirm 的返回值。
Returns:
更新后的调度摘要;无需执行时原样返回;同步失败时 status=sync_execution_failed。
"""
if not isinstance(schedule, dict):
return schedule
job_id = schedule.get('sync_pending_job_id')
if job_id is None:
return schedule
from app.services.shipping_notice.queue_service import run_shipping_notice_job
updated = dict(schedule)
try:
_ok_run, sync_status = run_shipping_notice_job({'job_id': int(job_id)})
updated['status'] = sync_status or updated.get('status')
updated['enqueue_result'] = sync_status or updated.get('enqueue_result')
updated['message'] = str(sync_status or updated.get('message') or '')
updated['auto_progress_started'] = True
except Exception as exc: # noqa: BLE001 — 确认已提交,推进异常必须降级为业务字段
updated['status'] = 'sync_execution_failed'
updated['auto_progress_started'] = True
updated['enqueue_result'] = updated.get('enqueue_result') or f'queued_sync_pending:{int(job_id)}'
updated['message'] = (
'确认建单已成功,同步自动推进执行异常;任务与 Job 已持久化,请重试推进或等待 Worker。'
)
updated['sync_error'] = str(exc)[:300]
updated['sync_pending_job_id'] = None
return updated
def trigger_auto_progress_after_review_confirm(
*,
task_no: str | None,
idempotent_replay: bool = False,
created_by_id: int | None = None,
) -> dict[str, Any] | None:
"""
兼容旧调用名:确认提交后调度自动推进(内部改为持久化 Job)。
核心逻辑:委托 schedule_auto_progress_after_review_confirm(commit=True);
幂等回放会检查实际推进态后决定是否补推。
Args: Args:
task_no: 新建或回放任务号。 task_no: 新建或回放任务号。
idempotent_replay: 是否幂等回放。 idempotent_replay: 是否幂等回放。
created_by_id: Job 创建人。
Returns: Returns:
auto_progress 响应;无任务或回放时返回 None。 调度摘要;无任务或不需推进时返回 None。
""" """
if idempotent_replay or not task_no: return schedule_auto_progress_after_review_confirm(
return None task_no=task_no,
from app.services.shipping_notice.progress_workflow import auto_progress idempotent_replay=idempotent_replay,
return auto_progress({'task_id': str(task_no).strip(), 'source': 'system'}) created_by_id=created_by_id,
commit=True,
)
@@ -0,0 +1,230 @@
"""
services/shipping_notice/order_review_customer_service.py
用途:建单前复核工作台的客户识别结果查询、重新匹配与人工确认。
依赖:order_review_draft_service、order_customer_matching、candidate_qualification_service、
ShippingOrderReviewCase / ShippingOrderCustomerMatch。
逻辑:由 workspace order-review-cases 客户路由调用;确认后重跑 Draft 校验以刷新建单资格;
不创建 Task、不重新解析 PDF。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError
from app.models import (
ShippingNoticeCandidate,
ShippingOrderCustomerMatch,
ShippingOrderExtraction,
ShippingOrderReviewCase,
)
from app.services.shipping_notice.candidate_qualification_service import (
resolve_review_case_customer_resolved,
)
from app.services.shipping_notice.order_customer_matching import (
confirm_order_customer_match,
refresh_order_customer_matches,
serialize_order_customer_match,
)
from app.services.shipping_notice.order_review_draft_service import (
soft_load_review_case_for_audit,
validate_draft,
)
from app.services.shipping_notice.workflow_ledger_service import (
assert_case_is_current_workflow_version,
)
def _load_writable_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase:
"""加载属主可写 Case,并校验 Workflow 当前版本。"""
case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no or ''))
if case is None:
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
if str(case.status or '') in {'confirmed', 'non_order', 'superseded', 'reparse_pending'}:
raise ConflictError(
'Review case is not editable',
code='SHIPPING.REVIEW_CASE_NOT_EDITABLE',
details={'status': case.status},
)
assert_case_is_current_workflow_version(case=case)
return case
def _resolve_extraction_for_case(case: ShippingOrderReviewCase) -> ShippingOrderExtraction | None:
"""优先 Case 关联 Candidate 的 Extraction;否则取 Run 内最新 Extraction。"""
candidate = (
db.session.get(ShippingNoticeCandidate, int(case.candidate_id))
if case.candidate_id
else None
)
if candidate is not None and candidate.order_extraction_id:
extraction = db.session.get(ShippingOrderExtraction, int(candidate.order_extraction_id))
if extraction is not None:
return extraction
return (
ShippingOrderExtraction.query
.filter_by(run_id=int(case.run_id))
.order_by(ShippingOrderExtraction.id.desc())
.first()
)
def _header_from_case(case: ShippingOrderReviewCase) -> dict[str, Any]:
"""从 Draft / Candidate 业务摘要投影客户匹配所需的头字段。"""
header: dict[str, Any] = {}
draft = case.current_draft
if draft is not None and isinstance(draft.header_values_json, dict):
# Draft 以 field_id 存值;客户匹配需要 bill_to_* 业务码,尽量从 Candidate 摘要补齐。
for key, value in draft.header_values_json.items():
if isinstance(key, str) and value is not None:
header[str(key)] = value
candidate = (
db.session.get(ShippingNoticeCandidate, int(case.candidate_id))
if case.candidate_id
else None
)
structured = candidate.structured_result_json if candidate is not None else None
summary = (
structured.get('business_summary')
if isinstance(structured, dict) and isinstance(structured.get('business_summary'), dict)
else {}
)
for key in (
'bill_to_customer',
'bill_to_customer_code',
'bill_to_source_system',
'ship_to_customer',
'ship_to_code',
'ship_to_source_system',
'customer_name',
):
if key not in header and summary.get(key) is not None:
header[key] = summary.get(key)
if 'bill_to_customer' not in header and header.get('customer_name'):
header['bill_to_customer'] = header.get('customer_name')
return header
def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> dict[str, Any]:
"""
投影复核 Case 的建单前客户识别状态,供工作台固定客户区展示。
Returns:
resolved、status、raw_name、confirmed 客户快照、候选列表、extraction_id。
"""
extraction = _resolve_extraction_for_case(case)
candidate = (
db.session.get(ShippingNoticeCandidate, int(case.candidate_id))
if case.candidate_id
else None
)
resolved = resolve_review_case_customer_resolved(case=case, candidate=candidate)
match = None
if extraction is not None:
match = ShippingOrderCustomerMatch.query.filter_by(
extraction_id=int(extraction.id),
role='bill_to',
).first()
match_payload = serialize_order_customer_match(match) if match is not None else None
status = str((match_payload or {}).get('status') or ('confirmed' if resolved else 'unmatched'))
return {
'resolved': bool(resolved),
'status': status,
'role': 'bill_to',
'extraction_id': int(extraction.id) if extraction is not None else None,
'raw_name': (match_payload or {}).get('raw_name'),
'customer_id': (match_payload or {}).get('customer_id'),
'standard_name': (match_payload or {}).get('standard_name'),
'short_code': (match_payload or {}).get('short_code'),
'candidates': list((match_payload or {}).get('candidates') or []),
'match': match_payload,
}
def confirm_review_case_customer(
*,
user_id: int,
case_no: str,
customer_id: int,
reason: str | None = None,
) -> dict[str, Any]:
"""
在复核工作台确认标准客户,并刷新建单资格。
核心逻辑:写入 Bill-to CustomerMatch=confirmed → validate Draft → 返回最新 Case。
"""
case = _load_writable_case(user_id=user_id, case_no=case_no)
extraction = _resolve_extraction_for_case(case)
if extraction is None:
raise ConflictError(
'Order extraction is required before confirming customer',
code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND',
)
# [STEP 1] 若尚无 match 行,先按当前头字段刷新,再人工确认。
if ShippingOrderCustomerMatch.query.filter_by(extraction_id=int(extraction.id), role='bill_to').first() is None:
refresh_order_customer_matches(extraction, _header_from_case(case))
confirm_order_customer_match(
int(extraction.id),
role='bill_to',
customer_id=int(customer_id),
site_id=None,
actor_id=int(user_id),
reason=str(reason or '复核工作台人工确认标准客户').strip(),
)
# confirm_order_customer_match 已 commit;随后重校验 Draft 以刷新 can_build / gates。
if case.current_draft is not None:
validate_draft(
user_id=int(user_id),
case_no=str(case.case_no),
expected_draft_version=int(case.current_draft.draft_version),
)
db.session.commit()
case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no))
if case is None:
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
from app.services.shipping_notice.order_review_projection import serialize_review_case
return {
'case': serialize_review_case(case),
'customer_resolution': project_review_case_customer_resolution(case),
}
def retry_review_case_customer_resolution(
*,
user_id: int,
case_no: str,
) -> dict[str, Any]:
"""
重新识别客户(不重解析 PDF):按当前 Draft/摘要刷新 CustomerMatch。
【AI 触发时机】:用户在复核工作台点击「重新识别客户」时调用。
"""
case = _load_writable_case(user_id=user_id, case_no=case_no)
extraction = _resolve_extraction_for_case(case)
if extraction is None:
raise ConflictError(
'Order extraction is required before retrying customer resolution',
code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND',
)
matches = refresh_order_customer_matches(extraction, _header_from_case(case))
db.session.commit()
if case.current_draft is not None:
validate_draft(
user_id=int(user_id),
case_no=str(case.case_no),
expected_draft_version=int(case.current_draft.draft_version),
)
db.session.commit()
case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no))
if case is None:
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
from app.services.shipping_notice.order_review_projection import serialize_review_case
return {
'case': serialize_review_case(case),
'customer_resolution': project_review_case_customer_resolution(case),
'matches': matches,
}
@@ -617,10 +617,11 @@ def reparse_case_document(*, user_id: int, case_no: str, reason: str, comment: s
reason_code=normalized, reason_code=normalized,
reason=comment_text, reason=comment_text,
) )
# 同一个 Document 的处理中后继是幂等赢家;其他 PDF 的重识别不应互相影响。 # 同一个 Document 的处理中后继是幂等赢家;失败后继只增加重试序号,不能被永久复用。
successors = ShippingOrderExtractionRun.query.filter_by(reparse_of_run_id=int(source.id)).order_by( successors = ShippingOrderExtractionRun.query.filter_by(reparse_of_run_id=int(source.id)).order_by(
ShippingOrderExtractionRun.created_at.desc(), ShippingOrderExtractionRun.created_at.desc(),
).all() ).all()
failed_attempt_count = 0
for successor in successors: for successor in successors:
marker = (successor.input_snapshot_json or {}).get('review_reparse') marker = (successor.input_snapshot_json or {}).get('review_reparse')
if isinstance(marker, dict) and int(marker.get('document_id') or 0) == int(case.document_id): if isinstance(marker, dict) and int(marker.get('document_id') or 0) == int(case.document_id):
@@ -636,6 +637,8 @@ def reparse_case_document(*, user_id: int, case_no: str, reason: str, comment: s
) )
db.session.flush() db.session.flush()
return successor, True return successor, True
if successor.status == 'failed':
failed_attempt_count += 1
if case.status == 'reparse_pending': if case.status == 'reparse_pending':
_reject_case_operation( _reject_case_operation(
case, case,
@@ -682,6 +685,7 @@ def reparse_case_document(*, user_id: int, case_no: str, reason: str, comment: s
user=user, agent_id=int(owner_agent.id), conversation_id=str(source.conversation_id), intake_nos=[intake_no], user=user, agent_id=int(owner_agent.id), conversation_id=str(source.conversation_id), intake_nos=[intake_no],
upload_batch_id=(source.input_snapshot_json or {}).get('upload_batch_id'), reparse_of_run=source, upload_batch_id=(source.input_snapshot_json or {}).get('upload_batch_id'), reparse_of_run=source,
reparse_reason=normalized, reparse_comment=comment, selected_document_id=int(case.document_id), reparse_case_no=case.case_no, reparse_reason=normalized, reparse_comment=comment, selected_document_id=int(case.document_id), reparse_case_no=case.case_no,
reparse_attempt_no=failed_attempt_count,
) )
if reused: if reused:
_audit_idempotent_reparse_reuse( _audit_idempotent_reparse_reuse(
@@ -1,25 +1,31 @@
""" """
services/shipping_notice/order_review_draft_service.py services/shipping_notice/order_review_draft_service.py
用途:建单前订单复核草稿的编辑、校验与统一审计。 用途:建单前订单复核草稿的编辑、校验与统一审计;含库存源路由重算、采用建议与保留人工决定。
依赖:Review Case/Draft、Run 冻结 Schema、订单字段规则、order_build_eligibility_service、 依赖:Review Case/Draft、Run 冻结 Schema、订单字段规则、order_build_eligibility_service、
fulfillment_audit、order_review_progress_bridge、 candidate_qualification_service.resolve_review_case_customer_resolved、
fulfillment_audit、order_review_progress_bridge、process_gate_bridge、
workflow_ledger_service.assert_case_is_current_workflow_version。 workflow_ledger_service.assert_case_is_current_workflow_version。
逻辑:只修改独立 Draft JSON;每次写入锁定 Case/Draft、校验草稿版本与 WorkflowItem 可写状态, 逻辑:只修改独立 Draft JSON;每次写入锁定 Case/Draft、校验草稿版本与 WorkflowItem 可写状态,
追加 CaseEvent + ShippingAuditEvent,并镜像 review_field_changed 到订单抽取进度流; 追加 CaseEvent + ShippingAuditEvent,并镜像 review_field_changed 到订单抽取进度流;
Item 已关闭/重识别中的冲突经 `_reject_draft_operation` 落 rejected 审计; Item 已关闭/重识别中的冲突经 `_reject_draft_operation` 落 rejected 审计;
整单校验汇总有效 Reservation、行级库存源候选与自动建单五门禁 整单校验汇总客户确认、有效 Reservation、行级库存源候选与自动建单资格;
(五门失败仅 can_auto_create=False,不阻断人工确认 can_build)。 库存路由恢复使用最新已发布规则与库存源启停,不重新识别 PDF,不静默覆盖人工决定;
路由恢复幂等键写入 Draft 历史集合(非仅最近一次),旧键重试可安全重放;
显式校验后同步客户/Reservation/重复订单/库存路由 Gate(findings.details)。
""" """
from __future__ import annotations from __future__ import annotations
import copy import copy
import logging
import uuid import uuid
from datetime import date from datetime import date
from decimal import Decimal from decimal import Decimal
from typing import Any, NoReturn from typing import Any, NoReturn
_LOGGER = logging.getLogger(__name__)
from app import db from app import db
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.models import ( from app.models import (
@@ -30,7 +36,11 @@ from app.models import (
) )
from app.services.shipping_notice.order_build_eligibility_service import ( from app.services.shipping_notice.order_build_eligibility_service import (
apply_manual_inventory_candidates, apply_manual_inventory_candidates,
apply_rule_suggestion_as_effective,
attach_rule_suggestion_without_override,
assess_order_build_eligibility, assess_order_build_eligibility,
mark_keep_manual_inventory_decision,
project_line_inventory_candidates,
) )
from app.services.shipping_notice.order_review_projection import serialize_review_case from app.services.shipping_notice.order_review_projection import serialize_review_case
from app.services.shipping_notice.order_schema.field_rules import ( from app.services.shipping_notice.order_schema.field_rules import (
@@ -372,7 +382,8 @@ def _validation(case: ShippingOrderReviewCase) -> dict[str, Any]:
""" """
全量校验草稿:动态 Schema、有效 Reservation 与行级库存源候选门禁同时生效,但不建单。 全量校验草稿:动态 Schema、有效 Reservation 与行级库存源候选门禁同时生效,但不建单。
核心逻辑:投影 field_code 值后调用资格服务;多候选不阻断;结果写入 核心逻辑:投影 field_code 值后调用资格服务;多候选不阻断;客户确认按真实
Bill-to / Candidate 状态评估(禁止硬编码已确认);结果写入
validation_result_json(含 line_projections)供工作台展示。 validation_result_json(含 line_projections)供工作台展示。
""" """
draft = case.current_draft draft = case.current_draft
@@ -411,6 +422,9 @@ def _validation(case: ShippingOrderReviewCase) -> dict[str, Any]:
from app import db from app import db
from app.models import ShippingNoticeCandidate, ShippingOrderExtractionRun, ShippingOrderExtractionUnit from app.models import ShippingNoticeCandidate, ShippingOrderExtractionRun, ShippingOrderExtractionUnit
from app.services.shipping_notice.candidate_qualification_service import (
resolve_review_case_customer_resolved,
)
candidate = db.session.get(ShippingNoticeCandidate, int(case.candidate_id)) if case.candidate_id else None candidate = db.session.get(ShippingNoticeCandidate, int(case.candidate_id)) if case.candidate_id else None
unit = case.unit unit = case.unit
@@ -419,12 +433,14 @@ def _validation(case: ShippingOrderReviewCase) -> dict[str, Any]:
run = case.run run = case.run
if run is None and case.run_id: if run is None and case.run_id:
run = db.session.get(ShippingOrderExtractionRun, int(case.run_id)) run = db.session.get(ShippingOrderExtractionRun, int(case.run_id))
# [STEP] 客户确认必须真实评估;未确认阻断 can_build / can_auto_create。
customer_resolved = resolve_review_case_customer_resolved(case=case, candidate=candidate)
eligibility = assess_order_build_eligibility( eligibility = assess_order_build_eligibility(
fields=fields, fields=fields,
header_by_code=header, header_by_code=header,
lines=lines, lines=lines,
line_metas=line_metas, line_metas=line_metas,
customer_resolved=True, customer_resolved=customer_resolved,
candidate=candidate, candidate=candidate,
unit=unit, unit=unit,
run=run, run=run,
@@ -580,8 +596,59 @@ def _record_change(
if line_key is not None: if line_key is not None:
before_snapshot['line_key'] = str(line_key)[:64] before_snapshot['line_key'] = str(line_key)[:64]
after_snapshot['line_key'] = str(line_key)[:64] after_snapshot['line_key'] = str(line_key)[:64]
# [STEP] 库存路由恢复:把候选与规则版本写入前后快照,供审计中心展示。
if str(event_type or '').startswith('inventory_routing_'):
before_raw = operation.get('previous_value')
after_raw = operation.get('new_value')
before_row = before_raw[0] if isinstance(before_raw, list) and before_raw else before_raw
after_row = after_raw[0] if isinstance(after_raw, list) and after_raw else after_raw
if isinstance(before_row, dict):
before_snapshot['selection_mode'] = str(before_row.get('selection_mode') or '')[:32] or None
before_snapshot['routing_status'] = str(before_row.get('routing_status') or '')[:32] or None
before_snapshot['candidate_inventory_source_codes'] = list(
before_row.get('candidate_inventory_source_codes') or []
)[:32]
before_snapshot['raw_rule_source_codes'] = list(before_row.get('raw_rule_source_codes') or [])[:32]
before_snapshot['unavailable_source_codes'] = list(
before_row.get('unavailable_source_codes') or []
)[:32]
before_snapshot['rule_versions'] = list(before_row.get('rule_versions') or [])[:40]
before_snapshot['suggestion_pending'] = bool(before_row.get('suggestion_pending'))
if isinstance(after_row, dict):
after_snapshot['selection_mode'] = str(after_row.get('selection_mode') or '')[:32] or None
after_snapshot['routing_status'] = str(after_row.get('routing_status') or '')[:32] or None
after_snapshot['candidate_inventory_source_codes'] = list(
after_row.get('candidate_inventory_source_codes') or []
)[:32]
after_snapshot['raw_rule_source_codes'] = list(after_row.get('raw_rule_source_codes') or [])[:32]
after_snapshot['rule_suggestion_source_codes'] = list(
after_row.get('rule_suggestion_source_codes') or []
)[:32]
after_snapshot['unavailable_source_codes'] = list(
after_row.get('unavailable_source_codes') or []
)[:32]
after_snapshot['rule_versions'] = list(after_row.get('rule_versions') or [])[:40]
after_snapshot['suggestion_pending'] = bool(after_row.get('suggestion_pending'))
if operation.get('candidate_inventory_source_codes') is not None:
after_snapshot['candidate_inventory_source_codes'] = list(
operation.get('candidate_inventory_source_codes') or []
)[:32]
if operation.get('rule_versions') is not None:
after_snapshot['rule_versions'] = list(operation.get('rule_versions') or [])[:40]
if operation.get('action_semantics'):
after_snapshot['action_semantics'] = str(operation.get('action_semantics'))[:64]
if operation.get('idempotency_key'):
after_snapshot['idempotency_key'] = str(operation.get('idempotency_key'))[:128]
if operation.get('line_keys') is not None:
after_snapshot['line_keys'] = [str(item)[:64] for item in list(operation.get('line_keys') or [])[:50]]
# 恢复机器值使用独立事件类型,便于坐标/字段证据反查(阶段 5)。
audit_event_type = (
'review_field_restored_machine'
if value_source == 'machine_restored'
else 'review_draft_changed'
)
record_fulfillment_audit( record_fulfillment_audit(
event_type='review_draft_changed', event_type=audit_event_type,
aggregate_type='order_review_case', aggregate_type='order_review_case',
aggregate_id=str(case.case_no), aggregate_id=str(case.case_no),
action=event_type, action=event_type,
@@ -594,7 +661,7 @@ def _record_change(
workflow_item_id=_workflow_item_no_for_case(case), workflow_item_id=_workflow_item_no_for_case(case),
before=before_snapshot, before=before_snapshot,
after=after_snapshot, after=after_snapshot,
metadata={'case_event_type': event_type}, metadata={'case_event_type': event_type, 'audit_event_type': audit_event_type},
source='order_review', source='order_review',
) )
# [STEP] 字段变更同步进入订单抽取进度流(工作区时间线)。 # [STEP] 字段变更同步进入订单抽取进度流(工作区时间线)。
@@ -602,13 +669,21 @@ def _record_change(
record_review_progress_event( record_review_progress_event(
case=case, case=case,
audit_event_type='review_draft_changed', audit_event_type=audit_event_type,
summary={ summary={
'field_id': str(field_id)[:64] if field_id is not None else None, 'field_id': str(field_id)[:64] if field_id is not None else None,
'draft_version': int(draft.draft_version), 'draft_version': int(draft.draft_version),
'case_event_type': event_type, 'case_event_type': event_type,
}, },
) )
# [STEP] 显式校验时同步建单前门禁,使 Gate 卡片与 Draft issues 同源。
if validate:
_sync_review_gates_safe(
case=case,
user_id=int(actor_id),
validation=result,
details={'case_event_type': event_type},
)
db.session.flush() db.session.flush()
return serialize_review_case(case) return serialize_review_case(case)
@@ -892,6 +967,558 @@ def set_line_inventory_candidates(
) )
# 路由恢复幂等历史上限;超限按插入顺序淘汰最旧条目。
_ROUTING_IDEMPOTENCY_HISTORY_LIMIT = 64
_ROUTING_IDEMPOTENCY_STORE_KEY = 'inventory_routing_recovery_idempotency'
_ROUTING_IDEMPOTENCY_LEGACY_KEY = 'inventory_routing_recovery'
def _normalize_routing_idempotency_key(raw: Any) -> str:
"""规范化库存路由恢复幂等键;空值返回空串。"""
return str(raw or '').strip()[:128]
def _routing_idempotency_entry_key(*, action: str, idempotency_key: str) -> str:
"""
生成幂等历史条目键(动作 + 幂等键)。
Args:
action: 路由恢复动作(可含 line_key 后缀)。
idempotency_key: 已规范化的幂等键。
Returns:
稳定字符串键,用于在 Draft JSON 中索引。
"""
return f'{str(action or "").strip()}:{idempotency_key}'[:192]
def _routing_recovery_idempotency_entries(reason: dict[str, Any]) -> dict[str, dict[str, Any]]:
"""
读取路由恢复幂等历史;兼容旧版单对象字段。
核心逻辑:优先读 inventory_routing_recovery_idempotency.by_key;
若仅有遗留 inventory_routing_recovery 单对象,则映射为单条历史。
"""
store = reason.get(_ROUTING_IDEMPOTENCY_STORE_KEY)
if isinstance(store, dict) and isinstance(store.get('by_key'), dict):
result: dict[str, dict[str, Any]] = {}
for raw_key, raw_entry in store['by_key'].items():
if isinstance(raw_entry, dict):
result[str(raw_key)[:192]] = dict(raw_entry)
return result
legacy = reason.get(_ROUTING_IDEMPOTENCY_LEGACY_KEY)
if isinstance(legacy, dict):
legacy_key = _normalize_routing_idempotency_key(legacy.get('idempotency_key'))
legacy_action = str(legacy.get('action') or '').strip()
if legacy_key and legacy_action:
entry_key = _routing_idempotency_entry_key(action=legacy_action, idempotency_key=legacy_key)
return {entry_key: dict(legacy)}
return {}
def _routing_recovery_replay(
case: ShippingOrderReviewCase,
*,
action: str,
idempotency_key: str,
) -> dict[str, Any] | None:
"""
若相同幂等键已成功执行过同一路由恢复动作,返回当前 Case 投影(幂等重放)。
核心逻辑:在 Draft change_reason_json 的幂等历史集合中查找 action+key;
命中即重放,即使后续其它操作已覆盖“最近一次”记录。
"""
key = _normalize_routing_idempotency_key(idempotency_key)
if not key:
return None
draft = case.current_draft
reason = draft.change_reason_json if isinstance(draft.change_reason_json, dict) else {}
entries = _routing_recovery_idempotency_entries(reason if isinstance(reason, dict) else {})
entry_key = _routing_idempotency_entry_key(action=action, idempotency_key=key)
hit = entries.get(entry_key)
if isinstance(hit, dict) and str(hit.get('idempotency_key') or '') == key:
return serialize_review_case(case)
return None
def _store_routing_recovery_idempotency(
case: ShippingOrderReviewCase,
*,
action: str,
idempotency_key: str,
line_keys: list[str],
) -> None:
"""
将成功的路由恢复幂等键追加写入 Draft 历史集合(非整对象覆盖)。
核心逻辑:写入 inventory_routing_recovery_idempotency.by_key;超限淘汰最旧;
同步写遗留 inventory_routing_recovery 指向最近一次,便于旧读路径兼容。
"""
key = _normalize_routing_idempotency_key(idempotency_key)
if not key:
return
draft = case.current_draft
reason = dict(draft.change_reason_json or {}) if isinstance(draft.change_reason_json, dict) else {}
entries = _routing_recovery_idempotency_entries(reason)
entry_key = _routing_idempotency_entry_key(action=action, idempotency_key=key)
record = {
'idempotency_key': key,
'action': action,
'line_keys': [str(item)[:64] for item in line_keys[:50]],
'draft_version_after': int(draft.draft_version) + 1,
}
entries[entry_key] = record
# [STEP] 超限时按插入顺序淘汰最旧条目,避免 change_reason_json 无限膨胀。
if len(entries) > _ROUTING_IDEMPOTENCY_HISTORY_LIMIT:
overflow = len(entries) - _ROUTING_IDEMPOTENCY_HISTORY_LIMIT
for stale_key in list(entries.keys())[:overflow]:
entries.pop(stale_key, None)
reason[_ROUTING_IDEMPOTENCY_STORE_KEY] = {'by_key': entries}
reason[_ROUTING_IDEMPOTENCY_LEGACY_KEY] = record
draft.change_reason_json = reason
def _line_routing_snapshot(line: dict[str, Any], fields: dict[str, dict[str, Any]], header_by_code: dict[str, Any]) -> dict[str, Any]:
"""
为审计生成单行路由前后快照(仅编码与规则版本,不含大对象)。
"""
line_by_code = {
str(field.get('field_code') or field_id): _current_value(line, field_id)
for field_id, field in fields.items()
if str(field.get('scope') or '') == 'line'
}
projection = project_line_inventory_candidates(
fields=fields,
header_by_code=header_by_code,
line_by_code=line_by_code,
line_meta=line,
)
return {
'line_key': str(line.get('line_key') or '')[:64],
'selection_mode': projection.get('selection_mode'),
'candidate_inventory_source_codes': list(projection.get('candidate_inventory_source_codes') or []),
'raw_rule_source_codes': list(projection.get('raw_rule_source_codes') or []),
'rule_suggestion_source_codes': list(projection.get('rule_suggestion_source_codes') or []),
'unavailable_source_codes': list(projection.get('unavailable_source_codes') or []),
'rule_versions': list(projection.get('rule_versions') or []),
'suggestion_pending': bool(projection.get('suggestion_pending')),
'routing_status': projection.get('routing_status'),
'block_reason': projection.get('block_reason'),
}
def _header_by_code_for_case(case: ShippingOrderReviewCase, fields: dict[str, dict[str, Any]]) -> dict[str, Any]:
"""从 Draft 投影 Header field_code→值。"""
header_container = dict(case.current_draft.header_values_json or {})
return {
str(field.get('field_code') or field_id): _current_value(header_container, field_id)
for field_id, field in fields.items()
if str(field.get('scope') or '') == 'header'
}
def reroute_inventory_routing(
*,
user_id: int,
case_no: str,
expected_draft_version: Any,
idempotency_key: str | None = None,
line_key: str | None = None,
) -> dict[str, Any]:
"""
按最新已发布规则与库存源启停重算库存路由;不重新识别 PDF。
核心逻辑:有人工决定时只写入规则建议与 suggestion_pending,不静默覆盖;
无人工决定时清除覆盖层并由校验投影最新有效候选;同一幂等键只产生一次有效副作用。
Args:
user_id: 操作人。
case_no: 复核 Case 编号。
expected_draft_version: 乐观锁版本。
idempotency_key: 可选幂等键。
line_key: 可选,仅重算指定行;缺省整单。
Returns:
序列化后的 Case 详情。
"""
action = 'inventory_routing_rerouted'
case = _locked_case(user_id=user_id, case_no=case_no, action=action)
replay = _routing_recovery_replay(case, action=action, idempotency_key=str(idempotency_key or ''))
if replay is not None:
return replay
_assert_version(case, expected_draft_version, actor_id=user_id, action=action)
fields = _schema_fields(case)
header_by_code = _header_by_code_for_case(case, fields)
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
target_key = str(line_key or '').strip()
before_rows: list[dict[str, Any]] = []
after_rows: list[dict[str, Any]] = []
touched_keys: list[str] = []
for raw in lines:
if not isinstance(raw, dict):
continue
current_key = str(raw.get('line_key') or '').strip()
if target_key and current_key != target_key:
continue
if not current_key:
continue
before_rows.append(_line_routing_snapshot(raw, fields, header_by_code))
suggestion_projection = project_line_inventory_candidates(
fields=fields,
header_by_code=header_by_code,
line_by_code={
str(field.get('field_code') or field_id): _current_value(raw, field_id)
for field_id, field in fields.items()
if str(field.get('scope') or '') == 'line'
},
line_meta={**raw, 'inventory_routing': {}},
)
attach_rule_suggestion_without_override(
line_meta=raw,
suggestion=dict(suggestion_projection.get('rule_suggestion') or {}),
)
after_rows.append(_line_routing_snapshot(raw, fields, header_by_code))
touched_keys.append(current_key)
if target_key and not touched_keys:
_reject_draft_operation(
case,
actor_id=user_id,
action=action,
error=NotFoundError('Order review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND'),
metadata={'line_key': target_key[:64]},
)
case.current_draft.lines_json = lines
_store_routing_recovery_idempotency(
case,
action=action,
idempotency_key=str(idempotency_key or ''),
line_keys=touched_keys,
)
return _record_change(
case,
actor_id=user_id,
event_type=action,
operation={
'line_key': target_key or None,
'line_keys': touched_keys,
'idempotency_key': _normalize_routing_idempotency_key(idempotency_key) or None,
'previous_value': before_rows[:20],
'new_value': after_rows[:20],
'rule_versions': [
item for row in after_rows for item in (row.get('rule_versions') or [])
][:40],
},
validate=True,
)
def _blocking_issues_for_gate(
validation: dict[str, Any],
gate_code: str,
) -> list[dict[str, Any]]:
"""
从校验结果中筛选归属指定门禁的阻断 issue。
Args:
validation: assess_order_build_eligibility 结果。
gate_code: owning_gate_code。
Returns:
阻断 issue 列表。
"""
return [
item for item in (validation.get('issues') or [])
if isinstance(item, dict)
and str(item.get('owning_gate_code') or '') == gate_code
and str(item.get('severity') or '') == 'blocking'
]
def _sync_review_gates_safe(
*,
case: ShippingOrderReviewCase,
user_id: int,
validation: dict[str, Any] | None = None,
details: dict[str, Any] | None = None,
) -> None:
"""
将客户/Reservation/重复订单/库存路由校验结果同步到统一 Gate。
核心逻辑:按 owning_gate 折叠阻断;原因码经 canonicalize;库存门禁附带
unavailable_reasons 等业务事实。失败向上抛出,与 Draft 同事务回滚。
Args:
case: 复核 Case。
user_id: 操作人。
validation: 已算好的校验结果;缺省时现场重算。
details: 附加到 Finding.details 的上下文。
"""
from app.services.shipping_notice.error_explainability_contract import canonicalize_reason_code
from app.services.shipping_notice.process_gate_bridge import (
sync_inventory_routing_gate_for_case,
sync_review_gate_for_case,
)
result = validation if isinstance(validation, dict) else _validation(case)
base_details = dict(details or {})
for gate_code, default_reason in (
('customer_resolution', 'customer_unresolved'),
('reservation_validation', 'reservation_missing'),
('duplicate_detection', 'duplicate_unresolved'),
):
issues = _blocking_issues_for_gate(result, gate_code)
if not issues:
sync_review_gate_for_case(
case=case,
gate_code=gate_code,
passed=True,
actor_id=int(user_id),
details=base_details,
)
continue
primary = issues[0]
reason = canonicalize_reason_code(
str(primary.get('reason_code') or primary.get('code') or default_reason)
) or default_reason
sync_details = {
**base_details,
'line_key': primary.get('line_key'),
'line_index': primary.get('line_index'),
'field_code': primary.get('field_code'),
'issue_codes': [
canonicalize_reason_code(str(item.get('code') or ''))
for item in issues
if canonicalize_reason_code(str(item.get('code') or ''))
],
}
sync_review_gate_for_case(
case=case,
gate_code=gate_code,
passed=False,
actor_id=int(user_id),
blocking_reason_code=reason,
default_reason_code=default_reason,
details=sync_details,
)
inventory_issues = _blocking_issues_for_gate(result, 'inventory_source_routing')
if not inventory_issues:
sync_inventory_routing_gate_for_case(
case=case,
passed=True,
actor_id=int(user_id),
details=base_details,
)
return
primary = inventory_issues[0]
unavailable_reasons: dict[str, str] = {}
unavailable_codes: list[str] = []
raw_codes: list[str] = []
matched_rule_codes: list[str] = []
for issue in inventory_issues:
reasons = issue.get('unavailable_reasons') if isinstance(issue.get('unavailable_reasons'), dict) else {}
unavailable_reasons.update({str(k): str(v) for k, v in reasons.items()})
unavailable_codes.extend(str(c) for c in (issue.get('unavailable_source_codes') or []) if c)
raw_codes.extend(str(c) for c in (issue.get('raw_rule_source_codes') or []) if c)
for line in result.get('line_projections') or []:
if not isinstance(line, dict):
continue
for rule in line.get('matched_rules') or []:
if not isinstance(rule, dict):
continue
rule_code = str(rule.get('rule_code') or '').strip()
if rule_code:
matched_rule_codes.append(rule_code)
sync_inventory_routing_gate_for_case(
case=case,
passed=False,
blocking_reason_code=canonicalize_reason_code(
str(primary.get('code') or 'no_inventory_source_candidates')
) or 'no_inventory_source_candidates',
actor_id=int(user_id),
details={
**base_details,
'unavailable_reasons': unavailable_reasons,
'unavailable_source_codes': list(dict.fromkeys(unavailable_codes)),
'raw_rule_source_codes': list(dict.fromkeys(raw_codes)),
'matched_rule_codes': list(dict.fromkeys(matched_rule_codes)),
'line_key': primary.get('line_key'),
'line_index': primary.get('line_index'),
'candidate_inventory_source_codes': list(primary.get('candidate_inventory_source_codes') or []),
},
)
def adopt_inventory_routing_suggestion(
*,
user_id: int,
case_no: str,
line_key: str,
expected_draft_version: Any,
idempotency_key: str | None = None,
reason: str | None = None,
) -> dict[str, Any]:
"""
采用当前规则建议为有效库存源候选(明确动作)。
Args:
user_id / case_no / line_key: 定位目标。
expected_draft_version: 乐观锁。
idempotency_key: 可选幂等键。
reason: 采用说明;缺省写入动作语义 adopt_rule_suggestion。
Returns:
序列化 Case。
"""
action = 'inventory_routing_suggestion_adopted'
case = _locked_case(user_id=user_id, case_no=case_no, action=action)
replay = _routing_recovery_replay(case, action=f'{action}:{line_key}', idempotency_key=str(idempotency_key or ''))
if replay is not None:
return replay
_assert_version(case, expected_draft_version, actor_id=user_id, action=action)
fields = _schema_fields(case)
header_by_code = _header_by_code_for_case(case, fields)
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
target = _find_line(case, lines, line_key, actor_id=user_id, action=action)
before = _line_routing_snapshot(target, fields, header_by_code)
# 实时重算建议,避免采用陈旧 overlay。
live = project_line_inventory_candidates(
fields=fields,
header_by_code=header_by_code,
line_by_code={
str(field.get('field_code') or field_id): _current_value(target, field_id)
for field_id, field in fields.items()
if str(field.get('scope') or '') == 'line'
},
line_meta=target,
)
suggestion = dict(live.get('rule_suggestion') or {})
try:
overlay = apply_rule_suggestion_as_effective(
line_meta=target,
suggestion=suggestion,
reason=str(reason or 'adopt_rule_suggestion'),
)
except ValueError as exc:
_reject_draft_operation(
case,
actor_id=user_id,
action=action,
error=ValidationError(
'Rule inventory suggestion cannot be adopted',
code='SHIPPING.REVIEW_INVENTORY_ROUTING_ADOPT_INVALID',
details={'reason': str(exc)},
),
metadata={'line_key': str(line_key)[:64], 'reason': str(exc)},
)
case.current_draft.lines_json = lines
after = _line_routing_snapshot(target, fields, header_by_code)
_store_routing_recovery_idempotency(
case,
action=f'{action}:{line_key}',
idempotency_key=str(idempotency_key or ''),
line_keys=[str(line_key)],
)
return _record_change(
case,
actor_id=user_id,
event_type=action,
operation={
'line_key': line_key,
'idempotency_key': _normalize_routing_idempotency_key(idempotency_key) or None,
'previous_value': before,
'new_value': after,
'candidate_inventory_source_codes': list(overlay.get('candidate_inventory_source_codes') or []),
'rule_versions': list(after.get('rule_versions') or []),
'action_semantics': 'adopt_rule_suggestion',
},
validate=True,
)
def keep_manual_inventory_routing(
*,
user_id: int,
case_no: str,
line_key: str,
expected_draft_version: Any,
idempotency_key: str | None = None,
reason: str | None = None,
) -> dict[str, Any]:
"""
明确保留人工库存源决定,拒绝当前规则建议。
Args:
user_id / case_no / line_key: 定位目标。
expected_draft_version: 乐观锁。
idempotency_key: 可选幂等键。
reason: 保留说明。
Returns:
序列化 Case。
"""
action = 'inventory_routing_manual_kept'
case = _locked_case(user_id=user_id, case_no=case_no, action=action)
replay = _routing_recovery_replay(case, action=f'{action}:{line_key}', idempotency_key=str(idempotency_key or ''))
if replay is not None:
return replay
_assert_version(case, expected_draft_version, actor_id=user_id, action=action)
fields = _schema_fields(case)
header_by_code = _header_by_code_for_case(case, fields)
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
target = _find_line(case, lines, line_key, actor_id=user_id, action=action)
before = _line_routing_snapshot(target, fields, header_by_code)
try:
overlay = mark_keep_manual_inventory_decision(
line_meta=target,
reason=str(reason or 'keep_manual_inventory_decision'),
)
except ValueError as exc:
_reject_draft_operation(
case,
actor_id=user_id,
action=action,
error=ValidationError(
'Manual inventory decision cannot be kept',
code='SHIPPING.REVIEW_INVENTORY_ROUTING_KEEP_INVALID',
details={'reason': str(exc)},
),
metadata={'line_key': str(line_key)[:64], 'reason': str(exc)},
)
case.current_draft.lines_json = lines
after = _line_routing_snapshot(target, fields, header_by_code)
_store_routing_recovery_idempotency(
case,
action=f'{action}:{line_key}',
idempotency_key=str(idempotency_key or ''),
line_keys=[str(line_key)],
)
return _record_change(
case,
actor_id=user_id,
event_type=action,
operation={
'line_key': line_key,
'idempotency_key': _normalize_routing_idempotency_key(idempotency_key) or None,
'previous_value': before,
'new_value': after,
'candidate_inventory_source_codes': list(overlay.get('candidate_inventory_source_codes') or []),
'action_semantics': 'keep_manual_inventory_decision',
},
validate=True,
)
def _set_llm_suggested_value( def _set_llm_suggested_value(
container: dict[str, Any], container: dict[str, Any],
field: dict[str, Any], field: dict[str, Any],
@@ -0,0 +1,185 @@
"""
services/shipping_notice/order_review_duplicate_service.py
用途:建单前复核工作台的重复订单投影与人工裁决。
依赖:ShippingOrderReviewCase / ShippingNoticeCandidate、candidate_service 重复裁决、
candidate_qualification_service、order_review_draft_service.validate_draft、
document_candidate_persist._serialize_candidate_brief。
逻辑:由 workspace order-review-cases duplicate-* 路由调用;裁决委托 resolve_candidate_duplicate,
再刷新建单资格与 Draft 校验;不创建 Task、不重解析 PDF。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError
from app.models import ShippingNoticeCandidate, ShippingOrderReviewCase
from app.services.shipping_notice.candidate_qualification_service import (
recalculate_candidate_qualification,
resolve_review_case_customer_resolved,
)
from app.services.shipping_notice.candidate_service import (
refresh_candidate_duplicate,
resolve_candidate_duplicate,
)
from app.services.shipping_notice.order_review_draft_service import (
soft_load_review_case_for_audit,
validate_draft,
)
from app.services.shipping_notice.workflow_ledger_service import (
assert_case_is_current_workflow_version,
)
def _candidate_for_case(case: ShippingOrderReviewCase) -> ShippingNoticeCandidate | None:
if not case.candidate_id:
return None
return db.session.get(ShippingNoticeCandidate, int(case.candidate_id))
def _load_writable_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase:
"""加载属主可写 Case,并校验 Workflow 当前版本。"""
case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no or ''))
if case is None:
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
if str(case.status or '') in {'confirmed', 'non_order', 'superseded', 'reparse_pending'}:
raise ConflictError(
'Review case is not editable',
code='SHIPPING.REVIEW_CASE_NOT_EDITABLE',
details={'status': case.status},
)
assert_case_is_current_workflow_version(case=case)
return case
def project_review_case_duplicate(case: ShippingOrderReviewCase) -> dict[str, Any]:
"""
投影建单前重复检测状态,供复核工作台集中裁决。
Returns:
含 status/blocking/matches/allowed_actions/resolution/resolved/candidate_no。
"""
from app.services.shipping_notice.document_candidate_persist import _serialize_candidate_brief
candidate = _candidate_for_case(case)
if candidate is None:
return {
'candidate_no': None,
'status': 'unchecked',
'blocking': False,
'fingerprint_strength': 'unavailable',
'matches': [],
'allowed_actions': [],
'resolution': None,
'resolved': False,
'needs_adjudication': False,
}
brief = _serialize_candidate_brief(candidate)
duplicate = brief.get('duplicate') if isinstance(brief.get('duplicate'), dict) else {}
resolution = brief.get('duplicate_resolution') if isinstance(brief.get('duplicate_resolution'), dict) else None
status = str(duplicate.get('status') or candidate.duplicate_status or 'unchecked')
blocking = bool(duplicate.get('blocking'))
resolved = bool(resolution and resolution.get('action'))
# 无阻断时视为无需裁决;阻断且未决议才需要面板操作。
needs_adjudication = blocking and not resolved
return {
'candidate_no': str(candidate.candidate_no or '') or None,
'status': status,
'blocking': blocking,
'fingerprint_strength': str(duplicate.get('fingerprint_strength') or 'unavailable'),
'matches': list(duplicate.get('matches') or []),
'allowed_actions': list(duplicate.get('allowed_actions') or []),
'resolution': resolution,
'resolved': resolved,
'needs_adjudication': needs_adjudication,
}
def _reload_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase:
case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no))
if case is None:
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
return case
def _refresh_case_after_duplicate(*, user_id: int, case_no: str) -> dict[str, Any]:
"""裁决/刷新后重算资格、校验 Draft,并返回最新 Case + duplicate 投影。"""
from app.services.shipping_notice.order_review_projection import serialize_review_case
case = _reload_case(user_id=user_id, case_no=case_no)
candidate = _candidate_for_case(case)
if candidate is not None:
customer_resolved = resolve_review_case_customer_resolved(case=case, candidate=candidate)
recalculate_candidate_qualification(
candidate=candidate,
run=case.run,
customer_resolved=customer_resolved,
persist=True,
)
if case.current_draft is not None:
validate_draft(
user_id=int(user_id),
case_no=str(case.case_no),
expected_draft_version=int(case.current_draft.draft_version),
)
db.session.commit()
case = _reload_case(user_id=user_id, case_no=case_no)
return {
'case': serialize_review_case(case),
'duplicate': project_review_case_duplicate(case),
}
def resolve_review_case_duplicate(
*,
user_id: int,
case_no: str,
action: str,
target_task_no: str | None = None,
reason: str | None = None,
) -> dict[str, Any]:
"""
裁决建单前重复订单:委托 Candidate 裁决 API,再刷新建单资格。
Args:
action: open_existing | create_revision | force_create
target_task_no: 匹配任务号;缺省取首个 match
reason: force_create 必填
Returns:
{'case': Case 投影, 'duplicate': 最新重复投影}
"""
case = _load_writable_case(user_id=user_id, case_no=case_no)
candidate = _candidate_for_case(case)
if candidate is None or not candidate.candidate_no:
raise ConflictError(
'Review case has no candidate for duplicate resolution',
code='SHIPPING.REVIEW_DUPLICATE_CANDIDATE_MISSING',
)
resolve_candidate_duplicate(
user_id=int(user_id),
candidate_no=str(candidate.candidate_no),
action=str(action or '').strip(),
target_task_no=target_task_no,
reason=reason,
)
return _refresh_case_after_duplicate(user_id=user_id, case_no=case_no)
def refresh_review_case_duplicate(*, user_id: int, case_no: str) -> dict[str, Any]:
"""
重新检测重复(清除陈旧决议),并刷新建单资格。
【AI 触发时机】:用户在复核工作台点击「重新检测重复」时调用。
"""
case = _load_writable_case(user_id=user_id, case_no=case_no)
candidate = _candidate_for_case(case)
if candidate is None or not candidate.candidate_no:
raise ConflictError(
'Review case has no candidate for duplicate refresh',
code='SHIPPING.REVIEW_DUPLICATE_CANDIDATE_MISSING',
)
refresh_candidate_duplicate(user_id=int(user_id), candidate_no=str(candidate.candidate_no))
return _refresh_case_after_duplicate(user_id=user_id, case_no=case_no)
@@ -1,9 +1,13 @@
""" """
建单前订单复核的证据与受控 PDF 预览服务。 建单前订单复核的证据与受控 PDF 预览服务。
依赖:Review Case、Document/FileAsset、冻结 Unit 机器结果和文件资产读取服务。 依赖:Review Case、Document/FileAsset、冻结 Unit 机器结果、field_highlight_contract、
文件资产读取服务。
逻辑:证据仅从当前 PDF Unit 的机器 Observation 裁剪而来;预览通过 Case owner 逻辑:证据仅从当前 PDF Unit 的机器 Observation 裁剪而来;预览通过 Case owner
鉴权后由应用代理二进制,绝不向客户端公开对象存储地址或内部键。 鉴权后由应用代理二进制,绝不向客户端公开对象存储地址或内部键。
字段高亮由 field_highlight_contract 投影;值匹配依赖 bbox_text/独立 quote,
坐标缺失不影响字段值与自动确认。根级非法 bbox 标 invalid 但不绘制;
禁止 value_bbox=None 时回退 observation 根级框。
""" """
from __future__ import annotations from __future__ import annotations
@@ -15,6 +19,7 @@ from app import db
from app.core.errors import ConflictError, NotFoundError from app.core.errors import ConflictError, NotFoundError
from app.models import FileAsset, ShippingNoticeDocument, ShippingOrderReviewCase from app.models import FileAsset, ShippingNoticeDocument, ShippingOrderReviewCase
from app.services.file_assets.service import read_asset_bytes from app.services.file_assets.service import read_asset_bytes
from app.services.shipping_notice.field_highlight_contract import build_field_highlight_projection
from app.services.shipping_notice.order_review_service import get_user_review_case from app.services.shipping_notice.order_review_service import get_user_review_case
_MAX_QUOTE_LENGTH = 500 _MAX_QUOTE_LENGTH = 500
@@ -26,6 +31,15 @@ def _safe_quote(value: Any) -> str | None:
return text[:_MAX_QUOTE_LENGTH] or None return text[:_MAX_QUOTE_LENGTH] or None
def _raw_bbox_dict(value: Any) -> dict[str, Any] | None:
"""识别上游是否提供了 bbox 结构(即便非法),供高亮契约区分 missing / invalid。"""
if not isinstance(value, dict):
return None
if not any(key in value for key in ('x0', 'y0', 'x1', 'y1')):
return None
return value
def _safe_bbox(value: Any) -> dict[str, float] | None: def _safe_bbox(value: Any) -> dict[str, float] | None:
"""仅接受完整、有限的归一化 bbox;缺失或不可信时返回空而不是伪造高亮。""" """仅接受完整、有限的归一化 bbox;缺失或不可信时返回空而不是伪造高亮。"""
if not isinstance(value, dict): if not isinstance(value, dict):
@@ -76,9 +90,15 @@ def _frozen_document_layout(case: ShippingOrderReviewCase) -> dict[str, Any]:
def _frozen_cell_coordinate( def _frozen_cell_coordinate(
case: ShippingOrderReviewCase, observation: dict[str, Any], case: ShippingOrderReviewCase, observation: dict[str, Any],
) -> tuple[int | None, dict[str, float] | None, str | None]: ) -> tuple[int | None, dict[str, float] | None, str | None]:
"""按冻结 table_id/cell_id 反查明细单元格 bbox,缺失时只返回空而不猜测。""" """
table_id = str(observation.get('table_id') or '').strip() 按冻结 table_id/cell_id 反查明细单元格 bbox,缺失时只返回空而不猜测。
cell_id = str(observation.get('cell_id') or '').strip()
核心逻辑:通用订单路径把身份放在 layout_evidence 内,必须同时读取嵌套字段,
禁止只认 observation 根级导致有 cell 证据却无法高亮。
"""
layout = observation.get('layout_evidence') if isinstance(observation.get('layout_evidence'), dict) else {}
table_id = str(observation.get('table_id') or layout.get('table_id') or '').strip()
cell_id = str(observation.get('cell_id') or layout.get('cell_id') or '').strip()
if not table_id or not cell_id: if not table_id or not cell_id:
return None, None, None return None, None, None
candidate = _frozen_document_layout(case).get('layout_candidate') candidate = _frozen_document_layout(case).get('layout_candidate')
@@ -117,10 +137,143 @@ def _frozen_cell_coordinate(
return None, None, None return None, None, None
def _normalized_evidence_text(value: Any) -> str:
"""折叠空白并统一大小写,供 PDF 冻结单元格唯一反查。"""
text = ' '.join(str(value or '').split()).strip().casefold()
try:
if text and all(char in '0123456789.-' for char in text) and '.' in text:
text = format(float(text), 'f').rstrip('0').rstrip('.')
except (TypeError, ValueError):
pass
return text
def _evidence_text_variants(value: Any) -> set[str]:
raw = _normalized_evidence_text(value)
variants = {raw} if raw else set()
match = re.fullmatch(r'(\d{4})-(\d{1,2})-(\d{1,2})', raw)
if match:
year, month, day = match.groups()
variants.update({f'{int(month)}/{int(day)}/{year}', f'{int(month):02d}/{int(day):02d}/{year}'})
return variants
def _frozen_value_coordinate(
case: ShippingOrderReviewCase, observation: dict[str, Any],
) -> tuple[int | None, dict[str, float] | None, str | None, str | None]:
"""按识别值在当前 PDF 冻结表格中唯一反查 cell bbox/text;重复值禁止猜测。"""
target = _normalized_evidence_text(observation.get('value'))
if not target:
return None, None, None, None
matches: list[tuple[int, dict[str, float], str]] = []
layout = _frozen_document_layout(case)
candidate = layout.get('layout_candidate') if isinstance(layout.get('layout_candidate'), dict) else {}
for page in candidate.get('pages') or []:
if not isinstance(page, dict):
continue
try:
page_no = int(page.get('page_no'))
width, height = float(page.get('width')), float(page.get('height'))
except (TypeError, ValueError):
continue
if page_no < 1 or width <= 0 or height <= 0:
continue
for table in page.get('tables') or []:
for row in table.get('rows') or []:
for cell in row.get('cells') or []:
if not isinstance(cell, dict) or not (_evidence_text_variants(cell.get('text')) & _evidence_text_variants(observation.get('value'))):
continue
bbox = cell.get('bbox') if isinstance(cell.get('bbox'), dict) else None
if not bbox:
continue
try:
normalized = _safe_bbox({
'x0': float(bbox['x0']) / width, 'y0': float(bbox['y0']) / height,
'x1': float(bbox['x1']) / width, 'y1': float(bbox['y1']) / height,
})
except (KeyError, TypeError, ValueError):
normalized = None
if normalized is not None:
matches.append((page_no, normalized, str(cell.get('text') or '')))
if len(matches) != 1:
# 表格 cell 未覆盖的值(例如数量/单位/日期)再按当前 PDF 页面字符序列唯一反查。
page_matches: list[tuple[int, dict[str, float], str]] = []
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
for page_key, glyphs in (evidence.get('page_glyphs') or {}).items():
if not isinstance(glyphs, list):
continue
try:
page_no = int(page_key)
except (TypeError, ValueError):
continue
# For line fields, constrain native-glyph matching to the extracted row.
target_line = observation.get('_line_index')
if target_line is not None:
suffix = f'vline-{int(target_line) + 21}'
row_glyphs = [g for g in glyphs if isinstance(g, dict) and str(g.get('line_id') or '').endswith(suffix)]
if row_glyphs:
glyphs = row_glyphs
row_y = observation.get('_row_y')
if row_y is not None:
glyphs = [g for g in glyphs if isinstance(g, dict) and isinstance(g.get('bbox'), dict)
and abs(((float(g['bbox'].get('y0', 0)) + float(g['bbox'].get('y1', 0))) / 2) - float(row_y)) <= 18]
for start in range(len(glyphs)):
text = ''
selected: list[dict[str, Any]] = []
for glyph in glyphs[start:start + max(len(target) * 2, 32)]:
if not isinstance(glyph, dict):
break
text += str(glyph.get('text') or '')
selected.append(glyph)
if _evidence_text_variants(text) & _evidence_text_variants(observation.get('value')):
boxes = [item.get('bbox') for item in selected if isinstance(item.get('bbox'), dict)]
if boxes:
try:
normalized = _safe_bbox({
'x0': min(float(b['x0']) for b in boxes) / float((evidence.get('pages') or {}).get(str(page_no), {}).get('width')),
'y0': min(float(b['y0']) for b in boxes) / float((evidence.get('pages') or {}).get(str(page_no), {}).get('height')),
'x1': max(float(b['x1']) for b in boxes) / float((evidence.get('pages') or {}).get(str(page_no), {}).get('width')),
'y1': max(float(b['y1']) for b in boxes) / float((evidence.get('pages') or {}).get(str(page_no), {}).get('height')),
})
except (TypeError, ValueError, KeyError):
normalized = None
if normalized is not None:
page_matches.append((page_no, normalized, text))
break
if len(_normalized_evidence_text(text)) > len(target) + 8:
break
if len(page_matches) == 1:
return (*page_matches[0], 'native_glyph')
return None, None, None, None
page_no, bbox, text = matches[0]
return page_no, bbox, 'frozen_layout_cell', text
def _layout_has_value_coordinate(layout_evidence: dict[str, Any]) -> bool | None:
"""
读取上游是否声明字段值级坐标。
Returns:
True/False 表示显式声明;None 表示旧数据未声明(可走冻结 cell 兼容路径)。
"""
if 'has_value_coordinate' in layout_evidence:
return bool(layout_evidence.get('has_value_coordinate'))
if 'value_bbox' in layout_evidence:
return isinstance(layout_evidence.get('value_bbox'), dict)
if 'normalized_bbox' in layout_evidence:
return isinstance(layout_evidence.get('normalized_bbox'), dict)
return None
def _layout_coordinate_evidence( def _layout_coordinate_evidence(
case: ShippingOrderReviewCase, observation: dict[str, Any], case: ShippingOrderReviewCase, observation: dict[str, Any],
) -> tuple[int | None, dict[str, float] | None, str | None]: ) -> tuple[int | None, dict[str, float] | None, str | None]:
"""将冻结的绝对坐标证据转为审阅器可绘制的归一化页内 bbox。""" """
将冻结的字段值级坐标转为审阅器可绘制的归一化页内 bbox。
核心逻辑:仅消费 layout_evidence.value_bbox / normalized_bbox;
value_bbox 显式为空时返回空框,禁止调用方再回退到 observation 根级 bbox。
"""
raw = observation.get('layout_evidence') if isinstance(observation.get('layout_evidence'), dict) else {} raw = observation.get('layout_evidence') if isinstance(observation.get('layout_evidence'), dict) else {}
try: try:
page_no = int(raw.get('page_no')) page_no = int(raw.get('page_no'))
@@ -129,9 +282,16 @@ def _layout_coordinate_evidence(
if page_no < 1: if page_no < 1:
return None, None, None return None, None, None
source = str(raw.get('source') or '')[:64] or None source = str(raw.get('source') or '')[:64] or None
dimensions = _frozen_page_dimensions(case, page_no) # [STEP] 优先已归一化的字段值框
layout_normalized = _safe_bbox(raw.get('normalized_bbox'))
if layout_normalized is not None:
return page_no, layout_normalized, source
value_bbox = raw.get('value_bbox') if isinstance(raw.get('value_bbox'), dict) else None value_bbox = raw.get('value_bbox') if isinstance(raw.get('value_bbox'), dict) else None
if dimensions is None or value_bbox is None: if value_bbox is None:
# 无绝对 value_bbox:直接返回,避免无意义的页尺寸查询与根级回退
return page_no, None, source
dimensions = _frozen_page_dimensions(case, page_no)
if dimensions is None:
return page_no, None, source return page_no, None, source
width, height = dimensions width, height = dimensions
try: try:
@@ -146,8 +306,101 @@ def _layout_coordinate_evidence(
return page_no, _safe_bbox(normalized), source return page_no, _safe_bbox(normalized), source
def _observation_raw_bbox_flags(
observation: dict[str, Any],
*,
resolved_bbox: dict[str, float] | None,
) -> tuple[bool, bool]:
"""
判断 observation 是否携带原始 bbox 结构,以及候选是否几何非法。
核心逻辑:
- 已有合法 resolved → 不标 invalid;
- layout_evidence 字段值级候选优先;
- observation 根级 bbox/normalized_bbox **不得用于绘制**,但若已提供且几何非法
(缺键/倒置/越界),须标 invalid,以便 UI 区分「无坐标」与「坐标非法」;
- 根级几何合法但未进入绘制链路 → 不记 present(保持 unavailable,避免伪字段级证据);
- 绝对 value_bbox 因缺页尺寸无法换算 → missing(unavailable),不伪造 invalid。
Returns:
(raw_bbox_present, raw_bbox_invalid)
"""
if resolved_bbox is not None:
return True, False
layout = observation.get('layout_evidence') if isinstance(observation.get('layout_evidence'), dict) else {}
# [STEP 1] 字段值级归一化候选
had_normalized = False
for item in (layout.get('normalized_bbox'),):
if _raw_bbox_dict(item) is None:
continue
had_normalized = True
if _safe_bbox(item) is None:
return True, True
absolute_present = _raw_bbox_dict(layout.get('value_bbox')) is not None
if had_normalized or absolute_present:
return True, False
# [STEP 2] 诊断专用:根级框只用于识别「提供了但非法」,永不据此绘制
for item in (observation.get('normalized_bbox'), observation.get('bbox')):
if _raw_bbox_dict(item) is None:
continue
if _safe_bbox(item) is None:
return True, True
return False, False
def _resolve_highlight_bbox(
case: ShippingOrderReviewCase,
observation: dict[str, Any],
*,
layout_evidence: dict[str, Any],
) -> tuple[int | None, dict[str, float] | None, str | None]:
"""
解析可绘制高亮 bbox;禁止无字段值级坐标时回退到 observation 根级或整格冒充。
核心逻辑:
1. 优先 layout value_bbox / normalized_bbox;
2. has_value_coordinate=False 时禁止任何回退;
3. 旧数据未声明时才允许冻结 cell 兼容路径;
4. 永不使用 observation.bbox / observation.normalized_bbox。
"""
coordinate_page, coordinate_bbox, coordinate_source = _layout_coordinate_evidence(case, observation)
page_no = observation.get('page_no')
try:
page = int(page_no) if page_no is not None else None
except (TypeError, ValueError):
page = None
if page is not None and page < 1:
page = None
resolved_page = coordinate_page or page
has_value = _layout_has_value_coordinate(layout_evidence)
if coordinate_bbox is not None:
return resolved_page, coordinate_bbox, coordinate_source
# [STEP] 上游已声明无字段值级坐标:只返回页码与来源,禁止 cell/根级回退
if has_value is False:
return resolved_page, None, coordinate_source or str(observation.get('source') or 'machine_extraction')[:64]
# [STEP] 旧 Observation 未声明时,允许冻结 cell 兼容(来源 frozen_layout_cell,最高 candidate)
cell_page, cell_bbox, cell_source = _frozen_cell_coordinate(case, observation)
if cell_bbox is not None:
return cell_page or resolved_page, cell_bbox, cell_source
# 明细可能来自邮件补充而缺少 table_id/cell_id;只在当前 PDF 冻结表格中唯一值命中时补定位。
value_page, value_bbox, value_source, value_text = _frozen_value_coordinate(case, observation)
if value_bbox is not None:
if isinstance(observation.get('layout_evidence'), dict):
observation['layout_evidence']['bbox_text'] = value_text
observation['layout_evidence']['quote_source'] = 'layout_cell_text'
observation['layout_evidence']['has_value_coordinate'] = True
return value_page, value_bbox, value_source
return resolved_page, None, coordinate_source or cell_source or str(observation.get('source') or 'machine_extraction')[:64]
def _observations(case: ShippingOrderReviewCase) -> list[dict[str, Any]]: def _observations(case: ShippingOrderReviewCase) -> list[dict[str, Any]]:
"""展开本 Case Unit 的机器字段 Observation;不会查询其他 Run 或 Document 的结果。""" """
展开本 Case Unit 的机器字段 Observation,并投影字段高亮契约字段。
核心逻辑:坐标从冻结 layout_evidence / cell 解析;质量状态由
build_field_highlight_projection 统一裁决;不查询其他 Run/Document,
不改写自动确认结果。
"""
result = case.unit.result_json if isinstance(case.unit.result_json, dict) else {} result = case.unit.result_json if isinstance(case.unit.result_json, dict) else {}
orders = [item for item in result.get('orders') or [] if isinstance(item, dict)] orders = [item for item in result.get('orders') or [] if isinstance(item, dict)]
if len(orders) != 1: if len(orders) != 1:
@@ -163,26 +416,66 @@ def _observations(case: ShippingOrderReviewCase) -> list[dict[str, Any]]:
for index, observation in enumerate(field.get('observations') or []): for index, observation in enumerate(field.get('observations') or []):
if not isinstance(observation, dict): if not isinstance(observation, dict):
continue continue
coordinate_page, coordinate_bbox, coordinate_source = _layout_coordinate_evidence(case, observation) # Carry schema/row identity into the resolver without exposing it in DTOs.
cell_page, cell_bbox, cell_source = _frozen_cell_coordinate(case, observation) observation['_field_id'] = field.get('field_id')
page_no = observation.get('page_no') if field.get('_line_index') is not None:
try: observation['_line_index'] = field.get('_line_index')
page = int(page_no) if page_no is not None else None layout_evidence = (
except (TypeError, ValueError): observation.get('layout_evidence')
page = None if isinstance(observation.get('layout_evidence'), dict)
if page is not None and page < 1: else {}
page = None )
# 反查路径会把当前 PDF 的唯一 cell 证据写回此临时容器,供后续契约读取。
if not isinstance(observation.get('layout_evidence'), dict):
observation['layout_evidence'] = layout_evidence
resolved_page, resolved_bbox, resolved_source = _resolve_highlight_bbox(
case, observation, layout_evidence=layout_evidence,
)
raw_present, raw_invalid = _observation_raw_bbox_flags(
observation, resolved_bbox=resolved_bbox,
)
quote = _safe_quote(observation.get('quote') or observation.get('evidence_quote'))
bbox_text = _safe_quote(
layout_evidence.get('bbox_text') or observation.get('bbox_text'),
)
quote_source = str(
layout_evidence.get('quote_source') or observation.get('quote_source') or '',
).strip() or None
# [STEP] 统一高亮投影:非法 bbox 不得进入 drawable 字段;值匹配依赖独立引文
highlight = build_field_highlight_projection(
normalized_bbox=resolved_bbox,
raw_bbox_present=raw_present,
raw_bbox_invalid=raw_invalid,
page_no=resolved_page,
source=resolved_source,
machine_value=observation.get('value'),
quote=quote,
bbox_text=bbox_text,
quote_source=quote_source,
evidence_ref=str(layout_evidence.get('evidence_ref') or '') or None,
token_ids=list(layout_evidence.get('token_ids') or []),
observation=observation,
layout_evidence=layout_evidence,
)
table_id = (
str(observation.get('table_id') or layout_evidence.get('table_id') or '')[:128] or None
)
cell_id = (
str(observation.get('cell_id') or layout_evidence.get('cell_id') or '')[:128] or None
)
items.append({ items.append({
'evidence_id': f"{field.get('field_id') or 'field'}:{field.get('_line_index', 'header')}:{index}", 'evidence_id': f"{field.get('field_id') or 'field'}:{field.get('_line_index', 'header')}:{index}",
'field_id': str(field.get('field_id') or ''), 'field_id': str(field.get('field_id') or ''),
'line_index': field.get('_line_index'), 'line_index': field.get('_line_index'),
'machine_value': observation.get('value'), 'machine_value': observation.get('value'),
'quote': _safe_quote(observation.get('quote') or observation.get('evidence_quote')), 'quote': quote,
'page_no': coordinate_page or cell_page or page, 'page_no': resolved_page,
'table_id': str(observation.get('table_id') or '')[:128] or None, 'table_id': table_id,
'cell_id': str(observation.get('cell_id') or '')[:128] or None, 'cell_id': cell_id,
'bbox': coordinate_bbox or cell_bbox or _safe_bbox(observation.get('normalized_bbox') or observation.get('bbox')), # bbox 与 highlight_bbox 对齐:仅可绘制质量才非空,兼容旧前端。
'source': coordinate_source or cell_source or str(observation.get('source') or 'machine_extraction')[:64], 'bbox': highlight['highlight_bbox'],
'source': resolved_source,
**highlight,
}) })
return items return items
@@ -193,6 +486,34 @@ def list_case_evidence(*, user_id: int, case_no: str) -> dict[str, Any]:
return {'case_no': case.case_no, 'items': _observations(case)} return {'case_no': case.case_no, 'items': _observations(case)}
def build_highlight_audit_summary(item: dict[str, Any]) -> dict[str, Any]:
"""
构造坐标高亮审计摘要:只含质量/页码/issue,不含 PDF 正文、URL、对象键。
Args:
item: list_case_evidence / get_case_evidence 单条证据。
Returns:
可写入审计 metadata/after 的脱敏摘要。
"""
bbox = item.get('highlight_bbox') if isinstance(item.get('highlight_bbox'), dict) else None
return {
'evidence_id': str(item.get('evidence_id') or '')[:128],
'field_id': str(item.get('field_id') or '')[:128],
'page_no': item.get('page_no'),
'highlight_quality': str(item.get('highlight_quality') or '')[:32],
'coordinate_status': str(item.get('coordinate_status') or '')[:32],
'highlight_source': str(item.get('highlight_source') or '')[:64],
'coordinate_issue_codes': [
str(code)[:100] for code in (item.get('coordinate_issue_codes') or [])[:20]
],
'has_drawable_bbox': bool(bbox),
'evidence_ref': str(item.get('evidence_ref') or '')[:256] or None,
'table_id': str(item.get('table_id') or '')[:128] or None,
'cell_id': str(item.get('cell_id') or '')[:128] or None,
}
def build_minimal_evidence_pack_for_field( def build_minimal_evidence_pack_for_field(
case: ShippingOrderReviewCase, case: ShippingOrderReviewCase,
*, *,
@@ -0,0 +1,406 @@
"""
services/shipping_notice/order_review_field_conflict_service.py
用途:建单前复核工作台的字段冲突投影与人工裁决。
依赖:ShippingOrderReviewCase / ShippingNoticeCandidate、order_review_draft_service、
candidate_qualification_service、field_adjudication 规范化比较。
逻辑:由 workspace order-review-cases 字段冲突路由调用;裁决写入 Draft 人工值、
清除 Candidate.conflicts_json 对应项并重跑建单资格;不创建 Task、不重解析 PDF。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import ShippingNoticeCandidate, ShippingOrderReviewCase
from app.services.shipping_notice.candidate_qualification_service import (
recalculate_candidate_qualification,
resolve_review_case_customer_resolved,
)
from app.services.shipping_notice.field_adjudication import _normalized_value
from app.services.shipping_notice.order_review_draft_service import (
_assert_version,
_locked_case,
_record_change,
_require_field,
_set_value,
soft_load_review_case_for_audit,
)
def _conflict_key(*, field: str, line_index: Any) -> str:
"""稳定冲突键:line_index:field_code。"""
try:
idx = int(line_index) if line_index is not None else -1
except (TypeError, ValueError):
idx = -1
return f'{idx}:{str(field or "").strip()}'
def _candidate_for_case(case: ShippingOrderReviewCase) -> ShippingNoticeCandidate | None:
if not case.candidate_id:
return None
return db.session.get(ShippingNoticeCandidate, int(case.candidate_id))
def _adjudication_blob(candidate: ShippingNoticeCandidate | None) -> dict[str, Any]:
if candidate is None:
return {}
structured = candidate.structured_result_json if isinstance(candidate.structured_result_json, dict) else {}
extraction = structured.get('extraction') if isinstance(structured.get('extraction'), dict) else {}
adj = extraction.get('field_adjudication') if isinstance(extraction.get('field_adjudication'), dict) else {}
return dict(adj)
def _observations_index(adjudication: dict[str, Any]) -> dict[str, dict[str, Any]]:
rows = list(adjudication.get('observations') or []) + list(adjudication.get('observation_history') or [])
index: dict[str, dict[str, Any]] = {}
for item in rows:
if not isinstance(item, dict):
continue
oid = str(item.get('observation_id') or '').strip()
if oid:
index[oid] = item
return index
def _option_display(
*,
field: str,
value_key: str,
observation_ids: list[str],
observations: dict[str, dict[str, Any]],
) -> dict[str, Any]:
"""把规范化 value_key 还原为可展示值与来源列表。"""
sources: list[str] = []
display = value_key
for oid in observation_ids:
obs = observations.get(str(oid))
if not obs:
continue
if str(obs.get('field') or '') != field:
continue
norm = _normalized_value(field, obs.get('value'))
if norm != str(value_key or '').strip().upper() and norm != str(value_key or '').strip():
# qty 等字段可能归一化格式不同,宽松匹配
if _normalized_value(field, value_key) != norm:
continue
display = obs.get('value') if obs.get('value') not in (None, '') else value_key
source = str(obs.get('source') or '').strip()
if source and source not in sources:
sources.append(source)
return {
'value_key': value_key,
'display_value': display,
'sources': sources,
}
def _line_key_for_index(case: ShippingOrderReviewCase, line_index: int) -> str | None:
"""按 line_index 定位 Draft 行键;优先显式 line_index,否则按顺序。"""
draft = case.current_draft
if draft is None:
return None
lines = list(draft.lines_json or [])
for idx, raw in enumerate(lines):
if not isinstance(raw, dict):
continue
raw_idx = raw.get('line_index')
try:
if raw_idx is not None and int(raw_idx) == int(line_index):
key = str(raw.get('line_key') or '').strip()
return key or None
except (TypeError, ValueError):
pass
if idx == int(line_index):
key = str(raw.get('line_key') or '').strip()
return key or None
return None
def _field_id_for_code(case: ShippingOrderReviewCase, field_code: str, *, scope: str) -> str | None:
"""Schema field_code → field_id。"""
run = case.run
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
definition = schema.get('definition') if isinstance(schema.get('definition'), dict) else {}
for item in definition.get('fields') or []:
if not isinstance(item, dict) or not item.get('enabled', True):
continue
if str(item.get('field_code') or '') != field_code:
continue
if str(item.get('scope') or '') != scope:
continue
field_id = str(item.get('field_id') or '').strip()
return field_id or None
# 宽松:忽略 scope 再匹配一次
for item in definition.get('fields') or []:
if not isinstance(item, dict) or not item.get('enabled', True):
continue
if str(item.get('field_code') or '') == field_code:
field_id = str(item.get('field_id') or '').strip()
return field_id or None
return None
def project_review_case_field_conflicts(case: ShippingOrderReviewCase) -> list[dict[str, Any]]:
"""
投影建单前仍未裁决的字段冲突,供复核工作台集中展示。
Returns:
冲突列表;每项含 conflict_key、field_code、line_index、options、reason。
"""
candidate = _candidate_for_case(case)
if candidate is None:
return []
raw_conflicts = list(candidate.conflicts_json or [])
if not raw_conflicts:
return []
adjudication = _adjudication_blob(candidate)
observations = _observations_index(adjudication)
projected: list[dict[str, Any]] = []
for item in raw_conflicts:
if not isinstance(item, dict):
continue
field = str(item.get('field') or '').strip()
if not field:
continue
try:
line_index = int(item.get('line_index')) if item.get('line_index') is not None else -1
except (TypeError, ValueError):
line_index = -1
value_keys = [str(v) for v in (item.get('values') or []) if v not in (None, '')]
observation_ids = [str(oid) for oid in (item.get('observation_ids') or []) if oid]
options = [
_option_display(
field=field,
value_key=key,
observation_ids=observation_ids,
observations=observations,
)
for key in value_keys
]
line_key = _line_key_for_index(case, line_index) if line_index >= 0 else None
projected.append({
'conflict_key': _conflict_key(field=field, line_index=line_index),
'field_code': field,
'line_index': line_index if line_index >= 0 else None,
'line_key': line_key,
'severity': str(item.get('severity') or 'blocking'),
'reason': str(item.get('reason') or 'field_conflict'),
'options': options,
'observation_ids': observation_ids,
})
return projected
def resolve_review_case_field_conflict(
*,
user_id: int,
case_no: str,
conflict_key: str,
resolution: str,
option_index: int | None = None,
custom_value: Any = None,
expected_draft_version: Any,
reason: str | None = None,
) -> dict[str, Any]:
"""
裁决建单前字段冲突:写入 Draft 值、清除 Candidate 冲突项、重校验资格。
Args:
resolution: adopt_option | custom
option_index: adopt_option 时选用 options[i]
custom_value: custom 时的手工值
expected_draft_version: 草稿乐观锁
reason: 裁决原因(可选,缺省写入默认文案)
Returns:
{'case': 最新 Case 投影, 'field_conflicts': 剩余冲突列表}。
"""
action = 'field_conflict_resolved'
case = _locked_case(user_id=user_id, case_no=case_no, action=action)
_assert_version(case, expected_draft_version, actor_id=user_id, action=action)
candidate = _candidate_for_case(case)
if candidate is None:
raise ConflictError(
'Review case has no candidate for field conflict resolution',
code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
)
conflicts = list(candidate.conflicts_json or [])
target_idx = -1
target: dict[str, Any] | None = None
for idx, item in enumerate(conflicts):
if not isinstance(item, dict):
continue
key = _conflict_key(field=item.get('field'), line_index=item.get('line_index'))
if key == str(conflict_key or '').strip():
target_idx = idx
target = item
break
if target is None or target_idx < 0:
raise NotFoundError(
'Field conflict not found',
code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
details={'conflict_key': conflict_key},
)
field_code = str(target.get('field') or '').strip()
try:
line_index = int(target.get('line_index')) if target.get('line_index') is not None else -1
except (TypeError, ValueError):
line_index = -1
value_keys = [str(v) for v in (target.get('values') or []) if v not in (None, '')]
mode = str(resolution or '').strip().lower()
chosen_display: Any = None
if mode == 'adopt_option':
if option_index is None or int(option_index) < 0 or int(option_index) >= len(value_keys):
raise ValidationError(
'option_index is required for adopt_option',
code='SHIPPING.REVIEW_FIELD_CONFLICT_OPTION_INVALID',
)
observations = _observations_index(_adjudication_blob(candidate))
option = _option_display(
field=field_code,
value_key=value_keys[int(option_index)],
observation_ids=[str(oid) for oid in (target.get('observation_ids') or []) if oid],
observations=observations,
)
chosen_display = option.get('display_value')
elif mode == 'custom':
if custom_value in (None, ''):
raise ValidationError(
'custom_value is required',
code='SHIPPING.REVIEW_FIELD_CONFLICT_VALUE_REQUIRED',
)
chosen_display = custom_value
else:
raise ValidationError(
'Invalid conflict resolution',
code='SHIPPING.INVALID_CONFLICT_RESOLUTION',
details={'resolution': resolution},
)
# [STEP 1] 写入 Draft 人工值。
scope = 'line' if line_index >= 0 else 'header'
field_id = _field_id_for_code(case, field_code, scope=scope)
if not field_id:
raise ConflictError(
'Conflict field is not in frozen schema',
code='SHIPPING.REVIEW_FIELD_CONFLICT_FIELD_UNKNOWN',
details={'field_code': field_code},
)
if scope == 'header':
field = _require_field(case, field_id, 'header', actor_id=user_id, action=action)
header = dict(case.current_draft.header_values_json or {})
change = _set_value(header, field, chosen_display, restore_machine=False)
case.current_draft.header_values_json = header
line_key = None
else:
line_key = _line_key_for_index(case, line_index)
if not line_key:
raise ConflictError(
'Conflict line is missing from draft',
code='SHIPPING.REVIEW_FIELD_CONFLICT_LINE_MISSING',
details={'line_index': line_index},
)
field = _require_field(case, field_id, 'line', actor_id=user_id, action=action)
lines = list(case.current_draft.lines_json or [])
target_line = None
for raw in lines:
if isinstance(raw, dict) and str(raw.get('line_key') or '') == line_key:
target_line = raw
break
if target_line is None:
raise ConflictError(
'Conflict line is missing from draft',
code='SHIPPING.REVIEW_FIELD_CONFLICT_LINE_MISSING',
details={'line_key': line_key},
)
change = _set_value(target_line, field, chosen_display, restore_machine=False)
case.current_draft.lines_json = lines
# [STEP 2] 清除 Candidate 冲突项,并同步 adjudication decision。
conflicts.pop(target_idx)
candidate.conflicts_json = conflicts
structured = dict(candidate.structured_result_json or {})
extraction = dict(structured.get('extraction') or {}) if isinstance(structured.get('extraction'), dict) else {}
adjudication = dict(extraction.get('field_adjudication') or {}) if isinstance(extraction.get('field_adjudication'), dict) else {}
decisions = list(adjudication.get('decisions') or [])
updated_decisions = []
for decision in decisions:
if not isinstance(decision, dict):
continue
same_field = str(decision.get('field') or '') == field_code
same_line = True
if line_index >= 0:
try:
same_line = int(decision.get('line_index')) == line_index
except (TypeError, ValueError):
same_line = False
if same_field and same_line:
updated_decisions.append({
**decision,
'status': 'selected',
'value': chosen_display,
'resolution_method': 'manual_review',
})
else:
updated_decisions.append(decision)
adjudication['decisions'] = updated_decisions
adjudication['conflicts'] = list(conflicts)
extraction['field_adjudication'] = adjudication
structured['extraction'] = extraction
candidate.structured_result_json = structured
db.session.flush()
# [STEP 3] 重算资格并写审计;由路由层 commit。
customer_resolved = resolve_review_case_customer_resolved(case=case, candidate=candidate)
recalculate_candidate_qualification(
candidate=candidate,
run=case.run,
customer_resolved=customer_resolved,
persist=True,
)
reason_text = str(reason or '复核工作台人工裁决字段冲突').strip()
case_payload = _record_change(
case,
actor_id=user_id,
event_type=action,
operation={
'conflict_key': conflict_key,
'field_code': field_code,
'line_key': line_key,
'resolution': mode,
'option_index': option_index,
'chosen_value': chosen_display,
'reason': reason_text[:500],
**change,
},
validate=True,
)
remaining = project_review_case_field_conflicts(case)
return {
'case': case_payload,
'field_conflicts': remaining,
}
def list_review_case_field_conflicts(*, user_id: int, case_no: str) -> dict[str, Any]:
"""只读列出建单前字段冲突(含 draft_version)。"""
from app.services.shipping_notice.order_review_projection import serialize_review_case
case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no))
if case is None:
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
items = project_review_case_field_conflicts(case)
draft_version = int(case.current_draft.draft_version) if case.current_draft else None
return {
'case_no': case.case_no,
'draft_version': draft_version,
'items': items,
'open_count': len(items),
'case': serialize_review_case(case),
}
@@ -0,0 +1,177 @@
"""
services/shipping_notice/order_review_profile_match_service.py
用途:建单前复核工作台的文档模板匹配只读投影。
依赖:ShippingOrderReviewCase、ShippingOrderExtractionRouteDecision、
Run.input_snapshot_json.order_document_profiles。
逻辑:由 serialize_review_case 调用;展示选中模板/候选分/回退原因;
A3 不做手工换模板或重抽取,重路由仍走 Process Gate。
"""
from __future__ import annotations
from typing import Any
from app.models import ShippingOrderExtractionRouteDecision, ShippingOrderReviewCase
_NEEDS_REVIEW_STATUSES = frozenset({
'no_match',
'ambiguous',
'layout_drift',
'evidence_insufficient',
})
def _latest_route_decision(case: ShippingOrderReviewCase) -> ShippingOrderExtractionRouteDecision | None:
"""取 Case 所属 Unit 最新一次路由决策。"""
unit_id = getattr(case, 'unit_id', None)
if unit_id is None:
return None
return (
ShippingOrderExtractionRouteDecision.query
.filter_by(unit_id=int(unit_id))
.order_by(
ShippingOrderExtractionRouteDecision.attempt_no.desc(),
ShippingOrderExtractionRouteDecision.id.desc(),
)
.first()
)
def _route_contract(route: ShippingOrderExtractionRouteDecision | None) -> dict[str, Any]:
if route is None:
return {}
items = route.candidate_summary_json if isinstance(route.candidate_summary_json, list) else []
for item in reversed(items):
if isinstance(item, dict) and item.get('_contract') == 'order-extraction-route.v1':
return item
return {}
def _profile_display_map(case: ShippingOrderReviewCase) -> dict[tuple[str, int], str]:
"""冻结快照 profile_code+version → display_name。"""
run = case.run
snapshot = run.input_snapshot_json if isinstance(getattr(run, 'input_snapshot_json', None), dict) else {}
profiles = snapshot.get('order_document_profiles') if isinstance(snapshot.get('order_document_profiles'), list) else []
mapping: dict[tuple[str, int], str] = {}
for item in profiles:
if not isinstance(item, dict):
continue
code = str(item.get('code') or item.get('profile_code') or '').strip()
try:
version = int(item.get('version') or 0)
except (TypeError, ValueError):
version = 0
if not code or version <= 0:
continue
name = str(item.get('display_name') or item.get('name') or code).strip() or code
mapping[(code, version)] = name
return mapping
def _sanitize_candidates(raw: list[Any], *, display_map: dict[tuple[str, int], str]) -> list[dict[str, Any]]:
"""过滤契约尾块,保留可展示的候选摘要。"""
out: list[dict[str, Any]] = []
for item in raw:
if not isinstance(item, dict):
continue
if item.get('_contract') == 'order-extraction-route.v1':
continue
code = str(item.get('profile_code') or item.get('code') or '').strip()
if not code:
continue
try:
version = int(item.get('version') or 0)
except (TypeError, ValueError):
version = 0
try:
score = float(item.get('score')) if item.get('score') is not None else None
except (TypeError, ValueError):
score = None
out.append({
'profile_code': code,
'version': version or None,
'display_name': display_map.get((code, version), code),
'score': score,
'hard_match': bool(item.get('hard_match')) if item.get('hard_match') is not None else None,
'reason_codes': [str(c) for c in (item.get('reason_codes') or []) if c][:12],
'missing_required_anchor_ids': [
str(c) for c in (item.get('missing_required_anchor_ids') or []) if c
][:12],
})
if len(out) >= 5:
break
return out
def project_review_case_profile_match(case: ShippingOrderReviewCase) -> dict[str, Any]:
"""
投影建单前文档模板匹配摘要。
Returns:
含 status、selected_profile、candidates、needs_review 等;无路由决策时 status=unknown。
"""
route = _latest_route_decision(case)
display_map = _profile_display_map(case)
if route is None:
return {
'status': 'unknown',
'execution_mode': None,
'route_type': None,
'selected_profile': None,
'candidates': [],
'fallback_reason_codes': [],
'needs_review': False,
'available': False,
}
contract = _route_contract(route)
match_status = str(route.match_status or '').strip() or 'unknown'
code = str(route.selected_profile_code or '').strip()
try:
version = int(route.selected_profile_version or 0)
except (TypeError, ValueError):
version = 0
selected = None
if code:
selected = {
'profile_code': code,
'version': version or None,
'checksum': str(route.selected_profile_checksum or '').strip() or None,
'display_name': display_map.get((code, version), code),
'auto_create_approved': (
bool(route.auto_create_approved)
if route.auto_create_approved is not None
else None
),
}
raw_candidates = list(route.candidate_summary_json or [])
candidates = _sanitize_candidates(raw_candidates, display_map=display_map)
fallback = [str(c) for c in (route.fallback_reason_codes_json or []) if c][:20]
needs_review = (
match_status in _NEEDS_REVIEW_STATUSES
or str(route.decision or '') == 'review_required'
or bool(fallback)
)
route_type = str(contract.get('route_type') or '').strip() or None
if not route_type and route.selected_profile_id:
route_type = 'profile_deterministic'
return {
'status': match_status,
'execution_mode': str(route.decision or '').strip() or None,
'route_type': route_type,
'selected_profile': selected,
'candidates': candidates,
'fallback_reason_codes': fallback,
'needs_review': needs_review,
'available': True,
'table_counts': {
'candidate': int(route.candidate_count or 0),
'matched': int(route.matched_table_count or 0),
'parsed': int(route.parsed_table_count or 0),
'approved': int(route.approved_table_count or 0),
},
}
@@ -1,11 +1,18 @@
""" """
建单前订单复核的用户态只读投影。 backend/app/services/shipping_notice/order_review_projection.py
用途:建单前订单复核的用户态只读投影。
依赖:Review Case/Draft、冻结 Run Schema、冻结文档快照、机器 Candidate 摘要、 依赖:Review Case/Draft、冻结 Run Schema、冻结文档快照、机器 Candidate 摘要、
Extraction.normalized_result_json.field_lineage(派生血缘)、 Extraction.normalized_result_json.field_lineage(派生血缘)、
workflow_ledger_service.find_item_by_current_case。 order_review_customer_service.project_review_case_customer_resolution、
order_review_field_conflict_service.project_review_case_field_conflicts、
order_review_duplicate_service.project_review_case_duplicate、
order_review_profile_match_service.project_review_case_profile_match、
workflow_ledger_service.find_item_by_current_case、ShippingTask(确认后推进态)。
逻辑:只返回工作台展示所需的字段定义、机器/人工草稿值、问题、建单资格与行级库存候选; 逻辑:只返回工作台展示所需的字段定义、机器/人工草稿值、问题、建单资格与行级库存候选;
固定投影 customer_resolution / field_conflicts / duplicate / profile_match;
为每行/表头投影 field_meta(value_source / locked / override_reason); 为每行/表头投影 field_meta(value_source / locked / override_reason);
已确认 Case 附带 confirmed_task_no 与 post_confirm_auto_progress,供刷新后恢复「已建单待推进」;
WorkflowItem 已关闭时 available_actions 仅保留 view; WorkflowItem 已关闭时 available_actions 仅保留 view;
不返回全文、对象存储定位、模型原始响应、Prompt 或其他内部执行载荷。 不返回全文、对象存储定位、模型原始响应、Prompt 或其他内部执行载荷。
""" """
@@ -29,6 +36,49 @@ def _safe_filename(value: Any) -> str | None:
return name[:255] or None return name[:255] or None
def _project_post_confirm_auto_progress(case: ShippingOrderReviewCase) -> dict[str, Any] | None:
"""
投影已确认 Case 的任务号与「是否仍需自动推进」态,供前端刷新后恢复重试入口。
核心逻辑:与 schedule_auto_progress_after_review_confirm 同一判定
(process_status=created 且已挂 Extraction);未确认则不投影。
Args:
case: 复核 Case。
Returns:
含 task_no / needs_retry / status / message 的摘要;未确认时为 None。
"""
if str(case.status or '') != 'confirmed' or not case.confirmed_task_id:
return None
from app.models import ShippingTask
from app.services.shipping_notice.order_review_confirmation_service import (
_task_needs_post_confirm_auto_progress,
)
task = db.session.get(ShippingTask, int(case.confirmed_task_id))
if task is None:
return {
'task_no': None,
'needs_retry': False,
'status': 'task_missing',
'message': '已确认但关联任务不可用',
'task_process_status': None,
}
needs_retry = bool(_task_needs_post_confirm_auto_progress(task))
return {
'task_no': str(task.task_no or ''),
'needs_retry': needs_retry,
'status': 'needs_retry' if needs_retry else 'advanced_or_idle',
'message': (
'已建单但任务仍停在待推进,可重试自动推进'
if needs_retry
else '任务已离开待推进态或不需推进'
),
'task_process_status': str(getattr(task, 'process_status', None) or ''),
}
def _schema_fields(run: ShippingOrderExtractionRun) -> list[dict[str, Any]]: def _schema_fields(run: ShippingOrderExtractionRun) -> list[dict[str, Any]]:
"""投影 Run 冻结 Schema,不读取当前 published Schema。""" """投影 Run 冻结 Schema,不读取当前 published Schema。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
@@ -229,10 +279,14 @@ def serialize_review_case(case: ShippingOrderReviewCase) -> dict[str, Any]:
'status': str((draft.validation_result_json or {}).get('status') or 'needs_review'), 'status': str((draft.validation_result_json or {}).get('status') or 'needs_review'),
'gates': dict((draft.validation_result_json or {}).get('gates') or {}), 'gates': dict((draft.validation_result_json or {}).get('gates') or {}),
'failed_gates': list((draft.validation_result_json or {}).get('failed_gates') or []), 'failed_gates': list((draft.validation_result_json or {}).get('failed_gates') or []),
'issues': list((draft.validation_result_json or {}).get('issues') or []),
'line_projections': list((draft.validation_result_json or {}).get('line_projections') or []), 'line_projections': list((draft.validation_result_json or {}).get('line_projections') or []),
'enabled_inventory_source_codes': list( 'enabled_inventory_source_codes': list(
(draft.validation_result_json or {}).get('enabled_inventory_source_codes') or [] (draft.validation_result_json or {}).get('enabled_inventory_source_codes') or []
), ),
'inventory_source_labels': dict(
(draft.validation_result_json or {}).get('inventory_source_labels') or {}
),
}, },
} }
from app.models import ShippingOrderReviewSuggestion from app.models import ShippingOrderReviewSuggestion
@@ -246,6 +300,35 @@ def serialize_review_case(case: ShippingOrderReviewCase) -> dict[str, Any]:
.all() .all()
) )
llm_suggestions = [serialize_suggestion(row) for row in rows] llm_suggestions = [serialize_suggestion(row) for row in rows]
process_gate = None
from app.models import ShippingProcessExecution
from app.services.shipping_notice.process_gate_projection import project_user_gate_summary
execution = (
ShippingProcessExecution.query
.filter_by(review_case_id=int(case.id))
.order_by(ShippingProcessExecution.id.desc())
.first()
)
if execution is not None:
process_gate = project_user_gate_summary(execution)
post_confirm = _project_post_confirm_auto_progress(case)
confirmed_task_no = None
if isinstance(post_confirm, dict) and post_confirm.get('task_no'):
confirmed_task_no = str(post_confirm.get('task_no') or '')
from app.services.shipping_notice.order_review_customer_service import (
project_review_case_customer_resolution,
)
from app.services.shipping_notice.order_review_field_conflict_service import (
project_review_case_field_conflicts,
)
from app.services.shipping_notice.order_review_duplicate_service import (
project_review_case_duplicate,
)
from app.services.shipping_notice.order_review_profile_match_service import (
project_review_case_profile_match,
)
return { return {
'case_no': case.case_no, 'case_no': case.case_no,
'run_no': run.run_no, 'run_no': run.run_no,
@@ -253,15 +336,22 @@ def serialize_review_case(case: ShippingOrderReviewCase) -> dict[str, Any]:
'status': case.status, 'status': case.status,
'disposition': case.disposition, 'disposition': case.disposition,
'confirmed_task_id': int(case.confirmed_task_id) if case.confirmed_task_id else None, 'confirmed_task_id': int(case.confirmed_task_id) if case.confirmed_task_id else None,
'confirmed_task_no': confirmed_task_no,
'post_confirm_auto_progress': post_confirm,
'candidate': { 'candidate': {
'candidate_no': candidate.candidate_no, 'candidate_no': candidate.candidate_no,
'validation_status': candidate.validation_status, 'validation_status': candidate.validation_status,
'po_number': candidate.po_number, 'po_number': candidate.po_number,
} if candidate is not None else None, } if candidate is not None else None,
'customer_resolution': project_review_case_customer_resolution(case),
'field_conflicts': project_review_case_field_conflicts(case),
'duplicate': project_review_case_duplicate(case),
'profile_match': project_review_case_profile_match(case),
'schema': {'schema_version_id': int(run.schema_version_id), 'fields': schema_fields}, 'schema': {'schema_version_id': int(run.schema_version_id), 'fields': schema_fields},
'draft': projected_draft, 'draft': projected_draft,
'llm_suggestions': llm_suggestions, 'llm_suggestions': llm_suggestions,
'available_actions': _allowed_actions(case), 'available_actions': _allowed_actions(case),
'process_gate': process_gate,
} }
@@ -3,8 +3,10 @@ backend/app/services/shipping_notice/order_schema/runtime.py
用途:编译已发布订单 Schema,并裁决 Dify 返回的动态字段 Observation。 用途:编译已发布订单 Schema,并裁决 Dify 返回的动态字段 Observation。
依赖:订单 Schema 动态模型、standard_field_registry、ShippingNoticeDocument、registry、 依赖:订单 Schema 动态模型、standard_field_registry、ShippingNoticeDocument、registry、
derivation_engine、audit_service、订单客户匹配服务。 derivation_engine、audit_service、订单客户匹配服务、process_gate_contract(字段阻断资格)。
逻辑:提交时先验证原文证据和字段规则并投影;再执行 Schema 派生并落库 FieldValue; 逻辑:提交时先验证原文证据和字段规则并投影;再执行 Schema 派生并落库 FieldValue;
仅 required 或 auto_create_key_field 字段可进入 blocked_fields;
可选非关键字段证据不足只生成 diagnostic Finding,不阻断建单;
必填门禁仅在派生后按最终投影判定; 必填门禁仅在派生后按最终投影判定;
published_version 固定读取唯一 Schema STANDARD_SHIPPING_NOTICE(兼容历史 SHIPPING_ORDER)。 published_version 固定读取唯一 Schema STANDARD_SHIPPING_NOTICE(兼容历史 SHIPPING_ORDER)。
""" """
@@ -310,6 +312,66 @@ def _valid_coordinate_evidence(raw: dict[str, Any]) -> bool:
) )
def field_may_block_process(config: dict[str, Any] | None) -> bool:
"""
判断字段质量问题是否允许进入流程阻断集合。
核心逻辑:仅 required=true 或 auto_create_key_field=true 可阻断;
可选非关键字段证据不足只生成诊断 Finding。
Args:
config: Schema 字段配置。
Returns:
True 表示可进入 blocked_fields。
"""
if not isinstance(config, dict):
return False
return bool(config.get('required')) or bool(config.get('auto_create_key_field'))
def build_field_finding(
*,
config: dict[str, Any],
decision: dict[str, Any] | None,
severity: str,
owning_gate_code: str,
) -> dict[str, Any]:
"""
构造标准字段 Finding(阻断或诊断)。
Args:
config: Schema 字段配置。
decision: 裁决摘要(含 id/status/reason_code)。
severity: blocking | diagnostic。
owning_gate_code: 唯一所属门禁。
Returns:
Finding 字典。
"""
field_code = str(config.get('field_code') or '')
reason = str((decision or {}).get('reason_code') or 'evidence_missing')
finding_code = (
'required_field_incomplete'
if severity == 'blocking' and config.get('required')
else 'key_field_quality_blocked'
if severity == 'blocking'
else 'optional_field_evidence_missing'
)
return {
'finding_code': finding_code,
'owning_gate_code': owning_gate_code,
'severity': severity,
'field_code': field_code,
'field_id': str(config.get('field_id') or ''),
'decision_id': (decision or {}).get('id'),
'decision_status': (decision or {}).get('status'),
'reason_code': reason,
'user_visible': severity == 'blocking',
'blocks_current_action': severity == 'blocking',
}
def _choose_value(observations: list[dict[str, Any]], config: dict[str, Any]) -> tuple[Any, str, str | None]: def _choose_value(observations: list[dict[str, Any]], config: dict[str, Any]) -> tuple[Any, str, str | None]:
"""按一致性、来源优先级和冲突策略选择字段值。""" """按一致性、来源优先级和冲突策略选择字段值。"""
if not observations: if not observations:
@@ -763,6 +825,7 @@ def persist_dynamic_order(
header: dict[str, Any] = {} header: dict[str, Any] = {}
line_projections: list[dict[str, Any]] = [] line_projections: list[dict[str, Any]] = []
blocked: list[str] = [] blocked: list[str] = []
findings: list[dict[str, Any]] = []
observations: list[dict[str, Any]] = [] observations: list[dict[str, Any]] = []
decisions: list[dict[str, Any]] = [] decisions: list[dict[str, Any]] = []
context_header, context_observations, context_decisions, context_blocked = persist_deterministic_context_fields( context_header, context_observations, context_decisions, context_blocked = persist_deterministic_context_fields(
@@ -772,12 +835,33 @@ def persist_dynamic_order(
observations.extend(context_observations) observations.extend(context_observations)
decisions.extend(context_decisions) decisions.extend(context_decisions)
blocked.extend(context_blocked) blocked.extend(context_blocked)
for decision in context_decisions:
if str(decision.get('field_code') or '') in context_blocked:
cfg = next((c for c in context_configs if str(c.get('field_code')) == decision.get('field_code')), None)
if cfg is not None:
findings.append(build_field_finding(
config=cfg,
decision=decision,
severity='blocking',
owning_gate_code='field_completeness',
))
backend_rows, table_issues = _layout_rows( backend_rows, table_issues = _layout_rows(
documents, schema_definition=version.definition_json or {}, documents, schema_definition=version.definition_json or {},
layout_candidates_by_document=layout_candidates_by_document, layout_candidates_by_document=layout_candidates_by_document,
) )
for issue in table_issues: for issue in table_issues:
blocked.extend(str(code) for code in issue['field_codes']) blocked.extend(str(code) for code in issue['field_codes'])
for code in issue.get('field_codes') or []:
findings.append({
'finding_code': 'layout_table_evidence_blocked',
'owning_gate_code': 'layout_parsing',
'severity': 'blocking',
'field_code': str(code),
'decision_id': None,
'reason_code': str(issue.get('reason') or 'layout_evidence_unavailable'),
'user_visible': True,
'blocks_current_action': True,
})
groups: list[tuple[int | None, int | None, str, list[Any], dict[str, Any]]] = [ groups: list[tuple[int | None, int | None, str, list[Any], dict[str, Any]]] = [
(None, None, 'header', raw_order.get('header_fields') or [], header) (None, None, 'header', raw_order.get('header_fields') or [], header)
] ]
@@ -817,11 +901,31 @@ def persist_dynamic_order(
decisions.append(decision) decisions.append(decision)
if value is not None: if value is not None:
projection[str(config['field_code'])] = _json_value(value) projection[str(config['field_code'])] = _json_value(value)
# 必填且值为空留给派生后统一门禁;此处只拦已提交但未通过裁决的质量问题。 # [STEP] 必填空值留给派生后统一门禁;仅关键字段质量问题可阻断;
if status not in {'accepted', 'corroborated'} and not ( # 可选非关键字段一律诊断,不进入 blocked_fields。
config.get('required') and value is None if status not in {'accepted', 'corroborated'}:
): deferred_required_empty = bool(config.get('required')) and value is None
if deferred_required_empty:
pass
elif field_may_block_process(config):
blocked.append(str(config['field_code'])) blocked.append(str(config['field_code']))
findings.append(build_field_finding(
config=config,
decision=decision,
severity='blocking',
owning_gate_code=(
'field_conflict_resolution'
if str(decision.get('reason_code') or '') == 'cross_source_conflict'
else 'order_field_extraction'
),
))
else:
findings.append(build_field_finding(
config=config,
decision=decision,
severity='diagnostic',
owning_gate_code='order_field_extraction',
))
# [STEP 2] 未提交字段也必须形成 missing Decision,保证每个 Schema 字段都有可审计结果。 # [STEP 2] 未提交字段也必须形成 missing Decision,保证每个 Schema 字段都有可审计结果。
# 必填缺失不在此处写入 blocked,避免派生补齐后仍残留阻断。 # 必填缺失不在此处写入 blocked,避免派生补齐后仍残留阻断。
@@ -839,6 +943,14 @@ def persist_dynamic_order(
decisions.append(decision) decisions.append(decision)
if value is not None: if value is not None:
projection[str(config['field_code'])] = _json_value(value) projection[str(config['field_code'])] = _json_value(value)
elif status not in {'accepted', 'corroborated'} and not field_may_block_process(config):
# 未提交的可选非关键字段:诊断但不阻断。
findings.append(build_field_finding(
config=config,
decision=decision,
severity='diagnostic',
owning_gate_code='order_field_extraction',
))
# [STEP 3] Schema 派生规则:仅补齐空目标;成功后落库 FieldValue,供冻结/Excel 读取。 # [STEP 3] Schema 派生规则:仅补齐空目标;成功后落库 FieldValue,供冻结/Excel 读取。
derivation_outcome = apply_derivation_rules_to_lines( derivation_outcome = apply_derivation_rules_to_lines(
@@ -908,15 +1020,25 @@ def persist_dynamic_order(
}, },
) )
# [STEP 4] Required 仅在派生之后按最终投影检查,避免派生刚补齐的必填项仍被误拦。 # [STEP 4] 关键字段完整性仅在派生之后按最终投影检查,避免派生刚补齐的必填项仍被误拦。
for config in all_configs.values(): for config in all_configs.values():
if not config.get('required'): if not field_may_block_process(config):
continue continue
code = str(config['field_code']) code = str(config['field_code'])
missing = False
if config['scope'] == 'header' and code not in header: if config['scope'] == 'header' and code not in header:
missing = True
blocked.append(code) blocked.append(code)
if config['scope'] == 'line' and (not line_projections or any(code not in line for line in line_projections)): if config['scope'] == 'line' and (not line_projections or any(code not in line for line in line_projections)):
missing = True
blocked.append(code) blocked.append(code)
if missing:
findings.append(build_field_finding(
config=config,
decision={'reason_code': 'required_field_missing', 'status': 'missing'},
severity='blocking',
owning_gate_code='field_completeness',
))
# 行级辅助投影:仅输出 line_key 与有效 Reservation;line_no 为可识别/可派生内部项次。 # 行级辅助投影:仅输出 line_key 与有效 Reservation;line_no 为可识别/可派生内部项次。
system_line_projections: list[dict[str, Any]] = [] system_line_projections: list[dict[str, Any]] = []
@@ -928,6 +1050,24 @@ def persist_dynamic_order(
header_reservation_id=header.get('reservation_id'), header_reservation_id=header.get('reservation_id'),
), ),
}) })
# [STEP 5] 去重 Finding:同 field_code+severity 只保留一条;blocked_fields 与 blocking Finding 对齐。
blocked_unique = sorted(set(blocked))
deduped_findings: list[dict[str, Any]] = []
seen_finding_keys: set[tuple[str, str, str]] = set()
for item in findings:
key = (
str(item.get('field_code') or ''),
str(item.get('severity') or ''),
str(item.get('finding_code') or ''),
)
if key in seen_finding_keys:
continue
seen_finding_keys.add(key)
# 派生后已补齐的字段若仍残留旧诊断/阻断,以最终 blocked 为准过滤阻断项。
if item.get('severity') == 'blocking' and item.get('field_code') and item['field_code'] not in blocked_unique:
if str(item.get('owning_gate_code') or '') in {'order_field_extraction', 'field_completeness'}:
continue
deduped_findings.append(item)
extraction.normalized_result_json = { extraction.normalized_result_json = {
'header': header, 'header': header,
'lines': line_projections, 'lines': line_projections,
@@ -935,10 +1075,11 @@ def persist_dynamic_order(
'derivation_rules_checksum': derivation_outcome['rules_checksum'], 'derivation_rules_checksum': derivation_outcome['rules_checksum'],
} }
extraction.validation_result_json = { extraction.validation_result_json = {
'blocked_fields': sorted(set(blocked)), 'blocked_fields': blocked_unique,
'deterministic_table_issues': table_issues, 'deterministic_table_issues': table_issues,
'findings': deduped_findings,
} }
extraction.status = 'needs_review' if blocked else 'accepted' extraction.status = 'needs_review' if blocked_unique else 'accepted'
extraction.updated_at = datetime.utcnow() extraction.updated_at = datetime.utcnow()
db.session.flush() db.session.flush()
customer_matches = refresh_order_customer_matches(extraction, header) customer_matches = refresh_order_customer_matches(extraction, header)
@@ -949,7 +1090,8 @@ def persist_dynamic_order(
'system_line_projections': system_line_projections, 'system_line_projections': system_line_projections,
'field_lineage': field_lineage, 'field_lineage': field_lineage,
'derivation_rules_checksum': derivation_outcome['rules_checksum'], 'derivation_rules_checksum': derivation_outcome['rules_checksum'],
'blocked_fields': sorted(set(blocked)), 'blocked_fields': blocked_unique,
'findings': deduped_findings,
'observations': observations, 'observations': observations,
'decisions': decisions, 'decisions': decisions,
'customer_matches': customer_matches, 'customer_matches': customer_matches,
@@ -185,22 +185,37 @@ def _definition(version: ShippingOrderSchemaVersion) -> dict[str, Any]:
def _auto_creation_policy(raw: Any) -> dict[str, Any]: def _auto_creation_policy(raw: Any) -> dict[str, Any]:
""" """
校验订单解析自动建单开关;字段阈值由各字段配置独立维护。 校验订单解析自动建单策略;可选统一 minimum_confidence。
Args: Args:
raw: 策略对象或其它值;非 dict 视为空策略。 raw: 策略对象或其它值;非 dict 视为空策略。
Returns: Returns:
规范化后的 ``{'enabled': bool}``。 规范化后的 ``{'enabled': bool, 'minimum_confidence': float|None}``。
Raises: Raises:
ValidationError: enabled 不是布尔值。 ValidationError: enabled / minimum_confidence 非法。
""" """
policy = raw if isinstance(raw, dict) else {} policy = raw if isinstance(raw, dict) else {}
enabled = policy.get('enabled', False) enabled = policy.get('enabled', False)
if not isinstance(enabled, bool): if not isinstance(enabled, bool):
raise ValidationError('auto_creation_policy.enabled must be boolean', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') raise ValidationError('auto_creation_policy.enabled must be boolean', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
return {'enabled': enabled} minimum_confidence = None
if policy.get('minimum_confidence') is not None:
try:
minimum_confidence = float(policy.get('minimum_confidence'))
except (TypeError, ValueError) as exc:
raise ValidationError(
'auto_creation_policy.minimum_confidence must be a number',
code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID',
) from exc
if not 0 <= minimum_confidence <= 1:
raise ValidationError(
'auto_creation_policy.minimum_confidence must be between 0 and 1',
code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID',
)
minimum_confidence = round(minimum_confidence, 4)
return {'enabled': enabled, 'minimum_confidence': minimum_confidence}
def _resolve_auto_creation_policy_for_definition( def _resolve_auto_creation_policy_for_definition(
@@ -1,9 +1,10 @@
""" """
backend/app/services/shipping_notice/order_schema/table_contract.py backend/app/services/shipping_notice/order_schema/table_contract.py
用途:把冻结订单 Schema 编译为确定性表格表头契约,并校验别名碰撞与安全禁用表头。 用途:把冻结订单 Schema 的明细字段编译为确定性表格表头契约,并校验同一作用域别名碰撞。
依赖:AppError 校验契约、reservation_id 后端安全边界。 依赖:AppError 校验契约、订单 Schema 的 line 字段配置。
逻辑:Schema 保存/发布和 Run 运行时共用同一纯函数;解析器只消费编译结果,不读取当前数据库配置。 逻辑:Schema 保存/发布和 Run 运行时共用同一纯函数;表格解析只消费 line 字段,
header 字段不参与列映射或别名冲突判断。
""" """
from __future__ import annotations from __future__ import annotations
@@ -26,12 +27,6 @@ TABLE_FIELD_CODES = frozenset({
'project_code', 'wbs_code', 'activity_code', 'line_remark', 'project_code', 'wbs_code', 'activity_code', 'line_remark',
}) })
# 这些技术/业务标识与 Reservation ID 语义不同,管理员配置不得覆盖安全边界。
RESERVATION_ID_FORBIDDEN_HEADERS = frozenset({
'allocation id', 'parent allocation id', 'commodity group id',
'supplier code', 'uuid', 'internal id',
})
@dataclass(frozen=True) @dataclass(frozen=True)
class TableHeaderContract: class TableHeaderContract:
"""冻结 Schema 编译出的确定性表头映射及字段配置。""" """冻结 Schema 编译出的确定性表头映射及字段配置。"""
@@ -58,16 +53,20 @@ def compile_table_header_contract(definition: dict[str, Any]) -> TableHeaderCont
Returns: Returns:
仅包含解析器支持字段的标准化表头映射与完整字段配置。 仅包含解析器支持字段的标准化表头映射与完整字段配置。
Raises: Raises:
ValidationError: 不同字段占用同一标准化表头,或 Reservation ID 使用安全禁用表头。 ValidationError: 不同 line 字段占用同一标准化表头。
""" """
mapping: dict[str, str] = {} mapping: dict[str, str] = {}
configs: dict[str, dict[str, Any]] = {} configs: dict[str, dict[str, Any]] = {}
origins: dict[str, str] = {} origins: dict[str, dict[str, str]] = {}
collisions: list[dict[str, str]] = [] collisions: list[dict[str, str]] = []
forbidden: list[str] = []
for raw in definition.get('fields') or []: for raw in definition.get('fields') or []:
if not isinstance(raw, dict) or not raw.get('enabled', True): if not isinstance(raw, dict) or not raw.get('enabled', True):
continue continue
# PDF/邮件表格只有明细列;订单头字段由文档键值和 LLM 语义抽取,
# 因此允许与 line 字段使用相同显示名或别名。
scope = str(raw.get('scope') or 'line').strip().lower()
if scope != 'line':
continue
field_code = str(raw.get('field_code') or '').strip() field_code = str(raw.get('field_code') or '').strip()
if field_code not in TABLE_FIELD_CODES: if field_code not in TABLE_FIELD_CODES:
continue continue
@@ -77,27 +76,30 @@ def compile_table_header_contract(definition: dict[str, Any]) -> TableHeaderCont
normalized = normalize_table_header(candidate) normalized = normalize_table_header(candidate)
if not normalized: if not normalized:
continue continue
# This is a safety denylist, not a business-field match. Keep it
# case-insensitive so changing capitalization cannot bypass it.
if field_code == 'reservation_id' and normalized.casefold() in RESERVATION_ID_FORBIDDEN_HEADERS:
forbidden.append(str(candidate))
continue
previous = mapping.get(normalized) previous = mapping.get(normalized)
if previous and previous != field_code: if previous and previous != field_code:
collisions.append({ collisions.append({
'header': str(candidate), 'header': str(candidate),
'normalized_header': normalized, 'normalized_header': normalized,
'scope': scope,
'field_code': field_code, 'field_code': field_code,
'display_name': str(raw.get('display_name') or field_code),
'conflicts_with': previous, 'conflicts_with': previous,
'first_header': origins[normalized], 'conflicts_with_scope': origins[normalized]['scope'],
'conflicts_with_display_name': origins[normalized]['display_name'],
'first_header': origins[normalized]['header'],
}) })
continue continue
mapping[normalized] = field_code mapping[normalized] = field_code
origins.setdefault(normalized, str(candidate)) origins.setdefault(normalized, {
if collisions or forbidden: 'header': str(candidate),
'scope': scope,
'display_name': str(raw.get('display_name') or field_code),
})
if collisions:
raise ValidationError( raise ValidationError(
'Deterministic table header aliases are ambiguous or unsafe', 'Deterministic table header aliases are ambiguous',
code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID',
details={'table_header_collisions': collisions, 'forbidden_reservation_headers': forbidden}, details={'table_header_collisions': collisions},
) )
return TableHeaderContract(header_to_field=mapping, fields_by_code=configs) return TableHeaderContract(header_to_field=mapping, fields_by_code=configs)
@@ -1,11 +1,12 @@
""" """
services/shipping_notice/order_stp_auto_create_service.py services/shipping_notice/order_stp_auto_create_service.py
用途:对未人工改脏且五门禁全绿的复核 Case 执行幂等 STP 自动建单。 用途:对未人工改脏且 Candidate Qualification 合格的复核 Case 执行幂等 STP 自动建单。
依赖:order_review_confirmation_service、draft 资格校验(含 can_auto_create)、fulfillment_audit。 依赖:order_review_confirmation_service、draft 资格校验(含 can_auto_create)、
candidate_qualification_service、fulfillment_audit。
逻辑:由抽取单元提交 / Run 收尾在 ensure_run_review_cases 之后调用; 逻辑:由抽取单元提交 / Run 收尾在 ensure_run_review_cases 之后调用;
有人工字段覆盖、资格未 ready 或五门禁失败则跳过(仅 Review Case); 先持久化资格快照;有人工字段覆盖、资格未 ready 或 can_auto_create=false 则跳过;
每单成功后独立 commit 并触发 auto_progress;成功/失败审计均 strict。 每单成功后与建单同事务入队 shipping_notice_run,再 commit;成功/失败审计均 strict。
""" """
from __future__ import annotations from __future__ import annotations
@@ -14,15 +15,58 @@ from typing import Any
from app import db from app import db
from app.core.errors import AppError from app.core.errors import AppError
from app.models import ShippingOrderExtractionRun, ShippingOrderReviewCase from app.models import (
ShippingNoticeCandidate,
ShippingOrderExtractionRun,
ShippingOrderReviewCase,
)
from app.services.shipping_notice.candidate_qualification_service import (
recalculate_candidate_qualification,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.order_review_confirmation_service import ( from app.services.shipping_notice.order_review_confirmation_service import (
confirm_review_case, confirm_review_case,
trigger_auto_progress_after_review_confirm, finalize_sync_auto_progress_after_commit,
schedule_auto_progress_after_review_confirm,
) )
from app.services.shipping_notice.order_review_draft_service import _validation from app.services.shipping_notice.order_review_draft_service import _validation
def _persist_case_candidate_qualification(
*,
case: ShippingOrderReviewCase,
run: ShippingOrderExtractionRun,
) -> None:
"""
为 Case 关联的当前 Candidate 写入资格快照。
核心逻辑:优先 machine_candidate_id;缺失时按 document + run 查找当前版本候选。
评估失败不阻断 STP 主流程(资格结果仍由后续 validation 裁决)。
"""
candidate_id = getattr(case, 'candidate_id', None)
candidate = None
if candidate_id:
candidate = db.session.get(ShippingNoticeCandidate, int(candidate_id))
if candidate is None:
candidate = (
ShippingNoticeCandidate.query
.filter_by(
order_extraction_run_id=int(run.id),
primary_document_id=int(case.document_id),
is_current_version=True,
)
.order_by(ShippingNoticeCandidate.id.desc())
.first()
)
if candidate is None:
return
recalculate_candidate_qualification(
candidate=candidate,
run=run,
persist=True,
)
def _draft_has_manual_edits(case: ShippingOrderReviewCase) -> bool: def _draft_has_manual_edits(case: ShippingOrderReviewCase) -> bool:
""" """
判断草稿是否含人工覆盖值。 判断草稿是否含人工覆盖值。
@@ -83,10 +127,12 @@ def maybe_stp_auto_create_for_run(*, run: ShippingOrderExtractionRun) -> list[di
continue continue
owner_id = int(case.owner_user_id) owner_id = int(case.owner_user_id)
draft_version = int(case.current_draft.draft_version) draft_version = int(case.current_draft.draft_version)
# [STEP] 持久化 Candidate Qualification 不可变快照(若 Case 已关联候选)。
_persist_case_candidate_qualification(case=case, run=run)
validation = _validation(case) validation = _validation(case)
case.current_draft.validation_result_json = validation case.current_draft.validation_result_json = validation
case.current_draft.issue_summary_json = list(validation.get('issues') or []) case.current_draft.issue_summary_json = list(validation.get('issues') or [])
# [STEP] 五门禁 + 无人工改脏才自动建单;否则仅 Review Case。 # [STEP] Candidate Qualification + 无人工改脏才自动建单;否则仅 Review Case。
if ( if (
validation.get('status') == 'ready' validation.get('status') == 'ready'
and bool(validation.get('can_auto_create')) and bool(validation.get('can_auto_create'))
@@ -134,11 +180,14 @@ def maybe_stp_auto_create_for_run(*, run: ShippingOrderExtractionRun) -> list[di
source='stp_auto_create', source='stp_auto_create',
strict=True, strict=True,
) )
db.session.commit() progress = schedule_auto_progress_after_review_confirm(
progress = trigger_auto_progress_after_review_confirm(
task_no=created.get('task_no'), task_no=created.get('task_no'),
idempotent_replay=bool(created.get('idempotent_replay')), idempotent_replay=bool(created.get('idempotent_replay')),
created_by_id=int(owner_id) if owner_id is not None else None,
commit=False,
) )
db.session.commit()
progress = finalize_sync_auto_progress_after_commit(progress)
results.append({ results.append({
'case_no': case.case_no, 'case_no': case.case_no,
'status': 'auto_created' if not created.get('idempotent_replay') else 'idempotent_replay', 'status': 'auto_created' if not created.get('idempotent_replay') else 'idempotent_replay',
@@ -3,11 +3,12 @@ services/shipping_notice/process_gate_bridge.py
用途:业务路径与统一门禁领域服务之间的桥接:定位/创建 Execution、 用途:业务路径与统一门禁领域服务之间的桥接:定位/创建 Execution、
将业务评估结果写入 Gate,人工确认后推进冻结/建单门禁,以及履约后段门禁同步。 将业务评估结果写入 Gate,人工确认后推进冻结/建单门禁,以及履约后段门禁同步。
依赖:process_gate_service、process_gate_contract、ShippingProcessExecution、 依赖:process_gate_service、process_gate_contract、constants、inventory_rpa_workflow、
ShippingNoticeWorkflowItem、ShippingOrderReviewCase、ShippingTask。 ShippingProcessExecution、ShippingNoticeWorkflowItem、ShippingOrderReviewCase、ShippingTask。
逻辑:由 order_extraction_run_service / order_review_confirmation_service / 逻辑:由 order_extraction_run_service / order_review_confirmation_service /
order_review_draft_service / progress_workflow / process_gate_executor 调用; order_review_draft_service / progress_workflow / process_gate_executor 调用;
禁止业务代码直接改 Gate.status。 复核草稿经 sync_review_gate_for_case 同步客户/Reservation/库存路由等 findings.details;
禁止业务代码直接改 Gate.status;履约库存准备失败映射细粒度 reason_code。
""" """
from __future__ import annotations from __future__ import annotations
@@ -34,6 +35,118 @@ from app.services.shipping_notice.process_gate_service import (
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
def inventory_preparation_reason_code(task: ShippingTask) -> str:
"""
由任务事实推导库存准备门禁阻断原因码。
核心逻辑:pending_human_reason 与最近 inventory_rpa_failed 事件优先于泛化
inventory_preparation_failed,区分排队/超时/登录/导出/耗尽/缺文件。
惰性导入 constants / inventory_rpa_workflow,避免与桥接模块循环依赖。
Args:
task: 履约任务。
Returns:
稳定阻断原因码(归属 inventory_preparation)。
"""
from app.services.shipping_notice.constants import (
PH_INV_UNAVAIL,
PH_RPA_EXHAUSTED,
PH_RPA_PENDING,
)
from app.services.shipping_notice.inventory_rpa_workflow import latest_task_event
pending = str(task.pending_human_reason or '').strip()
if pending == PH_RPA_PENDING:
return 'inventory_rpa_queued'
if pending == PH_RPA_EXHAUSTED:
return 'inventory_rpa_exhausted'
if pending == PH_INV_UNAVAIL:
return 'inventory_file_missing'
if getattr(task, 'id', None) is not None:
failed = latest_task_event(task, 'inventory_rpa_failed')
if failed is not None:
payload = getattr(failed, 'detail_json', None)
if not isinstance(payload, dict):
payload = getattr(failed, 'payload_json', None)
payload = payload if isinstance(payload, dict) else {}
err = str(payload.get('error') or '').strip().lower()
code = str(payload.get('error_code') or '').strip().lower()
blob = f'{err} {code}'
if 'timeout' in blob:
return 'inventory_rpa_timeout'
if 'login' in blob or 'auth' in blob:
return 'inventory_rpa_login_failed'
if 'export' in blob or 'rpa_export' in blob:
return 'inventory_rpa_export_failed'
if 'empty' in blob:
return 'inventory_file_empty'
if 'identity' in blob or 'mismatch' in blob:
return 'inventory_file_identity_mismatch'
return 'inventory_rpa_export_failed'
# [STEP] 空列表=文件无有效行;None/非列表=尚未落库存文件
if isinstance(task.inventory_lines_json, list):
if len(task.inventory_lines_json) == 0:
return 'inventory_file_empty'
return 'inventory_preparation_failed'
return 'inventory_file_missing'
_FREIGHT_UPLOAD_RPA_REASON_CODES = frozenset({
'upload_rpa_pending',
'upload_rpa_failed',
'upload_rpa_login_failed',
'upload_platform_rejected',
})
def manual_upload_reason_code(task: ShippingTask) -> str:
"""
由任务事实推导货代上传相关阻断原因码。
Args:
task: 履约任务。
Returns:
稳定阻断原因码;upload_rpa_* 归属 freight_upload_rpa,
manual_upload_pending / upload_result_unknown 归属 manual_upload_handoff。
"""
from app.services.shipping_notice.constants import (
PH_UPLOAD_RESULT_UNKNOWN,
PH_UPLOAD_RPA_FAILED,
PH_UPLOAD_RPA_PENDING,
)
pending = str(task.pending_human_reason or '').strip()
status = str(task.process_status or '').strip()
if pending == PH_UPLOAD_RPA_PENDING:
return 'upload_rpa_pending'
if pending == PH_UPLOAD_RPA_FAILED or status == 'upload_failed':
# [STEP] 登录失败优先于泛化 upload_rpa_failed,便于责任方落到 admin
from app.services.shipping_notice.inventory_rpa_workflow import latest_task_event
if getattr(task, 'id', None) is not None:
failed = latest_task_event(task, 'upload_rpa_failed') or latest_task_event(
task, 'freight_upload_failed'
)
if failed is not None:
payload = getattr(failed, 'detail_json', None)
if not isinstance(payload, dict):
payload = getattr(failed, 'payload_json', None)
payload = payload if isinstance(payload, dict) else {}
blob = f"{payload.get('error') or ''} {payload.get('error_code') or ''}".lower()
if 'login' in blob or 'auth' in blob:
return 'upload_rpa_login_failed'
if 'reject' in blob or 'platform' in blob:
return 'upload_platform_rejected'
return 'upload_rpa_failed'
if pending == PH_UPLOAD_RESULT_UNKNOWN or status == 'upload_result_unknown':
return 'upload_result_unknown'
return 'manual_upload_pending'
def _stable_fingerprint(value: Any) -> str: def _stable_fingerprint(value: Any) -> str:
"""对业务输入快照生成稳定指纹。""" """对业务输入快照生成稳定指纹。"""
encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str) encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str)
@@ -306,19 +419,20 @@ def sync_execution_after_review_confirm(
return execution return execution
def sync_inventory_routing_gate_for_case( def _ensure_execution_for_case(
*,
case: ShippingOrderReviewCase, case: ShippingOrderReviewCase,
passed: bool, *,
actor_id: int, actor_id: int,
details: dict[str, Any] | None = None, ) -> ShippingProcessExecution | None:
blocking_reason_code: str | None = None,
) -> ShippingProcessGate | None:
""" """
将库存源路由业务结果同步到 inventory_source_routing Gate。 为复核 Case 定位或创建 ProcessExecution。
Args:
case: 订单复核 Case。
actor_id: 触发同步的用户。
Returns: Returns:
更新后的 Gate;无 Execution 时尝试创建后同步。 Execution;无法创建时 None。
""" """
from app.services.shipping_notice.workflow_ledger_service import find_item_by_current_case from app.services.shipping_notice.workflow_ledger_service import find_item_by_current_case
@@ -337,31 +451,99 @@ def sync_inventory_routing_gate_for_case(
return None return None
if execution.review_case_id is None: if execution.review_case_id is None:
execution.review_case_id = int(case.id) execution.review_case_id = int(case.id)
return execution
def sync_review_gate_for_case(
*,
case: ShippingOrderReviewCase,
gate_code: str,
passed: bool,
actor_id: int,
details: dict[str, Any] | None = None,
blocking_reason_code: str | None = None,
finding_code: str | None = None,
default_reason_code: str | None = None,
invalidate_change_type: str | None = None,
) -> ShippingProcessGate | None:
"""
将复核草稿校验结果同步到指定建单前门禁。
核心逻辑:Finding.details 携带业务事实,供 explainability 投影;无 Execution 时幂等创建。
Args:
case: 复核 Case。
gate_code: 目标门禁码。
passed: 是否通过。
actor_id: 操作人。
details: 写入 Finding.details 的业务事实。
blocking_reason_code: 阻断稳定原因码。
finding_code: Finding 编码;缺省为 `{gate_code}_blocked`。
default_reason_code: 阻断时缺省原因码。
invalidate_change_type: 通过后失效类型。
Returns:
更新后的 Gate;无 Execution 时 None。
"""
execution = _ensure_execution_for_case(case, actor_id=actor_id)
if execution is None:
return None
reason = None if passed else (blocking_reason_code or default_reason_code)
finding_details = dict(details or {})
draft_version = case.current_draft.draft_version if case.current_draft else 0
return apply_gate_outcome( return apply_gate_outcome(
execution=execution, execution=execution,
gate_code='inventory_source_routing', gate_code=gate_code,
passed=passed, passed=passed,
effective_result={ effective_result={
'findings': [] if passed else [{ 'findings': [] if passed else [{
'finding_code': 'inventory_source_routing_blocked', 'finding_code': finding_code or f'{gate_code}_blocked',
'owning_gate_code': 'inventory_source_routing', 'owning_gate_code': gate_code,
'severity': 'blocking', 'severity': 'blocking',
'reason_code': blocking_reason_code or 'no_inventory_source_candidates', 'reason_code': reason,
'user_visible': True, 'user_visible': True,
'blocks_current_action': True, 'blocks_current_action': True,
'details': finding_details,
}], }],
'details': details or {}, 'details': finding_details,
}, },
blocking_reason_code=None if passed else (blocking_reason_code or 'no_inventory_source_candidates'), blocking_reason_code=reason,
actor_type='user', actor_type='user',
actor_id=actor_id, actor_id=actor_id,
idempotency_key=f'inv-route:{case.case_no}:{case.current_draft.draft_version if case.current_draft else 0}', idempotency_key=f'review-gate:{gate_code}:{case.case_no}:{draft_version}',
invalidate_change_type='inventory_source_changed' if passed else None, invalidate_change_type=invalidate_change_type if passed else None,
force=True, force=True,
) )
def sync_inventory_routing_gate_for_case(
*,
case: ShippingOrderReviewCase,
passed: bool,
actor_id: int,
details: dict[str, Any] | None = None,
blocking_reason_code: str | None = None,
) -> ShippingProcessGate | None:
"""
将库存源路由业务结果同步到 inventory_source_routing Gate。
Returns:
更新后的 Gate;无 Execution 时尝试创建后同步。
"""
return sync_review_gate_for_case(
case=case,
gate_code='inventory_source_routing',
passed=passed,
actor_id=actor_id,
details=details,
blocking_reason_code=blocking_reason_code,
finding_code='inventory_source_routing_blocked',
default_reason_code='no_inventory_source_candidates',
invalidate_change_type='inventory_source_changed',
)
def sync_early_pipeline_gates( def sync_early_pipeline_gates(
*, *,
execution: ShippingProcessExecution, execution: ShippingProcessExecution,
@@ -392,7 +574,16 @@ def sync_early_pipeline_gates(
execution=execution, execution=execution,
gate_code='layout_parsing', gate_code='layout_parsing',
passed=layouts_ready, passed=layouts_ready,
effective_result={'findings': [], 'layouts_ready': layouts_ready}, effective_result={
'findings': (
[] if layouts_ready else _fulfillment_blocking_finding(
gate_code='layout_parsing',
reason_code='layout_parse_failed',
details={'execution_no': str(execution.execution_no or '') or None},
)
),
'layouts_ready': layouts_ready,
},
blocking_reason_code=None if layouts_ready else 'layout_parse_failed', blocking_reason_code=None if layouts_ready else 'layout_parse_failed',
actor_type=actor_type, actor_type=actor_type,
actor_id=actor_id, actor_id=actor_id,
@@ -405,7 +596,16 @@ def sync_early_pipeline_gates(
execution=execution, execution=execution,
gate_code='document_profile_routing', gate_code='document_profile_routing',
passed=profile_routed, passed=profile_routed,
effective_result={'findings': [], 'routed': profile_routed}, effective_result={
'findings': (
[] if profile_routed else _fulfillment_blocking_finding(
gate_code='document_profile_routing',
reason_code='profile_not_matched',
details={'execution_no': str(execution.execution_no or '') or None},
)
),
'routed': profile_routed,
},
blocking_reason_code=None if profile_routed else 'profile_not_matched', blocking_reason_code=None if profile_routed else 'profile_not_matched',
actor_type=actor_type, actor_type=actor_type,
actor_id=actor_id, actor_id=actor_id,
@@ -445,6 +645,37 @@ def sync_early_pipeline_gates(
) )
def _fulfillment_blocking_finding(
*,
gate_code: str,
reason_code: str,
details: dict[str, Any] | None = None,
) -> list[dict[str, Any]]:
"""
构造履约门禁用户可见 blocking Finding(供 explainability.details 投影)。
Args:
gate_code: 所属门禁码。
reason_code: 稳定阻断原因码。
details: 白名单业务事实。
Returns:
含单条 Finding 的列表;无 reason 时为空列表。
"""
code = str(reason_code or '').strip()
if not code:
return []
return [{
'finding_code': f'{gate_code}_blocked',
'owning_gate_code': gate_code,
'severity': 'blocking',
'reason_code': code,
'user_visible': True,
'blocks_current_action': True,
'details': dict(details or {}),
}]
def sync_fulfillment_gates_from_task( def sync_fulfillment_gates_from_task(
*, *,
execution: ShippingProcessExecution, execution: ShippingProcessExecution,
@@ -452,10 +683,11 @@ def sync_fulfillment_gates_from_task(
actor_id: str | int | None = None, actor_id: str | int | None = None,
) -> None: ) -> None:
""" """
按 ShippingTask 履约状态同步 inventory_preparation→manual_upload_handoff 门禁。 按 ShippingTask 履约状态同步 inventory_preparation→freight_upload_rpa→manual_upload_handoff。
核心逻辑:将 process_status / export_file_path / match 相关字段投影为 Gate 结果; 核心逻辑:将 process_status / export_file_path / match 相关字段投影为 Gate 结果;
仅阻断当前业务真实卡住的第一道履约门禁,已满足的上游门禁标为 passed。 RPA 等待/失败写入 freight_upload_rpa(非人工交接);真正待人工上传才阻断
manual_upload_handoff;仅阻断当前业务真实卡住的第一道履约门禁。
由 auto_progress 与 Gate 恢复执行器在履约动作后调用。 由 auto_progress 与 Gate 恢复执行器在履约动作后调用。
Args: Args:
@@ -507,53 +739,88 @@ def sync_fulfillment_gates_from_task(
force=True, force=True,
) )
# [STEP 2] inventory_preparation # [STEP 2] inventory_preparation — 等待与失败使用细粒度原因码 + Finding 事实
task_facts = {
'process_status': status or None,
'task_no': str(task.task_no or '') or None,
'has_inventory_lines': has_inventory_lines,
}
if status == 'waiting_inventory': if status == 'waiting_inventory':
from app.services.shipping_notice.constants import PH_RPA_PENDING
waiting_reason = (
'inventory_rpa_queued'
if str(task.pending_human_reason or '').strip() == PH_RPA_PENDING
else 'inventory_preparation_waiting'
)
apply_gate_outcome( apply_gate_outcome(
execution=execution, execution=execution,
gate_code='inventory_preparation', gate_code='inventory_preparation',
passed=False, passed=False,
outcome='waiting_external', outcome='waiting_external',
effective_result={'findings': [], 'process_status': status}, effective_result={
blocking_reason_code='inventory_preparation_waiting', 'findings': _fulfillment_blocking_finding(
gate_code='inventory_preparation',
reason_code=waiting_reason,
details=task_facts,
),
'process_status': status,
},
blocking_reason_code=waiting_reason,
actor_type=actor_type, actor_type=actor_type,
actor_id=actor_id, actor_id=actor_id,
idempotency_key=f'fulfill:invprep:{execution.execution_no}:{status}', idempotency_key=f'fulfill:invprep:{execution.execution_no}:{status}:{waiting_reason}',
force=True, force=True,
) )
return return
inv_prep_passed = status in post_inventory or has_inventory_lines inv_prep_passed = status in post_inventory or has_inventory_lines
inv_prep_reason = None if inv_prep_passed else inventory_preparation_reason_code(task)
apply_gate_outcome( apply_gate_outcome(
execution=execution, execution=execution,
gate_code='inventory_preparation', gate_code='inventory_preparation',
passed=inv_prep_passed, passed=inv_prep_passed,
outcome=None if inv_prep_passed else 'blocked_retryable', outcome=None if inv_prep_passed else 'blocked_retryable',
effective_result={ effective_result={
'findings': [], 'findings': (
[] if inv_prep_passed else _fulfillment_blocking_finding(
gate_code='inventory_preparation',
reason_code=str(inv_prep_reason or 'inventory_preparation_failed'),
details=task_facts,
)
),
'process_status': status, 'process_status': status,
'has_inventory_lines': has_inventory_lines, 'has_inventory_lines': has_inventory_lines,
}, },
blocking_reason_code=None if inv_prep_passed else 'inventory_preparation_failed', blocking_reason_code=inv_prep_reason,
actor_type=actor_type, actor_type=actor_type,
actor_id=actor_id, actor_id=actor_id,
idempotency_key=f'fulfill:invprep:{execution.execution_no}:{status}:{inv_prep_passed}', idempotency_key=f'fulfill:invprep:{execution.execution_no}:{status}:{inv_prep_passed}:{inv_prep_reason}',
force=True, force=True,
) )
if not inv_prep_passed: if not inv_prep_passed:
return return
# [STEP 3] inventory_field_mapping — 以 mapping_confirmed 为准 # [STEP 3] inventory_field_mapping — 以 mapping_confirmed 为准
mapping_reason = 'inventory_mapping_required' if mapping_needed else None
apply_gate_outcome( apply_gate_outcome(
execution=execution, execution=execution,
gate_code='inventory_field_mapping', gate_code='inventory_field_mapping',
passed=not mapping_needed, passed=not mapping_needed,
outcome='blocked_manual' if mapping_needed else None, outcome='blocked_manual' if mapping_needed else None,
effective_result={ effective_result={
'findings': [], 'findings': (
[] if not mapping_needed else _fulfillment_blocking_finding(
gate_code='inventory_field_mapping',
reason_code=mapping_reason or 'inventory_mapping_required',
details={
**task_facts,
'inventory_file_id': int(inv_file.id) if inv_file else None,
},
)
),
'mapping_confirmed': mapping_confirmed, 'mapping_confirmed': mapping_confirmed,
'inventory_file_id': int(inv_file.id) if inv_file else None, 'inventory_file_id': int(inv_file.id) if inv_file else None,
}, },
blocking_reason_code='inventory_mapping_required' if mapping_needed else None, blocking_reason_code=mapping_reason,
actor_type=actor_type, actor_type=actor_type,
actor_id=actor_id, actor_id=actor_id,
idempotency_key=f'fulfill:map:{execution.execution_no}:{mapping_confirmed}:{mapping_needed}', idempotency_key=f'fulfill:map:{execution.execution_no}:{mapping_confirmed}:{mapping_needed}',
@@ -562,37 +829,81 @@ def sync_fulfillment_gates_from_task(
if mapping_needed: if mapping_needed:
return return
# [STEP 4] inventory_matching — 以 match_status 为准 # [STEP 4] inventory_matching — 以 match_status + 行 disposition 细分原因
from app.services.shipping_notice.error_explainability_contract import (
classify_inventory_match_reason,
)
line_results = (
list(task.line_results_json)
if isinstance(task.line_results_json, list)
else []
)
match_reason = None if match_passed else classify_inventory_match_reason(
line_results=line_results,
match_status=match_status,
)
apply_gate_outcome( apply_gate_outcome(
execution=execution, execution=execution,
gate_code='inventory_matching', gate_code='inventory_matching',
passed=match_passed, passed=match_passed,
outcome='blocked_manual' if (not match_passed and status in {'pending_review', 'inventory_ready'}) else None, outcome='blocked_manual' if (not match_passed and status in {'pending_review', 'inventory_ready'}) else None,
effective_result={'findings': [], 'match_status': match_status or None}, effective_result={
blocking_reason_code=None if match_passed else 'inventory_match_failed', 'findings': (
[] if match_passed else _fulfillment_blocking_finding(
gate_code='inventory_matching',
reason_code=str(match_reason or 'inventory_match_failed'),
details={
**task_facts,
'match_status': match_status or None,
'disposition_sample': [
str(item.get('disposition') or '')
for item in line_results[:12]
if isinstance(item, dict)
],
},
)
),
'match_status': match_status or None,
},
blocking_reason_code=match_reason,
actor_type=actor_type, actor_type=actor_type,
actor_id=actor_id, actor_id=actor_id,
idempotency_key=f'fulfill:match:{execution.execution_no}:{match_status or status}', idempotency_key=f'fulfill:match:{execution.execution_no}:{match_status or status}:{match_reason or "ok"}',
force=True, force=True,
) )
if not match_passed: if not match_passed:
return return
# [STEP 5] inventory_sufficiency — 以 match_completed / shortage_json 为准 # [STEP 5] inventory_sufficiency — 以 match_completed / shortage_json 为准
# 多文件冲突优先归匹配门禁;此处仅表达缺口人工复核
shortage_reason = None if sufficiency_ok else (
'inventory_multi_file_conflict'
if any(str(item.get('disposition') or '') == 'multi_file_conflict' for item in line_results if isinstance(item, dict))
else (
'inventory_shortage_review_required' if shortage else 'inventory_insufficient'
)
)
apply_gate_outcome( apply_gate_outcome(
execution=execution, execution=execution,
gate_code='inventory_sufficiency', gate_code='inventory_sufficiency',
passed=sufficiency_ok, passed=sufficiency_ok,
outcome='blocked_manual' if shortage else None, outcome='blocked_manual' if shortage else None,
effective_result={ effective_result={
'findings': [], 'findings': (
[] if sufficiency_ok else _fulfillment_blocking_finding(
gate_code='inventory_sufficiency',
reason_code=str(shortage_reason or 'inventory_insufficient'),
details={**task_facts, 'match_status': match_status or None},
)
),
'match_status': match_status or None, 'match_status': match_status or None,
'shortage': task.shortage_json if isinstance(task.shortage_json, (dict, list)) else None, 'shortage': task.shortage_json if isinstance(task.shortage_json, (dict, list)) else None,
}, },
blocking_reason_code=None if sufficiency_ok else 'inventory_insufficient', blocking_reason_code=None if sufficiency_ok else str(shortage_reason or 'inventory_insufficient'),
actor_type=actor_type, actor_type=actor_type,
actor_id=actor_id, actor_id=actor_id,
idempotency_key=f'fulfill:suff:{execution.execution_no}:{match_status}:{sufficiency_ok}', idempotency_key=f'fulfill:suff:{execution.execution_no}:{match_status}:{sufficiency_ok}:{shortage_reason or "ok"}',
force=True, force=True,
) )
if not sufficiency_ok: if not sufficiency_ok:
@@ -605,7 +916,16 @@ def sync_fulfillment_gates_from_task(
execution=execution, execution=execution,
gate_code='excel_readiness', gate_code='excel_readiness',
passed=excel_ready, passed=excel_ready,
effective_result={'findings': [], 'excel_gate_error': excel_error}, effective_result={
'findings': (
[] if excel_ready else _fulfillment_blocking_finding(
gate_code='excel_readiness',
reason_code='excel_not_ready',
details={**task_facts, 'match_status': match_status or None},
)
),
'excel_gate_error': excel_error,
},
blocking_reason_code=None if excel_ready else 'excel_not_ready', blocking_reason_code=None if excel_ready else 'excel_not_ready',
actor_type=actor_type, actor_type=actor_type,
actor_id=actor_id, actor_id=actor_id,
@@ -620,7 +940,16 @@ def sync_fulfillment_gates_from_task(
execution=execution, execution=execution,
gate_code='artifact_generation', gate_code='artifact_generation',
passed=artifact_ok, passed=artifact_ok,
effective_result={'findings': [], 'has_export': has_export}, effective_result={
'findings': (
[] if artifact_ok else _fulfillment_blocking_finding(
gate_code='artifact_generation',
reason_code='artifact_generation_failed',
details={**task_facts, 'has_export': has_export},
)
),
'has_export': has_export,
},
blocking_reason_code=None if artifact_ok else 'artifact_generation_failed', blocking_reason_code=None if artifact_ok else 'artifact_generation_failed',
actor_type=actor_type, actor_type=actor_type,
actor_id=actor_id, actor_id=actor_id,
@@ -630,19 +959,95 @@ def sync_fulfillment_gates_from_task(
if not artifact_ok: if not artifact_ok:
return return
# [STEP 7] manual_upload_handoff # [STEP 7] freight_upload_rpa(RPA)与 manual_upload_handoff(真正人工)分离。
uploaded = status in done_statuses uploaded = status in done_statuses
upload_reason = None if uploaded else manual_upload_reason_code(task)
task_details = {
'process_status': status or None,
'task_no': str(task.task_no or '') or None,
}
if uploaded:
apply_gate_outcome(
execution=execution,
gate_code='freight_upload_rpa',
passed=True,
effective_result={'process_status': status, 'findings': []},
actor_type=actor_type,
actor_id=actor_id,
idempotency_key=f'fulfill:freight_rpa:{execution.execution_no}:{status}:passed',
force=True,
)
apply_gate_outcome( apply_gate_outcome(
execution=execution, execution=execution,
gate_code='manual_upload_handoff', gate_code='manual_upload_handoff',
passed=uploaded, passed=True,
outcome=None if uploaded else ( effective_result={'process_status': status, 'findings': []},
'waiting_external' if status == 'waiting_upload' else 'blocked_manual'
),
effective_result={'findings': [], 'process_status': status},
blocking_reason_code=None if uploaded else 'manual_upload_pending',
actor_type=actor_type, actor_type=actor_type,
actor_id=actor_id, actor_id=actor_id,
idempotency_key=f'fulfill:upload:{execution.execution_no}:{status}', idempotency_key=f'fulfill:upload:{execution.execution_no}:{status}:passed',
force=True,
)
return
if upload_reason in _FREIGHT_UPLOAD_RPA_REASON_CODES:
if upload_reason == 'upload_rpa_pending':
rpa_outcome = 'waiting_external'
elif upload_reason in {'upload_rpa_login_failed', 'upload_platform_rejected'}:
rpa_outcome = 'blocked_manual'
else:
rpa_outcome = 'blocked_retryable'
apply_gate_outcome(
execution=execution,
gate_code='freight_upload_rpa',
passed=False,
outcome=rpa_outcome,
effective_result={
'findings': _fulfillment_blocking_finding(
gate_code='freight_upload_rpa',
reason_code=str(upload_reason),
details=task_details,
),
'process_status': status,
},
blocking_reason_code=upload_reason,
actor_type=actor_type,
actor_id=actor_id,
idempotency_key=f'fulfill:freight_rpa:{execution.execution_no}:{status}:{upload_reason}',
force=True,
)
return
# 真正人工交接:先通过/跳过 RPA 门禁,避免卡在 pending 的 freight_upload_rpa。
apply_gate_outcome(
execution=execution,
gate_code='freight_upload_rpa',
passed=True,
effective_result={
'process_status': status,
'findings': [],
'handoff': 'manual_upload',
},
actor_type=actor_type,
actor_id=actor_id,
idempotency_key=f'fulfill:freight_rpa:{execution.execution_no}:{status}:manual_handoff',
force=True,
)
apply_gate_outcome(
execution=execution,
gate_code='manual_upload_handoff',
passed=False,
outcome='blocked_manual',
effective_result={
'findings': _fulfillment_blocking_finding(
gate_code='manual_upload_handoff',
reason_code=str(upload_reason or 'manual_upload_pending'),
details=task_details,
),
'process_status': status,
},
blocking_reason_code=upload_reason or 'manual_upload_pending',
actor_type=actor_type,
actor_id=actor_id,
idempotency_key=f'fulfill:upload:{execution.execution_no}:{status}:{upload_reason}',
force=True, force=True,
) )
@@ -4,9 +4,11 @@ services/shipping_notice/process_gate_contract.py
用途:冻结货代发货通知全链路业务门禁(Gate)契约:编码、状态、恢复动作、 用途:冻结货代发货通知全链路业务门禁(Gate)契约:编码、状态、恢复动作、
阻断原因、责任方、Finding 严重级别、原因码唯一归属与字段阻断资格; 阻断原因、责任方、Finding 严重级别、原因码唯一归属与字段阻断资格;
作为 Execution/Gate/Attempt 与前后端类型的唯一代码源。 作为 Execution/Gate/Attempt 与前后端类型的唯一代码源。
依赖:无外部 IO;被 process_gate_dependency、领域服务、API、前端类型与文档引用。 依赖:无外部 IO;被 process_gate_dependency、领域服务、API、前端类型与文档引用;
细粒度错误可解释性分层码见 error_explainability_contract。
逻辑:本模块只冻结名称与规则,不执行业务;后续阶段接线时禁止前端或 Job 私自发明门禁码; 逻辑:本模块只冻结名称与规则,不执行业务;后续阶段接线时禁止前端或 Job 私自发明门禁码;
同一根因只允许一个 owning_gate 产生用户阻断 Finding。 同一根因只允许一个 owning_gate 产生用户阻断 Finding;
单源不可用明细(source_disabled 等)不得写入本模块 owning_gate,避免与行级阻断混层。
""" """
from __future__ import annotations from __future__ import annotations
@@ -263,8 +265,20 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
}, },
}, },
{ {
'gate_code': 'manual_upload_handoff', 'gate_code': 'freight_upload_rpa',
'sequence_no': 19, 'sequence_no': 19,
'label': '货代上传 RPA',
'responsible_party': 'worker',
'recoverable': True,
'default_next_actions': {
'waiting_external': 'poll_freight_upload_rpa',
'blocked_retryable': 'retry_freight_upload_rpa',
'blocked_manual': 'retry_freight_upload_rpa',
},
},
{
'gate_code': 'manual_upload_handoff',
'sequence_no': 20,
'label': '人工上传交接', 'label': '人工上传交接',
'responsible_party': 'owner', 'responsible_party': 'owner',
'recoverable': True, 'recoverable': True,
@@ -313,6 +327,8 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({
'open_shortage_review', 'open_shortage_review',
'recheck_excel_readiness', 'recheck_excel_readiness',
'regenerate_excel_artifact', 'regenerate_excel_artifact',
'poll_freight_upload_rpa',
'retry_freight_upload_rpa',
'regenerate_manual_upload_todo', 'regenerate_manual_upload_todo',
}) })
@@ -323,9 +339,13 @@ PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({
'profile_drift', 'profile_drift',
'profile_not_matched', 'profile_not_matched',
'extraction_incomplete', 'extraction_incomplete',
'order_extraction_failed',
'order_extraction_cancelled',
'evidence_missing', 'evidence_missing',
'required_field_missing', 'required_field_missing',
'reservation_invalid', 'reservation_invalid',
'reservation_missing',
'reservation_duplicate',
'customer_unresolved', 'customer_unresolved',
'customer_ambiguous', 'customer_ambiguous',
'duplicate_unresolved', 'duplicate_unresolved',
@@ -334,6 +354,18 @@ PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({
'no_inventory_source_candidates', 'no_inventory_source_candidates',
'require_manual_review', 'require_manual_review',
'inventory_source_unavailable', 'inventory_source_unavailable',
'inventory_source_conflicted',
'inventory_source_changed',
'inventory_source_identity_mismatch',
'inventory_multi_file_conflict',
'inventory_sku_not_found',
'inventory_reservation_not_found',
'inventory_warehouse_mismatch',
'inventory_required_column_missing',
'inventory_column_ambiguous',
'excel_template_missing',
'excel_input_incomplete',
'artifact_validation_failed',
'freeze_not_ready', 'freeze_not_ready',
'profile_not_auto_freeze_approved', 'profile_not_auto_freeze_approved',
'profile_manual_confirmation_required', 'profile_manual_confirmation_required',
@@ -352,6 +384,9 @@ PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({
'generic_auto_freeze_disabled', 'generic_auto_freeze_disabled',
'llm_path_cannot_auto_freeze', 'llm_path_cannot_auto_freeze',
'auto_freeze_not_enabled', 'auto_freeze_not_enabled',
'auto_create_disabled',
'classification_low_confidence',
'field_low_confidence',
'technical_failure_present', 'technical_failure_present',
'unit_review_required', 'unit_review_required',
'budget_stopped', 'budget_stopped',
@@ -362,16 +397,32 @@ PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({
'task_creation_failed', 'task_creation_failed',
'inventory_preparation_failed', 'inventory_preparation_failed',
'inventory_preparation_waiting', 'inventory_preparation_waiting',
'inventory_rpa_queued',
'inventory_rpa_timeout',
'inventory_rpa_login_failed',
'inventory_rpa_export_failed',
'inventory_rpa_exhausted',
'inventory_file_missing',
'inventory_file_empty',
'inventory_file_identity_mismatch',
'inventory_mapping_required', 'inventory_mapping_required',
'inventory_match_failed', 'inventory_match_failed',
'inventory_insufficient', 'inventory_insufficient',
'inventory_shortage_review_required',
'excel_not_ready', 'excel_not_ready',
'artifact_generation_failed', 'artifact_generation_failed',
'manual_upload_pending', 'manual_upload_pending',
'upload_rpa_pending',
'upload_rpa_failed',
'upload_rpa_login_failed',
'upload_platform_rejected',
'upload_result_unknown',
'gate_invalidated', 'gate_invalidated',
'lease_conflict', 'lease_conflict',
'version_conflict', 'version_conflict',
'not_recoverable', 'not_recoverable',
# 跨门禁技术重试耗尽(不绑定唯一 owning_gate,由当前 Gate 承载)
'technical_retry_exhausted',
}) })
# 原因码 → 唯一 owning_gate;同一根因禁止多门禁平行产生用户阻断。 # 原因码 → 唯一 owning_gate;同一根因禁止多门禁平行产生用户阻断。
@@ -382,9 +433,13 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = {
'profile_drift': 'document_profile_routing', 'profile_drift': 'document_profile_routing',
'profile_not_matched': 'document_profile_routing', 'profile_not_matched': 'document_profile_routing',
'extraction_incomplete': 'order_field_extraction', 'extraction_incomplete': 'order_field_extraction',
'order_extraction_failed': 'order_field_extraction',
'order_extraction_cancelled': 'order_field_extraction',
'evidence_missing': 'order_field_extraction', 'evidence_missing': 'order_field_extraction',
'required_field_missing': 'field_completeness', 'required_field_missing': 'field_completeness',
'reservation_invalid': 'reservation_validation', 'reservation_invalid': 'reservation_validation',
'reservation_missing': 'reservation_validation',
'reservation_duplicate': 'reservation_validation',
'customer_unresolved': 'customer_resolution', 'customer_unresolved': 'customer_resolution',
'customer_ambiguous': 'customer_resolution', 'customer_ambiguous': 'customer_resolution',
'duplicate_unresolved': 'duplicate_detection', 'duplicate_unresolved': 'duplicate_detection',
@@ -393,6 +448,18 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = {
'no_inventory_source_candidates': 'inventory_source_routing', 'no_inventory_source_candidates': 'inventory_source_routing',
'require_manual_review': 'inventory_source_routing', 'require_manual_review': 'inventory_source_routing',
'inventory_source_unavailable': 'inventory_source_routing', 'inventory_source_unavailable': 'inventory_source_routing',
'inventory_source_conflicted': 'inventory_source_routing',
'inventory_source_changed': 'inventory_source_routing',
'inventory_source_identity_mismatch': 'inventory_source_routing',
'inventory_multi_file_conflict': 'inventory_matching',
'inventory_sku_not_found': 'inventory_matching',
'inventory_reservation_not_found': 'inventory_matching',
'inventory_warehouse_mismatch': 'inventory_matching',
'inventory_required_column_missing': 'inventory_field_mapping',
'inventory_column_ambiguous': 'inventory_field_mapping',
'excel_template_missing': 'excel_readiness',
'excel_input_incomplete': 'excel_readiness',
'artifact_validation_failed': 'artifact_generation',
'freeze_not_ready': 'order_freeze_readiness', 'freeze_not_ready': 'order_freeze_readiness',
'profile_not_auto_freeze_approved': 'order_freeze_readiness', 'profile_not_auto_freeze_approved': 'order_freeze_readiness',
'profile_manual_confirmation_required': 'order_freeze_readiness', 'profile_manual_confirmation_required': 'order_freeze_readiness',
@@ -411,6 +478,9 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = {
'generic_auto_freeze_disabled': 'order_freeze_readiness', 'generic_auto_freeze_disabled': 'order_freeze_readiness',
'llm_path_cannot_auto_freeze': 'order_freeze_readiness', 'llm_path_cannot_auto_freeze': 'order_freeze_readiness',
'auto_freeze_not_enabled': 'order_freeze_readiness', 'auto_freeze_not_enabled': 'order_freeze_readiness',
'auto_create_disabled': 'order_freeze_readiness',
'classification_low_confidence': 'order_field_extraction',
'field_low_confidence': 'order_field_extraction',
'technical_failure_present': 'order_freeze_readiness', 'technical_failure_present': 'order_freeze_readiness',
'unit_review_required': 'order_freeze_readiness', 'unit_review_required': 'order_freeze_readiness',
'budget_stopped': 'order_freeze_readiness', 'budget_stopped': 'order_freeze_readiness',
@@ -421,16 +491,42 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = {
'task_creation_failed': 'task_creation', 'task_creation_failed': 'task_creation',
'inventory_preparation_failed': 'inventory_preparation', 'inventory_preparation_failed': 'inventory_preparation',
'inventory_preparation_waiting': 'inventory_preparation', 'inventory_preparation_waiting': 'inventory_preparation',
'inventory_rpa_queued': 'inventory_preparation',
'inventory_rpa_timeout': 'inventory_preparation',
'inventory_rpa_login_failed': 'inventory_preparation',
'inventory_rpa_export_failed': 'inventory_preparation',
'inventory_rpa_exhausted': 'inventory_preparation',
'inventory_file_missing': 'inventory_preparation',
'inventory_file_empty': 'inventory_preparation',
'inventory_file_identity_mismatch': 'inventory_preparation',
'inventory_mapping_required': 'inventory_field_mapping', 'inventory_mapping_required': 'inventory_field_mapping',
'inventory_match_failed': 'inventory_matching', 'inventory_match_failed': 'inventory_matching',
'inventory_insufficient': 'inventory_sufficiency', 'inventory_insufficient': 'inventory_sufficiency',
'inventory_shortage_review_required': 'inventory_sufficiency',
'excel_not_ready': 'excel_readiness', 'excel_not_ready': 'excel_readiness',
'artifact_generation_failed': 'artifact_generation', 'artifact_generation_failed': 'artifact_generation',
'manual_upload_pending': 'manual_upload_handoff', 'manual_upload_pending': 'manual_upload_handoff',
# RPA 等待/失败归 freight_upload_rpa,禁止再映射为人工交接语义。
'upload_rpa_pending': 'freight_upload_rpa',
'upload_rpa_failed': 'freight_upload_rpa',
'upload_rpa_login_failed': 'freight_upload_rpa',
'upload_platform_rejected': 'freight_upload_rpa',
'upload_result_unknown': 'manual_upload_handoff',
} }
# 旧自动建单五门禁键 → 唯一 owning_gate(禁止平行用户投影)。 # Candidate Qualification / 旧自动建单门禁键 → 唯一 owning_gate(禁止平行用户投影)。
AUTO_BUILD_LEGACY_GATE_OWNING_MAP: Final[dict[str, str]] = { AUTO_BUILD_LEGACY_GATE_OWNING_MAP: Final[dict[str, str]] = {
# 新统一门禁
'auto_create_enabled': 'order_freeze_readiness',
'classification_confidence': 'order_field_extraction',
'required_fields_complete': 'field_completeness',
'key_fields_minimum_confidence': 'order_field_extraction',
'evidence_complete': 'order_field_extraction',
'field_conflicts_resolved': 'field_conflict_resolution',
'duplicate_resolved': 'duplicate_detection',
'customer_confirmed': 'customer_resolution',
'idempotency_ok': 'task_creation',
# 兼容旧五门键名(历史测试 / 投影)
'approved_template': 'order_freeze_readiness', 'approved_template': 'order_freeze_readiness',
'fields_complete': 'field_completeness', 'fields_complete': 'field_completeness',
'evidence_passed': 'order_field_extraction', 'evidence_passed': 'order_field_extraction',
@@ -30,6 +30,7 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = {
'inventory_sufficiency', 'inventory_sufficiency',
'excel_readiness', 'excel_readiness',
'artifact_generation', 'artifact_generation',
'freight_upload_rpa',
'manual_upload_handoff', 'manual_upload_handoff',
), ),
'reservation_changed': ( 'reservation_changed': (
@@ -39,6 +40,7 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = {
'inventory_sufficiency', 'inventory_sufficiency',
'excel_readiness', 'excel_readiness',
'artifact_generation', 'artifact_generation',
'freight_upload_rpa',
'manual_upload_handoff', 'manual_upload_handoff',
), ),
'part_number_changed': ( 'part_number_changed': (
@@ -47,6 +49,7 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = {
'inventory_sufficiency', 'inventory_sufficiency',
'excel_readiness', 'excel_readiness',
'artifact_generation', 'artifact_generation',
'freight_upload_rpa',
'manual_upload_handoff', 'manual_upload_handoff',
), ),
'quantity_changed': ( 'quantity_changed': (
@@ -55,6 +58,7 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = {
'inventory_sufficiency', 'inventory_sufficiency',
'excel_readiness', 'excel_readiness',
'artifact_generation', 'artifact_generation',
'freight_upload_rpa',
'manual_upload_handoff', 'manual_upload_handoff',
), ),
'customer_changed': ( 'customer_changed': (
@@ -67,6 +71,7 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = {
'inventory_sufficiency', 'inventory_sufficiency',
'excel_readiness', 'excel_readiness',
'artifact_generation', 'artifact_generation',
'freight_upload_rpa',
'manual_upload_handoff', 'manual_upload_handoff',
), ),
'inventory_source_changed': ( 'inventory_source_changed': (
@@ -76,6 +81,7 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = {
'inventory_sufficiency', 'inventory_sufficiency',
'excel_readiness', 'excel_readiness',
'artifact_generation', 'artifact_generation',
'freight_upload_rpa',
'manual_upload_handoff', 'manual_upload_handoff',
), ),
'inventory_file_changed': ( 'inventory_file_changed': (
@@ -84,6 +90,7 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = {
'inventory_sufficiency', 'inventory_sufficiency',
'excel_readiness', 'excel_readiness',
'artifact_generation', 'artifact_generation',
'freight_upload_rpa',
'manual_upload_handoff', 'manual_upload_handoff',
), ),
'inventory_field_mapping_changed': ( 'inventory_field_mapping_changed': (
@@ -91,10 +98,12 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = {
'inventory_sufficiency', 'inventory_sufficiency',
'excel_readiness', 'excel_readiness',
'artifact_generation', 'artifact_generation',
'freight_upload_rpa',
'manual_upload_handoff', 'manual_upload_handoff',
), ),
'excel_regeneration_only': ( 'excel_regeneration_only': (
'artifact_generation', 'artifact_generation',
'freight_upload_rpa',
'manual_upload_handoff', 'manual_upload_handoff',
), ),
} }
@@ -118,7 +127,8 @@ PROCESS_GATE_PREREQUISITES: Final[dict[str, tuple[str, ...]]] = {
'inventory_sufficiency': ('inventory_matching',), 'inventory_sufficiency': ('inventory_matching',),
'excel_readiness': ('inventory_sufficiency',), 'excel_readiness': ('inventory_sufficiency',),
'artifact_generation': ('excel_readiness',), 'artifact_generation': ('excel_readiness',),
'manual_upload_handoff': ('artifact_generation',), 'freight_upload_rpa': ('artifact_generation',),
'manual_upload_handoff': ('freight_upload_rpa',),
} }
@@ -156,6 +156,8 @@ def _dispatch_action(
'recheck_inventory_sufficiency': _handle_recheck_inventory_sufficiency, 'recheck_inventory_sufficiency': _handle_recheck_inventory_sufficiency,
'recheck_excel_readiness': _handle_recheck_excel_readiness, 'recheck_excel_readiness': _handle_recheck_excel_readiness,
'regenerate_excel_artifact': _handle_regenerate_excel, 'regenerate_excel_artifact': _handle_regenerate_excel,
'poll_freight_upload_rpa': _handle_freight_upload_rpa,
'retry_freight_upload_rpa': _handle_freight_upload_rpa,
'regenerate_manual_upload_todo': _handle_regenerate_manual_upload_todo, 'regenerate_manual_upload_todo': _handle_regenerate_manual_upload_todo,
'open_order_review': _manual_open('open_order_review', 'order_freeze_readiness'), 'open_order_review': _manual_open('open_order_review', 'order_freeze_readiness'),
'open_inventory_source_review': _manual_open('open_inventory_source_review', 'inventory_source_routing'), 'open_inventory_source_review': _manual_open('open_inventory_source_review', 'inventory_source_routing'),
@@ -706,16 +708,30 @@ def _handle_retry_inventory_preparation(
gate: ShippingProcessGate, gate: ShippingProcessGate,
payload: dict[str, Any], payload: dict[str, Any],
) -> dict[str, Any]: ) -> dict[str, Any]:
"""重试/轮询库存准备。""" """
重试/轮询库存准备。
核心逻辑:调用 ensure_inventory 后按任务事实推导细粒度阻断码,再同步履约门禁。
"""
from app.models import ShippingTask
from app.services.shipping_notice.inventory_workflow import ensure_inventory from app.services.shipping_notice.inventory_workflow import ensure_inventory
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task from app.services.shipping_notice.process_gate_bridge import (
inventory_preparation_reason_code,
sync_fulfillment_gates_from_task,
)
response = ensure_inventory(_task_payload(execution, payload)) response = ensure_inventory(_task_payload(execution, payload))
task = ShippingTask.query.get(int(execution.task_id)) if execution.task_id else None
prep_reason = (
inventory_preparation_reason_code(task)
if task is not None
else 'inventory_preparation_failed'
)
outcome = _tool_outcome( outcome = _tool_outcome(
action_code='retry_inventory_preparation', action_code='retry_inventory_preparation',
response=response, response=response,
waiting_statuses={'waiting', 'waiting_external', 'pending', 'running'}, waiting_statuses={'waiting', 'waiting_external', 'pending', 'running'},
blocking_reason_code='inventory_preparation_failed', blocking_reason_code=prep_reason,
) )
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id')) sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id'))
return outcome return outcome
@@ -929,6 +945,56 @@ def _handle_regenerate_excel(
return outcome return outcome
def _handle_freight_upload_rpa(
*,
execution: ShippingProcessExecution,
gate: ShippingProcessGate,
payload: dict[str, Any],
) -> dict[str, Any]:
"""
轮询/重试货代上传 RPA。
核心逻辑:waiting_external 仅同步门禁;blocked_* 时调用 upload_to_freight(mode=retry_upload);
再按任务事实同步 freight_upload_rpa / manual_upload_handoff。
"""
from app.models import ShippingTask
from app.services.shipping_notice.fulfillment_workflow import upload_to_freight
from app.services.shipping_notice.process_gate_bridge import (
manual_upload_reason_code,
sync_fulfillment_gates_from_task,
)
task = ShippingTask.query.get(int(execution.task_id)) if execution.task_id else None
if task is None:
return {
'outcome': 'blocked_manual',
'blocking_reason_code': 'not_recoverable',
'blocking_reason_json': {'message': '缺少绑定任务,无法恢复货代上传 RPA'},
'effective_result_json': {'findings': []},
'output_snapshot': {'action_code': 'retry_freight_upload_rpa'},
}
response: dict[str, Any] = {'status': 'running'}
# [STEP] 仅在非等待态触发重试,避免 waiting_external 轮询重复写 trigger。
if str(gate.status or '') != 'waiting_external':
response = upload_to_freight({
**_task_payload(execution, payload),
'mode': 'retry_upload',
})
sync_fulfillment_gates_from_task(
execution=execution,
actor_type='system',
actor_id=payload.get('actor_user_id'),
)
reason = manual_upload_reason_code(task)
return _tool_outcome(
action_code='retry_freight_upload_rpa',
response=response,
waiting_statuses={'waiting', 'waiting_external', 'pending', 'running'},
blocking_reason_code=reason if reason.startswith('upload_rpa') else 'upload_rpa_failed',
)
def _handle_regenerate_manual_upload_todo( def _handle_regenerate_manual_upload_todo(
*, *,
execution: ShippingProcessExecution, execution: ShippingProcessExecution,
@@ -2,9 +2,12 @@
services/shipping_notice/process_gate_projection.py services/shipping_notice/process_gate_projection.py
用途:将 Execution / Gate / Attempt 投影为前后端共享的只读恢复视图。 用途:将 Execution / Gate / Attempt 投影为前后端共享的只读恢复视图。
依赖:ShippingProcessExecution/Gate/Attempt、process_gate_contract。 依赖:ShippingProcessExecution/Gate/Attempt、process_gate_contract;
error_explainability_contract(统一 explainability / request_id)。
逻辑:Chat、复核台与任务中心读取用户安全投影;管理员诊断中心读取完整投影; 逻辑:Chat、复核台与任务中心读取用户安全投影;管理员诊断中心读取完整投影;
用户端同一时间最多一个阻断 + 一个主要恢复动作;诊断 Finding 不进入用户阻断。 用户端同一时间最多一个阻断 + 一个主要恢复动作;诊断 Finding 不进入用户阻断;
explainability.details 仅白名单业务事实;request_id 仅真实 HTTP 请求号,
execution_no 写入 details;blocking_message 为中文兜底,前端优先 i18n。
""" """
from __future__ import annotations from __future__ import annotations
@@ -16,6 +19,10 @@ from app.models import (
ShippingProcessGate, ShippingProcessGate,
ShippingProcessGateAttempt, ShippingProcessGateAttempt,
) )
from app.services.shipping_notice.error_explainability_contract import (
build_explainability_reason,
message_zh_for_reason,
)
from app.services.shipping_notice.process_gate_contract import ( from app.services.shipping_notice.process_gate_contract import (
PROCESS_GATE_RECOVERABLE_STATUSES, PROCESS_GATE_RECOVERABLE_STATUSES,
get_process_gate_definition, get_process_gate_definition,
@@ -133,8 +140,9 @@ def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bo
'evaluation_version': int(gate.evaluation_version), 'evaluation_version': int(gate.evaluation_version),
'input_fingerprint': gate.input_fingerprint, 'input_fingerprint': gate.input_fingerprint,
'blocking_reason_code': gate.blocking_reason_code, 'blocking_reason_code': gate.blocking_reason_code,
'blocking_reason': gate.blocking_reason_json if include_diagnostics else ( 'blocking_reason': (
{'reason_code': gate.blocking_reason_code} if gate.blocking_reason_code else None gate.blocking_reason_json if include_diagnostics
else _user_facing_blocking_reason_payload(gate)
), ),
'recommendation': gate.recommendation_json if include_diagnostics else None, 'recommendation': gate.recommendation_json if include_diagnostics else None,
'effective_result': gate.effective_result_json if include_diagnostics else None, 'effective_result': gate.effective_result_json if include_diagnostics else None,
@@ -283,6 +291,25 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
status=str((blocking or {}).get('status') or ''), status=str((blocking or {}).get('status') or ''),
) if blocking else None ) if blocking else None
) )
# [STEP] 统一可解释性投影:文案/责任方/下一步与 error_explainability_contract 同源;
# request_id 仅真实请求号;execution_no 放入 details 供 Worker 路径关联。
explainability = None
if reason_code:
details = _user_facing_explainability_details(blocking)
execution_no = str(getattr(execution, 'execution_no', '') or '').strip()
if execution_no:
details.setdefault('execution_no', execution_no)
explainability = build_explainability_reason(
reason_code=str(reason_code),
responsible_party=full.get('responsible_party'),
next_action=str(next_action) if next_action else None,
details=details,
request_id=_resolve_explainability_request_id(
execution=execution,
blocking=blocking,
details=details,
),
)
refs = _execution_navigation_refs(execution) refs = _execution_navigation_refs(execution)
navigation = _navigation_for_action(next_action, refs) navigation = _navigation_for_action(next_action, refs)
return { return {
@@ -291,8 +318,12 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
'current_blocking_gate': blocking, 'current_blocking_gate': blocking,
'blocking_reason_code': reason_code, 'blocking_reason_code': reason_code,
'blocking_message': _user_facing_blocking_message(reason_code), 'blocking_message': _user_facing_blocking_message(reason_code),
'explainability': explainability,
'next_action_code': next_action, 'next_action_code': next_action,
'responsible_party': full.get('responsible_party'), 'responsible_party': (
(explainability or {}).get('responsible_party')
or full.get('responsible_party')
),
'diagnostic_hint': diagnostic_hint, 'diagnostic_hint': diagnostic_hint,
'case_no': refs.get('case_no'), 'case_no': refs.get('case_no'),
'review_case_no': refs.get('review_case_no'), 'review_case_no': refs.get('review_case_no'),
@@ -311,52 +342,200 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
} }
def _user_facing_blocking_reason_payload(gate: ShippingProcessGate) -> dict[str, Any] | None:
"""
用户路径 blocking_reason:保留 reason_code 与 Finding 白名单业务事实。
Args:
gate: 门禁行。
Returns:
精简字典;无原因时 None。
"""
if not gate.blocking_reason_code:
return None
payload: dict[str, Any] = {'reason_code': gate.blocking_reason_code}
for finding in _findings_from_gate(gate):
if finding.get('severity') != 'blocking' or not finding.get('user_visible', True):
continue
details = finding.get('details') if isinstance(finding.get('details'), dict) else {}
for key in _USER_FACING_DETAIL_KEYS:
if key in details and details[key] not in (None, '', [], {}):
payload[key] = details[key]
raw = gate.blocking_reason_json if isinstance(gate.blocking_reason_json, dict) else {}
for key in _USER_FACING_DETAIL_KEYS:
if key in raw and raw[key] not in (None, '', [], {}):
payload.setdefault(key, raw[key])
return payload
def _current_request_id() -> str | None:
"""
读取当前 HTTP 请求的 request_id;无请求上下文时返回 None。
Returns:
请求编号或 None。
"""
try:
from flask import g, has_request_context
if not has_request_context():
return None
value = str(getattr(g, 'request_id', '') or '').strip()
return value or None
except Exception:
return None
def _resolve_explainability_request_id(
*,
execution: ShippingProcessExecution,
blocking: dict[str, Any] | None,
details: dict[str, Any] | None,
) -> str | None:
"""
解析可解释性投影的真实 request_id(禁止用 execution_no 冒充)。
核心逻辑:仅接受 Flask g.request_id 或阻断载荷中显式 request_id;
Worker 无 HTTP 上下文时返回 None,由调用方把 execution_no 写入 details。
Args:
execution: 当前 Process Execution(保留参数供调用方签名稳定;本函数不回退 execution_no)。
blocking: 当前阻断 Gate 用户投影。
details: 已提取的用户可见 details。
Returns:
真实请求编号;无则 None(未知失败将标记 request_id_missing)。
"""
del execution # 刻意不回退 execution_no,避免与 HTTP request_id 混淆
# [STEP 1] HTTP 请求上下文
rid = _current_request_id()
if rid:
return rid
# [STEP 2] 阻断载荷 / details 中已携带的真实 request_id(排除 execution_no 形态)
for payload in (details, blocking if isinstance(blocking, dict) else None):
if not isinstance(payload, dict):
continue
for key in ('request_id',):
candidate = str(payload.get(key) or '').strip()
if candidate and not candidate.upper().startswith(('PEX-', 'EXEC-', 'PE-')):
return candidate[:64]
reason_payload = payload.get('blocking_reason')
if isinstance(reason_payload, dict):
candidate = str(reason_payload.get('request_id') or '').strip()
if candidate and not candidate.upper().startswith(('PEX-', 'EXEC-', 'PE-')):
return candidate[:64]
return None
# 允许进入用户 explainability.details 的业务事实键(禁止堆栈/路径/密钥)。
_USER_FACING_DETAIL_KEYS: frozenset[str] = frozenset({
'source_code',
'source_codes',
'unavailable_source_codes',
'unavailable_reasons',
'matched_rule_codes',
'matched_rule_ids',
'raw_rule_source_codes',
'candidate_inventory_source_codes',
'line_key',
'line_index',
'field_code',
'technical_retry_exhausted',
'request_id',
'process_status',
'match_status',
'task_no',
'has_inventory_lines',
'has_export',
'execution_no',
'inventory_file_id',
})
def _user_facing_explainability_details(blocking: dict[str, Any] | None) -> dict[str, Any]:
"""
从当前阻断 Gate 的 Finding / blocking_reason 提取用户可见业务事实。
Args:
blocking: serialize_process_gate 用户安全投影。
Returns:
白名单 details;可为空。
"""
details: dict[str, Any] = {}
if not isinstance(blocking, dict):
return details
# [STEP 1] Finding.details 白名单字段
for finding in blocking.get('findings') or []:
if not isinstance(finding, dict):
continue
payload = finding.get('details') if isinstance(finding.get('details'), dict) else {}
for key in _USER_FACING_DETAIL_KEYS:
if key in payload and payload[key] not in (None, '', [], {}):
details[key] = payload[key]
# [STEP 2] blocking_reason 白名单(用户路径当前多为 {reason_code})
reason_payload = blocking.get('blocking_reason')
if isinstance(reason_payload, dict):
for key in _USER_FACING_DETAIL_KEYS:
if key in reason_payload and reason_payload[key] not in (None, '', [], {}):
details.setdefault(key, reason_payload[key])
return details
def _user_facing_blocking_message(reason_code: str | None) -> str | None: def _user_facing_blocking_message(reason_code: str | None) -> str | None:
""" """
将内部原因码映射为用户可读业务文案;未知码不回落展示原码。 将内部原因码映射为用户可读业务文案;未知码不回落展示原码。
核心逻辑:优先 error_explainability_contract.message_zh_for_reason;
少量门禁专用码保留本地兜底。
Args: Args:
reason_code: Gate.blocking_reason_code。 reason_code: Gate.blocking_reason_code。
Returns: Returns:
可读文案;无法映射时 None(前端展示门禁标签 + 通用提示)。 可读文案;无法映射时 None(前端展示门禁标签 + 通用提示)。
""" """
text = message_zh_for_reason(reason_code)
if text:
return text
code = str(reason_code or '').strip() code = str(reason_code or '').strip()
if not code: if not code:
return None return None
messages = { # 尚未写入 EXPLAINABILITY_REASON_META 的门禁附属码
'auto_freeze_not_enabled': '自动建单策略尚未放行,需人工确认', legacy = {
'profile_not_auto_freeze_approved': '自动建单策略尚未放行,需人工确认',
'profile_manual_confirmation_required': '自动建单策略尚未放行,需人工确认', 'profile_manual_confirmation_required': '自动建单策略尚未放行,需人工确认',
'freeze_not_ready': '订单尚未满足冻结建单条件,请先完成复核确认', 'profile_auto_freeze_qualification_missing': '自动建单策略尚未放行,需人工确认',
'document_unavailable': '发货通知文档不可用,请重新上传或物化文档', 'profile_auto_freeze_suspended': '自动建单策略尚未放行,需人工确认',
'layout_parse_failed': 'PDF 版面解析失败,请重试解析', 'customer_confirmation_required': '客户身份需人工确认',
'profile_not_matched': '未能匹配文档模板,请人工确认 Profile', 'customer_scope_unmatched': '客户不在当前业务范围内',
'profile_ambiguous': '文档模板存在歧义,请人工确认 Profile', 'customer_scope_not_configured': '客户业务范围尚未配置',
'extraction_incomplete': '订单字段抽取未完成,请重试或进入复核', 'customer_scope_out_of_scope': '客户不在当前业务范围内',
'required_field_missing': '存在必填字段缺失,请补充订单信息', 'multiple_customers_detected': '检测到多个客户,请确认',
'reservation_invalid': 'Reservation 校验未通过,请修正后重试', 'multiple_profiles_detected': '检测到多个文档模板,请确认',
'customer_unresolved': '客户身份未识别,请确认客户', 'business_scenario_unmatched': '业务场景未匹配',
'customer_ambiguous': '客户身份存在歧义,请确认客户', 'business_scenario_not_configured': '业务场景尚未配置',
'duplicate_unresolved': '疑似重复订单,请裁定后继续', 'business_scenario_out_of_scope': '业务场景超出范围',
'field_conflict': '订单字段存在冲突,请解决冲突后继续', 'extraction_emergency_stop': '订单抽取已紧急停止',
'cross_source_conflict': '跨来源字段冲突,请解决冲突后继续', 'generic_auto_freeze_disabled': '通用自动建单未启用',
'no_inventory_source_candidates': '暂无可用库存源候选,请重算或人工指定', # 历史码:LLM 可进统一资格评估;文案改为引导复核而非「天然禁止」。
'require_manual_review': '库存源需人工确认', 'llm_path_cannot_auto_freeze': 'LLM 解析结果需通过统一自动建单资格检查',
'inventory_source_unavailable': '库存源不可用,请更换或重试', 'classification_low_confidence': '订单分类置信度不足',
'task_creation_failed': '履约任务创建失败,请重试或联系管理员', 'auto_create_disabled': '自动建单开关未启用',
'inventory_preparation_failed': '库存准备失败,请重试或上传库存文件', 'field_low_confidence': '关键字段置信度不足',
'inventory_preparation_waiting': '库存准备进行中,请稍后刷新', 'field_conflict': '字段冲突尚未解决',
'inventory_mapping_required': '库存字段映射待确认', 'duplicate_unresolved': '重复订单尚未裁定',
'inventory_match_failed': '库存匹配失败,请复核匹配结果', 'required_field_missing': '缺少创建订单所需字段',
'inventory_insufficient': '库存不足,请处理缺料后继续', 'evidence_missing': '关键识别结果缺少有效证据',
'excel_not_ready': '暂不满足 Excel 生成条件', 'customer_ambiguous': '匹配到多个客户,请确认',
'artifact_generation_failed': 'Excel 生成失败,请重试', 'customer_unresolved': '未能识别客户',
'manual_upload_pending': '请下载 Excel 并在货代平台上传后登记凭据', 'technical_failure_present': '存在技术失败,需处理后继续',
'gate_invalidated': '上游结果已变化,当前门禁需重新评估', 'unit_review_required': '存在待复核文档单元',
'review_required': '需要人工复核后才能继续', 'budget_stopped': '识别预算已用尽',
'run_failed': '识别运行失败',
'run_cancelled': '识别运行已取消',
'pending_orders_present': '仍有待处理订单',
} }
return messages.get(code) return legacy.get(code)
def project_admin_gate_diagnostics(execution: ShippingProcessExecution) -> dict[str, Any]: def project_admin_gate_diagnostics(execution: ShippingProcessExecution) -> dict[str, Any]:
@@ -3,9 +3,10 @@ services/shipping_notice/process_gate_recovery_service.py
用途:处理客户端门禁恢复动作请求(幂等、版本校验、权限边界由 API 层配合)。 用途:处理客户端门禁恢复动作请求(幂等、版本校验、权限边界由 API 层配合)。
依赖:process_gate_service、process_gate_executor、process_gate_contract、 依赖:process_gate_service、process_gate_executor、process_gate_contract、
ShippingProcessExecution。 fulfillment_audit、ShippingProcessExecution。
逻辑:只接受契约内 action_code;排队 Attempt 后同步动作立即执行,异步动作入队 Job; 逻辑:只接受契约内 action_code;排队 Attempt 后同步动作立即执行,异步动作入队 Job;
库存源路由的 retry_with_latest_rules / adopt / keep 委托 Draft 服务。 库存源路由的 retry_with_latest_rules / adopt / keep 委托 Draft 服务;
Workspace/对话侧恢复额外写入 chat_process_gate_* 语义审计(阶段 5–6)。
""" """
from __future__ import annotations from __future__ import annotations
@@ -14,6 +15,7 @@ from typing import Any
from app.core.errors import NotFoundError, ValidationError from app.core.errors import NotFoundError, ValidationError
from app.models import ShippingProcessExecution, ShippingProcessGate from app.models import ShippingProcessExecution, ShippingProcessGate
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.process_gate_contract import ( from app.services.shipping_notice.process_gate_contract import (
PROCESS_GATE_ACTION_CODES, PROCESS_GATE_ACTION_CODES,
get_process_gate_definition, get_process_gate_definition,
@@ -26,6 +28,71 @@ from app.services.shipping_notice.process_gate_executor import (
from app.services.shipping_notice.process_gate_service import queue_gate_attempt from app.services.shipping_notice.process_gate_service import queue_gate_attempt
def _chat_process_gate_event_type(*, action_code: str, trigger_type: str) -> str:
"""
将恢复动作映射为对话侧审计事件码。
核心逻辑:retry/re* → retried;含 skip → skipped;其余人工动作 → taken_over。
Args:
action_code: 契约内动作码。
trigger_type: queue_gate_attempt 使用的触发类型。
Returns:
chat_process_gate_* 事件码。
"""
action = str(action_code or '').strip().lower()
trigger = str(trigger_type or '').strip().lower()
if 'skip' in action:
return 'chat_process_gate_skipped'
if trigger == 'user_retry' or action.startswith('retry') or action.startswith('re'):
return 'chat_process_gate_retried'
return 'chat_process_gate_taken_over'
def _record_chat_process_gate_audit(
*,
execution: ShippingProcessExecution,
gate_code: str,
action_code: str,
trigger_type: str,
actor_type: str,
actor_id: int | str | None,
attempt_no: int,
idempotency_key: str,
) -> None:
"""
为对话/Workspace 门禁恢复追加 chat_* 语义审计。
核心逻辑:与 process_gate_recovery_requested 并列写入;不替代 Process Gate 原事件。
"""
event_type = _chat_process_gate_event_type(action_code=action_code, trigger_type=trigger_type)
record_fulfillment_audit(
event_type=event_type,
aggregate_type='process_gate',
aggregate_id=f'{execution.execution_no}:{gate_code}',
action=str(action_code or 'recovery')[:64],
actor_type=actor_type if actor_type in {'user', 'system', 'admin', 'worker'} else 'user',
actor_id=actor_id,
task_no=None,
result='success',
before={'gate_code': gate_code},
after={
'gate_code': gate_code,
'action_code': action_code,
'attempt_no': int(attempt_no),
'idempotency_key': str(idempotency_key or '')[:64],
'execution_no': execution.execution_no,
},
metadata={
'surface': 'chat',
'trigger_type': trigger_type,
'workbench_surface': 'chat',
},
source='chat_workbench',
)
def get_execution_by_no(execution_no: str) -> ShippingProcessExecution: def get_execution_by_no(execution_no: str) -> ShippingProcessExecution:
"""按编号读取 Execution;不存在抛 NotFound。""" """按编号读取 Execution;不存在抛 NotFound。"""
row = ShippingProcessExecution.query.filter_by( row = ShippingProcessExecution.query.filter_by(
@@ -107,10 +174,13 @@ def request_gate_action(
) )
definition = get_process_gate_definition(gate.gate_code) definition = get_process_gate_definition(gate.gate_code)
trigger_type = (
'user_retry' if action.startswith('retry') or action.startswith('re') else 'user_manual'
)
attempt = queue_gate_attempt( attempt = queue_gate_attempt(
execution_no=execution.execution_no, execution_no=execution.execution_no,
gate_code=gate.gate_code, gate_code=gate.gate_code,
trigger_type='user_retry' if action.startswith('retry') or action.startswith('re') else 'user_manual', trigger_type=trigger_type,
actor_type=actor_type, actor_type=actor_type,
actor_id=actor_id, actor_id=actor_id,
idempotency_key=idempotency_key, idempotency_key=idempotency_key,
@@ -118,7 +188,7 @@ def request_gate_action(
input_snapshot={'action_code': action, 'payload': body}, input_snapshot={'action_code': action, 'payload': body},
) )
# 幂等回放且已终态:直接返回,不二次执行。 # 幂等回放且已终态:直接返回,不二次执行;也不重复写 chat_* 审计。
if attempt.status in {'succeeded', 'failed', 'cancelled', 'superseded'}: if attempt.status in {'succeeded', 'failed', 'cancelled', 'superseded'}:
db_gate = ShippingProcessGate.query.get(int(attempt.gate_id)) db_gate = ShippingProcessGate.query.get(int(attempt.gate_id))
return { return {
@@ -137,6 +207,18 @@ def request_gate_action(
'gate_evaluation_version': int(db_gate.evaluation_version) if db_gate else int(gate.evaluation_version), 'gate_evaluation_version': int(db_gate.evaluation_version) if db_gate else int(gate.evaluation_version),
} }
# [STEP] 对话工作台语义审计:与 process_gate_recovery_requested 并存,供审计中心 chat 分组筛选。
_record_chat_process_gate_audit(
execution=execution,
gate_code=gate.gate_code,
action_code=action,
trigger_type=trigger_type,
actor_type=actor_type,
actor_id=actor_id,
attempt_no=int(attempt.attempt_no),
idempotency_key=str(idempotency_key or ''),
)
if action_requires_async_worker(action): if action_requires_async_worker(action):
from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job
@@ -64,8 +64,67 @@ def _locked_execution(execution_no: str) -> ShippingProcessExecution:
return row return row
def ensure_process_gates_for_execution(execution: ShippingProcessExecution) -> None:
"""
为既有 Execution 补齐契约新增的门禁行(如 freight_upload_rpa)。
核心逻辑:按 PROCESS_GATE_DEFINITIONS 插入缺失 gate_code;若旧版
manual_upload_handoff 仍占 sequence 19,先挪到 20 再插入 freight_upload_rpa=19,
避免 uq_shipping_process_gates_execution_sequence 冲突。不改动既有状态语义。
Args:
execution: 目标 Execution。
"""
rows = list(ShippingProcessGate.query.filter_by(execution_id=int(execution.id)).all())
by_code = {str(row.gate_code): row for row in rows}
now = _utc_now()
changed = False
# [STEP 1] 旧 Execution:manual 占 19 时先腾出序号给 freight_upload_rpa。
manual = by_code.get('manual_upload_handoff')
freight_def = next(
(item for item in PROCESS_GATE_DEFINITIONS if item['gate_code'] == 'freight_upload_rpa'),
None,
)
manual_def = next(
(item for item in PROCESS_GATE_DEFINITIONS if item['gate_code'] == 'manual_upload_handoff'),
None,
)
if (
freight_def is not None
and manual_def is not None
and 'freight_upload_rpa' not in by_code
and manual is not None
and int(manual.sequence_no) == int(freight_def['sequence_no'])
):
manual.sequence_no = int(manual_def['sequence_no'])
manual.updated_at = now
changed = True
db.session.flush()
# [STEP 2] 插入仍缺失的门禁行。
for item in PROCESS_GATE_DEFINITIONS:
code = str(item['gate_code'])
if code in by_code:
continue
db.session.add(ShippingProcessGate(
execution_id=int(execution.id),
gate_code=code,
sequence_no=int(item['sequence_no']),
status='pending',
evaluation_version=1,
next_action_code=None,
lock_version=1,
created_at=now,
updated_at=now,
))
changed = True
if changed:
db.session.flush()
def _locked_gate(*, execution: ShippingProcessExecution, gate_code: str) -> ShippingProcessGate: def _locked_gate(*, execution: ShippingProcessExecution, gate_code: str) -> ShippingProcessGate:
"""按 gate_code 行锁加载门禁。""" """按 gate_code 行锁加载门禁;缺失时先按契约补齐再加载。"""
code = str(gate_code or '').strip() code = str(gate_code or '').strip()
gate = ( gate = (
ShippingProcessGate.query ShippingProcessGate.query
@@ -73,6 +132,14 @@ def _locked_gate(*, execution: ShippingProcessExecution, gate_code: str) -> Ship
.with_for_update() .with_for_update()
.first() .first()
) )
if gate is None:
ensure_process_gates_for_execution(execution)
gate = (
ShippingProcessGate.query
.filter_by(execution_id=int(execution.id), gate_code=code)
.with_for_update()
.first()
)
if gate is None: if gate is None:
raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND') raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND')
return gate return gate
@@ -218,6 +285,8 @@ def ensure_execution_for_workflow_version(
existing.review_case_id = int(review_case_id) existing.review_case_id = int(review_case_id)
if task_id and existing.task_id is None: if task_id and existing.task_id is None:
existing.task_id = int(task_id) existing.task_id = int(task_id)
# 契约新增门禁(如 freight_upload_rpa)时补齐缺失行。
ensure_process_gates_for_execution(existing)
existing.updated_at = _utc_now() existing.updated_at = _utc_now()
db.session.flush() db.session.flush()
return existing return existing
@@ -595,6 +664,8 @@ def complete_gate_attempt(
_refresh_execution_pointers(execution) _refresh_execution_pointers(execution)
event_type = 'process_gate_passed' if outcome == 'passed' else 'process_gate_blocked' event_type = 'process_gate_passed' if outcome == 'passed' else 'process_gate_blocked'
# 顶层 reason_code 与 blocking_reason_code 对齐,便于审计中心按可解释性码筛选
gate_reason = str(gate.blocking_reason_code or '').strip() or None
record_fulfillment_audit( record_fulfillment_audit(
event_type=event_type, event_type=event_type,
aggregate_type='process_gate', aggregate_type='process_gate',
@@ -602,6 +673,7 @@ def complete_gate_attempt(
action=outcome, action=outcome,
actor_type='system', actor_type='system',
result='success' if outcome == 'passed' else 'failure', result='success' if outcome == 'passed' else 'failure',
reason_code=gate_reason,
error_code=attempt.error_code, error_code=attempt.error_code,
before=before, before=before,
after={ after={
@@ -613,7 +685,7 @@ def complete_gate_attempt(
'execution_no': execution.execution_no, 'execution_no': execution.execution_no,
'invalidated_downstream_gates': invalidated, 'invalidated_downstream_gates': invalidated,
}, },
metadata={'outcome': outcome}, metadata={'outcome': outcome, 'reason_code': gate_reason} if gate_reason else {'outcome': outcome},
source='process_gate', source='process_gate',
) )
db.session.flush() db.session.flush()
@@ -672,6 +744,7 @@ def invalidate_downstream_gates(
action='invalidate', action='invalidate',
actor_type=actor_type if actor_type in {'user', 'system', 'admin'} else 'system', actor_type=actor_type if actor_type in {'user', 'system', 'admin'} else 'system',
actor_id=actor_id, actor_id=actor_id,
reason_code='gate_invalidated',
before={'status': before, 'gate_code': gate.gate_code}, before={'status': before, 'gate_code': gate.gate_code},
after={ after={
'status': 'invalidated', 'status': 'invalidated',
@@ -5,6 +5,8 @@ services/shipping_notice/progress_audit_contract.py
依赖:无外部 IO;被 progress / audit / workflow / projection / OpenAPI 与测试引用。 依赖:无外部 IO;被 progress / audit / workflow / projection / OpenAPI 与测试引用。
逻辑:状态、用户可见阶段、健康提示、取消语义、Workflow Item 生命周期、模板评分/ 逻辑:状态、用户可见阶段、健康提示、取消语义、Workflow Item 生命周期、模板评分/
通用解析/LLM 建议/人工裁决事件码、全门禁(Process Gate)恢复审计事件码、 通用解析/LLM 建议/人工裁决事件码、全门禁(Process Gate)恢复审计事件码、
复核工作台布局相关写操作/敏感读取事件码、字段高亮坐标诊断事件码、
对话工作台 chat_* / Candidate 资格 / Workflow 节点事件码(双工作台阶段 5–6)、
审计事件字典与敏感键黑名单的唯一代码源; 审计事件字典与敏感键黑名单的唯一代码源;
UI 与 Worker 行为变更在后续阶段接线,本模块只冻结名称与规则。 UI 与 Worker 行为变更在后续阶段接线,本模块只冻结名称与规则。
SESSION_* 别名保留供过渡期测试引用。 SESSION_* 别名保留供过渡期测试引用。
@@ -75,6 +77,87 @@ SESSION_WORK_ITEM_CLOSED_REASONS: Final[frozenset[str]] = frozenset({
'admin_terminated', 'admin_terminated',
}) })
# 复核工作台布局重构(2026-08-01)业务写 / 敏感读稳定事件字典。
# 普通 UI 折叠不写服务端审计;访问类经 record_access_audit 映射 action,见 REVIEW_WORKBENCH_ACCESS_ACTIONS。
REVIEW_WORKBENCH_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
'review_workbench_opened',
'review_case_opened',
'review_document_switched',
'review_evidence_focused',
'review_evidence_list_viewed',
'review_highlight_diagnostic_viewed',
'review_field_locate_attempted',
'review_coordinate_corrected',
'review_version_history_viewed',
'review_eligibility_details_viewed',
'review_field_restored_machine',
'review_draft_changed',
'review_field_changed',
'review_field_updated',
'review_customer_confirmed',
'review_duplicate_resolved',
'review_conflict_resolved',
'review_qualification_evaluated',
'review_confirmed',
'review_marked_non_order',
'review_marked_quality_issue',
'inventory_routing_rerouted',
'inventory_routing_suggestion_adopted',
'inventory_routing_manual_kept',
'inventory_candidates_updated',
'llm_review_requested',
'llm_review_received',
'llm_suggestion_validated',
'llm_suggestion_accepted',
'llm_suggestion_modified',
'llm_suggestion_rejected',
'sensitive_evidence_viewed',
})
# 对话工作台轻量操作 / 聚焦 / 恢复(阶段 5–6);禁止前端私自发明事件名。
CHAT_WORKBENCH_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
'chat_candidate_viewed',
'chat_task_viewed',
'chat_task_refocused',
'chat_customer_confirmed',
'chat_task_retried',
'chat_process_gate_taken_over',
'chat_process_gate_retried',
'chat_process_gate_skipped',
})
# Candidate 资格评估 / 复核侧资格语义(阶段 6);与 chat / review 分组可叠加查询。
CANDIDATE_QUALIFICATION_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
'candidate_qualification_evaluated',
'review_qualification_evaluated',
})
# 后台 Workflow 节点生命周期(阶段 6);与 Process Gate / 履约节点投影对齐,禁止私造码。
WORKFLOW_NODE_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
'task_created',
'workflow_node_started',
'workflow_node_succeeded',
'workflow_node_failed',
'workflow_node_retried',
'workflow_node_taken_over',
'workflow_node_skipped',
'workflow_node_rolled_back',
'upload_rpa_triggered',
})
# Workspace 访问审计 action → 复核工作台语义(写入 shipping_resource_accessed.metadata.access_action)。
REVIEW_WORKBENCH_ACCESS_ACTIONS: Final[frozenset[str]] = frozenset({
'open_order_review_workbench',
'switch_order_review_document',
'view_order_review_evidence_list',
'view_order_review_evidence',
'view_order_review_highlight_diagnostic',
'attempt_order_review_field_locate',
'preview_order_review_document',
'view_order_review_version_history',
'view_order_review_eligibility_details',
})
# Workflow / 版本切换 / 人工复核 / 监管相关审计事件字典(含历史 session_* 字符串兼容)。 # Workflow / 版本切换 / 人工复核 / 监管相关审计事件字典(含历史 session_* 字符串兼容)。
WORKFLOW_ITEM_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({ WORKFLOW_ITEM_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
'workflow_created', 'workflow_created',
@@ -99,6 +182,27 @@ WORKFLOW_ITEM_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
'review_confirmation_revoked', 'review_confirmation_revoked',
'audit_access', 'audit_access',
'shipping_resource_accessed', 'shipping_resource_accessed',
'inventory_routing_rerouted',
'inventory_routing_suggestion_adopted',
'inventory_routing_manual_kept',
'inventory_candidates_updated',
'llm_review_requested',
'llm_review_received',
'llm_suggestion_validated',
'llm_suggestion_accepted',
'llm_suggestion_modified',
'llm_suggestion_rejected',
'review_workbench_opened',
'review_document_switched',
'review_evidence_focused',
'review_evidence_list_viewed',
'review_highlight_diagnostic_viewed',
'review_field_locate_attempted',
'review_coordinate_corrected',
'review_version_history_viewed',
'review_eligibility_details_viewed',
'review_field_restored_machine',
'sensitive_evidence_viewed',
}) })
# 过渡期别名。 # 过渡期别名。
SESSION_WORK_ITEM_AUDIT_EVENT_TYPES: Final[frozenset[str]] = WORKFLOW_ITEM_AUDIT_EVENT_TYPES SESSION_WORK_ITEM_AUDIT_EVENT_TYPES: Final[frozenset[str]] = WORKFLOW_ITEM_AUDIT_EVENT_TYPES
@@ -5,9 +5,9 @@ services/shipping_notice/progress_workflow.py
依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、 依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、
state_machine(CheckpointKind)、tool_response、process_gate_bridge。 state_machine(CheckpointKind)、tool_response、process_gate_bridge。
逻辑:由 task_workflow / 复核确认 / STP 直通落库对外转调本文件;按 checkpoint_kind 早停或继续; 逻辑:由 task_workflow / 复核确认 / STP 直通落库对外转调本文件;按 checkpoint_kind 早停或继续;
STP:must_human / wait_manual_upload 无副作用早停;货代 RPA 上传不在自动链内; must_human / complete 早停;wait_manual_upload 在 AUTO_UPLOAD=true 时落入履约链触发 RPA,
退出前将 Task 履约状态同步到统一 Process Gate(13–19); 关闭时才停人工上传;禁止平行编排语义;退出前同步 Process Gate;
系统触发时事件 actor_id=None 且 detail.source=system。 系统触发时事件 actor_id=None;workspace_api 须注入 operator_id 并写统一审计。
""" """
from __future__ import annotations from __future__ import annotations
@@ -44,9 +44,9 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
【AI 触发时机】:当用户要求“继续处理”“自动推进”“下一步全自动跑完能跑的步骤”时调用。 【AI 触发时机】:当用户要求“继续处理”“自动推进”“下一步全自动跑完能跑的步骤”时调用。
亦由 STP 直通建单、人工复核确认后系统入口复用(同一函数,禁止平行链路)。 亦由 STP 直通建单、人工复核确认后系统入口复用(同一函数,禁止平行链路)。
核心逻辑:先按 checkpoint_kind 早停(must_human / wait_manual_upload / complete); 核心逻辑:先按 checkpoint_kind 处理早停;WAIT_MANUAL_UPLOAD 在 AUTO_UPLOAD 开启时
Excel 后 WAIT_MANUAL_UPLOAD 幂等对齐 manual_upload_pending 并禁止 upload_to_freight; 不早停、落入履约链触发货代 RPA;关闭时才对齐 manual_upload_pending 并禁止自动上传。
再检查解析门禁与客户/库存源,保证正式库存就绪后委托 fulfillment(止于人工上传登记,不触发 RPA)。 再检查解析门禁与客户/库存源,库存就绪后委托 fulfillment_workflow 同一编排链。
Args: Args:
payload: 必须能定位任务;可额外携带 lang/locale/language、auto-chain 控制参数, payload: 必须能定位任务;可额外携带 lang/locale/language、auto-chain 控制参数,
以及 source(system|workspace_api|tool_api|review_confirmation 等)。 以及 source(system|workspace_api|tool_api|review_confirmation 等)。
@@ -63,16 +63,44 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
source = str(payload.get("source") or "system").strip() or "system" source = str(payload.get("source") or "system").strip() or "system"
# 系统入口不写用户 actor;人工 workspace/tool 可传 operator_id。 # 系统入口不写用户 actor;人工 workspace/tool 可传 operator_id。
actor_raw = payload.get("operator_id") or payload.get("actor_id") actor_raw = payload.get("operator_id") or payload.get("actor_id") or payload.get("_trusted_user_id")
try: try:
actor_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and source != "system" else None actor_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and source != "system" else None
except (TypeError, ValueError): except (TypeError, ValueError):
actor_id = None actor_id = None
from app.services.shipping_notice.tool_common import task_lifecycle_audit_snapshot
before = task_lifecycle_audit_snapshot(task)
log_task_event( log_task_event(
task, task,
"auto_progress_started", "auto_progress_started",
{"source": source, "process_status": task.process_status, "current_step": task.current_step}, {
"source": source,
"process_status": task.process_status,
"current_step": task.current_step,
"reason_code": "auto_progress_started",
},
actor_id=actor_id, actor_id=actor_id,
source=source,
before=before,
after=before,
)
# [STEP] 工作台用户触发时写入统一审计,避免仅有 TaskEvent 而审计中心不可见。
if actor_id is not None and source != "system":
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_auto_progress_started',
aggregate_type='shipping_task',
aggregate_id=str(task.task_no),
action='auto_progress',
actor_type='user',
actor_id=actor_id,
task_no=str(task.task_no),
conversation_id=getattr(task, 'conversation_id', None),
reason_code='auto_progress_started',
before=before,
after=before,
metadata={'source': source, 'current_step': task.current_step},
source=source,
) )
steps: list[str] = [] steps: list[str] = []
@@ -97,12 +125,52 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
data=serialize_task_for_tool(task), data=serialize_task_for_tool(task),
) )
if ui_early.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD: if ui_early.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD:
# 幂等对齐 WorkflowItem 为 manual_upload_pending;自动链禁止 upload_to_freight。 pending = str(getattr(task, 'pending_human_reason', '') or '').strip()
# RPA 已触发/失败:只对齐细粒度投影,不再重复编排。
if pending in {'upload_rpa_pending', 'upload_rpa_failed'}:
try: try:
from app.services.shipping_notice.workflow_ledger_service import sync_workflow_item_stage_for_task from app.services.shipping_notice.workflow_ledger_service import (
sync_workflow_item_stage_for_task,
)
sync_workflow_item_stage_for_task( sync_workflow_item_stage_for_task(
task_no=str(task.task_no), task_no=str(task.task_no),
lifecycle_status='manual_upload_pending', lifecycle_status='manual_upload_pending',
stage=pending,
event_code=pending,
actor_type='system',
actor_id=None,
payload={'task_no': task.task_no, 'source': source},
)
db.session.commit()
except Exception:
db.session.rollback()
_sync_process_gates_after_progress(task, payload)
return tool_response(
status='running' if pending == 'upload_rpa_pending' else 'needs_human',
task=task,
message=(
'货代上传 RPA 进行中,请等待回调。'
if pending == 'upload_rpa_pending'
else '货代上传 RPA 失败,请在对话侧恢复或改人工登记。'
),
data=serialize_task_for_tool(task),
human_options=ui_early.human_options,
checkpoint=ui_early.checkpoint,
stop_agent_turn=True,
)
# AUTO_UPLOAD 开启:与 fulfillment 链统一,继续向下触发上传,禁止在此早停。
if fulfillment_workflow.is_auto_upload_enabled():
pass
else:
# 关闭自动上传:对齐人工待办并禁止自动 upload_to_freight。
try:
from app.services.shipping_notice.workflow_ledger_service import (
sync_workflow_item_stage_for_task,
)
sync_workflow_item_stage_for_task(
task_no=str(task.task_no),
lifecycle_status='manual_upload_pending',
stage='manual_upload_pending',
event_code='manual_upload_pending', event_code='manual_upload_pending',
actor_type='system', actor_type='system',
actor_id=None, actor_id=None,
@@ -213,7 +281,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
else: else:
steps.append("载入库存") steps.append("载入库存")
# [STEP 3] 库存就绪后进入履约侧自动推进(止于 Excel 就绪)。 # [STEP 3] 库存就绪后进入履约侧自动推进(与 try_auto_chain 同一语义:可含货代 RPA)。
fulfillment_result = fulfillment_workflow.run_auto_progress_fulfillment_steps(task, payload, steps) fulfillment_result = fulfillment_workflow.run_auto_progress_fulfillment_steps(task, payload, steps)
# [STEP 4] 将履约真相同步到 Process Gate(inventory_preparation→manual_upload_handoff)。 # [STEP 4] 将履约真相同步到 Process Gate(inventory_preparation→manual_upload_handoff)。
@@ -4,9 +4,9 @@ services/shipping_notice/queue_service.py
用途:货代发货后台任务队列适配层。 用途:货代发货后台任务队列适配层。
依赖:app.jobs.queue、jobs.types、batch_orchestrator、intake_parse_workflow、 依赖:app.jobs.queue、jobs.types、batch_orchestrator、intake_parse_workflow、
order_extraction_run_service / document_layout.lifecycle(超时回收同步领域与 Workflow)。 order_extraction_run_service / document_layout.lifecycle(超时回收同步领域与 Workflow)。
逻辑:发货通知写入通用 jobs;worker 领取 RUN/PARSE;超时回收时 PARSE Job 逻辑:发货通知写入通用 jobs;enqueue 支持 commit=False 与业务同事务;
经 sync_intake_after_parse_job_recovery 同步 Intake,避免永久 parsing; worker 领取 RUN/PARSE;超时回收时 PARSE Job 经 sync_intake_after_parse_job_recovery
订单抽取/版面回收同步 WorkflowItem,避免永久 layout_parsing/extracting。 同步 Intake;订单抽取/版面回收同步 WorkflowItem。
""" """
from __future__ import annotations from __future__ import annotations
@@ -32,8 +32,29 @@ def shipping_task_execution_mode() -> str:
return str(current_app.config.get('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker') or 'worker').strip().lower() return str(current_app.config.get('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker') or 'worker').strip().lower()
def enqueue_shipping_notice_job(*, task_no: str, created_by_id: int | None = None, batch_no: str | None = None) -> tuple[bool, str]: def enqueue_shipping_notice_job(
"""持久化一条单票发货后台任务;不再复用 kb_jobs。""" *,
task_no: str,
created_by_id: int | None = None,
batch_no: str | None = None,
commit: bool = True,
) -> tuple[bool, str]:
"""
持久化一条单票发货后台任务;不再复用 kb_jobs。
核心逻辑:写入 shipping_notice_run Job;sync 模式在 commit=True 时当场执行,
commit=False 时仅 flush 入队,由调用方与业务行同事务提交后再执行(避免未提交任务被推进)。
Args:
task_no: 发货任务号。
created_by_id: 创建人。
batch_no: 可选批次号。
commit: False 时与业务同事务提交;此时 sync 模式返回 queued_sync_pending:<job_id>。
Returns:
(ok, result_token);result_token 为 queued_for_worker / queued_manual /
queued_sync_pending:<id> 或 sync 执行结果状态。
"""
normalized_task_no = str(task_no or '').strip().upper() normalized_task_no = str(task_no or '').strip().upper()
if not normalized_task_no: if not normalized_task_no:
return False, 'task_no is required' return False, 'task_no is required'
@@ -49,9 +70,13 @@ def enqueue_shipping_notice_job(*, task_no: str, created_by_id: int | None = Non
created_by_id=created_by_id, created_by_id=created_by_id,
message='等待后台处理发货任务', message='等待后台处理发货任务',
max_attempts=int(current_app.config.get('SHIPPING_NOTICE_JOB_MAX_ATTEMPTS', 3) or 3), max_attempts=int(current_app.config.get('SHIPPING_NOTICE_JOB_MAX_ATTEMPTS', 3) or 3),
commit=commit,
) )
if shipping_task_execution_mode() == 'sync': if shipping_task_execution_mode() == 'sync':
# [STEP] 同事务入队时延后执行,避免读到未提交的 Task。
if not commit:
return True, f'queued_sync_pending:{int(job_id)}'
ok, result = run_shipping_notice_job({'job_id': job_id}) ok, result = run_shipping_notice_job({'job_id': job_id})
return ok, result return ok, result
if shipping_task_execution_mode() in ('worker', 'rq'): if shipping_task_execution_mode() in ('worker', 'rq'):
@@ -203,6 +228,7 @@ def claim_next_shipping_notice_job() -> Job | None:
JobType.SHIPPING_NOTICE_PARSE, JobType.SHIPPING_NOTICE_PARSE,
JobType.SHIPPING_ORDER_EXTRACTION, JobType.SHIPPING_ORDER_EXTRACTION,
JobType.SHIPPING_DOCUMENT_LAYOUT, JobType.SHIPPING_DOCUMENT_LAYOUT,
JobType.SHIPPING_PROCESS_GATE,
], ],
) )
@@ -1,9 +1,10 @@
""" """
services/shipping_notice/rpa_worker_heartbeat.py services/shipping_notice/rpa_worker_heartbeat.py
用途:货代库存 RPA Worker 心跳存储、共享目录校验、就绪检查与状态查询。 用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传就绪检查与状态查询。
依赖:Flask current_app、redis_client、shipping_notice.rpa(目录与 mock 模式)。 依赖:Flask current_app、redis_client、shipping_notice.rpa(库存与上传目录、mock 模式)。
逻辑:freight_rpa_worker 调 POST /rpa/heartbeat;写 trigger 前由 rpa / inventory_rpa_workflow / shipping_inventory_rpa_job 调用就绪检查。 逻辑:freight_rpa_worker 调 POST /rpa/heartbeat;写 inventory/upload trigger 前强制就绪检查;
AUTO_UPLOAD 开启时由 create_app 与履约链调用货代上传就绪校验(Worker/凭据/共享目录/环境隔离)。
""" """
from __future__ import annotations from __future__ import annotations
@@ -28,7 +29,9 @@ logger = logging.getLogger(__name__)
RPA_WORKER_OFFLINE_MESSAGE = "RPA Worker 未在线,请启动 Windows RPA 服务后重试" RPA_WORKER_OFFLINE_MESSAGE = "RPA Worker 未在线,请启动 Windows RPA 服务后重试"
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,请检查 Redis 连接" RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,请检查 Redis 连接"
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 Worker、凭据与共享目录后重试"
INVENTORY_EXPORT_CAPABILITY = "inventory_export" INVENTORY_EXPORT_CAPABILITY = "inventory_export"
FREIGHT_UPLOAD_CAPABILITY = "freight_upload"
_REDIS_INDEX_KEY = "shipping:rpa:heartbeat:index" _REDIS_INDEX_KEY = "shipping:rpa:heartbeat:index"
_REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:" _REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:"
_MEMORY_STORE: dict[str, dict[str, Any]] = {} _MEMORY_STORE: dict[str, dict[str, Any]] = {}
@@ -37,13 +40,19 @@ _MEMORY_LOCK = threading.Lock()
_REASON_USER_HINTS: dict[str, str] = { _REASON_USER_HINTS: dict[str, str] = {
"no_worker_heartbeat": "未收到任何 Worker 心跳", "no_worker_heartbeat": "未收到任何 Worker 心跳",
"heartbeat_storage_unavailable": "心跳存储不可用(Redis)", "heartbeat_storage_unavailable": "心跳存储不可用(Redis)",
"trigger_dir_not_configured": "后端未配置库存 trigger 目录", "trigger_dir_not_configured": "后端未配置 trigger 目录",
"trigger_dir_not_accessible": "trigger 目录不存在或不可访问", "trigger_dir_not_accessible": "trigger 目录不存在或不可访问",
"shared_sentinel_missing": "共享目录哨兵文件缺失,可能 CIFS 未挂载", "shared_sentinel_missing": "共享目录哨兵文件缺失,可能 CIFS 未挂载",
"shared_scope_mismatch": "共享目录 scope 与后端配置不一致", "shared_scope_mismatch": "共享目录 scope 与后端配置不一致",
"trigger_dir_not_writable": "trigger 目录不可写", "trigger_dir_not_writable": "trigger 目录不可写",
"environment_mismatch": "Worker 环境与后端环境不一致", "environment_mismatch": "Worker 环境与后端环境不一致",
"missing_inventory_export_capability": "Worker 未声明 inventory_export 能力", "missing_inventory_export_capability": "Worker 未声明 inventory_export 能力",
"missing_freight_upload_capability": "Worker 未声明 freight_upload 能力",
"credential_key_missing": "未配置 SHIPPING_NOTICE_RPA_CREDENTIAL_KEY",
"upload_queue_dir_not_configured": "未配置货代上传队列目录",
"upload_queue_dir_not_accessible": "货代上传队列目录不可访问",
"callback_api_base_missing": "未配置 Worker 回调可达的 API 基址",
"auto_upload_disabled": "SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 未显式开启",
} }
@@ -385,7 +394,21 @@ def _worker_is_eligible(
backend_env: str, backend_env: str,
ttl_seconds: int, ttl_seconds: int,
now: float, now: float,
required_capability: str = INVENTORY_EXPORT_CAPABILITY,
) -> tuple[bool, list[str]]: ) -> tuple[bool, list[str]]:
"""
判断单 Worker 是否满足心跳新鲜度、能力声明与环境/scope 隔离。
Args:
worker: 心跳记录。
backend_env: 后端归一环境(dev/test/prod)。
ttl_seconds: 心跳 TTL。
now: 当前 epoch 秒。
required_capability: 必选能力(inventory_export / freight_upload)。
Returns:
(是否合格, 不合格原因列表)。
"""
reasons: list[str] = [] reasons: list[str] = []
age = _heartbeat_age_seconds(worker, now=now) age = _heartbeat_age_seconds(worker, now=now)
if age is None: if age is None:
@@ -394,7 +417,10 @@ def _worker_is_eligible(
reasons.append(f"heartbeat_stale:{int(age)}s") reasons.append(f"heartbeat_stale:{int(age)}s")
capabilities = _parse_capabilities(worker.get("capabilities")) capabilities = _parse_capabilities(worker.get("capabilities"))
if INVENTORY_EXPORT_CAPABILITY not in capabilities: if required_capability and required_capability not in capabilities:
if required_capability == FREIGHT_UPLOAD_CAPABILITY:
reasons.append("missing_freight_upload_capability")
else:
reasons.append("missing_inventory_export_capability") reasons.append("missing_inventory_export_capability")
worker_env = str(worker.get("environment") or "").strip().lower() worker_env = str(worker.get("environment") or "").strip().lower()
@@ -428,10 +454,22 @@ def _build_failure_message(result: RpaWorkerReadiness) -> tuple[str, str]:
return RPA_WORKER_OFFLINE_MESSAGE, f"{RPA_WORKER_OFFLINE_MESSAGE}({detail})" return RPA_WORKER_OFFLINE_MESSAGE, f"{RPA_WORKER_OFFLINE_MESSAGE}({detail})"
def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness: def _check_rpa_worker_ready_for_capability(
*,
trigger_dir: Path | None,
required_capability: str,
extra_reasons: list[str] | None = None,
) -> RpaWorkerReadiness:
""" """
检查库存 RPA 触发前 worker 是否就绪。 通用 Worker 就绪检查:心跳存储、共享挂载、能力声明与环境隔离。
核心逻辑:Redis 可用、共享哨兵有效、最近心跳在 TTL 内、环境/scope 匹配。
Args:
trigger_dir: 待校验的共享 trigger 目录。
required_capability: 必选 Worker 能力。
extra_reasons: 调用方预检附加原因(凭据/队列等)。
Returns:
RpaWorkerReadiness。
""" """
checked_at = _utc_now_iso() checked_at = _utc_now_iso()
if not _heartbeat_check_required(): if not _heartbeat_check_required():
@@ -441,12 +479,11 @@ def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
checked_at=checked_at, checked_at=checked_at,
) )
reasons: list[str] = [] reasons: list[str] = list(extra_reasons or [])
if _heartbeat_redis_required() and _redis_client() is None: if _heartbeat_redis_required() and _redis_client() is None:
reasons.append("heartbeat_storage_unavailable") reasons.append("heartbeat_storage_unavailable")
trigger_dir = inventory_trigger_dir() _mount_ok, mount_reasons = _verify_shared_trigger_mount(trigger_dir)
mount_ok, mount_reasons = _verify_shared_trigger_mount(trigger_dir)
reasons.extend(mount_reasons) reasons.extend(mount_reasons)
backend_env = resolve_backend_rpa_environment() backend_env = resolve_backend_rpa_environment()
@@ -464,6 +501,7 @@ def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
backend_env=backend_env, backend_env=backend_env,
ttl_seconds=ttl_seconds, ttl_seconds=ttl_seconds,
now=now, now=now,
required_capability=required_capability,
) )
enriched = { enriched = {
**worker, **worker,
@@ -491,10 +529,29 @@ def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
blocking_mount = any(reason in mount_block_tokens for reason in reasons) or any( blocking_mount = any(reason in mount_block_tokens for reason in reasons) or any(
reason.startswith("shared_scope_mismatch") for reason in reasons reason.startswith("shared_scope_mismatch") for reason in reasons
) )
ready = bool(eligible_workers) and not blocking_mount and "heartbeat_storage_unavailable" not in reasons config_block_tokens = {
message, detail_message = ("ready", "ready") if ready else _build_failure_message( "credential_key_missing",
RpaWorkerReadiness(ready=False, message="", reasons=sorted(set(reasons))) "upload_queue_dir_not_configured",
"upload_queue_dir_not_accessible",
"callback_api_base_missing",
}
blocking_config = any(reason in config_block_tokens for reason in reasons)
ready = (
bool(eligible_workers)
and not blocking_mount
and not blocking_config
and "heartbeat_storage_unavailable" not in reasons
) )
if ready:
message, detail_message = "ready", "ready"
else:
failure = RpaWorkerReadiness(ready=False, message="", reasons=sorted(set(reasons)))
if required_capability == FREIGHT_UPLOAD_CAPABILITY:
detail = _summarize_reasons(failure.reasons)
message = RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE
detail_message = f"{message}({detail})" if detail else message
else:
message, detail_message = _build_failure_message(failure)
return RpaWorkerReadiness( return RpaWorkerReadiness(
ready=ready, ready=ready,
message=message, message=message,
@@ -505,6 +562,145 @@ def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
) )
def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
"""
检查库存 RPA 触发前 worker 是否就绪。
核心逻辑:Redis 可用、共享哨兵有效、最近心跳在 TTL 内、环境/scope 匹配。
"""
return _check_rpa_worker_ready_for_capability(
trigger_dir=inventory_trigger_dir(),
required_capability=INVENTORY_EXPORT_CAPABILITY,
)
def _freight_upload_config_reasons() -> list[str]:
"""
预检货代上传静态配置:凭据主密钥、上传队列目录、回调 API 基址。
Returns:
不合规原因码列表(空表示静态配置通过)。
"""
from app.services.shipping_notice.rpa import upload_queue_dir, upload_trigger_dir
reasons: list[str] = []
credential_key = _config_str("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", "")
if not credential_key:
reasons.append("credential_key_missing")
queue_dir = upload_queue_dir()
if queue_dir is None:
reasons.append("upload_queue_dir_not_configured")
elif not queue_dir.exists() or not queue_dir.is_dir():
reasons.append("upload_queue_dir_not_accessible")
# Worker 经 HXOPS_API_BASE / INTERNAL_API_BASE_URL 回调 upload-complete。
callback_base = (
_config_str("INTERNAL_API_BASE_URL", "")
or _config_str("HXOPS_API_BASE", "")
or _config_str("HXOPS_TOOLS_API_BASE", "")
)
if not callback_base:
reasons.append("callback_api_base_missing")
# 触发目录缺失由通用挂载检查覆盖;此处仅保证 upload_trigger 配置存在。
if upload_trigger_dir() is None:
reasons.append("trigger_dir_not_configured")
return reasons
def check_freight_upload_rpa_ready() -> RpaWorkerReadiness:
"""
检查货代上传 RPA 是否可安全自动触发。
核心逻辑:凭据/队列/回调基址预检 + 上传 trigger 共享挂载 + Worker 心跳与
freight_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。
Returns:
RpaWorkerReadiness(含 reasons 供建单前/启动日志展示)。
"""
from app.services.shipping_notice.rpa import upload_trigger_dir
return _check_rpa_worker_ready_for_capability(
trigger_dir=upload_trigger_dir(),
required_capability=FREIGHT_UPLOAD_CAPABILITY,
extra_reasons=_freight_upload_config_reasons(),
)
def assert_freight_upload_rpa_ready() -> None:
"""
写货代上传 trigger 前的强制就绪检查。
Raises:
ServiceUnavailableError: Worker/凭据/共享目录/回调基址未就绪。
"""
result = check_freight_upload_rpa_ready()
if result.ready:
return
code = "RPA.FREIGHT_UPLOAD_NOT_READY"
if "heartbeat_storage_unavailable" in result.reasons:
code = "RPA.HEARTBEAT_STORAGE_UNAVAILABLE"
elif "credential_key_missing" in result.reasons:
code = "RPA.CREDENTIAL_KEY_MISSING"
logger.warning(
"[rpa-heartbeat] freight upload readiness blocked code=%s reasons=%s detail=%s",
code,
result.reasons,
result.detail_message,
)
from app.services.shipping_notice.rpa import upload_trigger_dir
raise ServiceUnavailableError(
result.message,
code=code,
details={
"reasons": result.reasons,
"detail_message": result.detail_message,
"checked_at": result.checked_at,
"shared_scope_id": shared_scope_id(),
"trigger_dir": str(upload_trigger_dir() or ""),
"capability": FREIGHT_UPLOAD_CAPABILITY,
},
)
def log_auto_upload_readiness_at_startup(app: Any = None) -> RpaWorkerReadiness | None:
"""
应用启动时:若 AUTO_UPLOAD 显式开启则校验货代上传就绪并打日志(不阻断启动)。
Args:
app: Flask app;缺省用 current_app。
Returns:
校验结果;AUTO_UPLOAD 关闭时返回 None。
"""
flask_app = app
if flask_app is None:
flask_app = current_app
enabled = str(flask_app.config.get("SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED", False)).strip().lower() in {
"1", "true", "yes", "on",
}
if not enabled:
flask_app.logger.info(
"[rpa-upload] AUTO_UPLOAD disabled (fail-closed default); skip freight upload readiness"
)
return None
with flask_app.app_context():
result = check_freight_upload_rpa_ready()
if result.ready:
flask_app.logger.info(
"[rpa-upload] AUTO_UPLOAD enabled and freight upload RPA ready checked_at=%s",
result.checked_at,
)
else:
flask_app.logger.warning(
"[rpa-upload] AUTO_UPLOAD enabled but freight upload RPA NOT ready: %s reasons=%s",
result.detail_message or result.message,
result.reasons,
)
return result
def assert_inventory_rpa_worker_ready() -> None: def assert_inventory_rpa_worker_ready() -> None:
""" """
写 trigger 前的强制就绪检查。 写 trigger 前的强制就绪检查。
@@ -537,8 +733,11 @@ def assert_inventory_rpa_worker_ready() -> None:
def serialize_rpa_worker_status() -> dict[str, Any]: def serialize_rpa_worker_status() -> dict[str, Any]:
"""管理端展示:在线 worker 列表与就绪摘要(含详细 reasons)。""" """管理端展示:在线 worker 列表与库存/货代上传就绪摘要(含详细 reasons)。"""
from app.services.shipping_notice.rpa import upload_trigger_dir
readiness = check_inventory_rpa_worker_ready() readiness = check_inventory_rpa_worker_ready()
freight_readiness = check_freight_upload_rpa_ready()
ttl_seconds = _heartbeat_ttl_seconds() ttl_seconds = _heartbeat_ttl_seconds()
workers = [] workers = []
now = time.time() now = time.time()
@@ -570,6 +769,15 @@ def serialize_rpa_worker_status() -> dict[str, Any]:
"shared_scope_id": shared_scope_id(), "shared_scope_id": shared_scope_id(),
"shared_sentinel_name": shared_sentinel_name(), "shared_sentinel_name": shared_sentinel_name(),
"trigger_dir": str(inventory_trigger_dir() or ""), "trigger_dir": str(inventory_trigger_dir() or ""),
"upload_trigger_dir": str(upload_trigger_dir() or ""),
"reasons": readiness.reasons, "reasons": readiness.reasons,
"workers": workers, "workers": workers,
"freight_upload": {
"ready": freight_readiness.ready,
"message": freight_readiness.message,
"detail_message": freight_readiness.detail_message,
"reasons": freight_readiness.reasons,
"checked_at": freight_readiness.checked_at,
"auto_upload_enabled": _config_bool("SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED", False),
},
} }
@@ -1,14 +1,16 @@
""" """
services/shipping_notice/stp_progress_contract.py services/shipping_notice/stp_progress_contract.py
用途:冻结 STP 履约主链进度/审计事件名与 summary.stp_facts 键,供 UI 与审计双写对齐。 用途:冻结 STP 履约主链进度/审计事件名、summary.stp_facts 键,以及对话侧 progress_nodes。
依赖:无运行时依赖(纯常量契约)。 依赖:无运行时依赖(纯常量契约);project_task_progress_nodes 仅读 Task 字段。
逻辑:与 order-extraction 的 progress_audit_contract 分离;ui_state / log_task_event / 逻辑:与 order-extraction 的 progress_audit_contract 分离;ui_state / log_task_event /
工作台时间线 i18n 共同消费本契约,禁止前端自行发明事件码。 工作台时间线 i18n 共同消费本契约,禁止前端自行发明事件码或进度百分比。
""" """
from __future__ import annotations from __future__ import annotations
from typing import Any
# STP 履约任务事件(ShippingTaskEvent.event_type);前缀匹配亦用于审计双写。 # STP 履约任务事件(ShippingTaskEvent.event_type);前缀匹配亦用于审计双写。
STP_TASK_EVENT_TYPES: frozenset[str] = frozenset({ STP_TASK_EVENT_TYPES: frozenset[str] = frozenset({
'candidates_frozen', 'candidates_frozen',
@@ -46,3 +48,158 @@ STP_FACTS_ALLOWED_KEYS: frozenset[str] = frozenset({
'recovery_source_codes', 'recovery_source_codes',
'match_status', 'match_status',
}) })
# 对话 / UI State 统一节点状态(与前端 WorkflowNodeStatus 对齐)。
WORKFLOW_NODE_STATUSES: frozenset[str] = frozenset({
'pending',
'running',
'succeeded',
'retrying',
'failed',
'manual_takeover',
'skipped',
'rolled_back',
})
# 固定后台推进节点顺序;货代上传节点在 AUTO_UPLOAD 显式开启且 RPA 就绪时走自动上传,否则待人工。
STP_PROGRESS_NODE_DEFS: tuple[dict[str, str], ...] = (
{'code': 'customer_confirm', 'label': '客户确认'},
{'code': 'task_create', 'label': '创建 Task'},
{'code': 'inventory_prepare', 'label': '库存准备'},
{'code': 'inventory_match', 'label': '库存匹配'},
{'code': 'inventory_rpa', 'label': '库存 RPA'},
{'code': 'freight_upload', 'label': '货代上传'},
)
def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]:
"""
将 Task 投影为固定顺序的 progress_nodes(不含进度百分比)。
核心逻辑:按客户确认 / 进程状态 / pending_human_reason 映射 WorkflowNodeStatus;
货代上传节点在 Excel 就绪后为 manual_takeover(首期不启 RPA)。
Args:
task: ShippingTask 或兼容对象。
Returns:
[{code, label, status}, ...];顺序与 STP_PROGRESS_NODE_DEFS 一致。
"""
customer_status = str(getattr(task, 'customer_resolution_status', '') or '').strip().lower()
process_status = str(getattr(task, 'process_status', '') or '').strip().lower()
pending = str(getattr(task, 'pending_human_reason', '') or '').strip().lower()
match_status = str(getattr(task, 'match_status', '') or '').strip().lower()
review_status = str(getattr(task, 'review_status', '') or '').strip().lower()
has_export = bool(str(getattr(task, 'export_file_name', '') or '').strip())
terminal = process_status in {'uploaded', 'closed'}
freight_ready = process_status in {
'waiting_upload', 'upload_failed', 'export_ready', 'export_generated',
} or has_export
matched = process_status in {'matched', 'export_ready', 'export_generated', 'waiting_upload', 'upload_failed', 'uploaded', 'closed'} or has_export
inventory_ready = matched or process_status in {'inventory_ready', 'matching'}
inventory_preparing = process_status in {'waiting_inventory', 'parsed', 'created'}
rpa_active = pending in {'rpa_pending', 'rpa_exhausted'} or (
process_status == 'waiting_inventory' and pending in {'rpa_pending', 'inv_unavail', 'rpa_exhausted'}
)
match_blocked = (
review_status == 'shortage_review'
or pending in {'shortage', 'shortage_review'}
or match_status in {'shortage', 'multi_source_conflict', 'multi_file_conflict'}
)
# [STEP 1] 客户确认节点。
if customer_status in {'confirmed', 'auto_confirmed', 'user_confirmed'}:
customer_node = 'succeeded'
elif customer_status in {'ambiguous', 'conflicted'} or pending in {'customer_review', 'customer_ambiguous'}:
customer_node = 'manual_takeover'
elif customer_status in {'pending', 'unresolved', ''}:
customer_node = 'pending' if process_status in {'created', ''} else 'manual_takeover'
else:
customer_node = 'pending'
# [STEP 2] Task 已存在即创建成功。
task_create_node = 'succeeded'
# [STEP 3–5] 库存准备 / 匹配 / RPA。
if terminal or freight_ready or matched:
inventory_prepare_node = 'succeeded'
inventory_match_node = 'succeeded'
inventory_rpa_node = 'succeeded' if not rpa_active else 'manual_takeover'
elif match_blocked:
inventory_prepare_node = 'succeeded'
inventory_match_node = 'manual_takeover'
inventory_rpa_node = 'succeeded' if inventory_ready else 'pending'
elif rpa_active:
inventory_prepare_node = 'running' if pending == 'rpa_pending' else 'failed'
if pending == 'rpa_exhausted':
inventory_prepare_node = 'manual_takeover'
inventory_match_node = 'pending'
inventory_rpa_node = 'retrying' if pending == 'rpa_pending' else 'manual_takeover'
elif inventory_ready and process_status in {'inventory_ready', 'matching'}:
inventory_prepare_node = 'succeeded'
inventory_match_node = 'running'
inventory_rpa_node = 'succeeded'
elif inventory_preparing and customer_node == 'succeeded':
inventory_prepare_node = 'running'
inventory_match_node = 'pending'
inventory_rpa_node = 'pending'
elif customer_node != 'succeeded':
inventory_prepare_node = 'pending'
inventory_match_node = 'pending'
inventory_rpa_node = 'pending'
else:
inventory_prepare_node = 'pending'
inventory_match_node = 'pending'
inventory_rpa_node = 'pending'
# [STEP 6] 货代上传:RPA 进行中为 running/retrying;否则人工接管或成功。
if terminal:
freight_node = 'succeeded'
elif process_status == 'upload_failed' or pending == 'upload_rpa_failed':
freight_node = 'failed'
elif pending == 'upload_rpa_pending':
freight_node = 'running'
elif freight_ready:
freight_node = 'manual_takeover'
else:
freight_node = 'pending'
status_by_code = {
'customer_confirm': customer_node,
'task_create': task_create_node,
'inventory_prepare': inventory_prepare_node,
'inventory_match': inventory_match_node,
'inventory_rpa': inventory_rpa_node,
'freight_upload': freight_node,
}
nodes: list[dict[str, Any]] = []
for item in STP_PROGRESS_NODE_DEFS:
code = item['code']
status = status_by_code.get(code, 'pending')
if status not in WORKFLOW_NODE_STATUSES:
status = 'pending'
nodes.append({
'code': code,
'label': item['label'],
'status': status,
})
return nodes
def derive_overall_node_status(progress_nodes: list[dict[str, Any]] | None) -> str:
"""
从 progress_nodes 推导侧栏单值 node_status(非百分比)。
核心逻辑:失败/接管优先;否则取首个非 succeeded 节点;全成功则 succeeded。
"""
nodes = [item for item in (progress_nodes or []) if isinstance(item, dict)]
if not nodes:
return 'pending'
statuses = [str(item.get('status') or '').strip() for item in nodes]
for preferred in ('failed', 'manual_takeover', 'retrying', 'running', 'rolled_back', 'skipped'):
if preferred in statuses:
return preferred
if all(status == 'succeeded' for status in statuses):
return 'succeeded'
return 'pending'
@@ -2,8 +2,10 @@
services/shipping_notice/task_disposition_service.py services/shipping_notice/task_disposition_service.py
用途:集中处理发货任务的回收站、作废与归档生命周期,避免复用 process_status 的业务含义。 用途:集中处理发货任务的回收站、作废与归档生命周期,避免复用 process_status 的业务含义。
依赖:ShippingTask / ShippingTaskEvent、SQLAlchemy 行锁、ShippingCase 生命周期事实。 依赖:ShippingTask / ShippingTaskEvent、fulfillment_audit.record_fulfillment_audit、
逻辑:workspace 批量处置 API(后续阶段)通过本模块锁定任务、重算资格、写审计;编排与回调阶段读取本模块的 active 判定以阻断副作用。 SQLAlchemy 行锁、ShippingCase 生命周期事实。
逻辑:workspace 批量处置 API 通过本模块锁定任务、重算资格;TaskEvent 与 ShippingAuditEvent
双写稳定 reason_code;编排与回调阶段读取本模块的 active 判定以阻断副作用。
""" """
from __future__ import annotations from __future__ import annotations
@@ -179,6 +181,30 @@ def task_disposition_capability(
raise ValidationError('Unsupported task disposition action', code='SHIPPING.TASK_DISPOSITION_INVALID') raise ValidationError('Unsupported task disposition action', code='SHIPPING.TASK_DISPOSITION_INVALID')
def _disposition_reason_code(event_type: str, detail: dict[str, Any]) -> str | None:
"""
将处置事件映射为可解释性稳定 reason_code。
Args:
event_type: ShippingTaskEvent.event_type。
detail: 事件明细。
Returns:
稳定原因码;无法映射时 None。
"""
name = str(event_type or '').strip()
mapping = {
'task_voided': 'task_voided_for_correction',
'task_archived': 'task_archived',
'task_deleted': (
'task_voided_for_correction'
if str(detail.get('outcome') or '') == 'voided_and_deleted'
else 'task_cancelled_by_user'
),
}
return mapping.get(name)
def _write_disposition_event( def _write_disposition_event(
task: ShippingTask, task: ShippingTask,
*, *,
@@ -187,14 +213,47 @@ def _write_disposition_event(
request_id: str | None, request_id: str | None,
detail: dict[str, Any], detail: dict[str, Any],
) -> None: ) -> None:
"""以独立审计事件记录处置前后事实,避免任务字段覆盖后无法追溯。""" """
以独立审计事件记录处置前后事实,并双写统一 ShippingAuditEvent。
核心逻辑:TaskEvent 保留细粒度明细;顶层 reason_code 供审计中心筛选。
"""
payload = dict(detail or {})
reason_code = _disposition_reason_code(event_type, payload)
if reason_code:
payload.setdefault('reason_code', reason_code)
db.session.add(ShippingTaskEvent( db.session.add(ShippingTaskEvent(
task_id=int(task.id), task_id=int(task.id),
event_type=event_type, event_type=event_type,
actor_id=actor_id, actor_id=actor_id,
request_id=str(request_id or '').strip()[:64] or None, request_id=str(request_id or '').strip()[:64] or None,
detail_json=detail, detail_json=payload,
)) ))
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='shipping_task_disposition',
aggregate_type='shipping_task',
aggregate_id=str(task.task_no),
action=str(event_type)[:64],
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=str(task.task_no),
reason_code=reason_code,
result='success',
after={
'lifecycle_status': getattr(task, 'lifecycle_status', None),
'process_status': getattr(task, 'process_status', None),
},
metadata={
'dual_write': 'shipping_task_event',
'task_event_type': event_type,
'reason_code': reason_code,
'outcome': payload.get('outcome'),
},
source='workspace_api',
strict=True,
)
def move_task_to_recycle_bin( def move_task_to_recycle_bin(
@@ -2,8 +2,10 @@
services/shipping_notice/task_workflow.py services/shipping_notice/task_workflow.py
用途:发货通知任务/批次生命周期、解析与单头/订单行编辑的主编排入口。 用途:发货通知任务/批次生命周期、解析与单头/订单行编辑的主编排入口。
依赖:query_service、tool_common、decision_workflow、progress_workflow、state_machine、动态订单字段编辑器。 依赖:query_service、tool_common、decision_workflow、progress_workflow、state_machine、
逻辑:tools.py 门面委托本模块;建单只创建待动态订单抽取任务,人工编辑只更新锁定 Extraction 的 FieldValue。 fulfillment_audit、动态订单字段编辑器、candidate_qualification_service。
逻辑:tools.py 门面委托本模块;创建 Task 前强制客户已确认(禁止先建单再 customer_review);
retry_task 写入操作人与前后快照审计。
""" """
from __future__ import annotations from __future__ import annotations
@@ -58,13 +60,19 @@ from app.services.shipping_notice.batch_create_idempotency import (
normalize_create_idempotency_key, normalize_create_idempotency_key,
) )
from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task
from app.services.shipping_notice.candidate_qualification_service import (
assert_customer_confirmed_before_task_create,
resolve_confirmed_bill_to_customer_id,
)
from app.services.shipping_notice.tool_common import ( from app.services.shipping_notice.tool_common import (
generate_task_no, generate_task_no,
log_task_event, log_task_event,
resolve_workspace_actor_id,
set_task_step_progress, set_task_step_progress,
task_lifecycle_audit_snapshot,
) )
from app.services.shipping_notice.order_freeze_service import assert_task_order_is_editable from app.services.shipping_notice.order_freeze_service import assert_task_order_is_editable
from app.models import ShippingOrderReviewEvent from app.models import ShippingNoticeCandidate, ShippingOrderReviewEvent
EDITABLE_NOTICE_FIELDS = frozenset({"customer_name", "customer_code", "ship_to", "po_number", "required_date"}) EDITABLE_NOTICE_FIELDS = frozenset({"customer_name", "customer_code", "ship_to", "po_number", "required_date"})
EDITABLE_NOTICE_LINE_FIELDS = frozenset({ EDITABLE_NOTICE_LINE_FIELDS = frozenset({
@@ -264,6 +272,19 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
duplicate_resolution_type=resolution_type, duplicate_resolution_type=resolution_type,
created_by_id=payload.get("user_id"), created_by_id=payload.get("user_id"),
) )
# [STEP] 建 Task 前强制客户确认:候选 Bill-to confirmed / 业务单已绑客户 / 显式 customer_id。
item_customer_id = _parse_optional_customer_id(
item.get("customer_id") if item.get("customer_id") is not None else payload.get("customer_id"),
)
candidate = None
candidate_id = item.get("source_candidate_id")
if candidate_id is not None:
candidate = db.session.get(ShippingNoticeCandidate, int(candidate_id))
assert_customer_confirmed_before_task_create(
shipping_case=shipping_case,
candidate=candidate,
customer_id=item_customer_id,
)
task = ShippingTask( task = ShippingTask(
task_no=generate_task_no(), task_no=generate_task_no(),
shipping_case_id=shipping_case.id, shipping_case_id=shipping_case.id,
@@ -301,6 +322,13 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
log_task_event(task, "task_created", {"source_type": task.source_type, "batch_no": batch.batch_no}) log_task_event(task, "task_created", {"source_type": task.source_type, "batch_no": batch.batch_no})
try: try:
db.session.flush() db.session.flush()
_bind_confirmed_customer_after_task_create(
task,
shipping_case=shipping_case,
customer_id=item_customer_id,
candidate=candidate,
actor_id=payload.get("user_id"),
)
except IntegrityError as exc: except IntegrityError as exc:
db.session.rollback() db.session.rollback()
# 修订链唯一约束竞争:并发两个 create_revision 指向同一父任务 # 修订链唯一约束竞争:并发两个 create_revision 指向同一父任务
@@ -418,6 +446,12 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
batch = _create_single_task_batch(payload) batch = _create_single_task_batch(payload)
db.session.flush() db.session.flush()
shipping_case = resolve_shipping_case_for_new_task(created_by_id=payload.get("user_id")) shipping_case = resolve_shipping_case_for_new_task(created_by_id=payload.get("user_id"))
# [STEP] 单票建单同样要求客户已确认,禁止创建后进入 customer_review。
customer_id = _parse_optional_customer_id(payload.get("customer_id"))
assert_customer_confirmed_before_task_create(
shipping_case=shipping_case,
customer_id=customer_id,
)
task = ShippingTask( task = ShippingTask(
task_no=generate_task_no(), task_no=generate_task_no(),
shipping_case_id=shipping_case.id, shipping_case_id=shipping_case.id,
@@ -439,6 +473,13 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
db.session.add(task) db.session.add(task)
log_task_event(task, "task_created", {"source_type": task.source_type, "batch_no": batch.batch_no}) log_task_event(task, "task_created", {"source_type": task.source_type, "batch_no": batch.batch_no})
db.session.flush() db.session.flush()
_bind_confirmed_customer_after_task_create(
task,
shipping_case=shipping_case,
customer_id=customer_id,
candidate=None,
actor_id=payload.get("user_id"),
)
batch.current_focus_task_no = task.task_no batch.current_focus_task_no = task.task_no
recompute_batch_summary(batch) recompute_batch_summary(batch)
db.session.commit() db.session.commit()
@@ -452,6 +493,55 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
def _parse_optional_customer_id(raw: Any) -> int | None:
"""解析可选 customer_id;非法值抛 ValidationError。"""
if raw is None or raw == '':
return None
try:
return int(raw)
except (TypeError, ValueError) as exc:
raise ValidationError(
'customer_id must be an integer',
code='SHIPPING.CUSTOMER_CONFIRMATION_CUSTOMER_REQUIRED',
details={'field': 'customer_id'},
) from exc
def _bind_confirmed_customer_after_task_create(
task: ShippingTask,
*,
shipping_case: Any,
customer_id: int | None,
candidate: ShippingNoticeCandidate | None,
actor_id: Any,
) -> None:
"""
创建 Task 后立即绑定已确认客户,避免以 pending 进入 customer_review。
核心逻辑:业务单已有客户则标记 inherited;否则用显式 customer_id 或候选 Bill-to 确认。
"""
if getattr(shipping_case, 'customer_id', None) is not None:
task.customer_resolution_status = 'confirmed'
task.customer_resolution_method = task.customer_resolution_method or 'inherited'
return
bind_id = customer_id or resolve_confirmed_bill_to_customer_id(candidate=candidate)
if bind_id is None:
raise ConflictError(
'Customer must be confirmed before creating a shipping task',
code='SHIPPING.CUSTOMER_REQUIRED_BEFORE_TASK',
)
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
confirm_task_customer(
task,
customer_id=int(bind_id),
actor_id=int(actor_id) if actor_id is not None else None,
resolution_method='pre_task_confirmed',
commit=False,
)
def _clean_notice_text(value: Any) -> str | None: def _clean_notice_text(value: Any) -> str | None:
text = str(value or "").strip() text = str(value or "").strip()
return text or None return text or None
@@ -1024,9 +1114,10 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
重置单个任务到可重新自动推进的状态,并重新交给后台编排器。 重置单个任务到可重新自动推进的状态,并重新交给后台编排器。
【AI 触发时机】:当用户要求“重试当前票”“重新跑这张单据”时调用。 【AI 触发时机】:当用户要求“重试当前票”“重新跑这张单据”时调用。
核心逻辑:保留解析/库存/匹配等业务真相字段,仅清理错误与人工阻断,再恢复到当前数据所对应的最近可续跑状态。 核心逻辑:保留解析/库存/匹配等业务真相字段,仅清理错误与人工阻断,再恢复到当前数据所对应的最近可续跑状态;
写入操作人、前后生命周期快照与统一审计事件。
Args: Args:
payload: 必须能定位 task;可选 comment 记录重试原因。 payload: 必须能定位 task;可选 comment;工作台须传 operator_id/actor_id/_trusted_user_id。
Returns: Returns:
dict[str, Any]: Tool 标准响应,返回重置后的任务状态与是否成功触发后台编排。 dict[str, Any]: Tool 标准响应,返回重置后的任务状态与是否成功触发后台编排。
@@ -1042,6 +1133,11 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
return customer_gate return customer_gate
comment = str(payload.get("comment") or "").strip() comment = str(payload.get("comment") or "").strip()
actor_id = resolve_workspace_actor_id(payload)
event_source = str(payload.get("event_source") or ("workspace_api" if actor_id else "system")).strip() or "system"
before = task_lifecycle_audit_snapshot(task)
# [STEP 1] 清理阻断态并恢复到可续跑 process_status。
task.review_status = None task.review_status = None
task.pending_human_reason = None task.pending_human_reason = None
task.error_message = None task.error_message = None
@@ -1062,13 +1158,37 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
else: else:
task.process_status = "created" task.process_status = "created"
after = task_lifecycle_audit_snapshot(task)
log_task_event( log_task_event(
task, task,
"task_retry_requested", "task_retry_requested",
{ {
"comment": comment, "comment": comment,
"restored_process_status": task.process_status, "restored_process_status": task.process_status,
"reason_code": "task_retry_requested",
}, },
actor_id=actor_id,
source=event_source,
before=before,
after=after,
)
# [STEP 2] 统一审计中心留痕(TaskEvent 双写前缀不含 task_retry,故显式写入)。
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_retry_requested',
aggregate_type='shipping_task',
aggregate_id=str(task.task_no),
action='retry_task',
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=str(task.task_no),
conversation_id=getattr(task, 'conversation_id', None),
reason_code='task_retry_requested',
reason=comment or None,
before=before,
after=after,
metadata={'restored_process_status': task.process_status},
source=event_source,
) )
sync_batch_after_task_change(task) sync_batch_after_task_change(task)
db.session.commit() db.session.commit()
@@ -3,8 +3,10 @@ services/shipping_notice/tool_common.py
用途:发货通知 Tool 链共享配置、payload 合并、消息拼接与任务事件写入(无阶段业务编排)。 用途:发货通知 Tool 链共享配置、payload 合并、消息拼接与任务事件写入(无阶段业务编排)。
依赖:constants、models.ShippingTaskEvent、fulfillment_audit、stp_progress_contract。 依赖:constants、models.ShippingTaskEvent、fulfillment_audit、stp_progress_contract。
逻辑:task_workflow / inventory_workflow / fulfillment_workflow 共用;log_task_event 对 逻辑:task_workflow / inventory_workflow / fulfillment_workflow / decision_workflow 共用;
inventory_rpa_/inventory_source_/export_/STP 事件同步投影到 ShippingAuditEvent,失败阻断业务。 log_task_event 对 inventory_rpa_/inventory_source_/export_/notice_replace/
freight_cancellation_/STP 事件同步投影到 ShippingAuditEvent;
task_lifecycle_audit_snapshot / resolve_workspace_actor_id 供旧工作台写入口补齐审计四要素。
""" """
from __future__ import annotations from __future__ import annotations
@@ -317,7 +319,13 @@ def log_task_event(
from app.services.shipping_notice.stp_progress_contract import STP_AUDIT_DUAL_WRITE_PREFIXES from app.services.shipping_notice.stp_progress_contract import STP_AUDIT_DUAL_WRITE_PREFIXES
event_name = str(event_type or '') event_name = str(event_type or '')
dual_write = event_name.startswith(('inventory_rpa_', 'inventory_source_', 'export_')) or any( dual_write = event_name.startswith((
'inventory_rpa_',
'inventory_source_',
'export_',
'notice_replace',
'freight_cancellation_',
)) or any(
event_name.startswith(prefix) or event_name == prefix event_name.startswith(prefix) or event_name == prefix
for prefix in STP_AUDIT_DUAL_WRITE_PREFIXES for prefix in STP_AUDIT_DUAL_WRITE_PREFIXES
) )
@@ -363,6 +371,23 @@ def log_task_event(
meta[key] = value meta[key] = value
elif isinstance(value, list) and all(isinstance(item, (str, int, float, bool)) or item is None for item in value): elif isinstance(value, list) and all(isinstance(item, (str, int, float, bool)) or item is None for item in value):
meta[key] = value[:32] meta[key] = value[:32]
# [STEP] 顶层 reason_code:优先 detail/after,其次按事件类型映射可解释性稳定码
reason_from_detail = str(detail_obj.get('reason_code') or '').strip()
reason_from_after = ''
if isinstance(after, dict):
reason_from_after = str(after.get('reason_code') or '').strip()
reason_code = (
reason_from_detail
or reason_from_after
or _audit_reason_code_for_task_event(event_name, detail_obj)
)
if reason_code:
meta.setdefault('reason_code', reason_code)
is_failure = (
event_name.endswith('_failed')
or event_name.endswith('_exhausted')
or event_name.endswith('_extract_failed')
)
record_fulfillment_audit( record_fulfillment_audit(
event_type=f'task_{event_type}'[:64], event_type=f'task_{event_type}'[:64],
aggregate_type='shipping_task', aggregate_type='shipping_task',
@@ -371,7 +396,8 @@ def log_task_event(
actor_type='user' if actor_id is not None else 'system', actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id, actor_id=actor_id,
task_no=str(task.task_no), task_no=str(task.task_no),
result='success', reason_code=reason_code,
result='failure' if is_failure else 'success',
before=safe_before, before=safe_before,
after=safe_after or {'status': getattr(task, 'process_status', None)}, after=safe_after or {'status': getattr(task, 'process_status', None)},
metadata=meta, metadata=meta,
@@ -380,6 +406,105 @@ def log_task_event(
) )
def _audit_reason_code_for_task_event(event_type: str, detail: dict[str, Any]) -> str | None:
"""
将任务事件类型映射为可解释性稳定 reason_code,供审计中心筛选。
Args:
event_type: ShippingTaskEvent.event_type。
detail: 事件明细;可含 error / error_code。
Returns:
稳定原因码;无法映射时 None。
"""
name = str(event_type or '').strip()
err_blob = f"{detail.get('error') or ''} {detail.get('error_code') or ''}".lower()
mapping = {
'inventory_rpa_queued': 'inventory_rpa_queued',
'inventory_rpa_started': 'inventory_rpa_queued',
'inventory_rpa_timeout': 'inventory_rpa_timeout',
'inventory_rpa_exhausted': 'inventory_rpa_exhausted',
'inventory_rpa_failed': 'inventory_rpa_export_failed',
'notice_replaced': 'attachment_replaced',
'notice_replace_extract_failed': 'document_text_unavailable',
'freight_cancellation_completed': 'task_voided_for_correction',
'task_pending_void': 'task_cancelled_by_user',
'matched_multi_file_conflict': 'inventory_multi_file_conflict',
'matched_shortage': 'inventory_shortage_review_required',
'rpa_callback_rejected': 'late_callback_ignored',
'late_callback_ignored': 'late_callback_ignored',
}
if name in mapping:
code = mapping[name]
if name == 'inventory_rpa_failed':
if 'timeout' in err_blob:
return 'inventory_rpa_timeout'
if 'login' in err_blob or 'auth' in err_blob:
return 'inventory_rpa_login_failed'
if 'export' in err_blob:
return 'inventory_rpa_export_failed'
return 'inventory_rpa_export_failed'
if name == 'notice_replace_extract_failed':
from app.services.shipping_notice.error_explainability_contract import (
primary_attachment_reason_from_warnings,
)
from_warnings = primary_attachment_reason_from_warnings(
list(detail.get('warnings') or []),
)
return from_warnings or code
return code
if name.startswith('inventory_rpa_') and name.endswith('_failed'):
return 'inventory_rpa_export_failed'
if name.startswith('upload_rpa') and 'fail' in name:
return 'upload_rpa_failed'
return None
def task_lifecycle_audit_snapshot(task: ShippingTask) -> dict[str, Any]:
"""
投影任务生命周期白名单快照,供 ShippingTaskEvent / ShippingAuditEvent 前后对比。
核心逻辑:仅输出审计允许的 status/phase/reason_code;业务明细放 detail/metadata。
Args:
task: 当前 ShippingTask。
Returns:
可写入 before/after 的受控快照 dict(可能为空)。
"""
snapshot = {
'status': getattr(task, 'process_status', None),
'phase': getattr(task, 'current_step', None) or getattr(task, 'review_status', None),
'reason_code': getattr(task, 'pending_human_reason', None),
}
return {key: value for key, value in snapshot.items() if value is not None}
def resolve_workspace_actor_id(payload: dict[str, Any] | None) -> int | None:
"""
从 Tool/工作台 payload 解析操作人用户 ID。
核心逻辑:优先 operator_id / actor_id / _trusted_user_id / user_id。
Args:
payload: 路由或 Tool 入参。
Returns:
用户主键,无法解析时 None。
"""
if not isinstance(payload, dict):
return None
for key in ('operator_id', 'actor_id', '_trusted_user_id', 'user_id'):
raw = payload.get(key)
if raw is None or raw == '':
continue
try:
return int(raw)
except (TypeError, ValueError):
continue
return None
def log_task_action_event( def log_task_action_event(
task: ShippingTask, task: ShippingTask,
event_type: str, event_type: str,
@@ -388,11 +513,25 @@ def log_task_action_event(
source: str, source: str,
comment: str | None = None, comment: str | None = None,
extra: dict[str, Any] | None = None, extra: dict[str, Any] | None = None,
actor_id: int | None = None,
before: dict[str, Any] | None = None,
after: dict[str, Any] | None = None,
) -> None: ) -> None:
""" """
写入标准化任务动作事件。 写入标准化任务动作事件。
核心逻辑:在原始 event_type 之外,统一补足 reference_context 所需的动作元数据,避免各入口散落拼接。 核心逻辑:在原始 event_type 之外,统一补足 reference_context 所需的动作元数据,
并透传操作人与前后快照,避免各入口散落拼接。
Args:
task: 目标任务。
event_type: ShippingTaskEvent 事件码。
action: 标准化动作名(供 reference_context)。
source: 来源,如 workspace_api。
comment: 可选备注。
extra: 额外 detail 字段。
actor_id: 操作人用户 ID;系统动作可空。
before/after: 可选生命周期快照。
""" """
log_task_event( log_task_event(
task, task,
@@ -404,6 +543,10 @@ def log_task_action_event(
comment=comment, comment=comment,
extra=extra, extra=extra,
), ),
actor_id=actor_id,
source=source,
before=before,
after=after,
) )
@@ -2,8 +2,9 @@
services/shipping_notice/tool_response.py services/shipping_notice/tool_response.py
用途:统一构建发货通知 Tool 的 JSON 响应结构。 用途:统一构建发货通知 Tool 的 JSON 响应结构。
依赖:state_machine 中的 checkpoint/human_options/action_buttons 解析能力。 依赖:state_machine 中的 checkpoint/human_options/action_buttons 解析能力;ShippingProcessExecution。
逻辑:由 task_workflow、inventory_workflow、fulfillment_workflow 等 workflow 调用本文件,把状态机信息整理成一致的 Tool 响应。 逻辑:由 task_workflow、inventory_workflow、fulfillment_workflow 等 workflow 调用本文件,把状态机信息整理成一致的 Tool 响应;
已绑定 ProcessExecution 的任务不再下发旧 action_buttons / next_required_action(恢复仅由 Gate 驱动)。
""" """
from __future__ import annotations from __future__ import annotations
@@ -14,6 +15,28 @@ if TYPE_CHECKING:
from app.models import ShippingTask from app.models import ShippingTask
def _task_has_process_execution(task: ShippingTask | None) -> bool:
"""
判断任务是否已绑定 ProcessExecution(Gate 为恢复真相源)。
Args:
task: ShippingTask 或 None。
Returns:
存在任意关联 Execution 时为 True。
"""
if task is None or getattr(task, 'id', None) is None:
return False
from app.models import ShippingProcessExecution
return (
ShippingProcessExecution.query
.filter_by(task_id=int(task.id))
.first()
is not None
)
def _sanitize_user_facing_text(value: str) -> str: def _sanitize_user_facing_text(value: str) -> str:
""" """
清理会被 Agent 复述给业务用户的内部项目名。 清理会被 Agent 复述给业务用户的内部项目名。
@@ -64,6 +87,7 @@ def tool_response(
核心逻辑:未显式传 checkpoint 时从 task DB 状态推导 checkpoint/human_options/action_buttons; 核心逻辑:未显式传 checkpoint 时从 task DB 状态推导 checkpoint/human_options/action_buttons;
显式 checkpoint 优先(如 parse_ok、task_exists)。 显式 checkpoint 优先(如 parse_ok、task_exists)。
若任务已有 ProcessExecution:不再填充 action_buttons / next_required_action,避免与 Gate 双真相。
Args: Args:
stop_agent_turn: True 时要求 Agent 本回合停止,等待用户操作。 stop_agent_turn: True 时要求 Agent 本回合停止,等待用户操作。
@@ -79,6 +103,7 @@ def tool_response(
if task is not None and not task_id: if task is not None and not task_id:
task_id = task.task_no task_id = task.task_no
gate_owns_recovery = _task_has_process_execution(task)
resolved_checkpoint = checkpoint resolved_checkpoint = checkpoint
resolved_human_options = human_options resolved_human_options = human_options
resolved_action_buttons = action_buttons resolved_action_buttons = action_buttons
@@ -88,7 +113,8 @@ def tool_response(
resolved_checkpoint = ui.checkpoint resolved_checkpoint = ui.checkpoint
if human_options is None: if human_options is None:
resolved_human_options = ui.human_options resolved_human_options = ui.human_options
if action_buttons is None and ui.action_buttons: # [STEP] Gate 绑定任务:忽略状态机推导的旧动作按钮。
if not gate_owns_recovery and action_buttons is None and ui.action_buttons:
resolved_action_buttons = ui.action_buttons resolved_action_buttons = ui.action_buttons
payload: dict[str, Any] = { payload: dict[str, Any] = {
@@ -100,7 +126,11 @@ def tool_response(
payload["task_id"] = task_id payload["task_id"] = task_id
if resolved_human_options is not None: if resolved_human_options is not None:
payload["human_options"] = resolved_human_options payload["human_options"] = resolved_human_options
if resolved_action_buttons is not None:
# [STEP] ProcessExecution 存在时业务调用清零旧动作字段(含调用方显式传入)。
if gate_owns_recovery:
payload["action_buttons"] = []
elif resolved_action_buttons is not None:
payload["action_buttons"] = resolved_action_buttons payload["action_buttons"] = resolved_action_buttons
elif resolved_human_options is not None: elif resolved_human_options is not None:
payload["action_buttons"] = build_action_buttons(resolved_human_options) payload["action_buttons"] = build_action_buttons(resolved_human_options)
@@ -110,7 +140,7 @@ def tool_response(
payload["action_buttons"] = buttons payload["action_buttons"] = buttons
if resolved_checkpoint: if resolved_checkpoint:
payload["checkpoint"] = resolved_checkpoint payload["checkpoint"] = resolved_checkpoint
if next_required_action: if next_required_action and not gate_owns_recovery:
payload["next_required_action"] = _sanitize_user_facing_text(next_required_action) payload["next_required_action"] = _sanitize_user_facing_text(next_required_action)
if forbidden_next_tools: if forbidden_next_tools:
payload["forbidden_next_tools"] = forbidden_next_tools payload["forbidden_next_tools"] = forbidden_next_tools
@@ -118,4 +148,8 @@ def tool_response(
payload["stop_agent_turn"] = True payload["stop_agent_turn"] = True
if extra: if extra:
payload.update(extra) payload.update(extra)
# [STEP] extra 不得绕过 Gate 绑定任务的旧动作清零。
if gate_owns_recovery:
payload["action_buttons"] = []
payload.pop("next_required_action", None)
return payload return payload
@@ -5,7 +5,8 @@ services/shipping_notice/ui_state.py
依赖:models.ShippingTask/ShippingBatch、state_machine、query_service、constants、stp_progress_contract、 依赖:models.ShippingTask/ShippingBatch、state_machine、query_service、constants、stp_progress_contract、
process_gate_projection(统一 Gate 用户摘要)。 process_gate_projection(统一 Gate 用户摘要)。
逻辑:从 ShippingTask DB 字段经状态机解析 checkpoint/checkpoint_kind/action_buttons, 逻辑:从 ShippingTask DB 字段经状态机解析 checkpoint/checkpoint_kind/action_buttons,
再补充七步流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、stp_facts); 再补充七步流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、
stp_facts、progress_nodes);
若存在 ProcessExecution:阻断时清空 action_buttons;非阻断时仅保留 若存在 ProcessExecution:阻断时清空 action_buttons;非阻断时仅保留
download_excel / mark_manual_uploaded / refresh(恢复动作仅由 process_gate 驱动); download_excel / mark_manual_uploaded / refresh(恢复动作仅由 process_gate 驱动);
批次 UI 仅作会话上传集合摘要,不作为履约写操作面。 批次 UI 仅作会话上传集合摘要,不作为履约写操作面。
@@ -462,7 +463,8 @@ def _build_task_summary(
输出可解释任务摘要,供通知卡、人工复核与任务工作台同源消费。 输出可解释任务摘要,供通知卡、人工复核与任务工作台同源消费。
核心逻辑:保留 title/message/issues;补充 stage、checkpoint_kind、current_todo、 核心逻辑:保留 title/message/issues;补充 stage、checkpoint_kind、current_todo、
pause_reason、next_auto_step、event_at、entry_surface、allowed_actions、stp_facts。 pause_reason、next_auto_step、event_at、entry_surface、allowed_actions、stp_facts、
progress_nodes(固定节点顺序,禁止前端算百分比)。
""" """
title = user_facing_task_stage(task) title = user_facing_task_stage(task)
message_by_checkpoint: dict[str, str] = { message_by_checkpoint: dict[str, str] = {
@@ -541,6 +543,10 @@ def _build_task_summary(
} }
if stp_facts is not None: if stp_facts is not None:
summary['stp_facts'] = stp_facts summary['stp_facts'] = stp_facts
# [STEP] 对话侧固定节点梯;前端只渲染 status,不自行推导百分比。
from app.services.shipping_notice.stp_progress_contract import project_task_progress_nodes
summary['progress_nodes'] = project_task_progress_nodes(task)
return summary return summary
@@ -614,9 +620,16 @@ def _process_gate_user_summary_for_task(task: ShippingTask) -> dict[str, Any] |
from app.models import ShippingProcessExecution from app.models import ShippingProcessExecution
from app.services.shipping_notice.process_gate_projection import project_user_gate_summary from app.services.shipping_notice.process_gate_projection import project_user_gate_summary
task_id = getattr(task, 'id', None)
if task_id is None:
return None
try:
task_pk = int(task_id)
except (TypeError, ValueError):
return None
execution = ( execution = (
ShippingProcessExecution.query ShippingProcessExecution.query
.filter_by(task_id=int(task.id)) .filter_by(task_id=task_pk)
.order_by(ShippingProcessExecution.id.desc()) .order_by(ShippingProcessExecution.id.desc())
.first() .first()
) )
@@ -154,7 +154,11 @@ def record_manual_upload(task: ShippingTask, *, artifact_id: int | None, evidenc
asset_no = str(evidence_asset_no or '').strip() asset_no = str(evidence_asset_no or '').strip()
receipt_no = str(freight_ref_no or '').strip() receipt_no = str(freight_ref_no or '').strip()
if not asset_no or not receipt_no: if not asset_no or not receipt_no:
raise ValidationError('Manual upload receipt number and evidence are required', code='SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED') raise ValidationError(
'Manual upload receipt number and evidence are required',
code='SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED',
details={'reason_code': 'close_blocked_missing_receipt'},
)
from app.services.shipping_notice.task_disposition_service import task_is_active from app.services.shipping_notice.task_disposition_service import task_is_active
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
if not task_is_active(task): if not task_is_active(task):
@@ -163,7 +167,11 @@ def record_manual_upload(task: ShippingTask, *, artifact_id: int | None, evidenc
artifact = current_upload_artifact(task, artifact_id) artifact = current_upload_artifact(task, artifact_id)
asset = get_asset_for_user(asset_no, operator_id) asset = get_asset_for_user(asset_no, operator_id)
if asset.upload_status != 'ready' or asset.deleted_at is not None: if asset.upload_status != 'ready' or asset.deleted_at is not None:
raise ValidationError('Manual upload evidence is unavailable', code='SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED') raise ValidationError(
'Manual upload evidence is unavailable',
code='SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED',
details={'reason_code': 'close_blocked_missing_receipt'},
)
attempt = ShippingUploadAttempt( attempt = ShippingUploadAttempt(
artifact_id=artifact.id, artifact_id=artifact.id,
attempt_no=ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id).count() + 1, attempt_no=ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id).count() + 1,
@@ -1130,6 +1130,15 @@ def bind_cases_for_run(
for_update=True, for_update=True,
) )
if existing is not None and is_reparse_extraction_run(run): if existing is not None and is_reparse_extraction_run(run):
# ensure_run_review_cases() may run from multiple persistence
# checkpoints for the same terminal Run. Once this Run/Case is
# already current, do not create another ItemVersion.
if (
int(existing.current_run_id or 0) == int(run.id)
and int(existing.current_case_id or 0) == int(case.id)
):
items.append(existing)
continue
items.append( items.append(
mark_reparse_succeeded( mark_reparse_succeeded(
item=existing, item=existing,
@@ -1672,7 +1681,8 @@ def advance_workflow_item_after_confirm(
复核确认建单后推进 WorkflowItem 至 building_order(不关闭)。 复核确认建单后推进 WorkflowItem 至 building_order(不关闭)。
核心逻辑:绑定 current_task_no;写入 Version.task 指针;用户可见事件 + 审计。 核心逻辑:绑定 current_task_no;写入 Version.task 指针;用户可见事件 + 审计。
Phase 3 自动链随后继续 inventory_matching → generating_excel → manual_upload_pending。 Phase 3 自动链随后继续 inventory_matching → generating_excel;
AUTO_UPLOAD 开启且 RPA 就绪时进入 upload_rpa_pending,否则真正待人工上传。
Args: Args:
case: 已确认 Case。 case: 已确认 Case。
@@ -1739,11 +1749,13 @@ def sync_workflow_item_stage_for_task(
actor_id: str | int | None = None, actor_id: str | int | None = None,
payload: dict[str, Any] | None = None, payload: dict[str, Any] | None = None,
excel_artifact_no: str | None = None, excel_artifact_no: str | None = None,
stage: str | None = None,
) -> ShippingNoticeWorkflowItem | None: ) -> ShippingNoticeWorkflowItem | None:
""" """
按任务号将绑定的 WorkflowItem 推进到履约阶段,并写 WorkflowEvent + 审计。 按任务号将绑定的 WorkflowItem 推进到履约阶段,并写 WorkflowEvent + 审计。
核心逻辑:终态(cancelled/closed)不覆盖;待人工登记不写 closed_at,父批次仍保持 open。 核心逻辑:终态(cancelled/closed)不覆盖;待人工登记不写 closed_at,父批次仍保持 open;
允许 lifecycle 不变而仅更新细粒度 stage(如 upload_rpa_pending)。
Args: Args:
task_no: 任务号。 task_no: 任务号。
@@ -1752,6 +1764,7 @@ def sync_workflow_item_stage_for_task(
actor_*: 操作者。 actor_*: 操作者。
payload: 脱敏事件载荷。 payload: 脱敏事件载荷。
excel_artifact_no: 可选写入 Version.excel_artifact_no。 excel_artifact_no: 可选写入 Version.excel_artifact_no。
stage: 可选细粒度阶段码;缺省等于 lifecycle_status。
Returns: Returns:
更新后的 Item;未绑定则 None。 更新后的 Item;未绑定则 None。
@@ -1760,15 +1773,18 @@ def sync_workflow_item_stage_for_task(
if item is None: if item is None:
return None return None
target = str(lifecycle_status or '').strip().lower() target = str(lifecycle_status or '').strip().lower()
resolved_stage = str(stage or target or '').strip().lower()[:64] or target
if target not in WORKFLOW_ITEM_LIFECYCLE_STATUSES: if target not in WORKFLOW_ITEM_LIFECYCLE_STATUSES:
return item return item
if str(item.lifecycle_status or '') in {'cancelled', 'closed'}: if str(item.lifecycle_status or '') in {'cancelled', 'closed'}:
return item return item
if str(item.lifecycle_status or '') == target: lifecycle_unchanged = str(item.lifecycle_status or '') == target
stage_unchanged = str(item.current_stage or '') == resolved_stage
if lifecycle_unchanged and stage_unchanged:
return item return item
before = _item_snapshot(item) before = _item_snapshot(item)
item.lifecycle_status = target item.lifecycle_status = target
item.current_stage = target item.current_stage = resolved_stage
item.closed_at = None item.closed_at = None
version = _resolve_version(item) version = _resolve_version(item)
if version is not None and excel_artifact_no: if version is not None and excel_artifact_no:
@@ -1777,7 +1793,7 @@ def sync_workflow_item_stage_for_task(
_bump_lock(item) _bump_lock(item)
workflow = db.session.get(ShippingNoticeWorkflow, int(item.workflow_id)) workflow = db.session.get(ShippingNoticeWorkflow, int(item.workflow_id))
if workflow is not None: if workflow is not None:
_touch_workflow(workflow, stage=target) _touch_workflow(workflow, stage=resolved_stage)
db.session.flush() db.session.flush()
_audit( _audit(
event_type='workflow_stage_changed', event_type='workflow_stage_changed',
@@ -1787,7 +1803,7 @@ def sync_workflow_item_stage_for_task(
before=before, before=before,
after=_item_snapshot(item), after=_item_snapshot(item),
action='sync_stage', action='sync_stage',
reason_code=target, reason_code=resolved_stage or target,
task_no=str(task_no), task_no=str(task_no),
) )
if workflow is not None: if workflow is not None:
@@ -1796,8 +1812,8 @@ def sync_workflow_item_stage_for_task(
item=item, item=item,
version=version, version=version,
event_code=str(event_code)[:64], event_code=str(event_code)[:64],
stage_code=target, stage_code=resolved_stage,
message_code=f'shipping.workflow_item.stage.{target}', message_code=f'shipping.workflow_item.stage.{resolved_stage}',
actor_type=actor_type, actor_type=actor_type,
actor_id=actor_id or item.owner_user_id, actor_id=actor_id or item.owner_user_id,
payload=dict(payload or {}), payload=dict(payload or {}),
@@ -3,12 +3,16 @@ services/shipping_notice/workflow_progress_projection.py
用途:将 Workflow / WorkflowItem / WorkflowEvent 投影为工作台只读 DTO(计数、阶段、摘要)。 用途:将 Workflow / WorkflowItem / WorkflowEvent 投影为工作台只读 DTO(计数、阶段、摘要)。
依赖:ShippingNoticeWorkflow* 模型、ShippingNoticeDocument、ShippingOrderExtractionRun、 依赖:ShippingNoticeWorkflow* 模型、ShippingNoticeDocument、ShippingOrderExtractionRun、
workflow_ledger_service、progress_audit_contract、process_gate_projection。 ShippingTask、workflow_ledger_service、progress_audit_contract、process_gate_projection、
stp_progress_contract.project_task_progress_nodes。
逻辑:由 workspace/shipping_notice 工作流读接口调用;解决「Run 已建但 Item=0」—— 逻辑:由 workspace/shipping_notice 工作流读接口调用;解决「Run 已建但 Item=0」——
Item 在版面阶段即存在;会话投影返回全部 open Workflow(非仅第一条); Item 在版面阶段即存在;会话投影返回全部 open Workflow(非仅第一条);
counts.waiting_manual_upload 单独统计,不得并入 completed; counts.waiting_manual_upload 单独统计,不得并入 completed;
display_lifecycle_status / is_waiting_manual_upload / upload_phase 为上传态权威投影,
禁止调用方仅凭 lifecycle_status=manual_upload_pending 推断人工待办(RPA 中亦可能存该桶);
available_actions / reparse_kind 与 ledger 重识别资格同源,禁止前端自行推导; available_actions / reparse_kind 与 ledger 重识别资格同源,禁止前端自行推导;
用户提示优先消费统一 Gate 摘要(唯一当前阻断),不再平行拼旧五门禁文案。 用户提示优先消费统一 Gate 摘要(唯一当前阻断),不再平行拼旧五门禁文案;
绑定 Task 时附带 progress_nodes / node_status 供对话侧栏直接消费。
""" """
from __future__ import annotations from __future__ import annotations
@@ -40,6 +44,67 @@ _REPARSE_BLOCKED_LIFECYCLE = frozenset({
'generating_excel', 'generating_excel',
}) })
# 细粒度上传阶段:优先于宽生命周期展示,避免 RPA 中误显示「待人工上传」。
_UPLOAD_RPA_DISPLAY_STAGES = frozenset({
'upload_rpa_pending',
'upload_rpa_running',
'upload_rpa_failed',
})
def _display_lifecycle_status(item: ShippingNoticeWorkflowItem) -> str:
"""
解析用户可见生命周期标签:细粒度 current_stage 优先于 lifecycle_status。
Args:
item: WorkflowItem。
Returns:
展示用状态码。
"""
stage = str(item.current_stage or '').strip()
if stage in _UPLOAD_RPA_DISPLAY_STAGES:
return stage
return str(item.lifecycle_status or '').strip()
def _upload_phase(item: ShippingNoticeWorkflowItem) -> str:
"""
解析上传相位:供 UI/Gate 区分 RPA 运行与真正待人工上传。
Args:
item: WorkflowItem。
Returns:
none | rpa_pending | rpa_running | rpa_failed | manual_pending
"""
stage = str(item.current_stage or '').strip()
if stage == 'upload_rpa_pending':
return 'rpa_pending'
if stage == 'upload_rpa_running':
return 'rpa_running'
if stage == 'upload_rpa_failed':
return 'rpa_failed'
lifecycle = str(item.lifecycle_status or '').strip()
if lifecycle == 'manual_upload_pending' and stage not in _UPLOAD_RPA_DISPLAY_STAGES:
return 'manual_pending'
return 'none'
def _is_waiting_manual_upload(item: ShippingNoticeWorkflowItem) -> bool:
"""
是否真正等待人工上传/登记凭据。
核心逻辑:仅 upload_phase=manual_pending;RPA 运行/失败不得视为人工待办。
Args:
item: WorkflowItem。
Returns:
True 表示可提示用户人工上传。
"""
return _upload_phase(item) == 'manual_pending'
def _iso(value: datetime | None) -> str | None: def _iso(value: datetime | None) -> str | None:
"""UTC ISO8601;空值保持 None。""" """UTC ISO8601;空值保持 None。"""
@@ -70,8 +135,8 @@ def _item_counts(items: list[ShippingNoticeWorkflowItem]) -> dict[str, int]:
汇总 Workflow 内 Item 用户态计数。 汇总 Workflow 内 Item 用户态计数。
核心逻辑:processing 聚合 layout_parsing/extracting 及后续履约中态; 核心逻辑:processing 聚合 layout_parsing/extracting 及后续履约中态;
waiting_manual_upload 仅 manual_upload_pending(非完成); waiting_manual_upload 仅「真正待人工上传」(manual_upload_pending 且非 upload_rpa_*);
completed 仅 closed/cancelled。 RPA 上传中计入 processing;completed 仅 closed/cancelled。
""" """
from app.services.shipping_notice.progress_audit_contract import ( from app.services.shipping_notice.progress_audit_contract import (
WORKFLOW_ITEM_TERMINAL_LIFECYCLE_STATUSES, WORKFLOW_ITEM_TERMINAL_LIFECYCLE_STATUSES,
@@ -87,10 +152,18 @@ def _item_counts(items: list[ShippingNoticeWorkflowItem]) -> dict[str, int]:
'generating_excel', 'generating_excel',
'reparse_failed', 'reparse_failed',
}) })
rpa_stages = frozenset({
'upload_rpa_pending',
'upload_rpa_running',
'upload_rpa_failed',
})
counts = Counter() counts = Counter()
for item in items: for item in items:
status = str(item.lifecycle_status or '').strip() status = str(item.lifecycle_status or '').strip()
if status in processing_statuses: stage = str(item.current_stage or '').strip()
if stage in rpa_stages:
counts['processing'] += 1
elif status in processing_statuses:
counts['processing'] += 1 counts['processing'] += 1
elif status == 'pending_review': elif status == 'pending_review':
counts['pending_review'] += 1 counts['pending_review'] += 1
@@ -226,6 +299,8 @@ def serialize_workflow_item(
核心逻辑:附带当前/根 Document 文件名,供工作台列表直接展示 PDF 名; 核心逻辑:附带当前/根 Document 文件名,供工作台列表直接展示 PDF 名;
附带 available_actions / reparse_kind,供前端按权威契约展示按钮; 附带 available_actions / reparse_kind,供前端按权威契约展示按钮;
附带 display_lifecycle_status / is_waiting_manual_upload / upload_phase,
禁止调用方仅凭 lifecycle_status 推断人工待办;
若存在活动 ProcessExecution,附带统一 Gate 用户摘要(唯一阻断)。 若存在活动 ProcessExecution,附带统一 Gate 用户摘要(唯一阻断)。
Args: Args:
@@ -240,6 +315,7 @@ def serialize_workflow_item(
item, item,
run_status_by_no=run_status_by_no, run_status_by_no=run_status_by_no,
) )
upload_phase = _upload_phase(item)
payload: dict[str, Any] = { payload: dict[str, Any] = {
'item_no': str(item.item_no), 'item_no': str(item.item_no),
'workflow_no': str(item.workflow_no), 'workflow_no': str(item.workflow_no),
@@ -254,6 +330,11 @@ def serialize_workflow_item(
'current_task_no': str(item.current_task_no or '') or None, 'current_task_no': str(item.current_task_no or '') or None,
'lifecycle_status': str(item.lifecycle_status or ''), 'lifecycle_status': str(item.lifecycle_status or ''),
'current_stage': str(item.current_stage or ''), 'current_stage': str(item.current_stage or ''),
# 细粒度阶段优先:RPA 上传中不得被 UI 误读为「待人工上传」。
'display_lifecycle_status': _display_lifecycle_status(item),
# 权威人工待办布尔:调用方禁止用 lifecycle_status==manual_upload_pending 自行推断。
'is_waiting_manual_upload': _is_waiting_manual_upload(item),
'upload_phase': upload_phase,
'closed_reason': str(item.closed_reason or '') or None, 'closed_reason': str(item.closed_reason or '') or None,
'lock_version': int(item.lock_version or 1), 'lock_version': int(item.lock_version or 1),
'last_activity_at': _iso(item.last_activity_at), 'last_activity_at': _iso(item.last_activity_at),
@@ -271,6 +352,20 @@ def serialize_workflow_item(
payload['gate_user_hint'] = gate_summary.get('blocking_message') payload['gate_user_hint'] = gate_summary.get('blocking_message')
elif gate_summary.get('diagnostic_hint'): elif gate_summary.get('diagnostic_hint'):
payload['gate_user_hint'] = gate_summary.get('diagnostic_hint') payload['gate_user_hint'] = gate_summary.get('diagnostic_hint')
# [STEP] 绑定 Task 时投影固定节点梯,对话侧栏无需打开 Task 工作台。
task_no = str(item.current_task_no or '').strip()
if task_no:
from app.models import ShippingTask
from app.services.shipping_notice.stp_progress_contract import (
derive_overall_node_status,
project_task_progress_nodes,
)
task = ShippingTask.query.filter_by(task_no=task_no).first()
if task is not None:
progress_nodes = project_task_progress_nodes(task)
payload['progress_nodes'] = progress_nodes
payload['node_status'] = derive_overall_node_status(progress_nodes)
if include_events: if include_events:
events = ( events = (
ShippingNoticeWorkflowEvent.query ShippingNoticeWorkflowEvent.query
@@ -0,0 +1,66 @@
"""candidate qualification append-only history
Revision ID: f3b4c5d6e7f8
Revises: f4a5b6c7d8e0
Create Date: 2026-08-02 12:00:00.000000
用途:Candidate 资格评估改为追加式历史;每次评估保留独立快照行。
依赖:shipping_order_candidate_qualifications。
逻辑:去掉 candidate_id 唯一约束;新增 evaluation_seq / is_current。
"""
from alembic import op
import sqlalchemy as sa
revision = 'f3b4c5d6e7f8'
down_revision = 'f4a5b6c7d8e0'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""去掉唯一约束并增加追加式历史字段。"""
op.drop_constraint(
'uq_shipping_order_candidate_qualifications_candidate',
'shipping_order_candidate_qualifications',
type_='unique',
)
op.add_column(
'shipping_order_candidate_qualifications',
sa.Column('evaluation_seq', sa.Integer(), nullable=False, server_default='1'),
)
op.add_column(
'shipping_order_candidate_qualifications',
sa.Column('is_current', sa.Boolean(), nullable=False, server_default=sa.text('true')),
)
op.create_index(
'ix_ship_order_cand_qual_candidate_current',
'shipping_order_candidate_qualifications',
['candidate_id', 'is_current'],
)
op.create_index(
'ix_ship_order_cand_qual_candidate_seq',
'shipping_order_candidate_qualifications',
['candidate_id', 'evaluation_seq'],
unique=True,
)
def downgrade() -> None:
"""恢复每 Candidate 单行模型(仅保留当前行时需运维预清理历史)。"""
op.drop_index(
'ix_ship_order_cand_qual_candidate_seq',
table_name='shipping_order_candidate_qualifications',
)
op.drop_index(
'ix_ship_order_cand_qual_candidate_current',
table_name='shipping_order_candidate_qualifications',
)
op.drop_column('shipping_order_candidate_qualifications', 'is_current')
op.drop_column('shipping_order_candidate_qualifications', 'evaluation_seq')
op.create_unique_constraint(
'uq_shipping_order_candidate_qualifications_candidate',
'shipping_order_candidate_qualifications',
['candidate_id'],
)
@@ -0,0 +1,92 @@
"""add shipping order candidate qualifications
Revision ID: f4a5b6c7d8e0
Revises: d0e1f2a3b4c6
Create Date: 2026-08-02 02:40:00.000000
用途:新增 Candidate 级统一自动建单资格快照表。
依赖:shipping_notice_candidates、shipping_order_extraction_runs、users。
逻辑:模板质量资格与候选自动建单资格分离;每种解析来源共用同一资格状态枚举。
说明:原误用 revision e2f3a4b5c6d7(与 add_chat_tool_runs 冲突),已改为 f4a5b6c7d8e0。
"""
from alembic import op
import sqlalchemy as sa
revision = 'f4a5b6c7d8e0'
down_revision = 'd0e1f2a3b4c6'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""创建 shipping_order_candidate_qualifications。"""
op.create_table(
'shipping_order_candidate_qualifications',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column(
'candidate_id',
sa.Integer(),
sa.ForeignKey('shipping_notice_candidates.id'),
nullable=False,
),
sa.Column(
'run_id',
sa.Integer(),
sa.ForeignKey('shipping_order_extraction_runs.id'),
nullable=True,
),
sa.Column('status', sa.String(length=32), nullable=False),
sa.Column('qualification_score', sa.Float(), nullable=False, server_default='0'),
sa.Column('gate_results_json', sa.JSON(), nullable=False),
sa.Column('blocking_reason_codes_json', sa.JSON(), nullable=False),
sa.Column('parser_trace_json', sa.JSON(), nullable=False),
sa.Column('evidence_snapshot_json', sa.JSON(), nullable=False),
sa.Column('evaluator_version', sa.String(length=64), nullable=False),
sa.Column('evaluated_at', sa.DateTime(), nullable=False),
sa.Column('evaluated_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
sa.Column('request_id', sa.String(length=64), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint(
'candidate_id',
name='uq_shipping_order_candidate_qualifications_candidate',
),
sa.CheckConstraint(
"status IN ('eligible', 'review_required', 'blocked', 'rejected')",
name='ck_shipping_order_candidate_qualifications_status',
),
)
op.create_index(
'ix_shipping_order_candidate_qualifications_run_id',
'shipping_order_candidate_qualifications',
['run_id'],
)
op.create_index(
'ix_shipping_order_candidate_qualifications_status',
'shipping_order_candidate_qualifications',
['status'],
)
op.create_index(
'ix_ship_order_cand_qual_status_evaluated',
'shipping_order_candidate_qualifications',
['status', 'evaluated_at'],
)
def downgrade() -> None:
"""删除 Candidate 资格快照表。"""
op.drop_index(
'ix_ship_order_cand_qual_status_evaluated',
table_name='shipping_order_candidate_qualifications',
)
op.drop_index(
'ix_shipping_order_candidate_qualifications_status',
table_name='shipping_order_candidate_qualifications',
)
op.drop_index(
'ix_shipping_order_candidate_qualifications_run_id',
table_name='shipping_order_candidate_qualifications',
)
op.drop_table('shipping_order_candidate_qualifications')
+6
View File
@@ -0,0 +1,6 @@
[pytest]
markers =
pure_unit: skip Flask app/DB creation unless the test requests the app fixture
auto_rpa: enable shipping notice auto RPA / auto progress in test config
inventory_source_gate: skip default Dublin destination injection for inventory source gate tests
rpa_e2e: freight RPA end-to-end scenarios
-104
View File
@@ -1,104 +0,0 @@
"""Seed agents for freight shipping notice Chatflow orchestration."""
import sqlalchemy as sa
from app import create_app, db
from app.models import Agent
from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME
app = create_app()
CHAT_DESCRIPTION = "货代发货通知智能体:自然语言驱动解析、库存匹配、Excel 生成与货代上传(Tool 编排)"
def _normalize_url(raw: str | None) -> str | None:
if raw is None:
return None
text = str(raw).strip()
if not text:
return None
if (text.startswith("`") and text.endswith("`")) or (text.startswith('"') and text.endswith('"')):
text = text[1:-1].strip()
return text or None
def _ensure_pg_sequence(table: str, pk: str) -> None:
engine_name = db.engine.dialect.name
if engine_name != "postgresql":
return
if not table.replace("_", "").isalnum() or not pk.replace("_", "").isalnum():
raise ValueError("invalid identifier")
sql = sa.text(
f"SELECT setval(pg_get_serial_sequence(:tbl, :pk), COALESCE((SELECT MAX({pk}) FROM {table}), 0), true)"
)
db.session.execute(sql, {"tbl": table, "pk": pk})
db.session.commit()
def _upsert_agent(
*,
name: str,
description: str,
dify_app_type: str,
dify_app_id: str | None = None,
dify_api_key: str | None = None,
api_base_url: str | None = None,
agent_code: str = 'shipping_notice',
runtime_provider: str = 'hybrid',
conversation_mode: str = 'task_chat',
):
agent = Agent.query.filter_by(name=name).first()
extra_config = {'dify_app_type': dify_app_type}
if not agent:
agent = Agent(
name=name,
description=description,
type='api',
dify_app_id=dify_app_id,
dify_api_key=dify_api_key,
api_base_url=api_base_url,
extra_config=extra_config,
is_active=True,
agent_code=agent_code,
runtime_provider=runtime_provider,
conversation_mode=conversation_mode,
dify_app_type=dify_app_type,
)
db.session.add(agent)
print(f'Created agent: {name}')
else:
agent.description = description
agent.type = 'api'
agent.extra_config = extra_config
agent.agent_code = agent_code
agent.runtime_provider = runtime_provider
agent.conversation_mode = conversation_mode
agent.dify_app_type = dify_app_type
if dify_app_id:
agent.dify_app_id = dify_app_id
if dify_api_key:
agent.dify_api_key = dify_api_key
if api_base_url:
agent.api_base_url = api_base_url
agent.is_active = True
print(f'Updated agent: {name}')
return agent
if __name__ == "__main__":
import os
with app.app_context():
_ensure_pg_sequence("agents", "id")
chat_key = os.getenv("SHIPPING_NOTICE_CHAT_DIFY_API_KEY") or os.getenv("DIFY_API_KEY")
chat_base = _normalize_url(os.getenv("SHIPPING_NOTICE_CHAT_DIFY_BASE") or os.getenv("DIFY_API_BASE"))
_upsert_agent(
name=CHAT_AGENT_NAME,
description=CHAT_DESCRIPTION,
dify_app_type="chatflow",
dify_app_id=os.getenv("SHIPPING_NOTICE_CHAT_DIFY_APP_ID"),
dify_api_key=chat_key,
api_base_url=chat_base,
)
db.session.commit()
print("Shipping notice agents seeded.")
+28 -4
View File
@@ -4,7 +4,8 @@ tests/conftest.py
用途:Flask testing app、库存配置种子与测试隔离夹具。 用途:Flask testing app、库存配置种子与测试隔离夹具。
依赖:pytest、app.create_app、shipping inventory 模型。 依赖:pytest、app.create_app、shipping inventory 模型。
逻辑:各测试用例共享;Windows 下将 basetemp 固定到 backend/.pytest_tmp, 逻辑:各测试用例共享;Windows 下将 basetemp 固定到 backend/.pytest_tmp,
配合 pytest.ini 的 retention=0,避免 %TEMP%/pytest-current 清理 PermissionError。 配合 pytest.ini 的 retention=0,避免 %TEMP%/pytest-current 清理 PermissionError;
pure_unit 标记跳过 Flask/DB 创建,供契约类纯单测加速。
""" """
import shutil import shutil
@@ -13,6 +14,18 @@ from pathlib import Path
import pytest import pytest
def pytest_configure(config):
"""
注册自定义标记,避免 PytestUnknownMarkWarning。
pure_unit:契约类纯单测,跳过 Flask/DB 创建(见 _shipping_notice_stable_auto_config)。
"""
config.addinivalue_line(
'markers',
'pure_unit: skip Flask app/DB creation unless the test requests the app fixture',
)
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def _capture_legacy_order_rows_for_tests(monkeypatch): def _capture_legacy_order_rows_for_tests(monkeypatch):
"""将旧测试夹具的 lines_json 参数暂存为动态订单输入,生产模型不保留该属性。""" """将旧测试夹具的 lines_json 参数暂存为动态订单输入,生产模型不保留该属性。"""
@@ -94,8 +107,15 @@ def _isolate_persisted_settings(monkeypatch, tmp_path):
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def _shipping_notice_stable_auto_config(app, request, monkeypatch): def _shipping_notice_stable_auto_config(request, monkeypatch):
"""发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。""" """
发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。
标记 pure_unit 且未显式请求 app 的用例跳过 Flask/DB 创建,显著降低契约类单测耗时。
"""
if request.node.get_closest_marker("pure_unit") and "app" not in request.fixturenames:
return
app = request.getfixturevalue("app")
tmp_path = request.getfixturevalue("tmp_path") tmp_path = request.getfixturevalue("tmp_path")
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue") app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str( app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(
@@ -109,10 +129,14 @@ def _shipping_notice_stable_auto_config(app, request, monkeypatch):
"app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready", "app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready",
lambda: None, lambda: None,
) )
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat.assert_freight_upload_rpa_ready",
lambda: None,
)
return return
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
# STP 首期禁止货代 RPA 自动上传;单测默认与产品一致关闭。 # 货代自动上传默认 fail-closed;单测与产品默认一致关闭。
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
app.config["ENV_NAME"] = "dev" app.config["ENV_NAME"] = "dev"
@@ -375,7 +375,11 @@ def test_chat_stream_error_event_keeps_persisted_chat_log_id(app, monkeypatch):
error_event = next(event for event in events if event.get("event") == "error") error_event = next(event for event in events if event.get("event") == "error")
# 关键断言:持久化返回的主键必须沿原 error 事件继续向 relay 传播。 # 关键断言:持久化返回的主键必须沿原 error 事件继续向 relay 传播。
assert error_event["chat_log_id"] == 42 assert error_event["chat_log_id"] == 42
assert error_event["message"] assert error_event["message"] == "当前服务连接超时,请稍后重试。"
assert error_event["answer"] == error_event["message"]
serialized = json.dumps(error_event, ensure_ascii=False)
for technical_text in ("Dify", "API Key", "Base URL", "connect timed out", "[Error:"):
assert technical_text not in serialized
def test_chat_stream_read_timeout_after_answer_emits_terminal_event(app, monkeypatch): def test_chat_stream_read_timeout_after_answer_emits_terminal_event(app, monkeypatch):
+21 -1
View File
@@ -17,7 +17,10 @@ SCHEMA = {'fields': [
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'aliases': ['PO#', 'PO Number']}, {'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'aliases': ['PO#', 'PO Number']},
{'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'aliases': ['MPN', 'Part Number']}, {'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'aliases': ['MPN', 'Part Number']},
{'field_id': 'qty', 'field_code': 'qty'}, {'field_id': 'qty', 'field_code': 'qty'},
{'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line', 'aliases': ['Reservation ID']}, {
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line',
'aliases': ['Reservation ID', 'External reservation ID'],
},
{'field_id': 'allocation', 'field_code': 'allocation_id'}, {'field_id': 'allocation', 'field_code': 'allocation_id'},
{'field_id': 'source', 'field_code': 'inventory_source_hint', 'scope': 'line', 'aliases': ['Source Type']}, {'field_id': 'source', 'field_code': 'inventory_source_hint', 'scope': 'line', 'aliases': ['Source Type']},
]} ]}
@@ -63,6 +66,23 @@ def test_email_supplement_html_grid_merges_by_po_and_mpn_without_overwriting_pdf
assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn' assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn'
def test_email_supplement_external_reservation_id_alias_merges_real_mail_header():
"""真实邮件的 External reservation ID 表头必须按 Schema 别名补到订单行。"""
supplement = parse_email_allocation_tables(
content_hash='e' * 64,
html_tables=['''<table><tr><th>PO#</th><th>MPN</th><th>External reservation ID</th><th>Source Type</th><th>Allocated Qty</th></tr><tr><td>4518738152</td><td>D4-A08AR12000002</td><td>3000099143</td><td>DBS SIN</td><td>20</td></tr></table>'''],
schema_definition=SCHEMA,
)
merged = merge_email_supplements(
orders=[_order()], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
)
assert supplement['rows'][0]['reservation_id'] == '3000099143'
assert _value(merged[0]['lines'][0]['fields'], 'reservation') == '3000099143'
assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn'
def test_email_supplement_po_fallback_requires_one_reservation(): def test_email_supplement_po_fallback_requires_one_reservation():
"""缺 MPN 时只有唯一 Reservation 的 PO 可广播;多 Reservation 必须复核。""" """缺 MPN 时只有唯一 Reservation 的 PO 可广播;多 Reservation 必须复核。"""
one = {'document_id': 44, 'rows': [{'po_number': '4518738152', 'reservation_id': '2000484577', 'evidence': {}}]} one = {'document_id': 44, 'rows': [{'po_number': '4518738152', 'reservation_id': '2000484577', 'evidence': {}}]}
@@ -22,13 +22,14 @@ def _field(
code: str, code: str,
aliases: list[str], aliases: list[str],
*, *,
scope: str = 'line',
value_type: str = 'string', value_type: str = 'string',
enabled: bool = True, enabled: bool = True,
collection_mode: str = 'llm_extraction', collection_mode: str = 'llm_extraction',
) -> dict: ) -> dict:
"""构造一个启用的最小 Schema 字段配置。""" """构造一个启用的最小 Schema 字段配置。"""
return { return {
'field_id': f'id-{code}', 'field_code': code, 'scope': 'line', 'field_id': f'id-{scope}-{code}', 'field_code': code, 'scope': scope,
'value_type': value_type, 'enabled': enabled, 'display_name': code, 'value_type': value_type, 'enabled': enabled, 'display_name': code,
'aliases': aliases, 'normalizer_key': 'trim', 'aliases': aliases, 'normalizer_key': 'trim',
'validator_keys': ['positive_decimal'] if code == 'qty' else [], 'validator_keys': ['positive_decimal'] if code == 'qty' else [],
@@ -70,12 +71,36 @@ def test_table_contract_allows_case_distinct_aliases_and_matches_exact_case():
assert 'CUSTOMER PN' not in contract.header_to_field assert 'CUSTOMER PN' not in contract.header_to_field
def test_table_contract_rejects_forbidden_reservation_header(): def test_table_contract_allows_explicit_reservation_alias():
"""管理员不得把 Allocation/Internal/UUID 类表头配置成 Reservation ID。""" """显式 Schema 别名是表格字段映射的唯一来源,不受全局英文黑名单否定。"""
with pytest.raises(ValidationError) as caught: contract = compile_table_header_contract(_definition(_field('reservation_id', ['Allocation ID'])))
compile_table_header_contract(_definition(_field('reservation_id', ['Allocation ID'])))
assert caught.value.details['forbidden_reservation_headers'] == ['Allocation ID'] assert contract.header_to_field['Allocation ID'] == 'reservation_id'
def test_table_contract_allows_same_alias_across_header_and_line_scopes():
"""订单头和明细字段可同名;表格契约只消费 line scope 的列定义。"""
contract = compile_table_header_contract(_definition(
_field('reservation_id', ['Reservation ID'], scope='header'),
_field('reservation_id', ['Reservation ID'], scope='line'),
))
assert contract.header_to_field['Reservation ID'] == 'reservation_id'
assert contract.fields_by_code['reservation_id']['scope'] == 'line'
def test_table_contract_rejects_duplicate_alias_within_line_scope():
"""同一明细列不能映射到两个不同业务字段,错误需标明冲突双方。"""
with pytest.raises(ValidationError) as caught:
compile_table_header_contract(_definition(
_field('part_number', ['Part Number']),
_field('customer_part_number', ['Part Number']),
))
collision = caught.value.details['table_header_collisions'][0]
assert collision['field_code'] == 'customer_part_number'
assert collision['conflicts_with'] == 'part_number'
assert collision['scope'] == collision['conflicts_with_scope'] == 'line'
def test_table_contract_includes_internal_line_number(): def test_table_contract_includes_internal_line_number():
+76 -2
View File
@@ -1,9 +1,9 @@
""" """
backend/tests/test_rpa_worker_heartbeat.py backend/tests/test_rpa_worker_heartbeat.py
用途:货代库存 RPA Worker 心跳存储、共享目录校验、就绪检查与 API 契约单测。 用途:货代库存/上传 RPA Worker 心跳存储、共享目录校验、就绪检查与 API 契约单测。
依赖:rpa_worker_heartbeat、shipping_notice_tools heartbeat 路由。 依赖:rpa_worker_heartbeat、shipping_notice_tools heartbeat 路由。
逻辑:覆盖跨平台 scope、哨兵、Redis 策略、环境匹配与 fail-fast 断言。 逻辑:覆盖跨平台 scope、哨兵、Redis 策略、环境匹配、货代上传就绪与 fail-fast 断言。
""" """
from __future__ import annotations from __future__ import annotations
@@ -15,10 +15,14 @@ import pytest
from app.core.errors import ServiceUnavailableError from app.core.errors import ServiceUnavailableError
from app.services.shipping_notice.rpa_worker_heartbeat import ( from app.services.shipping_notice.rpa_worker_heartbeat import (
FREIGHT_UPLOAD_CAPABILITY,
INVENTORY_EXPORT_CAPABILITY, INVENTORY_EXPORT_CAPABILITY,
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE,
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE, RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
RPA_WORKER_OFFLINE_MESSAGE, RPA_WORKER_OFFLINE_MESSAGE,
assert_freight_upload_rpa_ready,
assert_inventory_rpa_worker_ready, assert_inventory_rpa_worker_ready,
check_freight_upload_rpa_ready,
check_inventory_rpa_worker_ready, check_inventory_rpa_worker_ready,
record_rpa_worker_heartbeat, record_rpa_worker_heartbeat,
resolve_backend_rpa_environment, resolve_backend_rpa_environment,
@@ -371,3 +375,73 @@ def test_shared_scope_id_derived_from_mount_path_when_env_missing(app, tmp_path)
with app.app_context(): with app.app_context():
assert shared_scope_id() == "hxops-rpa-test-data" assert shared_scope_id() == "hxops-rpa-test-data"
def _enable_freight_upload_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data"):
"""配置货代上传 trigger/queue 与心跳策略,供上传就绪单测复用。"""
upload_trigger = tmp_path / "upload_triggers"
upload_queue = tmp_path / "upload_queue"
upload_trigger.mkdir()
upload_queue.mkdir()
_write_shared_sentinel(upload_trigger, scope_id=scope_id)
app.config["ENV_NAME"] = "test"
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger)
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue)
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id
app.config["SHIPPING_NOTICE_RPA_CREDENTIAL_KEY"] = "dGVzdC1rZXktMzItYnl0ZXMtZm9yLWZlcm5ldCE="
app.config["INTERNAL_API_BASE_URL"] = "http://127.0.0.1:5052"
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
return upload_trigger
def test_check_freight_upload_rpa_ready_requires_freight_upload_capability(app, tmp_path):
"""仅 inventory_export 能力时货代上传不得 ready。"""
upload_trigger = _enable_freight_upload_checks(app, tmp_path)
with app.app_context():
record_rpa_worker_heartbeat(
_heartbeat_payload(
trigger_dir=str(upload_trigger),
shared_scope_id="hxops-rpa-test-data",
capabilities=[INVENTORY_EXPORT_CAPABILITY],
)
)
result = check_freight_upload_rpa_ready()
# 关键断言:缺少 freight_upload 能力必须阻断自动上传。
assert result.ready is False
assert any("missing_freight_upload_capability" in reason for reason in result.reasons)
def test_check_freight_upload_rpa_ready_when_worker_and_dirs_ok(app, tmp_path):
"""Worker 声明 freight_upload 且目录/凭据齐全时应 ready。"""
upload_trigger = _enable_freight_upload_checks(app, tmp_path)
with app.app_context():
record_rpa_worker_heartbeat(
_heartbeat_payload(
trigger_dir=str(upload_trigger),
shared_scope_id="hxops-rpa-test-data",
capabilities=[INVENTORY_EXPORT_CAPABILITY, FREIGHT_UPLOAD_CAPABILITY],
)
)
result = check_freight_upload_rpa_ready()
assert result.ready is True
def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path):
"""上传 fail-fast 须带 reasons,供建单前/触发时展示阻断原因。"""
from app.services.shipping_notice.rpa_worker_heartbeat import (
reset_rpa_worker_heartbeat_state_for_tests,
)
_enable_freight_upload_checks(app, tmp_path)
# 去掉凭据主密钥:即使 Redis 残留心跳,静态配置缺失也必须阻断。
app.config.pop("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", None)
reset_rpa_worker_heartbeat_state_for_tests()
with app.app_context():
with pytest.raises(ServiceUnavailableError) as exc_info:
assert_freight_upload_rpa_ready()
assert exc_info.value.message == RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE
reasons = (exc_info.value.details or {}).get("reasons", [])
assert "credential_key_missing" in reasons
@@ -1,9 +1,9 @@
""" """
tests/test_shipping_auto_build_workflow_gate.py tests/test_shipping_auto_build_workflow_gate.py
用途:验收自动建单五门禁——失败仅 Review Case、禁止 STP 自动建单;can_build 仍供人工确认。 用途:验收自动建单门禁——失败仅 Review Case、禁止 STP 自动建单;can_build 仍供人工确认。
依赖:order_build_eligibility_service、types.SimpleNamespace。 依赖:order_build_eligibility_service、types.SimpleNamespace。
逻辑:构造五门全绿 / 单门失败用例;断言 can_auto_create 与 failed_gates。 逻辑:构造 Candidate Qualification 全绿 / 单门失败用例;断言 can_auto_create 与 failed_gates。
""" """
from __future__ import annotations from __future__ import annotations
@@ -17,23 +17,43 @@ from app.services.shipping_notice.order_build_eligibility_service import (
) )
def test_auto_build_gates_pass_when_all_five_green(): def _candidate(**overrides):
"""五门全绿时 can_auto_create=True。""" """构造默认可通过资格的 Candidate 替身。"""
candidate = SimpleNamespace( base = dict(
acceptance_mode='automatic', acceptance_mode='automatic',
candidate_status='accepted', candidate_status='accepted',
extraction_source='profile',
classification_confidence=0.96,
evidence_json=[{'field': 'po'}], evidence_json=[{'field': 'po'}],
conflicts_json=None, conflicts_json=None,
duplicate_status='none', duplicate_status='none',
duplicate_resolution=None, duplicate_resolution=None,
missing_fields_json=[],
field_confidence_json={},
consumed_task_id=None,
structured_result_json={'customer': {'resolution_status': 'confirmed'}},
validation_status='ready',
)
base.update(overrides)
return SimpleNamespace(**base)
def test_auto_build_gates_pass_when_qualification_green(monkeypatch):
"""统一资格全绿时 can_auto_create=True。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': True},
) )
unit = SimpleNamespace(route_decision_json={'auto_create_approved': True})
run = SimpleNamespace(auto_freeze_policy_json={'enabled': True})
result = assess_auto_build_gates( result = assess_auto_build_gates(
fields_complete=True, fields_complete=True,
candidate=candidate, candidate=_candidate(),
unit=unit, unit=SimpleNamespace(route_decision_json={'auto_create_approved': True}),
run=run, run=SimpleNamespace(auto_freeze_policy_json={'enabled': True, 'emergency_stop': False}),
customer_resolved=True,
) )
assert result['can_auto_create'] is True assert result['can_auto_create'] is True
assert result['failed_gates'] == [] assert result['failed_gates'] == []
@@ -41,53 +61,82 @@ def test_auto_build_gates_pass_when_all_five_green():
assert all(result['gates'].values()) assert all(result['gates'].values())
def test_auto_build_gates_fail_without_approved_template(): def test_auto_build_gates_allow_without_approved_template(monkeypatch):
"""模板未批准 → Review Case,禁止自动建单。""" """模板未批准不再单独阻断自动建单(合格 Candidate 仍可放行)。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': True},
)
result = assess_auto_build_gates( result = assess_auto_build_gates(
fields_complete=True, fields_complete=True,
candidate=SimpleNamespace( candidate=_candidate(acceptance_mode='manual', candidate_status='provisional'),
acceptance_mode='manual',
candidate_status='provisional',
evidence_json=[{'field': 'po'}],
conflicts_json=None,
duplicate_status='none',
duplicate_resolution=None,
),
unit=SimpleNamespace(route_decision_json={'auto_create_approved': False}), unit=SimpleNamespace(route_decision_json={'auto_create_approved': False}),
run=SimpleNamespace(auto_freeze_policy_json={'enabled': True}), run=SimpleNamespace(auto_freeze_policy_json={'enabled': True, 'emergency_stop': False}),
customer_resolved=True,
) )
assert result['can_auto_create'] is False assert result['can_auto_create'] is True
assert 'approved_template' in result['failed_gates'] assert 'approved_template' not in result['failed_gates']
def test_auto_build_gates_fail_on_conflict_or_missing_quality(app): def test_auto_build_gates_fail_on_conflict_or_disabled_switch(monkeypatch):
"""冲突或质量门禁未过 → 不能自动建单。""" """冲突或自动建单开关关闭 → 不能自动建单。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
result = assess_auto_build_gates( result = assess_auto_build_gates(
fields_complete=True, fields_complete=True,
candidate=SimpleNamespace( candidate=_candidate(conflicts_json=[{'code': 'qty_conflict'}]),
acceptance_mode='automatic',
candidate_status='accepted',
evidence_json=[{'field': 'po'}],
conflicts_json=[{'code': 'qty_conflict'}],
duplicate_status='none',
duplicate_resolution=None,
),
unit=SimpleNamespace(route_decision_json={'auto_create_approved': True}), unit=SimpleNamespace(route_decision_json={'auto_create_approved': True}),
run=SimpleNamespace(auto_freeze_policy_json={'enabled': False}), run=SimpleNamespace(auto_freeze_policy_json={'enabled': False, 'emergency_stop': False}),
customer_resolved=True,
# schema 开关由参数控制
)
# 通过 monkeypatch 关闭 schema 开关
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': False},
)
result = assess_auto_build_gates(
fields_complete=True,
candidate=_candidate(conflicts_json=[{'code': 'qty_conflict'}]),
unit=SimpleNamespace(route_decision_json={'auto_create_approved': True}),
run=SimpleNamespace(auto_freeze_policy_json={'enabled': False, 'emergency_stop': False}),
customer_resolved=True,
) )
assert result['can_auto_create'] is False assert result['can_auto_create'] is False
assert 'no_conflict_or_duplicate' in result['failed_gates'] assert 'field_conflicts_resolved' in result['failed_gates']
assert 'quality_gate_passed' in result['failed_gates'] assert 'auto_create_enabled' in result['failed_gates']
def test_eligibility_can_build_independent_of_auto_create_gates(app, monkeypatch): def test_eligibility_can_build_independent_of_auto_create_gates(app, monkeypatch):
""" """
五门失败不阻断人工确认 can_build(库存/Reservation 齐备时)。 资格失败不阻断人工确认 can_build(库存/Reservation 齐备时)。
""" """
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': False},
)
monkeypatch.setattr( monkeypatch.setattr(
'app.services.shipping_notice.order_build_eligibility_service.list_database_inventory_sources', 'app.services.shipping_notice.order_build_eligibility_service.list_database_inventory_sources',
lambda enabled_only=True: [{'source_code': 'DBS_DUB'}], lambda enabled_only=True: [{'source_code': 'DBS_DUB'}],
) )
monkeypatch.setattr(
'app.services.shipping_notice.order_build_eligibility_service.classify_inventory_source_codes',
lambda codes: {
'available': list(codes or []),
'unavailable': [],
'unavailable_reasons': {},
},
)
monkeypatch.setattr( monkeypatch.setattr(
'app.services.shipping_notice.order_build_eligibility_service.evaluate_inventory_source_rules_for_field_values', 'app.services.shipping_notice.order_build_eligibility_service.evaluate_inventory_source_rules_for_field_values',
lambda **kwargs: SimpleNamespace( lambda **kwargs: SimpleNamespace(
@@ -96,6 +145,7 @@ def test_eligibility_can_build_independent_of_auto_create_gates(app, monkeypatch
can_build=True, can_build=True,
block_reason=None, block_reason=None,
matched_rule_ids=[1], matched_rule_ids=[1],
matched_rules=(),
evidence={}, evidence={},
), ),
) )
@@ -109,19 +159,46 @@ def test_eligibility_can_build_independent_of_auto_create_gates(app, monkeypatch
header_by_code={}, header_by_code={},
lines=[{'reservation_id': '2000484577', 'part_number': 'PN-1', 'qty': '2'}], lines=[{'reservation_id': '2000484577', 'part_number': 'PN-1', 'qty': '2'}],
line_metas=[{'line_key': 'L1'}], line_metas=[{'line_key': 'L1'}],
candidate=SimpleNamespace( candidate=_candidate(
acceptance_mode='manual', acceptance_mode='manual',
candidate_status='provisional', candidate_status='provisional',
evidence_json=[], evidence_json=[],
conflicts_json=None,
duplicate_status='none',
duplicate_resolution=None,
), ),
unit=SimpleNamespace(route_decision_json={'auto_create_approved': False}), unit=SimpleNamespace(route_decision_json={'auto_create_approved': False}),
run=SimpleNamespace(auto_freeze_policy_json={'enabled': False}), run=SimpleNamespace(auto_freeze_policy_json={'enabled': False}),
customer_resolved=True,
) )
# 关键断言:人工可建单,但自动建单被五门阻断。 # 关键断言:人工可建单,但自动建单被阻断;用户侧仅一条资格阻断 Finding。
assert result['can_build'] is True assert result['can_build'] is True
assert result['can_auto_create'] is False assert result['can_auto_create'] is False
assert 'approved_template' in result['failed_gates'] assert 'auto_create_enabled' in result['failed_gates'] or 'evidence_complete' in result['failed_gates']
assert any(item.get('severity') == 'auto_create_blocking' for item in result['issues']) auto_issues = [item for item in result['issues'] if item.get('severity') == 'auto_create_blocking']
assert len(auto_issues) == 1
assert auto_issues[0].get('code') == 'candidate_qualification_blocked'
assert not any(str(item.get('code') or '').startswith('auto_build_gate_') for item in result['issues'])
def test_auto_build_customer_failure_owns_customer_resolution(monkeypatch):
"""客户未确认归属 customer_resolution,不平行投影多个用户阻断。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': True},
)
result = assess_auto_build_gates(
fields_complete=True,
candidate=_candidate(
structured_result_json={'customer': {'resolution_status': 'ambiguous'}},
),
unit=SimpleNamespace(route_decision_json={'auto_create_approved': True}),
run=SimpleNamespace(auto_freeze_policy_json={'enabled': True, 'emergency_stop': False}),
customer_resolved=None,
)
assert result['can_auto_create'] is False
assert result['user_blocking_finding']['owning_gate_code'] == 'customer_resolution'
assert result['user_blocking_finding']['reason_code'] == 'customer_ambiguous'
blocking = [f for f in result['findings'] if f.get('severity') == 'blocking']
assert len(blocking) == 1
@@ -0,0 +1,36 @@
"""
tests/test_shipping_auto_upload_config_align.py
用途:锁定 AUTO_UPLOAD 配置默认与服务层回退一致(生产安全 fail-closed)。
依赖:fulfillment_workflow、pytest、Flask app。
逻辑:断言键缺失时回退 False;显式 true/false 时尊重配置。
"""
from __future__ import annotations
def test_auto_upload_defaults_false_when_config_key_missing(app) -> None:
"""配置键缺失时与 settings 默认一致为 False,禁止缺省即自动上传。"""
with app.app_context():
from app.services.shipping_notice.fulfillment_workflow import is_auto_upload_enabled
app.config.pop('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', None)
assert is_auto_upload_enabled() is False
def test_auto_upload_respects_explicit_false(app) -> None:
"""显式关闭时必须为 False。"""
with app.app_context():
from app.services.shipping_notice.fulfillment_workflow import is_auto_upload_enabled
app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = False
assert is_auto_upload_enabled() is False
def test_auto_upload_respects_explicit_true(app) -> None:
"""显式开启时必须为 True。"""
with app.app_context():
from app.services.shipping_notice.fulfillment_workflow import is_auto_upload_enabled
app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = True
assert is_auto_upload_enabled() is True
@@ -0,0 +1,286 @@
"""
tests/test_shipping_candidate_qualification.py
用途:验收 Candidate 统一自动建单资格——三种解析来源、模板未批准可放行、LLM 可放行。
依赖:candidate_qualification_service、types.SimpleNamespace。
逻辑:构造合格/失败候选;断言 status、原因码与 parser_trace 不含硬性模板门禁。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.shipping_notice.candidate_qualification_service import (
evaluate_candidate_qualification,
)
from app.services.shipping_notice.order_build_eligibility_service import assess_auto_build_gates
def _eligible_candidate(**overrides):
"""构造默认可通过资格评估的 Candidate 替身。"""
base = dict(
candidate_status='accepted',
acceptance_mode='automatic',
extraction_source='profile',
classification_confidence=0.96,
confidence=0.96,
missing_fields_json=[],
field_confidence_json={},
evidence_json=[{'field': 'po_number'}],
conflicts_json=None,
duplicate_status='none',
duplicate_resolution=None,
consumed_task_id=None,
structured_result_json={
'customer': {'resolution_status': 'user_confirmed'},
},
validation_status='ready',
)
base.update(overrides)
return SimpleNamespace(**base)
def test_profile_unapproved_but_qualified_candidate_is_eligible(monkeypatch):
"""模板未批准但 Candidate 合格 → eligible,允许自动建单。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': True},
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
candidate = _eligible_candidate(extraction_source='profile')
unit = SimpleNamespace(route_decision_json={
'route_type': 'profile_deterministic',
'auto_create_approved': False,
'selected_profile_id': 12,
'selected_profile_code': 'DEMO',
})
result = evaluate_candidate_qualification(
candidate=candidate,
unit=unit,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['status'] == 'eligible'
assert result['can_auto_create'] is True
assert result['parser_trace']['profile_auto_create_approved'] is False
assert 'profile_not_auto_freeze_approved' not in result['blocking_reason_codes']
def test_llm_candidate_can_pass_unified_gates(monkeypatch):
"""LLM Candidate 具备分类/字段置信度与证据时可通过统一门禁 → eligible。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': True, 'minimum_confidence': 0.85},
)
candidate = _eligible_candidate(
extraction_source='llm',
classification_confidence=0.96,
field_confidence_json={
'po_number': {
'confidence': 0.95,
'minimum_confidence': 0.85,
'auto_create_key_field': True,
},
},
evidence_json=[{'field': 'po_number'}],
)
unit = SimpleNamespace(route_decision_json={
'route_type': 'llm_assisted_review',
'auto_create_approved': False,
})
result = evaluate_candidate_qualification(
candidate=candidate,
unit=unit,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['status'] == 'eligible'
assert result['parser_trace']['parser_source'] == 'llm_assisted'
assert result['confidence_policy']['source'] == 'schema_auto_creation_policy'
assert 'llm_path_cannot_auto_freeze' not in result['blocking_reason_codes']
def test_missing_classification_confidence_blocks(monkeypatch):
"""分类置信度缺失时 fail-closed(无人工确认)。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
candidate = _eligible_candidate(
classification_confidence=None,
confidence=None,
)
result = evaluate_candidate_qualification(
candidate=candidate,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['can_auto_create'] is False
assert 'classification_confidence' in result['failed_gates']
def test_llm_missing_field_confidence_blocks(monkeypatch):
"""LLM 路径缺少字段级置信度时不得自动建单。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
candidate = _eligible_candidate(
extraction_source='llm',
field_confidence_json={},
)
unit = SimpleNamespace(route_decision_json={'route_type': 'llm_assisted'})
result = evaluate_candidate_qualification(
candidate=candidate,
unit=unit,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['can_auto_create'] is False
assert 'key_fields_minimum_confidence' in result['failed_gates']
def test_deterministic_without_confidence_requires_validation_ready(monkeypatch):
"""确定性解析器无字段置信度时,validation 未就绪不得隐式放行。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
candidate = _eligible_candidate(
extraction_source='profile',
field_confidence_json={},
validation_status='pending',
missing_fields_json=['po_number'],
)
result = evaluate_candidate_qualification(
candidate=candidate,
unit=SimpleNamespace(route_decision_json={'route_type': 'profile_deterministic'}),
fields_complete=None,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['can_auto_create'] is False
assert 'key_fields_minimum_confidence' in result['failed_gates']
assert result['confidence_policy']['source'] in {
'schema_auto_creation_policy',
'key_field_minimum_confidence',
'default_fallback_0_85',
}
def test_generic_candidate_failure_has_concrete_reason_codes(monkeypatch):
"""通用解析失败 Candidate 必须给出具体原因码。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
candidate = _eligible_candidate(
extraction_source='generic',
evidence_json=[],
conflicts_json=[{'code': 'qty_conflict'}],
classification_confidence=0.2,
duplicate_status='unchecked',
)
result = evaluate_candidate_qualification(
candidate=candidate,
unit=SimpleNamespace(route_decision_json={'route_type': 'generic_deterministic'}),
fields_complete=False,
customer_resolved=False,
schema_auto_create_enabled=True,
)
assert result['status'] in {'blocked', 'review_required'}
assert result['can_auto_create'] is False
assert 'evidence_missing' in result['blocking_reason_codes']
assert 'field_conflict' in result['blocking_reason_codes']
assert 'required_field_missing' in result['blocking_reason_codes']
assert 'duplicate_unresolved' in result['blocking_reason_codes'] or 'duplicate_resolved' in result['failed_gates']
assert any(code.startswith('customer_') for code in result['blocking_reason_codes'])
def test_duplicate_unchecked_blocks_auto_create(monkeypatch):
"""重复检测未完成(unchecked)不得放行自动建单。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
candidate = _eligible_candidate(duplicate_status='unchecked', duplicate_resolution=None)
result = evaluate_candidate_qualification(
candidate=candidate,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['can_auto_create'] is False
assert 'duplicate_resolved' in result['failed_gates']
def test_duplicate_create_revision_and_force_create_count_as_resolved(monkeypatch):
"""复核裁决 create_revision / force_create 须通过 duplicate_resolved 门禁。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
for action in ('create_revision', 'force_create'):
candidate = _eligible_candidate(
duplicate_status='possible_duplicate',
duplicate_resolution=action,
)
result = evaluate_candidate_qualification(
candidate=candidate,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['gates']['duplicate_resolved'] is True, action
assert 'duplicate_resolved' not in result['failed_gates'], action
def test_evidence_without_field_binding_blocks(monkeypatch):
"""证据条目未绑定字段时不得仅凭非空 list 放行。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
candidate = _eligible_candidate(evidence_json=[{'page': 1, 'note': 'unrelated'}])
result = evaluate_candidate_qualification(
candidate=candidate,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['can_auto_create'] is False
assert 'evidence_complete' in result['failed_gates']
def test_assess_auto_build_gates_no_longer_requires_approved_template(monkeypatch):
"""建单资格服务不再把 approved_template 作为必要门禁。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': True},
)
result = assess_auto_build_gates(
fields_complete=True,
candidate=_eligible_candidate(),
unit=SimpleNamespace(route_decision_json={'auto_create_approved': False}),
run=SimpleNamespace(auto_freeze_policy_json={'enabled': True, 'emergency_stop': False}),
customer_resolved=True,
)
# 关键断言:模板未批准仍可自动建单;门禁键不含 approved_template。
assert 'approved_template' not in result['gates']
assert result['can_auto_create'] is True
assert result['qualification']['status'] == 'eligible'
@@ -0,0 +1,98 @@
"""
tests/test_shipping_chat_workbench_audit.py
用途:锁定双工作台阶段 5–6 对话侧 / 资格 / 节点审计字典与查询分组。
依赖:progress_audit_contract、audit_query_service、pytest。
逻辑:断言 chat_* / qualification / workflow_node 事件冻结;分组筛选映射正确。
"""
from __future__ import annotations
from app.services.shipping_notice.audit_query_service import _apply_filters
from app.services.shipping_notice.progress_audit_contract import (
CANDIDATE_QUALIFICATION_AUDIT_EVENT_TYPES,
CHAT_WORKBENCH_AUDIT_EVENT_TYPES,
PROCESS_GATE_AUDIT_EVENT_TYPES,
WORKFLOW_NODE_AUDIT_EVENT_TYPES,
)
from app.services.shipping_notice.process_gate_recovery_service import (
_chat_process_gate_event_type,
)
def test_chat_workbench_audit_events_are_frozen() -> None:
"""对话侧恢复与轻量动作事件必须冻结,禁止前端私造。"""
required = {
'chat_candidate_viewed',
'chat_task_viewed',
'chat_task_refocused',
'chat_customer_confirmed',
'chat_task_retried',
'chat_process_gate_taken_over',
'chat_process_gate_retried',
'chat_process_gate_skipped',
}
assert required.issubset(CHAT_WORKBENCH_AUDIT_EVENT_TYPES)
def test_qualification_and_workflow_node_audit_events_are_frozen() -> None:
"""资格评估与节点生命周期事件字典须覆盖阶段 6 清单关键项。"""
assert 'candidate_qualification_evaluated' in CANDIDATE_QUALIFICATION_AUDIT_EVENT_TYPES
assert 'review_qualification_evaluated' in CANDIDATE_QUALIFICATION_AUDIT_EVENT_TYPES
for code in (
'task_created',
'workflow_node_started',
'workflow_node_succeeded',
'workflow_node_failed',
'workflow_node_retried',
'workflow_node_taken_over',
'upload_rpa_triggered',
):
assert code in WORKFLOW_NODE_AUDIT_EVENT_TYPES
def test_chat_process_gate_event_mapping() -> None:
"""retry → retried;人工动作 → taken_over;skip → skipped。"""
assert _chat_process_gate_event_type(
action_code='retry_inventory_matching',
trigger_type='user_retry',
) == 'chat_process_gate_retried'
assert _chat_process_gate_event_type(
action_code='open_order_review',
trigger_type='user_manual',
) == 'chat_process_gate_taken_over'
assert _chat_process_gate_event_type(
action_code='skip_gate_demo',
trigger_type='user_manual',
) == 'chat_process_gate_skipped'
def test_audit_event_type_group_filters_use_frozen_dictionaries(app) -> None:
"""
event_type_group 须映射到冻结字典(编译为 IN 子句)。
断言:各分组产生的 SQL 文本包含对应字典中至少一个已知事件码。
"""
from app.models import ShippingAuditEvent
with app.app_context():
base = ShippingAuditEvent.query
cases = (
('chat_workbench', 'chat_process_gate_retried'),
('process_gate', 'process_gate_recovery_requested'),
('candidate_qualification', 'candidate_qualification_evaluated'),
('workflow_node', 'upload_rpa_triggered'),
('review_workbench', 'review_confirmed'),
)
for group, marker in cases:
filtered = _apply_filters(base, filters={'event_type_group': group})
sql = str(filtered.statement.compile(compile_kwargs={'literal_binds': True}))
# 关键断言:分组筛选把冻结事件码编入 WHERE IN。
assert marker in sql
assert 'event_type' in sql.lower()
def test_process_gate_dictionary_still_covers_recovery() -> None:
"""Process Gate 原事件字典不得因 chat_* 语义事件而缺恢复码。"""
assert 'process_gate_recovery_requested' in PROCESS_GATE_AUDIT_EVENT_TYPES
assert 'process_gate_technical_retry' in PROCESS_GATE_AUDIT_EVENT_TYPES
@@ -170,12 +170,15 @@ def test_workspace_customer_search_and_confirmation_api(app, client):
db.session.commit() db.session.commit()
task_no = task.task_no task_no = task.task_no
customer_id = customer.id customer_id = customer.id
short_code = customer.short_code
username = user.username username = user.username
headers = {'X-Username': username, 'X-Role': 'user', 'Content-Type': 'application/json'} headers = {'X-Username': username, 'X-Role': 'user', 'Content-Type': 'application/json'}
options_response = client.get('/api/workspace/shipping-customers?q=GAA', headers=headers) options_response = client.get(f'/api/workspace/shipping-customers?q={short_code}', headers=headers)
assert options_response.status_code == 200 assert options_response.status_code == 200
assert options_response.get_json()[0]['short_code'] == 'GAA' options_payload = options_response.get_json()
assert options_payload['success'] is True
assert options_payload['data'][0]['short_code'] == short_code
confirm_response = client.post( confirm_response = client.post(
f'/api/workspace/shipping-tasks/{task_no}/confirm-customer', f'/api/workspace/shipping-tasks/{task_no}/confirm-customer',
@@ -183,10 +186,12 @@ def test_workspace_customer_search_and_confirmation_api(app, client):
headers=headers, headers=headers,
) )
assert confirm_response.status_code == 200 assert confirm_response.status_code == 200
payload = confirm_response.get_json() envelope = confirm_response.get_json()
assert envelope['success'] is True
payload = envelope['data']
assert payload['customer_resolution_status'] == 'confirmed' assert payload['customer_resolution_status'] == 'confirmed'
assert payload['customer_id'] == customer_id assert payload['customer_id'] == customer_id
assert payload['business_no'].startswith('GAA') assert payload['business_no'].startswith(short_code)
other_headers = {'X-Username': 'gate-other-user', 'X-Role': 'user', 'Content-Type': 'application/json'} other_headers = {'X-Username': 'gate-other-user', 'X-Role': 'user', 'Content-Type': 'application/json'}
forbidden_response = client.post( forbidden_response = client.post(
@@ -0,0 +1,60 @@
"""
tests/test_shipping_document_layout_cell_coordinate_status.py
用途:锁定阶段 3 Cell 坐标来源分级与高风险字段门禁。
依赖:cell_coordinate_status。
逻辑:pure_unit;覆盖 native verified / OCR candidate / HTML unavailable / 高风险缺 token。
"""
from __future__ import annotations
import pytest
from app.services.shipping_notice.document_layout.cell_coordinate_status import (
HIGH_RISK_FIELD_CODES,
classify_cell_coordinate_status,
)
pytestmark = pytest.mark.pure_unit
def test_native_unique_glyph_is_verified():
"""原生 glyph 唯一对齐且置信度满值 → verified。"""
grade = classify_cell_coordinate_status(
source='native_text', has_bbox=True, has_token_ids=True, confidence=1.0,
field_code='qty',
)
assert grade['highlight_quality'] == 'verified'
assert grade['highlight_source'] == 'native_glyph'
def test_ocr_and_opencv_remain_candidate():
"""OCR / OpenCV 三重校验通过后仍不得自动升 verified。"""
ocr = classify_cell_coordinate_status(
source='ocr', has_bbox=True, has_token_ids=True, confidence=0.95,
)
opencv = classify_cell_coordinate_status(
source='opencv', has_bbox=True, has_token_ids=True, confidence=1.0,
)
assert ocr['highlight_quality'] == 'candidate'
assert opencv['highlight_quality'] == 'candidate'
def test_html_only_is_unavailable():
"""仅 HTML 行列不得伪造 PDF bbox。"""
grade = classify_cell_coordinate_status(
source='html', has_bbox=False, has_token_ids=False,
)
assert grade['highlight_quality'] == 'unavailable'
assert 'html_only_no_pdf_bbox' in grade['coordinate_issue_codes']
def test_high_risk_field_without_tokens_unavailable():
"""高风险字段缺 token 时禁止 candidate 高亮。"""
assert 'part_number' in HIGH_RISK_FIELD_CODES
grade = classify_cell_coordinate_status(
source='opencv', has_bbox=True, has_token_ids=False, confidence=1.0,
field_code='part_number',
)
assert grade['highlight_quality'] == 'unavailable'
assert 'cell_token_unbound' in grade['coordinate_issue_codes']
Loaded 100 of 226 files, more files were not shown because too many files have changed in this diff. Show more