refactor(agent, shipping): 简化代理模型并完善订单抽取业务

- 移除 Agent 的 exposure_mode 与 internal_executor 相关逻辑,清理关联的过滤、序列化代码
- 删除废弃的 AgentRuntimeBinding 模型及其依赖
- 新增订单抽取上传批次、请求快照等数据库迁移与业务逻辑
- 修复附件完整性检测、订单抽取状态映射问题
- 更新多语言错误文案与前端单元测试配置
- 清理平台配置中不再使用的暴露模式配置
This commit is contained in:
hugo committed 2026-07-28 20:25:48 +08:00
1 parent 1f3ecb87b7
commit 61ac6403c4
159 files changed
+12883 -5099

No files matched your search

+2 -35
View File
@@ -9,7 +9,6 @@ from flask import g, request
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.errors import ValidationError
from app.core.response import ok
from app.services.admin import agent_service
@@ -69,8 +68,8 @@ def list_agent_intent_routes():
@admin_bp.route('/agents', methods=['GET'])
@require_admin
def list_agents():
"""按管理页签返回应用或内部执行器;缺省 scope 保持旧版全部列表兼容。"""
return ok(agent_service.list_agents(scope=request.args.get('scope')), request_id=_request_id())
"""列出全部应用。"""
return ok(agent_service.list_agents(), request_id=_request_id())
@admin_bp.route('/agents', methods=['POST'])
@@ -107,38 +106,6 @@ def test_agent(id: int):
return ok(payload, request_id=_request_id())
@admin_bp.route('/agents/<int:id>/runtime-bindings', methods=['GET'])
@require_admin
def list_agent_runtime_bindings(id: int):
"""列出入口 Agent 的显式运行能力绑定。"""
from app.services.agent_runtime_binding_service import list_runtime_bindings
return ok(list_runtime_bindings(id), request_id=_request_id())
@admin_bp.route('/agents/<int:id>/runtime-bindings/<path:capability_code>', methods=['PUT'])
@require_admin
def save_agent_runtime_binding(id: int, capability_code: str):
"""保存单个能力 Provider;API Key 仍由 Provider Agent 自身配置管理。"""
body = request.get_json(silent=True)
if not isinstance(body, dict):
raise ValidationError('JSON body must be an object')
try:
provider_agent_id = int(body.get('provider_agent_id'))
except (TypeError, ValueError) as exc:
raise ValidationError('provider_agent_id is required') from exc
from app.services.agent_runtime_binding_service import save_runtime_binding, serialize_runtime_binding
binding = save_runtime_binding(
owner_agent_id=id,
capability_code=capability_code,
provider_agent_id=provider_agent_id,
enabled=body.get('enabled') is not False,
config=body.get('config'),
)
return ok(serialize_runtime_binding(binding), request_id=_request_id())
@admin_bp.route('/agents/<int:id>/permissions', methods=['POST'])
@require_admin
def update_agent_permissions(id: int):
@@ -223,6 +223,23 @@ def suspend_order_document_profile_auto_freeze_qualification(profile_id: int):
return _ok(quality.serialize_qualification(qualification))
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/auto-freeze-qualification/scope', methods=['POST'])
@require_admin
def configure_order_document_profile_auto_freeze_scope(profile_id: int):
"""配置模板版本的客户/业务场景自动冻结范围;空列表表示清空授权范围。"""
from app.services.shipping_notice import document_profile_quality_service as quality
data = request.get_json(silent=True) or {}
qualification = quality.configure_auto_freeze_qualification_scope(
profile_id=profile_id,
actor_id=int(_actor_id() or 0),
customer_ids=data.get('customer_ids'),
business_scenarios=data.get('business_scenarios'),
requires_customer_confirmation=bool(data.get('requires_customer_confirmation', True)),
)
return _ok(quality.serialize_qualification(qualification))
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>', methods=['DELETE'])
@require_admin
def delete_order_document_profile(profile_id: int):
+5 -11
View File
@@ -15,7 +15,6 @@ from app.core.auth.jwt import get_current_user
from app.core.errors import UnauthorizedError
from app.models import Agent, User, AgentGuide
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
from app.services.agent_user_access import require_user_application_access
from app.services.minio_service import minio_service
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
@@ -41,11 +40,11 @@ def _list_active_agents_for_user(user: User) -> list[Agent]:
if user.role == 'admin':
return (
db.session.query(Agent)
.filter(Agent.is_active.is_(True), Agent.exposure_mode == 'workspace')
.filter(Agent.is_active.is_(True))
.order_by(Agent.id.asc())
.all()
)
return [agent for agent in user.agents if agent.is_active and agent.exposure_mode == 'workspace']
return [agent for agent in user.agents if agent.is_active]
@agents_bp.route('', methods=['GET'])
@@ -68,14 +67,12 @@ def list_agent_guides(agent_id):
获取指定应用的新手指南列表 (需登录)
用途:客户端 Chat 界面点击新手指南
"""
user = get_current_user()
if not user:
raise UnauthorizedError()
get_current_user() # Ensure user is logged in.
if agent_id == 0:
generic_agent = (
db.session.query(Agent)
.filter_by(agent_code='generic', is_active=True, exposure_mode='workspace')
.filter_by(agent_code='generic', is_active=True)
.order_by(Agent.sort_order.asc(), Agent.id.asc())
.first()
)
@@ -84,9 +81,6 @@ def list_agent_guides(agent_id):
else:
return jsonify([])
agent = db.session.get(Agent, agent_id)
require_user_application_access(agent, user)
guides = (
db.session.query(AgentGuide)
.filter_by(agent_id=agent_id, status=1)
@@ -116,7 +110,7 @@ def list_public_agents():
"""
agents = (
db.session.query(Agent)
.filter(Agent.is_active.is_(True), Agent.exposure_mode == 'workspace')
.filter(Agent.is_active.is_(True))
.order_by(Agent.id.asc())
.all()
)
+7 -1
View File
@@ -229,7 +229,13 @@ def _order_extraction_attention_by_conversation(
if not conversation_ids:
return {}
severity_rank = {'info': 1, 'warning': 2, 'error': 3}
status_severity = {'completed': 'info', 'needs_review': 'warning', 'failed': 'error', 'cancelled': 'error'}
status_severity = {
'completed': 'info',
'partially_completed': 'warning',
'review_required': 'warning',
'failed': 'error',
'cancelled': 'error',
}
rows = db.session.query(
ShippingOrderExtractionRun.conversation_id,
ShippingOrderExtractionRun.status,
+13 -24
View File
@@ -11,11 +11,6 @@ from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaul
from app.services.feedback_notify import send_feedback_group_notification
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
from app.services.agent_registry.serialization import serialize_registry_fields
from app.services.agent_user_access import (
require_user_application_access,
visible_agent_ids,
visible_default_agent_id,
)
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
from app.core.auth.jwt import get_current_user as _auth_current_user
@@ -446,7 +441,7 @@ def _build_login_payload(user: User, source: str='password', bind_status: str=No
'id': user.id,
'username': user.username,
'role': user.role,
'default_agent_id': visible_default_agent_id(user),
'default_agent_id': user.default_agent_id,
'feature_permissions': user.get_feature_permissions(),
'source': source,
'access_token': issue_local_access_token(user),
@@ -775,7 +770,7 @@ def casdoor_password_login():
_write_login_audit('casdoor', 'success', user=user)
db.session.commit()
api_bearer_token = id_token or access_token
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': visible_default_agent_id(user), 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
except WeComLoginError:
db.session.rollback()
raise
@@ -905,7 +900,7 @@ def casdoor_login():
_write_login_audit('casdoor', 'success', user=user)
db.session.commit()
api_bearer_token = id_token or access_token
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': visible_default_agent_id(user), 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
except WeComLoginError:
db.session.rollback()
current_app.logger.warning('[casdoor_login] business_reject')
@@ -1346,32 +1341,26 @@ def home():
raise UnauthorizedError('Unauthorized')
def _load_home_payload():
allowed_agent_ids = visible_agent_ids(user)
if user.role == 'admin':
agent_rows = Agent.query.filter(
Agent.is_active.is_(True), Agent.exposure_mode == 'workspace',
).all()
agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all()
else:
agent_rows = [
agent for agent in user.agents
if agent.is_active and agent.exposure_mode == 'workspace'
]
agent_rows = [agent for agent in user.agents if agent.is_active]
agent_rows = sort_agent_rows(agent_rows)
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
favorite_ids = [f.agent_id for f in favorites if f.agent_id in allowed_agent_ids]
favorite_ids = [f.agent_id for f in favorites]
qqs = db.session.query(QuickQuestion).filter(
or_(
QuickQuestion.user_id == user.id,
and_(QuickQuestion.user_id.is_(None), QuickQuestion.is_enabled.is_(True)),
)
).filter(QuickQuestion.agent_id.in_(allowed_agent_ids)).all() if allowed_agent_ids else []
).all()
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
layout = layout_config.layout if layout_config else {}
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
embedded_agents = []
for rel in embedded_rel:
agent = db.session.get(Agent, rel.agent_id)
if agent and agent.id in allowed_agent_ids:
if agent:
registry = serialize_registry_fields(agent)
embedded_agents.append({
'id': agent.id,
@@ -1380,7 +1369,7 @@ def home():
'runtime_provider': registry.get('runtime_provider'),
'conversation_mode': registry.get('conversation_mode'),
})
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': visible_default_agent_id(user), 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
try:
return _run_db_with_retry(_load_home_payload, label='user.home')
except (OperationalError, DatabaseError) as exc:
@@ -1392,7 +1381,6 @@ def toggle_favorite(agent_id: int):
user = _get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
require_user_application_access(db.session.get(Agent, agent_id), user)
if request.method == 'POST':
exists = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).first()
if not exists:
@@ -1411,7 +1399,6 @@ def add_quick_question():
data = request.get_json() or {}
if not data.get('title') or not data.get('question') or (not data.get('agent_id')):
raise ValidationError('Missing fields')
require_user_application_access(db.session.get(Agent, data['agent_id']), user)
qq = QuickQuestion(user_id=user.id, title=data['title'], question=data['question'], agent_id=data['agent_id'])
db.session.add(qq)
db.session.commit()
@@ -1435,7 +1422,6 @@ def update_quick_question(qq_id: int):
if 'question' in data:
qq.question = data['question']
if 'agent_id' in data:
require_user_application_access(db.session.get(Agent, data['agent_id']), user)
qq.agent_id = data['agent_id']
db.session.commit()
return jsonify({'status': 'ok'})
@@ -1829,7 +1815,10 @@ def get_agent_details(id):
if not user:
raise UnauthorizedError('Unauthorized')
agent = db.session.get(Agent, id)
require_user_application_access(agent, user)
if not agent:
raise NotFoundError('Not found')
if user.role != 'admin' and agent not in user.agents:
raise ForbiddenError('Access denied')
from app.services.agent_registry.resolver import resolve_runtime_provider
from app.services.agent_registry.serialization import serialize_agent_for_user_detail
+33 -1
View File
@@ -971,6 +971,17 @@ def workspace_create_shipping_order_extraction_run():
code='SHIPPING_NOTICE.ORDER_EXTRACTION_AGENT_INVALID',
) from exc
conversation_id = str(body.get('conversation_id') or '').strip()
upload_batch_id = str(body.get('upload_batch_id') or '').strip()
if not upload_batch_id:
raise ValidationError(
'upload_batch_id is required',
code='SHIPPING_NOTICE.UPLOAD_BATCH_REQUIRED',
)
if len(upload_batch_id) > 36:
raise ValidationError(
'upload_batch_id is too long',
code='SHIPPING_NOTICE.UPLOAD_BATCH_INVALID',
)
intake_nos = body.get('intake_nos')
if not isinstance(intake_nos, list):
raise ValidationError(
@@ -987,6 +998,7 @@ def workspace_create_shipping_order_extraction_run():
agent_id=agent_id,
conversation_id=conversation_id,
intake_nos=intake_nos,
upload_batch_id=upload_batch_id,
)
db.session.commit()
return ok(
@@ -1017,6 +1029,15 @@ def workspace_list_shipping_order_extraction_progress_events(run_no: str):
return _ok({'items': list_user_order_extraction_progress_events(user_id=user.id, run_no=run_no)})
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/documents', methods=['GET'])
def workspace_list_shipping_order_extraction_documents(run_no: str):
"""返回当前用户一次订单抽取的按 PDF 归并详情。"""
user = _require_user()
from app.services.shipping_notice.order_extraction_run_service import list_user_order_extraction_documents
return _ok({'items': list_user_order_extraction_documents(user_id=user.id, run_no=run_no)})
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/seen', methods=['POST'])
def workspace_mark_shipping_order_extraction_run_seen(run_no: str):
"""确认当前用户已加载终态订单识别卡片;仅用于会话待查看提醒,不改变业务结果。"""
@@ -1103,12 +1124,23 @@ def workspace_create_shipping_notice_intake():
if not asset_no:
raise ValidationError('asset_no is required')
conversation_id = str(body.get('conversation_id') or '').strip() or None
upload_batch_id = str(body.get('upload_batch_id') or '').strip()
if not upload_batch_id:
raise ValidationError(
'upload_batch_id is required',
code='SHIPPING_NOTICE.UPLOAD_BATCH_REQUIRED',
)
if len(upload_batch_id) > 36:
raise ValidationError(
'upload_batch_id is too long',
code='SHIPPING_NOTICE.UPLOAD_BATCH_INVALID',
)
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
data = create_shipping_notice_intake(
user_id=user.id,
asset_no=asset_no,
conversation_id=conversation_id,
upload_batch_id=upload_batch_id,
)
return ok(data, request_id=getattr(g, 'request_id', None), status=202)
+23
View File
@@ -171,6 +171,8 @@ class Config:
DIFY_CHAT_READ_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_READ_TIMEOUT_SECONDS', '30'))
# Redis 连接配置,默认使用本地 Redis + 密码
REDIS_URL = os.getenv('REDIS_URL')
# 订单文档模板预览默认要求 Redis;仅开发单进程 run.py 可显式放开进程内一次性令牌兜底。
ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK = False
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
HR_WORKFLOW_IFRAME_URL = os.getenv('HR_WORKFLOW_IFRAME_URL')
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE')
@@ -461,6 +463,19 @@ class Config:
SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', '300')
)
# 订单抽取发送后选择计划预算:首轮只挑最相关附件,后续批次按固定预算待扩展。
SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_ATTACHMENTS = int(
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_ATTACHMENTS', '2')
)
SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_CONCURRENCY = int(
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_CONCURRENCY', '2')
)
SHIPPING_NOTICE_ORDER_EXTRACTION_EXPANSION_BATCH_SIZE = int(
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_EXPANSION_BATCH_SIZE', '2')
)
SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS = int(
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS', '6')
)
SHIPPING_NOTICE_PARSER_VERSION = os.getenv('SHIPPING_NOTICE_PARSER_VERSION', 'v6')
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED = os.getenv(
'SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED', 'false'
@@ -510,11 +525,19 @@ class Config:
SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS = int(
os.getenv('SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS', str(500_000))
)
# 订单抽取 Worker 的全 Run 资源门槛;超出时停止扩批并进入可复核终态。
SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_BYTES = int(
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_BYTES', str(30 * 1024 * 1024))
)
SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_RUNTIME_SECONDS = int(
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_RUNTIME_SECONDS', '300')
)
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK = True
# 本机常无 Redis:不强制 Redis,允许进程内存兜底心跳(单进程 run.py 可用)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
+8 -4
View File
@@ -13,9 +13,8 @@ from functools import wraps
from flask import current_app, g, request
from app.core.auth.jwt import get_current_user as _auth_current_user
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
from app.models import Agent, User
from app.services.agent_user_access import require_user_application_access
def _get_current_user() -> User:
@@ -48,7 +47,7 @@ def _resolve_request_agent_id() -> str | None:
def require_agent_permission(f):
"""
装饰器:校验当前用户是否拥有指定 Agent 访问权限。
核心逻辑:从 body/query/form 读 agent_id → 阻断内部执行器 → admin 放行 workspace 或检查用户授权。
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → admin 放行或检查 user.agents。
Args:
f: 被装饰的视图函数。
Returns:
@@ -64,8 +63,13 @@ def require_agent_permission(f):
if not user:
raise UnauthorizedError('Unauthorized')
agent = Agent.query.get(agent_id)
require_user_application_access(agent, user)
if not agent:
raise NotFoundError('Agent not found')
g.current_agent = agent
if user.role == 'admin':
return f(*args, **kwargs)
if agent not in user.agents:
raise ForbiddenError('Permission denied for this agent')
return f(*args, **kwargs)
return decorated_function
@@ -9,7 +9,10 @@ backend/app/jobs/handlers/shipping_order_extraction.py
from __future__ import annotations
import time
from datetime import date, datetime
from decimal import Decimal
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import AppError
@@ -22,6 +25,7 @@ from app.models import (
ShippingOrderExtractionPlan,
ShippingOrderExtractionRouteDecision,
ShippingOrderExtractionRun,
ShippingNoticeIntake,
ShippingOrderExtractionUnit,
)
from app.services.shipping_notice.audit_service import append_shipping_audit_event
@@ -29,16 +33,52 @@ from app.services.shipping_notice.order_extraction import submit_order_extractio
from app.services.shipping_notice.order_extraction_merge import merge_unit_orders
from app.services.shipping_notice.order_extraction_run_service import (
mark_order_extraction_persistence_started,
materialize_order_extraction_run_inputs,
transition_order_extraction_run,
)
from app.services.shipping_notice.order_extraction_progress import (
record_run_progress,
record_unit_progress,
)
from app.services.shipping_notice.order_extraction_workflow import (
route_deterministic_unit,
validate_unit_orders,
)
MAX_UNIT_TECHNICAL_ATTEMPTS = 3
EXPANDABLE_UNIT_REVIEW_REASON_CODES = {
'required_anchor_missing',
'required_field_missing',
'business_table_not_found',
'multiple_business_tables',
'po_missing',
'multiple_po_detected',
'row_needs_review',
}
def _json_safe_order_payload(value: Any) -> Any:
"""将坐标解析的 Decimal/date 递归转为 JSON 标量后写入 Unit 快照。
模板解析保留 Decimal 以便规则校验;Unit 的 result_json 是 JSON 列,落库前必须
转为字符串,避免候选已生成却在持久化边界失败。
"""
if isinstance(value, Decimal):
return format(value.normalize(), 'f')
if isinstance(value, (date, datetime)):
return value.isoformat()
if isinstance(value, list):
return [_json_safe_order_payload(item) for item in value]
if isinstance(value, dict):
return {str(key): _json_safe_order_payload(item) for key, item in value.items()}
return value
EXPANDABLE_ORDER_CONFLICT_REASONS = {
'supplement_relation_ambiguous',
}
def _append_route_decision(*, run, unit, job, attempt_no: int, route_result) -> None:
"""追加 Unit 脱敏路由投影及统一审计,禁止保存订单值、正文或布局载荷。"""
"""追加 Unit 脱敏路由投影及统一审计,尝试号必须区分同一 Job 内的单元重试。"""
decision = route_result.decision if isinstance(route_result.decision, dict) else {}
candidates = decision.get('candidate_summary') if isinstance(decision.get('candidate_summary'), list) else []
safe_candidates = [{
@@ -86,13 +126,358 @@ def _append_route_decision(*, run, unit, job, attempt_no: int, route_result) ->
def _result_requires_review(*, units: list[ShippingOrderExtractionUnit], result: dict) -> bool:
"""汇总人工复核、未接受候选和技术局部失败,确保不把不完整订单标记完成。"""
"""汇总人工复核、未接受候选、技术失败和自动冻结阻断,避免不完整 Run 被标记完成。"""
return bool(
result.get('pending_count')
or any(unit.status in {'skipped', 'failed'} for unit in units)
or result.get('auto_freeze', {}).get('blocked_tasks')
or any(unit.status in {'review_required', 'failed'} for unit in units)
)
def _selection_progress_summary(run: ShippingOrderExtractionRun) -> dict[str, int]:
"""从冻结选择计划提取首轮预算摘要,供 Run 级事件和卡片文案直接使用。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {}
items = selection.get('items') if isinstance(selection.get('items'), list) else []
budget_limited_count = sum(
1 for item in items if isinstance(item, dict)
and {'budget_initial_limit', 'budget_total_limit'} & {str(code) for code in (item.get('skip_reason_codes') or [])}
)
return {
'total_attachment_count': int(selection.get('total_attachment_count') or 0),
'selected_attachment_count': int(selection.get('selected_attachment_count') or 0),
'planned_attachment_count': int(selection.get('planned_attachment_count') or 0),
'pending_expansion_attachment_count': int(selection.get('pending_expansion_attachment_count') or 0),
'group_count': int(selection.get('group_count') or 0),
'max_initial_attachments': int(selection.get('max_initial_attachments') or 0),
'max_initial_concurrency': int(selection.get('max_initial_concurrency') or 0),
'budget_limited_attachment_count': budget_limited_count,
}
def _units_for_batch(plan: ShippingOrderExtractionPlan, *, selection_batch: int) -> list[ShippingOrderExtractionUnit]:
"""按批次读取计划单元;未标批次的普通文件视为首轮。"""
normalized_batch = int(selection_batch or 1)
return [
unit for unit in plan.units
if int(unit.selection_batch or 1) == normalized_batch
]
def _next_existing_batch(plan: ShippingOrderExtractionPlan, *, after_batch: int) -> int | None:
"""返回计划中已存在但尚未轮到的下一批。"""
candidates = sorted({
int(unit.selection_batch or 1)
for unit in plan.units
if int(unit.selection_batch or 1) > int(after_batch or 0)
})
return candidates[0] if candidates else None
def _pending_snapshot_batches(run: ShippingOrderExtractionRun, plan: ShippingOrderExtractionPlan) -> list[int]:
"""从冻结选择计划中找出尚未激活为执行单元的后续批次。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {}
planned_batches = sorted({
int(item.get('planned_selection_batch') or 0)
for item in selection.get('items') or []
if isinstance(item, dict) and int(item.get('planned_selection_batch') or 0) > 1
})
existing_batches = {
int(unit.selection_batch or 1)
for unit in plan.units
if int(unit.selection_batch or 1) > 1
}
return [batch for batch in planned_batches if batch not in existing_batches]
def _should_expand_after_wave(*, wave_units: list[ShippingOrderExtractionUnit], wave_orders: list[dict]) -> bool:
"""仅在可通过更多附件补证的业务缺口出现时才扩下一轮。"""
return bool(_expansion_trigger_reason_codes(wave_units=wave_units, wave_orders=wave_orders))
def _expansion_trigger_reason_codes(
*,
wave_units: list[ShippingOrderExtractionUnit],
wave_orders: list[dict],
) -> list[str]:
"""汇总当前批次触发扩批的业务原因码,供事件与工作台共享。"""
if not wave_units:
return []
reason_codes = {
str(unit.reason_code or '').strip()
for unit in wave_units
if unit.status == 'review_required'
and str(unit.reason_code or '').strip() in EXPANDABLE_UNIT_REVIEW_REASON_CODES
}
for order in wave_orders:
if not isinstance(order, dict):
continue
if order.get('_hxops_expand_for_missing_reservation'):
reason_codes.add('missing_reservation_id')
for conflict in order.get('conflicts') or []:
if not isinstance(conflict, dict):
continue
code = str(conflict.get('reason') or '').strip()
if code in EXPANDABLE_ORDER_CONFLICT_REASONS:
reason_codes.add(code)
return sorted(code for code in reason_codes if code)
def _schema_field_ids_by_code(run: ShippingOrderExtractionRun) -> dict[str, set[str]]:
"""读取冻结 Schema 中稳定 field_code -> field_id 集合,供业务缺口判定复用。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
definition = schema.get('definition') if isinstance(schema.get('definition'), dict) else {}
mapping: dict[str, set[str]] = {}
for item in definition.get('fields') or []:
if not isinstance(item, dict):
continue
field_code = str(item.get('field_code') or '').strip()
field_id = str(item.get('field_id') or '').strip()
if not field_code or not field_id:
continue
mapping.setdefault(field_code, set()).add(field_id)
return mapping
def _field_has_value(fields: list[dict] | None, *, field_ids: set[str]) -> bool:
"""判断指定字段是否存在非空 Observation。"""
for field in fields or []:
if not isinstance(field, dict) or str(field.get('field_id') or '') not in field_ids:
continue
for observation in field.get('observations') or []:
if isinstance(observation, dict) and str(observation.get('value') or '').strip():
return True
return False
def _order_requires_expansion(order: dict[str, Any]) -> bool:
"""识别当前订单是否仍缺少可由其他附件补证的业务字段或存在冲突。"""
conflicts = [
item for item in (order.get('conflicts') or [])
if isinstance(item, dict)
]
if any(str(item.get('reason') or '').strip() in EXPANDABLE_ORDER_CONFLICT_REASONS for item in conflicts):
return True
return bool(order.get('_hxops_expand_for_missing_reservation'))
def _mark_expandable_business_gaps(
run: ShippingOrderExtractionRun,
*,
orders: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""把可由后续附件补证的业务缺口标记到订单上,供扩批决策复用。"""
field_ids_by_code = _schema_field_ids_by_code(run)
reservation_field_ids = field_ids_by_code.get('reservation_id', set())
if not reservation_field_ids:
return orders
for order in orders:
if not isinstance(order, dict):
continue
lines = order.get('lines') if isinstance(order.get('lines'), list) else []
order['_hxops_expand_for_missing_reservation'] = any(
isinstance(line, dict)
and not _field_has_value(line.get('fields'), field_ids=reservation_field_ids)
for line in lines
)
return orders
def _wave_orders_for_expansion(
run: ShippingOrderExtractionRun,
*,
orders: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""为当前批次生成扩批判定所需的业务事实视图。"""
if not orders:
return []
schema_snapshot = run.input_snapshot_json.get('schema') if isinstance(run.input_snapshot_json, dict) else {}
merged = merge_unit_orders(
orders=orders,
schema_definition=schema_snapshot.get('definition') or {},
)
from app.services.shipping_notice.order_supplement_merge import merge_email_supplements
supplements_by_intake = {
int(intake.get('intake_id') or 0): supplement
for intake in run.input_snapshot_json.get('intakes') or [] if isinstance(intake, dict)
for supplement in intake.get('email_supplements') or [] if isinstance(supplement, dict)
}
merged = merge_email_supplements(
orders=merged,
supplements_by_intake=supplements_by_intake,
schema_definition=schema_snapshot.get('definition') or {},
)
return _mark_expandable_business_gaps(run, orders=merged)
def _activate_expansion_batch(
*,
run: ShippingOrderExtractionRun,
plan: ShippingOrderExtractionPlan,
selection_batch: int,
) -> list[ShippingOrderExtractionUnit]:
"""按冻结批次计划补物化附件并追加执行单元;重复触发保持幂等。"""
from app.services.shipping_notice.order_extraction_materialization import ensure_order_extraction_input_documents
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan_batch
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {}
schema_definition = (snapshot.get('schema') or {}).get('definition') if isinstance(snapshot.get('schema'), dict) else {}
intake_ids = [
int(item.get('intake_id'))
for item in (snapshot.get('intakes') or [])
if isinstance(item, dict) and item.get('intake_id') is not None
]
intakes = (
ShippingNoticeIntake.query
.filter(ShippingNoticeIntake.id.in_(intake_ids))
.order_by(ShippingNoticeIntake.id.asc())
.all()
) if intake_ids else []
ensure_order_extraction_input_documents(
intakes=intakes,
attachment_selection=selection,
schema_definition=schema_definition if isinstance(schema_definition, dict) else {},
selection_batches={int(selection_batch)},
)
return ensure_order_extraction_plan_batch(run, selection_batch=int(selection_batch))
def _reload_run_and_unit(*, run_id: int, unit_id: int) -> tuple[ShippingOrderExtractionRun, ShippingOrderExtractionUnit]:
"""在单元异常回滚后重新加载实体,避免继续使用失效会话对象。"""
run = ShippingOrderExtractionRun.query.filter_by(id=run_id).with_for_update().first()
unit = db.session.get(ShippingOrderExtractionUnit, int(unit_id))
if run is None or unit is None:
raise RuntimeError('order extraction run or unit disappeared during retry handling')
return run, unit
def _record_unit_technical_failure(*, run, unit, job, exc: Exception, retryable: bool) -> None:
"""将单元异常收敛为稳定技术失败事实,并在可重试时回到 pending。"""
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
error_code = str(getattr(exc, 'code', None) or 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED')
transition_order_extraction_unit(
unit,
target_status='failed',
error_code=error_code,
error_message=str(exc),
)
record_unit_progress(
run=run,
unit=unit,
event_code='technical_failed',
reason_code=error_code,
summary={
'retryable': bool(retryable),
'attempt_count': int(unit.attempt_count or 0),
},
job_id=job.id,
)
if retryable and int(unit.attempt_count or 0) < MAX_UNIT_TECHNICAL_ATTEMPTS:
record_unit_progress(
run=run,
unit=unit,
event_code='technical_retrying',
reason_code=error_code,
summary={
'next_attempt_count': int(unit.attempt_count or 0) + 1,
'max_attempt_count': MAX_UNIT_TECHNICAL_ATTEMPTS,
},
job_id=job.id,
)
transition_order_extraction_unit(unit, target_status='pending')
def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[dict] | None:
"""
独立处理一个附件单元;技术失败最多自动重试 2 次,不影响其他单元继续执行。
Returns:
`list[dict]`: 当前单元产出的订单数组(确定性成功)。
`None`: 当前单元进入 review_required 或最终技术失败。
"""
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
while True:
if unit.status == 'failed':
transition_order_extraction_unit(unit, target_status='pending')
if unit.status in {'review_required', 'candidate_ready'}:
return None
transition_order_extraction_unit(unit, target_status='routing')
record_unit_progress(run=run, unit=unit, event_code='document_queued', job_id=job.id)
transition_order_extraction_unit(unit, target_status='matching_profile')
record_unit_progress(run=run, unit=unit, event_code='profile_matching', job_id=job.id)
db.session.commit()
try:
route_result = route_deterministic_unit(run, unit=unit)
_append_route_decision(
run=run,
unit=unit,
job=job,
# 同一 Job 可在单元内多次路由;审计唯一键要求使用单元执行代次。
attempt_no=int(unit.attempt_count or 1),
route_result=route_result,
)
if route_result.execution_mode == 'deterministic':
record_unit_progress(
run=run,
unit=unit,
event_code='profile_matched',
summary={
'profile_code': route_result.decision.get('selected_profile_code'),
'profile_version': route_result.decision.get('selected_profile_version'),
},
job_id=job.id,
)
db.session.commit()
if route_result.execution_mode != 'deterministic':
transition_order_extraction_unit(
unit, target_status='review_required',
error_code=(route_result.decision.get('fallback_reason_codes') or ['review_required'])[0],
error_message='订单模板路由要求人工处理',
result={
'fallback_reason_codes': route_result.decision.get('fallback_reason_codes') or [],
'review_details': route_result.decision.get('review_details') or [],
},
)
record_unit_progress(
run=run,
unit=unit,
event_code='review_required',
reason_code=(route_result.decision.get('fallback_reason_codes') or ['review_required'])[0],
summary={'fallback_reason_codes': route_result.decision.get('fallback_reason_codes') or []},
job_id=job.id,
)
db.session.commit()
return None
transition_order_extraction_unit(unit, target_status='extracting')
record_unit_progress(run=run, unit=unit, event_code='table_reconstructed', job_id=job.id)
unit_orders = validate_unit_orders(run, unit=unit, orders=route_result.orders)
record_unit_progress(run=run, unit=unit, event_code='order_fields_extracted', job_id=job.id)
for order in unit_orders:
order['_hxops_intake_id'] = int(unit.intake_id)
unit_orders = _json_safe_order_payload(unit_orders)
transition_order_extraction_unit(
unit,
target_status='merging_supplement',
result={'orders': unit_orders, 'execution': {'mode': 'deterministic'}},
)
db.session.commit()
return unit_orders
except Exception as exc:
db.session.rollback()
retryable = not isinstance(exc, AppError) or bool(getattr(exc, 'retryable', False))
run, unit = _reload_run_and_unit(run_id=int(run.id), unit_id=int(unit.id))
_record_unit_technical_failure(run=run, unit=unit, job=job, exc=exc, retryable=retryable)
db.session.commit()
if retryable and int(unit.attempt_count or 0) < MAX_UNIT_TECHNICAL_ATTEMPTS:
continue
return None
@register_handler(JobType.SHIPPING_ORDER_EXTRACTION)
def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
"""
@@ -114,84 +499,215 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
if run is None:
fail_job(job.id, error='order extraction run not found', retryable=False, owned_attempt=owned_attempt)
return
if run.status in {'completed', 'needs_review'}:
if run.status in {'completed', 'partially_completed', 'review_required'}:
finish_job(job.id, result={'run_no': run.run_no, 'status': run.status, 'idempotent_replay': True}, owned_attempt=owned_attempt)
return
if run.status == 'result_persisted':
target = 'needs_review' if (run.result_json or {}).get('requires_review') else 'completed'
transition_order_extraction_run(run, target_status=target)
db.session.commit()
finish_job(job.id, result={'run_no': run.run_no, 'status': run.status}, owned_attempt=owned_attempt)
return
if run.status not in {'queued', 'running'}:
if run.status not in {'queued', 'processing'}:
fail_job(job.id, error=f'run status is not executable: {run.status}', retryable=False, owned_attempt=owned_attempt)
return
started = time.perf_counter()
try:
if run.status == 'queued':
transition_order_extraction_run(run, target_status='running', phase='deterministic_parsing')
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan, transition_order_extraction_unit
transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing')
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
plan = ensure_order_extraction_plan(run)
plan = materialize_order_extraction_run_inputs(run)
selection = (run.input_snapshot_json or {}).get('attachment_selection') or {}
max_runtime_seconds = max(0, int(selection.get('max_runtime_seconds') or 0))
runtime_budget_stopped = False
run.current_job_id = job.id
run.attempt_count = owned_attempt
record_run_progress(
run=run,
event_code='initial_wave_started',
summary={
**_selection_progress_summary(run),
'unit_count': int(getattr(plan, 'unit_count', 0) or 0),
'job_attempt': owned_attempt,
},
job_id=job.id,
commit=False,
)
db.session.commit()
units = ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id).order_by(ShippingOrderExtractionUnit.position.asc()).all()
orders: list[dict] = []
unit_orders_by_id: dict[int, list[dict]] = {}
persisted_orders: list[dict] = []
pending_merge_unit_ids: list[int] = []
current_batch = 1
expansion_events_emitted: set[int] = set()
# [STEP 1] 每个文档独立路由,单个歧义不得阻断其他 PDF/PO 的确定性结果。
for unit in units:
if unit.status == 'succeeded' and isinstance(unit.result_json, dict):
saved_orders = unit.result_json.get('orders')
if isinstance(saved_orders, list):
orders.extend(item for item in saved_orders if isinstance(item, dict))
continue
if unit.status == 'failed':
transition_order_extraction_unit(unit, target_status='pending')
if unit.status == 'skipped':
continue
transition_order_extraction_unit(unit, target_status='running')
db.session.commit()
route_result = route_deterministic_unit(run, unit=unit)
_append_route_decision(run=run, unit=unit, job=job, attempt_no=owned_attempt, route_result=route_result)
db.session.commit()
if route_result.execution_mode != 'deterministic':
transition_order_extraction_unit(
unit, target_status='skipped',
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED',
error_message='订单模板路由要求人工处理',
# [STEP 1] 每个文档独立路由;当前批次未完整收敛时,再按冻结计划激活下一批附件。
while True:
if max_runtime_seconds and time.perf_counter() - started >= max_runtime_seconds:
runtime_budget_stopped = True
record_run_progress(
run=run, event_code='budget_stopped', reason_code='budget_runtime_limit',
summary={'max_runtime_seconds': max_runtime_seconds}, job_id=job.id,
)
db.session.commit()
break
units = _units_for_batch(plan, selection_batch=current_batch)
wave_orders: list[dict] = []
for unit in units:
# 总时限不能中断正在进行的外部解析,但禁止在到期后启动新的 Unit。
if max_runtime_seconds and time.perf_counter() - started >= max_runtime_seconds:
runtime_budget_stopped = True
record_run_progress(
run=run, event_code='budget_stopped', reason_code='budget_runtime_limit',
summary={'max_runtime_seconds': max_runtime_seconds}, job_id=job.id,
)
break
if unit.status == 'candidate_ready' and isinstance(unit.result_json, dict):
saved_orders = unit.result_json.get('orders')
if isinstance(saved_orders, list):
unit_orders_by_id[int(unit.id)] = [item for item in saved_orders if isinstance(item, dict)]
persisted_orders.extend(unit_orders_by_id[int(unit.id)])
wave_orders.extend(unit_orders_by_id[int(unit.id)])
continue
if unit.status == 'review_required':
continue
unit_orders = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=owned_attempt)
db.session.expire_all()
unit = db.session.get(ShippingOrderExtractionUnit, int(unit.id))
if unit is None or not unit_orders or unit.status != 'merging_supplement':
continue
unit_orders_by_id[int(unit.id)] = unit_orders
pending_merge_unit_ids.append(int(unit.id))
wave_orders.extend(unit_orders)
if runtime_budget_stopped:
break
wave_orders = _wave_orders_for_expansion(run, orders=wave_orders)
expansion_reason_codes = _expansion_trigger_reason_codes(wave_units=units, wave_orders=wave_orders)
next_existing_batch = _next_existing_batch(plan, after_batch=current_batch)
if expansion_reason_codes and next_existing_batch is not None:
source_batch = current_batch
current_batch = next_existing_batch
if current_batch not in expansion_events_emitted:
record_run_progress(
run=run,
event_code='expansion_wave_started',
summary={
**_selection_progress_summary(run),
'selection_batch': current_batch,
'unit_count': len(_units_for_batch(plan, selection_batch=current_batch)),
'triggered_by_batch': source_batch,
'reason_codes': expansion_reason_codes,
},
job_id=job.id,
commit=False,
)
expansion_events_emitted.add(current_batch)
db.session.commit()
continue
unit_orders = validate_unit_orders(run, unit=unit, orders=route_result.orders)
for order in unit_orders:
order['_hxops_intake_id'] = int(unit.intake_id)
transition_order_extraction_unit(
unit, target_status='succeeded',
result={'orders': unit_orders, 'execution': {'mode': 'deterministic'}},
)
db.session.commit()
orders.extend(unit_orders)
pending_batches = _pending_snapshot_batches(run, plan)
if expansion_reason_codes and pending_batches:
next_batch = pending_batches[0]
created_units = _activate_expansion_batch(run=run, plan=plan, selection_batch=next_batch)
db.session.flush()
plan = ShippingOrderExtractionPlan.query.filter_by(id=plan.id).first() or plan
if created_units or _units_for_batch(plan, selection_batch=next_batch):
record_run_progress(
run=run,
event_code='expansion_wave_started',
summary={
**_selection_progress_summary(run),
'selection_batch': next_batch,
'unit_count': len(_units_for_batch(plan, selection_batch=next_batch)),
'triggered_by_batch': current_batch,
'reason_codes': expansion_reason_codes,
},
job_id=job.id,
commit=False,
)
expansion_events_emitted.add(next_batch)
db.session.commit()
current_batch = next_batch
continue
break
units = ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id).order_by(ShippingOrderExtractionUnit.position.asc()).all()
schema_snapshot = run.input_snapshot_json.get('schema') or {}
orders = merge_unit_orders(orders=orders, schema_definition=schema_snapshot.get('definition') or {})
orders_to_merge = [
order
for unit_id in pending_merge_unit_ids
for order in unit_orders_by_id.get(unit_id, [])
if isinstance(order, dict)
]
orders_to_merge = merge_unit_orders(orders=orders_to_merge, schema_definition=schema_snapshot.get('definition') or {})
from app.services.shipping_notice.order_supplement_merge import merge_email_supplements
supplements_by_intake = {
int(intake.get('intake_id') or 0): supplement
for intake in run.input_snapshot_json.get('intakes') or [] if isinstance(intake, dict)
for supplement in intake.get('email_supplements') or [] if isinstance(supplement, dict)
}
orders = merge_email_supplements(
orders=orders,
merged_orders = merge_email_supplements(
orders=orders_to_merge,
supplements_by_intake=supplements_by_intake,
schema_definition=schema_snapshot.get('definition') or {},
)
offset = 0
for unit in units:
unit_orders = unit_orders_by_id.get(int(unit.id), [])
if unit.status != 'merging_supplement':
continue
count = len(unit_orders)
merged_unit_orders = merged_orders[offset:offset + count]
offset += count
relation_codes = sorted({
str(order.get('_hxops_email_supplement_relation') or '').strip()
for order in merged_unit_orders
if isinstance(order, dict) and str(order.get('_hxops_email_supplement_relation') or '').strip()
})
conflict_count = sum(
1
for order in merged_unit_orders if isinstance(order, dict)
for conflict in order.get('conflicts') or [] if isinstance(conflict, dict)
if str(conflict.get('reason') or '').strip() == 'supplement_relation_ambiguous'
)
supplement_status = (
'conflict'
if conflict_count > 0
else 'merged'
if relation_codes
else 'none'
)
record_unit_progress(
run=run,
unit=unit,
event_code='email_supplement_merged',
summary={
'status': supplement_status,
'relation_codes': relation_codes,
'conflict_count': conflict_count,
},
reason_code='email_supplement_ambiguous' if conflict_count > 0 else None,
job_id=job.id,
)
transition_order_extraction_unit(
unit,
target_status='candidate_ready',
result={'orders': merged_unit_orders, 'execution': {'mode': 'deterministic'}},
)
record_unit_progress(
run=run,
unit=unit,
event_code='candidate_ready',
summary={
'order_count': len(merged_unit_orders),
'email_supplement_status': supplement_status,
'email_supplement_relation_codes': relation_codes,
'email_supplement_conflict_count': conflict_count,
},
job_id=job.id,
)
orders = persisted_orders + merged_orders
execution = {
'mode': 'deterministic',
'unit_count': len(units),
'deterministic_unit_count': sum(1 for unit in units if unit.status == 'succeeded'),
'review_required_unit_count': sum(1 for unit in units if unit.status == 'skipped'),
'deterministic_unit_count': sum(1 for unit in units if unit.status == 'candidate_ready'),
'review_required_unit_count': sum(1 for unit in units if unit.status == 'review_required'),
'failed_unit_count': sum(1 for unit in units if unit.status == 'failed'),
'duration_ms': int((time.perf_counter() - started) * 1000),
}
@@ -202,7 +718,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
# [STEP 2] Candidate 写入与解析执行分离;落库失败可重试,已完成 Unit 不重复解析。
mark_order_extraction_persistence_started(run)
result = submit_order_extraction_run_result(run=run, orders=orders)
requires_review = _result_requires_review(units=units, result=result)
requires_review = runtime_budget_stopped or _result_requires_review(units=units, result=result)
summary = {
'run_no': run.run_no, 'batch_no': result.get('batch_no'),
'created_count': int(result.get('created_count') or 0),
@@ -211,20 +727,45 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
'non_shipping_count': int(result.get('non_shipping_count') or 0),
'execution': execution, 'requires_review': requires_review,
}
transition_order_extraction_run(run, target_status='result_persisted', phase='result_persisted', result=summary)
db.session.commit()
final_status = 'needs_review' if requires_review else 'completed'
final_status = (
'failed'
if execution['deterministic_unit_count'] == 0 and execution['failed_unit_count'] > 0 and execution['review_required_unit_count'] == 0
else 'review_required'
if execution['deterministic_unit_count'] == 0 and execution['review_required_unit_count'] > 0 and execution['failed_unit_count'] == 0
else 'partially_completed'
if requires_review
else 'completed'
)
selection_summary = _selection_progress_summary(run)
if selection_summary['budget_limited_attachment_count'] > 0 and final_status != 'completed':
budget_stop_reason_codes = _expansion_trigger_reason_codes(
wave_units=units,
wave_orders=_mark_expandable_business_gaps(run, orders=merged_orders),
)
record_run_progress(
run=run,
event_code='budget_stopped',
summary={
**selection_summary,
'execution': execution,
'requires_review': requires_review,
'reason_codes': budget_stop_reason_codes,
},
reason_code='budget_initial_limit',
job_id=job.id,
)
transition_order_extraction_run(run, target_status=final_status, result=summary)
record_run_progress(run=run, event_code='run_completed', summary=summary, job_id=job.id)
db.session.commit()
finish_job(job.id, result=summary, message='订单抽取完成', owned_attempt=owned_attempt)
except Exception as exc:
db.session.rollback()
run = ShippingOrderExtractionRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
retryable = not isinstance(exc, AppError) or bool(getattr(exc, 'retryable', False))
if run is not None and run.status in {'queued', 'running', 'failed'}:
if run is not None and run.status in {'queued', 'processing', 'failed'}:
running_unit = ShippingOrderExtractionUnit.query.join(ShippingOrderExtractionPlan).filter(
ShippingOrderExtractionPlan.run_id == run.id,
ShippingOrderExtractionUnit.status == 'running',
ShippingOrderExtractionUnit.status.in_(['routing', 'matching_profile', 'extracting', 'merging_supplement']),
).first()
if running_unit is not None:
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
@@ -234,12 +775,27 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
error_code=str(getattr(exc, 'code', None) or 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED'),
error_message=str(exc),
)
record_unit_progress(
run=run,
unit=running_unit,
event_code='technical_failed',
reason_code=str(getattr(exc, 'code', None) or 'technical_failure'),
job_id=job.id,
)
if retryable and owned_attempt < int(job.max_attempts or 1):
if run.status == 'running':
if run.status == 'processing':
if running_unit is not None:
record_unit_progress(
run=run,
unit=running_unit,
event_code='technical_retrying',
reason_code=str(getattr(exc, 'code', None) or 'technical_failure'),
job_id=job.id,
)
transition_order_extraction_run(run, target_status='queued', phase='retry_queued')
elif run.status in {'queued', 'running'}:
elif run.status in {'queued', 'processing'}:
if run.status == 'queued':
transition_order_extraction_run(run, target_status='running', phase='failing')
transition_order_extraction_run(run, target_status='processing', phase='failing')
transition_order_extraction_run(
run, target_status='failed',
error_code=str(getattr(exc, 'code', None) or 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED'),
-2
View File
@@ -7,7 +7,6 @@ backend/app/models/__init__.py
"""
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
from app.models.agent_runtime_binding import AgentRuntimeBinding
from app.models.base import Base, user_agent_permissions
from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, GeneralFeedback
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
@@ -132,7 +131,6 @@ __all__ = [
'UserDefaultAgent',
'User',
'Agent',
'AgentRuntimeBinding',
'ChatSession',
'ChatLog',
'ChatToolRun',
+1 -6
View File
@@ -11,7 +11,7 @@ from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Integer, Index, JSON, String, Text, UniqueConstraint, text
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, Index, JSON, String, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base, user_agent_permissions
@@ -26,10 +26,6 @@ class Agent(Base):
__tablename__ = 'agents'
__table_args__ = (
CheckConstraint(
"exposure_mode IN ('workspace', 'internal')",
name='ck_agents_exposure_mode',
),
Index('uq_agents_one_active_shipping_notice', 'agent_code', unique=True,
postgresql_where=text("agent_code = 'shipping_notice' AND is_active = true"),
sqlite_where=text("agent_code = 'shipping_notice' AND is_active = 1")),
@@ -53,7 +49,6 @@ class Agent(Base):
runtime_provider: Mapped[str] = mapped_column(String(32), default='dify', nullable=False)
conversation_mode: Mapped[str] = mapped_column(String(32), default='chat', nullable=False)
dify_app_type: Mapped[str] = mapped_column(String(20), default='chatflow', nullable=False)
exposure_mode: Mapped[str] = mapped_column(String(20), default='workspace', nullable=False)
iframe_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
category: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
sub_category: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
@@ -1,45 +0,0 @@
"""
backend/app/models/agent_runtime_binding.py
用途:定义用户入口 Agent 到内部运行能力 Provider 的显式绑定。
依赖:agents 表。
逻辑:业务代码按 owner_agent_id + capability_code 解析 Provider;执行策略仅保存通用超时与重试参数。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import Boolean, ForeignKey, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class AgentRuntimeBinding(Base):
"""一个 Agent 的命名运行能力绑定;同一能力只允许一个当前 Provider。"""
__tablename__ = 'agent_runtime_bindings'
__table_args__ = (
UniqueConstraint('owner_agent_id', 'capability_code', name='uq_agent_runtime_binding_capability'),
)
id: Mapped[int] = mapped_column(primary_key=True)
owner_agent_id: Mapped[int] = mapped_column(
ForeignKey('agents.id', ondelete='CASCADE'), nullable=False, index=True,
)
capability_code: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
provider_agent_id: Mapped[int] = mapped_column(
ForeignKey('agents.id'), nullable=False, index=True,
)
enabled: Mapped[bool] = mapped_column(Boolean, default=True, server_default='1', nullable=False)
quality_batch_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_extraction_quality_batches.id'), nullable=True, index=True,
)
config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
owner_agent: Mapped['Agent'] = relationship('Agent', foreign_keys=[owner_agent_id])
provider_agent: Mapped['Agent'] = relationship('Agent', foreign_keys=[provider_agent_id])
+4
View File
@@ -14,6 +14,7 @@ backend/app/models/shipping.py
from __future__ import annotations
import uuid
from datetime import datetime
from typing import List, Optional
@@ -434,6 +435,7 @@ class ShippingNoticeIntake(Base):
name='uq_shipping_notice_intakes_asset_purpose_parser',
),
Index('ix_shipping_notice_intakes_user_conversation_created', 'user_id', 'conversation_id', 'created_at'),
Index('ix_shipping_notice_intakes_user_upload_batch_created', 'user_id', 'upload_batch_id', 'created_at'),
Index('ix_shipping_notice_intakes_parse_status_created', 'parse_status', 'created_at'),
Index('ix_shipping_notice_intakes_expires', 'expires_at'),
Index('ix_shipping_notice_intakes_user_business_fingerprint', 'user_id', 'business_fingerprint'),
@@ -447,6 +449,8 @@ class ShippingNoticeIntake(Base):
asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=False)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True, nullable=False)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
# 同一输入框一次选取的上传批次;发送端只能冻结同一批次的 Intake。
upload_batch_id: Mapped[str] = mapped_column(String(36), nullable=False, default=lambda: str(uuid.uuid4()))
purpose: Mapped[str] = mapped_column(String(32), default='shipping_notice', nullable=False)
parse_status: Mapped[str] = mapped_column(String(32), default='created', nullable=False, index=True)
order_extraction_status: Mapped[str] = mapped_column(
@@ -11,7 +11,7 @@ from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint
from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
@@ -45,6 +45,13 @@ class ShippingDocumentProfileAutoFreezeQualification(Base):
quality_suite_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_document_profile_test_suites.id'), nullable=True,
)
customer_ids_json: Mapped[Optional[list[int]]] = mapped_column(JSON, nullable=True)
business_scenarios_json: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)
requires_customer_confirmation: Mapped[bool] = mapped_column(
Boolean, nullable=False, default=True, server_default=text('true'),
)
scope_updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
scope_updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
status: Mapped[str] = mapped_column(
String(32), nullable=False, default='manual_confirmation', server_default='manual_confirmation',
)
@@ -37,8 +37,8 @@ class ShippingOrderExtractionRun(Base):
UniqueConstraint('run_no', name='uq_shipping_order_extraction_runs_no'),
UniqueConstraint('idempotency_key', name='uq_shipping_order_extraction_runs_idempotency'),
CheckConstraint(
"status IN ('queued', 'running', 'result_persisted', 'completed', "
"'needs_review', 'failed', 'cancelled')",
"status IN ('queued', 'processing', 'completed', "
"'partially_completed', 'review_required', 'failed', 'cancelled')",
name='ck_shipping_order_extraction_runs_status',
),
Index('ix_shipping_order_extraction_runs_user_created', 'user_id', 'created_at'),
@@ -50,8 +50,8 @@ class ShippingOrderExtractionRun(Base):
'owner_agent_id',
'conversation_id',
unique=True,
postgresql_where=text("status IN ('queued', 'running', 'result_persisted')"),
sqlite_where=text("status IN ('queued', 'running', 'result_persisted')"),
postgresql_where=text("status IN ('queued', 'processing')"),
sqlite_where=text("status IN ('queued', 'processing')"),
),
)
@@ -76,6 +76,9 @@ class ShippingOrderExtractionRun(Base):
schema_version_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_schema_versions.id'), nullable=False,
)
# 请求快照是发送时的审计与幂等锚点;Worker 后续可物化 input_snapshot_* 作为执行快照。
request_snapshot_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
request_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False)
input_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False)
idempotency_key: Mapped[str] = mapped_column(String(64), nullable=False)
@@ -189,7 +192,7 @@ class ShippingOrderExtractionPlan(Base):
class ShippingOrderExtractionUnit(Base):
"""计划内单个冻结文档抽取单元;状态、结果和错误相互隔离。"""
"""计划内单个冻结附件抽取单元;状态、选择事实和错误相互隔离。"""
__tablename__ = 'shipping_order_extraction_units'
__table_args__ = (
@@ -200,7 +203,8 @@ class ShippingOrderExtractionUnit(Base):
name='ck_shipping_order_extraction_units_type',
),
CheckConstraint(
"status IN ('pending', 'running', 'succeeded', 'failed', 'skipped')",
"status IN ('pending', 'routing', 'matching_profile', 'extracting', "
"'merging_supplement', 'candidate_ready', 'review_required', 'failed', 'cancelled')",
name='ck_shipping_order_extraction_units_status',
),
ForeignKeyConstraint(
@@ -222,11 +226,20 @@ class ShippingOrderExtractionUnit(Base):
unit_type: Mapped[str] = mapped_column(String(32), nullable=False)
document_type: Mapped[str] = mapped_column(String(32), nullable=False)
content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
selection_batch: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
selection_reason_codes_json: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)
group_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
budget_cost_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
retry_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
technical_failure_reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
attempt_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
last_activity_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -286,29 +299,31 @@ class ShippingOrderExtractionRouteDecision(Base):
class ShippingOrderExtractionProgressEvent(Base):
"""订单抽取的脱敏进度明细;事件幂等键抵御 SSE 断线重放。"""
"""订单抽取的可恢复业务事件;用户态与管理员态通过 visibility 隔离。"""
__tablename__ = 'shipping_order_extraction_progress_events'
__table_args__ = (
UniqueConstraint('idempotency_key', name='uq_shipping_order_extraction_progress_event_key'),
Index('ix_shipping_order_extraction_progress_events_run_created', 'run_id', 'created_at'),
UniqueConstraint('run_id', 'sequence_no', name='uq_shipping_order_extraction_progress_event_sequence'),
Index('ix_shipping_order_extraction_progress_events_run_sequence', 'run_id', 'sequence_no'),
Index('ix_shipping_order_extraction_progress_events_expires_id', 'expires_at', 'id'),
Index('ix_shipping_order_extraction_progress_events_workflow_node', 'workflow_run_id', 'node_execution_id'),
Index('ix_shipping_order_extraction_progress_events_run_visibility', 'run_id', 'visibility', 'sequence_no'),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extraction_runs.id', ondelete='CASCADE'), nullable=False)
unit_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_extraction_units.id', ondelete='CASCADE'), nullable=True)
document_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True)
attempt_count: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
workflow_run_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
node_execution_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
event_type: Mapped[str] = mapped_column(String(64), nullable=False)
node_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
stage_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
event_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
provider_occurred_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
sequence_no: Mapped[int] = mapped_column(Integer, nullable=False)
visibility: Mapped[str] = mapped_column(String(32), nullable=False, default='workspace', server_default='workspace')
event_code: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='completed', server_default='completed')
occurred_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
received_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
details_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
mapping_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
+6 -72
View File
@@ -14,8 +14,8 @@ import requests
from app import db
from app.core.config.settings import Config
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import Agent, AgentRuntimeBinding, ShippingOrderExtractionRun, User
from app.core.errors import NotFoundError, ValidationError
from app.models import Agent, User
from app.services.agent_directory import normalize_directory_member_ids, replace_directory_members
from app.services.admin.training_exam_pdf_service import parse_training_question_bank_from_guide
from app.services.agent_registry.admin_payload import apply_agent_payload, validate_agent_payload
@@ -29,20 +29,9 @@ def serialize_agent(agent: Agent) -> dict:
return serialize_agent_for_admin(agent)
def list_agents(*, scope: str | None = None) -> list[dict]:
"""按管理域返回 Agent;scope=applications/executors,缺省返回全部兼容旧客户端。"""
query = db.session.query(Agent)
if scope == 'applications':
query = query.filter(Agent.exposure_mode == 'workspace')
elif scope == 'executors':
query = query.filter(Agent.exposure_mode == 'internal')
elif scope not in (None, ''):
raise ValidationError(
'Invalid agent management scope',
code='AGENT.ADMIN_SCOPE_INVALID',
details={'scope': scope},
)
agents = query.order_by(Agent.id.asc()).all()
def list_agents() -> list[dict]:
"""返回全部 Agent(按 id 升序)。"""
agents = db.session.query(Agent).order_by(Agent.id.asc()).all()
return [serialize_agent(a) for a in agents]
@@ -71,24 +60,6 @@ def create_agent(data: dict[str, Any]) -> dict:
db.session.flush()
member_ids = data.get('directory_member_ids') if agent.is_aggregate else []
replace_directory_members(agent, normalize_directory_member_ids(member_ids, directory_agent_id=agent.id))
runtime_binding = data.get('order_extraction_runtime_binding')
if runtime_binding is not None:
if not isinstance(runtime_binding, dict):
raise ValidationError('order_extraction_runtime_binding 必须为 JSON 对象')
try:
provider_agent_id = int(runtime_binding.get('provider_agent_id'))
except (TypeError, ValueError) as exc:
raise ValidationError('provider_agent_id is required') from exc
from app.services.agent_runtime_binding_service import save_runtime_binding
save_runtime_binding(
owner_agent_id=agent.id,
capability_code='shipping.order_extraction',
provider_agent_id=provider_agent_id,
enabled=runtime_binding.get('enabled') is not False,
config=runtime_binding.get('config'),
commit=False,
)
db.session.commit()
return {'id': agent.id}
@@ -115,7 +86,6 @@ def update_agent(agent_id: int, data: dict[str, Any]) -> None:
'runtime_provider': data.get('runtime_provider', agent.runtime_provider),
'conversation_mode': data.get('conversation_mode', agent.conversation_mode),
'dify_app_type': data.get('dify_app_type', agent.dify_app_type),
'exposure_mode': data.get('exposure_mode', agent.exposure_mode),
'iframe_url': data.get('iframe_url', agent.iframe_url),
'category': data.get('category', agent.category),
'sub_category': data.get('sub_category', agent.sub_category),
@@ -138,44 +108,13 @@ def update_agent(agent_id: int, data: dict[str, Any]) -> None:
if 'directory_member_ids' in data or 'is_aggregate' in data:
member_ids = data.get('directory_member_ids') if agent.is_aggregate else []
replace_directory_members(agent, normalize_directory_member_ids(member_ids, directory_agent_id=agent.id))
runtime_binding = data.get('order_extraction_runtime_binding')
if runtime_binding is not None:
if not isinstance(runtime_binding, dict):
raise ValidationError('order_extraction_runtime_binding 必须为 JSON 对象')
try:
provider_agent_id = int(runtime_binding.get('provider_agent_id'))
except (TypeError, ValueError) as exc:
raise ValidationError('provider_agent_id is required') from exc
from app.services.agent_runtime_binding_service import save_runtime_binding
save_runtime_binding(
owner_agent_id=agent.id,
capability_code='shipping.order_extraction',
provider_agent_id=provider_agent_id,
enabled=runtime_binding.get('enabled') is not False,
config=runtime_binding.get('config'),
commit=False,
)
db.session.commit()
def delete_agent(agent_id: int) -> None:
"""删除 Agent;被能力绑定或历史订单抽取 Run 引用时明确阻断。"""
"""删除 Agent(不存在时静默成功)。"""
agent = db.session.get(Agent, agent_id)
if agent:
binding_count = AgentRuntimeBinding.query.filter(
(AgentRuntimeBinding.owner_agent_id == agent.id)
| (AgentRuntimeBinding.provider_agent_id == agent.id)
).count()
run_count = ShippingOrderExtractionRun.query.filter(
(ShippingOrderExtractionRun.owner_agent_id == agent.id)
).count()
if binding_count or run_count:
raise ConflictError(
'Agent is referenced by runtime capability history',
code='AGENT.RUNTIME_PROVIDER_DELETE_BLOCKED',
details={'binding_count': binding_count, 'run_count': run_count},
)
db.session.delete(agent)
db.session.commit()
@@ -356,11 +295,6 @@ def update_agent_permissions(agent_id: int, user_ids: list[int]) -> None:
agent = db.session.get(Agent, agent_id)
if not agent:
raise NotFoundError('Not found')
if agent.exposure_mode == 'internal' and user_ids:
raise ValidationError(
'内部执行器不可授予用户权限',
code='AGENT.INTERNAL_EXECUTOR_PERMISSION_FORBIDDEN',
)
current_users = db.session.query(User).filter(User.agents.contains(agent)).all()
current_user_ids = {u.id for u in current_users}
new_user_ids = set(user_ids)
@@ -20,12 +20,7 @@ def compute_dashboard_summary() -> dict:
agent_count、user_count、total_conversations、avg_score。
"""
total_users = db.session.query(func.count(User.id)).scalar() or 0
active_agents = (
db.session.query(func.count(Agent.id))
.filter(Agent.is_active.is_(True), Agent.exposure_mode == 'workspace')
.scalar()
or 0
)
active_agents = db.session.query(func.count(Agent.id)).filter_by(is_active=True).scalar() or 0
total_conversations = db.session.query(func.count(ChatLog.id)).scalar() or 0
avg_score = db.session.query(func.avg(Feedback.score)).scalar()
avg_score = round(float(avg_score), 1) if avg_score else 0.0
@@ -44,13 +39,7 @@ def compute_dashboard_badges() -> dict:
pending_approvals、pending_requests。
"""
pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar() or 0
pending_requests = (
db.session.query(func.count(PermissionRequest.id))
.join(Agent, Agent.id == PermissionRequest.agent_id)
.filter(PermissionRequest.status == 'pending', Agent.exposure_mode == 'workspace')
.scalar()
or 0
)
pending_requests = db.session.query(func.count(PermissionRequest.id)).filter_by(status='pending').scalar() or 0
return {
'pending_approvals': pending_approvals,
'pending_requests': pending_requests,
-11
View File
@@ -13,7 +13,6 @@ from typing import Any
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import Agent, KbDocument, QuickQuestion
from app.services.agent_user_access import is_user_application, require_user_application
def parse_aliases(raw_aliases) -> list[str]:
@@ -83,7 +82,6 @@ def apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answe
if 'question' in data:
qq.question = str(data['question']).strip()
if 'agent_id' in data:
require_user_application(db.session.get(Agent, data['agent_id']))
qq.agent_id = data['agent_id']
if 'sort_order' in data:
qq.sort_order = data.get('sort_order', 0)
@@ -124,8 +122,6 @@ def list_quick_questions(*, stale_only: bool = False) -> list[dict]:
rows = []
for q in query.all():
agent = db.session.get(Agent, q.agent_id)
if not is_user_application(agent):
continue
stale_doc = db.session.get(KbDocument, q.stale_kb_document_id) if q.stale_kb_document_id else None
rows.append(serialize_quick_question(q, agent.name if agent else 'Unknown', stale_doc))
return rows
@@ -168,8 +164,6 @@ def list_faq_candidates(*, agent_id: int | None = None) -> dict:
from app.services.hot_faq_aggregator import HotFaqAggregator
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
if agent_id is not None:
require_user_application(db.session.get(Agent, agent_id))
items = HotFaqCandidateStore.list_candidates(agent_id)
return {
'items': items,
@@ -182,8 +176,6 @@ def refresh_faq_candidates(*, agent_id: int | None, dry_run: bool) -> dict:
"""手动触发离线热点聚合。"""
from app.services.hot_faq_aggregator import HotFaqAggregator
if agent_id is not None:
require_user_application(db.session.get(Agent, agent_id))
return HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run)
@@ -197,8 +189,6 @@ def promote_faq_candidate(data: dict[str, Any]) -> dict:
q_norm = normalize_faq_query(str(data.get('q_norm') or ''))
if not agent_id or not q_norm:
raise ValidationError('agent_id and q_norm are required')
require_user_application(db.session.get(Agent, agent_id))
candidate = HotFaqCandidateStore.get_candidate(int(agent_id), q_norm)
if not candidate:
raise NotFoundError('FAQ candidate not found')
@@ -242,6 +232,5 @@ def dismiss_faq_candidate(*, agent_id: int, q_norm: str) -> dict:
normalized = normalize_faq_query(q_norm)
if not agent_id or not normalized:
raise ValidationError('agent_id and q_norm are required')
require_user_application(db.session.get(Agent, agent_id))
HotFaqCandidateStore.dismiss(int(agent_id), normalized)
return {'status': 'ok'}
@@ -13,7 +13,6 @@ from typing import Any
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import Agent, PermissionRequest, User
from app.services.agent_user_access import load_grantable_agents, require_user_application
from app.services.wecom_notify import send_wecom_event_message
_BATCH_ACTION_LABELS = {'add': '新增', 'remove': '移除', 'set': '重置为'}
@@ -33,7 +32,7 @@ def serialize_permission_request(req: PermissionRequest) -> dict:
def _load_users_and_agents(user_ids: list[Any], agent_ids: list[Any]) -> tuple[list[User], list[Agent]]:
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
agents = load_grantable_agents(agent_ids)
agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all()
return users, agents
@@ -105,18 +104,16 @@ def update_user_permissions(user_id: int, data: dict[str, Any]) -> dict:
if not user:
raise NotFoundError('Not found')
agent_ids = data.get('agent_ids', [])
agents = load_grantable_agents(agent_ids)
agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all()
user.agents = agents
db.session.commit()
return {'status': 'ok'}
def list_permission_requests() -> list[dict]:
"""返回 workspace 应用的权限申请;内部执行器申请仅保留数据库审计。"""
"""返回全部权限申请(按 created_at 降序)。"""
reqs = (
db.session.query(PermissionRequest)
.join(Agent, Agent.id == PermissionRequest.agent_id)
.filter(Agent.exposure_mode == 'workspace')
.order_by(PermissionRequest.created_at.desc())
.all()
)
@@ -135,9 +132,6 @@ def approve_permission_request(request_id: int) -> dict:
user = db.session.get(User, req.user_id)
agent = db.session.get(Agent, req.agent_id)
if not user:
raise NotFoundError('User not found')
require_user_application(agent)
req.status = 'approved'
req.reviewed_at = datetime.utcnow()
if user and agent and (agent not in user.agents):
@@ -286,7 +286,6 @@ def build_application_report(
.outerjoin(auth_stats, auth_stats.c.agent_id == Agent.id)
.outerjoin(pending_stats, pending_stats.c.agent_id == Agent.id)
.outerjoin(feedback_stats, feedback_stats.c.agent_id == Agent.id)
.filter(Agent.exposure_mode == 'workspace')
)
if status_key == 'active':
query = query.filter(Agent.is_active.is_(True))
+3 -4
View File
@@ -16,7 +16,6 @@ from sqlalchemy.orm import joinedload
from app import db
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.models import Agent, User
from app.services.agent_user_access import is_user_application, load_grantable_agents
from app.services.auth import casdoor_service
from app.services.user_admin import delete_admin_users
@@ -81,7 +80,7 @@ def serialize_admin_user(user: User) -> dict:
'employee_id': user.employee_id,
'phone_number': user.phone_number,
'feature_permissions': user.get_feature_permissions(),
'agent_ids': [agent.id for agent in user.agents if is_user_application(agent)],
'agent_ids': [agent.id for agent in user.agents],
}
@@ -210,7 +209,7 @@ def create_user(data: dict[str, Any]) -> dict:
db.session.add(user)
try:
if data.get('agent_ids'):
agents = load_grantable_agents(data['agent_ids'])
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents
casdoor_service.sync_create_user(
username=user.username,
@@ -262,7 +261,7 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict:
if new_password:
user.set_password(new_password)
if 'agent_ids' in data:
agents = load_grantable_agents(data['agent_ids'])
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents
if new_password:
casdoor_service.sync_update_user(user, new_password=new_password)
@@ -20,7 +20,6 @@ from app import db
from app.core.config.env_persistence import persist_env_settings
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.models import Agent, LoginAudit, User, WecomNotifyAudit
from app.services.agent_user_access import load_grantable_agents
from app.services.auth import wecom_auth_service
from app.services.oa_wecom_sync import sync_wecom_userids_from_oa
@@ -314,11 +313,10 @@ def provision_user(data: dict[str, Any]) -> tuple[dict, int]:
except (TypeError, ValueError):
db.session.rollback()
raise ValidationError('agent_ids must be integer array')
try:
agents = load_grantable_agents(unique_ids)
except ValidationError:
agents = db.session.query(Agent).filter(Agent.id.in_(unique_ids)).all()
if len(agents) != len(unique_ids):
db.session.rollback()
raise
raise ValidationError('Some agent_ids are invalid')
user.agents = agents
else:
user.agents = []
@@ -17,7 +17,6 @@ from app.services.agent_registry.resolver import (
normalize_capabilities,
resolve_agent_code,
resolve_conversation_mode,
resolve_effective_role,
resolve_capabilities,
resolve_handler,
resolve_handler_for_agent_code,
@@ -34,7 +33,6 @@ __all__ = [
'normalize_capabilities',
'resolve_agent_code',
'resolve_conversation_mode',
'resolve_effective_role',
'resolve_capabilities',
'resolve_handler',
'resolve_handler_for_agent_code',
@@ -35,7 +35,6 @@ MIGRATED_EXTRA_REGISTRY_KEYS = frozenset({
'runtime_provider',
'conversation_mode',
'dify_app_type',
'exposure_mode',
'iframe_url',
'category',
'sub_category',
@@ -151,7 +150,6 @@ def validate_agent_payload(
valid_runtime_providers = get_platform_enum_set('runtime_providers')
valid_conversation_modes = get_platform_enum_set('conversation_modes')
valid_dify_app_types = get_platform_enum_set('dify_app_types')
valid_exposure_modes = get_platform_enum_set('exposure_modes')
valid_suggested_styles = get_platform_enum_set('suggested_questions_styles')
dify_required_providers = get_dify_required_providers()
@@ -177,26 +175,6 @@ def validate_agent_payload(
if dify_app_type not in valid_dify_app_types:
dify_app_type = 'chatflow'
exposure_mode = _strip(data.get('exposure_mode')) or (
getattr(agent, 'exposure_mode', None) if agent else 'workspace'
) or 'workspace'
if exposure_mode not in valid_exposure_modes:
raise ValidationError(f'无效的 exposure_mode: {exposure_mode}')
existing_exposure = _strip(getattr(agent, 'exposure_mode', None) if agent else '')
if agent is not None and existing_exposure and exposure_mode != existing_exposure:
raise ValidationError(
'应用与内部执行器不可互相转换',
code='AGENT.EXPOSURE_ROLE_IMMUTABLE',
)
# 新建内部执行器统一使用 Dify Workflow;历史内部记录保留原组合以兼容旧数据。
if exposure_mode == 'internal' and agent is None:
if runtime_provider != 'dify' or dify_app_type != 'workflow':
raise ValidationError(
'新建内部执行器必须使用 runtime_provider=dify 与 dify_app_type=workflow',
code='AGENT.INTERNAL_EXECUTOR_CONFIG_INVALID',
)
dify_app_id = _strip(data.get('dify_app_id')) or (agent.dify_app_id if agent else '')
if runtime_provider in dify_required_providers and not dify_app_id:
raise ValidationError('runtime_provider 含 dify 时 dify_app_id 必填')
@@ -282,7 +260,6 @@ def validate_agent_payload(
'runtime_provider': runtime_provider,
'conversation_mode': conversation_mode,
'dify_app_type': dify_app_type,
'exposure_mode': exposure_mode,
'iframe_url': iframe_url or None,
'category': _strip(data.get('category')) or None,
'sub_category': _strip(data.get('sub_category')) or None,
@@ -308,7 +285,7 @@ def apply_agent_payload(agent: Agent, normalized: dict[str, Any]) -> None:
"""
column_fields = (
'name', 'description', 'icon_url', 'is_active', 'is_aggregate', 'dify_app_id', 'api_base_url', 'type',
'agent_code', 'runtime_provider', 'conversation_mode', 'dify_app_type', 'exposure_mode', 'iframe_url',
'agent_code', 'runtime_provider', 'conversation_mode', 'dify_app_type', 'iframe_url',
'category', 'sub_category', 'sort_order', 'welcome_message', 'suggested_questions_style',
'suggested_questions', 'capabilities', 'file_upload_policy', 'bound_schedule_task_id',
'handler_config',
@@ -46,7 +46,6 @@ def build_agent_registry_schema() -> dict[str, Any]:
'forced_capabilities': dict(entry.get('forced_capabilities') or {}),
'progress_contract': deepcopy_schema(entry.get('progress_contract')),
'default_intent_routes': list(entry.get('default_intent_routes') or []),
'required_runtime_capabilities': deepcopy_schema(entry.get('required_runtime_capabilities')),
})
return {
@@ -54,7 +53,6 @@ def build_agent_registry_schema() -> dict[str, Any]:
'runtime_providers': list(platform.get('runtime_providers') or []),
'conversation_modes': list(platform.get('conversation_modes') or []),
'dify_app_types': list(platform.get('dify_app_types') or []),
'exposure_modes': list(platform.get('exposure_modes') or []),
'suggested_questions_styles': list(platform.get('suggested_questions_styles') or []),
'default_capabilities': get_default_capabilities(),
'tool_run_progress_defaults': get_tool_run_progress_defaults(),
@@ -14,9 +14,6 @@ platform:
dify_app_types:
- chatflow
- workflow
exposure_modes:
- workspace
- internal
suggested_questions_styles:
- plain
- styled
@@ -152,23 +152,6 @@ def resolve_conversation_mode(agent) -> str:
return _read_string_column(agent, 'conversation_mode', default=_COLUMN_DEFAULTS['conversation_mode'])
def resolve_effective_role(agent) -> str:
"""
解析 Agent 的运行时角色,不新增数据库字段。
核心逻辑:internal Provider 统一视为内部执行器,其余注册项继续视为用户入口;
历史 conversation_mode 保留用于兼容,但内部执行器运行时不参与聊天呈现。
Args:
agent: Agent ORM 或具备 exposure_mode 属性的代理对象。
Returns:
user_agent 或 internal_executor。
"""
exposure_mode = _read_string_column(agent, 'exposure_mode', default='workspace')
return 'internal_executor' if exposure_mode == 'internal' else 'user_agent'
def resolve_capabilities(agent) -> dict[str, bool]:
"""
解析 Agent 平台能力声明。
@@ -15,7 +15,6 @@ from app.services.agent_registry.resolver import (
resolve_agent_code,
resolve_capabilities,
resolve_conversation_mode,
resolve_effective_role,
resolve_progress_contract,
resolve_runtime_provider,
)
@@ -49,9 +48,7 @@ def serialize_registry_fields(agent: Agent | Any) -> dict[str, Any]:
'agent_code': resolve_agent_code(agent),
'runtime_provider': resolve_runtime_provider(agent),
'conversation_mode': resolve_conversation_mode(agent),
'effective_role': resolve_effective_role(agent),
'dify_app_type': getattr(agent, 'dify_app_type', None) or 'chatflow',
'exposure_mode': getattr(agent, 'exposure_mode', None) or 'workspace',
'iframe_url': getattr(agent, 'iframe_url', None),
'category': getattr(agent, 'category', None) or None,
'sub_category': getattr(agent, 'sub_category', None) or None,
@@ -1,219 +0,0 @@
"""
backend/app/services/agent_runtime_binding_service.py
用途:解析、校验和管理 Agent 的命名运行能力 Provider 绑定。
依赖:Agent/AgentRuntimeBinding、Agent Catalog、统一 AppError。
逻辑:Catalog 声明 owner 需要的能力和 Provider 约束;管理员只保存 Agent 外键,运行时禁止名称或环境变量回退。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import Agent, AgentRuntimeBinding
from app.services.agent_registry.catalog import get_catalog_entry
from app.services.agent_registry.resolver import resolve_effective_role
_EXECUTOR_GOVERNANCE_DEFAULTS = {
'provider_max_concurrency': 4,
'circuit_failure_threshold': 5,
'circuit_cooldown_seconds': 60,
}
def _capability_definition(owner: Agent, capability_code: str) -> dict[str, Any]:
"""读取 owner Agent Catalog 中声明的能力定义;未声明能力不可由管理员任意绑定。"""
entry = get_catalog_entry(owner.agent_code) or {}
definitions = entry.get('required_runtime_capabilities')
definitions = definitions if isinstance(definitions, dict) else {}
definition = definitions.get(capability_code)
if not isinstance(definition, dict):
raise ValidationError(
'Runtime capability is not declared by the Agent Catalog',
code='AGENT.RUNTIME_CAPABILITY_NOT_DECLARED',
)
return definition
def _normalize_config(raw: Any) -> dict[str, Any]:
"""限制通用超时/重试配置,避免任意 JSON 成为隐式业务配置后门。"""
if raw is None:
raw = {}
if not isinstance(raw, dict):
raise ValidationError('config must be an object', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID')
unknown = set(raw) - {'timeout_seconds', 'max_attempts', 'auto_create_enabled'}
if unknown:
raise ValidationError(
'Unsupported runtime binding config keys',
code='AGENT.RUNTIME_BINDING_CONFIG_INVALID',
details={'keys': sorted(unknown)},
)
try:
timeout_seconds = int(raw.get('timeout_seconds', 900))
max_attempts = int(raw.get('max_attempts', 3))
except (TypeError, ValueError) as exc:
raise ValidationError(
'Runtime binding execution settings must be integers',
code='AGENT.RUNTIME_BINDING_CONFIG_INVALID',
) from exc
if not 30 <= timeout_seconds <= 3600 or not 1 <= max_attempts <= 10:
raise ValidationError(
'Runtime binding config is outside allowed limits',
code='AGENT.RUNTIME_BINDING_CONFIG_INVALID',
)
result = {
'timeout_seconds': timeout_seconds,
'max_attempts': max_attempts,
}
if 'auto_create_enabled' in raw:
if not isinstance(raw['auto_create_enabled'], bool):
raise ValidationError('auto_create_enabled must be boolean', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID')
result['auto_create_enabled'] = raw['auto_create_enabled']
return result
def resolve_executor_governance(provider: Agent) -> dict[str, int]:
"""读取内部执行器全局治理,供新 Run 冻结并避免入口应用绕过 Provider 保护。"""
raw_extra = provider.extra_config if isinstance(provider.extra_config, dict) else {}
raw = raw_extra.get('order_extraction_governance') if isinstance(raw_extra.get('order_extraction_governance'), dict) else {}
try:
config = {
'provider_max_concurrency': int(raw.get('provider_max_concurrency', _EXECUTOR_GOVERNANCE_DEFAULTS['provider_max_concurrency'])),
'circuit_failure_threshold': int(raw.get('circuit_failure_threshold', _EXECUTOR_GOVERNANCE_DEFAULTS['circuit_failure_threshold'])),
'circuit_cooldown_seconds': int(raw.get('circuit_cooldown_seconds', _EXECUTOR_GOVERNANCE_DEFAULTS['circuit_cooldown_seconds'])),
}
except (TypeError, ValueError) as exc:
raise ValidationError('Internal executor governance settings must be integers', code='AGENT.EXECUTOR_GOVERNANCE_INVALID') from exc
if not 1 <= config['provider_max_concurrency'] <= 20:
raise ValidationError('Internal executor concurrency is outside allowed limits', code='AGENT.EXECUTOR_GOVERNANCE_INVALID')
if not 2 <= config['circuit_failure_threshold'] <= 20 or not 10 <= config['circuit_cooldown_seconds'] <= 600:
raise ValidationError('Internal executor circuit settings are outside allowed limits', code='AGENT.EXECUTOR_GOVERNANCE_INVALID')
return config
def _validate_provider(provider: Agent, definition: dict[str, Any]) -> None:
"""按 Catalog 校验 Provider 类型、可见性和 Dify 配置完整性。"""
allowed_providers = set(definition.get('allowed_runtime_providers') or [])
allowed_app_types = set(definition.get('allowed_dify_app_types') or [])
allowed_exposure = set(definition.get('allowed_exposure_modes') or [])
allowed_roles = set(definition.get('allowed_effective_roles') or [])
if not provider.is_active:
raise ConflictError('Runtime provider is disabled', code='AGENT.RUNTIME_PROVIDER_DISABLED')
if allowed_providers and provider.runtime_provider not in allowed_providers:
raise ValidationError('Runtime provider type is invalid', code='AGENT.RUNTIME_PROVIDER_INVALID')
if allowed_app_types and provider.dify_app_type not in allowed_app_types:
raise ValidationError('Dify application type is invalid', code='AGENT.RUNTIME_PROVIDER_INVALID')
if allowed_exposure and provider.exposure_mode not in allowed_exposure:
raise ValidationError('Runtime provider exposure mode is invalid', code='AGENT.RUNTIME_PROVIDER_INVALID')
if allowed_roles and resolve_effective_role(provider) not in allowed_roles:
raise ValidationError('Runtime provider role is invalid', code='AGENT.RUNTIME_PROVIDER_INVALID')
if provider.runtime_provider in {'dify', 'hybrid'} and (
not str(provider.dify_app_id or '').strip()
or not str(provider.dify_api_key or '').strip()
or not str(provider.api_base_url or '').strip()
):
raise ConflictError(
'Runtime provider Dify configuration is incomplete',
code='AGENT.RUNTIME_PROVIDER_CONFIG_INCOMPLETE',
)
def serialize_runtime_binding(binding: AgentRuntimeBinding) -> dict[str, Any]:
"""输出管理端安全视图;不返回 Provider API Key。"""
provider = binding.provider_agent
return {
'id': binding.id,
'owner_agent_id': binding.owner_agent_id,
'capability_code': binding.capability_code,
'provider_agent_id': binding.provider_agent_id,
'provider': {
'id': provider.id,
'name': provider.name,
'runtime_provider': provider.runtime_provider,
'dify_app_type': provider.dify_app_type,
'exposure_mode': provider.exposure_mode,
'is_active': provider.is_active,
} if provider else None,
'enabled': bool(binding.enabled),
'quality_batch_id': binding.quality_batch_id,
'config': dict(binding.config_json or {}),
}
def list_runtime_bindings(owner_agent_id: int) -> list[dict[str, Any]]:
"""列出指定 owner Agent 的全部显式运行能力绑定。"""
owner = db.session.get(Agent, owner_agent_id)
if owner is None:
raise NotFoundError('Agent not found')
rows = AgentRuntimeBinding.query.filter_by(owner_agent_id=owner.id).order_by(
AgentRuntimeBinding.capability_code.asc(),
).all()
return [serialize_runtime_binding(row) for row in rows]
def save_runtime_binding(
*,
owner_agent_id: int,
capability_code: str,
provider_agent_id: int,
enabled: bool,
quality_batch_id: int | None = None,
config: Any,
commit: bool = True,
) -> AgentRuntimeBinding:
"""创建或更新能力绑定;开启自动建单时必须引用已批准质量批次。"""
owner = db.session.get(Agent, owner_agent_id)
provider = db.session.get(Agent, provider_agent_id)
if owner is None or provider is None:
raise NotFoundError('Agent not found')
code = str(capability_code or '').strip()
if owner.id == provider.id:
raise ValidationError('Owner and provider must be different Agents', code='AGENT.RUNTIME_PROVIDER_INVALID')
definition = _capability_definition(owner, code)
if enabled:
_validate_provider(provider, definition)
normalized_config = _normalize_config(config)
if code == 'shipping.order_extraction' and normalized_config.get('auto_create_enabled'):
from app.services.shipping_notice.order_extraction_quality_service import require_approved_quality_batch
from app.services.shipping_notice.order_schema.runtime import published_version
require_approved_quality_batch(
batch_id=quality_batch_id,
owner_agent_id=owner.id,
schema_version_id=int(published_version().id),
)
binding = AgentRuntimeBinding.query.filter_by(
owner_agent_id=owner.id, capability_code=code,
).first()
if binding is None:
binding = AgentRuntimeBinding(owner_agent_id=owner.id, capability_code=code)
db.session.add(binding)
binding.provider_agent_id = provider.id
binding.enabled = bool(enabled)
binding.quality_batch_id = int(quality_batch_id) if quality_batch_id is not None else None
binding.config_json = normalized_config
if commit:
db.session.commit()
else:
db.session.flush()
return binding
def resolve_runtime_binding(*, owner_agent_id: int, capability_code: str) -> AgentRuntimeBinding:
"""运行时解析启用绑定并复检 Provider;未配置时明确阻断,禁止任何隐式回退。"""
binding = AgentRuntimeBinding.query.filter_by(
owner_agent_id=owner_agent_id,
capability_code=capability_code,
enabled=True,
).first()
if binding is None:
raise ConflictError(
'Runtime capability provider is not configured',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_NOT_CONFIGURED',
)
definition = _capability_definition(binding.owner_agent, capability_code)
_validate_provider(binding.provider_agent, definition)
return binding
-106
View File
@@ -1,106 +0,0 @@
"""
backend/app/services/agent_user_access.py
用途:统一约束哪些 Agent 可以进入用户授权、工作台和普通对话链路。
依赖:SQLAlchemy Session、Agent/User 模型、统一业务异常。
逻辑:内部执行器只允许 Runtime Binding 后台调用;所有用户入口仅接受 workspace 应用。
"""
from __future__ import annotations
from collections.abc import Iterable
from app import db
from app.core.errors import ForbiddenError, NotFoundError, ValidationError
from app.models import Agent, User
USER_ACCESS_FORBIDDEN_CODE = 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN'
def is_user_application(agent: Agent | None, *, require_active: bool = False) -> bool:
"""判断 Agent 是否可进入用户侧;可选同时要求启用状态。"""
if agent is None or agent.exposure_mode != 'workspace':
return False
return bool(agent.is_active) if require_active else True
def load_grantable_agents(agent_ids: Iterable[object] | None) -> list[Agent]:
"""
加载可授予用户的应用并保持输入顺序。
参数约束:所有 ID 必须存在且属于 workspace;内部执行器不得被授权给任何用户。
"""
if agent_ids is not None and not isinstance(agent_ids, (list, tuple, set)):
raise ValidationError('agent_ids must be an array')
raw_ids = list(agent_ids or [])
try:
normalized_ids = list(dict.fromkeys(int(agent_id) for agent_id in raw_ids))
except (TypeError, ValueError) as exc:
raise ValidationError('agent_ids must be an integer array') from exc
if not normalized_ids:
return []
agents = db.session.query(Agent).filter(Agent.id.in_(normalized_ids)).all()
by_id = {agent.id: agent for agent in agents}
missing_ids = [agent_id for agent_id in normalized_ids if agent_id not in by_id]
if missing_ids:
raise ValidationError('Some agent_ids are invalid', details={'agent_ids': missing_ids})
internal_ids = [agent_id for agent_id in normalized_ids if not is_user_application(by_id[agent_id])]
if internal_ids:
raise ValidationError(
'Internal executors cannot be assigned to users',
code=USER_ACCESS_FORBIDDEN_CODE,
details={'agent_ids': internal_ids},
)
return [by_id[agent_id] for agent_id in normalized_ids]
def require_user_application(agent: Agent | None, *, require_active: bool = False) -> Agent:
"""要求目标是 workspace 应用;用户入口可额外要求启用状态。"""
if agent is None or (require_active and not agent.is_active):
raise NotFoundError('Agent not found')
if not is_user_application(agent):
raise ForbiddenError(
'Internal executors are unavailable from user-facing APIs',
code=USER_ACCESS_FORBIDDEN_CODE,
)
return agent
def require_user_application_access(agent: Agent | None, user: User) -> Agent:
"""
校验普通用户入口的 Agent 访问。
核心逻辑:先阻断停用项和内部执行器,再处理管理员全 workspace 可见、普通用户按授权可见。
"""
agent = require_user_application(agent, require_active=True)
if user.role != 'admin' and agent not in user.agents:
raise ForbiddenError('Permission denied for this agent')
return agent
def visible_default_agent_id(user: User) -> int | None:
"""返回可用于用户入口的默认应用 ID;历史内部执行器引用按未配置处理。"""
if user.default_agent_id is None:
return None
agent = db.session.get(Agent, user.default_agent_id)
if not is_user_application(agent, require_active=True):
return None
if user.role != 'admin' and agent not in user.agents:
return None
return int(agent.id)
def visible_agent_ids(user: User, *, active_only: bool = True) -> set[int]:
"""返回当前用户在用户侧实际可见的应用 ID 集合。"""
if user.role == 'admin':
query = db.session.query(Agent.id).filter(Agent.exposure_mode == 'workspace')
if active_only:
query = query.filter(Agent.is_active.is_(True))
return {int(row[0]) for row in query.all()}
return {
int(agent.id)
for agent in user.agents
if is_user_application(agent, require_active=active_only)
}
@@ -57,6 +57,12 @@ def is_attachment_parse_incomplete(structured: dict[str, Any] | None) -> bool:
if not isinstance(structured, dict):
return False
preview_status = str(structured.get('preview_status') or '').strip().lower()
if preview_status == 'directory_incomplete':
return True
if structured.get('attachment_directory_complete') is False:
return True
warnings = structured.get('warnings') or []
for item in warnings:
if is_blocking_warning(str(item or '')):
@@ -0,0 +1,279 @@
"""
services/shipping_notice/attachment_selection.py
用途:基于 Intake 快览事实生成可审计的附件选择计划。
依赖:ShippingNoticeIntake、标准库正则与哈希;只读取 structured_result_json,不回读 Document/布局结果。
逻辑:发送阶段调用本文件,把当前批次附件目录转换为“为何选择/为何跳过”的稳定计划;
后续深度解析、预算扩展与审计都应复用这份快照,而不是重新猜测附件优先级。
"""
from __future__ import annotations
import re
from collections import defaultdict
from typing import Any
from app.models import ShippingNoticeIntake
_PO_HINT_RE = re.compile(r'\b(?:PO[-_ ]*)?([A-Z]{0,4}\d{5,})\b', re.IGNORECASE)
_TOKEN_RE = re.compile(r'[A-Z0-9]{4,}', re.IGNORECASE)
_IMAGE_MIME_PREFIX = 'image/'
_READY_REASON = 'ready_for_extraction'
_EXCLUDED_CATALOG_REASONS = {
'archive',
'executable',
'macro_enabled',
'unknown_binary',
'inline_resource',
'signature_or_logo',
}
_TYPE_WEIGHTS: tuple[tuple[tuple[str, ...], int, str], ...] = (
(('application/pdf',), 160, 'type_pdf'),
((
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/msword',
), 80, 'type_word'),
((
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.ms-excel',
'text/csv',
), 90, 'type_spreadsheet'),
(('message/rfc822',), 70, 'type_nested_eml'),
)
_NAME_HINTS: tuple[tuple[str, int, str], ...] = (
('po', 60, 'filename_po_hint'),
('order', 45, 'filename_order_hint'),
('reservation', 40, 'filename_reservation_hint'),
('booking', 35, 'filename_booking_hint'),
('shipping', 20, 'filename_shipping_hint'),
)
_NEGATIVE_NAME_HINTS: tuple[tuple[str, int, str], ...] = (
('copy', -40, 'filename_copy_hint'),
('duplicate', -80, 'filename_duplicate_hint'),
('signature', -180, 'filename_signature_hint'),
('sign', -120, 'filename_sign_hint'),
('logo', -180, 'filename_logo_hint'),
('stamp', -100, 'filename_stamp_hint'),
)
def _structured(intake: ShippingNoticeIntake) -> dict[str, Any]:
"""读取 Intake 快览摘要;缺失时返回空对象,调用方决定是否视为不可选。"""
return intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
def _mail_text(structured: dict[str, Any]) -> str:
"""合并主题与正文白名单快照,供命名线索打分和分组使用。"""
email_meta = structured.get('email') if isinstance(structured.get('email'), dict) else {}
body_text = str(email_meta.get('body_text') or '').strip()
subject = str(email_meta.get('subject') or '').strip()
html_tables = ' '.join(
str(item).strip() for item in (email_meta.get('body_html_tables') or []) if str(item).strip()
)
return ' '.join(part for part in (subject, body_text, html_tables) if part).strip()
def _po_hints(*values: str) -> list[str]:
"""提取稳定的订单号线索;用于分组与评分,不输出正文原文。"""
found: list[str] = []
for value in values:
for item in _PO_HINT_RE.findall(str(value or '')):
normalized = str(item or '').strip().upper()
if normalized and normalized not in found:
found.append(normalized)
return found
def _mail_tokens(text: str) -> set[str]:
"""把邮件主题/正文压缩成稳定 token 集合,供附件名做轻量交叉评分。"""
return {token.upper() for token in _TOKEN_RE.findall(text or '') if len(token) >= 4}
def _score_attachment(*, filename: str, mime_type: str, size: int, mail_text: str) -> tuple[int, list[str], str]:
"""只基于快览可见事实为单个附件评分,并返回稳定原因码和分组键。"""
score = 0
reasons: list[str] = []
normalized_name = filename.lower()
normalized_mime = mime_type.lower()
tokens = _mail_tokens(mail_text)
name_tokens = {token.upper() for token in _TOKEN_RE.findall(filename or '') if len(token) >= 4}
for mime_prefixes, weight, reason in _TYPE_WEIGHTS:
if any(normalized_mime.startswith(prefix) for prefix in mime_prefixes):
score += weight
reasons.append(reason)
break
if size >= 1024 * 20:
score += 15
reasons.append('size_non_trivial')
if size >= 1024 * 1024:
score += 10
reasons.append('size_large_attachment')
if 0 < size <= 1024 * 8:
score -= 15
reasons.append('size_too_small')
for needle, weight, reason in _NAME_HINTS:
if needle in normalized_name:
score += weight
reasons.append(reason)
for needle, weight, reason in _NEGATIVE_NAME_HINTS:
if needle in normalized_name:
score += weight
reasons.append(reason)
po_hints = _po_hints(filename, mail_text)
if po_hints:
score += 80
reasons.append('po_hint_detected')
overlap = sorted(tokens & name_tokens)
if overlap:
score += min(30, len(overlap) * 10)
reasons.append('mail_filename_token_overlap')
group_key = po_hints[0] if po_hints else (overlap[0] if overlap else normalized_name[:48] or 'ungrouped')
return score, reasons, group_key
def build_attachment_selection_snapshot(
*,
intakes: list[ShippingNoticeIntake],
max_initial_attachments: int = 2,
max_initial_concurrency: int = 2,
expansion_batch_size: int = 2,
max_total_attachments: int = 6,
max_total_bytes: int | None = None,
max_runtime_seconds: int | None = None,
) -> dict[str, Any]:
"""
基于当前批次 Intake 快览事实生成可解释的附件选择计划。
AI 触发时机:点击发送后,需要把“当前输入框这批附件”冻结成一份稳定计划时使用。
该函数只能读取快览字段,禁止依赖附件正文、布局坐标、Document、Candidate 或 Provider 输出。
Args:
intakes: 当前发送批次的 Intake;必须已经通过上传快览。
max_initial_attachments: 首轮自动选择上限。
max_initial_concurrency: 首轮并发上限。
expansion_batch_size: 后续每轮扩展的附件上限。
max_total_attachments: 单次邮件深度解析总附件预算上限。
Returns:
可写入 Run 快照的脱敏计划摘要,包含每个附件的 selected / skipped 结论与原因码。
"""
rows: list[dict[str, Any]] = []
duplicate_content_hashes: dict[str, int] = defaultdict(int)
for intake in intakes:
structured = _structured(intake)
mail_text = _mail_text(structured)
attachments = structured.get('attachments') if isinstance(structured.get('attachments'), list) else []
for item in attachments:
if not isinstance(item, dict):
continue
filename = str(item.get('filename') or '').strip()
mime_type = str(item.get('mime_type') or 'application/octet-stream').strip().lower()
content_hash = str(item.get('content_hash') or '').strip().lower()
catalog_reason = str(item.get('catalog_reason') or '').strip().lower() or _READY_REASON
ready_for_extraction = bool(item.get('ready_for_extraction'))
is_inline = bool(item.get('is_inline_resource')) or mime_type.startswith(_IMAGE_MIME_PREFIX)
size = max(0, int(item.get('size') or 0))
if is_inline:
# 邮件签名和正文内嵌资源不是用户上传的业务附件,不纳入识别范围或数量统计。
continue
score, score_reasons, group_key = _score_attachment(
filename=filename,
mime_type=mime_type,
size=size,
mail_text=mail_text,
)
if content_hash:
duplicate_content_hashes[content_hash] += 1
rows.append({
'intake_no': intake.intake_no,
'attachment_key': str(item.get('attachment_key') or '').strip(),
'filename': filename,
'mime_type': mime_type,
'size': size,
'content_hash': content_hash or None,
'catalog_reason': catalog_reason,
'ready_for_extraction': ready_for_extraction,
'score': score,
'score_reasons': score_reasons,
'group_key': group_key,
'selected': False,
'selection_batch': None,
'planned_selection_batch': None,
'skip_reason_codes': [],
})
eligible: list[dict[str, Any]] = []
seen_hashes: set[str] = set()
for row in rows:
skip_reasons: list[str] = []
catalog_reason = str(row.get('catalog_reason') or _READY_REASON)
content_hash = str(row.get('content_hash') or '')
if not bool(row.get('ready_for_extraction')):
skip_reasons.append(f'catalog_reason:{catalog_reason}')
elif catalog_reason in _EXCLUDED_CATALOG_REASONS:
skip_reasons.append(f'catalog_reason:{catalog_reason}')
elif content_hash and content_hash in seen_hashes:
skip_reasons.append('duplicate_content_hash')
elif content_hash and duplicate_content_hashes.get(content_hash, 0) > 1:
seen_hashes.add(content_hash)
if not skip_reasons:
if content_hash:
seen_hashes.add(content_hash)
eligible.append(row)
else:
row['skip_reason_codes'] = skip_reasons
eligible_ordered = sorted(eligible, key=lambda item: (-int(item['score']), str(item['filename'])))
byte_budget = max(0, int(max_total_bytes or 0))
planned_bytes = 0
for index, row in enumerate(eligible_ordered):
size = int(row.get('size') or 0)
if byte_budget and planned_bytes + size > byte_budget:
row['skip_reason_codes'] = ['budget_total_bytes']
continue
if index < max_initial_attachments:
row['selected'] = True
row['selection_batch'] = 1
planned_bytes += size
continue
if index < max_total_attachments:
row['planned_selection_batch'] = (
2 + ((index - max_initial_attachments) // max(1, int(expansion_batch_size or 1)))
)
planned_bytes += size
continue
row['skip_reason_codes'] = ['budget_total_limit']
group_counts: dict[str, int] = defaultdict(int)
for row in rows:
group_counts[str(row.get('group_key') or 'ungrouped')] += 1
pending_expansion_batches: dict[int, int] = defaultdict(int)
for row in rows:
planned_batch = int(row.get('planned_selection_batch') or 0)
if planned_batch > 1:
pending_expansion_batches[planned_batch] += 1
return {
'selection_version': 'shipping_notice_attachment_selection.v1',
'max_initial_attachments': int(max_initial_attachments),
'max_initial_concurrency': int(max_initial_concurrency),
'expansion_batch_size': int(expansion_batch_size),
'max_total_attachments': int(max_total_attachments),
'max_total_bytes': int(max_total_bytes or 0),
'max_runtime_seconds': int(max_runtime_seconds or 0),
'planned_total_bytes': planned_bytes,
'total_attachment_count': len(rows),
'eligible_attachment_count': len(eligible),
'selected_attachment_count': sum(1 for row in rows if row.get('selected')),
'planned_attachment_count': sum(
1 for row in rows
if row.get('selected') or int(row.get('planned_selection_batch') or 0) > 1
),
'pending_expansion_attachment_count': sum(pending_expansion_batches.values()),
'pending_expansion_batches': {
str(batch): count for batch, count in sorted(pending_expansion_batches.items())
},
'group_count': len(group_counts),
'items': rows,
}
@@ -35,7 +35,10 @@ from app.services.shipping_notice.business_fingerprint import (
build_content_fingerprint,
)
from app.services.shipping_notice.eml_parse import pop_attachment_payload, strip_attachment_payloads
from app.services.shipping_notice.email_allocation_table_parser import parse_email_allocation_tables
from app.services.shipping_notice.email_allocation_table_parser import (
parse_email_allocation_tables,
parse_email_allocation_text,
)
from app.services.shipping_notice.intake_business_parser import parse_intake_business_summary
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
from app.services.shipping_notice.order_candidate_builder import (
@@ -465,6 +468,18 @@ def persist_documents_and_candidates(
from app.services.shipping_notice.duplicate_detection import detect_duplicates_for_candidate
meta = result.meta if isinstance(result.meta, dict) else {}
if str(meta.get('eml_attachment_mode') or '').strip().lower() == 'preview':
# 阶段 1 约束:EML 上传快览只保留目录,不得提前落附件 Document/派生资产或触发布局任务。
strip_attachment_payloads(meta)
return {
'document_count': 0,
'candidate_count': 0,
'linked_asset_count': 0,
'created_asset_count': 0,
'layout_version_count': 0,
'documents': [],
'candidates': [],
}
email_meta = meta.get('email') if isinstance(meta.get('email'), dict) else {}
body_text = str(email_meta.get('body_text') or '')
definition = schema_definition or {'fields': []}
@@ -539,6 +554,12 @@ def persist_documents_and_candidates(
html_tables=canonical_html_tables,
content_hash=str(body_doc.content_hash or ''),
)
# Outlook 等客户端可能把正文表展平成纯文本行;HTML 表为空时再使用严格序列解析。
if not supplement.get('rows') and not canonical_html_tables:
supplement = parse_email_allocation_text(
body_text=body_text,
content_hash=str(body_doc.content_hash or ''),
)
supplement['document_id'] = int(body_doc.id)
body_doc.order_extraction_result_json = {'email_supplement': supplement}
from app.services.shipping_notice.audit_service import append_shipping_audit_event
@@ -258,8 +258,26 @@ def reconstruct_coordinate_profile_rows(
for item in (exclusion_regions or []) if isinstance(item, dict)
]
if exclusions:
# Footer, signature and tax blocks are not candidate physical rows at all.
glyphs = [item for item in glyphs if not any(_inside_region(item[1].bbox, region) for region in exclusions)]
# Footer, signature and tax blocks are not candidate rows. Keep an explicit
# deletion marker from an exclusion region, however: it controls the prior
# detail row and must not be discarded before row reconstruction sees it.
deletion_marker_indices = {
glyph_index
for band in _group_visual_rows(glyphs)
if _DELETED_PATTERN.fullmatch(re.sub(
r'\s+', '', ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)),
))
and any(
any(_inside_region(glyph.bbox, region) for region in exclusions)
for glyph_index, glyph in band
)
for glyph_index, _glyph in band
}
glyphs = [
item for item in glyphs
if item[0] in deletion_marker_indices
or not any(_inside_region(item[1].bbox, region) for region in exclusions)
]
if not glyphs:
return []
@@ -11,7 +11,10 @@ from __future__ import annotations
from dataclasses import dataclass
from typing import Any
import cv2
try:
import cv2 # type: ignore
except ModuleNotFoundError:
cv2 = None
import numpy as np
from pydantic import BaseModel, ConfigDict, Field, model_validator
@@ -109,6 +112,8 @@ def reconstruct_opencv_table_geometry(
Returns:
ready 时包含所有 HTML 原始 cell 的页面 bbox;失败时仅包含问题码。
"""
if cv2 is None:
return _not_ready(grid, 'opencv_unavailable')
if min_consensus < 2 or len(configs) < min_consensus:
raise ValueError('OpenCV grid reconstruction requires at least two configurations')
image = _grayscale_page(page_image)
@@ -48,7 +48,8 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
if not tables or not pages or not glyph_tables:
# v2 模板按页面坐标区域取证;表格检测只能辅助,不能成为续页区域的硬前提。
if not pages or (not glyph_tables and not page_glyphs):
return ProfileMatchResult(status='evidence_insufficient')
candidates: list[tuple[dict[str, Any], OrderCoordinateProfileV2, ProfileMatchCandidate]] = []
@@ -65,8 +66,6 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
except (TypeError, ValueError):
continue
reason_codes: list[str] = []
if len(tables) < len(profile.table_regions):
reason_codes.append('table_region_count_insufficient')
required = profile.document_match.required_anchors
required_hits = [_anchor_present(
anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
@@ -114,6 +113,8 @@ def _anchor_present(
if not expected or not all(candidates):
return False
page_numbers = sorted({str(item.get('page_no') or '') for item in tables if item.get('page_no')})
if not page_numbers:
page_numbers = sorted(str(page_no) for page_no in pages)
for page_no in page_numbers:
glyphs = page_glyphs.get(page_no)
# v1 frozen snapshots do not have page glyphs. Preserve historical matching
@@ -8,6 +8,7 @@ services/shipping_notice/document_profile_quality_service.py
from __future__ import annotations
import re
from datetime import datetime
from decimal import Decimal
from typing import Any
@@ -21,6 +22,7 @@ from app.models import (
ShippingDocumentProfileAutoFreezeQualification,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingCustomer,
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileSample,
)
@@ -46,6 +48,7 @@ from app.services.shipping_notice.order_schema.field_rules import normalize_orde
# 多明细和声明的跨页覆盖等质量门禁仍然生效。
MINIMUM_BLIND_SAMPLES = 1
HEADERLESS_MINIMUM_BLIND_SAMPLES = 1
_BUSINESS_SCENARIO_PATTERN = re.compile(r'^[a-z0-9_:-]{1,64}$')
def _quality_checksum(profile: ShippingOrderDocumentProfile) -> str:
@@ -557,7 +560,11 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
def approve_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
"""批准最近一次合格盲测,形成绑定 Profile checksum 的不可变自动建单凭证。"""
"""批准合格盲测并升级当前模板版本的自动建单资格。
保留已有的客户、业务场景和人工确认范围配置;盲测批准只证明
模板解析质量合格,范围门禁仍由管理员单独配置。
"""
suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id))
if suite is None:
raise NotFoundError('Order document profile test suite not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_FOUND')
@@ -571,8 +578,14 @@ def approve_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
suite.status = 'approved'
suite.approved_by_id = actor_id
suite.approved_at = datetime.utcnow()
qualification = ensure_manual_confirmation_qualification(profile)
qualification.status = 'auto_freeze_approved'
qualification.quality_suite_id = suite.id
qualification.approved_by_id = actor_id
qualification.approved_at = suite.approved_at
_audit(profile_id=profile.id, event_type='blind_test_approved', actor_id=actor_id, detail={
'suite_id': suite.id, 'profile_checksum': _quality_checksum(profile),
'qualification_id': qualification.id,
})
db.session.commit()
return serialize_suite(suite)
@@ -610,6 +623,45 @@ def ensure_manual_confirmation_qualification(profile: ShippingOrderDocumentProfi
return qualification
def _normalize_customer_scope(customer_ids: list[int] | None) -> list[int] | None:
"""标准化授权客户列表;只接受存在的客户主键,空列表视为未配置。"""
raw_ids = [int(item) for item in (customer_ids or [])]
normalized = sorted(set(raw_ids))
if not normalized:
return None
existing_ids = {
int(row.id)
for row in ShippingCustomer.query.filter(ShippingCustomer.id.in_(normalized)).all()
}
missing = [customer_id for customer_id in normalized if customer_id not in existing_ids]
if missing:
raise ValidationError(
'Customer scope contains unknown customer ids',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_QUALIFICATION_INVALID',
details={'customer_ids': missing},
)
return normalized
def _normalize_business_scenarios(business_scenarios: list[str] | None) -> list[str] | None:
"""标准化授权业务场景列表;仅接受稳定代码,不接受自由文本说明。"""
normalized = sorted({
str(item or '').strip().lower()
for item in (business_scenarios or [])
if str(item or '').strip()
})
if not normalized:
return None
invalid = [item for item in normalized if _BUSINESS_SCENARIO_PATTERN.match(item) is None]
if invalid:
raise ValidationError(
'Business scenarios contain invalid values',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_QUALIFICATION_INVALID',
details={'business_scenarios': invalid},
)
return normalized
def qualification_summary(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
"""返回模板版本资格摘要;旧发布版本没有记录时安全降级为人工确认。"""
qualification = ShippingDocumentProfileAutoFreezeQualification.query.filter_by(
@@ -623,6 +675,11 @@ def qualification_summary(profile: ShippingOrderDocumentProfile) -> dict[str, An
'qualification_id': qualification.id,
'parser_version': qualification.parser_version,
'quality_suite_id': qualification.quality_suite_id,
'customer_ids': list(qualification.customer_ids_json or []),
'business_scenarios': list(qualification.business_scenarios_json or []),
'customer_scope_configured': bool(qualification.customer_ids_json),
'business_scenario_scope_configured': bool(qualification.business_scenarios_json),
'requires_customer_confirmation': bool(qualification.requires_customer_confirmation),
}
@@ -634,9 +691,47 @@ def serialize_qualification(qualification: ShippingDocumentProfileAutoFreezeQual
'qualification_id': qualification.id,
'parser_version': qualification.parser_version,
'quality_suite_id': qualification.quality_suite_id,
'customer_ids': list(qualification.customer_ids_json or []),
'business_scenarios': list(qualification.business_scenarios_json or []),
'customer_scope_configured': bool(qualification.customer_ids_json),
'business_scenario_scope_configured': bool(qualification.business_scenarios_json),
'requires_customer_confirmation': bool(qualification.requires_customer_confirmation),
'scope_updated_at': qualification.scope_updated_at.isoformat() if qualification.scope_updated_at else None,
}
def configure_auto_freeze_qualification_scope(
*,
profile_id: int,
actor_id: int,
customer_ids: list[int] | None,
business_scenarios: list[str] | None,
requires_customer_confirmation: bool = True,
) -> ShippingDocumentProfileAutoFreezeQualification:
"""配置模板版本的客户/业务场景授权范围;为空时表示清空并回到未配置状态。"""
profile = _profile(profile_id)
qualification = ShippingDocumentProfileAutoFreezeQualification.query.filter_by(
profile_id=profile.id, profile_version=profile.version, profile_checksum=str(profile.checksum or ''),
).one_or_none()
if qualification is None:
raise ConflictError('Profile qualification is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_QUALIFICATION_NOT_FOUND')
normalized_customer_ids = _normalize_customer_scope(customer_ids)
normalized_business_scenarios = _normalize_business_scenarios(business_scenarios)
qualification.customer_ids_json = normalized_customer_ids
qualification.business_scenarios_json = normalized_business_scenarios
qualification.requires_customer_confirmation = bool(requires_customer_confirmation)
qualification.scope_updated_by_id = actor_id
qualification.scope_updated_at = datetime.utcnow()
_audit(profile_id=profile.id, event_type='auto_freeze_scope_configured', actor_id=actor_id, detail={
'qualification_id': qualification.id,
'customer_scope_count': len(normalized_customer_ids or []),
'business_scenario_count': len(normalized_business_scenarios or []),
'requires_customer_confirmation': qualification.requires_customer_confirmation,
})
db.session.commit()
return qualification
def suspend_auto_freeze_qualification(*, profile_id: int, actor_id: int, reason: str) -> ShippingDocumentProfileAutoFreezeQualification:
"""单独暂停一个模板版本资格;即使未来已批准也立即阻断新的自动冻结。"""
profile = _profile(profile_id)
@@ -99,3 +99,66 @@ def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str)
})
result.update({'rows': rows, 'issues': sorted(set(issues))})
return result
def parse_email_allocation_text(*, body_text: str, content_hash: str) -> dict[str, Any]:
"""解析无 HTML 的纵向表头正文,只有完整唯一表头序列才会产出补充行。
这类邮件客户端会把一行表头和数据单元格都展平成换行文本。按固定表头序列
还原时保留文本索引证据;找不到完整序列则安全返回空结果,绝不猜测正文段落。
"""
result = empty_email_supplement_result()
tokens = [line.strip() for line in str(body_text or '').splitlines() if line.strip()]
expected = [
'allocation_id', 'reservation_id', 'source_from_party', 'source_type',
'allocated_entity', 'mpn', 'allocated_qty', 'po_number',
]
normalized = [normalize_table_header(token) for token in tokens]
aliases = {
field: {normalize_table_header(alias) for alias in values}
for field, values in _HEADERS.items()
}
start = next((
index for index in range(0, len(tokens) - len(expected) + 1)
if all(normalized[index + offset] in aliases[field] for offset, field in enumerate(expected))
), None)
if start is None:
return result
column_count = len(expected)
rows: list[dict[str, Any]] = []
seen_rows: set[tuple[str, ...]] = set()
for offset in range(start + column_count, len(tokens), column_count):
values = tokens[offset:offset + column_count]
if len(values) != column_count:
break
po_number = normalize_po_number(values[-1])
if not po_number:
# 正文表结束后的普通段落不得作为一条不完整记录继续吞入。
break
identity = tuple(values)
# 转发邮件常同时含原始正文与引用正文;同一整行仅保留一次,不能制造假冲突。
if identity in seen_rows:
continue
seen_rows.add(identity)
row = {field: value for field, value in zip(expected, values)}
row['po_number'] = po_number
reservation_id = validated_reservation_id(row.get('reservation_id'))
if not reservation_id:
result['issues'].append('email_supplement_reservation_invalid')
continue
row['reservation_id'] = reservation_id
row['evidence'] = {
field: {
'table_index': None, 'row_index': len(rows) + 1, 'column_index': column,
'cell_id': f'email-supplement-text:{content_hash}:r{len(rows) + 1}:c{column}',
'raw_value': value,
}
for column, (field, value) in enumerate(zip(expected, values))
}
row['table_index'] = None
row['row_index'] = len(rows) + 1
rows.append(row)
result['rows'] = rows
result['issues'] = sorted(set(result['issues']))
return result
+314 -12
View File
@@ -1,7 +1,7 @@
"""
services/shipping_notice/eml_parse.py
用途:将 .eml 解析为结构化结果(邮件元数据、清洗正文、真实附件及各自文本)。
用途:将 .eml 解析为结构化结果(邮件元数据、清洗正文、附件目录,按模式可选附件全文)。
依赖:标准库 email/html、BeautifulSoup;Flask current_app(可选);notice_upload.extract_notice_text(叶附件抽取)。
逻辑:由 notice_upload.extract_notice_text 在 file_type=eml 时调用;忽略内嵌图片/签名图;
嵌套 message/rfc822 与附件型 multipart(disposition/filename)登记为独立附件;
@@ -22,7 +22,7 @@ from email.message import Message
from email.parser import BytesParser
from email.utils import parsedate_to_datetime
from pathlib import Path
from typing import Any, Callable
from typing import Any, Callable, Literal
from bs4 import BeautifulSoup, Comment
@@ -545,8 +545,8 @@ def _register_and_expand_attached_multipart(
"parse_status": "skipped",
"extracted_text": "",
"warnings": [],
"_payload_bytes": raw or b"",
}
_remember_payload(item, raw or b"", retain_payloads=state.retain_payloads)
if size > state.limits.max_attachment_bytes:
item["parse_status"] = "skipped"
@@ -656,12 +656,15 @@ def _guess_suffix(filename: str, mime_type: str) -> str:
ExtractTextFn = Callable[[Path], tuple[str, dict[str, Any]]]
AttachmentExtractMode = Literal["deep", "preview"]
@dataclass
class _ParseState:
limits: EmlLimits
extract_text: ExtractTextFn
retain_payloads: bool = False
attachment_mode: AttachmentExtractMode = "deep"
warnings: list[str] = field(default_factory=list)
attachments: list[dict[str, Any]] = field(default_factory=list)
nested_bodies: list[str] = field(default_factory=list) # 兼容保留;v3 起 rfc822 改走 attachments,不再写入
@@ -678,6 +681,23 @@ def _next_attachment_key(state: _ParseState) -> str:
return f"att-{state.attachment_seq:03d}"
def _skip_inline_resource(state: _ParseState) -> None:
"""跳过内嵌资源但保留 MIME 遍历序号,保证快览与深度解析附件键一致。"""
state.skipped_inline += 1
_next_attachment_key(state)
def _remember_payload(
item: dict[str, Any],
payload: bytes,
*,
retain_payloads: bool,
) -> None:
"""仅在调用方显式要求时保留附件原始字节,避免预览链路持有大对象。"""
if retain_payloads and payload:
item["_payload_bytes"] = payload
def _is_eml_payload(*, filename: str, mime_type: str) -> bool:
"""判定附件是否为可递归的 .eml / rfc822 载荷。"""
suffix = Path(filename or "").suffix.lower()
@@ -685,6 +705,101 @@ def _is_eml_payload(*, filename: str, mime_type: str) -> bool:
return suffix == ".eml" or mime in {"message/rfc822", "application/eml"}
_PREVIEW_READY_SUFFIXES = frozenset(
{
".pdf",
".doc",
".docx",
".xls",
".xlsx",
".csv",
".txt",
".html",
".htm",
".xml",
".json",
".eml",
".msg",
".png",
".jpg",
".jpeg",
".webp",
".bmp",
".tif",
".tiff",
}
)
_PREVIEW_ARCHIVE_SUFFIXES = frozenset(
{".zip", ".rar", ".7z", ".tar", ".gz", ".tgz", ".bz2", ".xz"}
)
_PREVIEW_EXECUTABLE_SUFFIXES = frozenset(
{".exe", ".dll", ".bat", ".cmd", ".com", ".msi", ".vbs", ".js", ".jar", ".ps1", ".scr"}
)
_PREVIEW_MACRO_SUFFIXES = frozenset({".docm", ".xlsm", ".pptm", ".xlam", ".xltm"})
_PREVIEW_READY_MIME_PREFIXES = ("text/", "image/")
_PREVIEW_READY_MIMES = frozenset(
{
"application/pdf",
"message/rfc822",
"application/eml",
"application/msword",
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
}
)
_PREVIEW_ARCHIVE_MIMES = frozenset(
{
"application/zip",
"application/x-zip-compressed",
"application/x-7z-compressed",
"application/x-rar-compressed",
"application/gzip",
"application/x-tar",
}
)
_PREVIEW_EXECUTABLE_MIMES = frozenset(
{
"application/x-msdownload",
"application/x-msdos-program",
"application/x-sh",
"application/x-powershell",
"application/java-archive",
}
)
def _preview_catalog_reason(
*,
filename: str,
mime_type: str,
is_inline_resource: bool,
) -> tuple[bool, str]:
"""
根据目录阶段可见事实判断附件是否可进入后续深度解析。
Returns:
tuple[bool, str]: (是否可进入深度解析, 原因码)。
"""
suffix = Path(str(filename or "")).suffix.lower()
mime = str(mime_type or "").lower()
if is_inline_resource:
if _looks_like_signature_or_logo(filename):
return False, "signature_or_logo"
return False, "inline_resource"
if suffix in _PREVIEW_ARCHIVE_SUFFIXES or mime in _PREVIEW_ARCHIVE_MIMES:
return False, "archive"
if suffix in _PREVIEW_MACRO_SUFFIXES or "macroenabled" in mime:
return False, "macro_enabled"
if suffix in _PREVIEW_EXECUTABLE_SUFFIXES or mime in _PREVIEW_EXECUTABLE_MIMES:
return False, "executable"
if suffix in _PREVIEW_READY_SUFFIXES:
return True, "ready_for_extraction"
if mime in _PREVIEW_READY_MIMES or any(mime.startswith(prefix) for prefix in _PREVIEW_READY_MIME_PREFIXES):
return True, "ready_for_extraction"
return False, "unknown_binary"
def _expand_eml_file_attachment(
*,
state: _ParseState,
@@ -812,9 +927,9 @@ def _append_attachment(
"parse_status": "skipped",
"extracted_text": "",
"warnings": [],
# 仅内存保留供阶段二派生资产;写 structured_result / 对外 API 前必须剥离
"_payload_bytes": payload or b"",
}
# 仅在显式深度链路保留原始字节;预览模式不再为后续派生资产持有 payload。
_remember_payload(item, payload or b"", retain_payloads=state.retain_payloads)
# [STEP 2] 单附件 / 总大小上限
# 计费规则:顶层真实附件(含 .eml 容器)计入总量;从已计费 .eml 展开的子内容不计。
@@ -900,8 +1015,8 @@ def _register_and_expand_rfc822(
"parse_status": "empty",
"extracted_text": "",
"warnings": [],
"_payload_bytes": raw or b"",
}
_remember_payload(item, raw or b"", retain_payloads=state.retain_payloads)
if content_hash and content_hash in state.seen_hashes:
item["parse_status"] = "duplicate"
@@ -1000,6 +1115,182 @@ def _maybe_charge_rfc822_container(
return True
def _append_preview_attachment(
state: _ParseState,
*,
filename: str,
mime_type: str,
payload: bytes,
count_toward_total: bool = True,
is_inline_resource: bool = False,
forced_status: str | None = None,
forced_warning: str | None = None,
) -> None:
"""
仅登记附件目录,不做正文抽取或递归展开。
核心逻辑:目录阶段只保留文件名、MIME、大小、哈希、内嵌标记和后续是否允许深度解析。
forced_status/forced_warning 用于记录超深、不可读嵌套等目录不完整事实。
"""
state.discovered_attachment_count += 1
if len(state.attachments) >= state.limits.max_attachments:
_note_attachment_limit_exceeded(state)
return
raw = payload or b""
size = len(raw)
content_hash = hashlib.sha256(raw).hexdigest().lower() if raw else ""
ready_for_extraction, catalog_reason = _preview_catalog_reason(
filename=filename,
mime_type=mime_type,
is_inline_resource=is_inline_resource,
)
key = _next_attachment_key(state)
item: dict[str, Any] = {
"attachment_key": key,
"filename": filename,
"mime_type": mime_type or "application/octet-stream",
"size": size,
"content_hash": content_hash,
"parse_status": "ready_for_extraction" if ready_for_extraction else "directory_only",
"extracted_text": "",
"warnings": [],
"ready_for_extraction": ready_for_extraction,
"is_inline_resource": is_inline_resource,
"catalog_reason": catalog_reason,
}
_remember_payload(item, raw, retain_payloads=state.retain_payloads)
if forced_warning:
item["parse_status"] = forced_status or "skipped"
item["ready_for_extraction"] = False
item["warnings"].append(forced_warning)
if forced_warning.startswith("eml_total_attachment_size_exceeded"):
if not any(str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings):
state.warnings.append(forced_warning)
elif forced_warning not in state.warnings:
state.warnings.append(forced_warning)
state.attachments.append(item)
return
if size > state.limits.max_attachment_bytes:
item["parse_status"] = "skipped"
item["ready_for_extraction"] = False
item["warnings"].append(f"eml_attachment_too_large:{size}")
state.warnings.append(f"eml_attachment_too_large:{filename}:{size}")
state.attachments.append(item)
return
if count_toward_total:
if state.total_attachment_bytes + size > state.limits.max_total_attachment_bytes:
item["parse_status"] = "skipped"
item["ready_for_extraction"] = False
item["warnings"].append("eml_total_attachment_size_exceeded")
if not any(str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings):
state.warnings.append(
f"eml_total_attachment_size_exceeded:{state.limits.max_total_attachment_bytes}"
)
state.attachments.append(item)
return
state.total_attachment_bytes += size
if content_hash and content_hash in state.seen_hashes:
item["parse_status"] = "duplicate"
item["ready_for_extraction"] = False
item["catalog_reason"] = "duplicate"
item["warnings"].append(f"eml_attachment_duplicate:{state.seen_hashes[content_hash]}")
state.warnings.append(f"eml_attachment_duplicate:{filename}")
state.attachments.append(item)
return
if content_hash:
state.seen_hashes[content_hash] = key
state.attachments.append(item)
def _walk_message_preview(
msg: Message,
state: _ParseState,
*,
depth: int,
count_toward_total: bool = True,
) -> None:
"""
遍历 MIME 树并仅登记附件目录。
核心逻辑:正文提取仍由根消息自身负责;目录阶段对 message/rfc822 和附件型 multipart
只登记容器,不递归进入其内部附件,确保上传时延与附件正文/OCR/表格无关。
"""
if depth > state.limits.max_nesting_depth:
state.warnings.append(f"eml_nesting_depth_exceeded:{state.limits.max_nesting_depth}")
return
if not msg.is_multipart():
is_inline = _is_inline_or_embedded_resource(msg)
if is_inline:
_skip_inline_resource(state)
elif _is_real_attachment(msg):
_append_preview_attachment(
state,
filename=_part_filename(msg),
mime_type=str(msg.get_content_type() or "application/octet-stream"),
payload=_read_part_payload(msg),
count_toward_total=count_toward_total,
)
return
parts = list(msg.iter_parts()) if hasattr(msg, "iter_parts") else list(msg.get_payload() or [])
for part in parts:
if not isinstance(part, Message):
continue
ctype = str(part.get_content_type() or "").lower()
if ctype == "message/rfc822":
_append_preview_attachment(
state,
filename=str(part.get_filename() or "").strip() or "forwarded-message.eml",
mime_type="message/rfc822",
payload=_rfc822_container_bytes(part),
count_toward_total=count_toward_total,
forced_status="skipped" if _unwrap_rfc822(part) is None else None,
forced_warning="eml_nested_message_unreadable" if _unwrap_rfc822(part) is None else None,
)
continue
if part.is_multipart():
if _is_attached_multipart(part):
try:
raw = part.as_bytes()
except Exception:
raw = b""
_append_preview_attachment(
state,
filename=_part_filename(part, fallback="bundle"),
mime_type=str(part.get_content_type() or "multipart/mixed"),
payload=raw,
count_toward_total=count_toward_total,
)
continue
_walk_message_preview(
part,
state,
depth=depth,
count_toward_total=count_toward_total,
)
continue
is_inline = _is_inline_or_embedded_resource(part)
if is_inline:
# 内嵌签名图不是用户可识别的业务附件,不能占用附件数量或预算。
_skip_inline_resource(state)
continue
if _is_body_text_part(part):
continue
if _is_real_attachment(part):
_append_preview_attachment(
state,
filename=_part_filename(part),
mime_type=str(part.get_content_type() or "application/octet-stream"),
payload=_read_part_payload(part),
count_toward_total=count_toward_total,
)
def _walk_message(
msg: Message,
state: _ParseState,
@@ -1093,7 +1384,7 @@ def _walk_message(
continue
if _is_inline_or_embedded_resource(part):
state.skipped_inline += 1
_skip_inline_resource(state)
continue
if _is_body_text_part(part):
@@ -1140,12 +1431,13 @@ def parse_eml_bytes(
limits: EmlLimits | None = None,
depth: int = 0,
retain_payloads: bool = False,
attachment_mode: AttachmentExtractMode = "deep",
) -> tuple[str, dict[str, Any]]:
"""
结构化解析 EML 字节流。
核心逻辑:提取邮件头与清洗正文 → 区分真实附件与内嵌图片 → 对附件调用 extract_text;
嵌套 rfc822 登记为独立附件并展开内层;不执行宏、脚本或嵌入对象。
核心逻辑:提取邮件头与清洗正文;`deep` 模式递归抽取附件全文,
`preview` 模式仅登记附件目录(名称、MIME、大小、哈希、是否内嵌、是否允许后续深度解析)。
Args:
data: .eml 原始字节。
@@ -1154,6 +1446,7 @@ def parse_eml_bytes(
depth: 当前嵌套深度(供嵌套 .eml 附件复用)。
retain_payloads: True 时在 attachments[*]._payload_bytes 保留二进制供派生资产;
默认 False,返回前剥离,避免测试/JSON 路径泄漏。
attachment_mode: `deep` 递归抽附件文本;`preview` 只生成附件目录。
Returns:
tuple[str, dict]: (扁平拼接文本, meta含 email/attachments/attachment_count/warnings)。
@@ -1178,8 +1471,16 @@ def parse_eml_bytes(
body_text = _extract_body_text(msg)
body_html_tables = _extract_body_html_tables(msg)
state = _ParseState(limits=limits, extract_text=extract_text)
_walk_message(msg, state, depth=depth)
state = _ParseState(
limits=limits,
extract_text=extract_text,
retain_payloads=retain_payloads,
attachment_mode=attachment_mode,
)
if attachment_mode == "preview":
_walk_message_preview(msg, state, depth=depth)
else:
_walk_message(msg, state, depth=depth)
if state.skipped_inline:
state.warnings.append(f"eml_inline_resources_skipped:{state.skipped_inline}")
@@ -1199,10 +1500,11 @@ def parse_eml_bytes(
flat = _compose_flat_text(
subject=subject,
body_text=combined_body,
attachments=state.attachments,
attachments=state.attachments if attachment_mode == "deep" else [],
)
meta: dict[str, Any] = {
"file_type": "eml",
"eml_attachment_mode": attachment_mode,
"warnings": list(state.warnings),
"email": email_meta,
"attachments": list(state.attachments),
@@ -4,6 +4,7 @@
用途:集中检查订单解析、字段裁决、客户、冲突与库存源状态,阻止不完整订单进入不可编辑快照。
依赖:订单 Extraction、字段裁决、冲突门禁、库存源门禁及已发布履约策略。
逻辑:order_freeze_service 在创建 Snapshot 前调用;失败统一返回结构化 blocking issues。
阶段 5 自动冻结入口接入后,同一服务继续负责把 Run 级自动冻结门禁摘要折叠为冻结阻断原因。
"""
from __future__ import annotations
@@ -17,12 +18,21 @@ from app.services.shipping_notice.fulfillment_policy_registry import required_fi
from app.services.shipping_notice.task_field_gate import open_field_conflict_issues
def assert_freeze_readiness(*, task: ShippingTask, extraction: ShippingOrderExtraction, policy: Any, configs: dict[str, dict[str, Any]]) -> None:
"""校验当前任务是否可冻结;任何问题均 fail closed,附带可展示的 issues。"""
def assert_freeze_readiness(
*,
task: ShippingTask,
extraction: ShippingOrderExtraction,
policy: Any,
configs: dict[str, dict[str, Any]],
freeze_mode: str = 'manual',
auto_freeze_policy: dict[str, Any] | None = None,
) -> None:
"""校验当前任务是否可冻结;自动冻结额外消费 Run 级门禁摘要并折叠为统一 issues。"""
issues: list[dict[str, Any]] = []
if extraction.status != 'accepted':
issues.append({'reason': 'extraction_not_accepted'})
issues.extend(open_field_conflict_issues(task))
issues.extend(_auto_freeze_blocking_issues(freeze_mode=freeze_mode, auto_freeze_policy=auto_freeze_policy))
required = required_field_configs(extraction.schema_version.definition_json or {}, policy)
required_codes = {'reservation_id', 'part_number', 'qty'}
@@ -55,3 +65,28 @@ def assert_freeze_readiness(*, task: ShippingTask, extraction: ShippingOrderExtr
issues.append({'reason': 'customer_po_missing_or_unreviewed', 'field': 'customer_po_number'})
if issues:
raise ValidationError('Order is not ready to freeze', code='SHIPPING.ORDER_FREEZE_BLOCKED', details={'issues': issues})
def _auto_freeze_blocking_issues(
*,
freeze_mode: str,
auto_freeze_policy: dict[str, Any] | None,
) -> list[dict[str, Any]]:
"""把 Run 级自动冻结门禁摘要转换为冻结阻断 issues;人工冻结路径不消费这层策略。"""
if str(freeze_mode or 'manual') != 'auto':
return []
policy = auto_freeze_policy if isinstance(auto_freeze_policy, dict) else {}
issues: list[dict[str, Any]] = []
if not policy:
return [{'reason': 'auto_freeze_policy_missing'}]
if not bool(policy.get('enabled')):
issues.append({
'reason': 'auto_freeze_not_enabled',
'mode': str(policy.get('mode') or '') or None,
'qualification_status': str(policy.get('qualification_status') or '') or None,
'customer_scope_status': str(policy.get('customer_scope_status') or '') or None,
})
for code in policy.get('blocking_reason_codes') or []:
if str(code).strip():
issues.append({'reason': 'auto_freeze_blocked', 'blocking_reason_code': str(code)})
return issues
@@ -15,7 +15,7 @@ from __future__ import annotations
import tempfile
from datetime import datetime
from pathlib import Path
from typing import Any
from typing import Any, Literal
from flask import current_app
@@ -78,8 +78,7 @@ def _attachment_summaries_for_structured(meta: dict[str, Any]) -> tuple[list[dic
"""
从 EML 抽取 meta 生成可写入 structured_result_json 的附件摘要。
核心逻辑:单附件按 NOTICE_TEXT_MAX_CHARS 截断;全部附件再共享
SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS 总预算。
核心逻辑:`preview` 模式只保留附件目录字段;`deep` 模式才会写入附件全文与截断预算。
Returns:
(附件摘要列表, 汇总级 warnings)
@@ -92,24 +91,11 @@ def _attachment_summaries_for_structured(meta: dict[str, Any]) -> tuple[list[dic
per_limit = 200000
budget = _eml_stored_attachment_chars_budget()
remaining = budget
preview_mode = str(meta.get('eml_attachment_mode') or '').strip().lower() == 'preview'
for item in meta.get('attachments') or []:
if not isinstance(item, dict):
continue
original = str(item.get('extracted_text') or '')
text, truncated = _truncate_meta_text(original, limit=per_limit)
warn = list(item.get('warnings') or [])
if truncated:
warn = [*warn, f'eml_attachment_text_truncated:{per_limit}']
if remaining <= 0:
if text:
text = ''
warn = [*warn, f'eml_attachment_text_budget_exhausted:{budget}']
elif len(text) > remaining:
text = text[:remaining]
warn = [*warn, f'eml_attachment_text_budget_exhausted:{budget}']
remaining = 0
else:
remaining -= len(text)
row: dict[str, Any] = {
'attachment_key': item.get('attachment_key'),
'filename': item.get('filename'),
@@ -117,11 +103,30 @@ def _attachment_summaries_for_structured(meta: dict[str, Any]) -> tuple[list[dic
'size': item.get('size'),
'content_hash': item.get('content_hash'),
'parse_status': item.get('parse_status'),
'extracted_text': text,
'text_length': len(original),
'stored_text_length': len(text),
'warnings': warn,
'ready_for_extraction': bool(item.get('ready_for_extraction')),
'is_inline_resource': bool(item.get('is_inline_resource')),
'catalog_reason': item.get('catalog_reason'),
}
if not preview_mode:
original = str(item.get('extracted_text') or '')
text, truncated = _truncate_meta_text(original, limit=per_limit)
if truncated:
warn = [*warn, f'eml_attachment_text_truncated:{per_limit}']
if remaining <= 0:
if text:
text = ''
warn = [*warn, f'eml_attachment_text_budget_exhausted:{budget}']
elif len(text) > remaining:
text = text[:remaining]
warn = [*warn, f'eml_attachment_text_budget_exhausted:{budget}']
remaining = 0
else:
remaining -= len(text)
row['warnings'] = warn
row['extracted_text'] = text
row['text_length'] = len(original)
row['stored_text_length'] = len(text)
if item.get('asset_no'):
row['asset_no'] = item.get('asset_no')
if item.get('asset_id') is not None:
@@ -129,7 +134,7 @@ def _attachment_summaries_for_structured(meta: dict[str, Any]) -> tuple[list[dic
if item.get('document_id') is not None:
row['document_id'] = item.get('document_id')
rows.append(row)
if any(
if (not preview_mode) and any(
any(str(w).startswith('eml_attachment_text_budget_exhausted:') for w in (row.get('warnings') or []))
for row in rows
):
@@ -137,16 +142,46 @@ def _attachment_summaries_for_structured(meta: dict[str, Any]) -> tuple[list[dic
return rows, extra_warnings
def _attachment_directory_complete(payload: dict[str, Any]) -> bool:
"""
判定上传快览拿到的附件目录是否完整。
核心逻辑:重复、内嵌资源和目录保留项不阻断;只有目录发现缺口才标记 incomplete。
"""
warnings = payload.get('warnings') or []
if any(
str(item).startswith(prefix)
for item in warnings
for prefix in (
'eml_nesting_depth_exceeded:',
'eml_attachment_limit_exceeded:',
'eml_total_attachment_size_exceeded:',
'eml_nested_message_unreadable',
)
):
return False
rows = payload.get('attachments') or []
if int(payload.get('attachment_count') or 0) > len(rows):
return False
for row in rows:
if not isinstance(row, dict):
continue
if str(row.get('parse_status') or '').strip().lower() == 'skipped':
return False
return True
def intake_result_to_structured_summary(
result: NoticeIntakeResult,
*,
business_summary: dict[str, Any] | None = None,
technical_failure: bool = False,
) -> dict[str, Any]:
"""
生成前端可展示的预解析摘要(技术摘要 + 可选业务摘要)。
核心逻辑:普通文件仅写文件级统计;EML 额外写入 email 元数据、attachment_count 与附件摘要
(含各附件独立 extracted_text);email.body_text 按 notice 文本上限截断;
核心逻辑:普通文件仅写文件级统计;EML 额外写入 email 元数据、attachment_count 与附件摘要。
`preview` 模式只落附件目录和白名单 HTML 表格快照,不写附件全文;email.body_text 按 notice 文本上限截断;
截断警告统一为 `eml_*_truncated:{limit}`(N=上限字符数)。
"""
line_count = 0
@@ -160,8 +195,12 @@ def intake_result_to_structured_summary(
'line_count': line_count,
'warnings': list(result.warnings),
'parser_version': _parser_version(),
'technical_failure': bool(technical_failure),
}
meta = result.meta if isinstance(result.meta, dict) else {}
attachment_mode = str(meta.get('eml_attachment_mode') or '').strip().lower()
if attachment_mode:
payload['eml_attachment_mode'] = attachment_mode
email_meta = meta.get('email')
if isinstance(email_meta, dict) and email_meta:
original_body = str(email_meta.get('body_text') or '')
@@ -179,6 +218,7 @@ def intake_result_to_structured_summary(
'body_text': body_text,
'body_text_length': len(original_body),
'stored_body_text_length': len(body_text),
'body_html_tables': [str(item) for item in (email_meta.get('body_html_tables') or []) if str(item).strip()],
}
if body_truncated:
payload['warnings'] = [
@@ -194,6 +234,36 @@ def intake_result_to_structured_summary(
payload['warnings'] = [*payload['warnings'], *attach_extra_warnings]
if attachments:
payload['attachments'] = attachments
if attachment_mode == 'preview':
attachment_directory_complete = _attachment_directory_complete(payload)
payload['ready_attachment_count'] = sum(
1 for row in attachments if bool(row.get('ready_for_extraction'))
)
payload['directory_only_attachment_count'] = sum(
1
for row in attachments
if str(row.get('parse_status') or '').strip().lower() == 'directory_only'
)
payload['duplicate_attachment_count'] = sum(
1
for row in attachments
if str(row.get('parse_status') or '').strip().lower() == 'duplicate'
)
payload['attachment_directory_complete'] = attachment_directory_complete
payload['ready_for_extraction'] = (not technical_failure) and attachment_directory_complete
payload['preview_status'] = (
'technical_failed'
if technical_failure
else 'ready_for_extraction'
if attachment_directory_complete
else 'directory_incomplete'
)
elif technical_failure:
payload['ready_for_extraction'] = False
payload['preview_status'] = 'technical_failed'
else:
payload['ready_for_extraction'] = True
payload['preview_status'] = 'ready_for_extraction'
if isinstance(business_summary, dict):
payload['business_summary'] = business_summary
payload['confidence'] = business_summary.get('confidence')
@@ -201,7 +271,13 @@ def intake_result_to_structured_summary(
return payload
def extract_notice_from_asset(asset: FileAsset) -> NoticeIntakeResult:
def extract_notice_from_asset(
asset: FileAsset,
*,
eml_attachment_mode: Literal['deep', 'preview'] = 'deep',
retain_payloads: bool = True,
preview_only: bool = False,
) -> NoticeIntakeResult:
"""
从 FileAsset 下载并抽取发货通知文本。
核心逻辑:写入临时文件后复用 extract_notice_text,避免长期落盘到 notice_uploads。
@@ -214,8 +290,12 @@ def extract_notice_from_asset(asset: FileAsset) -> NoticeIntakeResult:
tmp.write(raw)
tmp_path = Path(tmp.name)
try:
# EML 须保留附件二进制,供阶段二幂等创建派生 FileAsset
text, meta = extract_notice_text(tmp_path, retain_payloads=True)
text, meta = extract_notice_text(
tmp_path,
retain_payloads=retain_payloads,
eml_attachment_mode=eml_attachment_mode,
preview_only=preview_only,
)
warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else []
except Exception as exc:
return NoticeIntakeResult(
@@ -236,7 +316,17 @@ def extract_notice_from_asset(asset: FileAsset) -> NoticeIntakeResult:
except OSError:
pass
if not str(text or '').strip():
preview_accept_without_text = bool(preview_only) or (
isinstance(meta, dict)
and str(meta.get('file_type') or '').lower() == 'eml'
and str(meta.get('eml_attachment_mode') or '').lower() == 'preview'
and (
bool(meta.get('attachment_count'))
or bool(meta.get('attachments'))
or bool(meta.get('email'))
)
)
if not str(text or '').strip() and not preview_accept_without_text:
return NoticeIntakeResult(
filename=filename,
source_type=source_type,
@@ -615,7 +705,13 @@ def run_intake_parse(
)
from app.services.shipping_notice.eml_parse import strip_attachment_payloads
result = extract_notice_from_asset(asset)
preview_only = str(intake.purpose or '') != 'order_document_profile_sample'
result = extract_notice_from_asset(
asset,
eml_attachment_mode='preview' if preview_only else 'deep',
retain_payloads=not preview_only,
preview_only=preview_only,
)
intake_id = int(intake.id)
intake_no = intake.intake_no
parser_version = _parser_version()
@@ -625,7 +721,10 @@ def run_intake_parse(
if result.status in {'extract_failed', 'empty_text'}:
strip_attachment_payloads(result.meta if isinstance(result.meta, dict) else {})
summary = intake_result_to_structured_summary(result)
summary = intake_result_to_structured_summary(
result,
technical_failure=(result.status == 'extract_failed'),
)
error_message = (
'; '.join(warnings)[:1000] or '文本抽取失败'
if result.status == 'extract_failed'
@@ -667,7 +766,7 @@ def run_intake_parse(
'reason': 'stale_parse_lease',
}
persist_info: dict[str, Any] = {}
persist_info: dict[str, Any] = {'document_count': 0, 'candidate_count': 0}
uploaded_storage_keys: list[str] = []
try:
is_profile_sample = str(locked.purpose or '') == 'order_document_profile_sample'
@@ -677,14 +776,15 @@ def run_intake_parse(
schema_version = ShippingOrderSchemaVersion.query.filter_by(status='published').first()
schema_definition = dict(schema_version.definition_json or {}) if schema_version is not None else {'fields': []}
# [STEP 2] 上传阶段只完成文件预处理;禁止提前生成 Candidate 或业务判重。
persist_info = persist_intake_documents(
intake=locked,
parent_asset=asset,
result=result,
uploaded_storage_keys=uploaded_storage_keys,
schema_definition=schema_definition,
)
# [STEP 2] shipping_notice 上传阶段只落快览摘要;模板样本用途保留文档/布局持久化。
if is_profile_sample:
persist_info = persist_intake_documents(
intake=locked,
parent_asset=asset,
result=result,
uploaded_storage_keys=uploaded_storage_keys,
schema_definition=schema_definition,
)
tech_summary = intake_result_to_structured_summary(result)
tech_summary['document_count'] = persist_info.get('document_count')
@@ -767,7 +867,10 @@ def run_intake_parse(
storage_bucket=storage_bucket,
)
strip_attachment_payloads(result.meta if isinstance(result.meta, dict) else {})
fail_summary = intake_result_to_structured_summary(result)
fail_summary = intake_result_to_structured_summary(
result,
technical_failure=True,
)
fail_warnings = [
*warnings,
f'document_candidate_persist_failed:{type(exc).__name__}:{str(exc)[:200]}',
@@ -127,6 +127,7 @@ def _lean_parse_summary(structured: dict[str, Any] | None) -> dict[str, Any]:
if email.get('stored_body_text_length') is not None
else len(str(email.get('body_text') or ''))
),
'body_html_table_count': len(email.get('body_html_tables') or []),
}
out['email'] = lean_email
attachments = out.get('attachments')
@@ -145,6 +146,9 @@ def _lean_parse_summary(structured: dict[str, Any] | None) -> dict[str, Any]:
'text_length': item.get('text_length'),
'stored_text_length': item.get('stored_text_length'),
'warnings': list(item.get('warnings') or []),
'ready_for_extraction': bool(item.get('ready_for_extraction')),
'is_inline_resource': bool(item.get('is_inline_resource')),
'catalog_reason': item.get('catalog_reason'),
}
if item.get('asset_no'):
row['asset_no'] = item.get('asset_no')
@@ -192,6 +196,7 @@ def serialize_intake(
'intake_no': intake.intake_no,
'asset_no': asset.asset_no if asset else None,
'conversation_id': intake.conversation_id,
'upload_batch_id': intake.upload_batch_id,
'parse_status': intake.parse_status,
'parser_version': intake.parser_version,
'order_extraction_status': intake.order_extraction_status,
@@ -326,6 +331,7 @@ def create_shipping_notice_intake(
user_id: int,
asset_no: str,
conversation_id: str | None = None,
upload_batch_id: str | None = None,
) -> dict[str, Any]:
"""
基于已上传 FileAsset 创建接入记录并投递解析 Job。
@@ -339,7 +345,7 @@ def create_shipping_notice_intake(
"""
return _create_intake_for_asset(
user_id=user_id, asset_no=asset_no, purpose='shipping_notice',
conversation_id=conversation_id,
conversation_id=conversation_id, upload_batch_id=upload_batch_id,
)
@@ -352,12 +358,13 @@ def create_order_document_profile_sample_intake(*, user_id: int, asset_no: str)
"""
return _create_intake_for_asset(
user_id=user_id, asset_no=asset_no, purpose=ORDER_DOCUMENT_PROFILE_SAMPLE_PURPOSE,
conversation_id=None,
conversation_id=None, upload_batch_id=None,
)
def _create_intake_for_asset(
*, user_id: int, asset_no: str, purpose: str, conversation_id: str | None,
upload_batch_id: str | None,
) -> dict[str, Any]:
"""按受控 purpose 创建幂等 Intake;模板样本与业务发货通知共享基础设施但隔离用途。"""
asset = get_asset_for_user(asset_no, user_id)
@@ -368,6 +375,9 @@ def _create_intake_for_asset(
parser_version = _parser_version()
conv = str(conversation_id or '').strip() or None
provided_batch_id = str(upload_batch_id or '').strip()
# Workspace API 强制提供批次;服务层保留内部调用的隔离默认值。
batch_id = provided_batch_id or str(uuid.uuid4())
if purpose == ORDER_DOCUMENT_PROFILE_SAMPLE_PURPOSE:
extension = str(asset.extension or '').strip().lower()
if extension not in {'pdf', 'eml'}:
@@ -388,6 +398,7 @@ def _create_intake_for_asset(
asset_id=int(asset.id),
user_id=int(user_id),
conversation_id=conv,
upload_batch_id=batch_id or str(uuid.uuid4()),
purpose=purpose,
parse_status='created',
parser_version=parser_version,
@@ -408,6 +419,13 @@ def _create_intake_for_asset(
if intake is None:
raise
if purpose == 'shipping_notice' and provided_batch_id and intake.upload_batch_id != batch_id:
db.session.rollback()
raise ConflictError(
code='SHIPPING_NOTICE.UPLOAD_BATCH_MISMATCH',
message='Uploaded asset already belongs to another input batch',
)
# [STEP 2] 终态 / 已在飞 / 禁止复活
status_now = str(intake.parse_status or '')
if status_now in {'parsed', 'consumed', 'queued', 'parsing'}:
@@ -149,16 +149,21 @@ def extract_notice_text(
file_path: Path,
*,
retain_payloads: bool = False,
eml_attachment_mode: Literal["deep", "preview"] = "deep",
preview_only: bool = False,
) -> tuple[str, dict[str, Any]]:
"""
从发货通知附件抽取纯文本(PDF/DOCX/CSV/图片 OCR/EML/HTML 等)。
核心逻辑:普通文件走 edkb loaders;.eml 委托 eml_parse 做结构化解析(元数据 + 真实附件独立抽取),
内嵌 Logo/签名图不进入附件列表,也不参与订单文本拼接。
核心逻辑:普通文件走 edkb loaders;.eml 委托 eml_parse 做结构化解析。
`deep` 模式递归抽取附件文本,`preview` 模式仅保留邮件头/正文/附件目录。
非 EML 的 `preview_only` 只返回文件元信息,避免上传阶段触发 Loader 或 OCR。
Args:
file_path: 已落盘的通知文件路径。
retain_payloads: 仅 EML;True 时保留 attachments[*]._payload_bytes 供 Intake 派生资产。
eml_attachment_mode: `preview` 仅生成附件目录;`deep` 递归抽取附件文本。
preview_only: True 时普通文件不执行文本/OCR 抽取,留待发送后的深度识别阶段。
Returns:
tuple[str, dict]: (抽取文本, meta 含 warnings、file_type;eml 另含 email/attachments/attachment_count)。
@@ -168,6 +173,13 @@ def extract_notice_text(
ctx = Context(file_type=ext)
warnings: list[str] = []
if preview_only and ext != "eml":
return "", {
"warnings": warnings,
"file_type": ext,
"content_mode": "preview",
}
if ext in {"txt", "md", "log"}:
return _decode_text(path.read_bytes()).strip(), {"warnings": warnings, "file_type": ext}
if ext in {"html", "htm"}:
@@ -178,6 +190,7 @@ def extract_notice_text(
path.read_bytes(),
extract_text=extract_notice_text,
retain_payloads=retain_payloads,
attachment_mode=eml_attachment_mode,
)
blocks: list[Block] = []
@@ -325,6 +338,7 @@ def intake_notice_attachment(
task_no: str | None = None,
temp_request_id: str | None = None,
temp_index: int = 1,
eml_attachment_mode: Literal["deep", "preview"] = "preview",
) -> NoticeIntakeResult:
"""
单份发货通知附件的统一接入:落盘 → 抽取 → 截断 → 失败分流。
@@ -339,6 +353,7 @@ def intake_notice_attachment(
task_no: storage=task 时必填。
temp_request_id: storage=temp 时必填。
temp_index: storage=temp 时文件序号,避免同名覆盖。
eml_attachment_mode: EML 上传模式;`preview` 仅保留附件目录,适合输入栏快览。
Returns:
NoticeIntakeResult: 含 accepted / empty_text / extract_failed 状态与截断后正文。
@@ -363,7 +378,7 @@ def intake_notice_attachment(
if not temp_request_id:
raise ValueError("temp_request_id is required for temp storage")
saved_path = save_temp_notice_upload(temp_request_id, temp_index, name, raw_bytes)
text, meta = extract_notice_text(saved_path)
text, meta = extract_notice_text(saved_path, eml_attachment_mode=eml_attachment_mode)
warnings = list(meta.get("warnings") or []) if isinstance(meta, dict) else []
except Exception as exc:
warnings = [f"notice_extract_failed:{exc}"]
@@ -381,7 +396,17 @@ def intake_notice_attachment(
saved_path=saved_path,
)
if not str(text or "").strip():
preview_accept_without_text = (
isinstance(meta, dict)
and str(meta.get("file_type") or "").lower() == "eml"
and str(meta.get("eml_attachment_mode") or "").lower() == "preview"
and (
bool(meta.get("attachment_count"))
or bool(meta.get("attachments"))
or bool(meta.get("email"))
)
)
if not str(text or "").strip() and not preview_accept_without_text:
return NoticeIntakeResult(
filename=name,
source_type=source_type,
@@ -0,0 +1,309 @@
"""
services/shipping_notice/order_auto_freeze_execution.py
用途:消费 Run 级自动冻结门禁摘要,把当前 Run 已接受的候选订单落成 Task 并冻结为 Snapshot。
依赖:Run/Candidate/Task 模型、候选建批编排与订单冻结服务。
逻辑:只有当 run.auto_freeze_policy_json 已明确放行时才执行;执行范围严格限定在当前 Run,
且只创建/冻结本轮 accepted + selected 的候选,不触碰库存、Excel 或外部上传链路。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import (
ShippingNoticeCandidate,
ShippingOrderCustomerMatch,
ShippingOrderExtraction,
ShippingOrderExtractionRun,
ShippingTask,
)
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
def maybe_execute_run_auto_freeze(
*,
run: ShippingOrderExtractionRun,
submission_result: dict[str, Any],
) -> dict[str, Any]:
"""在门禁已放行时消费当前 Run 的 accepted Candidate,并自动冻结其新建任务。"""
result = dict(submission_result or {})
policy = run.auto_freeze_policy_json if isinstance(run.auto_freeze_policy_json, dict) else {}
if not bool(policy.get('enabled')):
return result
candidate_nos = _eligible_candidate_nos(run)
create_result: dict[str, Any] | None = None
if candidate_nos:
create_result = create_shipping_batch_from_candidates(
user_id=int(run.user_id),
conversation_id=run.conversation_id,
intake_nos=_snapshot_intake_nos(run),
candidate_nos=candidate_nos,
create_idempotency_key=f"extract:{str(run.input_snapshot_hash or '')[:48]}",
)
frozen_task_nos, blocked_tasks = _freeze_created_tasks(run=run, policy=policy)
refreshed = _refresh_submission_result(
run=run,
previous_result=result,
create_result=create_result,
)
refreshed['auto_freeze'] = {
'enabled': True,
'frozen_task_nos': frozen_task_nos,
'blocked_tasks': blocked_tasks,
}
return refreshed
def _eligible_candidate_nos(run: ShippingOrderExtractionRun) -> list[str]:
"""只返回当前 Run 中可以自动建单的 accepted + selected 候选。"""
rows = (
ShippingNoticeCandidate.query
.filter_by(
order_extraction_run_id=int(run.id),
is_current_version=True,
candidate_status='accepted',
selected=True,
)
.filter(ShippingNoticeCandidate.consumed_task_id.is_(None))
.order_by(ShippingNoticeCandidate.id.asc())
.all()
)
return [str(item.candidate_no) for item in rows if str(item.candidate_no or '').strip()]
def _snapshot_intake_nos(run: ShippingOrderExtractionRun) -> list[str]:
"""从 Run 冻结快照提取 Intake 编号,确保自动消费范围不越过本轮输入。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else []
return [
str(item.get('intake_no') or '').strip().upper()
for item in intakes
if isinstance(item, dict) and str(item.get('intake_no') or '').strip()
]
def _freeze_created_tasks(
*,
run: ShippingOrderExtractionRun,
policy: dict[str, Any],
) -> tuple[list[str], list[dict[str, Any]]]:
"""冻结当前 Run 已建出的任务;任一任务阻断时只保留 fail-closed 事实。"""
candidates = (
ShippingNoticeCandidate.query
.filter_by(order_extraction_run_id=int(run.id), is_current_version=True)
.filter(ShippingNoticeCandidate.consumed_task_id.isnot(None))
.order_by(ShippingNoticeCandidate.id.asc())
.all()
)
frozen_task_nos: list[str] = []
blocked_tasks: list[dict[str, Any]] = []
for candidate in candidates:
if str(candidate.duplicate_resolution or '').strip().lower() == 'open_existing':
continue
task = db.session.get(ShippingTask, int(candidate.consumed_task_id or 0))
if task is None:
continue
_inherit_confirmed_ordering_customer(run=run, task=task, policy=policy)
try:
snapshot = freeze_order_snapshot(
task,
actor_id=None,
expected_order_data_version=int(task.order_data_version or 1),
freeze_mode='auto',
auto_freeze_policy=policy,
)
frozen_task_nos.append(str(task.task_no or f"snapshot-{snapshot.id}"))
except Exception as exc: # pragma: no cover - 阻断明细由调用侧测试断言
blocked_tasks.append({
'candidate_no': str(candidate.candidate_no or ''),
'task_no': str(task.task_no or ''),
'code': str(getattr(exc, 'code', '') or ''),
'message': str(exc),
'details': getattr(exc, 'details', None),
})
return frozen_task_nos, blocked_tasks
def _inherit_confirmed_ordering_customer(
*,
run: ShippingOrderExtractionRun,
task: ShippingTask,
policy: dict[str, Any],
) -> None:
"""把 Run 已确认的唯一 Bill-to 客户补写到当前任务 Extraction,供自动冻结门禁复用。"""
confirmed_ids = sorted({
int(item)
for item in (policy.get('confirmed_customer_ids') or [])
if str(item).strip().isdigit()
})
if len(confirmed_ids) != 1 or not task.current_order_extraction_id:
return
extraction = db.session.get(ShippingOrderExtraction, int(task.current_order_extraction_id))
if extraction is None:
return
target = ShippingOrderCustomerMatch.query.filter_by(
extraction_id=int(extraction.id),
role='bill_to',
).one_or_none()
if (
target is not None
and target.status == 'confirmed'
and int(target.customer_id or 0) == confirmed_ids[0]
and bool(target.customer_short_code_snapshot)
and bool(target.identity_fingerprint)
and bool(target.identity_rule_version)
):
return
if target is not None and target.status == 'confirmed' and target.customer_id not in {None, confirmed_ids[0]}:
return
source = (
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 == confirmed_ids[0],
)
.order_by(ShippingOrderCustomerMatch.confirmed_at.desc(), ShippingOrderCustomerMatch.id.desc())
.first()
)
if source is None:
return
if target is None:
target = ShippingOrderCustomerMatch(
extraction_id=int(extraction.id),
role='bill_to',
identity_components_json={},
candidates_json=[],
)
db.session.add(target)
target.raw_name = source.raw_name
target.normalized_name = source.normalized_name
target.source_system = source.source_system
target.external_code = source.external_code
target.identity_fingerprint = source.identity_fingerprint
target.identity_rule_version = source.identity_rule_version
target.identity_components_json = dict(source.identity_components_json or {})
target.status = 'confirmed'
target.customer_id = source.customer_id
target.site_id = source.site_id
target.customer_name_snapshot = source.customer_name_snapshot
target.customer_short_code_snapshot = source.customer_short_code_snapshot
target.candidates_json = list(source.candidates_json or [])
target.resolution_method = source.resolution_method or 'run_auto_freeze_inherited'
target.confirmation_reason = source.confirmation_reason or 'run_auto_freeze_inherited'
target.confirmed_by_id = source.confirmed_by_id
target.confirmed_at = source.confirmed_at or datetime.utcnow()
target.updated_at = datetime.utcnow()
db.session.flush()
def _refresh_submission_result(
*,
run: ShippingOrderExtractionRun,
previous_result: dict[str, Any],
create_result: dict[str, Any] | None,
) -> dict[str, Any]:
"""按当前 Run 持久化事实重建摘要,确保自动建单后 created/pending 计数可恢复。"""
candidates = (
ShippingNoticeCandidate.query
.filter_by(order_extraction_run_id=int(run.id), is_current_version=True)
.order_by(ShippingNoticeCandidate.id.asc())
.all()
)
pending_by_candidate_no = {
str(item.get('candidate_no') or ''): item
for item in previous_result.get('pending_orders') or []
if isinstance(item, dict) and str(item.get('candidate_no') or '').strip()
}
created: list[dict[str, Any]] = []
opened_existing: list[dict[str, Any]] = []
pending_orders: list[dict[str, Any]] = []
created_with_missing_fields_count = 0
for candidate in candidates:
if candidate.consumed_task_id is None:
pending_item = pending_by_candidate_no.get(str(candidate.candidate_no or ''))
if pending_item is not None:
pending_orders.append(pending_item)
continue
task = db.session.get(ShippingTask, int(candidate.consumed_task_id))
if task is None:
continue
if str(candidate.duplicate_resolution or '').strip().lower() == 'open_existing':
opened_existing.append({
'candidate_no': candidate.candidate_no,
'task_no': task.task_no,
'batch_no': None,
})
continue
created.append({'task_no': task.task_no})
if candidate.missing_fields_json:
created_with_missing_fields_count += 1
created_with_missing_fields_count = min(created_with_missing_fields_count, len(created))
non_shipping_orders = list(previous_result.get('non_shipping_orders') or [])
refreshed = {
'status': 'ok',
'request_id': str(run.run_no),
'batch_no': (
create_result.get('batch_no')
if isinstance(create_result, dict) and create_result.get('batch_no')
else previous_result.get('batch_no')
),
'created': created,
'opened_existing': opened_existing,
'pending_orders': pending_orders,
'non_shipping_orders': non_shipping_orders,
'created_count': len(created),
'opened_existing_count': len(opened_existing),
'pending_count': len(pending_orders),
'non_shipping_count': len(non_shipping_orders),
'created_with_missing_fields_count': created_with_missing_fields_count,
}
refreshed['message'] = _build_submission_message(
created_count=refreshed['created_count'],
opened_existing_count=refreshed['opened_existing_count'],
pending_count=refreshed['pending_count'],
non_shipping_count=refreshed['non_shipping_count'],
created_with_missing_fields_count=created_with_missing_fields_count,
)
return refreshed
def _build_submission_message(
*,
created_count: int,
opened_existing_count: int,
pending_count: int,
non_shipping_count: int,
created_with_missing_fields_count: int,
) -> str:
"""生成自动冻结执行后的统一结果摘要,保持与订单抽取主链路文案一致。"""
if not created_count and not opened_existing_count and not pending_count:
if non_shipping_count:
return f'未识别到需要处理的发货订单,已忽略 {non_shipping_count} 项非发货内容;本次未创建任务。'
return '未识别到发货订单,本次未创建任务。'
parts: list[str] = []
if created_count:
parts.append(f'已创建 {created_count} 个发货任务')
if opened_existing_count:
parts.append(f'已打开 {opened_existing_count} 个已有任务')
if pending_count:
prefix = '另有' if parts else '有'
parts.append(f'{prefix} {pending_count} 个订单需要补充信息或处理冲突')
if non_shipping_count:
parts.append(f'已忽略 {non_shipping_count} 项非发货内容')
message = ';'.join(parts) + '。'
if created_with_missing_fields_count:
message += (
f'其中 {created_with_missing_fields_count} 个新建任务仍缺少 Reservation ID,'
'可通过自然对话补充。'
)
return message
@@ -0,0 +1,255 @@
"""
services/shipping_notice/order_auto_freeze_policy.py
用途:统一生成订单抽取 Run 的自动冻结门禁摘要,不让各处各自拼 policy JSON。
依赖:Run/Unit/RouteDecision/Qualification 模型;只读取脱敏事实,不触碰履约副作用。
逻辑:Run 创建时冻结初始人工确认策略;结果落库后按模板资格、技术失败、预算停止和复核状态刷新门禁摘要。
"""
from __future__ import annotations
from typing import Any
from app.models import (
ShippingDocumentProfileAutoFreezeQualification,
ShippingOrderCustomerMatch,
ShippingOrderExtraction,
ShippingOrderExtractionProgressEvent,
ShippingOrderExtractionRouteDecision,
ShippingOrderExtractionRun,
)
_DEFAULT_BUSINESS_SCENARIO = 'shipping_notice_order'
def build_initial_auto_freeze_policy(*, schema_policy_version: str | None) -> dict[str, Any]:
"""创建 Run 时冻结首版自动冻结策略,默认仅允许人工确认。"""
return {
'mode': 'manual_confirmation',
'enabled': False,
'schema_policy_version': schema_policy_version,
}
def evaluate_run_auto_freeze_policy(
*,
run: ShippingOrderExtractionRun,
submission_result: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""按 Run 已知事实计算自动冻结门禁摘要,并消费模板资格里的客户/场景授权范围。"""
current = dict(run.auto_freeze_policy_json or {})
policy = build_initial_auto_freeze_policy(
schema_policy_version=str(current.get('schema_policy_version') or '') or None,
)
approved_routes = _approved_routes(run)
qualification = None
selected_route = None
blocking_reason_codes: list[str] = []
confirmed_customer_ids: list[int] = []
customer_scope_status = 'unconfigured'
current_business_scenario = _DEFAULT_BUSINESS_SCENARIO
business_scenario_status = 'unconfigured'
requires_customer_confirmation = True
if not approved_routes:
blocking_reason_codes.append('profile_not_auto_freeze_approved')
elif len({
(int(route.selected_profile_id or 0), str(route.selected_profile_checksum or ''))
for route in approved_routes
if route.selected_profile_id
}) > 1:
blocking_reason_codes.append('multiple_profiles_detected')
else:
selected_route = approved_routes[-1]
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')
confirmed_customer_ids = _confirmed_customer_ids(run)
customer_scope_status, customer_scope_reason_codes = _evaluate_customer_scope(
qualification=qualification,
confirmed_customer_ids=confirmed_customer_ids,
)
blocking_reason_codes.extend(customer_scope_reason_codes)
business_scenario_status, business_scenario_reason_codes = _evaluate_business_scenario_scope(
qualification=qualification,
business_scenario=current_business_scenario,
)
blocking_reason_codes.extend(business_scenario_reason_codes)
requires_customer_confirmation = bool(
qualification.requires_customer_confirmation
) if qualification is not None else True
if _has_technical_failure(run):
blocking_reason_codes.append('technical_failure_present')
if _has_review_required_unit(run):
# Worker 提交候选时 Run 仍可能处于 processing,不能等最终状态才阻断副作用。
blocking_reason_codes.append('unit_review_required')
if _has_budget_stop(run):
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':
blocking_reason_codes.append('run_failed')
if str(run.status or '') == 'cancelled':
blocking_reason_codes.append('run_cancelled')
if _has_blocking_pending_orders(submission_result):
blocking_reason_codes.append('pending_orders_present')
enabled = bool(
qualification is not None
and str(qualification.status or '') == 'auto_freeze_approved'
and customer_scope_status == 'matched'
and business_scenario_status == 'matched'
and not requires_customer_confirmation
and not blocking_reason_codes
)
if requires_customer_confirmation:
blocking_reason_codes.append('customer_confirmation_required')
policy.update({
'enabled': enabled,
'selected_profile_id': int(selected_route.selected_profile_id) if selected_route and selected_route.selected_profile_id else None,
'selected_profile_code': str(selected_route.selected_profile_code or '') or None if selected_route else None,
'selected_profile_checksum': str(selected_route.selected_profile_checksum or '') or None if selected_route else None,
'qualification_id': int(qualification.id) if qualification is not None else None,
'qualification_status': str(qualification.status or '') if qualification is not None else None,
'authorized_customer_ids': list(qualification.customer_ids_json or []) if qualification is not None else [],
'confirmed_customer_ids': confirmed_customer_ids,
'customer_scope_status': customer_scope_status,
'authorized_business_scenarios': list(qualification.business_scenarios_json or []) if qualification is not None else [],
'business_scenario': current_business_scenario,
'business_scenario_status': business_scenario_status,
'customer_confirmation_required': requires_customer_confirmation,
'blocking_reason_codes': sorted(set(code for code in blocking_reason_codes if code)),
'evaluated_from_run': True,
})
return policy
def _approved_routes(run: ShippingOrderExtractionRun) -> list[ShippingOrderExtractionRouteDecision]:
"""只返回声明可自动冻结模板命中的分流决策。"""
return [
route for route in (run.route_decisions or [])
if bool(route.auto_create_approved) and route.selected_profile_id
]
def _qualification_for_route(
route: ShippingOrderExtractionRouteDecision,
) -> ShippingDocumentProfileAutoFreezeQualification | None:
"""按命中的模板版本读取当前资格状态;缺失时按 fail-closed 处理。"""
return ShippingDocumentProfileAutoFreezeQualification.query.filter_by(
profile_id=int(route.selected_profile_id),
profile_checksum=str(route.selected_profile_checksum or ''),
).one_or_none()
def _confirmed_customer_ids(run: ShippingOrderExtractionRun) -> list[int]:
"""读取本轮已确认的 Bill-to 客户;跨订单多客户时必须维持 fail-closed。"""
rows = (
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),
)
.all()
)
return sorted({int(row.customer_id) for row in rows if row.customer_id is not None})
def _evaluate_customer_scope(
*,
qualification: ShippingDocumentProfileAutoFreezeQualification | None,
confirmed_customer_ids: list[int],
) -> tuple[str, list[str]]:
"""根据资格白名单和 Run 已确认客户判断当前客户授权状态。"""
if qualification is None:
return 'unconfigured', []
configured_ids = [int(item) for item in (qualification.customer_ids_json or [])]
if not configured_ids:
return 'unconfigured', ['customer_scope_not_configured']
if not confirmed_customer_ids:
return 'customer_unconfirmed', ['customer_confirmation_required']
if len(confirmed_customer_ids) > 1:
return 'ambiguous', ['multiple_customers_detected']
if int(confirmed_customer_ids[0]) not in set(configured_ids):
return 'out_of_scope', ['customer_scope_out_of_scope']
return 'matched', []
def _evaluate_business_scenario_scope(
*,
qualification: ShippingDocumentProfileAutoFreezeQualification | None,
business_scenario: str,
) -> tuple[str, list[str]]:
"""根据资格白名单判断当前 Run 所属业务场景是否允许自动冻结。"""
if qualification is None:
return 'unconfigured', []
configured = [
str(item or '').strip().lower()
for item in (qualification.business_scenarios_json or [])
if str(item or '').strip()
]
if not configured:
return 'unconfigured', ['business_scenario_not_configured']
if str(business_scenario or '').strip().lower() not in set(configured):
return 'out_of_scope', ['business_scenario_out_of_scope']
return 'matched', []
def _has_technical_failure(run: ShippingOrderExtractionRun) -> bool:
"""任一单元技术失败或技术失败事件均阻断自动冻结。"""
units = (run.extraction_plan.units if run.extraction_plan is not None else [])
if any(str(unit.technical_failure_reason_code or '').strip() for unit in units):
return True
return ShippingOrderExtractionProgressEvent.query.filter_by(
run_id=int(run.id),
event_code='technical_failed',
).first() is not None
def _has_review_required_unit(run: ShippingOrderExtractionRun) -> bool:
"""任一 Unit 已要求人工复核时,禁止其余订单绕过整体 Run 门禁自动冻结。"""
units = run.extraction_plan.units if run.extraction_plan is not None else []
return any(str(unit.status or '') == 'review_required' for unit in units)
def _has_budget_stop(run: ShippingOrderExtractionRun) -> bool:
"""预算停止事件是自动冻结硬阻断。"""
return ShippingOrderExtractionProgressEvent.query.filter_by(
run_id=int(run.id),
event_code='budget_stopped',
).first() is not None
def _has_blocking_pending_orders(submission_result: dict[str, Any] | None) -> bool:
"""
判断提交结果中的待处理订单是否属于真实阻断。
AI 触发时机:阶段 5 需要区分“业务上仍待复核的 pending”与“已 accepted、仅等待自动消费为 Task 的 pending”。
后者不会携带原因码或缺字段清单,不应把本应放行的自动冻结继续卡死在 pending_count 上。
"""
if not isinstance(submission_result, dict):
return False
pending_orders = submission_result.get('pending_orders')
if not isinstance(pending_orders, list):
return int(submission_result.get('pending_count') or 0) > 0
if not pending_orders:
return False
for item in pending_orders:
if not isinstance(item, dict):
return True
reasons = [str(code) for code in item.get('reasons') or [] if str(code).strip()]
missing_fields = [str(code) for code in item.get('missing_fields') or [] if str(code).strip()]
duplicate_status = str(item.get('duplicate_status') or '').strip().lower()
if reasons or missing_fields or duplicate_status not in {'', 'none'}:
return True
return False
@@ -57,6 +57,7 @@ from app.services.shipping_notice.order_schema.compatibility import (
remap_profile_field_codes,
)
from app.services.shipping_notice.document_layout.order_profile_extractors import registered_extractor_output_codes
from app.services.shipping_notice.preview_grant_store import preview_grant_store
PROFILE_CODE_PATTERN = re.compile(r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
@@ -141,16 +142,8 @@ def _bound_sample_document(profile_id: int, document_id: int) -> ShippingNoticeD
def _preview_grant_store() -> Any:
"""取得预览令牌 Redis;多 Worker 下必须可原子消费,连接不可用时拒绝预览。"""
from app.services.redis_client import get_redis_client
client = get_redis_client()
if client is None:
raise ServiceUnavailableError(
'Order profile preview is temporarily unavailable',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
)
return client
"""取得预览令牌存储;生产强依赖 Redis,开发环境可显式启用单进程兜底。"""
return preview_grant_store()
def _schema_fields(version: ShippingOrderSchemaVersion) -> dict[str, dict[str, Any]]:
@@ -33,6 +33,8 @@ from app.services.shipping_notice.business_fingerprint import (
build_business_fingerprint,
build_content_fingerprint,
)
from app.services.shipping_notice.order_auto_freeze_policy import evaluate_run_auto_freeze_policy
from app.services.shipping_notice.order_auto_freeze_execution import maybe_execute_run_auto_freeze
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
from app.services.shipping_notice.duplicate_detection import (
aggregate_intake_duplicate_from_candidates,
@@ -99,6 +101,26 @@ def _order_extraction_submission(intake: ShippingNoticeIntake) -> dict[str, Any]
return submission if isinstance(submission, dict) else {}
def _store_run_submission_result(
*,
intakes: list[ShippingNoticeIntake],
snapshot_hash: str,
request_id: str,
result: dict[str, Any],
) -> None:
"""把最新 Run 提交结果回写到 Intake,确保自动冻结后的 created/pending 摘要可重放。"""
for intake in intakes:
structured = dict(intake.structured_result_json or {})
structured['order_extraction_submission'] = {
'input_snapshot_hash': snapshot_hash,
'request_id': request_id,
'result': result,
'submitted_at': datetime.utcnow().isoformat(),
}
intake.structured_result_json = structured
flag_modified(intake, 'structured_result_json')
def _float(value: Any, default: float = 0.0) -> float:
"""将 LLM 置信度规范为 0..1 浮点数。"""
try:
@@ -188,6 +210,7 @@ def persist_order_extraction_result(
frozen_layout_candidates_by_document: dict[int, list[dict[str, Any]]] | None = None,
frozen_evidence_text_by_document: dict[int, str] | None = None,
auto_create_enabled: bool = False,
allow_orphaned_consumed_reparse: bool = False,
) -> dict[str, Any]:
"""
持久化后台订单抽取 Run 的结构化结果,并执行后端裁决、判重与自动建单。
@@ -235,7 +258,16 @@ def persist_order_extraction_result(
replay = dict(replay_results[0])
replay['idempotent_replay'] = True
return replay
if any(row.parse_status == 'consumed' for row in intakes):
if any(row.parse_status == 'consumed' for row in intakes) and not (
allow_orphaned_consumed_reparse
and all(
row.parse_status == 'consumed'
and row.consumed_at is not None
and row.consumed_task_id is None
and row.consumed_batch_id is None
for row in intakes
)
):
raise ConflictError(
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING',
message='已消费的 Intake 仅允许回放原订单抽取结果',
@@ -756,21 +788,21 @@ def submit_order_extraction_run_result(
if len(intakes) != len(intake_nos):
raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='Run 输入 Intake 不完整')
run_extractions = ShippingOrderExtraction.query.filter_by(run_id=int(run.id)).all()
if run_extractions and all(
run_candidates = ShippingNoticeCandidate.query.filter_by(order_extraction_run_id=int(run.id)).all()
if run_extractions and run_candidates and all(
extraction.status in {'accepted', 'needs_review'}
for extraction in run_extractions
):
candidates = ShippingNoticeCandidate.query.filter_by(order_extraction_run_id=int(run.id)).all()
consumed_task_ids = {
int(candidate.consumed_task_id)
for candidate in candidates
for candidate in run_candidates
if candidate.consumed_task_id is not None
}
task_nos = sorted({
str(task.task_no)
for task in ShippingTask.query.filter(ShippingTask.id.in_(consumed_task_ids)).all()
}) if consumed_task_ids else []
pending = [candidate for candidate in candidates if candidate.consumed_task_id is None]
pending = [candidate for candidate in run_candidates if candidate.consumed_task_id is None]
result = {
'status': 'ok',
'request_id': str(run.run_no),
@@ -787,16 +819,17 @@ def submit_order_extraction_run_result(
'idempotent_replay': True,
'recovered_from_run_facts': True,
}
for intake in intakes:
structured = dict(intake.structured_result_json or {})
structured['order_extraction_submission'] = {
'input_snapshot_hash': run.input_snapshot_hash,
'request_id': str(run.run_no),
'result': result,
'submitted_at': datetime.utcnow().isoformat(),
}
intake.structured_result_json = structured
flag_modified(intake, 'structured_result_json')
run.auto_freeze_policy_json = evaluate_run_auto_freeze_policy(run=run, submission_result=result)
flag_modified(run, 'auto_freeze_policy_json')
result = maybe_execute_run_auto_freeze(run=run, submission_result=result)
_store_run_submission_result(
intakes=intakes,
snapshot_hash=str(run.input_snapshot_hash),
request_id=str(run.run_no),
result=result,
)
run.auto_freeze_policy_json = evaluate_run_auto_freeze_policy(run=run, submission_result=result)
flag_modified(run, 'auto_freeze_policy_json')
db.session.commit()
return result
cached_orders = (
@@ -826,28 +859,41 @@ def submit_order_extraction_run_result(
'idempotent_replay': True,
'recovered_from_consumed_empty_result': True,
}
for intake in intakes:
structured = dict(intake.structured_result_json or {})
structured['order_extraction_submission'] = {
'input_snapshot_hash': run.input_snapshot_hash,
'request_id': str(run.run_no),
'result': result,
'submitted_at': datetime.utcnow().isoformat(),
}
intake.structured_result_json = structured
flag_modified(intake, 'structured_result_json')
run.auto_freeze_policy_json = evaluate_run_auto_freeze_policy(run=run, submission_result=result)
flag_modified(run, 'auto_freeze_policy_json')
result = maybe_execute_run_auto_freeze(run=run, submission_result=result)
_store_run_submission_result(
intakes=intakes,
snapshot_hash=str(run.input_snapshot_hash),
request_id=str(run.run_no),
result=result,
)
run.auto_freeze_policy_json = evaluate_run_auto_freeze_policy(run=run, submission_result=result)
flag_modified(run, 'auto_freeze_policy_json')
db.session.commit()
return result
is_replay = all(
str(_order_extraction_submission(intake).get('request_id') or '') == str(run.run_no)
for intake in intakes
)
# 重识别只可复用“曾被空结果误标 consumed、但未实际建单/建批”的 Intake。
# 已绑定任务或批次的记录仍保持不可写,避免新版本覆盖真实业务结果。
is_orphaned_reparse = (
run.reparse_of_run_id is not None
and all(
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
for intake in intakes
)
)
session = db.session.query(ChatSession).filter_by(session_id=run.conversation_id).one()
current_intakes = _load_intakes(
session=session,
intake_nos=intake_nos,
lock=True,
allow_consumed=is_replay,
allow_consumed=is_replay or is_orphaned_reparse,
)
current_documents = _load_documents(current_intakes, lock=True)
current_intake_by_id = {int(item.id): item for item in current_intakes}
@@ -876,7 +922,7 @@ def submit_order_extraction_run_result(
code='SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED',
message='Run 冻结后的邮件或附件内容已变化',
)
return persist_order_extraction_result(
result = persist_order_extraction_result(
session=session,
intakes=current_intakes,
documents=current_documents,
@@ -892,4 +938,18 @@ def submit_order_extraction_run_result(
auto_create_enabled=bool(
((run.auto_freeze_policy_json or {}).get('enabled', False))
),
allow_orphaned_consumed_reparse=is_orphaned_reparse,
)
run.auto_freeze_policy_json = evaluate_run_auto_freeze_policy(run=run, submission_result=result)
flag_modified(run, 'auto_freeze_policy_json')
result = maybe_execute_run_auto_freeze(run=run, submission_result=result)
_store_run_submission_result(
intakes=current_intakes,
snapshot_hash=str(run.input_snapshot_hash),
request_id=str(run.run_no),
result=result,
)
run.auto_freeze_policy_json = evaluate_run_auto_freeze_policy(run=run, submission_result=result)
flag_modified(run, 'auto_freeze_policy_json')
db.session.commit()
return result
@@ -0,0 +1,312 @@
"""
services/shipping_notice/order_extraction_materialization.py
用途:在点击发送后,按附件选择计划为 Run 物化本次真正需要的输入文档。
依赖:ShippingNoticeIntake/FileAsset、notice_upload、document_candidate_persist、attachment_selection。
逻辑:上传阶段保持快览轻量;发送阶段只为本次计划选中的附件和邮件正文创建 Document/派生资产,
不把未选附件偷偷升级成可执行输入。
"""
from __future__ import annotations
import tempfile
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from flask import current_app
from app import db
from app.core.errors import ConflictError
from app.models import FileAsset, ShippingNoticeDocument, ShippingNoticeIntake
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.eml_parse import pop_attachment_payload
from app.services.shipping_notice.notice_upload import (
NoticeIntakeResult,
extract_notice_text,
)
from app.services.shipping_notice.intake_parse_workflow import extract_notice_from_asset
def _existing_document_keys(intake: ShippingNoticeIntake) -> set[str]:
"""返回当前 Intake 已落库文档键,供发送阶段判断是否需要补物化。"""
rows = (
db.session.query(ShippingNoticeDocument.attachment_key)
.filter(ShippingNoticeDocument.intake_id == int(intake.id))
.all()
)
return {str(value or '').strip() for (value,) in rows if str(value or '').strip()}
def _selected_attachment_keys_for_intake(
*,
intake: ShippingNoticeIntake,
attachment_selection: dict[str, Any],
selection_batches: set[int] | None = None,
) -> set[str]:
"""从计划摘要中取出某个 Intake 在指定批次内被授权深度解析的附件键。"""
normalized = str(intake.intake_no or '').strip().upper()
allowed_batches = {int(batch) for batch in (selection_batches or {1}) if int(batch) > 0}
selected: set[str] = set()
for row in attachment_selection.get('items') or []:
if not isinstance(row, dict):
continue
if str(row.get('intake_no') or '').strip().upper() != normalized:
continue
batch_no = int(
row.get('selection_batch')
or row.get('planned_selection_batch')
or 0
)
if batch_no not in allowed_batches:
continue
if batch_no == 1 and not row.get('selected'):
continue
key = str(row.get('attachment_key') or '').strip()
if key:
selected.add(key)
return selected
def _parse_attachment_payload(
*, payload: bytes, filename: str, mime_type: str, flask_app: Any | None = None,
) -> tuple[str, dict[str, Any]]:
"""仅对选中的附件载荷做深度文本抽取;并发线程必须自建 Flask 上下文。"""
suffix = Path(str(filename or 'attachment')).suffix or '.bin'
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
tmp.write(payload or b'')
tmp_path = Path(tmp.name)
try:
if flask_app is None:
return extract_notice_text(tmp_path)
with flask_app.app_context():
return extract_notice_text(tmp_path)
finally:
try:
tmp_path.unlink(missing_ok=True)
except OSError:
pass
def _build_selected_eml_result(
*,
intake: ShippingNoticeIntake,
parent_asset: FileAsset,
selected_attachment_keys: set[str],
max_concurrency: int = 1,
) -> NoticeIntakeResult:
"""
基于 preview 目录和载荷,只为本次选中的 EML 附件构造深度持久化输入。
核心逻辑:先以 preview+retain_payloads 读取目录和原始二进制,再仅对 selected keys 深度抽取。
"""
preview_result = extract_notice_from_asset(
parent_asset,
eml_attachment_mode='preview',
retain_payloads=True,
)
if preview_result.status != 'accepted':
raise ConflictError(
'Shipping notice preview is not ready for extraction',
code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE',
details={'intake_nos': [str(intake.intake_no or '')]},
)
meta = dict(preview_result.meta or {}) if isinstance(preview_result.meta, dict) else {}
selected_rows: list[dict[str, Any]] = []
parse_inputs: list[tuple[int, dict[str, Any], bytes]] = []
for raw_item in meta.get('attachments') or []:
if not isinstance(raw_item, dict):
continue
item = dict(raw_item)
key = str(item.get('attachment_key') or '').strip()
payload = pop_attachment_payload(item)
if key not in selected_attachment_keys:
continue
warnings = [str(value) for value in (item.get('warnings') or [])]
if not payload:
item['parse_status'] = 'failed'
item['extracted_text'] = ''
item['warnings'] = [*warnings, 'selected_attachment_payload_missing']
selected_rows.append(item)
continue
parse_inputs.append((len(selected_rows), item, payload))
selected_rows.append(item)
flask_app = current_app._get_current_object()
# 线程只处理附件字节和临时文件,禁止访问 ORM/Session;Document 写入仍在主线程串行收口。
def parse_one(item: dict[str, Any], payload: bytes) -> tuple[str, dict[str, Any]]:
return _parse_attachment_payload(
payload=payload,
filename=str(item.get('filename') or item.get('attachment_key') or 'attachment'),
mime_type=str(item.get('mime_type') or 'application/octet-stream'),
flask_app=flask_app,
)
parsed: dict[int, tuple[str, dict[str, Any]]] = {}
worker_count = min(max(1, int(max_concurrency or 1)), len(parse_inputs))
if worker_count > 1:
with ThreadPoolExecutor(max_workers=worker_count, thread_name_prefix='shipping-attachment-extract') as pool:
futures = {
index: pool.submit(parse_one, item, payload)
for index, item, payload in parse_inputs
}
for index, future in futures.items():
parsed[index] = future.result()
else:
for index, item, payload in parse_inputs:
parsed[index] = parse_one(item, payload)
for index, item, payload in parse_inputs:
text, attachment_meta = parsed[index]
warnings = [str(value) for value in (item.get('warnings') or [])]
attachment_warnings = [str(value) for value in (attachment_meta.get('warnings') or [])]
item['parse_status'] = 'parsed' if str(text or '').strip() else 'empty'
item['extracted_text'] = str(text or '')
item['warnings'] = [*warnings, *attachment_warnings]
item['_payload_bytes'] = payload
email_meta = meta.get('email') if isinstance(meta.get('email'), dict) else {}
return NoticeIntakeResult(
filename=str(parent_asset.original_filename or intake.intake_no or 'notice.eml'),
source_type='email',
source_file_type=parent_asset.mime_type,
text=str(preview_result.text or ''),
warnings=list(preview_result.warnings or []),
meta={
'file_type': 'eml',
'eml_attachment_mode': 'deep',
'warnings': list(preview_result.warnings or []),
'email': {
'message_id': email_meta.get('message_id') or '',
'subject': email_meta.get('subject') or '',
'from': email_meta.get('from') or '',
'to': email_meta.get('to') or '',
'date': email_meta.get('date') or '',
'body_text': email_meta.get('body_text') or '',
'body_html_tables': [str(item) for item in (email_meta.get('body_html_tables') or []) if str(item).strip()],
},
'attachments': selected_rows,
'attachment_count': len(selected_rows),
'attachment_registered_count': len(selected_rows),
},
content_hash=str(parent_asset.content_hash or ''),
file_size=int(parent_asset.file_size or 0),
status='accepted',
saved_path=None,
)
def _asset_read_snapshot(asset: FileAsset) -> SimpleNamespace:
"""把线程所需的 Asset 字段复制为纯数据,禁止背景线程触碰主线程 ORM 实体。"""
return SimpleNamespace(
deleted_at=asset.deleted_at,
expires_at=asset.expires_at,
lifecycle_status=asset.lifecycle_status,
storage_key=str(asset.storage_key or ''),
original_filename=str(asset.original_filename or ''),
mime_type=asset.mime_type,
content_hash=str(asset.content_hash or ''),
file_size=int(asset.file_size or 0),
)
def _build_single_file_result_in_thread(*, parent_asset: Any, flask_app: Any) -> NoticeIntakeResult:
"""复用资产抽取入口在线程中处理普通文件;禁止访问 Session 或持久化任何 ORM 事实。"""
with flask_app.app_context():
return extract_notice_from_asset(parent_asset, eml_attachment_mode='deep')
def ensure_order_extraction_input_documents(
*,
intakes: list[ShippingNoticeIntake],
attachment_selection: dict[str, Any],
schema_definition: dict[str, Any] | None = None,
selection_batches: set[int] | None = None,
) -> None:
"""
在创建 Run 前,确保当前发送批次所需的输入文档已按计划物化。
AI 触发时机:点击发送后、冻结 Run 快照前使用。上传阶段禁止调用本函数。
核心逻辑:
1. 普通单文件只物化唯一 `file` 文档;
2. EML 只物化正文 + 当前授权批次的附件,不等待布局任务终态;
3. 已满足本次计划的 Intake 不重复物化。
"""
definition = dict(schema_definition or {})
allowed_batches = {int(batch) for batch in (selection_batches or {1}) if int(batch) > 0}
max_concurrency = max(1, int(attachment_selection.get('max_initial_concurrency') or 1))
normal_inputs: list[tuple[ShippingNoticeIntake, FileAsset]] = []
eml_inputs: list[tuple[ShippingNoticeIntake, FileAsset, set[str]]] = []
for intake in intakes:
parent_asset = db.session.get(FileAsset, int(intake.asset_id)) if intake.asset_id else None
if parent_asset is None:
raise ConflictError(
'Shipping notice asset is unavailable',
code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE',
details={'intake_nos': [str(intake.intake_no or '')], 'reason': 'parent_asset_missing'},
)
existing_keys = _existing_document_keys(intake)
source_name = str(parent_asset.original_filename or '')
is_eml = source_name.lower().endswith('.eml') or str(parent_asset.mime_type or '').lower() in {'message/rfc822', 'application/eml'}
if not is_eml:
if existing_keys == {'file'}:
continue
normal_inputs.append((intake, parent_asset))
continue
selected_attachment_keys = _selected_attachment_keys_for_intake(
intake=intake,
attachment_selection=attachment_selection,
selection_batches=allowed_batches,
)
required_keys = {'body', *selected_attachment_keys}
if required_keys and required_keys.issubset(existing_keys):
continue
if not selected_attachment_keys:
raise ConflictError(
'Shipping notice contains no eligible attachments for automatic extraction',
code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE',
details={'intake_nos': [str(intake.intake_no or '')], 'reason': 'no_eligible_selected_attachment'},
)
eml_inputs.append((intake, parent_asset, selected_attachment_keys))
flask_app = current_app._get_current_object()
normal_results: dict[int, NoticeIntakeResult] = {}
if normal_inputs:
worker_count = min(max_concurrency, len(normal_inputs))
with ThreadPoolExecutor(max_workers=worker_count, thread_name_prefix='shipping-file-extract') as pool:
futures = {
int(intake.id): pool.submit(
_build_single_file_result_in_thread,
parent_asset=_asset_read_snapshot(parent_asset),
flask_app=flask_app,
)
for intake, parent_asset in normal_inputs
}
for intake_id, future in futures.items():
normal_results[intake_id] = future.result()
# 所有 Document / Candidate 写入继续在 Worker 主线程按输入顺序收口。
for intake, parent_asset in normal_inputs:
persist_intake_documents(
intake=intake,
parent_asset=parent_asset,
result=normal_results[int(intake.id)],
schema_definition=definition,
)
for intake, parent_asset, selected_attachment_keys in eml_inputs:
persist_intake_documents(
intake=intake,
parent_asset=parent_asset,
result=_build_selected_eml_result(
intake=intake,
parent_asset=parent_asset,
selected_attachment_keys=selected_attachment_keys,
# 每批最多两个附件;后续扩批仍按相同的安全上限执行。
max_concurrency=max_concurrency,
),
schema_definition=definition,
)
@@ -8,6 +8,7 @@ services/shipping_notice/order_extraction_plan.py
from __future__ import annotations
from collections import defaultdict
from datetime import datetime
from typing import Any
@@ -15,6 +16,7 @@ from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import (
ShippingOrderExtractionPlan,
ShippingNoticeDocument,
ShippingOrderExtractionRun,
ShippingOrderExtractionUnit,
)
@@ -22,18 +24,78 @@ from app.models import (
PLAN_VERSION = 'shipping_order_extraction.plan.v1'
UNIT_TRANSITIONS = {
'pending': {'running', 'skipped'},
'running': {'succeeded', 'failed', 'skipped'},
'pending': {'routing', 'matching_profile', 'cancelled'},
'routing': {'matching_profile', 'review_required', 'failed', 'cancelled'},
'matching_profile': {'extracting', 'review_required', 'failed', 'cancelled'},
'extracting': {'merging_supplement', 'candidate_ready', 'review_required', 'failed', 'cancelled'},
'merging_supplement': {'candidate_ready', 'review_required', 'failed', 'cancelled'},
'failed': {'pending'},
'succeeded': set(),
'skipped': set(),
'candidate_ready': set(),
'review_required': set(),
'cancelled': set(),
}
def _selection_snapshot(run: ShippingOrderExtractionRun) -> dict[str, Any]:
"""提取 Run 冻结的附件选择快照,供首轮与扩批复用。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
return snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {}
def _selection_items(selection_snapshot: dict[str, Any]) -> list[dict[str, Any]]:
"""返回可用的选择计划明细行。"""
items = selection_snapshot.get('items') if isinstance(selection_snapshot.get('items'), list) else []
return [item for item in items if isinstance(item, dict)]
def _selection_row_batch(row: dict[str, Any]) -> int | None:
"""统一读取首轮已选批次或后续计划批次。"""
batch = int(row.get('selection_batch') or row.get('planned_selection_batch') or 0)
return batch if batch > 0 else None
def _selection_batch_counts(selection_snapshot: dict[str, Any]) -> dict[int, int]:
"""统计每个批次计划中的附件数量,供预算事实落入 unit。"""
counts: dict[int, int] = defaultdict(int)
for row in _selection_items(selection_snapshot):
batch = _selection_row_batch(row)
if batch is not None:
counts[batch] += 1
return counts
def _unit_budget_cost(
*,
selection_snapshot: dict[str, Any],
selection_batch: int | None,
batch_counts: dict[int, int],
) -> dict[str, Any] | None:
"""构造单元级预算摘要,保持首轮与扩展批次口径一致。"""
if selection_batch is None:
return None
return {
'initial_attachment_budget': int(selection_snapshot.get('max_initial_attachments') or 0),
'initial_concurrency_budget': int(selection_snapshot.get('max_initial_concurrency') or 0),
'expansion_batch_size': int(selection_snapshot.get('expansion_batch_size') or 0),
'max_total_attachments': int(selection_snapshot.get('max_total_attachments') or 0),
'selected_in_batch': int(batch_counts.get(selection_batch, 0) or 0),
}
def _snapshot_documents(run: ShippingOrderExtractionRun) -> list[dict[str, Any]]:
"""按冻结 Intake/Document 顺序展开计划输入,并校验必要引用完整。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else []
selection_snapshot = _selection_snapshot(run)
selection_items = _selection_items(selection_snapshot)
selection_by_key: dict[tuple[str, str], dict[str, Any]] = {}
selected_count_by_batch = _selection_batch_counts(selection_snapshot)
for row in selection_items:
intake_no = str(row.get('intake_no') or '').strip().upper()
attachment_key = str(row.get('attachment_key') or '').strip()
if not intake_no or not attachment_key:
continue
selection_by_key[(intake_no, attachment_key)] = row
documents: list[dict[str, Any]] = []
for intake_position, intake in enumerate(intakes):
if not isinstance(intake, dict):
@@ -42,6 +104,7 @@ def _snapshot_documents(run: ShippingOrderExtractionRun) -> list[dict[str, Any]]
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE',
)
intake_id = intake.get('intake_id')
intake_no = str(intake.get('intake_no') or '').strip().upper()
raw_documents = intake.get('documents') if isinstance(intake.get('documents'), list) else []
for document_position, document in enumerate(raw_documents):
if not isinstance(document, dict) or not intake_id or not document.get('document_id'):
@@ -49,13 +112,27 @@ def _snapshot_documents(run: ShippingOrderExtractionRun) -> list[dict[str, Any]]
'Frozen extraction document reference is invalid',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE',
)
selection_row = selection_by_key.get(
(intake_no, str(document.get('attachment_key') or '').strip()),
{},
)
selection_batch = _selection_row_batch(selection_row)
documents.append({
'intake_id': int(intake_id),
'document_id': int(document['document_id']),
'document_type': str(document.get('document_type') or 'attachment'),
'attachment_key': str(document.get('attachment_key') or '').strip() or None,
'content_hash': str(document.get('content_hash') or '') or None,
'intake_position': intake_position,
'document_position': document_position,
'selection_batch': selection_batch,
'selection_reason_codes': list(selection_row.get('score_reasons') or []),
'group_key': str(selection_row.get('group_key') or '').strip() or None,
'budget_cost': _unit_budget_cost(
selection_snapshot=selection_snapshot,
selection_batch=selection_batch,
batch_counts=selected_count_by_batch,
),
})
if not documents:
raise ValidationError(
@@ -65,6 +142,114 @@ def _snapshot_documents(run: ShippingOrderExtractionRun) -> list[dict[str, Any]]
return documents
def _planned_selection_rows(run: ShippingOrderExtractionRun, *, selection_batch: int) -> list[dict[str, Any]]:
"""读取某个未来批次在冻结选择计划中的附件明细。"""
normalized_batch = int(selection_batch or 0)
if normalized_batch <= 1:
return []
rows: list[dict[str, Any]] = []
for row in _selection_items(_selection_snapshot(run)):
if _selection_row_batch(row) != normalized_batch:
continue
intake_no = str(row.get('intake_no') or '').strip().upper()
attachment_key = str(row.get('attachment_key') or '').strip()
if not intake_no or not attachment_key:
continue
rows.append(row)
return rows
def ensure_order_extraction_plan_batch(
run: ShippingOrderExtractionRun,
*,
selection_batch: int,
) -> list[ShippingOrderExtractionUnit]:
"""
幂等追加某个未来批次的附件单元。
AI 触发时机:仅在首轮处理后确认需要扩批,并且该批附件已完成发送阶段物化时调用。
"""
normalized_batch = int(selection_batch or 0)
if normalized_batch <= 1:
return []
plan = ensure_order_extraction_plan(run)
selection_rows = _planned_selection_rows(run, selection_batch=normalized_batch)
if not selection_rows:
return []
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
intake_id_by_no = {
str(item.get('intake_no') or '').strip().upper(): int(item.get('intake_id'))
for item in (snapshot.get('intakes') or [])
if isinstance(item, dict) and item.get('intake_id')
}
existing_document_ids = {int(unit.document_id) for unit in plan.units}
selection_snapshot = _selection_snapshot(run)
batch_counts = _selection_batch_counts(selection_snapshot)
keys_by_intake: dict[int, set[str]] = defaultdict(set)
ordered_pairs: list[tuple[int, str, dict[str, Any]]] = []
for row in selection_rows:
intake_id = intake_id_by_no.get(str(row.get('intake_no') or '').strip().upper())
attachment_key = str(row.get('attachment_key') or '').strip()
if intake_id is None or not attachment_key:
continue
keys_by_intake[intake_id].add(attachment_key)
ordered_pairs.append((intake_id, attachment_key, row))
if not ordered_pairs:
return []
documents = (
ShippingNoticeDocument.query
.filter(ShippingNoticeDocument.intake_id.in_(keys_by_intake.keys()))
.all()
)
document_by_pair = {
(int(document.intake_id), str(document.attachment_key or '').strip()): document
for document in documents
if str(document.attachment_key or '').strip() in keys_by_intake.get(int(document.intake_id), set())
}
next_position = max((int(unit.position) for unit in plan.units), default=-1) + 1
created_units: list[ShippingOrderExtractionUnit] = []
for intake_id, attachment_key, row in ordered_pairs:
document = document_by_pair.get((intake_id, attachment_key))
if document is None:
raise ValidationError(
'Frozen extraction attachment batch is unavailable',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE',
)
if int(document.id) in existing_document_ids:
continue
unit = ShippingOrderExtractionUnit(
plan_id=plan.id,
intake_id=intake_id,
document_id=int(document.id),
position=next_position,
unit_type='document_extraction',
document_type=str(document.document_type or 'attachment'),
content_hash=str(document.content_hash or '') or None,
selection_batch=normalized_batch,
selection_reason_codes_json=list(row.get('score_reasons') or []) or None,
group_key=str(row.get('group_key') or '').strip() or None,
budget_cost_json=_unit_budget_cost(
selection_snapshot=selection_snapshot,
selection_batch=normalized_batch,
batch_counts=batch_counts,
),
retry_status='not_started',
technical_failure_reason_code=None,
status='pending',
)
db.session.add(unit)
created_units.append(unit)
existing_document_ids.add(int(document.id))
next_position += 1
if created_units:
db.session.flush()
plan.unit_count = len(plan.units)
_refresh_plan_status(plan)
return created_units
def ensure_order_extraction_plan(run: ShippingOrderExtractionRun) -> ShippingOrderExtractionPlan:
"""
幂等创建 Run 的文档级抽取计划。
@@ -113,6 +298,12 @@ def ensure_order_extraction_plan(run: ShippingOrderExtractionRun) -> ShippingOrd
unit_type='document_extraction',
document_type=document_type,
content_hash=document['content_hash'],
selection_batch=document.get('selection_batch'),
selection_reason_codes_json=document.get('selection_reason_codes') or None,
group_key=document.get('group_key'),
budget_cost_json=document.get('budget_cost'),
retry_status='not_started',
technical_failure_reason_code=None,
status='pending',
))
db.session.flush()
@@ -124,9 +315,9 @@ def _refresh_plan_status(plan: ShippingOrderExtractionPlan) -> None:
statuses = [str(unit.status) for unit in plan.units]
if not statuses or all(status == 'pending' for status in statuses):
plan.status = 'planned'
elif any(status in {'pending', 'running'} for status in statuses):
elif any(status in {'pending', 'routing', 'matching_profile', 'extracting', 'merging_supplement'} for status in statuses):
plan.status = 'running'
elif all(status in {'succeeded', 'skipped'} for status in statuses):
elif all(status in {'candidate_ready', 'review_required'} for status in statuses):
plan.status = 'completed'
elif all(status == 'failed' for status in statuses):
plan.status = 'failed'
@@ -143,13 +334,13 @@ def transition_order_extraction_unit(
error_message: str | None = None,
) -> ShippingOrderExtractionUnit:
"""
单调推进一个文档单元并同步计划汇总状态。
单调推进一个附件单元并同步计划汇总状态。
Args:
unit: 已加载且由调用方在事务内持有的计划单元。
target_status: 当前状态允许的下一状态;`skipped` 表示业务复核,失败重试必须先回到 pending。
result: 仅 succeeded 可写的结构化局部结果,不得包含正文或凭据。
error_code/error_message: 仅 failed 可写的安全诊断摘要。
target_status: 当前状态允许的下一状态;失败重试必须先回到 pending 再开启新 attempt。
result: 仅 candidate_ready 可写的结构化局部结果,不得包含正文或凭据。
error_code/error_message: review_required/failed/cancelled 可写的稳定原因摘要。
Returns:
已更新但尚未提交的单元。
"""
@@ -164,32 +355,70 @@ def transition_order_extraction_unit(
before_projection = {'status': current, 'attempt_count': int(unit.attempt_count or 0)}
now = datetime.utcnow()
unit.status = target_status
if target_status == 'running':
unit.last_activity_at = now
if target_status in {'routing', 'matching_profile'}:
unit.attempt_count = int(unit.attempt_count or 0) + 1
unit.started_at = now
unit.retry_status = 'retrying' if int(unit.attempt_count or 0) > 1 else 'running'
unit.started_at = unit.started_at or now
unit.finished_at = None
unit.reason_code = None
unit.summary_json = None
unit.result_json = None
unit.error_code = None
unit.error_message = None
elif target_status == 'succeeded':
unit.technical_failure_reason_code = None
elif target_status in {'extracting', 'merging_supplement'}:
unit.finished_at = None
unit.reason_code = None
unit.summary_json = dict(result or unit.summary_json or {})
unit.error_code = None
unit.error_message = None
unit.retry_status = 'running'
unit.technical_failure_reason_code = None
elif target_status == 'candidate_ready':
unit.summary_json = dict(result or {})
unit.result_json = dict(result or {})
unit.reason_code = None
unit.error_code = None
unit.error_message = None
unit.finished_at = now
unit.retry_status = 'succeeded'
unit.technical_failure_reason_code = None
elif target_status == 'review_required':
unit.summary_json = dict(result or {})
unit.result_json = None
unit.reason_code = str(error_code or 'review_required')[:64]
unit.error_code = None
unit.error_message = str(error_message or 'Order extraction requires manual review')[:2000]
unit.finished_at = now
unit.retry_status = 'review_required'
unit.technical_failure_reason_code = None
elif target_status == 'failed':
unit.result_json = None
unit.summary_json = dict(result or {})
unit.reason_code = None
unit.error_code = str(error_code or 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED')[:64]
unit.error_message = str(error_message or 'Order extraction unit failed')[:2000]
unit.finished_at = now
unit.retry_status = 'failed'
unit.technical_failure_reason_code = unit.error_code
elif target_status == 'pending':
unit.finished_at = None
unit.reason_code = None
unit.summary_json = None
unit.error_code = None
unit.error_message = None
elif target_status == 'skipped':
unit.retry_status = 'pending_retry'
unit.technical_failure_reason_code = None
elif target_status == 'cancelled':
unit.result_json = None
unit.error_code = str(error_code or 'SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED')[:64]
unit.error_message = str(error_message or 'Order extraction requires review')[:2000]
unit.summary_json = dict(result or {})
unit.reason_code = str(error_code or 'cancelled')[:64]
unit.error_code = None
unit.error_message = str(error_message or 'Order extraction unit was cancelled')[:2000]
unit.finished_at = now
unit.retry_status = 'cancelled'
unit.technical_failure_reason_code = None
plan_run = getattr(unit.plan, 'run', None)
if plan_run is not None and getattr(plan_run, 'run_no', None):
append_shipping_audit_event(
@@ -198,7 +427,7 @@ def transition_order_extraction_unit(
aggregate_id=str(unit.id),
run_no=str(plan_run.run_no),
actor_type='system',
reason_code=unit.error_code if target_status in {'failed', 'skipped'} else None,
reason_code=unit.reason_code if target_status in {'review_required', 'cancelled'} else unit.error_code if target_status == 'failed' else None,
before=before_projection,
after={'status': target_status, 'attempt_count': int(unit.attempt_count or 0)},
metadata={'target_status': target_status},
@@ -1,9 +1,9 @@
"""
services/shipping_notice/order_extraction_progress.py
用途:把已脱敏的 Workflow 生命周期事件持久化为订单抽取 Run 的当前进度与诊断时间线。
依赖:Dify 事件观察器、ShippingOrderExtractionRun、独立 SQLAlchemy Session。
逻辑:订单 Worker 的长事务只负责业务事实;本模块使用短事务去重并更新可恢复投影,任何记录失败均不影响主链路。
用途:记录订单抽取 Run/Unit 的确定性业务事件,作为用户态进度与管理员诊断的共同事实源。
依赖:ShippingOrderExtractionRun/Unit/ProgressEvent ORM、统一数据库会话。
逻辑:调用方只能写入受控 event_code;服务负责幂等、顺序号、终态保护和最小化 Run 投影。
"""
from __future__ import annotations
@@ -14,189 +14,255 @@ import logging
from datetime import datetime, timedelta
from typing import Any
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from sqlalchemy import func
from app import db
from app.models import ShippingOrderExtractionProgressEvent, ShippingOrderExtractionRun
from app.models import (
ShippingOrderExtractionProgressEvent,
ShippingOrderExtractionRun,
ShippingOrderExtractionUnit,
)
_LOGGER = logging.getLogger(__name__)
# 数据库列限制为 VARCHAR(32),映射版本必须保持在该上限内。
MAPPING_VERSION = 'shipping-order-extract-node-v1'
MAPPING_VERSION = 'shipping-order-progress-v2'
EVENT_RETENTION_DAYS = 90
TERMINAL_RUN_STATUSES = {'completed', 'needs_review', 'failed', 'cancelled'}
_STAGE_PRIORITY = {
'auto_recovering': 90,
'hxops_persistence': 80,
'provider_result_ready': 70,
'result_processing': 60,
'order_recognition': 50,
'document_processing': 40,
'generic_processing': 30,
'workflow_accepted': 20,
'queued': 10,
EVENT_CODE_ORDER = {
'plan_created': 5,
'initial_wave_started': 8,
'expansion_wave_started': 9,
'document_queued': 10,
'profile_matching': 20,
'profile_matched': 30,
'table_reconstructed': 40,
'order_fields_extracted': 50,
'email_supplement_merged': 60,
'technical_retrying': 65,
'candidate_ready': 70,
'review_required': 70,
'technical_failed': 70,
'budget_stopped': 80,
'run_completed': 90,
}
WORKSPACE_EVENT_CODES = {
'plan_created',
'initial_wave_started',
'expansion_wave_started',
'document_queued',
'profile_matching',
'profile_matched',
'table_reconstructed',
'order_fields_extracted',
'email_supplement_merged',
'candidate_ready',
'review_required',
'technical_retrying',
'technical_failed',
'budget_stopped',
'run_completed',
}
VISIBILITIES = {'workspace', 'admin'}
TERMINAL_RUN_STATUSES = {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'}
def _safe_text(value: Any, limit: int) -> str | None:
"""压缩外部事件标识;调用方只允许传入无业务正文的技术枚举或编号。"""
"""压缩受控标识文本,防止异常正文或路径被误写入事件表。"""
text = ' '.join(str(value or '').replace('\x00', '').split()).strip()
return text[:limit] if text else None
def _event_key(event: dict[str, Any]) -> str:
"""为缺少节点执行编号的 Dify 版本生成稳定、无业务正文的去重键。"""
def _safe_summary(summary: Any) -> dict[str, Any] | None:
"""仅接受可 JSON 序列化的结构化摘要;失败时回退为空。"""
if not isinstance(summary, dict):
return None
try:
return json.loads(json.dumps(summary, ensure_ascii=True, sort_keys=True, default=str))
except (TypeError, ValueError):
return None
def _event_key(*, run_id: int, unit_id: int | None, document_id: int | None, event_code: str, status: str, visibility: str, reason_code: str | None, attempt_count: int | None, summary: dict[str, Any] | None) -> str:
"""生成稳定事件幂等键,重复执行或重放不会插入重复用户事件。"""
payload = {
'workflow_run_id': _safe_text(event.get('workflow_run_id'), 128),
'node_execution_id': _safe_text(event.get('node_execution_id'), 128),
'event_type': _safe_text(event.get('event_type'), 64),
'node_type': _safe_text(event.get('node_type'), 64),
'event_status': _safe_text(event.get('event_status'), 32),
'job_id': event.get('job_id') if isinstance(event.get('job_id'), int) else None,
'attempt_count': event.get('attempt_count') if isinstance(event.get('attempt_count'), int) else None,
'provider_occurred_at': _safe_text(event.get('provider_occurred_at'), 64),
'run_id': int(run_id),
'unit_id': int(unit_id) if unit_id is not None else None,
'document_id': int(document_id) if document_id is not None else None,
'event_code': event_code,
'status': status,
'visibility': visibility,
'reason_code': reason_code,
'attempt_count': int(attempt_count) if attempt_count is not None else None,
'summary': summary or None,
}
return hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=True).encode('ascii')).hexdigest()
def _stage_for_event(event: dict[str, Any]) -> str | None:
"""按节点技术类型映射通用阶段;禁止从节点标题或输出猜测业务含义。"""
event_type = str(event.get('event_type') or '').lower()
if event_type == 'workflow_started':
return 'workflow_accepted'
if event_type == 'hxops_persistence_started':
return 'hxops_persistence'
if event_type in {'poll_started', 'retry_started', 'stream_interrupted'}:
return 'auto_recovering'
if event_type == 'workflow_finished' and str(event.get('event_status') or '').lower() in {'succeeded', 'success'}:
return 'provider_result_ready'
node_type = str(event.get('node_type') or '').lower().replace('_', '-').replace(' ', '-')
if not node_type:
return None
if any(token in node_type for token in ('document', 'file-extractor', 'text-extractor')):
return 'document_processing'
if node_type in {'llm', 'agent'} or 'llm' in node_type:
return 'order_recognition'
if any(token in node_type for token in ('code', 'template', 'parameter', 'json')):
return 'result_processing'
return 'generic_processing'
def _next_sequence_no(run_id: int) -> int:
"""按 Run 内稳定自增序号排序,前端无需猜测事件时序。"""
current = db.session.query(func.max(ShippingOrderExtractionProgressEvent.sequence_no)).filter_by(run_id=run_id).scalar()
return int(current or 0) + 1
def _main_stage(active: set[str], completed: set[str], previous: str | None) -> str:
"""并行阶段按优先级归并;除自动恢复结束外,用户主阶段不得向低优先级回退。"""
if previous == 'hxops_persistence':
return previous
candidates = active or completed or {'queued'}
candidate = max(candidates, key=lambda item: _STAGE_PRIORITY.get(item, 0))
if previous and previous != 'auto_recovering':
return max((previous, candidate), key=lambda item: _STAGE_PRIORITY.get(item, 0))
return candidate
def _should_update_projection(run: ShippingOrderExtractionRun, event_code: str) -> bool:
"""迟到事件不能把 Run 当前活动从更后阶段回退。"""
current = str(run.current_stage_code or '').strip()
if not current:
return True
return EVENT_CODE_ORDER.get(event_code, 0) >= EVENT_CODE_ORDER.get(current, 0)
def _apply_projection(run: ShippingOrderExtractionRun, event: dict[str, Any], stage: str | None, now: datetime) -> None:
"""更新用户可见投影;终态 Run 仍保留明细,但不再被Dify事件改回运行态。"""
event_type = str(event.get('event_type') or '').lower()
def _apply_run_projection(run: ShippingOrderExtractionRun, *, event_code: str, occurred_at: datetime) -> None:
"""维持最小 Run 投影,供阶段一验证恢复性与轮询版本控制。"""
if run.status in TERMINAL_RUN_STATUSES:
return
active = {str(item) for item in (run.active_stage_codes_json or []) if str(item)}
if _should_update_projection(run, event_code):
run.current_stage_code = event_code
run.active_stage_codes_json = [] if event_code in {
'candidate_ready', 'review_required', 'technical_failed', 'budget_stopped', 'run_completed',
} else [event_code]
completed = {str(item) for item in (run.completed_stage_codes_json or []) if str(item)}
if event_type == 'node_started' and stage:
# Workflow 已被真实节点接管后,连接成功只作为已完成里程碑保留。
if 'workflow_accepted' in active:
active.discard('workflow_accepted')
completed.add('workflow_accepted')
active.add(stage)
elif event_type == 'node_finished' and stage:
active.discard(stage)
completed.add(stage)
elif event_type == 'workflow_started' and stage:
active.add(stage)
elif event_type == 'workflow_finished' and stage:
active.clear()
completed.add(stage)
elif event_type == 'hxops_persistence_started' and stage:
active.clear()
active.add(stage)
elif event_type in {'poll_started', 'retry_started', 'stream_interrupted'} and stage:
active.add(stage)
elif event_type == 'recovered':
active.discard('auto_recovering')
run.active_stage_codes_json = sorted(active)
if event_code in WORKSPACE_EVENT_CODES:
completed.add(event_code)
run.completed_stage_codes_json = sorted(completed)
run.current_stage_code = _main_stage(active, completed, run.current_stage_code)
run.progress_message_code = f'shipping.order_extraction.{run.current_stage_code}'
run.progress_message_code = f'shipping.order_extraction.events.{event_code}'
run.progress_mapping_version = MAPPING_VERSION
run.last_activity_at = now
run.last_activity_at = occurred_at
run.progress_version = int(run.progress_version or 0) + 1
def record_order_extraction_progress_event(*, run_no: str, event: dict[str, Any]) -> bool:
def record_order_extraction_progress_event(
*,
run_no: str,
event: dict[str, Any],
commit: bool = True,
) -> bool:
"""
使用独立短事务写入一个脱敏进度事件与 Run 投影。
写入一个确定性订单抽取事件。
AI 触发时机:无;仅由订单抽取 Worker 的 Dify 观察器或 HXOPS 持久化边界调用。
AI 触发时机:无需直接调用;仅供 Worker、Run service 或测试写入已发生的业务事实。
Args:
run_no: 订单抽取 Run 编号。
event: 已标准化的安全事件,禁止包含节点输入、输出、Prompt、正文或异常堆栈。
event: 受控事件对象,必须包含 event_code;禁止传入堆栈、路径、原文与 Workflow 节点数据。
commit: 是否在函数内提交事务;Worker 可传 False 后与状态机同事务提交。
Returns:
是否新增了事件;重复事件或未知 Run 返回 False。
新事件是否真正写入。
"""
normalized_no = str(run_no or '').strip()
if not normalized_no:
event_code = _safe_text((event or {}).get('event_code'), 64)
if not normalized_no or not event_code or event_code not in WORKSPACE_EVENT_CODES:
return False
now = datetime.utcnow()
stage = _stage_for_event(event)
key = _event_key(event)
visibility = _safe_text(event.get('visibility'), 32) or 'workspace'
if visibility not in VISIBILITIES:
return False
status = _safe_text(event.get('status'), 32) or 'completed'
occurred_at = event.get('occurred_at') if isinstance(event.get('occurred_at'), datetime) else datetime.utcnow()
summary = _safe_summary(event.get('summary'))
reason_code = _safe_text(event.get('reason_code'), 64)
try:
with Session(bind=db.engine) as session:
run = session.execute(
select(ShippingOrderExtractionRun)
.where(ShippingOrderExtractionRun.run_no == normalized_no)
.with_for_update(),
).scalar_one_or_none()
if run is None:
return False
row = ShippingOrderExtractionProgressEvent(
run_id=run.id,
job_id=event.get('job_id') if isinstance(event.get('job_id'), int) else None,
attempt_count=event.get('attempt_count') if isinstance(event.get('attempt_count'), int) else None,
workflow_run_id=_safe_text(event.get('workflow_run_id'), 128),
node_execution_id=_safe_text(event.get('node_execution_id'), 128),
event_type=_safe_text(event.get('event_type'), 64) or 'unknown',
node_type=_safe_text(event.get('node_type'), 64),
stage_code=stage,
event_status=_safe_text(event.get('event_status'), 32),
received_at=now,
details_json={'source': 'dify_workflow_observer'},
idempotency_key=key,
mapping_version=MAPPING_VERSION,
expires_at=now + timedelta(days=EVENT_RETENTION_DAYS),
)
session.add(row)
try:
session.flush()
except IntegrityError:
session.rollback()
return False
_apply_projection(run, event, stage, now)
session.commit()
return True
run = ShippingOrderExtractionRun.query.filter_by(run_no=normalized_no).with_for_update().first()
if run is None:
return False
if run.status in TERMINAL_RUN_STATUSES and event_code not in {'run_completed', 'technical_failed'}:
return False
unit_id = int(event['unit_id']) if event.get('unit_id') is not None else None
document_id = int(event['document_id']) if event.get('document_id') is not None else None
attempt_count = int(event['attempt_count']) if event.get('attempt_count') is not None else None
key = _event_key(
run_id=int(run.id),
unit_id=unit_id,
document_id=document_id,
event_code=event_code,
status=status,
visibility=visibility,
reason_code=reason_code,
attempt_count=attempt_count,
summary=summary,
)
if ShippingOrderExtractionProgressEvent.query.filter_by(idempotency_key=key).first() is not None:
return False
row = ShippingOrderExtractionProgressEvent(
run_id=run.id,
unit_id=unit_id,
document_id=document_id,
job_id=int(event['job_id']) if event.get('job_id') is not None else None,
attempt_count=attempt_count,
sequence_no=_next_sequence_no(int(run.id)),
visibility=visibility,
event_code=event_code,
status=status,
occurred_at=occurred_at,
reason_code=reason_code,
received_at=datetime.utcnow(),
summary_json=summary,
idempotency_key=key,
mapping_version=MAPPING_VERSION,
expires_at=occurred_at + timedelta(days=EVENT_RETENTION_DAYS),
)
db.session.add(row)
_apply_run_projection(run, event_code=event_code, occurred_at=occurred_at)
if commit:
db.session.commit()
else:
db.session.flush()
return True
except Exception:
_LOGGER.exception('order extraction progress recording failed run_no=%s event_type=%s', normalized_no, event.get('event_type'))
if commit:
db.session.rollback()
_LOGGER.exception('order extraction progress recording failed run_no=%s event_code=%s', normalized_no, event_code)
return False
def record_order_extraction_persistence_started(*, run_no: str, job_id: int, attempt_count: int) -> bool:
"""在HXOPS开始落库前写入不可被Dify迟到事件覆盖的持久化阶段。"""
def record_unit_progress(
*,
run: ShippingOrderExtractionRun,
unit: ShippingOrderExtractionUnit,
event_code: str,
summary: dict[str, Any] | None = None,
reason_code: str | None = None,
visibility: str = 'workspace',
job_id: int | None = None,
commit: bool = False,
) -> bool:
"""以 Run/Unit 实体写入业务事件,供 Worker 在状态推进时复用。"""
return record_order_extraction_progress_event(
run_no=run_no,
run_no=str(run.run_no),
commit=commit,
event={
'event_type': 'hxops_persistence_started',
'event_status': 'running',
'job_id': job_id,
'attempt_count': attempt_count,
'node_type': 'hxops_persistence',
'unit_id': int(unit.id),
'document_id': int(unit.document_id),
'event_code': event_code,
'status': 'completed',
'summary': summary,
'reason_code': reason_code,
'visibility': visibility,
'job_id': int(job_id) if job_id is not None else None,
'attempt_count': int(unit.attempt_count or 0),
'occurred_at': datetime.utcnow(),
},
)
def record_run_progress(
*,
run: ShippingOrderExtractionRun,
event_code: str,
summary: dict[str, Any] | None = None,
reason_code: str | None = None,
visibility: str = 'workspace',
job_id: int | None = None,
commit: bool = False,
) -> bool:
"""记录 Run 级事件,如 run_completed。"""
return record_order_extraction_progress_event(
run_no=str(run.run_no),
commit=commit,
event={
'event_code': event_code,
'status': 'completed',
'summary': summary,
'reason_code': reason_code,
'visibility': visibility,
'job_id': int(job_id) if job_id is not None else None,
'attempt_count': int(run.attempt_count or 0),
'occurred_at': datetime.utcnow(),
},
)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,81 @@
"""
services/shipping_notice/order_extraction_runtime_snapshot.py
用途:为订单抽取 Worker 提供“冻结正文 + 当前可用布局”的运行时快照兜底。
依赖:Run 冻结 snapshot、ShippingNoticeDocument、document_layout.lifecycle、schema_mapping。
逻辑:创建 Run 时不再等待布局终态,所以 Worker 执行单元时允许补读当前 ready layout;
但正文、邮件上下文和其余输入仍严格来自 Run 冻结快照,避免退回到上传阶段的可变全量解析。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.core.errors import ValidationError
from app.models import ShippingNoticeDocument
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
from app.services.shipping_notice.document_layout.schema_mapping import map_layout_document_to_schema
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
def _ready_layout(document: dict[str, Any]) -> dict[str, Any] | None:
"""读取文档快照中的 ready layout;非 ready 一律视为缺失。"""
layout = document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {}
return layout if layout.get('status') == 'ready' else None
def _runtime_layout_schema_candidates(*, run: Any, layout_snapshot: dict[str, Any]) -> list[dict[str, Any]]:
"""基于当前 ready layout 重新计算冻结 Schema 的候选映射。"""
schema_snapshot = run.input_snapshot_json.get('schema') if isinstance(run.input_snapshot_json, dict) else {}
definition = schema_snapshot.get('definition') if isinstance(schema_snapshot.get('definition'), dict) else {}
contract = compile_table_header_contract(definition)
layout_candidate = (
layout_snapshot.get('layout_candidate')
if isinstance(layout_snapshot.get('layout_candidate'), dict)
else None
)
if layout_candidate is None:
return []
try:
return map_layout_document_to_schema(layout_candidate, contract=contract)
except (TypeError, ValueError):
return [{
'mapping_status': 'failed',
'issues': ['layout_schema_mapping_invalid'],
}]
def resolve_unit_runtime_snapshot(run: Any, unit: Any) -> tuple[dict[str, Any], dict[str, Any]]:
"""
定位 Unit 对应的 Intake/Document,并在缺少 ready layout 时补读当前布局版本。
AI 触发时机:无需调用。Worker 进入单元执行前由 `order_extraction_workflow` 内部调用。
关键约束:只补读布局快照与其 Schema 映射;正文、邮件上下文、附件边界仍来自 Run 冻结 snapshot。
"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
for intake in snapshot.get('intakes') or []:
if not isinstance(intake, dict) or int(intake.get('intake_id') or 0) != int(unit.intake_id):
continue
for raw_document in intake.get('documents') or []:
if not isinstance(raw_document, dict) or int(raw_document.get('document_id') or 0) != int(unit.document_id):
continue
document = dict(raw_document)
if _ready_layout(document) is not None:
return intake, document
persisted_document = db.session.get(ShippingNoticeDocument, int(unit.document_id))
if persisted_document is None:
return intake, document
runtime_layout = current_layout_snapshot(persisted_document)
if not isinstance(runtime_layout, dict) or runtime_layout.get('status') != 'ready':
return intake, document
document['layout_snapshot'] = runtime_layout
document['layout_schema_candidates'] = _runtime_layout_schema_candidates(
run=run,
layout_snapshot=runtime_layout,
)
return intake, document
raise ValidationError(
'Extraction unit is absent from the frozen run snapshot',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE',
)
@@ -0,0 +1,67 @@
"""
services/shipping_notice/order_extraction_snapshot_selection.py
用途:把发送阶段的附件选择计划映射为 Run 冻结快照中的文档范围。
依赖:仅依赖选择计划 JSON 和文档基础字段,不触碰 ORM、布局或 Provider 结果。
逻辑:阶段 2 发送后,Run 只应冻结当前计划选中的附件文档;邮件正文补充事实保留,
其余未选附件不得偷偷混入 snapshot/plan,避免“本批发送”误扩大成整封邮件全量执行。
"""
from __future__ import annotations
from typing import Any
def selected_attachment_keys_by_intake(
selection_snapshot: dict[str, Any] | None,
) -> dict[str, set[str]]:
"""把脱敏选择计划压缩为 intake_no -> attachment_key 集合。"""
snapshot = selection_snapshot if isinstance(selection_snapshot, dict) else {}
rows = snapshot.get('items') if isinstance(snapshot.get('items'), list) else []
selected: dict[str, set[str]] = {}
for row in rows:
if not isinstance(row, dict) or not row.get('selected'):
continue
intake_no = str(row.get('intake_no') or '').strip().upper()
attachment_key = str(row.get('attachment_key') or '').strip()
if not intake_no or not attachment_key:
continue
selected.setdefault(intake_no, set()).add(attachment_key)
return selected
def has_attachment_catalog(selection_snapshot: dict[str, Any] | None) -> bool:
"""是否存在 EML 附件目录;普通单文件场景不应用目录选择规则。"""
snapshot = selection_snapshot if isinstance(selection_snapshot, dict) else {}
return int(snapshot.get('total_attachment_count') or 0) > 0
def has_selected_attachments(selection_snapshot: dict[str, Any] | None) -> bool:
"""发送计划里是否至少选中一个附件。"""
snapshot = selection_snapshot if isinstance(selection_snapshot, dict) else {}
return int(snapshot.get('selected_attachment_count') or 0) > 0
def should_include_snapshot_document(
*,
selection_snapshot: dict[str, Any] | None,
intake_no: str,
document_type: str,
attachment_key: str | None,
) -> bool:
"""
判定某个冻结 Document 是否应进入 Run snapshot。
核心逻辑:
1. 邮件正文永远保留,供补充事实合并使用;
2. 普通单文件没有附件目录时,仍保留全部附件 Document;
3. EML 场景只保留本次选择计划选中的附件,未选附件不能进入执行快照。
"""
if str(document_type or '') == 'email_body':
return True
if not has_attachment_catalog(selection_snapshot):
return True
selected = selected_attachment_keys_by_intake(selection_snapshot)
normalized_intake = str(intake_no or '').strip().upper()
normalized_key = str(attachment_key or '').strip()
return bool(normalized_intake and normalized_key and normalized_key in selected.get(normalized_intake, set()))
@@ -13,6 +13,9 @@ from dataclasses import dataclass
from typing import Any, Literal
from app.core.errors import ValidationError
from app.services.shipping_notice.order_extraction_runtime_snapshot import (
resolve_unit_runtime_snapshot,
)
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
from app.services.shipping_notice.document_layout.order_profile import (
OrderDocumentProfile,
@@ -42,18 +45,8 @@ class DeterministicRouteResult:
def _unit_snapshot(run: Any, unit: Any) -> tuple[dict[str, Any], dict[str, Any]]:
"""从 Run 冻结快照定位一个单元的 Intake 与 Document,禁止回读可变正文。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
for intake in snapshot.get('intakes') or []:
if not isinstance(intake, dict) or int(intake.get('intake_id') or 0) != int(unit.intake_id):
continue
for document in intake.get('documents') or []:
if isinstance(document, dict) and int(document.get('document_id') or 0) == int(unit.document_id):
return intake, document
raise ValidationError(
'Extraction unit is absent from the frozen run snapshot',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE',
)
"""从 Run 快照定位单元,并在必要时补读当前 ready layout。"""
return resolve_unit_runtime_snapshot(run, unit)
def build_order_extraction_execution_snapshot(run: Any, *, unit: Any) -> dict[str, str]:
@@ -332,9 +325,12 @@ def _coordinate_v2_profile_rows(
profile = _frozen_coordinate_profile(raw_profile)
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
characters = tables.get(str(raw_table.get('table_id') or ''))
page_size = pages.get(str(raw_table.get('page_no') or ''))
page_no = int(raw_table.get('page_no') or 1)
# 整页坐标是 v2 区域的权威证据;检测表格漏掉续页时仍可读取该页模板区域。
characters = page_glyphs.get(str(page_no)) or tables.get(str(raw_table.get('table_id') or ''))
page_size = pages.get(str(page_no))
if not isinstance(characters, list) or not isinstance(page_size, dict):
return None
try:
@@ -347,7 +343,6 @@ def _coordinate_v2_profile_rows(
return None
rows: list[dict[str, Any]] = []
for region in profile.table_regions:
page_no = int(raw_table.get('page_no') or 1)
if region.page_scope == 'first_page' and page_no != 1:
continue
if region.page_scope == 'continuation_pages' and page_no <= 1:
@@ -510,7 +505,16 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
issues: list[str] = []
matched_any = False
cross_page_carries: dict[tuple[str, str], dict[str, Any]] = {}
for raw_table in sorted((item for item in layout.get('tables') or [] if isinstance(item, dict)), key=lambda item: (int(item.get('page_no') or 1), str(item.get('table_id') or ''))):
raw_tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
# 坐标模板按页执行,避免“模板两页、检测器只识别一张表”时续页被静默遗漏。
if v2_profiles:
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
raw_tables = [
{'table_id': f'page-{page_no}', 'page_no': int(page_no)}
for page_no in sorted(pages, key=lambda value: int(value))
]
for raw_table in sorted(raw_tables, key=lambda item: (int(item.get('page_no') or 1), str(item.get('table_id') or ''))):
if not isinstance(raw_table, dict):
continue
table_id = str(raw_table.get('table_id') or '')
@@ -928,45 +932,77 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
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]
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
approved_tables = [
item for item in tables
if bool(item.get('auto_create_approved'))
]
# 文档出现多个模板表时不猜测其业务关系,即使其中一个模板已批准也必须人工复核。
if not tables:
decision['fallback_reason_codes'] = ['no_layout_table']
decision['fallback_reason_codes'] = ['business_table_not_found']
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
if len(tables) != 1:
decision['fallback_reason_codes'] = ['multiple_tables_detected']
decision['fallback_reason_codes'] = ['multiple_business_tables']
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
if len(approved_tables) != 1:
decision['fallback_reason_codes'] = ['profile_not_auto_create_approved']
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
selected = approved_tables[0]
selected = tables[0]
decision.update({
'selected_profile_code': selected.get('profile_code'),
'selected_profile_id': selected.get('profile_id'),
'selected_profile_version': selected.get('profile_version'),
'selected_profile_checksum': selected.get('profile_checksum'),
'auto_create_approved': True,
'auto_create_approved': bool(selected.get('auto_create_approved')),
'business_table_count': 1,
'matched_table_count': 1,
})
confirmed_order_fields = _confirmed_profile_order_fields(run, unit=unit)
orders, reason_code = _build_approved_profile_order_result(
unit=unit, intake=intake, schema=schema, definition=definition, table=approved_tables[0],
unit=unit, intake=intake, schema=schema, definition=definition, table=selected,
confirmed_order_fields=confirmed_order_fields,
)
if orders is None and reason_code in {'row_needs_review', 'required_field_missing'}:
# Keep the matched table as an editable candidate. Missing fields are then
# visible to the reviewer instead of discarding the entire PDF result.
orders, review_reason = _build_approved_profile_order_result(
unit=unit, intake=intake, schema=schema, definition=definition, table=selected,
confirmed_order_fields=confirmed_order_fields, allow_manual_review=True,
)
if orders is not None:
decision['fallback_reason_codes'] = [reason_code]
decision['parsed_table_count'] = 1
return DeterministicRouteResult(execution_mode='deterministic', orders=orders, decision=decision)
reason_code = review_reason or reason_code
if orders is None:
decision['fallback_reason_codes'] = [reason_code or 'no_parsed_lines']
if reason_code == 'row_needs_review':
decision['review_details'] = _profile_row_review_details(selected)
decision['fallback_reason_codes'] = [reason_code or 'business_table_not_found']
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
decision['parsed_table_count'] = 1
decision['business_table_count'] = 1
decision['matched_table_count'] = 1
decision['document_table_count'] = len(tables)
if not bool(selected.get('auto_create_approved')):
# 模板匹配仍可提供给人工编辑,但永远不带自动接受标记或自动建单资格。
for order in orders:
if isinstance(order, dict):
order.pop('_hxops_acceptance', None)
decision['fallback_reason_codes'] = ['profile_auto_create_not_approved']
return DeterministicRouteResult(execution_mode='deterministic', orders=orders, decision=decision)
def _profile_row_review_details(table: dict[str, Any]) -> list[dict[str, Any]]:
"""将本次模板行校验问题压缩为可展示、可定位的人工复核清单。"""
details: list[dict[str, Any]] = []
for row_index, row in enumerate(table.get('rows') or [], 1):
if not isinstance(row, dict) or row.get('status') == 'parsed':
continue
for issue in row.get('issues') or []:
code = str(issue or '').strip()
if code.startswith('order_profile_field_invalid:'):
details.append({
'line_number': row_index,
'field_code': code.rsplit(':', 1)[-1],
'reason_code': 'invalid_value',
})
else:
details.append({'line_number': row_index, 'field_code': None, 'reason_code': 'needs_review'})
return details
def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, Any]] | None:
"""兼容旧调用方:仅在结构化路由允许确定性解析时返回订单数组。"""
result = route_deterministic_unit(run, unit=unit)
@@ -976,14 +1012,14 @@ def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, An
def _route_reason_for_issue(issue: str) -> str:
"""把内部解析问题收敛为管理员可长期依赖的稳定路由原因码。"""
mapping = {
'order_profile_evidence_insufficient': 'profile_evidence_insufficient',
'order_profile_no_match': 'profile_no_match',
'order_profile_evidence_insufficient': 'required_anchor_missing',
'order_profile_no_match': 'profile_not_found',
'order_profile_ambiguous': 'profile_ambiguous',
'order_profile_layout_drift': 'profile_layout_drift',
'order_profile_snapshot_field_mismatch': 'profile_schema_field_mismatch',
'order_profile_layout_drift': 'profile_drift_detected',
'order_profile_snapshot_field_mismatch': 'required_field_missing',
'order_profile_multiple_matches': 'profile_ambiguous',
}
return mapping.get(issue, 'profile_layout_drift')
return mapping.get(issue, 'profile_drift_detected')
def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfileV2:
@@ -999,6 +1035,7 @@ def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfileV2:
def _build_approved_profile_order_result(
*, unit: Any, intake: dict[str, Any], schema: dict[str, Any], definition: dict[str, Any],
table: dict[str, Any], confirmed_order_fields: list[dict[str, Any]] | None = None,
allow_manual_review: bool = False,
) -> tuple[list[dict[str, Any]] | None, str | None]:
"""
把已批准 Profile 本次实际解析的唯一完整表格转换为零 Provider 订单。
@@ -1026,12 +1063,15 @@ def _build_approved_profile_order_result(
}
line_groups: list[dict[str, Any]] = []
header_values: dict[str, list[dict[str, Any]]] = {}
has_review_rows = False
for row in table.get('rows') or []:
# Profile parser 已判定 deleted/invalid 行不可进入订单;禁止把部分解析结果当作完整订单。
if not isinstance(row, dict) or row.get('status') == 'deleted':
continue
if row.get('status') != 'parsed' or row.get('issues'):
return None, 'row_needs_review'
if not allow_manual_review:
return None, 'row_needs_review'
has_review_rows = True
line_fields: list[dict[str, Any]] = []
for raw in row.get('fields') or []:
if not isinstance(raw, dict):
@@ -1058,8 +1098,8 @@ def _build_approved_profile_order_result(
if len(unique) != 1:
# Multiple document-level PO values cannot be attributed to individual lines.
if field_id in po_field_ids:
return None, 'multiple_business_tables_ambiguous'
return None, 'header_value_conflict'
return None, 'multiple_po_detected'
return None, 'required_field_missing'
header_fields.append({'field_id': field_id, 'observations': [observations[0]]})
present_header = {item['field_id'] for item in header_fields}
for candidate in confirmed_order_fields or []:
@@ -1068,7 +1108,7 @@ def _build_approved_profile_order_result(
continue
if field_id in present_header:
# Header table evidence and independent order-field evidence must never silently compete.
return None, 'header_value_conflict'
return None, 'required_field_missing'
header_fields.append({'field_id': field_id, '_hxops_order_field_evidence': True, 'observations': [{
'value': candidate.get('value'), 'document_id': int(unit.document_id),
'quote': str(candidate.get('value') or '')[:1000], 'confidence': 1.0,
@@ -1082,17 +1122,21 @@ def _build_approved_profile_order_result(
}]})
present_header.add(field_id)
if not line_groups:
return None, 'no_parsed_lines'
return None, 'business_table_not_found'
for config in fields:
if not config.get('required'):
continue
field_id = str(config.get('field_id') or '')
if allow_manual_review:
continue
if config.get('scope') == 'header' and field_id not in present_header and field_id not in po_field_ids:
return None, 'required_header_missing'
if field_id in po_field_ids:
return None, 'po_missing'
return None, 'required_field_missing'
if config.get('scope') == 'line' and any(
field_id not in {item['field_id'] for item in group['fields']} for group in line_groups
):
return None, 'required_line_field_missing'
return None, 'required_field_missing'
base_order = {
'schema_version_id': schema.get('schema_version_id'), 'schema_checksum': schema.get('checksum'),
'classification': 'shipping_request', 'classification_confidence': 1.0,
@@ -1100,9 +1144,11 @@ def _build_approved_profile_order_result(
'primary_document_id': int(unit.document_id),
'header_fields': header_fields, 'lines': line_groups, 'conflicts': [],
# Only this frozen approved-profile builder may add this internal marker.
'_hxops_acceptance': 'approved_deterministic_profile_v1',
}
# A PDF can yield multiple Tasks only when every parsed line carries one explicit PO.
if not has_review_rows:
# Only this frozen approved-profile builder may add this internal marker.
base_order['_hxops_acceptance'] = 'approved_deterministic_profile_v1'
# 当前业务约束:一份 PDF 只能形成一个 PO;检测到多个 PO 必须整体拒识并转人工复核。
line_pos = []
for group in line_groups:
matches = [field for field in group['fields'] if field.get('field_id') in po_field_ids]
@@ -1123,29 +1169,7 @@ def _build_approved_profile_order_result(
'observations': [po_field.get('observations', [None])[0]],
})
return [base_order], None
if len(line_pos) != len(line_groups):
return None, 'multiple_business_tables_ambiguous'
orders: list[dict[str, Any]] = []
for value in sorted(distinct_pos):
po_lines = []
po_field_id = None
po_observation = None
for line_value, group, po_field in line_pos:
if line_value != value:
continue
cloned = json.loads(json.dumps(group))
cloned['fields'] = [field for field in cloned['fields'] if field.get('field_id') not in po_field_ids]
po_lines.append(cloned)
po_field_id = str(po_field.get('field_id') or '')
po_observation = po_field.get('observations', [None])[0]
if not po_field_id or not isinstance(po_observation, dict):
return None, 'required_header_missing'
order = json.loads(json.dumps(base_order))
order['lines'] = po_lines
order['header_fields'] = [field for field in order['header_fields'] if field.get('field_id') not in po_field_ids]
order['header_fields'].append({'field_id': po_field_id, 'observations': [po_observation]})
orders.append(order)
return orders, None
return None, 'multiple_po_detected'
def _build_approved_profile_order(
@@ -0,0 +1,403 @@
"""
backend/app/services/shipping_notice/order_extraction_workspace_projection.py
用途:把订单抽取 Run/Unit 的数据库事实投影为工作台摘要和按 PDF 的详情列表。
依赖:ShippingOrderExtractionRun/Unit/RouteDecision/ProgressEvent ORM、冻结 snapshot 和 Unit 结果 JSON。
逻辑:只输出用户可理解的业务信息;文件名、原因码、模板摘要和可操作按钮都在这里统一裁剪与组装。
"""
from __future__ import annotations
from collections import Counter
from typing import Any
from app.models import (
ShippingOrderExtractionProgressEvent,
ShippingOrderExtractionRouteDecision,
ShippingOrderExtractionRun,
ShippingOrderExtractionUnit,
)
ACTIVE_UNIT_STATUSES = {'pending', 'routing', 'matching_profile', 'extracting', 'merging_supplement'}
def _safe_file_name(value: Any) -> str | None:
"""只保留用户可见文件名,阻断路径片段进入工作台响应。"""
text = str(value or '').strip().replace('\\', '/')
if not text:
return None
name = text.split('/')[-1].strip()
return name[:255] or None
def _snapshot_documents(run: ShippingOrderExtractionRun) -> dict[int, dict[str, Any]]:
"""按冻结快照读取文档元数据,避免为展示层回读可变附件记录。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
items: dict[int, dict[str, Any]] = {}
for intake in snapshot.get('intakes') or []:
if not isinstance(intake, dict):
continue
intake_id = int(intake.get('intake_id') or 0)
for document in intake.get('documents') or []:
if not isinstance(document, dict):
continue
document_id = int(document.get('document_id') or 0)
if document_id <= 0:
continue
items[document_id] = {
'document_id': document_id,
'intake_id': intake_id,
'file_name': _safe_file_name(document.get('filename')),
'document_type': str(document.get('document_type') or ''),
}
return items
def _snapshot_profiles(run: ShippingOrderExtractionRun) -> dict[tuple[str, int], dict[str, Any]]:
"""从冻结快照中读取模板展示信息,避免文档详情受后续模板修改影响。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
profiles: dict[tuple[str, int], dict[str, Any]] = {}
for item in snapshot.get('order_document_profiles') or []:
if not isinstance(item, dict):
continue
code = str(item.get('profile_code') or '').strip()
version = int(item.get('version') or 0)
if not code or version <= 0:
continue
profiles[(code, version)] = {
'code': code,
'name': str(item.get('display_name') or item.get('profile_code') or '').strip() or None,
'version': version,
}
return profiles
def _schema_field_codes(run: ShippingOrderExtractionRun) -> dict[str, str]:
"""建立 field_id -> field_code 映射,供详情投影从订单快照中提取业务字段。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
return {
str(field.get('field_id') or ''): str(field.get('field_code') or '')
for field in schema.get('definition', {}).get('fields') or []
if isinstance(field, dict) and str(field.get('field_id') or '').strip()
}
def _field_values(fields: Any, *, field_codes: dict[str, str], targets: set[str]) -> list[str]:
"""从候选订单字段中提取稳定业务值,不把坐标或证据细节暴露给工作台。"""
values: list[str] = []
if not isinstance(fields, list):
return values
for item in fields:
if not isinstance(item, dict):
continue
if field_codes.get(str(item.get('field_id') or '')) not in targets:
continue
for observation in item.get('observations') or []:
if not isinstance(observation, dict):
continue
text = str(observation.get('value') or '').strip()
if text and text not in values:
values.append(text)
return values
def _orders_from_unit(unit: ShippingOrderExtractionUnit) -> list[dict[str, Any]]:
"""读取单元最终候选订单列表;非成功单元返回空列表。"""
result = unit.result_json if isinstance(unit.result_json, dict) else {}
return [item for item in result.get('orders') or [] if isinstance(item, dict)]
def _candidate_count(unit: ShippingOrderExtractionUnit) -> int:
"""统计单元可确认候选数;review_required 保留的中间结果不能算作成功候选。"""
if str(unit.status or '') != 'candidate_ready':
return 0
return len(_orders_from_unit(unit))
def _first_po_number(orders: list[dict[str, Any]], *, field_codes: dict[str, str]) -> str | None:
"""提取单元最主要的 PO 号码;多值时取首个稳定顺序值用于列表摘要。"""
for order in orders:
values = _field_values(
order.get('header_fields'),
field_codes=field_codes,
targets={'customer_po_number', 'po_number'},
)
if values:
return values[0]
return None
def _line_count(orders: list[dict[str, Any]]) -> int:
"""统计候选订单总行数。"""
return sum(len(order.get('lines') or []) for order in orders if isinstance(order, dict))
def _line_field_has_value(
orders: list[dict[str, Any]],
*,
field_codes: dict[str, str],
target: str,
) -> bool:
"""判断候选订单行内是否存在指定业务字段值。"""
for order in orders:
if not isinstance(order, dict):
continue
for line in order.get('lines') or []:
if not isinstance(line, dict):
continue
if _field_values(line.get('fields'), field_codes=field_codes, targets={target}):
return True
return False
def _latest_route_decisions(run: ShippingOrderExtractionRun) -> dict[int, ShippingOrderExtractionRouteDecision]:
"""按单元读取最新路由决策,用于展示模板命中结果。"""
decisions: dict[int, ShippingOrderExtractionRouteDecision] = {}
rows = (
ShippingOrderExtractionRouteDecision.query.filter_by(run_id=run.id)
.order_by(ShippingOrderExtractionRouteDecision.unit_id.asc(), ShippingOrderExtractionRouteDecision.id.asc())
.all()
)
for row in rows:
decisions[int(row.unit_id)] = row
return decisions
def _latest_progress_events(run: ShippingOrderExtractionRun) -> tuple[dict[tuple[int, str], ShippingOrderExtractionProgressEvent], ShippingOrderExtractionProgressEvent | None]:
"""收集每个单元每类事件的最新记录,并找出当前活动事件。"""
events: dict[tuple[int, str], ShippingOrderExtractionProgressEvent] = {}
current: ShippingOrderExtractionProgressEvent | None = None
rows = (
ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id, visibility='workspace')
.order_by(ShippingOrderExtractionProgressEvent.sequence_no.asc(), ShippingOrderExtractionProgressEvent.id.asc())
.all()
)
for row in rows:
unit_id = int(row.unit_id or 0)
if unit_id > 0:
events[(unit_id, str(row.event_code or ''))] = row
if str(row.event_code or '') != 'run_completed':
current = row
return events, current
def _current_activity_reason_codes(event: ShippingOrderExtractionProgressEvent | None) -> list[str]:
"""归并当前事件的顶层 reason_code 与 summary.reason_codes,供聊天卡直接展示。"""
if event is None:
return []
summary = event.summary_json if isinstance(event.summary_json, dict) else {}
codes = {
str(event.reason_code or '').strip(),
*[
str(code or '').strip()
for code in (summary.get('reason_codes') or [])
],
}
return sorted(code for code in codes if code)
def _run_available_actions(run: ShippingOrderExtractionRun, units: list[ShippingOrderExtractionUnit]) -> list[str]:
"""根据 Run 与 Unit 事实返回用户可见操作,前端不得自行推断。"""
actions = ['view_details']
if run.status in {'review_required', 'partially_completed'} or any(unit.status == 'review_required' for unit in units):
actions.append('enter_manual_review')
if run.status == 'failed' or any(unit.status == 'failed' for unit in units):
actions.append('retry_failed_attachments')
return actions
def _document_available_actions(unit: ShippingOrderExtractionUnit) -> list[str]:
"""按单元状态返回详情项可见操作。"""
if unit.status == 'candidate_ready':
return ['view_evidence', 'review_candidate']
if unit.status == 'review_required':
return ['view_evidence', 'manual_review']
return []
def _email_supplement_projection(
unit: ShippingOrderExtractionUnit,
event_map: dict[tuple[int, str], ShippingOrderExtractionProgressEvent],
*,
field_codes: dict[str, str],
) -> dict[str, Any]:
"""汇总正文补充的业务结果,避免让前端重算冲突逻辑。"""
event = event_map.get((int(unit.id), 'email_supplement_merged'))
summary = event.summary_json if event is not None and isinstance(event.summary_json, dict) else {}
orders = _orders_from_unit(unit)
if summary:
relation_codes = list(summary.get('relation_codes') or [])
conflict_count = int(summary.get('conflict_count') or 0)
status = str(summary.get('status') or 'none')
else:
relation_codes = sorted({
str(order.get('_hxops_email_supplement_relation') or '').strip()
for order in orders
if isinstance(order, dict) and str(order.get('_hxops_email_supplement_relation') or '').strip()
})
conflict_count = sum(
1
for order in orders if isinstance(order, dict)
for conflict in order.get('conflicts') or [] if isinstance(conflict, dict)
if str(conflict.get('reason') or '').strip() == 'supplement_relation_ambiguous'
)
status = 'conflict' if conflict_count > 0 else 'merged' if relation_codes else 'none'
def field_status(target: str) -> str:
if conflict_count > 0:
return 'conflict'
if target not in field_codes.values():
return 'unavailable'
if not relation_codes:
return 'none'
return 'merged' if _line_field_has_value(orders, field_codes=field_codes, target=target) else 'none'
return {
'status': status,
'relation_codes': relation_codes,
'conflict_count': conflict_count,
'reservation_id_status': field_status('reservation_id'),
'source_type_status': field_status('inventory_source_hint'),
}
def _profile_projection(
unit: ShippingOrderExtractionUnit,
*,
route_by_unit: dict[int, ShippingOrderExtractionRouteDecision],
profiles_by_key: dict[tuple[str, int], dict[str, Any]],
) -> dict[str, Any] | None:
"""返回单元命中的模板摘要;未命中或需人工时返回空。"""
route = route_by_unit.get(int(unit.id))
if route is None:
return None
code = str(route.selected_profile_code or '').strip()
version = int(route.selected_profile_version or 0)
if not code or version <= 0:
return None
return profiles_by_key.get((code, version), {'code': code, 'name': code, 'version': version})
def serialize_workspace_run_documents(run: ShippingOrderExtractionRun) -> list[dict[str, Any]]:
"""
构建工作台按 PDF 展示的详情列表。
AI 触发时机:当工作台详情抽屉或聊天卡需要回答“哪份 PDF 成功、用了什么模板、为什么失败”时使用。
"""
units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else []
documents = _snapshot_documents(run)
profiles_by_key = _snapshot_profiles(run)
field_codes = _schema_field_codes(run)
route_by_unit = _latest_route_decisions(run)
event_map, _ = _latest_progress_events(run)
items: list[dict[str, Any]] = []
for unit in units:
orders = _orders_from_unit(unit)
document = documents.get(int(unit.document_id), {})
items.append({
'unit_id': int(unit.id),
'document_id': int(unit.document_id),
'file_name': document.get('file_name'),
'status': unit.status,
'selection_batch': int(unit.selection_batch) if unit.selection_batch is not None else None,
'group_key': str(unit.group_key or '').strip() or None,
'retry_status': str(unit.retry_status or '').strip() or None,
'technical_failure_reason_code': str(unit.technical_failure_reason_code or '').strip() or None,
'budget_cost': dict(unit.budget_cost_json or {}) if isinstance(unit.budget_cost_json, dict) else None,
'po_number': _first_po_number(orders, field_codes=field_codes),
'line_count': _line_count(orders),
'profile': _profile_projection(unit, route_by_unit=route_by_unit, profiles_by_key=profiles_by_key),
'email_supplement': _email_supplement_projection(unit, event_map, field_codes=field_codes),
'reason_code': unit.reason_code or ('technical_failure' if unit.status == 'failed' else None),
'review_details': list((unit.result_json or {}).get('review_details') or []),
'available_actions': _document_available_actions(unit),
})
return items
def serialize_workspace_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
"""
构建工作台订单抽取摘要。
AI 触发时机:工作台 Run 列表、聊天卡恢复和详情按钮都应直接消费这个投影,而不是自己统计 Unit。
"""
units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else []
documents = _snapshot_documents(run)
_, current_event = _latest_progress_events(run)
status_counter = Counter(str(unit.status or '') for unit in units)
current_activity = None
if run.status in {'queued', 'processing'}:
if current_event is not None:
current_document = documents.get(int(current_event.document_id or 0), {}) if current_event.document_id is not None else {}
current_activity = {
'unit_id': int(current_event.unit_id) if current_event.unit_id is not None else None,
'file_name': current_document.get('file_name'),
'event_code': current_event.event_code,
'selection_batch': int(current_event.summary_json.get('selection_batch') or 0) or None
if isinstance(current_event.summary_json, dict) else None,
'reason_codes': _current_activity_reason_codes(current_event),
}
else:
pending_unit = next((unit for unit in units if unit.status in ACTIVE_UNIT_STATUSES), None)
if pending_unit is not None:
pending_document = documents.get(int(pending_unit.document_id), {})
current_activity = {
'unit_id': int(pending_unit.id),
'file_name': pending_document.get('file_name'),
'event_code': 'document_queued' if run.status == 'queued' else pending_unit.status,
'selection_batch': int(pending_unit.selection_batch or 0) or None,
'reason_codes': [],
}
return {
'summary': {
'total_documents': len(units),
'pending_documents': sum(status_counter.get(status, 0) for status in {'pending'}),
'processing_documents': sum(status_counter.get(status, 0) for status in {'routing', 'matching_profile', 'extracting', 'merging_supplement'}),
'completed_documents': status_counter.get('candidate_ready', 0),
'review_required_documents': status_counter.get('review_required', 0),
'failed_documents': status_counter.get('failed', 0),
'candidate_count': sum(_candidate_count(unit) for unit in units),
},
'current_activity': current_activity,
'available_actions': _run_available_actions(run, units),
}
def serialize_workspace_run_chat_state(run: ShippingOrderExtractionRun) -> dict[str, Any]:
"""
构建聊天消息使用的订单抽取状态卡。
AI 触发时机:聊天历史恢复、Run 轮询和终态持久化都必须复用这份用户态投影,
不能继续把 Workflow/health 等旧展示语义塞回消息 payload。
"""
projection = serialize_workspace_run(run)
summary = projection['summary'] if isinstance(projection.get('summary'), dict) else {}
current_activity = projection['current_activity'] if isinstance(projection.get('current_activity'), dict) else None
return {
'status': str(run.status or 'queued'),
'summary': {
'totalDocuments': int(summary.get('total_documents') or 0),
'pendingDocuments': int(summary.get('pending_documents') or 0),
'processingDocuments': int(summary.get('processing_documents') or 0),
'completedDocuments': int(summary.get('completed_documents') or 0),
'reviewRequiredDocuments': int(summary.get('review_required_documents') or 0),
'failedDocuments': int(summary.get('failed_documents') or 0),
'candidateCount': int(summary.get('candidate_count') or 0),
},
'currentActivity': (
{
'unitId': int(current_activity.get('unit_id') or 0),
'fileName': current_activity.get('file_name'),
'eventCode': str(current_activity.get('event_code') or ''),
'selectionBatch': int(current_activity.get('selection_batch') or 0) or None,
'reasonCodes': [str(code) for code in current_activity.get('reason_codes') or [] if str(code).strip()],
}
if current_activity else None
),
'availableActions': [str(action) for action in projection.get('available_actions') or []],
'terminal': str(run.status or '') not in {'queued', 'processing'},
'errorCode': str(run.error_code or '') or 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,
}
@@ -58,9 +58,11 @@ DATE_FIELDS = frozenset({'order_date', 'required_date', 'requested_receipt_date'
def freeze_order_snapshot(
task: ShippingTask,
*,
actor_id: int,
actor_id: int | None,
expected_order_data_version: int,
rule_versions: dict[str, Any] | None = None,
freeze_mode: str = 'manual',
auto_freeze_policy: dict[str, Any] | None = None,
) -> ShippingOrderSnapshot:
"""
冻结指定任务的已接受解析为不可变履约订单。
@@ -69,9 +71,11 @@ def freeze_order_snapshot(
Args:
task: 必须是当前用户有权操作且尚未冻结的任务。
actor_id: 执行冻结的用户 ID,不能为空。
actor_id: 执行冻结的用户 ID;自动冻结允许为空并记为系统执行。
expected_order_data_version: 用户界面读取到的版本;不匹配时拒绝覆盖。
rule_versions: 已冻结的订单/客户规则版本审计数据。
freeze_mode: `manual` 表示人工冻结;`auto` 表示消费 Run 自动冻结门禁。
auto_freeze_policy: 自动冻结时传入的 Run 级门禁摘要;人工路径忽略。
Returns:
ShippingOrderSnapshot: 已落库的不可变快照。
@@ -88,7 +92,7 @@ def freeze_order_snapshot(
return snapshot
raise ConflictError('Order snapshot reference is invalid', code='SHIPPING.ORDER_SNAPSHOT_FROZEN')
task = locked_task
if not actor_id:
if str(freeze_mode or 'manual') == 'manual' and not actor_id:
raise ValidationError('Snapshot freeze requires an operator', code='SHIPPING.ORDER_FREEZE_BLOCKED')
actual_version = int(task.order_data_version or 1)
if actual_version != int(expected_order_data_version):
@@ -101,7 +105,14 @@ def freeze_order_snapshot(
policy, configs = _policy_configs(extraction)
customer_match = _confirmed_ordering_customer(extraction)
from app.services.shipping_notice.freeze_readiness_service import assert_freeze_readiness
assert_freeze_readiness(task=task, extraction=extraction, policy=policy, configs=configs)
assert_freeze_readiness(
task=task,
extraction=extraction,
policy=policy,
configs=configs,
freeze_mode=freeze_mode,
auto_freeze_policy=auto_freeze_policy,
)
_assert_llm_review_gate(extraction, configs)
header_values, line_values = _extraction_values(extraction, configs)
@@ -0,0 +1,70 @@
"""
backend/app/services/shipping_notice/preview_grant_store.py
用途:为订单文档模板页预览令牌提供受控存储后端选择。
依赖:Flask current_app、统一 Redis client。
逻辑:生产默认强依赖 Redis;开发单进程可按配置回退到进程内一次性令牌存储。
"""
from __future__ import annotations
import threading
import time
from typing import Any
from flask import current_app
from app.core.errors import ServiceUnavailableError
from app.services.redis_client import get_redis_client
class _MemoryGrantStore:
"""为单进程开发环境提供最小 setex/getdel 语义,保持一次性令牌行为。"""
def __init__(self) -> None:
self._lock = threading.Lock()
self._items: dict[str, tuple[float, str]] = {}
def setex(self, key: str, ttl_seconds: int, value: str) -> None:
expires_at = time.time() + max(int(ttl_seconds), 1)
with self._lock:
self._items[key] = (expires_at, value)
def getdel(self, key: str) -> str | None:
now = time.time()
with self._lock:
row = self._items.pop(key, None)
if row is None:
return None
expires_at, value = row
if expires_at <= now:
return None
return value
_memory_store = _MemoryGrantStore()
def _memory_fallback_allowed() -> bool:
"""仅在显式允许时启用内存兜底,避免生产多 Worker 场景放松预览边界。"""
if not current_app:
return False
return bool(current_app.config.get('ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK', False))
def preview_grant_store() -> Any:
"""
返回模板预览授权存储。
AI/调用方触发时机:仅供订单文档模板预览接口内部使用。Redis 不可用时,
只有启用了开发兜底配置,才允许退回进程内一次性 token 存储。
"""
client = get_redis_client()
if client is not None:
return client
if _memory_fallback_allowed():
return _memory_store
raise ServiceUnavailableError(
'Order profile preview is temporarily unavailable',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
)
@@ -118,8 +118,8 @@ def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
"""
回收通用 jobs 表里超时的发货任务,并顺带消费 RPA callback cleanup 队列。
核心逻辑:单票编排与预解析分超时配置回收;预解析 Job 回收同事务同步 Intake,
避免 Job 已 requeue/failed 而 Intake 永久 parsing。
核心逻辑:按 Job 类型分别回收单票编排、预解析、订单抽取与版面解析;
预解析和订单抽取回收时同步领域状态,避免 Job 已 requeue/failed 而界面永久等待。
"""
from app.jobs.queue import recover_stale_jobs
from app.services.shipping_notice.intake_parse_workflow import (
@@ -146,6 +146,16 @@ def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
job_type=JobType.SHIPPING_NOTICE_PARSE,
on_recovered=sync_intake_after_parse_job_recovery,
)
from app.services.shipping_notice.order_extraction_run_service import (
sync_order_extraction_run_after_job_recovery,
)
extraction_count = recover_stale_jobs(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
timeout_seconds=run_timeout,
job_type=JobType.SHIPPING_ORDER_EXTRACTION,
on_recovered=sync_order_extraction_run_after_job_recovery,
)
from app.services.shipping_notice.document_layout.lifecycle import sync_layout_after_job_recovery
layout_count = recover_stale_jobs(
@@ -156,16 +166,17 @@ def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
job_type=JobType.SHIPPING_DOCUMENT_LAYOUT,
on_recovered=sync_layout_after_job_recovery,
)
count = int(run_count) + int(parse_count) + int(layout_count)
count = int(run_count) + int(parse_count) + int(extraction_count) + int(layout_count)
cleanup_count, cleanup_warnings = recover_pending_rpa_callback_cleanup_jobs()
if cleanup_warnings:
logger.warning('rpa callback cleanup warnings: %s', '; '.join(cleanup_warnings[:5]))
if count:
logger.warning(
'recovered %s stale shipping_notice job(s) (run=%s parse=%s layout=%s)',
'recovered %s stale shipping_notice job(s) (run=%s parse=%s extraction=%s layout=%s)',
count,
run_count,
parse_count,
extraction_count,
layout_count,
)
if cleanup_count:
@@ -0,0 +1,228 @@
"""rebuild order extraction progress facts
Revision ID: 0ab45c6d7e8f
Revises: 09a23b4c5d6e
Create Date: 2026-07-28 15:30:00.000000
用途:重建订单解析 Run/Unit/Event 的确定性业务进度事实模型。
依赖:shipping_order_extraction_runs、shipping_order_extraction_units、shipping_order_extraction_progress_events。
逻辑:不做旧 Workflow 字段兼容,直接替换为 Run 汇总与 Unit 业务事件结构。
"""
from alembic import op
import sqlalchemy as sa
revision = '0ab45c6d7e8f'
down_revision = '09a23b4c5d6e'
branch_labels = None
depends_on = None
def _columns(inspector: sa.Inspector, table_name: str) -> set[str]:
return {column['name'] for column in inspector.get_columns(table_name)}
def _indexes(inspector: sa.Inspector, table_name: str) -> set[str]:
return {index['name'] for index in inspector.get_indexes(table_name)}
def _has_table(inspector: sa.Inspector, table_name: str) -> bool:
return table_name in inspector.get_table_names()
def _check_constraints(inspector: sa.Inspector, table_name: str) -> set[str]:
return {
constraint['name']
for constraint in inspector.get_check_constraints(table_name)
if constraint.get('name')
}
def upgrade() -> None:
"""切换到订单解析确定性业务状态、Unit 摘要字段和新事件表。"""
bind = op.get_bind()
inspector = sa.inspect(bind)
run_checks = _check_constraints(inspector, 'shipping_order_extraction_runs')
unit_checks = _check_constraints(inspector, 'shipping_order_extraction_units')
if 'ck_shipping_order_extraction_runs_status' in run_checks:
op.drop_constraint('ck_shipping_order_extraction_runs_status', 'shipping_order_extraction_runs', type_='check')
if 'ck_shipping_order_extraction_units_status' in unit_checks:
op.drop_constraint('ck_shipping_order_extraction_units_status', 'shipping_order_extraction_units', type_='check')
# 兼容历史运行状态,避免存量数据在新增约束时失败。
op.execute(
sa.text(
"""
UPDATE shipping_order_extraction_runs
SET status = CASE status
WHEN 'running' THEN 'processing'
WHEN 'result_persisted' THEN 'completed'
WHEN 'needs_review' THEN 'review_required'
ELSE status
END
WHERE status IN ('running', 'result_persisted', 'needs_review')
"""
)
)
op.execute(
sa.text(
"""
UPDATE shipping_order_extraction_units
SET status = CASE status
WHEN 'running' THEN 'extracting'
WHEN 'succeeded' THEN 'candidate_ready'
WHEN 'skipped' THEN 'review_required'
ELSE status
END
WHERE status IN ('running', 'succeeded', 'skipped')
"""
)
)
with op.batch_alter_table('shipping_order_extraction_runs') as batch:
batch.create_check_constraint(
'ck_shipping_order_extraction_runs_status',
"status IN ('queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled')",
)
for index_name in ('uq_shipping_order_extraction_runs_active_conversation',):
if index_name in _indexes(inspector, 'shipping_order_extraction_runs'):
op.drop_index(index_name, table_name='shipping_order_extraction_runs')
op.create_index(
'uq_shipping_order_extraction_runs_active_conversation',
'shipping_order_extraction_runs',
['user_id', 'owner_agent_id', 'conversation_id'],
unique=True,
sqlite_where=sa.text("status IN ('queued', 'processing')"),
postgresql_where=sa.text("status IN ('queued', 'processing')"),
)
with op.batch_alter_table('shipping_order_extraction_units') as batch:
batch.create_check_constraint(
'ck_shipping_order_extraction_units_status',
"status IN ('pending', 'routing', 'matching_profile', 'extracting', 'merging_supplement', 'candidate_ready', 'review_required', 'failed', 'cancelled')",
)
existing_columns = _columns(inspector, 'shipping_order_extraction_units')
if 'reason_code' not in existing_columns:
batch.add_column(sa.Column('reason_code', sa.String(length=64), nullable=True))
if 'summary_json' not in existing_columns:
batch.add_column(sa.Column('summary_json', sa.JSON(), nullable=True))
if 'last_activity_at' not in existing_columns:
batch.add_column(sa.Column('last_activity_at', sa.DateTime(), nullable=True))
if _has_table(inspector, 'shipping_order_extraction_progress_events'):
op.drop_table('shipping_order_extraction_progress_events')
op.create_table(
'shipping_order_extraction_progress_events',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('run_id', sa.Integer(), sa.ForeignKey('shipping_order_extraction_runs.id', ondelete='CASCADE'), nullable=False),
sa.Column('unit_id', sa.Integer(), sa.ForeignKey('shipping_order_extraction_units.id', ondelete='CASCADE'), nullable=True),
sa.Column('document_id', sa.Integer(), nullable=True),
sa.Column('job_id', sa.Integer(), sa.ForeignKey('jobs.id'), nullable=True),
sa.Column('attempt_count', sa.Integer(), nullable=True),
sa.Column('sequence_no', sa.Integer(), nullable=False),
sa.Column('visibility', sa.String(length=32), nullable=False, server_default='workspace'),
sa.Column('event_code', sa.String(length=64), nullable=False),
sa.Column('status', sa.String(length=32), nullable=False, server_default='completed'),
sa.Column('occurred_at', sa.DateTime(), nullable=True),
sa.Column('reason_code', sa.String(length=64), nullable=True),
sa.Column('received_at', sa.DateTime(), nullable=False),
sa.Column('summary_json', sa.JSON(), nullable=True),
sa.Column('idempotency_key', sa.String(length=128), nullable=False),
sa.Column('mapping_version', sa.String(length=32), nullable=True),
sa.Column('expires_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('idempotency_key', name='uq_shipping_order_extraction_progress_event_key'),
sa.UniqueConstraint('run_id', 'sequence_no', name='uq_shipping_order_extraction_progress_event_sequence'),
)
op.create_index(
'ix_shipping_order_extraction_progress_events_run_sequence',
'shipping_order_extraction_progress_events',
['run_id', 'sequence_no'],
)
op.create_index(
'ix_shipping_order_extraction_progress_events_expires_id',
'shipping_order_extraction_progress_events',
['expires_at', 'id'],
)
op.create_index(
'ix_shipping_order_extraction_progress_events_run_visibility',
'shipping_order_extraction_progress_events',
['run_id', 'visibility', 'sequence_no'],
)
def downgrade() -> None:
"""恢复旧的 Workflow 观察器阶段结构,仅用于受控回滚。"""
bind = op.get_bind()
inspector = sa.inspect(bind)
if _has_table(inspector, 'shipping_order_extraction_progress_events'):
op.drop_table('shipping_order_extraction_progress_events')
op.create_table(
'shipping_order_extraction_progress_events',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('run_id', sa.Integer(), sa.ForeignKey('shipping_order_extraction_runs.id', ondelete='CASCADE'), nullable=False),
sa.Column('job_id', sa.Integer(), sa.ForeignKey('jobs.id'), nullable=True),
sa.Column('attempt_count', sa.Integer(), nullable=True),
sa.Column('workflow_run_id', sa.String(length=128), nullable=True),
sa.Column('node_execution_id', sa.String(length=128), nullable=True),
sa.Column('event_type', sa.String(length=64), nullable=False),
sa.Column('node_type', sa.String(length=64), nullable=True),
sa.Column('stage_code', sa.String(length=64), nullable=True),
sa.Column('event_status', sa.String(length=32), nullable=True),
sa.Column('provider_occurred_at', sa.DateTime(), nullable=True),
sa.Column('received_at', sa.DateTime(), nullable=False),
sa.Column('details_json', sa.JSON(), nullable=True),
sa.Column('idempotency_key', sa.String(length=128), nullable=False),
sa.Column('mapping_version', sa.String(length=32), nullable=True),
sa.Column('expires_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('idempotency_key', name='uq_shipping_order_extraction_progress_event_key'),
)
op.create_index(
'ix_shipping_order_extraction_progress_events_run_created',
'shipping_order_extraction_progress_events',
['run_id', 'created_at'],
)
op.create_index(
'ix_shipping_order_extraction_progress_events_expires_id',
'shipping_order_extraction_progress_events',
['expires_at', 'id'],
)
op.create_index(
'ix_shipping_order_extraction_progress_events_workflow_node',
'shipping_order_extraction_progress_events',
['workflow_run_id', 'node_execution_id'],
)
with op.batch_alter_table('shipping_order_extraction_units') as batch:
existing_columns = _columns(inspector, 'shipping_order_extraction_units')
for column_name in ('last_activity_at', 'summary_json', 'reason_code'):
if column_name in existing_columns:
batch.drop_column(column_name)
if 'ck_shipping_order_extraction_units_status' in _check_constraints(inspector, 'shipping_order_extraction_units'):
batch.drop_constraint('ck_shipping_order_extraction_units_status', type_='check')
batch.create_check_constraint(
'ck_shipping_order_extraction_units_status',
"status IN ('pending', 'running', 'succeeded', 'failed', 'skipped')",
)
if 'uq_shipping_order_extraction_runs_active_conversation' in _indexes(inspector, 'shipping_order_extraction_runs'):
op.drop_index('uq_shipping_order_extraction_runs_active_conversation', table_name='shipping_order_extraction_runs')
op.create_index(
'uq_shipping_order_extraction_runs_active_conversation',
'shipping_order_extraction_runs',
['user_id', 'owner_agent_id', 'conversation_id'],
unique=True,
sqlite_where=sa.text("status IN ('queued', 'running', 'result_persisted')"),
postgresql_where=sa.text("status IN ('queued', 'running', 'result_persisted')"),
)
with op.batch_alter_table('shipping_order_extraction_runs') as batch:
if 'ck_shipping_order_extraction_runs_status' in _check_constraints(inspector, 'shipping_order_extraction_runs'):
batch.drop_constraint('ck_shipping_order_extraction_runs_status', type_='check')
batch.create_check_constraint(
'ck_shipping_order_extraction_runs_status',
"status IN ('queued', 'running', 'result_persisted', 'completed', 'needs_review', 'failed', 'cancelled')",
)
@@ -0,0 +1,54 @@
"""Remove obsolete internal executor configuration.
Revision ID: 0ac56d7e8f90
Revises: 1d2e3f4a5b6c, 3dd67e8f9a0b
Create Date: 2026-07-28 16:20:00.000000
Purpose: remove the retired internal executor and runtime binding data model.
Dependencies: agents and agent_runtime_bindings.
Logic: delete obsolete bindings, normalize retained Agent records, then remove the exposure column and binding table.
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = '0ac56d7e8f90'
down_revision = ('1d2e3f4a5b6c', '3dd67e8f9a0b')
branch_labels = None
depends_on = None
def upgrade() -> None:
"""Permanently remove internal-executor semantics and their obsolete bindings."""
bind = op.get_bind()
inspector = sa.inspect(bind)
tables = set(inspector.get_table_names())
if 'agent_runtime_bindings' in tables:
bind.execute(sa.text('DELETE FROM agent_runtime_bindings'))
if 'agents' not in tables:
return
columns = {column['name'] for column in inspector.get_columns('agents')}
if 'exposure_mode' not in columns:
return
# Retain Agent rows because chats, guides, and historical Runs may reference them.
# Removing the role column makes all retained records ordinary applications.
bind.execute(sa.text("UPDATE agents SET exposure_mode = 'workspace' WHERE exposure_mode = 'internal'"))
inspector = sa.inspect(bind)
if 'agent_runtime_bindings' in set(inspector.get_table_names()):
op.drop_table('agent_runtime_bindings')
with op.batch_alter_table('agents') as batch:
constraints = {item['name'] for item in sa.inspect(bind).get_check_constraints('agents') if item.get('name')}
if 'ck_agents_exposure_mode' in constraints:
batch.drop_constraint('ck_agents_exposure_mode', type_='check')
batch.drop_column('exposure_mode')
def downgrade() -> None:
"""This intentional destructive cleanup has no downgrade path."""
raise RuntimeError('Internal executor removal cannot be downgraded')
@@ -0,0 +1,55 @@
"""align order route decision constraint
Revision ID: 0bd56e7f8a91
Revises: 0ac56d7e8f90
Create Date: 2026-07-28 14:00:00.000000
用途:使数据库路由决策约束与确定性订单抽取模型一致。
依赖:shipping_order_extraction_route_decisions、ShippingOrderExtractionRouteDecision。
逻辑:替换历史 decision 枚举约束,允许 deterministic、review_required 与 skipped;不修改已有审计数据。
"""
from alembic import op
revision = '0bd56e7f8a91'
down_revision = '0ac56d7e8f90'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""替换遗留的路由 decision 检查约束,支持人工复核和跳过投影。"""
op.drop_constraint(
'ck_shipping_order_extraction_route_decision',
'shipping_order_extraction_route_decisions',
type_='check',
)
# 历史 dify/blocked 仅是旧路由语义:分别映射为当前确定性/人工复核投影。
op.execute(
"UPDATE shipping_order_extraction_route_decisions "
"SET decision = CASE decision "
"WHEN 'dify' THEN 'deterministic' "
"WHEN 'blocked' THEN 'review_required' "
"ELSE decision END "
"WHERE decision IN ('dify', 'blocked')"
)
op.create_check_constraint(
'ck_shipping_order_extraction_route_decision',
'shipping_order_extraction_route_decisions',
"decision IN ('deterministic', 'review_required', 'skipped')",
)
def downgrade() -> None:
"""恢复历史枚举,回退前须确认不存在新 decision 值。"""
op.drop_constraint(
'ck_shipping_order_extraction_route_decision',
'shipping_order_extraction_route_decisions',
type_='check',
)
op.create_check_constraint(
'ck_shipping_order_extraction_route_decision',
'shipping_order_extraction_route_decisions',
"decision IN ('deterministic', 'dify', 'blocked')",
)
@@ -0,0 +1,48 @@
"""add customer and scenario scope to profile auto-freeze qualifications
Revision ID: 0ce67f8a9b01
Revises: 0bd56e7f8a91
Create Date: 2026-07-28 18:40:00.000000
用途:为模板版本级自动冻结资格补齐客户/业务场景授权范围。
依赖:已存在的自动冻结资格表与用户表。
逻辑:仅追加授权范围与配置审计字段,不改变既有资格状态。
"""
from alembic import op
import sqlalchemy as sa
revision = '0ce67f8a9b01'
down_revision = '0bd56e7f8a91'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""为资格表增加客户范围、业务场景和客户确认开关。"""
with op.batch_alter_table('shipping_document_profile_auto_freeze_qualifications', recreate='auto') as batch_op:
batch_op.add_column(sa.Column('customer_ids_json', sa.JSON(), nullable=True))
batch_op.add_column(sa.Column('business_scenarios_json', sa.JSON(), nullable=True))
batch_op.add_column(
sa.Column('requires_customer_confirmation', sa.Boolean(), nullable=False, server_default=sa.text('true')),
)
batch_op.add_column(sa.Column('scope_updated_by_id', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('scope_updated_at', sa.DateTime(), nullable=True))
batch_op.create_foreign_key(
'fk_ship_doc_prof_auto_freeze_scope_updated_by_user',
'users',
['scope_updated_by_id'],
['id'],
)
def downgrade() -> None:
"""移除资格范围字段,保留既有状态记录。"""
with op.batch_alter_table('shipping_document_profile_auto_freeze_qualifications', recreate='auto') as batch_op:
batch_op.drop_constraint('fk_ship_doc_prof_auto_freeze_scope_updated_by_user', type_='foreignkey')
batch_op.drop_column('scope_updated_at')
batch_op.drop_column('scope_updated_by_id')
batch_op.drop_column('requires_customer_confirmation')
batch_op.drop_column('business_scenarios_json')
batch_op.drop_column('customer_ids_json')
@@ -0,0 +1,38 @@
"""add upload batch to shipping notice intakes
Revision ID: 0cf78a9b0c12
Revises: 0ce67f8a9b01
Create Date: 2026-07-28 20:10:00.000000
用途:为聊天输入框的一次文件选择持久化上传批次。
依赖:shipping_notice_intakes。
逻辑:Run 创建按 upload_batch_id 锁定当前发送附件,避免历史未发送 Intake 混入。
"""
from alembic import op
import sqlalchemy as sa
revision = '0cf78a9b0c12'
down_revision = '0ce67f8a9b01'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""新增上传批次与按用户批次查询索引;无历史兼容回填。"""
with op.batch_alter_table('shipping_notice_intakes', recreate='auto') as batch_op:
# 旧 Intake 不回填也不可发送;可空使已有生产表能够原地升级。
batch_op.add_column(sa.Column('upload_batch_id', sa.String(length=36), nullable=True))
batch_op.create_index(
'ix_shipping_notice_intakes_user_upload_batch_created',
['user_id', 'upload_batch_id', 'created_at'],
unique=False,
)
def downgrade() -> None:
"""移除输入框上传批次字段和索引。"""
with op.batch_alter_table('shipping_notice_intakes', recreate='auto') as batch_op:
batch_op.drop_index('ix_shipping_notice_intakes_user_upload_batch_created')
batch_op.drop_column('upload_batch_id')
@@ -0,0 +1,63 @@
"""add order extraction unit plan metadata
Revision ID: 1d2e3f4a5b6c
Revises: 0ab45c6d7e8f
Create Date: 2026-07-28 17:10:00.000000
用途:为订单抽取单元补充选择批次、分组键、预算、重试与技术失败事实。
依赖:shipping_order_extraction_units。
逻辑:阶段 2/4 直接在 Unit 层持久化计划与失败元数据,避免后续只能回读 snapshot 猜测。
"""
from alembic import op
import sqlalchemy as sa
revision = '1d2e3f4a5b6c'
down_revision = '0ab45c6d7e8f'
branch_labels = None
depends_on = None
def _columns(inspector: sa.Inspector, table_name: str) -> set[str]:
return {column['name'] for column in inspector.get_columns(table_name)}
def upgrade() -> None:
"""为订单抽取单元添加阶段 2/4 所需的计划与失败元数据字段。"""
bind = op.get_bind()
inspector = sa.inspect(bind)
existing_columns = _columns(inspector, 'shipping_order_extraction_units')
with op.batch_alter_table('shipping_order_extraction_units') as batch:
if 'selection_batch' not in existing_columns:
batch.add_column(sa.Column('selection_batch', sa.Integer(), nullable=True))
if 'selection_reason_codes_json' not in existing_columns:
batch.add_column(sa.Column('selection_reason_codes_json', sa.JSON(), nullable=True))
if 'group_key' not in existing_columns:
batch.add_column(sa.Column('group_key', sa.String(length=128), nullable=True))
if 'budget_cost_json' not in existing_columns:
batch.add_column(sa.Column('budget_cost_json', sa.JSON(), nullable=True))
if 'retry_status' not in existing_columns:
batch.add_column(sa.Column('retry_status', sa.String(length=32), nullable=True))
if 'technical_failure_reason_code' not in existing_columns:
batch.add_column(sa.Column('technical_failure_reason_code', sa.String(length=64), nullable=True))
def downgrade() -> None:
"""移除订单抽取单元的计划与失败元数据字段。"""
bind = op.get_bind()
inspector = sa.inspect(bind)
existing_columns = _columns(inspector, 'shipping_order_extraction_units')
with op.batch_alter_table('shipping_order_extraction_units') as batch:
for column_name in (
'technical_failure_reason_code',
'retry_status',
'budget_cost_json',
'group_key',
'selection_reason_codes_json',
'selection_batch',
):
if column_name in existing_columns:
batch.drop_column(column_name)
@@ -0,0 +1,33 @@
"""add immutable request snapshot to order extraction run
Revision ID: 2d3e4f5a6b7c
Revises: 0cf78a9b0c12
Create Date: 2026-07-28 21:15:00.000000
用途:保留用户点击发送时的轻量请求快照,隔离 Worker 物化后的执行快照。
依赖:shipping_order_extraction_runs。
逻辑:请求快照稳定用于幂等和审计;input_snapshot_* 继续承载不可变执行证据。
"""
from alembic import op
import sqlalchemy as sa
revision = '2d3e4f5a6b7c'
down_revision = '0cf78a9b0c12'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""新增请求时冻结的哈希及 JSON 快照;旧记录保留为空。"""
with op.batch_alter_table('shipping_order_extraction_runs', recreate='auto') as batch_op:
batch_op.add_column(sa.Column('request_snapshot_hash', sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column('request_snapshot_json', sa.JSON(), nullable=True))
def downgrade() -> None:
"""移除请求快照字段。"""
with op.batch_alter_table('shipping_order_extraction_runs', recreate='auto') as batch_op:
batch_op.drop_column('request_snapshot_json')
batch_op.drop_column('request_snapshot_hash')
@@ -7,7 +7,7 @@ import pytest
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import Agent, AgentRuntimeBinding, User
from app.models import Agent, User
from app.services.admin import agent_service
@@ -85,87 +85,6 @@ def test_update_agent_clears_handler_config_when_explicit_null(app):
assert refreshed.handler_config is None
def test_create_agent_and_runtime_binding_are_atomic(app):
"""创建货代 Agent 时绑定校验失败必须回滚 Agent,不能留下半配置入口。"""
with app.app_context():
provider = Agent(
name='Invalid Chatflow Provider',
agent_code='generic',
runtime_provider='dify',
dify_app_type='chatflow',
exposure_mode='workspace',
dify_app_id='invalid-create-provider',
dify_api_key='sk-test',
api_base_url='http://dify.example/v1',
is_active=True,
)
db.session.add(provider)
db.session.commit()
with pytest.raises(ValidationError):
agent_service.create_agent({
'name': 'Atomic Shipping Create',
'agent_code': 'shipping_notice',
'runtime_provider': 'hybrid',
'conversation_mode': 'task_chat',
'dify_app_id': 'atomic-shipping-create',
'dify_api_key': 'sk-test',
'api_base_url': 'http://dify.example/v1',
'order_extraction_runtime_binding': {
'provider_agent_id': provider.id,
'enabled': True,
'config': {'timeout_seconds': 900, 'max_attempts': 3},
},
})
db.session.rollback()
assert Agent.query.filter_by(name='Atomic Shipping Create').count() == 0
assert AgentRuntimeBinding.query.count() == 0
def test_update_agent_and_runtime_binding_are_atomic(app):
"""更新 Agent 时绑定校验失败必须回滚 Agent 字段,避免配置只保存一半。"""
with app.app_context():
owner = Agent(
name='Atomic Shipping Update',
description='before',
agent_code='shipping_notice',
runtime_provider='hybrid',
conversation_mode='task_chat',
dify_app_id='atomic-shipping-update',
dify_api_key='sk-test',
api_base_url='http://dify.example/v1',
is_active=True,
)
provider = Agent(
name='Invalid Update Provider',
agent_code='generic',
runtime_provider='dify',
dify_app_type='chatflow',
exposure_mode='workspace',
dify_app_id='invalid-update-provider',
dify_api_key='sk-test',
api_base_url='http://dify.example/v1',
is_active=True,
)
db.session.add_all([owner, provider])
db.session.commit()
with pytest.raises(ValidationError):
agent_service.update_agent(owner.id, {
'description': 'after',
'order_extraction_runtime_binding': {
'provider_agent_id': provider.id,
'enabled': True,
'config': {'timeout_seconds': 900, 'max_attempts': 3},
},
})
db.session.rollback()
assert db.session.get(Agent, owner.id).description == 'before'
assert AgentRuntimeBinding.query.filter_by(owner_agent_id=owner.id).count() == 0
def test_update_agent_permissions(app):
with app.app_context():
agent = Agent(
@@ -50,31 +50,6 @@ def test_batch_update_permissions_no_users(app):
permission_service.batch_update_permissions({'user_ids': [], 'agent_ids': [1]})
@pytest.mark.parametrize('operation', ['single', 'batch'])
def test_internal_executor_cannot_be_assigned_to_user(app, operation):
"""授权服务必须在所有写入口拒绝 internal 执行器。"""
with app.app_context():
executor = Agent(
name='internal-executor', type='api', dify_app_id='wf-internal', dify_api_key='key',
dify_app_type='workflow', runtime_provider='dify', exposure_mode='internal',
)
user = User(username=f'internal-{operation}', email=f'internal-{operation}@example.com', role='user')
db.session.add_all([executor, user])
db.session.commit()
with pytest.raises(ValidationError) as caught:
if operation == 'single':
permission_service.update_user_permissions(user.id, {'agent_ids': [executor.id]})
else:
permission_service.batch_update_permissions({
'user_ids': [user.id], 'agent_ids': [executor.id], 'action': 'add',
})
assert caught.value.code == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN'
db.session.refresh(user)
assert executor not in user.agents
def test_permission_request_approve(app, monkeypatch):
with app.app_context():
agent = Agent(name='req-agent', type='api', dify_app_id='app-r', dify_api_key='key-r')
@@ -100,27 +75,3 @@ def test_permission_request_approve(app, monkeypatch):
def test_permission_request_not_found(app):
with app.app_context():
with pytest.raises(NotFoundError):
permission_service.approve_permission_request(99999)
def test_internal_executor_permission_request_cannot_be_approved(app):
"""历史或伪造的内部执行器权限申请不得转化为用户授权。"""
with app.app_context():
executor = Agent(
name='request-executor', type='api', dify_app_id='wf-request', dify_api_key='key',
dify_app_type='workflow', runtime_provider='dify', exposure_mode='internal',
)
user = User(username='request-internal', email='request-internal@example.com', role='user')
db.session.add_all([executor, user])
db.session.flush()
req = PermissionRequest(user_id=user.id, agent_id=executor.id, reason='invalid', status='pending')
db.session.add(req)
db.session.commit()
with pytest.raises(ForbiddenError) as caught:
permission_service.approve_permission_request(req.id)
assert getattr(caught.value, 'code', None) == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN'
db.session.refresh(user)
assert executor not in user.agents
@@ -54,23 +54,3 @@ def test_list_users_sort_by_username_and_department(app):
assert depts == sorted(depts, reverse=True)
fallback = user_service.resolve_users_order_by({'sort_by': 'role', 'sort_dir': 'asc'})
assert len(fallback) == 1
def test_update_user_rejects_internal_executor_permission(app):
"""用户 CRUD 的 agent_ids 写入口不得绕过统一授权策略。"""
with app.app_context():
user = User(username='crud-internal', email='crud-internal@example.com', role='user')
executor = Agent(
name='CRUD Executor', exposure_mode='internal', runtime_provider='dify',
dify_app_type='workflow', dify_app_id='crud-workflow', dify_api_key='key',
)
db.session.add_all([user, executor])
db.session.commit()
with pytest.raises(ValidationError) as caught:
user_service.update_user(user.id, {'agent_ids': [executor.id]})
assert caught.value.code == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN'
db.session.refresh(user)
assert executor not in user.agents
@@ -21,28 +21,3 @@ def test_binding_stats(app):
stats = wecom_admin_service.binding_stats()
assert stats['total_active'] == 2
assert stats['bound'] == 1
assert stats['unbound'] == 1
def test_provision_user_rejects_internal_executor_permission(app):
"""企微开户/绑定不得把内部执行器写入用户授权关系。"""
with app.app_context():
user = User(username='wecom-internal', email='wecom-internal@example.com', role='user')
executor = Agent(
name='WeCom Executor', exposure_mode='internal', runtime_provider='dify',
dify_app_type='workflow', dify_app_id='wecom-workflow', dify_api_key='key',
)
db.session.add_all([user, executor])
db.session.commit()
with pytest.raises(ValidationError) as caught:
wecom_admin_service.provision_user({
'create_user': False,
'user_id': user.id,
'bind': {'wecom_userid': 'wx-internal'},
'agent_ids': [executor.id],
})
assert caught.value.code == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN'
db.session.refresh(user)
assert executor not in user.agents
@@ -31,6 +31,8 @@ from app.models import (
ShippingTask,
User,
)
from app.services.shipping_notice.freeze_readiness_service import assert_freeze_readiness
from app.services.shipping_notice.fulfillment_policy_registry import published_policy, required_field_configs
from app.services.shipping_notice.order_freeze_service import (
HEADER_FIELD_PROJECTIONS,
LINE_FIELD_PROJECTIONS,
@@ -280,6 +282,47 @@ def test_freeze_rejects_open_conflict_and_missing_fulfillment_value(app):
assert missing_error.value.code == 'SHIPPING.ORDER_FREEZE_BLOCKED'
def test_auto_freeze_readiness_fails_closed_with_run_policy_blockers(app):
"""自动冻结模式必须消费 Run 级门禁摘要,并把阻断原因折叠为统一 freeze issues。"""
with app.app_context():
task, _user = _build_accepted_order(suffix='auto-freeze-readiness')
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
assert extraction is not None
policy = published_policy()
definition = extraction.schema_version.definition_json or {}
configs = {
str(item.get('field_code') or ''): item
for item in definition.get('fields') or []
if isinstance(item, dict) and item.get('enabled', True)
}
configs.update(required_field_configs(definition, policy))
with pytest.raises(ValidationError) as blocked_error:
assert_freeze_readiness(
task=task,
extraction=extraction,
policy=policy,
configs=configs,
freeze_mode='auto',
auto_freeze_policy={
'mode': 'manual_confirmation',
'enabled': False,
'qualification_status': 'auto_freeze_approved',
'customer_scope_status': 'unconfigured',
'blocking_reason_codes': [
'customer_scope_not_configured',
'customer_confirmation_required',
],
},
)
assert blocked_error.value.code == 'SHIPPING.ORDER_FREEZE_BLOCKED'
issues = blocked_error.value.details['issues']
assert {'reason': 'auto_freeze_blocked', 'blocking_reason_code': 'customer_scope_not_configured'} in issues
assert {'reason': 'auto_freeze_blocked', 'blocking_reason_code': 'customer_confirmation_required'} in issues
assert any(item['reason'] == 'auto_freeze_not_enabled' for item in issues)
def test_freeze_is_idempotent_for_repeated_confirmation(app):
"""关键断言:用户重复确认冻结只返回同一 Snapshot,不产生第二份履约事实。"""
with app.app_context():
@@ -40,74 +40,6 @@ def test_validate_agent_payload_parses_is_active_string_false():
assert normalized['is_active'] is False
def test_validate_agent_payload_restricts_new_internal_executor_to_workflow():
"""新建 internal Agent 只能登记为 Dify Workflow。"""
with pytest.raises(ValidationError, match='内部执行器'):
validate_agent_payload({
'name': 'Invalid Internal',
'agent_code': 'generic',
'runtime_provider': 'dify',
'dify_app_type': 'chatflow',
'exposure_mode': 'internal',
'dify_app_id': 'app-1',
})
def test_validate_agent_payload_rejects_moving_internal_to_workspace():
"""内部执行器的可见性不可改回 workspace。"""
from types import SimpleNamespace
agent = SimpleNamespace(
agent_code='generic', runtime_provider='dify', conversation_mode='task_chat',
dify_app_type='workflow', exposure_mode='internal',
dify_app_id='app-1', bound_schedule_task_id=None, capabilities=None, handler_config=None,
suggested_questions_style='plain', suggested_questions=[], sort_order=0,
file_upload_policy=None, is_active=True, is_aggregate=False,
)
with pytest.raises(ValidationError) as caught:
validate_agent_payload({
'name': 'Provider', 'exposure_mode': 'workspace',
}, agent=agent, provided_fields=frozenset({'name', 'exposure_mode'}))
assert caught.value.code == 'AGENT.EXPOSURE_ROLE_IMMUTABLE'
def test_validate_agent_payload_rejects_promoting_workspace_to_internal():
"""workspace Agent 不能通过编辑请求转换为 internal 执行器。"""
from types import SimpleNamespace
agent = SimpleNamespace(
agent_code='generic', runtime_provider='dify', conversation_mode='chat',
dify_app_type='chatflow', exposure_mode='workspace',
dify_app_id='app-1', bound_schedule_task_id=None, capabilities=None, handler_config=None,
suggested_questions_style='plain', suggested_questions=[], sort_order=0,
file_upload_policy=None, is_active=True, is_aggregate=False,
)
with pytest.raises(ValidationError) as caught:
validate_agent_payload({
'name': 'Promote Provider', 'exposure_mode': 'internal',
'runtime_provider': 'dify', 'dify_app_type': 'workflow',
}, agent=agent, provided_fields=frozenset({'name', 'exposure_mode', 'runtime_provider', 'dify_app_type'}))
assert caught.value.code == 'AGENT.EXPOSURE_ROLE_IMMUTABLE'
def test_validate_agent_payload_keeps_internal_exposure_immutable():
"""已注册内部执行器不得通过编辑请求改成工作台应用。"""
from types import SimpleNamespace
agent = SimpleNamespace(
agent_code='generic', runtime_provider='dify', conversation_mode='task_chat',
dify_app_type='workflow', exposure_mode='internal',
dify_app_id='app-1', bound_schedule_task_id=None, capabilities=None, handler_config=None,
suggested_questions_style='plain', suggested_questions=[], sort_order=0,
file_upload_policy=None, is_active=True, is_aggregate=False,
)
with pytest.raises(ValidationError) as caught:
validate_agent_payload({
'name': 'Internal Provider', 'exposure_mode': 'workspace',
}, agent=agent, provided_fields=frozenset({'name', 'exposure_mode'}))
assert caught.value.code == 'AGENT.EXPOSURE_ROLE_IMMUTABLE'
def test_validate_agent_payload_applies_forced_capabilities_from_manifest():
"""validate_agent_payload 路径应合并 manifest forced_capabilities。"""
normalized = validate_agent_payload({
@@ -20,7 +20,6 @@ from app.services.agent_registry.resolver import (
resolve_agent_code,
resolve_capabilities,
resolve_conversation_mode,
resolve_effective_role,
resolve_handler_key,
resolve_intent_routes,
resolve_progress_contract,
@@ -102,13 +101,6 @@ def test_resolve_runtime_provider_reads_column_not_legacy_type():
assert resolve_runtime_provider(registered_iframe) == 'iframe'
def test_resolve_effective_role_derives_from_exposure_mode_only():
"""internal 仅派生为内部执行器;历史 conversation_mode 不影响角色。"""
assert resolve_effective_role(_agent(exposure_mode='internal', conversation_mode='task_chat')) == 'internal_executor'
assert resolve_effective_role(_agent(exposure_mode='workspace', conversation_mode='embedded')) == 'user_agent'
assert resolve_effective_role(SimpleNamespace()) == 'user_agent'
def test_resolve_capabilities_normalizes_schema():
"""capabilities 列 dict 应归一化为固定 schema 布尔键。"""
agent = _agent(
@@ -35,7 +35,6 @@ def test_serialize_agent_for_admin_includes_api_key_for_admin_edit():
agent_code='generic',
runtime_provider='dify',
conversation_mode='chat',
exposure_mode='internal',
dify_app_type='chatflow',
iframe_url=None,
category=None,
@@ -52,7 +51,6 @@ def test_serialize_agent_for_admin_includes_api_key_for_admin_edit():
payload = serialize_agent_for_admin(agent)
assert payload['dify_api_key'] == agent.dify_api_key
assert payload['dify_api_key_masked'] == mask_dify_api_key(agent.dify_api_key)
assert payload['effective_role'] == 'internal_executor'
def test_serialize_registry_fields_includes_progress_contract():
@@ -60,7 +58,6 @@ def test_serialize_registry_fields_includes_progress_contract():
agent_code='file_check',
runtime_provider='dify',
conversation_mode='task_chat',
exposure_mode='workspace',
capabilities={'task_progress': True},
bound_schedule_task_id=42,
handler_config={'poll_interval_seconds': 2, 'lock_input_when_running': True},
@@ -77,7 +74,6 @@ def test_serialize_registry_fields_includes_progress_contract():
payload = serialize_registry_fields(file_check)
assert payload['progress_contract']['data_source']['type'] == 'schedule_run'
assert payload['tool_run_progress']['schedule_task_id'] == 42
assert payload['effective_role'] == 'user_agent'
def test_build_tool_run_progress_view_skips_domain_state_contract():
@@ -1,67 +0,0 @@
"""
backend/tests/test_agent_runtime_binding_migration.py
用途:隔离验证阶段 2 Agent 能力绑定迁移可往返执行。
依赖:Alembic Operations、SQLAlchemy 内存数据库、c17c8d9e0f1a 增量迁移。
逻辑:构造阶段 1 最小表,验证 exposure/binding/Run Provider/Job 唯一索引并完整回滚。
"""
from __future__ import annotations
import importlib
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def _pre_schema(engine: sa.Engine) -> None:
"""创建阶段 2 迁移依赖的最小表结构。"""
metadata = sa.MetaData()
sa.Table('agents', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table(
'jobs', metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('domain', sa.String(64)),
sa.Column('job_type', sa.String(64)),
sa.Column('business_ref', sa.String(128)),
sa.Column('status', sa.String(32)),
)
sa.Table(
'shipping_order_extraction_runs', metadata,
sa.Column('id', sa.Integer(), primary_key=True),
)
metadata.create_all(engine)
def test_agent_runtime_binding_migration_round_trip():
"""迁移应创建全部阶段 2 列/表/索引,并可回到阶段 1 结构。"""
engine = sa.create_engine('sqlite:///:memory:')
_pre_schema(engine)
migration = importlib.import_module('migrations.versions.c17c8d9e0f1a_add_agent_runtime_bindings')
with engine.begin() as connection:
original_op = migration.op
migration.op = Operations(MigrationContext.configure(connection))
try:
migration.upgrade()
inspector = sa.inspect(connection)
assert 'exposure_mode' in {item['name'] for item in inspector.get_columns('agents')}
assert 'agent_runtime_bindings' in inspector.get_table_names()
run_columns = {item['name'] for item in inspector.get_columns('shipping_order_extraction_runs')}
assert {
'runtime_binding_id', 'provider_agent_id', 'provider_result_json', 'provider_completed_at',
} <= run_columns
assert 'provider_config_json' not in run_columns
assert 'provider_snapshot_json' not in run_columns
indexes = {item['name']: item for item in inspector.get_indexes('jobs')}
assert indexes['uq_jobs_shipping_order_extraction_active_ref']['unique'] == 1
migration.downgrade()
inspector = sa.inspect(connection)
assert 'exposure_mode' not in {item['name'] for item in inspector.get_columns('agents')}
assert 'agent_runtime_bindings' not in inspector.get_table_names()
run_columns = {item['name'] for item in inspector.get_columns('shipping_order_extraction_runs')}
assert 'runtime_binding_id' not in run_columns
assert 'provider_result_json' not in run_columns
finally:
migration.op = original_op
File diff suppressed because it is too large. Load diff
+25 -1
View File
@@ -6,7 +6,10 @@
from __future__ import annotations
from app.services.shipping_notice.email_allocation_table_parser import parse_email_allocation_tables
from app.services.shipping_notice.email_allocation_table_parser import (
parse_email_allocation_tables,
parse_email_allocation_text,
)
from app.services.shipping_notice.order_supplement_merge import merge_email_supplements
@@ -69,3 +72,24 @@ def test_email_supplement_po_fallback_requires_one_reservation():
]}
result = merge_email_supplements(orders=[_order()], supplements_by_intake={1: ambiguous}, schema_definition=SCHEMA)[0]
assert any(item.get('reason') == 'supplement_relation_ambiguous' for item in result['conflicts'])
def test_email_supplement_plain_text_vertical_table_is_parsed_without_guessing_body_text():
"""Outlook 展平的纵向表头可恢复补充行,尾部邮件正文不会被误当数据。"""
supplement = parse_email_allocation_text(
content_hash='b' * 64,
body_text='''Hello\nallocation_id\nreservation_id\nsource_from_party\nsource_type\nallocated_entity\nmpn\nallocated_qty\nPO#\nA-1\n2000484577\nWelltrust\nDSB CMH\nIEC-CJS\nD4-A08AR12000002\n30\n4518838152\nThank you''',
)
assert supplement['rows'] == [{
'allocation_id': 'A-1', 'reservation_id': '2000484577',
'source_from_party': 'Welltrust', 'source_type': 'DSB CMH',
'allocated_entity': 'IEC-CJS', 'mpn': 'D4-A08AR12000002',
'allocated_qty': '30', 'po_number': '4518838152',
'evidence': supplement['rows'][0]['evidence'], 'table_index': None, 'row_index': 1,
}]
def test_email_supplement_plain_text_deduplicates_quoted_email_rows():
"""转发邮件重复同一正文表时只保留一个事实行,避免制造补充关联冲突。"""
body = '''allocation_id\nreservation_id\nsource_from_party\nsource_type\nallocated_entity\nmpn\nallocated_qty\nPO#\nA-1\n2000484577\nWelltrust\nDSB CMH\nIEC-CJS\nD4-A08AR12000002\n30\n4518838152\nA-1\n2000484577\nWelltrust\nDSB CMH\nIEC-CJS\nD4-A08AR12000002\n30\n4518838152'''
assert len(parse_email_allocation_text(body_text=body, content_hash='c' * 64)['rows']) == 1
@@ -1,65 +0,0 @@
"""
用途:验证内部执行器不会通过用户列表、详情、授权序列化或统一访问策略暴露。
依赖:通用 app/client 测试夹具、JWT、本地 Agent/User 模型。
"""
import pytest
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.core.errors import ForbiddenError
from app.models import Agent, User
from app.services.admin.user_service import serialize_admin_user
from app.services.agent_user_access import require_user_application_access
def _seed_user_access_rows():
"""创建 workspace 应用、内部执行器及带历史脏授权的用户。"""
application = Agent(name='Visible Application', exposure_mode='workspace', is_active=True)
executor = Agent(
name='Hidden Executor', exposure_mode='internal', is_active=True,
runtime_provider='dify', dify_app_type='workflow', dify_app_id='hidden-workflow',
dify_api_key='key',
)
user = User(username='isolated-user', email='isolated-user@example.com', role='user')
admin = User(username='isolated-admin', email='isolated-admin@example.com', role='admin')
user.agents.extend([application, executor])
db.session.add_all([application, executor, user, admin])
db.session.commit()
return application, executor, user, admin
def test_internal_executor_is_hidden_from_public_list_and_admin_user_detail(app, client):
"""公开列表和管理员普通用户详情接口都不能暴露内部执行器。"""
with app.app_context():
application, executor, _user, admin = _seed_user_access_rows()
admin_token = issue_local_access_token(admin)
executor_id = executor.id
application_id = application.id
public_response = client.get('/api/agents/public')
assert public_response.status_code == 200
assert {row['id'] for row in public_response.get_json()} == {application_id}
detail_response = client.get(
f'/api/user/agents/{executor_id}',
headers={'Authorization': f'Bearer {admin_token}'},
)
assert detail_response.status_code == 403
assert detail_response.get_json()['error']['code'] == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN'
def test_internal_executor_is_hidden_from_user_permission_serialization(app):
"""历史脏授权关系不能返回权限矩阵或再次通过用户访问校验。"""
with app.app_context():
application, executor, user, admin = _seed_user_access_rows()
assert serialize_admin_user(user)['agent_ids'] == [application.id]
with pytest.raises(ForbiddenError) as user_error:
require_user_application_access(executor, user)
with pytest.raises(ForbiddenError) as admin_error:
require_user_application_access(executor, admin)
assert user_error.value.code == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN'
assert admin_error.value.code == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN'
@@ -1,104 +0,0 @@
"""
用途:验证内部执行器用户侧历史关系清理迁移的数据边界与幂等性。
依赖:Alembic Operations、SQLite 临时数据库。
"""
import importlib
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def test_internal_executor_user_links_cleanup_is_complete_and_idempotent():
"""迁移只清理 internal 用户关系,并保留 workspace 关系与历史权限申请。"""
engine = sa.create_engine('sqlite:///:memory:')
metadata = sa.MetaData()
agents = sa.Table(
'agents', metadata,
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('exposure_mode', sa.String(20), nullable=False),
)
users = sa.Table(
'users', metadata,
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('default_agent_id', sa.Integer, nullable=True),
)
permissions = sa.Table(
'user_agent_permissions', metadata,
sa.Column('user_id', sa.Integer, primary_key=True),
sa.Column('agent_id', sa.Integer, primary_key=True),
)
favorites = sa.Table(
'user_favorite_agents', metadata,
sa.Column('user_id', sa.Integer, primary_key=True),
sa.Column('agent_id', sa.Integer, primary_key=True),
)
defaults = sa.Table(
'user_default_agents', metadata,
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('user_id', sa.Integer, nullable=False),
sa.Column('agent_id', sa.Integer, nullable=False),
)
requests = sa.Table(
'permission_requests', metadata,
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('agent_id', sa.Integer, nullable=False),
sa.Column('status', sa.String(20), nullable=False),
sa.Column('reviewed_at', sa.DateTime, nullable=True),
)
metadata.create_all(engine)
migration = importlib.import_module(
'migrations.versions.a62b3c4d5e6f_remove_internal_executor_user_links'
)
with engine.begin() as connection:
connection.execute(agents.insert(), [
{'id': 1, 'exposure_mode': 'workspace'},
{'id': 2, 'exposure_mode': 'internal'},
])
connection.execute(users.insert(), [
{'id': 10, 'default_agent_id': 1},
{'id': 11, 'default_agent_id': 2},
])
for table in (permissions, favorites):
connection.execute(table.insert(), [
{'user_id': 10, 'agent_id': 1},
{'user_id': 11, 'agent_id': 2},
])
connection.execute(defaults.insert(), [
{'id': 100, 'user_id': 10, 'agent_id': 1},
{'id': 101, 'user_id': 11, 'agent_id': 2},
])
connection.execute(requests.insert(), [
{'id': 200, 'agent_id': 1, 'status': 'pending'},
{'id': 201, 'agent_id': 2, 'status': 'pending'},
{'id': 202, 'agent_id': 2, 'status': 'approved'},
])
original_op = migration.op
migration.op = Operations(MigrationContext.configure(connection))
try:
migration.upgrade()
migration.upgrade()
finally:
migration.op = original_op
assert connection.execute(sa.select(permissions)).mappings().all() == [
{'user_id': 10, 'agent_id': 1}
]
assert connection.execute(sa.select(favorites)).mappings().all() == [
{'user_id': 10, 'agent_id': 1}
]
assert connection.execute(sa.select(defaults)).mappings().all() == [
{'id': 100, 'user_id': 10, 'agent_id': 1}
]
user_rows = {row['id']: row for row in connection.execute(sa.select(users)).mappings()}
assert user_rows[10]['default_agent_id'] == 1
assert user_rows[11]['default_agent_id'] is None
request_rows = {row['id']: row for row in connection.execute(sa.select(requests)).mappings()}
assert request_rows[200]['status'] == 'pending'
assert request_rows[201]['status'] == 'rejected'
assert request_rows[201]['reviewed_at'] is not None
assert request_rows[202]['status'] == 'approved'
@@ -1,7 +1,7 @@
"""验证已批准 PDF 模板的多 PO 拆分与严格拒识边界。
"""验证已批准 PDF 模板的一单一 PO 约束与严格拒识边界。
依赖:确定性 Profile 订单构建器。
逻辑:只有每行携带唯一 PO 证据时拆分;文档级多 PO 绝不猜测行归属。
逻辑:一份 PDF 正常只允许一个 PO;检测到多个 PO 时必须整体拒识。
"""
from __future__ import annotations
@@ -27,15 +27,14 @@ def _row(po: str, part: str) -> dict:
]}
def test_approved_pdf_splits_explicit_line_pos_into_independent_orders():
"""同一 PDF 的两条明细各有 PO 时,必须生成两份独立订单。"""
def test_approved_pdf_rejects_multiple_pos_in_one_pdf():
"""同一 PDF 的两条明细各有 PO 时,必须整体拒识而不是拆成多单。"""
orders, reason = _build_approved_profile_order_result(
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
definition=DEFINITION, table={'rows': [_row('PO-1', 'P-1'), _row('PO-2', 'P-2')]},
)
assert reason is None
assert len(orders or []) == 2
assert [item['header_fields'][0]['observations'][0]['value'] for item in orders or []] == ['PO-1', 'PO-2']
assert orders is None
assert reason == 'multiple_po_detected'
def test_approved_pdf_keeps_one_order_when_only_one_po_is_proven():
@@ -0,0 +1,102 @@
"""验证订单解析确定性进度事实迁移可完整 upgrade/downgrade。
依赖:Alembic Operations、SQLite 内存数据库、0ab45c6d7e8f 迁移。
逻辑:创建最小前置 Run/Unit/Job 结构,检查新状态约束与事件表字段,再验证受控回滚。
"""
from __future__ import annotations
import importlib
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def _pre_migration_schema(engine: sa.Engine) -> None:
metadata = sa.MetaData()
sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table('agents', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table('jobs', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table(
'shipping_order_extraction_runs',
metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('owner_agent_id', sa.Integer(), nullable=False),
sa.Column('conversation_id', sa.String(100), nullable=False),
sa.Column('status', sa.String(32), nullable=False),
)
sa.Table(
'shipping_order_extraction_units',
metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('plan_id', sa.Integer(), nullable=False),
sa.Column('intake_id', sa.Integer(), nullable=False),
sa.Column('document_id', sa.Integer(), nullable=False),
sa.Column('status', sa.String(32), nullable=False),
)
sa.Table(
'shipping_order_extraction_progress_events',
metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('run_id', sa.Integer(), nullable=False),
sa.Column('workflow_run_id', sa.String(128)),
sa.Column('node_execution_id', sa.String(128)),
sa.Column('event_type', sa.String(64), nullable=False),
sa.Column('node_type', sa.String(64)),
sa.Column('stage_code', sa.String(64)),
sa.Column('event_status', sa.String(32)),
sa.Column('provider_occurred_at', sa.DateTime()),
sa.Column('received_at', sa.DateTime(), nullable=False),
sa.Column('details_json', sa.JSON()),
sa.Column('idempotency_key', sa.String(128), nullable=False),
sa.Column('mapping_version', sa.String(32)),
sa.Column('expires_at', sa.DateTime()),
sa.Column('created_at', sa.DateTime(), nullable=False),
)
metadata.create_all(engine)
def test_order_extraction_progress_facts_migration_round_trip():
migration = importlib.import_module(
'migrations.versions.0ab45c6d7e8f_rebuild_order_extraction_progress_facts'
)
engine = sa.create_engine('sqlite:///:memory:')
_pre_migration_schema(engine)
with engine.begin() as connection:
original_op = migration.op
migration.op = Operations(MigrationContext.configure(connection))
try:
migration.upgrade()
inspector = sa.inspect(connection)
unit_columns = {
column['name'] for column in inspector.get_columns('shipping_order_extraction_units')
}
assert {'reason_code', 'summary_json', 'last_activity_at'} <= unit_columns
event_columns = {
column['name'] for column in inspector.get_columns('shipping_order_extraction_progress_events')
}
assert {
'run_id', 'unit_id', 'document_id', 'sequence_no', 'visibility',
'event_code', 'status', 'occurred_at', 'reason_code', 'summary_json',
} <= event_columns
assert {
'workflow_run_id', 'node_execution_id', 'event_type', 'node_type',
'stage_code', 'event_status', 'provider_occurred_at', 'details_json',
}.isdisjoint(event_columns)
migration.downgrade()
inspector = sa.inspect(connection)
reverted_event_columns = {
column['name'] for column in inspector.get_columns('shipping_order_extraction_progress_events')
}
assert {'workflow_run_id', 'node_execution_id', 'event_type', 'stage_code'} <= reverted_event_columns
reverted_unit_columns = {
column['name'] for column in inspector.get_columns('shipping_order_extraction_units')
}
assert {'reason_code', 'summary_json', 'last_activity_at'}.isdisjoint(reverted_unit_columns)
finally:
migration.op = original_op
@@ -0,0 +1,47 @@
"""验证订单抽取请求快照迁移的升级与回退契约。"""
from __future__ import annotations
import importlib
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def test_order_extraction_request_snapshot_migration_round_trip():
"""发送时审计锚点字段必须独立升级回退,不能与可变执行快照混淆。"""
migration = importlib.import_module(
'migrations.versions.2d3e4f5a6b7c_add_order_extraction_request_snapshot'
)
engine = sa.create_engine('sqlite://')
metadata = sa.MetaData()
sa.Table(
'shipping_order_extraction_runs',
metadata,
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('input_snapshot_hash', sa.String(length=64), nullable=False),
sa.Column('input_snapshot_json', sa.JSON(), nullable=False),
)
metadata.create_all(engine)
with engine.begin() as connection:
original_op = migration.op
migration.op = Operations(MigrationContext.configure(connection))
try:
migration.upgrade()
columns = {
item['name']
for item in sa.inspect(connection).get_columns('shipping_order_extraction_runs')
}
assert {'request_snapshot_hash', 'request_snapshot_json'} <= columns
migration.downgrade()
downgraded = {
item['name']
for item in sa.inspect(connection).get_columns('shipping_order_extraction_runs')
}
assert 'request_snapshot_hash' not in downgraded
assert 'request_snapshot_json' not in downgraded
finally:
migration.op = original_op
@@ -0,0 +1,42 @@
"""验证自动冻结资格范围迁移的升级与回退契约。"""
from __future__ import annotations
import importlib
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def test_profile_auto_freeze_scope_migration_contract():
"""资格范围字段必须可升级回退,且不依赖业务表全量存在。"""
base = importlib.import_module('migrations.versions.0aa34b5c6d7e_add_profile_auto_freeze_qualifications')
migration = importlib.import_module('migrations.versions.0ce67f8a9b01_add_auto_freeze_scope_to_profile_qualification')
engine = sa.create_engine('sqlite://')
metadata = sa.MetaData()
for name in ('shipping_order_document_profiles', 'shipping_order_schema_versions', 'shipping_document_profile_test_suites', 'users'):
sa.Table(name, metadata, sa.Column('id', sa.Integer, primary_key=True))
metadata.create_all(engine)
with engine.begin() as connection:
base.op = Operations(MigrationContext.configure(connection))
base.upgrade()
migration.op = Operations(MigrationContext.configure(connection))
migration.upgrade()
columns = {
item['name']
for item in sa.inspect(connection).get_columns('shipping_document_profile_auto_freeze_qualifications')
}
assert {
'customer_ids_json',
'business_scenarios_json',
'requires_customer_confirmation',
'scope_updated_by_id',
'scope_updated_at',
} <= columns
migration.downgrade()
columns_after_downgrade = {
item['name']
for item in sa.inspect(connection).get_columns('shipping_document_profile_auto_freeze_qualifications')
}
assert 'customer_ids_json' not in columns_after_downgrade
@@ -0,0 +1,641 @@
"""
backend/tests/test_shipping_attachment_selection.py
用途:验证发送阶段附件选择计划只依赖快览事实,并能把计划摘要投影到 Run 响应。
依赖:pytest、纯函数 attachment_selection、订单抽取 Run 序列化服务。
逻辑:覆盖评分/排除/去重/首轮预算,以及 Run API 的 selection_plan 摘要输出。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.shipping_notice.attachment_selection import build_attachment_selection_snapshot
from app.services.shipping_notice.order_extraction_plan import (
_snapshot_documents,
transition_order_extraction_unit,
)
from app.services.shipping_notice.order_extraction_runtime_snapshot import (
resolve_unit_runtime_snapshot,
)
from app.services.shipping_notice.order_extraction_snapshot_selection import (
has_attachment_catalog,
has_selected_attachments,
selected_attachment_keys_by_intake,
should_include_snapshot_document,
)
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_run
from app.services.shipping_notice.order_extraction_workspace_projection import (
serialize_workspace_run_documents,
)
def _preview_intake(intake_no: str, attachments: list[dict], *, subject: str = '', body_text: str = ''):
"""构造最小快览 Intake 假对象,避免测试选择计划时依赖数据库。"""
return SimpleNamespace(
intake_no=intake_no,
structured_result_json={
'email': {
'subject': subject,
'body_text': body_text,
'body_html_tables': [],
},
'attachments': attachments,
},
)
def test_attachment_selection_snapshot_prefers_po_hints_and_skips_risky_duplicates():
"""首轮仅选 2 个高相关附件;后续候选进入未来批次,风险附件和重复哈希必须稳定跳过。"""
snapshot = build_attachment_selection_snapshot(intakes=[
_preview_intake(
'SNI-A',
[
{
'attachment_key': 'po-1.pdf',
'filename': 'PO_451883815A.pdf',
'mime_type': 'application/pdf',
'size': 48000,
'content_hash': 'a' * 64,
'ready_for_extraction': True,
'catalog_reason': 'ready_for_extraction',
},
{
'attachment_key': 'logo.png',
'filename': 'customer-logo.png',
'mime_type': 'image/png',
'size': 4096,
'content_hash': 'b' * 64,
'ready_for_extraction': False,
'is_inline_resource': True,
'catalog_reason': 'inline_resource',
},
{
'attachment_key': 'archive.zip',
'filename': 'orders.zip',
'mime_type': 'application/zip',
'size': 120000,
'content_hash': 'c' * 64,
'ready_for_extraction': False,
'catalog_reason': 'archive',
},
],
subject='PO 451883815A and booking details',
),
_preview_intake(
'SNI-B',
[
{
'attachment_key': 'po-1-duplicate.pdf',
'filename': 'PO_451883815A_copy.pdf',
'mime_type': 'application/pdf',
'size': 48000,
'content_hash': 'a' * 64,
'ready_for_extraction': True,
'catalog_reason': 'ready_for_extraction',
},
{
'attachment_key': 'booking.xlsx',
'filename': 'booking_451883816.xlsx',
'mime_type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'size': 56000,
'content_hash': 'd' * 64,
'ready_for_extraction': True,
'catalog_reason': 'ready_for_extraction',
},
{
'attachment_key': 'third.docx',
'filename': 'order_notes.docx',
'mime_type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'size': 42000,
'content_hash': 'e' * 64,
'ready_for_extraction': True,
'catalog_reason': 'ready_for_extraction',
},
],
body_text='Please process PO 451883816 first.',
),
])
assert snapshot['selection_version'] == 'shipping_notice_attachment_selection.v1'
# 内嵌签名资源不属于业务附件,不计入选择计划数量。
assert snapshot['total_attachment_count'] == 5
assert snapshot['eligible_attachment_count'] == 3
assert snapshot['selected_attachment_count'] == 2
assert snapshot['planned_attachment_count'] == 3
assert snapshot['pending_expansion_attachment_count'] == 1
assert snapshot['pending_expansion_batches'] == {'2': 1}
selected = [item for item in snapshot['items'] if item['selected']]
assert [item['filename'] for item in selected] == ['PO_451883815A.pdf', 'booking_451883816.xlsx']
by_name = {item['filename']: item for item in snapshot['items']}
assert by_name['PO_451883815A_copy.pdf']['skip_reason_codes'] == ['duplicate_content_hash']
assert 'customer-logo.png' not in by_name
assert by_name['orders.zip']['skip_reason_codes'] == ['catalog_reason:archive']
assert by_name['order_notes.docx']['skip_reason_codes'] == []
assert by_name['order_notes.docx']['planned_selection_batch'] == 2
assert by_name['PO_451883815A.pdf']['group_key'] == '451883815A'
def test_attachment_selection_snapshot_stops_at_total_byte_budget():
"""累计深度解析字节超预算时,后续附件必须标记为预算停止而非静默扩批。"""
snapshot = build_attachment_selection_snapshot(
intakes=[_preview_intake('SNI-BYTE', [
{
'attachment_key': 'first.pdf', 'filename': 'first.pdf', 'mime_type': 'application/pdf',
'size': 20, 'content_hash': 'a' * 64, 'ready_for_extraction': True,
'catalog_reason': 'ready_for_extraction',
},
{
'attachment_key': 'second.pdf', 'filename': 'second.pdf', 'mime_type': 'application/pdf',
'size': 20, 'content_hash': 'b' * 64, 'ready_for_extraction': True,
'catalog_reason': 'ready_for_extraction',
},
])],
max_total_bytes=30,
)
by_name = {item['filename']: item for item in snapshot['items']}
assert snapshot['planned_total_bytes'] == 20
assert by_name['first.pdf']['selected'] is True
assert by_name['second.pdf']['skip_reason_codes'] == ['budget_total_bytes']
def test_attachment_selection_snapshot_excludes_inline_resources_from_counts():
"""邮件签名图不属于用户业务附件,不能占用识别计划的附件数量或预算。"""
snapshot = build_attachment_selection_snapshot(intakes=[
_preview_intake(
'SNI-A',
[
{
'attachment_key': 'signature.gif',
'filename': 'signature.gif',
'mime_type': 'image/gif',
'size': 1024,
'content_hash': 'a' * 64,
'ready_for_extraction': False,
'is_inline_resource': True,
'catalog_reason': 'inline_resource',
},
{
'attachment_key': 'po-1.pdf',
'filename': 'PO_4518838152.pdf',
'mime_type': 'application/pdf',
'size': 48000,
'content_hash': 'b' * 64,
'ready_for_extraction': True,
'catalog_reason': 'ready_for_extraction',
},
{
'attachment_key': 'po-2.pdf',
'filename': 'PO_4518838154.pdf',
'mime_type': 'application/pdf',
'size': 48000,
'content_hash': 'c' * 64,
'ready_for_extraction': True,
'catalog_reason': 'ready_for_extraction',
},
],
),
])
assert snapshot['total_attachment_count'] == 2
assert snapshot['eligible_attachment_count'] == 2
assert snapshot['selected_attachment_count'] == 2
assert [item['filename'] for item in snapshot['items']] == [
'PO_4518838152.pdf', 'PO_4518838154.pdf',
]
def test_serialize_order_extraction_run_includes_selection_plan_summary(monkeypatch):
"""Run 用户态响应应暴露计划摘要计数,但不能泄露具体正文或打分细节。"""
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workspace_projection.serialize_workspace_run',
lambda _run: {
'summary': {
'total_documents': 0,
'pending_documents': 0,
'processing_documents': 0,
'completed_documents': 0,
'review_required_documents': 0,
'failed_documents': 0,
'candidate_count': 0,
},
'current_activity': None,
'available_actions': ['view_details'],
},
)
run = SimpleNamespace(
run_no='SNER-SELECTION',
owner_agent_id=1,
conversation_id='conv-selection',
status='queued',
phase='queued',
schema_version_id=1,
attempt_count=0,
reparse_source=None,
superseding_run=None,
reparse_reason=None,
superseded_at=None,
result_json=None,
error_code=None,
created_at=None,
updated_at=None,
started_at=None,
finished_at=None,
extraction_plan=SimpleNamespace(units=[
SimpleNamespace(
selection_batch=1,
status='candidate_ready',
reason_code=None,
result_json={
'orders': [{
'lines': [{'fields': []}],
'conflicts': [{'reason': 'supplement_relation_ambiguous'}],
}],
},
retry_status='running',
technical_failure_reason_code=None,
),
SimpleNamespace(
selection_batch=1,
status='failed',
reason_code=None,
result_json=None,
retry_status='failed',
technical_failure_reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
),
SimpleNamespace(
selection_batch=2,
status='review_required',
reason_code='required_field_missing',
result_json={'orders': []},
retry_status='review_required',
technical_failure_reason_code=None,
),
]),
input_snapshot_json={
'schema': {
'version': 1,
'checksum': 'a' * 64,
'definition': {
'fields': [{'field_code': 'reservation_id', 'field_id': 'reservation-id'}],
},
},
'intakes': [{'intake_no': 'SNI-1'}],
'attachment_selection': {
'selection_version': 'shipping_notice_attachment_selection.v1',
'max_initial_attachments': 2,
'max_initial_concurrency': 2,
'expansion_batch_size': 2,
'max_total_attachments': 6,
'total_attachment_count': 5,
'eligible_attachment_count': 3,
'selected_attachment_count': 2,
'planned_attachment_count': 3,
'pending_expansion_attachment_count': 1,
'pending_expansion_batches': {'2': 1},
'group_count': 2,
'items': [
{'selected': True, 'selection_batch': 1, 'filename': 'must-not-leak.pdf', 'score': 999},
{'selected': True, 'selection_batch': 1},
{'selected': False, 'planned_selection_batch': 2, 'skip_reason_codes': []},
{'selected': False, 'skip_reason_codes': ['duplicate_content_hash']},
{'selected': False, 'skip_reason_codes': ['catalog_reason:inline_resource']},
],
},
},
)
payload = serialize_order_extraction_run(run)
assert payload['selection_plan'] == {
'selection_version': 'shipping_notice_attachment_selection.v1',
'max_initial_attachments': 2,
'max_initial_concurrency': 2,
'expansion_batch_size': 2,
'max_total_attachments': 6,
'max_total_bytes': 0,
'max_runtime_seconds': 0,
'input_total_bytes': 0,
'planned_total_bytes': 0,
'total_attachment_count': 5,
'eligible_attachment_count': 3,
'selected_attachment_count': 2,
'planned_attachment_count': 3,
'pending_expansion_attachment_count': 1,
'pending_expansion_batches': {'2': 1},
'skipped_attachment_count': 2,
'duplicate_attachment_count': 1,
'budget_limited_attachment_count': 0,
'group_count': 2,
}
assert payload['unit_summary'] == {
'total_units': 3,
'selected_units': 3,
'retrying_units': 1,
'pending_retry_units': 0,
'failed_units': 1,
'review_required_units': 1,
'succeeded_units': 0,
'selection_batches': {'1': 2, '2': 1},
'review_required_reason_codes': ['required_field_missing'],
'expansion_trigger_reason_codes': [
'missing_reservation_id',
'required_field_missing',
'supplement_relation_ambiguous',
],
'technical_failure_reason_codes': ['SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT'],
}
assert 'must-not-leak' not in str(payload)
def test_snapshot_selection_helpers_keep_only_selected_attachment_documents():
"""Run snapshot 应只包含本次计划选中的附件,正文补充事实必须保留。"""
selection_snapshot = {
'total_attachment_count': 4,
'selected_attachment_count': 2,
'items': [
{'intake_no': 'SNI-A', 'attachment_key': 'po-1.pdf', 'selected': True},
{'intake_no': 'SNI-A', 'attachment_key': 'copy.pdf', 'selected': False},
{'intake_no': 'SNI-B', 'attachment_key': 'booking.xlsx', 'selected': True},
],
}
assert has_attachment_catalog(selection_snapshot) is True
assert has_selected_attachments(selection_snapshot) is True
assert selected_attachment_keys_by_intake(selection_snapshot) == {
'SNI-A': {'po-1.pdf'},
'SNI-B': {'booking.xlsx'},
}
assert should_include_snapshot_document(
selection_snapshot=selection_snapshot,
intake_no='SNI-A',
document_type='email_body',
attachment_key='body',
) is True
assert should_include_snapshot_document(
selection_snapshot=selection_snapshot,
intake_no='SNI-A',
document_type='attachment',
attachment_key='po-1.pdf',
) is True
assert should_include_snapshot_document(
selection_snapshot=selection_snapshot,
intake_no='SNI-A',
document_type='attachment',
attachment_key='copy.pdf',
) is False
def test_snapshot_selection_helpers_fall_back_to_all_documents_for_non_catalog_inputs():
"""普通单文件没有附件目录时,不应误把唯一文档过滤掉。"""
selection_snapshot = {'total_attachment_count': 0, 'selected_attachment_count': 0, 'items': []}
assert has_attachment_catalog(selection_snapshot) is False
assert has_selected_attachments(selection_snapshot) is False
assert should_include_snapshot_document(
selection_snapshot=selection_snapshot,
intake_no='SNI-FILE',
document_type='attachment',
attachment_key='file',
) is True
def test_snapshot_documents_include_selection_metadata():
"""计划编译应把选择批次、原因码、分组键和预算摘要映射到附件单元。"""
run = SimpleNamespace(
input_snapshot_json={
'attachment_selection': {
'max_initial_attachments': 2,
'max_initial_concurrency': 2,
'items': [
{
'intake_no': 'SNI-A',
'attachment_key': 'po-1.pdf',
'selected': True,
'selection_batch': 1,
'score_reasons': ['type_pdf', 'po_hint_detected'],
'group_key': '451883815A',
},
{
'intake_no': 'SNI-A',
'attachment_key': 'copy.pdf',
'selected': False,
'score_reasons': ['filename_copy_hint'],
'group_key': '451883815A',
},
],
},
'intakes': [{
'intake_id': 11,
'intake_no': 'SNI-A',
'documents': [
{
'document_id': 101,
'document_type': 'attachment',
'attachment_key': 'po-1.pdf',
'content_hash': 'a' * 64,
},
{
'document_id': 102,
'document_type': 'attachment',
'attachment_key': 'copy.pdf',
'content_hash': 'b' * 64,
},
],
}],
},
)
documents = _snapshot_documents(run)
assert documents[0]['selection_batch'] == 1
assert documents[0]['selection_reason_codes'] == ['type_pdf', 'po_hint_detected']
assert documents[0]['group_key'] == '451883815A'
assert documents[0]['budget_cost'] == {
'initial_attachment_budget': 2,
'initial_concurrency_budget': 2,
'expansion_batch_size': 0,
'max_total_attachments': 0,
'selected_in_batch': 1,
}
assert documents[1]['selection_batch'] is None
assert documents[1]['selection_reason_codes'] == ['filename_copy_hint']
def test_transition_order_extraction_unit_tracks_retry_and_technical_failure(monkeypatch):
"""附件单元失败与重试时应更新 retry_status 和 technical_failure_reason_code。"""
audit_calls: list[dict] = []
monkeypatch.setattr(
'app.services.shipping_notice.audit_service.append_shipping_audit_event',
lambda **kwargs: audit_calls.append(kwargs),
)
plan = SimpleNamespace(units=[], run=SimpleNamespace(run_no='SNER-PLAN'))
unit = SimpleNamespace(
id=1,
status='pending',
attempt_count=0,
reason_code=None,
summary_json=None,
result_json=None,
error_code=None,
error_message=None,
last_activity_at=None,
started_at=None,
finished_at=None,
retry_status='not_started',
technical_failure_reason_code=None,
plan=plan,
)
plan.units = [unit]
transition_order_extraction_unit(unit, target_status='routing')
assert unit.retry_status == 'running'
assert unit.technical_failure_reason_code is None
transition_order_extraction_unit(
unit,
target_status='failed',
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
error_message='timeout',
)
assert unit.retry_status == 'failed'
assert unit.technical_failure_reason_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT'
transition_order_extraction_unit(unit, target_status='pending')
assert unit.retry_status == 'pending_retry'
assert unit.technical_failure_reason_code is None
assert audit_calls
def test_runtime_snapshot_keeps_frozen_ready_layout_without_db_lookup(monkeypatch):
"""冻结快照已有 ready layout 时,Worker 不应回读当前 Document。"""
run = SimpleNamespace(
input_snapshot_json={
'intakes': [{
'intake_id': 11,
'documents': [{
'document_id': 101,
'layout_snapshot': {'status': 'ready', 'layout_candidate': {'pages': []}},
'layout_schema_candidates': [{'mapping_status': 'accepted'}],
}],
}],
},
)
unit = SimpleNamespace(intake_id=11, document_id=101)
monkeypatch.setattr('app.services.shipping_notice.order_extraction_runtime_snapshot.db.session.get', lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('should not query db')))
intake, document = resolve_unit_runtime_snapshot(run, unit)
assert intake['intake_id'] == 11
assert document['layout_snapshot']['status'] == 'ready'
assert document['layout_schema_candidates'] == [{'mapping_status': 'accepted'}]
def test_runtime_snapshot_hydrates_current_ready_layout_when_snapshot_is_stale(monkeypatch):
"""Run 先创建后布局就绪时,Worker 应补读当前 ready layout 和 schema candidates。"""
run = SimpleNamespace(
input_snapshot_json={
'schema': {'definition': {'fields': []}},
'intakes': [{
'intake_id': 11,
'documents': [{
'document_id': 101,
'layout_snapshot': {'status': 'queued'},
'layout_schema_candidates': [],
}],
}],
},
)
unit = SimpleNamespace(intake_id=11, document_id=101)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_runtime_snapshot.db.session.get',
lambda model, document_id: SimpleNamespace(id=document_id),
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_runtime_snapshot.current_layout_snapshot',
lambda document: {'status': 'ready', 'layout_candidate': {'pages': [{'page_no': 1, 'tables': []}]}},
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_runtime_snapshot.map_layout_document_to_schema',
lambda layout_candidate, contract: [{'mapping_status': 'accepted', 'issues': []}],
)
_intake, document = resolve_unit_runtime_snapshot(run, unit)
assert document['layout_snapshot']['status'] == 'ready'
assert document['layout_schema_candidates'] == [{'mapping_status': 'accepted', 'issues': []}]
def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch):
"""工作台文档详情应直接暴露单元选择、预算和失败事实。"""
run = SimpleNamespace(
id=1,
input_snapshot_json={
'schema': {'definition': {'fields': []}},
'intakes': [{
'intake_id': 11,
'documents': [{
'document_id': 101,
'document_type': 'attachment',
'filename': 'po-1.pdf',
}],
}],
},
extraction_plan=SimpleNamespace(units=[SimpleNamespace(
id=7,
document_id=101,
status='failed',
reason_code=None,
selection_batch=1,
group_key='451883815A',
retry_status='failed',
technical_failure_reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
budget_cost_json={
'initial_attachment_budget': 2,
'initial_concurrency_budget': 2,
'selected_in_batch': 1,
},
result_json={},
)]),
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workspace_projection._latest_route_decisions',
lambda _run: {},
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workspace_projection._latest_progress_events',
lambda _run: ({}, None),
)
items = serialize_workspace_run_documents(run)
assert items == [{
'unit_id': 7,
'document_id': 101,
'file_name': 'po-1.pdf',
'status': 'failed',
'selection_batch': 1,
'group_key': '451883815A',
'retry_status': 'failed',
'technical_failure_reason_code': 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
'budget_cost': {
'initial_attachment_budget': 2,
'initial_concurrency_budget': 2,
'selected_in_batch': 1,
},
'po_number': None,
'line_count': 0,
'profile': None,
'email_supplement': {
'status': 'none',
'relation_codes': [],
'conflict_count': 0,
'reservation_id_status': 'unavailable',
'source_type_status': 'unavailable',
},
'reason_code': 'technical_failure',
'review_details': [],
'available_actions': [],
}]
@@ -17,6 +17,7 @@ from app.models import (
FileAsset,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingCustomer,
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileAudit,
ShippingDocumentProfileTestSuite,
@@ -136,8 +137,8 @@ def _publishable_v2_draft(profile: ShippingOrderDocumentProfile) -> None:
}
def test_profile_blind_test_approval_does_not_enable_auto_freeze(app):
"""关键断言:盲测批准与自动冻结资格独立,首版仍只能人工确认。"""
def test_profile_blind_test_approval_enables_current_auto_freeze_qualification(app):
"""关键断言:盲测批准应升级当前模板版本资格,避免审批结果无法生效。"""
with app.app_context():
profile, user, documents = _published_profile_with_samples()
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
@@ -156,7 +157,12 @@ def test_profile_blind_test_approval_does_not_enable_auto_freeze(app):
assert executed['latest_run']['status'] == 'passed'
approved = quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
assert approved['status'] == 'approved'
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
qualification = quality.qualification_summary(profile)
assert qualification['status'] == 'auto_freeze_approved'
assert qualification['quality_suite_id'] == suite['id']
# 盲测只批准解析质量,未配置范围时仍要求人工确认。
assert qualification['requires_customer_confirmation'] is True
with pytest.raises(Exception) as immutable:
quality.add_sample(
suite_id=suite['id'], document_id=documents[0].id, table_id='other',
@@ -308,6 +314,41 @@ def test_profile_auto_freeze_qualification_can_be_suspended_independently(app):
assert published['auto_freeze_qualification']['status'] == 'manual_confirmation'
def test_profile_auto_freeze_scope_can_be_configured_independently(app):
"""关键断言:客户/业务场景授权范围可独立配置,并写入模板审计摘要。"""
from app.services.shipping_notice import order_document_profile_service as profiles
with app.app_context():
profile, user, _documents = _published_profile_with_samples()
_publishable_v2_draft(profile)
db.session.commit()
published = profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
customer = ShippingCustomer(standard_name='Scope Customer', short_code='SCOP')
db.session.add(customer)
db.session.commit()
qualification = quality.configure_auto_freeze_qualification_scope(
profile_id=profile.id,
actor_id=user.id,
customer_ids=[customer.id],
business_scenarios=['shipping_notice_order'],
requires_customer_confirmation=False,
)
assert qualification.customer_ids_json == [customer.id]
assert qualification.business_scenarios_json == ['shipping_notice_order']
assert qualification.requires_customer_confirmation is False
refreshed = profiles.payload(db.session.get(ShippingOrderDocumentProfile, profile.id))
assert refreshed['auto_freeze_qualification']['customer_scope_configured'] is True
assert refreshed['auto_freeze_qualification']['business_scenario_scope_configured'] is True
assert refreshed['auto_freeze_qualification']['requires_customer_confirmation'] is False
assert published['auto_freeze_qualification']['status'] == 'manual_confirmation'
audit = ShippingOrderDocumentProfileAudit.query.filter_by(profile_id=profile.id).order_by(
ShippingOrderDocumentProfileAudit.id.desc(),
).first()
assert audit.event_type == 'auto_freeze_scope_configured'
def test_profile_change_supersedes_stale_draft_suite_and_creates_current_suite(app):
"""保存模板后必须建立新 checksum 的盲测集,旧草稿真值不得继续阻断或背书。"""
with app.app_context():
@@ -1,5 +1,6 @@
from email.message import EmailMessage
from pathlib import Path
from unittest.mock import patch
import pytest
@@ -93,6 +94,44 @@ def _minimal_pdf_bytes(marker: str) -> bytes:
return bytes(out)
def test_extract_notice_text_preview_only_skips_pdf_loader_and_ocr(tmp_path):
"""上传快览只返回普通文件元信息,绝不能同步调用 PDF Loader 或 OCR。"""
from app.services.shipping_notice.notice_upload import extract_notice_text
path = tmp_path / "order.pdf"
path.write_bytes(_minimal_pdf_bytes("PREVIEW-ONLY"))
with patch('app.services.shipping_notice.notice_upload.loader_pdf.run') as pdf_loader, patch(
'app.services.shipping_notice.notice_upload.ocr.run',
) as ocr_loader:
text, meta = extract_notice_text(path, preview_only=True)
assert text == ""
assert meta == {
'warnings': [],
'file_type': 'pdf',
'content_mode': 'preview',
}
pdf_loader.assert_not_called()
ocr_loader.assert_not_called()
def test_extract_notice_text_preview_only_skips_plain_text_read(tmp_path):
"""快览对文本文件也只返回目录元信息,不能读取或持久化正文。"""
from app.services.shipping_notice.notice_upload import extract_notice_text
path = tmp_path / "order.txt"
path.write_text("PO Number: 4510039227", encoding="utf-8")
with patch.object(Path, "read_bytes", side_effect=AssertionError("preview must not read content")):
text, meta = extract_notice_text(path, preview_only=True)
assert text == ""
assert meta == {
'warnings': [],
'file_type': 'txt',
'content_mode': 'preview',
}
_TINY_PNG = (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f\x00"
@@ -290,6 +329,33 @@ def test_extract_eml_skips_signature_inline_image(tmp_path):
assert "--- attachment: signature.png ---" not in text
def test_preview_eml_skips_signature_inline_image_from_attachment_count(tmp_path):
"""签名图不计数,但快览和深度解析必须保留一致的业务附件键。"""
from app.services.shipping_notice.notice_upload import extract_notice_text
raw = _build_eml(
subject="Two POs",
body="Body with two PO attachments.",
attachments=[
("order-1.pdf", "application/pdf", _minimal_pdf_bytes("PO-ONE")),
("order-2.pdf", "application/pdf", _minimal_pdf_bytes("PO-TWO")),
],
inline_images=[("signature.png", "<sig001@example.com>", _TINY_PNG)],
)
path = tmp_path / "preview-with-signature.eml"
path.write_bytes(raw)
_, preview_meta = extract_notice_text(path, eml_attachment_mode="preview")
_, deep_meta = extract_notice_text(path)
assert preview_meta["attachment_count"] == 2
assert preview_meta["attachment_registered_count"] == 2
assert [item["filename"] for item in preview_meta["attachments"]] == ["order-1.pdf", "order-2.pdf"]
assert [item["attachment_key"] for item in preview_meta["attachments"]] == ["att-002", "att-003"]
assert [item["attachment_key"] for item in deep_meta["attachments"]] == ["att-002", "att-003"]
assert any(str(w).startswith("eml_inline_resources_skipped:") for w in preview_meta["warnings"])
def test_extract_eml_duplicate_attachments(tmp_path):
"""同信内重复内容哈希的附件标记 duplicate,不重复抽取。"""
from app.services.shipping_notice.notice_upload import extract_notice_text
+289 -66
View File
@@ -8,6 +8,8 @@ backend/tests/test_shipping_notice_intakes.py
from __future__ import annotations
import threading
import time
from datetime import datetime
from unittest.mock import patch
@@ -932,6 +934,186 @@ def _seed_parsed_intake(user_id: int, *, intake_no: str = 'SNI-TEST-0001', hash_
return asset, intake
def test_run_intake_parse_for_pdf_uses_preview_and_creates_no_documents(app, shipping_user, monkeypatch):
"""普通文件上传只写快览,深度抽取与 Document 物化必须留给发送阶段。"""
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
with app.app_context():
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PDF-PREVIEW')
asset.original_filename = 'order.pdf'
asset.mime_type = 'application/pdf'
intake.parse_status = 'parsing'
db.session.commit()
calls: list[dict] = []
def _preview_result(_asset, **kwargs):
calls.append(kwargs)
return NoticeIntakeResult(
filename='order.pdf', source_type='pdf', source_file_type='application/pdf',
text='', warnings=[], meta={'file_type': 'pdf', 'content_mode': 'preview'},
content_hash=str(asset.content_hash), file_size=12, status='accepted', saved_path=None,
)
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
_preview_result,
)
result = run_intake_parse(intake, asset)
assert result['status'] == 'parsed'
assert calls == [{
'eml_attachment_mode': 'preview', 'retain_payloads': False, 'preview_only': True,
}]
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake.id).count() == 0
def test_materialize_single_file_reextracts_deeply_after_send(app, shipping_user, monkeypatch):
"""发送阶段物化普通文件时必须重新走深度抽取,而不是复用上传快览空文本。"""
from app.services.shipping_notice.order_extraction_materialization import (
ensure_order_extraction_input_documents,
)
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
with app.app_context():
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PDF-MATERIALIZE')
asset.original_filename = 'order.pdf'
asset.mime_type = 'application/pdf'
db.session.commit()
calls: list[dict] = []
def _deep_result(_asset, **kwargs):
calls.append(kwargs)
return NoticeIntakeResult(
filename='order.pdf', source_type='pdf', source_file_type='application/pdf',
text='PO Number: 4510039227\\nSKU-A qty 1', warnings=[], meta={'file_type': 'pdf'},
content_hash=str(asset.content_hash), file_size=12, status='accepted', saved_path=None,
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_materialization.extract_notice_from_asset',
_deep_result,
)
persisted: list[NoticeIntakeResult] = []
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_materialization.persist_intake_documents',
lambda **kwargs: persisted.append(kwargs['result']) or {'document_count': 1},
)
ensure_order_extraction_input_documents(
intakes=[intake], attachment_selection={}, schema_definition={'fields': []},
)
assert calls == [{'eml_attachment_mode': 'deep'}]
assert len(persisted) == 1
assert persisted[0].text.startswith('PO Number:')
def test_selected_eml_attachments_use_bounded_parallel_deep_extraction(app, shipping_user, monkeypatch):
"""首轮附件深度抽取最多并发 2,ORM 持久化仍留在调用线程处理。"""
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
import app.services.shipping_notice.order_extraction_materialization as materialization
with app.app_context():
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PARALLEL-MATERIALIZE')
asset.original_filename = 'orders.eml'
asset.mime_type = 'message/rfc822'
db.session.commit()
active = 0
peak = 0
lock = threading.Lock()
def _preview_result(_asset, **kwargs):
assert kwargs == {'eml_attachment_mode': 'preview', 'retain_payloads': True}
return NoticeIntakeResult(
filename='orders.eml', source_type='email', source_file_type='message/rfc822',
text='mail preview', warnings=[],
meta={'attachments': [
{
'attachment_key': f'order-{index}.pdf', 'filename': f'order-{index}.pdf',
'mime_type': 'application/pdf', '_payload_bytes': f'pdf-{index}'.encode(),
}
for index in range(3)
]},
content_hash=str(asset.content_hash), file_size=12, status='accepted', saved_path=None,
)
def _deep_extract(*, payload, filename, mime_type, flask_app):
nonlocal active, peak
assert flask_app is app
with lock:
active += 1
peak = max(peak, active)
time.sleep(0.03)
with lock:
active -= 1
return f'text:{filename}', {'warnings': []}
monkeypatch.setattr(materialization, 'extract_notice_from_asset', _preview_result)
monkeypatch.setattr(materialization, '_parse_attachment_payload', _deep_extract)
result = materialization._build_selected_eml_result(
intake=intake,
parent_asset=asset,
selected_attachment_keys={'order-0.pdf', 'order-1.pdf', 'order-2.pdf'},
max_concurrency=2,
)
assert peak == 2
assert [item['extracted_text'] for item in result.meta['attachments']] == [
'text:order-0.pdf', 'text:order-1.pdf', 'text:order-2.pdf',
]
def test_selected_normal_files_use_global_bounded_parallel_extraction(app, shipping_user, monkeypatch):
"""不同普通文件共享首轮并发预算,完成顺序不得改变主线程持久化顺序。"""
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
import app.services.shipping_notice.order_extraction_materialization as materialization
with app.app_context():
first_asset, first_intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PARALLEL-PDF-1')
second_asset, second_intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PARALLEL-PDF-2')
first_asset.original_filename = 'first.pdf'
second_asset.original_filename = 'second.pdf'
first_asset.mime_type = second_asset.mime_type = 'application/pdf'
db.session.commit()
active = 0
peak = 0
lock = threading.Lock()
persisted: list[str] = []
def _deep_result(*, parent_asset, flask_app):
nonlocal active, peak
assert flask_app is app
with lock:
active += 1
peak = max(peak, active)
time.sleep(0.03)
with lock:
active -= 1
return NoticeIntakeResult(
filename=parent_asset.original_filename, source_type='pdf', source_file_type='application/pdf',
text='PO 4510000001', warnings=[], meta={}, content_hash=str(parent_asset.content_hash),
file_size=12, status='accepted', saved_path=None,
)
monkeypatch.setattr(materialization, '_build_single_file_result_in_thread', _deep_result)
monkeypatch.setattr(
materialization,
'persist_intake_documents',
lambda **kwargs: persisted.append(kwargs['result'].filename) or {'document_count': 1},
)
materialization.ensure_order_extraction_input_documents(
intakes=[first_intake, second_intake],
attachment_selection={'max_initial_concurrency': 2},
schema_definition={'fields': []},
)
assert peak == 2
assert persisted == ['first.pdf', 'second.pdf']
def test_create_batch_from_intakes_marks_consumed_and_links_task(app, shipping_user, monkeypatch):
with app.app_context():
asset, intake = _seed_parsed_intake(shipping_user.id)
@@ -2461,6 +2643,51 @@ def test_recover_stale_parse_job_resets_stuck_parsing_intake(app, shipping_user)
assert finished.status == 'success'
def test_recover_stale_order_extraction_job_requeues_run(app, shipping_user):
"""订单抽取 Worker 退出后,超时回收须使 Job 和 Run 一起回到可重试状态。"""
with app.app_context():
from datetime import timedelta
from app.jobs.types import JobType
from app.models import Job, ShippingOrderExtractionRun
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
run = ShippingOrderExtractionRun(
run_no='SNER-STALE-RECOVERY',
user_id=shipping_user.id,
owner_agent_id=shipping_user.id,
conversation_id='stale-recovery-test',
schema_version_id=1,
input_snapshot_hash='stale-recovery-hash',
input_snapshot_json={'intakes': []},
idempotency_key='stale-recovery-idempotency-key',
status='processing',
phase='deterministic_parsing',
)
db.session.add(run)
db.session.flush()
job = Job(
domain='shipping_notice',
job_type=JobType.SHIPPING_ORDER_EXTRACTION.value,
status='running',
business_ref=run.run_no,
payload_json={'run_no': run.run_no},
attempts=1,
max_attempts=3,
started_at=datetime.utcnow() - timedelta(hours=1),
locked_at=datetime.utcnow() - timedelta(hours=1),
locked_by='dead-worker',
)
db.session.add(job)
db.session.commit()
count, _ = recover_stale_shipping_notice_jobs()
assert count >= 1
db.session.expire_all()
assert db.session.get(Job, job.id).status == 'queued'
assert db.session.get(ShippingOrderExtractionRun, run.id).status == 'queued'
def test_recover_exhausted_parse_job_marks_intake_parse_failed_and_clears_stage2(
app, shipping_user,
):
@@ -2775,7 +3002,7 @@ def test_stale_parse_lease_cannot_overwrite_after_recovery(app, shipping_user, m
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
lambda _asset: NoticeIntakeResult(
lambda _asset, **_kwargs: NoticeIntakeResult(
filename='notice.txt',
source_type='manual',
source_file_type='text/plain',
@@ -2952,7 +3179,7 @@ def test_parse_writeback_skips_cancel_during_extract(app, shipping_user, monkeyp
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
lambda _asset: NoticeIntakeResult(
lambda _asset, **_kwargs: NoticeIntakeResult(
filename='notice.txt',
source_type='manual',
source_file_type='text/plain',
@@ -2976,9 +3203,10 @@ def test_parse_writeback_skips_cancel_during_extract(app, shipping_user, monkeyp
def test_run_intake_parse_persists_eml_attachment_texts(app, shipping_user, monkeypatch):
"""
FileAsset → run_intake_parse → DB:EML 附件独立文本应持久化进 structured_result_json。
FileAsset → run_intake_parse → DB:shipping_notice 用途的 EML 上传仅持久化附件目录。
核心逻辑:mock 读取资产字节为含文本附件的 EML,断言 attachment_count 与 extracted_text 落库。
核心逻辑:阶段 1 上传快览只保留邮件头/正文/附件目录,不得把附件全文、派生资产或 Document
混入 Intake 摘要;详情接口也只能回放目录事实。
"""
from email.message import EmailMessage
@@ -3049,14 +3277,18 @@ def test_run_intake_parse_persists_eml_attachment_texts(app, shipping_user, monk
assert structured.get('email', {}).get('subject') == 'Intake EML Persist'
attachments = structured.get('attachments') or []
assert len(attachments) == 2
texts = {row['filename']: row.get('extracted_text') for row in attachments}
assert 'PO-PERSIST-LINE-001' in str(texts.get('order-a.txt') or '')
assert 'PO-PERSIST-LINE-002' in str(texts.get('order-b.txt') or '')
assert 'PO-PERSIST-LINE-001' in str(refreshed.extracted_text or '')
by_name = {str(row.get('filename') or ''): row for row in attachments}
assert by_name['order-a.txt'].get('parse_status') == 'ready_for_extraction'
assert by_name['order-b.txt'].get('parse_status') == 'ready_for_extraction'
assert by_name['order-a.txt'].get('ready_for_extraction') is True
assert by_name['order-b.txt'].get('ready_for_extraction') is True
assert all('extracted_text' not in row for row in attachments)
assert 'PO-PERSIST-LINE-001' not in str(refreshed.extracted_text or '')
expected_parser = str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6')
assert refreshed.parser_version == expected_parser
assert all('_payload_bytes' not in row for row in attachments)
assert all(row.get('asset_no') for row in attachments)
assert all(row.get('asset_no') is None for row in attachments)
assert all(row.get('document_id') is None for row in attachments)
from app.services.shipping_notice.intake_service import serialize_intake
@@ -3067,17 +3299,17 @@ def test_run_intake_parse_persists_eml_attachment_texts(app, shipping_user, monk
full = serialize_intake(refreshed, asset=asset, include_parse_texts=True)
full_atts = (full.get('parse_summary') or {}).get('attachments') or []
assert 'PO-PERSIST-LINE-001' in str(full_atts[0].get('extracted_text') or '')
assert full_atts and 'extracted_text' not in full_atts[0]
def test_run_intake_parse_persists_attached_multipart_and_detail_api(
app, client, shipping_user, monkeypatch,
):
"""
FileAsset → run_intake_parse → DB → 详情接口:附件型 multipart 独立文本与超深深 skipped 须落库返回。
FileAsset → run_intake_parse → DB → 详情接口:上传快览只保留附件目录,不递归落 multipart 子内容。
核心逻辑:mixed 容器内 plain+html 均持久化;嵌套容器超限为 skipped 并带 depth warning;
status 瘦身、详情含全文。
核心逻辑:附件型 multipart 只作为单个目录项展示;嵌套内容和深度警告不应以附件全文形式写入
shipping_notice Intake 的摘要或详情接口。
"""
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
@@ -3151,18 +3383,12 @@ def test_run_intake_parse_persists_attached_multipart_and_detail_api(
for row in (structured.get('attachments') or [])
}
assert 'bundle-persist.mime' in by_name
assert 'inner-depth.mime' in by_name
bundle_text = str(by_name['bundle-persist.mime'].get('extracted_text') or '')
assert 'PLAIN-PO-101' in bundle_text
assert 'HTML-PO-202' in bundle_text
assert by_name['bundle-persist.mime'].get('parse_status') == 'parsed'
assert by_name['inner-depth.mime'].get('parse_status') == 'skipped'
warnings = list(structured.get('warnings') or []) + list(
by_name['inner-depth.mime'].get('warnings') or []
)
assert any(str(w).startswith('eml_nesting_depth_exceeded:') for w in warnings)
assert 'PLAIN-PO-101' in str(refreshed.extracted_text or '')
assert 'HTML-PO-202' in str(refreshed.extracted_text or '')
assert 'inner-depth.mime' not in by_name
assert by_name['bundle-persist.mime'].get('parse_status') == 'directory_only'
assert by_name['bundle-persist.mime'].get('ready_for_extraction') is False
assert by_name['bundle-persist.mime'].get('catalog_reason') == 'unknown_binary'
assert 'PLAIN-PO-101' not in str(refreshed.extracted_text or '')
assert 'HTML-PO-202' not in str(refreshed.extracted_text or '')
lean = serialize_intake(refreshed, asset=asset, include_parse_texts=False)
lean_bundle = next(
@@ -3178,8 +3404,7 @@ def test_run_intake_parse_persists_attached_multipart_and_detail_api(
for row in ((full.get('parse_summary') or {}).get('attachments') or [])
if row.get('filename') == 'bundle-persist.mime'
)
assert 'PLAIN-PO-101' in str(full_bundle.get('extracted_text') or '')
assert 'HTML-PO-202' in str(full_bundle.get('extracted_text') or '')
assert 'extracted_text' not in full_bundle
headers = {'Authorization': f'Bearer {issue_local_access_token(shipping_user)}'}
@@ -3193,8 +3418,7 @@ def test_run_intake_parse_persists_attached_multipart_and_detail_api(
status_atts = (status_item.get('parse_summary') or {}).get('attachments') or []
status_bundle = next(row for row in status_atts if row.get('filename') == 'bundle-persist.mime')
assert 'extracted_text' not in status_bundle
status_inner = next(row for row in status_atts if row.get('filename') == 'inner-depth.mime')
assert status_inner.get('parse_status') == 'skipped'
assert all(row.get('filename') != 'inner-depth.mime' for row in status_atts)
detail_res = client.get(
'/api/workspace/shipping-notice/intakes/SNI-EML-MP-PERSIST-001',
@@ -3203,10 +3427,8 @@ def test_run_intake_parse_persists_attached_multipart_and_detail_api(
assert detail_res.status_code == 200
detail_atts = (detail_res.get_json()['data'].get('parse_summary') or {}).get('attachments') or []
detail_bundle = next(row for row in detail_atts if row.get('filename') == 'bundle-persist.mime')
assert 'PLAIN-PO-101' in str(detail_bundle.get('extracted_text') or '')
assert 'HTML-PO-202' in str(detail_bundle.get('extracted_text') or '')
detail_inner = next(row for row in detail_atts if row.get('filename') == 'inner-depth.mime')
assert detail_inner.get('parse_status') == 'skipped'
assert 'extracted_text' not in detail_bundle
assert all(row.get('filename') != 'inner-depth.mime' for row in detail_atts)
def test_intake_status_api_strips_texts_detail_returns_full(app, client):
@@ -3413,8 +3635,10 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid
app, shipping_user, monkeypatch,
):
"""
上传预处理验收:3 个含真实 PO 的 PDF → 正文 Document(email_context) + 3 PDF Document;
点击发送前不生成 Candidate;各 PDF 独立 FileAsset;重试不膨胀。
上传预处理验收:EML 快览阶段不创建附件 Document、派生资产或布局任务。
核心逻辑:即使附件是可解析 PDF,shipping_notice 上传阶段也只登记目录与可解析标记;
真正的 Document/资产/布局物化必须等到点击发送后的计划链路。
"""
from email.message import EmailMessage
@@ -3489,7 +3713,7 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid
if str(w).startswith('document_candidate_persist_failed')
]
assert not persist_warns, persist_warns
assert first.get('document_count') == 4, first
assert first.get('document_count') == 0, first
docs = (
db.session.query(ShippingNoticeDocument)
.filter_by(intake_id=refreshed_intake.id)
@@ -3511,26 +3735,24 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid
.all()
)
assert len(docs) == 4, (first, refreshed_intake.parse_warnings_json)
body_docs = [d for d in docs if d.document_type == 'email_body']
assert len(body_docs) == 1
assert body_docs[0].classification == 'email_context'
pdf_docs = [d for d in docs if d.document_type == 'attachment']
assert len(pdf_docs) == 3
assert all(d.classification == 'order_notice' for d in pdf_docs)
assert all(d.asset_id for d in pdf_docs)
assert len(docs) == 0, (first, refreshed_intake.parse_warnings_json)
assert len(cands) == 0
assert len(children) == 3
assert len({c.content_hash for c in children}) == 3
assert len(children) == 0
from app.models import Job, ShippingDocumentLayoutVersion
assert ShippingDocumentLayoutVersion.query.filter(
ShippingDocumentLayoutVersion.document_id.in_([item.id for item in pdf_docs]),
).count() == 3
assert Job.query.filter_by(job_type='shipping_document_layout').count() == 3
assert ShippingDocumentLayoutVersion.query.count() == 0
assert Job.query.filter_by(job_type='shipping_document_layout').count() == 0
structured = refreshed_intake.structured_result_json or {}
assert structured.get('attachment_count') == 3
assert structured.get('ready_attachment_count') == 3
rows = structured.get('attachments') or []
assert {row.get('filename') for row in rows} == {f'{po}.pdf' for po in markers}
assert all(row.get('parse_status') == 'ready_for_extraction' for row in rows)
assert all('extracted_text' not in row for row in rows)
detail = serialize_intake(refreshed_intake, asset=parent, include_parse_texts=True)
assert detail['document_count'] == 4
assert detail['document_count'] == 0
assert detail['candidate_count'] == 0
intake2 = (
@@ -3549,22 +3771,22 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid
.one()
.id
)
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake_id).count() == 4
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake_id).count() == 0
assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=intake_id).count() == 0
assert ShippingDocumentLayoutVersion.query.count() == 3
assert Job.query.filter_by(job_type='shipping_document_layout').count() == 3
assert ShippingDocumentLayoutVersion.query.count() == 0
assert Job.query.filter_by(job_type='shipping_document_layout').count() == 0
assert (
db.session.query(FileAsset)
.filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None))
.count()
== 3
== 0
)
def test_run_intake_parse_persists_sanitized_email_html_layout_without_meta_leak(
app, shipping_user, monkeypatch,
):
"""HTML 正文表格应生成独立布局版本,临时 HTML 不得进入 Intake 摘要或 Dify 文档正文。"""
"""HTML 正文表格快览只保留脱敏摘要,不在上传阶段生成 Document 或布局版本。"""
from email.message import EmailMessage
from io import BytesIO
@@ -3607,18 +3829,19 @@ def test_run_intake_parse_persists_sanitized_email_html_layout_without_meta_leak
result = run_intake_parse(intake, parent)
db.session.expire_all()
body = ShippingNoticeDocument.query.filter_by(
intake_id=intake.id, document_type='email_body',
).one()
version = ShippingDocumentLayoutVersion.query.filter_by(document_id=body.id).one()
structured = db.session.get(ShippingNoticeIntake, intake.id).structured_result_json
assert result['status'] == 'parsed'
assert version.status == 'needs_review'
assert version.payload_json['layout_candidate']['parser']['name'] == 'eml-html-dom'
assert 'SECRET' not in repr(version.payload_json)
assert 'body_html_tables' not in repr(structured)
assert '<table' not in repr(structured)
assert ShippingNoticeDocument.query.filter_by(intake_id=intake.id).count() == 0
assert ShippingDocumentLayoutVersion.query.count() == 0
email_summary = (structured.get('email') or {})
html_tables = email_summary.get('body_html_tables') or []
assert len(html_tables) == 1
assert '<table' in str(html_tables[0] or '')
assert 'script' not in str(html_tables[0] or '').lower()
assert 'SECRET' not in repr(structured)
assert structured.get('document_count') == 0
assert structured.get('candidate_count') == 0
def test_stage2_supporting_pdf_without_po_has_document_but_no_candidate(
@@ -4325,7 +4548,7 @@ def test_extract_failed_retry_clears_previous_stage2(app, shipping_user, monkeyp
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
lambda _a: NoticeIntakeResult(
lambda _a, **_kwargs: NoticeIntakeResult(
filename='clear.eml',
source_type='email',
source_file_type='message/rfc822',
@@ -0,0 +1,46 @@
"""验证发货通知上传批次迁移的升级与回退契约。"""
from __future__ import annotations
import importlib
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def test_shipping_notice_upload_batch_migration_round_trip():
"""上传批次字段和查询索引必须可升级回退,避免部署后历史附件无法查询。"""
migration = importlib.import_module(
'migrations.versions.0cf78a9b0c12_add_shipping_notice_upload_batch'
)
engine = sa.create_engine('sqlite://')
metadata = sa.MetaData()
sa.Table(
'shipping_notice_intakes',
metadata,
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('user_id', sa.Integer, nullable=False),
sa.Column('created_at', sa.DateTime, nullable=False),
)
metadata.create_all(engine)
with engine.begin() as connection:
original_op = migration.op
migration.op = Operations(MigrationContext.configure(connection))
try:
migration.upgrade()
inspector = sa.inspect(connection)
assert 'upload_batch_id' in {
item['name'] for item in inspector.get_columns('shipping_notice_intakes')
}
assert 'ix_shipping_notice_intakes_user_upload_batch_created' in {
item['name'] for item in inspector.get_indexes('shipping_notice_intakes')
}
migration.downgrade()
assert 'upload_batch_id' not in {
item['name'] for item in sa.inspect(connection).get_columns('shipping_notice_intakes')
}
finally:
migration.op = original_op
@@ -0,0 +1,381 @@
"""
backend/tests/test_shipping_order_auto_freeze_policy.py
用途:验证订单抽取 Run 的自动冻结门禁摘要按模板资格、技术失败和预算事实 fail-closed。
依赖:Run 创建夹具、Profile 资格模型与自动冻结策略服务。
逻辑:结果后评估只汇总已知事实,不在客户/场景资格未建模前提前放行自动冻结。
"""
from __future__ import annotations
import sys
import types
from datetime import datetime
from unittest.mock import patch
# 本组用例只验证 Run 级门禁摘要,不执行 OpenCV 版面识别;本地缺少 cv2 时用空模块兜底导入链。
if 'cv2' not in sys.modules:
sys.modules['cv2'] = types.SimpleNamespace()
from app import db
from app.models import (
Job,
ShippingDocumentProfileAutoFreezeQualification,
ShippingCustomer,
ShippingOrderDocumentProfile,
ShippingOrderCustomerMatch,
ShippingOrderExtraction,
ShippingOrderExtractionProgressEvent,
ShippingOrderExtractionRouteDecision,
)
from app.services.shipping_notice.order_auto_freeze_policy import evaluate_run_auto_freeze_policy
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
from tests.test_shipping_order_extraction_runs import _seed_run_input
def _published_profile(*, schema_version_id: int, checksum: str) -> ShippingOrderDocumentProfile:
"""构造最小 published Profile,供资格与 Run 门禁测试复用。"""
profile = ShippingOrderDocumentProfile(
profile_code=f'AF-{checksum[:6]}',
display_name='Auto freeze profile',
version=1,
status='published',
schema_version_id=schema_version_id,
structure_fingerprint='fp-' + checksum[:16],
checksum=checksum,
definition_json={'contract_version': 'order_coordinate_profile.v2', 'table_regions': []},
published_at=datetime.utcnow(),
)
db.session.add(profile)
db.session.flush()
return profile
def _confirm_run_customer(*, run_id: int, intake_id: int, schema_version_id: int, customer: ShippingCustomer) -> None:
"""为 Run 构造一条已确认的 Bill-to 客户匹配,供范围门禁测试复用。"""
extraction = ShippingOrderExtraction(
run_id=run_id,
intake_id=intake_id,
schema_version_id=schema_version_id,
input_snapshot_hash=f'run-{run_id}-customer-{customer.id}',
input_snapshot_json={},
status='accepted',
)
db.session.add(extraction)
db.session.flush()
db.session.add(ShippingOrderCustomerMatch(
extraction_id=extraction.id,
role='bill_to',
identity_components_json={},
status='confirmed',
customer_id=customer.id,
customer_name_snapshot=customer.standard_name,
customer_short_code_snapshot=customer.short_code,
identity_fingerprint=f'customer-{customer.id}',
identity_rule_version='customer-match.v1',
resolution_method='manual',
confirmed_at=datetime.utcnow(),
))
def _materialize_run_plan(run) -> None:
"""模拟 Worker 物化边界,为 Run 级门禁测试创建延迟生成的执行计划。"""
from app.services.shipping_notice.order_extraction_run_service import materialize_order_extraction_run_inputs
with patch('app.services.shipping_notice.order_extraction_run_service.ensure_order_extraction_input_documents'):
materialize_order_extraction_run_inputs(run)
def test_evaluate_run_auto_freeze_policy_keeps_fail_closed_with_run_blockers(app):
"""即使命中已批准模板,技术失败、预算停止与待处理订单仍必须阻断自动冻结。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-FREEZE-POLICY')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
_materialize_run_plan(run)
plan = run.extraction_plan
unit = plan.units[0]
job = db.session.get(Job, run.current_job_id)
profile = _published_profile(schema_version_id=run.schema_version_id, checksum='a' * 64)
qualification = ShippingDocumentProfileAutoFreezeQualification(
profile_id=profile.id,
profile_version=profile.version,
profile_checksum=profile.checksum,
schema_version_id=run.schema_version_id,
parser_version='deterministic-order-parser.v1',
status='auto_freeze_approved',
)
next_sequence_no = (
db.session.query(ShippingOrderExtractionProgressEvent.sequence_no)
.filter_by(run_id=run.id)
.order_by(ShippingOrderExtractionProgressEvent.sequence_no.desc())
.limit(1)
.scalar()
or 0
) + 1
unit.technical_failure_reason_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT'
run.status = 'review_required'
db.session.add_all([
qualification,
ShippingOrderExtractionRouteDecision(
run_id=run.id,
unit_id=unit.id,
job_id=job.id,
attempt_no=1,
decision='deterministic',
match_status='unique_match',
selected_profile_id=profile.id,
selected_profile_code=profile.profile_code,
selected_profile_version=profile.version,
selected_profile_checksum=profile.checksum,
auto_create_approved=True,
candidate_count=1,
table_count=1,
document_table_count=1,
business_table_count=1,
matched_table_count=1,
parsed_table_count=1,
approved_table_count=1,
candidate_summary_json=[],
fallback_reason_codes_json=[],
),
ShippingOrderExtractionProgressEvent(
run_id=run.id,
sequence_no=next_sequence_no,
visibility='workspace',
event_code='budget_stopped',
status='completed',
occurred_at=datetime.utcnow(),
reason_code='budget_initial_limit',
idempotency_key=f'budget-stop-{run.id}',
summary_json={'reason_codes': ['budget_initial_limit']},
),
])
db.session.commit()
policy = evaluate_run_auto_freeze_policy(run=run, submission_result={'pending_count': 1})
assert policy['enabled'] is False
assert policy['selected_profile_id'] == profile.id
assert policy['qualification_id'] == qualification.id
assert policy['qualification_status'] == 'auto_freeze_approved'
assert set(policy['blocking_reason_codes']) >= {
'technical_failure_present',
'budget_stopped',
'review_required',
'pending_orders_present',
'customer_scope_not_configured',
'business_scenario_not_configured',
'customer_confirmation_required',
}
def test_evaluate_run_auto_freeze_policy_blocks_suspended_profile(app):
"""模板资格被暂停后,新 Run 即使命中该模板也必须继续人工确认。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-FREEZE-SUSPENDED')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
_materialize_run_plan(run)
unit = run.extraction_plan.units[0]
job = db.session.get(Job, run.current_job_id)
profile = _published_profile(schema_version_id=run.schema_version_id, checksum='b' * 64)
qualification = ShippingDocumentProfileAutoFreezeQualification(
profile_id=profile.id,
profile_version=profile.version,
profile_checksum=profile.checksum,
schema_version_id=run.schema_version_id,
parser_version='deterministic-order-parser.v1',
status='auto_freeze_suspended',
)
db.session.add_all([
qualification,
ShippingOrderExtractionRouteDecision(
run_id=run.id,
unit_id=unit.id,
job_id=job.id,
attempt_no=1,
decision='deterministic',
match_status='unique_match',
selected_profile_id=profile.id,
selected_profile_code=profile.profile_code,
selected_profile_version=profile.version,
selected_profile_checksum=profile.checksum,
auto_create_approved=True,
candidate_count=1,
table_count=1,
document_table_count=1,
business_table_count=1,
matched_table_count=1,
parsed_table_count=1,
approved_table_count=1,
candidate_summary_json=[],
fallback_reason_codes_json=[],
),
])
db.session.commit()
policy = evaluate_run_auto_freeze_policy(run=run, submission_result={'pending_count': 0})
assert policy['enabled'] is False
assert policy['qualification_status'] == 'auto_freeze_suspended'
assert 'profile_auto_freeze_suspended' in policy['blocking_reason_codes']
assert 'customer_scope_not_configured' in policy['blocking_reason_codes']
def test_evaluate_run_auto_freeze_policy_matches_customer_and_business_scope(app):
"""客户和业务场景配置命中且无真实 pending 时,Run 可以进入自动冻结放行状态。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-FREEZE-SCOPE-MATCH')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
_materialize_run_plan(run)
unit = run.extraction_plan.units[0]
job = db.session.get(Job, run.current_job_id)
profile = _published_profile(schema_version_id=run.schema_version_id, checksum='c' * 64)
customer = ShippingCustomer(standard_name='Matched Customer', short_code='MATCH')
db.session.add(customer)
db.session.flush()
_confirm_run_customer(run_id=run.id, intake_id=intake.id, schema_version_id=run.schema_version_id, customer=customer)
qualification = ShippingDocumentProfileAutoFreezeQualification(
profile_id=profile.id,
profile_version=profile.version,
profile_checksum=profile.checksum,
schema_version_id=run.schema_version_id,
parser_version='deterministic-order-parser.v1',
status='auto_freeze_approved',
customer_ids_json=[customer.id],
business_scenarios_json=['shipping_notice_order'],
requires_customer_confirmation=False,
)
db.session.add_all([
qualification,
ShippingOrderExtractionRouteDecision(
run_id=run.id,
unit_id=unit.id,
job_id=job.id,
attempt_no=1,
decision='deterministic',
match_status='unique_match',
selected_profile_id=profile.id,
selected_profile_code=profile.profile_code,
selected_profile_version=profile.version,
selected_profile_checksum=profile.checksum,
auto_create_approved=True,
candidate_count=1,
table_count=1,
document_table_count=1,
business_table_count=1,
matched_table_count=1,
parsed_table_count=1,
approved_table_count=1,
candidate_summary_json=[],
fallback_reason_codes_json=[],
),
])
db.session.commit()
policy = evaluate_run_auto_freeze_policy(run=run, submission_result={'pending_count': 0})
assert policy['enabled'] is True
assert policy['customer_scope_status'] == 'matched'
assert policy['business_scenario_status'] == 'matched'
assert policy['confirmed_customer_ids'] == [customer.id]
assert policy['authorized_customer_ids'] == [customer.id]
assert policy['customer_confirmation_required'] is False
assert 'customer_scope_not_configured' not in policy['blocking_reason_codes']
assert 'customer_scope_out_of_scope' not in policy['blocking_reason_codes']
assert 'business_scenario_not_configured' not in policy['blocking_reason_codes']
assert 'business_scenario_out_of_scope' not in policy['blocking_reason_codes']
assert 'customer_confirmation_required' not in policy['blocking_reason_codes']
# Worker 提交本 Unit 的候选时,Run 可能尚未转为 review_required;Unit 事实必须先阻断副作用。
unit.status = 'review_required'
run.status = 'processing'
db.session.flush()
blocked = evaluate_run_auto_freeze_policy(run=run, submission_result={'pending_count': 0})
assert blocked['enabled'] is False
assert 'unit_review_required' in blocked['blocking_reason_codes']
def test_evaluate_run_auto_freeze_policy_ignores_placeholder_pending_orders(app):
"""仅因自动消费尚未执行而遗留的空原因 pending,不应继续阻断自动冻结。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-FREEZE-PENDING-PLACEHOLDER')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
_materialize_run_plan(run)
unit = run.extraction_plan.units[0]
job = db.session.get(Job, run.current_job_id)
profile = _published_profile(schema_version_id=run.schema_version_id, checksum='d' * 64)
customer = ShippingCustomer(standard_name='Matched Customer 2', short_code='MAT')
db.session.add(customer)
db.session.flush()
_confirm_run_customer(run_id=run.id, intake_id=intake.id, schema_version_id=run.schema_version_id, customer=customer)
qualification = ShippingDocumentProfileAutoFreezeQualification(
profile_id=profile.id,
profile_version=profile.version,
profile_checksum=profile.checksum,
schema_version_id=run.schema_version_id,
parser_version='deterministic-order-parser.v1',
status='auto_freeze_approved',
customer_ids_json=[customer.id],
business_scenarios_json=['shipping_notice_order'],
requires_customer_confirmation=False,
)
db.session.add_all([
qualification,
ShippingOrderExtractionRouteDecision(
run_id=run.id,
unit_id=unit.id,
job_id=job.id,
attempt_no=1,
decision='deterministic',
match_status='unique_match',
selected_profile_id=profile.id,
selected_profile_code=profile.profile_code,
selected_profile_version=profile.version,
selected_profile_checksum=profile.checksum,
auto_create_approved=True,
candidate_count=1,
table_count=1,
document_table_count=1,
business_table_count=1,
matched_table_count=1,
parsed_table_count=1,
approved_table_count=1,
candidate_summary_json=[],
fallback_reason_codes_json=[],
),
])
db.session.commit()
policy = evaluate_run_auto_freeze_policy(run=run, submission_result={
'pending_count': 1,
'pending_orders': [{
'candidate_no': 'SNC-PLACEHOLDER',
'reasons': [],
'missing_fields': [],
'duplicate_status': None,
}],
})
assert policy['enabled'] is True
assert 'pending_orders_present' not in policy['blocking_reason_codes']
@@ -14,6 +14,7 @@ from types import SimpleNamespace
import numpy as np
import pytest
import app.services.shipping_notice.preview_grant_store as preview_grant_store_service
from app import db
from app.models import (
ShippingOrderDocumentProfile,
@@ -894,7 +895,8 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(
def test_profile_page_preview_fails_closed_without_redis_or_sample_binding(app, monkeypatch):
"""预览授权依赖 Redis 且只能读取 Profile 已绑定样本,不能降级为进程内或任意文档读取。"""
with app.app_context():
monkeypatch.setattr('app.services.redis_client.get_redis_client', lambda: None)
app.config['ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK'] = False
monkeypatch.setattr(preview_grant_store_service, 'get_redis_client', lambda: None)
with pytest.raises(Exception) as unavailable:
service._preview_grant_store()
assert getattr(unavailable.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE'
@@ -903,6 +905,17 @@ def test_profile_page_preview_fails_closed_without_redis_or_sample_binding(app,
assert getattr(unbound.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND'
def test_profile_page_preview_uses_memory_fallback_in_development(app, monkeypatch):
"""开发环境允许单进程内存兜底,仍需保持一次性令牌语义。"""
with app.app_context():
app.config['ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK'] = True
monkeypatch.setattr(preview_grant_store_service, 'get_redis_client', lambda: None)
store = service._preview_grant_store()
store.setex('preview-token', 30, '{"page_no":1}')
assert store.getdel('preview-token') == '{"page_no":1}'
assert store.getdel('preview-token') is None
def test_profile_region_preview_requires_a_bound_document(app, monkeypatch):
"""局部预览只能作用于当前模板样本,避免管理员接口被 document_id 枚举越权。"""
with app.app_context():
@@ -22,58 +22,57 @@ def _run() -> ShippingOrderExtractionRun:
row = ShippingOrderExtractionRun(
run_no='SNER-PROGRESS', user_id=1, owner_agent_id=1, conversation_id='progress-conv',
schema_version_id=1, input_snapshot_hash='a' * 64, input_snapshot_json={}, idempotency_key='b' * 64,
status='running', phase='calling_provider',
status='processing', phase='deterministic_parsing',
)
db.session.add(row)
db.session.commit()
return row
def test_progress_events_dedupe_parallel_stages_and_protect_hxops_persistence(app):
"""重复SSE不重复落库;并行阶段合并,持久化阶段不被迟到Dify节点覆盖。"""
def test_progress_events_dedupe_sequence_and_protect_terminal_run(app):
"""重复业务事件不重复落库;终态后迟到普通事件不能覆盖当前投影。"""
with app.app_context():
run = _run()
assert record_order_extraction_progress_event(
run_no=run.run_no,
event={'event_type': 'workflow_started', 'workflow_run_id': 'wf-progress'},
event={'event_code': 'document_queued', 'document_id': 11},
) is True
assert record_order_extraction_progress_event(
run_no=run.run_no,
event={'event_type': 'node_started', 'workflow_run_id': 'wf-progress', 'node_execution_id': 'n1', 'node_type': 'document-extractor'},
event={'event_code': 'profile_matching', 'unit_id': 7, 'document_id': 11},
) is True
assert record_order_extraction_progress_event(
run_no=run.run_no,
event={'event_type': 'node_started', 'workflow_run_id': 'wf-progress', 'node_execution_id': 'n2', 'node_type': 'llm'},
event={'event_code': 'profile_matched', 'unit_id': 7, 'document_id': 11, 'summary': {'profile_code': 'vendor_a'}},
) is True
assert record_order_extraction_progress_event(
run_no=run.run_no,
event={'event_type': 'node_started', 'workflow_run_id': 'wf-progress', 'node_execution_id': 'n2', 'node_type': 'llm'},
event={'event_code': 'profile_matched', 'unit_id': 7, 'document_id': 11, 'summary': {'profile_code': 'vendor_a'}},
) is False
db.session.expire_all()
run = db.session.get(ShippingOrderExtractionRun, run.id)
assert run.current_stage_code == 'order_recognition'
assert set(run.active_stage_codes_json or []) == {'document_processing', 'order_recognition'}
assert run.current_stage_code == 'profile_matched'
assert list(run.active_stage_codes_json or []) == ['profile_matched']
assert record_order_extraction_progress_event(
run_no=run.run_no,
event={'event_type': 'node_finished', 'workflow_run_id': 'wf-progress', 'node_execution_id': 'n2', 'node_type': 'llm'},
event={'event_code': 'candidate_ready', 'unit_id': 7, 'document_id': 11},
) is True
db.session.expire_all()
run = db.session.get(ShippingOrderExtractionRun, run.id)
assert run.current_stage_code == 'order_recognition'
assert run.current_stage_code == 'candidate_ready'
run.status = 'completed'
run.progress_version = 4
db.session.commit()
assert record_order_extraction_progress_event(
run_no=run.run_no,
event={'event_type': 'hxops_persistence_started', 'job_id': 1, 'attempt_count': 1},
) is True
assert record_order_extraction_progress_event(
run_no=run.run_no,
event={'event_type': 'node_finished', 'workflow_run_id': 'wf-progress', 'node_execution_id': 'n1', 'node_type': 'document-extractor'},
) is True
event={'event_code': 'profile_matching', 'unit_id': 8, 'document_id': 12},
) is False
db.session.expire_all()
run = db.session.get(ShippingOrderExtractionRun, run.id)
assert run.current_stage_code == 'hxops_persistence'
assert ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).count() == 6
assert run.current_stage_code == 'candidate_ready'
assert ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).count() == 4
def test_progress_mapping_version_fits_persisted_column(app):
@@ -82,7 +81,7 @@ def test_progress_mapping_version_fits_persisted_column(app):
run = _run()
assert record_order_extraction_progress_event(
run_no=run.run_no,
event={'event_type': 'workflow_started', 'workflow_run_id': 'wf-version'},
event={'event_code': 'document_queued', 'document_id': 11},
) is True
db.session.expire_all()
persisted = db.session.get(ShippingOrderExtractionRun, run.id)
@@ -90,43 +89,115 @@ def test_progress_mapping_version_fits_persisted_column(app):
assert persisted.progress_mapping_version == MAPPING_VERSION
def test_progress_event_discards_custom_node_title(app):
"""自定义节点标题可能包含业务意图,诊断事件与幂等键均不得持久化该文本。"""
def test_progress_event_accepts_email_supplement_merge_summary(app):
"""正文补充合并事件必须可持久化,并把当前投影推进到 supplement 合并阶段。"""
with app.app_context():
run = _run()
assert record_order_extraction_progress_event(
run_no=run.run_no,
event={
'event_code': 'email_supplement_merged',
'unit_id': 7,
'document_id': 11,
'summary': {'status': 'merged', 'relation_codes': ['po_mpn'], 'conflict_count': 0},
},
) is True
db.session.expire_all()
run = db.session.get(ShippingOrderExtractionRun, run.id)
event = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).one()
assert run.current_stage_code == 'email_supplement_merged'
assert list(run.active_stage_codes_json or []) == ['email_supplement_merged']
assert event.summary_json == {'conflict_count': 0, 'relation_codes': ['po_mpn'], 'status': 'merged'}
def test_progress_event_accepts_plan_expansion_and_budget_run_level_events(app):
"""计划创建、扩批启动和预算停止必须作为 Run 级事实进入统一进度流。"""
with app.app_context():
run = _run()
assert record_order_extraction_progress_event(
run_no=run.run_no,
event={
'event_code': 'plan_created',
'summary': {'unit_count': 2, 'selection': {'selected_attachment_count': 2}},
},
) is True
assert record_order_extraction_progress_event(
run_no=run.run_no,
event={
'event_code': 'initial_wave_started',
'summary': {'selected_attachment_count': 2, 'max_initial_attachments': 2},
},
) is True
assert record_order_extraction_progress_event(
run_no=run.run_no,
event={
'event_code': 'expansion_wave_started',
'summary': {'selection_batch': 2, 'unit_count': 2, 'reason_codes': ['required_field_missing']},
},
) is True
assert record_order_extraction_progress_event(
run_no=run.run_no,
event={
'event_code': 'budget_stopped',
'reason_code': 'budget_initial_limit',
'summary': {'budget_limited_attachment_count': 2},
},
) is True
db.session.expire_all()
run = db.session.get(ShippingOrderExtractionRun, run.id)
events = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).order_by(
ShippingOrderExtractionProgressEvent.sequence_no.asc(),
).all()
assert [row.event_code for row in events] == [
'plan_created',
'initial_wave_started',
'expansion_wave_started',
'budget_stopped',
]
assert events[2].summary_json == {
'reason_codes': ['required_field_missing'],
'selection_batch': 2,
'unit_count': 2,
}
assert run.current_stage_code == 'budget_stopped'
assert list(run.active_stage_codes_json or []) == []
def test_progress_event_discards_unstructured_payload(app):
"""自定义非结构化文本不能进入新事件表摘要。"""
with app.app_context():
run = _run()
event = {
'event_type': 'node_started',
'workflow_run_id': 'wf-safe',
'node_execution_id': 'node-safe',
'node_type': 'llm',
'event_code': 'profile_matching',
'document_id': 11,
'node_title': '客户甲秘密订单识别',
}
assert record_order_extraction_progress_event(run_no=run.run_no, event=event) is True
event['node_title'] = '另一个可能敏感的标题'
assert record_order_extraction_progress_event(run_no=run.run_no, event=event) is False
row = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).one()
assert not hasattr(row, 'node_title')
assert '客户甲' not in str(row.details_json)
rows = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).order_by(ShippingOrderExtractionProgressEvent.id.asc()).all()
assert len(rows) == 1
assert all('客户甲' not in str(row.summary_json) for row in rows)
def test_terminal_run_records_diagnostics_without_mutating_projection(app):
"""终态后的迟到节点只保留管理员审计,绝不把用户状态改回运行中。"""
def test_terminal_run_rejects_late_workspace_event_without_mutating_projection(app):
"""终态后的迟到普通事件直接忽略,绝不把用户状态改回处理中。"""
with app.app_context():
run = _run()
run.status = 'completed'
run.current_stage_code = 'hxops_persistence'
run.current_stage_code = 'candidate_ready'
run.progress_version = 9
db.session.commit()
assert record_order_extraction_progress_event(
run_no=run.run_no,
event={'event_type': 'node_started', 'workflow_run_id': 'wf-late', 'node_execution_id': 'late-1', 'node_type': 'llm'},
) is True
event={'event_code': 'profile_matching', 'unit_id': 8, 'document_id': 12},
) is False
db.session.expire_all()
run = db.session.get(ShippingOrderExtractionRun, run.id)
assert run.status == 'completed'
assert run.current_stage_code == 'hxops_persistence'
assert run.current_stage_code == 'candidate_ready'
assert run.progress_version == 9
@@ -136,11 +207,11 @@ def test_progress_cleanup_deletes_only_expired_events_and_keeps_run(app):
run = _run()
now = datetime.utcnow()
expired = ShippingOrderExtractionProgressEvent(
run_id=run.id, event_type='node_finished', stage_code='order_recognition', event_status='completed',
run_id=run.id, sequence_no=1, visibility='workspace', event_code='candidate_ready', status='completed',
received_at=now - timedelta(days=91), idempotency_key='expired-progress-event', expires_at=now - timedelta(seconds=1),
)
retained = ShippingOrderExtractionProgressEvent(
run_id=run.id, event_type='node_started', stage_code='document_processing', event_status='running',
run_id=run.id, sequence_no=2, visibility='workspace', event_code='profile_matching', status='completed',
received_at=now, idempotency_key='retained-progress-event', expires_at=now + timedelta(days=1),
)
db.session.add_all([expired, retained])
@@ -152,9 +223,9 @@ def test_progress_cleanup_deletes_only_expired_events_and_keeps_run(app):
def test_user_slow_threshold_uses_p95_after_minimum_samples_and_is_capped(app):
"""慢响应阈值不足20样本回退60秒,满足样本后按P95且上限300秒。"""
"""慢响应阈值不足20样本回退180秒,满足样本后按P95且上限300秒。"""
with app.app_context():
assert get_order_extraction_user_slow_threshold_seconds() == 60
assert get_order_extraction_user_slow_threshold_seconds() == 180
base = datetime.utcnow() - timedelta(minutes=10)
for index in range(20):
run = ShippingOrderExtractionRun(
@@ -1,344 +1,65 @@
"""
backend/tests/test_shipping_order_extraction_quality_gate.py
用途:验证 L7 订单抽取双人影子标签、指标、双角色批准和 Runtime Binding 自动建单门禁。
依赖:质量服务、Agent Runtime Binding、订单抽取 Run 测试夹具。
逻辑:构造 100 个匿名一致样本达标批次,并覆盖分歧、权限边界和批准引用。
"""
from __future__ import annotations
from datetime import datetime
import pytest
"""Verify order extraction quality batches without runtime bindings."""
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.core.errors import ConflictError, ValidationError
from app.jobs.context import JobContext
from app.jobs.handlers.shipping_order_extraction import run_shipping_order_extraction
from app.jobs.queue import claim_next_job
from app.jobs.types import JobType
from app.models import (
Agent,
AgentRuntimeBinding,
ShippingOrderSchema,
ShippingOrderExtractionQualityBatch,
ShippingOrderExtractionQualityLabel,
ShippingOrderExtractionRun,
User,
)
from app.services.agent_runtime_binding_service import save_runtime_binding
from app.services.shipping_notice.order_extraction_quality_service import (
approve_quality_batch,
list_approved_quality_batches,
quality_metrics,
require_approved_quality_batch,
save_quality_label,
)
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
from app.models import ShippingOrderExtractionQualityBatch, ShippingOrderExtractionQualityLabel, ShippingOrderExtractionRun, User
from app.services.shipping_notice.order_extraction_quality_service import quality_metrics, save_quality_label
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.conftest import parse_api_data
def _quality_batch(owner: Agent, schema_version_id: int, creator: User) -> ShippingOrderExtractionQualityBatch:
"""建立 collecting 批次,供服务级测试批量注入匿名标签。"""
batch = ShippingOrderExtractionQualityBatch(
batch_no=f'SOQ-TEST-{owner.id}', owner_agent_id=owner.id,
schema_version_id=schema_version_id,
threshold_version='l7.v1', status='collecting', created_by_id=creator.id,
)
db.session.add(batch)
db.session.flush()
return batch
def _add_agreed_samples(
batch: ShippingOrderExtractionQualityBatch, runs: list[ShippingOrderExtractionRun],
first: User, second: User,
) -> None:
"""为每个 Run 写入两份完全一致且无错误的匿名标签。"""
for run in runs:
for reviewer in (first, second):
db.session.add(ShippingOrderExtractionQualityLabel(
batch_id=batch.id, run_id=run.id, reviewer_id=reviewer.id,
core_expected_count=4, core_extracted_count=4, core_correct_count=4,
wrong_merge=False, wrong_split=False, wrong_auto_create=False,
))
db.session.flush()
def test_quality_metrics_require_two_matching_reviews(app):
"""单人和分歧标签不计样本;100 个一致样本才通过固定阈值。"""
"""Only matching reviews count toward quality eligibility metrics."""
with app.app_context():
user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-METRICS')
second = User(username='quality-second', email='quality-second@example.com', role='admin', password_hash='x')
db.session.add(second)
user, owner, session, _intake, _document = _seed_run_input(suffix='QUALITY-METRICS')
reviewer = User(username='quality-reviewer', email='quality-reviewer@example.com', role='admin', password_hash='x')
db.session.add(reviewer)
db.session.flush()
batch = _quality_batch(owner, 1, user)
runs = []
for index in range(100):
run = ShippingOrderExtractionRun(
run_no=f'SNER-QUALITY-{index:03d}', user_id=user.id, owner_agent_id=owner.id,
conversation_id=f'quality-{index}', schema_version_id=batch.schema_version_id,
input_snapshot_hash=f'{index:064x}'[-64:], input_snapshot_json={},
idempotency_key=f'{index + 1000:064x}'[-64:], status='completed', phase='completed',
provider_config_json={'auto_create_enabled': False},
)
db.session.add(run)
runs.append(run)
batch = ShippingOrderExtractionQualityBatch(
batch_no='SOQ-QUALITY-METRICS', owner_agent_id=owner.id, schema_version_id=1,
threshold_version='l7.v1', status='collecting', created_by_id=user.id,
)
run = ShippingOrderExtractionRun(
run_no='SNER-QUALITY-METRICS', user_id=user.id, owner_agent_id=owner.id,
conversation_id=session.session_id, schema_version_id=1,
input_snapshot_hash='a' * 64, input_snapshot_json={}, idempotency_key='b' * 64,
status='completed', phase='completed', auto_freeze_policy_json={'enabled': False},
)
db.session.add_all([batch, run])
db.session.flush()
for actor in (user, reviewer):
db.session.add(ShippingOrderExtractionQualityLabel(
batch_id=batch.id, run_id=run.id, reviewer_id=actor.id,
core_expected_count=4, core_extracted_count=4, core_correct_count=4,
wrong_merge=False, wrong_split=False, wrong_auto_create=False,
))
db.session.flush()
_add_agreed_samples(batch, runs, user, second)
metrics = quality_metrics(batch)
assert metrics['eligible'] is True
assert metrics['agreed_sample_count'] == 100
assert metrics['precision'] == 1.0
assert metrics['recall'] == 1.0
assert quality_metrics(batch)['agreed_sample_count'] == 1
def test_quality_label_rejects_wrong_owner_or_auto_create_run(app):
"""标签只能引用同 Owner/Schema 的终态 unit.v3 影子 Run,不能标生产自动建单结果。"""
def test_quality_label_rejects_auto_creation_run(app):
"""Production auto-creation Runs cannot become quality samples."""
with app.app_context():
user, owner, session, intake, _document = _seed_run_input(suffix='QUALITY-LABEL')
user, owner, session, _intake, _document = _seed_run_input(suffix='QUALITY-INVALID')
user.role = 'admin'
batch = _quality_batch(owner, 1, user)
batch = ShippingOrderExtractionQualityBatch(
batch_no='SOQ-QUALITY-INVALID', owner_agent_id=owner.id, schema_version_id=1,
threshold_version='l7.v1', status='collecting', created_by_id=user.id,
)
run = ShippingOrderExtractionRun(
run_no='SNER-QUALITY-INVALID', user_id=user.id, owner_agent_id=owner.id,
conversation_id=session.session_id, schema_version_id=batch.schema_version_id,
input_snapshot_hash='a' * 64, input_snapshot_json={}, idempotency_key='b' * 64,
status='completed', phase='completed',
provider_config_json={'auto_create_enabled': True},
conversation_id=session.session_id, schema_version_id=1,
input_snapshot_hash='c' * 64, input_snapshot_json={}, idempotency_key='d' * 64,
status='completed', phase='completed', auto_freeze_policy_json={'enabled': True},
)
db.session.add(run)
db.session.flush()
db.session.add_all([batch, run])
db.session.commit()
with pytest.raises(ValidationError) as caught:
try:
save_quality_label(
batch_id=batch.id, run_no=run.run_no, actor_id=user.id,
payload={'core_expected_count': 4, 'core_extracted_count': 4, 'core_correct_count': 4},
)
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_RUN_INVALID'
def test_approved_quality_batch_is_required_for_auto_create_binding(app):
"""unit.v3 自动建单必须引用同 Owner、当前阈值、双人批准且仍达标的批次。"""
with app.app_context():
user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-BINDING')
business = User(username='quality-business', email='quality-business@example.com', role='admin', password_hash='x')
technical = User(username='quality-technical', email='quality-technical@example.com', role='admin', password_hash='x')
db.session.add_all([business, technical])
db.session.flush()
batch = _quality_batch(owner, 1, user)
runs = []
for index in range(100):
run = ShippingOrderExtractionRun(
run_no=f'SNER-APPROVE-{index:03d}', user_id=user.id, owner_agent_id=owner.id,
conversation_id=f'approve-{index}', schema_version_id=batch.schema_version_id,
input_snapshot_hash=f'{index + 2000:064x}'[-64:], input_snapshot_json={},
idempotency_key=f'{index + 3000:064x}'[-64:], status='completed', phase='completed',
provider_config_json={'auto_create_enabled': False},
)
db.session.add(run)
runs.append(run)
db.session.flush()
_add_agreed_samples(batch, runs, business, technical)
batch.status = 'ready'
db.session.flush()
approve_quality_batch(batch_id=batch.id, role='business', actor_id=business.id)
approve_quality_batch(batch_id=batch.id, role='technical', actor_id=technical.id)
provider = Agent.query.filter_by(exposure_mode='internal').first()
approved = require_approved_quality_batch(
batch_id=batch.id, owner_agent_id=owner.id, schema_version_id=batch.schema_version_id,
)
binding = save_runtime_binding(
owner_agent_id=owner.id, capability_code='shipping.order_extraction',
provider_agent_id=provider.id, enabled=True, quality_batch_id=batch.id,
config={'auto_create_enabled': True},
)
assert approved.status == 'approved'
assert binding.quality_batch_id == batch.id
def test_same_admin_cannot_approve_both_roles(app):
"""业务和技术批准必须由不同管理员完成。"""
with app.app_context():
user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-APPROVERS')
user.role = 'admin'
batch = _quality_batch(owner, 1, user)
batch.status = 'ready'
batch.business_approved_by_id = user.id
batch.business_approved_at = datetime.utcnow()
db.session.flush()
with pytest.raises(ConflictError):
require_approved_quality_batch(
batch_id=batch.id, owner_agent_id=owner.id, schema_version_id=batch.schema_version_id,
)
with pytest.raises(ConflictError):
approve_quality_batch(batch_id=batch.id, role='technical', actor_id=user.id)
def test_first_approval_freezes_labels_and_schema_mismatch_blocks_release(app):
"""任一角色批准后标签不可变化,且旧 Schema 批次不能给新 Schema 的执行放行。"""
with app.app_context():
user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-FREEZE')
user.role = 'admin'
second = User(username='quality-freeze-second', email='quality-freeze-second@example.com', role='admin', password_hash='x')
db.session.add(second)
db.session.flush()
batch = _quality_batch(owner, 1, user)
runs = []
for index in range(100):
run = ShippingOrderExtractionRun(
run_no=f'SNER-FREEZE-{index:03d}', user_id=user.id, owner_agent_id=owner.id,
conversation_id=f'freeze-{index}', schema_version_id=batch.schema_version_id,
input_snapshot_hash=f'{index + 4000:064x}'[-64:], input_snapshot_json={},
idempotency_key=f'{index + 5000:064x}'[-64:], status='completed', phase='completed',
provider_config_json={'auto_create_enabled': False},
)
db.session.add(run)
runs.append(run)
db.session.flush()
_add_agreed_samples(batch, runs, user, second)
batch.status = 'ready'
db.session.flush()
approve_quality_batch(batch_id=batch.id, role='business', actor_id=user.id)
with pytest.raises(ConflictError) as frozen:
save_quality_label(
batch_id=batch.id, run_no=runs[0].run_no, actor_id=second.id,
payload={'core_expected_count': 5, 'core_extracted_count': 5, 'core_correct_count': 5},
)
with pytest.raises(ConflictError):
require_approved_quality_batch(
batch_id=batch.id, owner_agent_id=owner.id,
schema_version_id=batch.schema_version_id + 1,
)
assert frozen.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_IMMUTABLE'
def test_approved_batch_is_listed_and_frozen_on_run(app):
"""管理端候选只含当前 Schema 已批准批次,启用后 Run 必须冻结相同批次。"""
with app.app_context():
user, owner, session, intake, _document = _seed_run_input(suffix='QUALITY-RUN')
business = User(username='quality-run-business', email='quality-run-business@example.com', role='admin', password_hash='x')
technical = User(username='quality-run-technical', email='quality-run-technical@example.com', role='admin', password_hash='x')
db.session.add_all([business, technical])
db.session.flush()
batch = _quality_batch(owner, 1, user)
runs = []
for index in range(100):
run = ShippingOrderExtractionRun(
run_no=f'SNER-RUN-GATE-{index:03d}', user_id=user.id, owner_agent_id=owner.id,
conversation_id=f'run-gate-{index}', schema_version_id=batch.schema_version_id,
input_snapshot_hash=f'{index + 6000:064x}'[-64:], input_snapshot_json={},
idempotency_key=f'{index + 7000:064x}'[-64:], status='completed', phase='completed',
provider_config_json={'auto_create_enabled': False},
)
db.session.add(run)
runs.append(run)
db.session.flush()
_add_agreed_samples(batch, runs, business, technical)
batch.status = 'ready'
db.session.flush()
approve_quality_batch(batch_id=batch.id, role='business', actor_id=business.id)
approve_quality_batch(batch_id=batch.id, role='technical', actor_id=technical.id)
binding = Agent.query.filter_by(exposure_mode='internal').first()
save_runtime_binding(
owner_agent_id=owner.id, capability_code='shipping.order_extraction',
provider_agent_id=binding.id, enabled=True, quality_batch_id=batch.id,
config={'auto_create_enabled': True},
)
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one()
schema.auto_creation_policy_json = {'enabled': True}
db.session.commit()
listed = list_approved_quality_batches(owner_agent_id=owner.id)
run, reused = create_order_extraction_run(
user=user, agent_id=owner.id, conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
assert reused is False
assert [item['id'] for item in listed] == [batch.id]
assert run.quality_batch_id == batch.id
assert run.provider_config_json['auto_create_enabled'] is True
db.session.commit()
batch.threshold_version = 'obsolete-threshold'
db.session.commit()
job = claim_next_job(
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
worker_id='quality-gate-worker',
)
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
db.session.refresh(run)
assert run.status == 'failed'
assert run.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_GATE_BLOCKED'
def test_disabled_schema_keeps_runtime_auto_create_binding_in_shadow_mode(app):
"""质量批次已配置时,Schema 总开关关闭仍可创建影子 Run,且不得触发自动建单。"""
with app.app_context():
user, owner, session, intake, _document = _seed_run_input(suffix='QUALITY-SHADOW')
provider = Agent.query.filter_by(exposure_mode='internal').first()
binding = AgentRuntimeBinding.query.filter_by(
owner_agent_id=owner.id, capability_code='shipping.order_extraction',
).one()
binding.config_json = {'timeout_seconds': 900, 'max_attempts': 3, 'auto_create_enabled': True}
binding.provider_agent_id = provider.id
# The missing quality batch is intentional: schema-disabled execution is shadow-only.
binding.quality_batch_id = None
db.session.commit()
run, reused = create_order_extraction_run(
user=user, agent_id=owner.id, conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
assert reused is False
assert run.provider_config_json['auto_create_enabled'] is False
assert run.input_snapshot_json['auto_creation_policy']['schema_enabled'] is False
assert run.input_snapshot_json['auto_creation_policy']['runtime_binding_enabled'] is True
def test_quality_batch_admin_api_is_protected_and_returns_safe_summary(app, client):
"""质量批次列表仅管理员可读,且响应不暴露 Run、字段值、引文或单条标签。"""
with app.app_context():
user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-API')
user.role = 'admin'
db.session.flush()
token = issue_local_access_token(user)
db.session.commit()
owner_id = owner.id
admin_username = user.username
forbidden = client.get(
f'/api/admin/shipping-notice/order-extraction-quality-batches?owner_agent_id={owner_id}',
headers={'X-Username': 'missing-quality-user', 'X-Role': 'user'},
)
auth = {'Authorization': f'Bearer {token}'}
created = client.post(
'/api/admin/shipping-notice/order-extraction-quality-batches',
json={'owner_agent_id': owner_id, 'schema_version_id': 1},
headers=auth,
)
listed = client.get(
f'/api/admin/shipping-notice/order-extraction-quality-batches?owner_agent_id={owner_id}',
headers=auth,
)
assert forbidden.status_code in {401, 403}
assert created.status_code == 201
created_data = parse_api_data(created.get_json())
assert created_data['status'] == 'collecting'
assert listed.status_code == 200
assert parse_api_data(listed.get_json()) == []
serialized = str(created.get_json()).lower()
assert all(key not in serialized for key in ('document', 'quote', 'orders', 'evidence_ref', 'cell_id', 'labels'))
except Exception as exc:
assert getattr(exc, 'code', None) == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_RUN_INVALID'
else:
raise AssertionError('auto-creation run must be rejected')
@@ -1,9 +1,9 @@
"""
backend/tests/test_shipping_order_extraction_quality_migration.py
用途:验证 L7 质量批次/标签和 Runtime Binding 引用迁移可完整往返。
用途:验证 L7 质量批次/标签迁移可完整往返。
依赖:Alembic Operations、SQLite 内存数据库、a71f8091a2b7 迁移。
逻辑:构造最小父表,升级检查表/列/索引,降级确认完全移除。
逻辑:构造最小父表,升级检查表/索引,降级确认完全移除。
"""
from __future__ import annotations
@@ -16,7 +16,7 @@ from alembic.operations import Operations
def test_order_extraction_quality_migration_round_trip(monkeypatch):
"""质量表和 Binding 外键必须可独立升级、写入并完整降级。"""
"""质量表必须可独立升级、写入并完整降级。"""
migration = importlib.import_module(
'migrations.versions.a71f8091a2b7_add_order_extraction_quality_gate',
)
@@ -24,11 +24,6 @@ def test_order_extraction_quality_migration_round_trip(monkeypatch):
metadata = sa.MetaData()
for name in ('agents', 'users', 'shipping_order_schema_versions', 'shipping_order_extraction_runs'):
sa.Table(name, metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table(
'agent_runtime_bindings', metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('owner_agent_id', sa.Integer()),
)
metadata.create_all(engine)
with engine.begin() as connection:
operations = Operations(MigrationContext.configure(connection))
@@ -38,14 +33,8 @@ def test_order_extraction_quality_migration_round_trip(monkeypatch):
inspector = sa.inspect(connection)
assert 'shipping_order_extraction_quality_batches' in inspector.get_table_names()
assert 'shipping_order_extraction_quality_labels' in inspector.get_table_names()
assert 'quality_batch_id' in {
item['name'] for item in inspector.get_columns('agent_runtime_bindings')
}
migration.downgrade()
inspector = sa.inspect(connection)
assert 'shipping_order_extraction_quality_batches' not in inspector.get_table_names()
assert 'shipping_order_extraction_quality_labels' not in inspector.get_table_names()
assert 'quality_batch_id' not in {
item['name'] for item in inspector.get_columns('agent_runtime_bindings')
}
@@ -46,42 +46,3 @@ def test_order_extraction_run_quality_migration_round_trip(monkeypatch):
migration.downgrade()
inspector = sa.inspect(connection)
assert 'quality_batch_id' not in {
item['name'] for item in inspector.get_columns('shipping_order_extraction_runs')
}
def test_quality_binding_migration_round_trip(monkeypatch):
"""Binding 与 Run 的质量批次引用必须一起升级和完整降级。"""
migration = importlib.import_module(
'migrations.versions.a77f8091a2c3_add_order_extraction_quality_binding',
)
engine = sa.create_engine('sqlite:///:memory:')
metadata = sa.MetaData()
sa.Table(
'shipping_order_extraction_quality_batches', metadata,
sa.Column('id', sa.Integer(), primary_key=True),
)
for table_name in ('agent_runtime_bindings', 'shipping_order_extraction_runs'):
sa.Table(table_name, metadata, sa.Column('id', sa.Integer(), primary_key=True))
metadata.create_all(engine)
with engine.begin() as connection:
operations = Operations(MigrationContext.configure(connection))
monkeypatch.setattr(migration, 'op', operations)
migration.upgrade()
inspector = sa.inspect(connection)
for table_name in ('agent_runtime_bindings', 'shipping_order_extraction_runs'):
assert 'quality_batch_id' in {
item['name'] for item in inspector.get_columns(table_name)
}
assert f'ix_{table_name}_quality_batch_id' in {
item['name'] for item in inspector.get_indexes(table_name)
}
migration.downgrade()
inspector = sa.inspect(connection)
for table_name in ('agent_runtime_bindings', 'shipping_order_extraction_runs'):
assert 'quality_batch_id' not in {
item['name'] for item in inspector.get_columns(table_name)
}
File diff suppressed because it is too large. Load diff
@@ -13,26 +13,28 @@ from app.models import ShippingAuditEvent
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
def test_business_review_route_transitions_unit_to_skipped_not_failed(app):
"""模板未匹配等业务拒识使用 skipped,计划完成后由 Run 汇总为 needs_review。"""
def test_business_review_route_transitions_unit_to_review_required_not_failed(app):
"""模板未匹配等业务拒识使用 review_required,计划完成后由 Run 汇总为 review_required/partially_completed。"""
with app.app_context():
plan = SimpleNamespace(units=[])
unit = SimpleNamespace(
status='running', attempt_count=1, started_at=None, finished_at=None,
result_json={'stale': True}, error_code=None, error_message=None, plan=plan,
status='matching_profile', attempt_count=1, started_at=None, finished_at=None,
last_activity_at=None, result_json={'stale': True}, summary_json=None,
reason_code=None, error_code=None, error_message=None, plan=plan,
)
plan.units = [unit]
transition_order_extraction_unit(
unit,
target_status='skipped',
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED',
target_status='review_required',
error_code='profile_not_found',
error_message='Template requires review',
)
# 关键断言:业务不确定性是可复核的完成态,不能污染技术失败率。
assert unit.status == 'skipped'
assert unit.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED'
assert unit.status == 'review_required'
assert unit.reason_code == 'profile_not_found'
assert unit.error_code is None
assert plan.status == 'completed'
@@ -42,16 +44,49 @@ def test_unit_transition_appends_auditable_status_event(app):
run = SimpleNamespace(run_no='SNER-STAGE0')
plan = SimpleNamespace(units=[], run=run)
unit = SimpleNamespace(
id=37, status='running', attempt_count=1, started_at=None, finished_at=None,
result_json=None, error_code=None, error_message=None, plan=plan,
id=37, status='matching_profile', attempt_count=1, started_at=None, finished_at=None,
last_activity_at=None, result_json=None, summary_json=None,
reason_code=None, error_code=None, error_message=None, plan=plan,
)
plan.units = [unit]
transition_order_extraction_unit(unit, target_status='skipped')
transition_order_extraction_unit(unit, target_status='review_required', error_code='profile_not_found')
db.session.commit()
event = ShippingAuditEvent.query.filter_by(aggregate_id='37').one()
# 关键断言:单元业务复核状态能和 Run 关联,但不复制订单内容。
assert event.event_type == 'order_extraction_unit_status_changed'
assert event.run_no == 'SNER-STAGE0'
assert event.reason_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED'
assert event.reason_code == 'profile_not_found'
def test_supplement_merge_transition_keeps_unit_on_business_path(app):
"""正文补充合并必须走 merging_supplement -> candidate_ready,不能跳回技术态。"""
with app.app_context():
plan = SimpleNamespace(units=[])
unit = SimpleNamespace(
status='extracting', attempt_count=1, started_at=None, finished_at=None,
last_activity_at=None, result_json=None, summary_json=None,
reason_code=None, error_code=None, error_message=None, plan=plan,
)
plan.units = [unit]
transition_order_extraction_unit(
unit,
target_status='merging_supplement',
result={'orders': [{'po_number': '450001'}]},
)
assert unit.status == 'merging_supplement'
assert unit.error_code is None
assert plan.status == 'running'
transition_order_extraction_unit(
unit,
target_status='candidate_ready',
result={'orders': [{'po_number': '450001', '_hxops_email_supplement_relation': 'po_mpn'}]},
)
assert unit.status == 'candidate_ready'
assert unit.result_json['orders'][0]['_hxops_email_supplement_relation'] == 'po_mpn'
assert unit.reason_code is None
assert plan.status == 'completed'
@@ -0,0 +1,368 @@
"""订单抽取 Worker 的单元级自动重试与技术失败收口测试。"""
from types import SimpleNamespace
from app.core.errors import ServiceUnavailableError, ValidationError
from app.jobs.handlers.shipping_order_extraction import (
_expansion_trigger_reason_codes,
_mark_expandable_business_gaps,
_pending_snapshot_batches,
_process_unit_with_retries,
_result_requires_review,
_should_expand_after_wave,
_units_for_batch,
)
def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
"""深度抽取只允许在 Worker 首轮执行,且必须在读取 Unit 计划之前完成。"""
import app.jobs.handlers.shipping_order_extraction as handler
events: list[str] = []
run = SimpleNamespace(
id=1, run_no='SNER-WORKER-MATERIALIZE', status='queued', current_job_id=None,
attempt_count=0, input_snapshot_json={'attachment_selection': {}},
)
job = SimpleNamespace(id=1, attempts=1, business_ref=run.run_no, max_attempts=3)
plan = SimpleNamespace(id=1, unit_count=0, units=[])
monkeypatch.setattr(handler.db.session, 'get', lambda _model, _id: job)
monkeypatch.setattr(
handler,
'ShippingOrderExtractionRun',
SimpleNamespace(query=SimpleNamespace(
filter_by=lambda **_kwargs: SimpleNamespace(
with_for_update=lambda: SimpleNamespace(first=lambda: run),
),
)),
)
monkeypatch.setattr(
handler,
'ShippingOrderExtractionUnit',
SimpleNamespace(
position=SimpleNamespace(asc=lambda: None),
query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
order_by=lambda *_args: SimpleNamespace(all=lambda: []),
)),
),
)
monkeypatch.setattr(handler, 'transition_order_extraction_run', lambda target, **_kwargs: setattr(target, 'status', 'processing'))
monkeypatch.setattr(handler, 'materialize_order_extraction_run_inputs', lambda _run: events.append('materialize') or plan)
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: events.append('units') or [])
monkeypatch.setattr(handler, '_next_existing_batch', lambda _plan, *, after_batch: None)
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda _run, _plan: [])
monkeypatch.setattr(handler, '_wave_orders_for_expansion', lambda _run, *, orders: [])
monkeypatch.setattr(handler, '_expansion_trigger_reason_codes', lambda **_kwargs: [])
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: None)
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: None)
monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda *, run, orders: {})
monkeypatch.setattr(handler, '_result_requires_review', lambda **_kwargs: False)
monkeypatch.setattr(handler, 'finish_job', lambda *_args, **_kwargs: events.append('finished'))
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None)
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 1})
assert events.index('materialize') < events.index('units')
def _patch_unit_transitions(monkeypatch):
"""用轻量状态机替代 ORM transition,便于验证单元级自动重试行为。"""
def fake_transition(unit, *, target_status, error_code=None, error_message=None, result=None, **_kwargs):
if target_status == 'routing':
unit.attempt_count = int(unit.attempt_count or 0) + 1
unit.retry_status = 'retrying' if int(unit.attempt_count or 0) > 1 else 'running'
elif target_status == 'pending':
unit.retry_status = 'pending_retry'
elif target_status == 'failed':
unit.retry_status = 'failed'
unit.technical_failure_reason_code = error_code
unit.error_code = error_code
unit.error_message = error_message
elif target_status == 'review_required':
unit.retry_status = 'review_required'
elif target_status == 'candidate_ready':
unit.retry_status = 'succeeded'
unit.status = target_status
unit.result_json = result
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_plan.transition_order_extraction_unit',
fake_transition,
)
def _patch_worker_io(monkeypatch, *, event_log: list[tuple[str, str | None]]):
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.db.session.commit', lambda: None)
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.db.session.rollback', lambda: None)
monkeypatch.setattr(
'app.jobs.handlers.shipping_order_extraction.record_unit_progress',
lambda *, event_code, reason_code=None, **_kwargs: event_log.append((event_code, reason_code)),
)
monkeypatch.setattr(
'app.jobs.handlers.shipping_order_extraction._append_route_decision',
lambda **_kwargs: None,
)
def test_process_unit_with_retries_retries_retryable_failures_and_returns_orders(monkeypatch):
"""同一附件技术故障应在单元内自动重试,成功后不需要整轮 Run 重跑。"""
event_log: list[tuple[str, str | None]] = []
_patch_unit_transitions(monkeypatch)
_patch_worker_io(monkeypatch, event_log=event_log)
run = SimpleNamespace(id=1, run_no='SNER-WORKER-RETRY')
unit = SimpleNamespace(
id=7,
intake_id=11,
document_id=101,
status='pending',
attempt_count=0,
retry_status='not_started',
technical_failure_reason_code=None,
result_json=None,
)
job = SimpleNamespace(id=5)
orders = [{'source_intake_no': 'SNI-1', 'primary_document_id': 101, 'header_fields': [], 'lines': []}]
calls = {'count': 0}
def fake_route(_run, *, unit):
calls['count'] += 1
if calls['count'] < 3:
raise ServiceUnavailableError('layout service unavailable', code='SYSTEM.SERVICE_UNAVAILABLE')
return SimpleNamespace(
execution_mode='deterministic',
orders=orders,
decision={'selected_profile_code': 'vendor_a', 'selected_profile_version': 2},
)
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.route_deterministic_unit', fake_route)
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.validate_unit_orders', lambda _run, *, unit, orders: orders)
monkeypatch.setattr(
'app.jobs.handlers.shipping_order_extraction._reload_run_and_unit',
lambda *, run_id, unit_id: (run, unit),
)
result = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1)
assert result is orders
assert unit.status == 'merging_supplement'
assert unit.attempt_count == 3
assert event_log.count(('technical_retrying', 'SYSTEM.SERVICE_UNAVAILABLE')) == 2
assert event_log.count(('technical_failed', 'SYSTEM.SERVICE_UNAVAILABLE')) == 2
def test_process_unit_with_retries_records_distinct_route_attempts(monkeypatch):
"""同一 Job 内重试路由时,审计尝试号必须随 Unit 递增以避开唯一约束。"""
event_log: list[tuple[str, str | None]] = []
_patch_unit_transitions(monkeypatch)
_patch_worker_io(monkeypatch, event_log=event_log)
run = SimpleNamespace(id=1, run_no='SNER-WORKER-ROUTE-ATTEMPTS')
unit = SimpleNamespace(
id=10, intake_id=14, document_id=104, status='pending', attempt_count=0,
retry_status='not_started', technical_failure_reason_code=None, result_json=None,
)
job = SimpleNamespace(id=8)
route_attempts: list[int] = []
calls = {'count': 0}
def fake_route(_run, *, unit):
calls['count'] += 1
return SimpleNamespace(
execution_mode='deterministic',
orders=[{'source_intake_no': 'SNI-ROUTE', 'primary_document_id': 104, 'header_fields': [], 'lines': []}],
decision={'selected_profile_code': 'vendor_a', 'selected_profile_version': 1},
)
def fake_validate(_run, *, unit, orders):
if calls['count'] == 1:
raise ServiceUnavailableError('temporary validation failure', code='SYSTEM.SERVICE_UNAVAILABLE')
return orders
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.route_deterministic_unit', fake_route)
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.validate_unit_orders', fake_validate)
monkeypatch.setattr(
'app.jobs.handlers.shipping_order_extraction._append_route_decision',
lambda **kwargs: route_attempts.append(kwargs['attempt_no']),
)
monkeypatch.setattr(
'app.jobs.handlers.shipping_order_extraction._reload_run_and_unit',
lambda *, run_id, unit_id: (run, unit),
)
assert _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1)
assert route_attempts == [1, 2]
def test_process_unit_with_retries_exhausts_retry_budget_and_marks_unit_failed(monkeypatch):
"""自动重试耗尽后仅保留单元级技术失败,调用方可继续处理其他附件。"""
event_log: list[tuple[str, str | None]] = []
_patch_unit_transitions(monkeypatch)
_patch_worker_io(monkeypatch, event_log=event_log)
run = SimpleNamespace(id=1, run_no='SNER-WORKER-FAILED')
unit = SimpleNamespace(
id=8,
intake_id=12,
document_id=102,
status='pending',
attempt_count=0,
retry_status='not_started',
technical_failure_reason_code=None,
result_json=None,
)
job = SimpleNamespace(id=6)
monkeypatch.setattr(
'app.jobs.handlers.shipping_order_extraction.route_deterministic_unit',
lambda _run, *, unit: (_ for _ in ()).throw(ServiceUnavailableError('ocr timeout', code='OCR.TIMEOUT')),
)
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.validate_unit_orders', lambda _run, *, unit, orders: orders)
monkeypatch.setattr(
'app.jobs.handlers.shipping_order_extraction._reload_run_and_unit',
lambda *, run_id, unit_id: (run, unit),
)
result = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1)
assert result is None
assert unit.status == 'failed'
assert unit.attempt_count == 3
assert unit.technical_failure_reason_code == 'OCR.TIMEOUT'
assert event_log.count(('technical_retrying', 'OCR.TIMEOUT')) == 2
assert event_log.count(('technical_failed', 'OCR.TIMEOUT')) == 3
def test_process_unit_with_retries_does_not_retry_non_retryable_validation_errors(monkeypatch):
"""业务/校验类异常不得误走技术自动重试。"""
event_log: list[tuple[str, str | None]] = []
_patch_unit_transitions(monkeypatch)
_patch_worker_io(monkeypatch, event_log=event_log)
run = SimpleNamespace(id=1, run_no='SNER-WORKER-NONRETRY')
unit = SimpleNamespace(
id=9,
intake_id=13,
document_id=103,
status='pending',
attempt_count=0,
retry_status='not_started',
technical_failure_reason_code=None,
result_json=None,
)
job = SimpleNamespace(id=7)
monkeypatch.setattr(
'app.jobs.handlers.shipping_order_extraction.route_deterministic_unit',
lambda _run, *, unit: (_ for _ in ()).throw(
ValidationError('snapshot stale', code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE'),
),
)
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.validate_unit_orders', lambda _run, *, unit, orders: orders)
monkeypatch.setattr(
'app.jobs.handlers.shipping_order_extraction._reload_run_and_unit',
lambda *, run_id, unit_id: (run, unit),
)
result = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1)
assert result is None
assert unit.status == 'failed'
assert unit.attempt_count == 1
assert unit.technical_failure_reason_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE'
assert ('technical_retrying', 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE') not in event_log
assert event_log.count(('technical_failed', 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE')) == 1
def test_should_expand_after_wave_when_current_wave_needs_more_evidence():
"""只有可补证的 review/业务缺口才扩批;纯技术失败不应直接消耗下一轮预算。"""
assert _should_expand_after_wave(
wave_units=[SimpleNamespace(status='review_required', reason_code='required_field_missing')],
wave_orders=[],
) is True
assert _should_expand_after_wave(
wave_units=[SimpleNamespace(status='failed', reason_code='OCR.TIMEOUT')],
wave_orders=[{'id': 1}],
) is False
def test_auto_freeze_blocked_task_requires_run_review():
"""自动冻结的 Task 级门禁拒绝必须把 Run 收口为需人工处理,而非 completed。"""
assert _result_requires_review(
units=[SimpleNamespace(status='candidate_ready')],
result={'pending_count': 0, 'auto_freeze': {'blocked_tasks': [{'task_no': 'ST-1'}]}},
) is True
assert _should_expand_after_wave(
wave_units=[SimpleNamespace(status='candidate_ready', reason_code=None)],
wave_orders=[{'_hxops_expand_for_missing_reservation': True}],
) is True
assert _should_expand_after_wave(
wave_units=[SimpleNamespace(status='merging_supplement', reason_code=None)],
wave_orders=[{'id': 1}],
) is False
def test_expansion_trigger_reason_codes_merge_review_and_order_gaps():
"""扩批原因应同时汇总 review reason、正文冲突和缺 Reservation。"""
codes = _expansion_trigger_reason_codes(
wave_units=[SimpleNamespace(status='review_required', reason_code='required_field_missing')],
wave_orders=[{
'_hxops_expand_for_missing_reservation': True,
'conflicts': [{'reason': 'supplement_relation_ambiguous'}],
}],
)
assert codes == [
'missing_reservation_id',
'required_field_missing',
'supplement_relation_ambiguous',
]
def test_mark_expandable_business_gaps_flags_missing_reservation_from_schema():
"""缺 Reservation 的订单应被标记为可通过下一附件补证。"""
run = SimpleNamespace(
input_snapshot_json={
'schema': {
'definition': {
'fields': [
{'field_code': 'reservation_id', 'field_id': 'reservation-id'},
],
},
},
},
)
orders = [{
'lines': [
{'fields': []},
{'fields': [{'field_id': 'reservation-id', 'observations': [{'value': 'RSV001'}]}]},
],
}]
marked = _mark_expandable_business_gaps(run, orders=orders)
assert marked[0]['_hxops_expand_for_missing_reservation'] is True
def test_pending_snapshot_batches_ignore_already_activated_units():
"""冻结计划里已有的未来批次,激活后不应重复出现在待扩批列表里。"""
run = SimpleNamespace(
input_snapshot_json={
'attachment_selection': {
'items': [
{'planned_selection_batch': 2},
{'planned_selection_batch': 3},
],
},
},
)
plan = SimpleNamespace(units=[
SimpleNamespace(selection_batch=1),
SimpleNamespace(selection_batch=2),
])
assert _pending_snapshot_batches(run, plan) == [3]
assert [unit.selection_batch for unit in _units_for_batch(plan, selection_batch=1)] == [1]
@@ -0,0 +1,42 @@
"""订单抽取工作台投影的纯单元测试。"""
from types import SimpleNamespace
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run_chat_state
def test_workspace_projection_exposes_run_level_current_activity(monkeypatch):
"""Run 级事件也应进入聊天卡 currentActivity,而不是只支持单元级事件。"""
run = SimpleNamespace(
status='processing',
extraction_plan=SimpleNamespace(units=[]),
input_snapshot_json={},
error_code=None,
started_at=None,
finished_at=None,
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workspace_projection._latest_progress_events',
lambda _run: (
{},
SimpleNamespace(
unit_id=None,
document_id=None,
event_code='expansion_wave_started',
reason_code='budget_initial_limit',
summary_json={'selection_batch': 2, 'reason_codes': ['required_field_missing']},
),
),
)
result = serialize_workspace_run_chat_state(run)
assert result['currentActivity'] == {
'unitId': 0,
'fileName': None,
'eventCode': 'expansion_wave_started',
'selectionBatch': 2,
'reasonCodes': ['budget_initial_limit', 'required_field_missing'],
}
assert result['status'] == 'processing'
@@ -88,3 +88,22 @@ def test_profile_matcher_uses_page_glyphs_for_anchor_outside_table():
def test_profile_matcher_uses_table_glyphs_only_for_legacy_evidence():
"""缺少新 page_glyphs 的历史冻结快照继续保持兼容,不降低已有模板可回放性。"""
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=_layout()).status == 'unique_match'
def test_profile_matcher_allows_multiple_template_regions_on_one_detected_table():
"""续页未被检测器拆表时,页级坐标证据仍可匹配多区域模板。"""
profile = _profile('PO_A')
profile['definition']['table_regions'][0]['region']['y1'] = .5
profile['definition']['table_regions'][0]['line_layouts'][0]['region']['y1'] = .5
profile['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['y1'] = .5
profile['definition']['table_regions'].append({
'region_id': 'lines_page_2', 'page_scope': 'exact_page', 'page_no': 2,
'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': 1},
'header_layouts': [{'layout_id': 'header_page_2', 'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': 1}}],
})
layout = _layout()
layout['coordinate_evidence']['page_glyphs'] = {'1': layout['coordinate_evidence']['tables']['table-1']}
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
assert result.status == 'unique_match'
+21
View File
@@ -197,6 +197,27 @@ catch (e) {
| 在 `*.api.ts` 里 `msg.error` | API 层只抛错,UI 层负责展示 |
| 新增后端 code 却不加 `errors.json` | 四语言同步 `errors.codes.*` |
### 3.6 订单抽取:API 错误码 vs 运行原因码(强约束)
订单抽取链路同时存在两类“码”,**语义不同,禁止混用**:
| 类型 | 承载位置 | 例子 | 用途 | 前端展示位置 |
|------|----------|------|------|--------------|
| **API 错误码** | Envelope `error.code` / `BusinessError.code` | `SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_FOUND`、`SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING` | 请求级失败:创建 Run、重试、重解析、详情接口访问失败 | `errors.json` / `BusinessError.message` / `useMessage()` |
| **运行原因码** | 订单抽取 payload 内部字段:`reason_code`、`summary.reason_codes`、`unit_summary.review_required_reason_codes`、`unit_summary.expansion_trigger_reason_codes`、`technical_failure_reason_code` | `required_field_missing`、`multiple_po_detected`、`missing_reservation_id`、`budget_initial_limit`、`SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT` | Run/Unit 事实解释:为什么复核、为什么扩批、为什么预算停止、哪个技术单元失败 | 聊天卡片、详情抽屉、逐 PDF 结果项 |
**硬约束:**
1. `reason_code(s)` **不是** `BusinessError.code`,不得走 `errors.codes.*` 全局错误映射。
2. 订单抽取业务原因码(如 `required_field_missing`、`supplement_relation_ambiguous`)使用 `chat.json` 的 `shippingOrderExtractionReason.*` 翻译。
3. 预算原因码(如 `budget_initial_limit`)和技术原因码(如 `SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT`)在订单抽取卡片/抽屉中按运行事实展示,**不得**伪装成请求失败 toast。
4. 只有当请求本身失败时,才使用 `BusinessError` + `errors.json`;Run 已创建后的 `review_required / failed / budget_stopped` 一律视为**业务运行事实**。
5. 对话卡片与详情抽屉可以按以下四类对时间线做轻量分组,但不得发明额外状态:
- `business`:业务复核 / 证据不足 / 扩批触发
- `technical`:技术异常 / 技术重试 / 技术失败
- `budget`:预算停止 / 限额耗尽
- `progress`:计划创建、首轮启动、普通进度
---
## 4. 新增错误码检查清单
+16 -15
View File
@@ -113,18 +113,18 @@
### 3.x 一封邮件多订单与 Candidate 级判重
- 保持“一封 EML = 一个 Intake”;上传阶段只预处理正文和附件为 Document。订单抽取已切换为独立 Run:点击发送直接创建后台作业并轮询 Run 状态,不再把 `shipping_intake_nos` 发送给普通 Chatflow;普通无附件问答仍走聊天 SSE。
- 保持“一封 EML = 一个 Intake”;上传阶段只做快览:读取邮件头、正文白名单 HTML 表格快照和附件目录,不抽取附件全文、不创建附件 Document/派生资产、不调度 MinerU/OCR。订单抽取已切换为独立 Run:点击发送直接创建后台作业并轮询 Run 状态,不再把 `shipping_intake_nos` 发送给普通 Chatflow;普通无附件问答仍走聊天 SSE。
- 一个附件可包含多个订单,一个订单也可跨正文/多个附件;按实际业务订单生成 Candidate,不按附件数量机械拆分。
- 正文与附件由 LLM 结合语义关联;后端规则解析与 Dify LLM 均只产出不可变字段 Observation,由 HXOPS 按字段证据统一裁决;`part_number`/Qty 必须保留原文 evidence,不确定字段返回空值,关键字段冲突必须阻断自动建单。
- 正文与附件由 HXOPS 的确定性关系规则关联并统一裁决;`part_number`/Qty 必须保留原文 evidence,不确定字段返回空值,关键字段冲突必须阻断自动建单。订单抽取主链不调用 Dify。
- 判重以 Candidate 为业务粒度:附件 hash 判断相同文件,业务身份指纹判断同一订单,内容指纹区分完全重复与订单修订。
- 高置信发货需求只要包含可信内部料号 `part_number` + 正数 Qty 且有原文证据即可自动创建 Batch/Task;Reservation ID 缺失时 Task 必须停在自然对话补字段门禁;`inventory_source_hint` 是可选库存源路由线索,不作为必填门禁。
- 低置信、证据不足、阻断冲突或可能修订的 Candidate 保留待处理;同 Intake 已自动建单部分不得导致剩余 Candidate 丢失。
- 订单抽取最终必须以持久化 `ShippingOrderExtractionRun` 为业务生命周期真相;Run 冻结用户、入口 Agent、会话、Intake/Document 正文和 published Schema,幂等键由服务端快照计算,不依赖浏览器 request ID。
- 订单抽取最终必须以持久化 `ShippingOrderExtractionRun` 为业务生命周期真相;发送时 Run 冻结用户、入口 Agent、会话、Intake、Schema 与附件选择计划的轻量请求快照,Worker 物化后另冻结 Document 正文执行快照。幂等键始终锚定请求快照,不依赖浏览器 request ID。
- 订单附件结构化必须支持版本化订单坐标 Profile v2。模板真相为静态文档锚点、表区相对坐标、独立表头布局、明细物理行布局、字段区域到稳定 `field_id + field_code` 的绑定、注册解析器、跨页/终止规则;表头文字只能用于建议、校准和匹配,不能决定最终字段。已发布版本不可原地修改,同模板发布新版本时原子退役旧版本;Run 必须复制完整 published Profile,不能只保存当前 Profile ID。
- 业务管理员必须通过受控样本页面维护订单坐标 Profile:可配置相对区域、静态锚点、独立表头/明细布局和注册解析器;不得编辑 HTML、原始 bbox、JSON、正则、脚本、Prompt 或结构指纹。草稿更新使用乐观锁;每个明细字段区域必须绑定 Schema 允许的 `pdf_coordinate`/`ocr_coordinate` 来源和最低证据等级;不可变版本可复制为新草稿或退役。
- Profile 治理必须保存模板模式、训练样本计数和不含锚点正文的匹配策略摘要;训练/标注样本、盲测样本及其增删、草稿保存、区域/字段绑定变化、测试执行/批准、发布和退役均追加审计。样本文档被训练或盲测引用后不得删除;审计不得保存 PDF、HTML、对象存储地址、正文或凭据。
- 模板工作台页面预览仅针对已绑定样本:PDF 以短时、单页、单用途 Redis 授权返回低分辨率 PNG,响应始终 `private, no-store`,不返回 MinIO URL、PDF、bbox、原始 HTML 或永久下载令牌。OCR 坐标只可由管理员对绑定 PDF 显式触发;页面文本和局部解析候选不包含坐标/token 身份。EML 仅使用既有白名单清洗的表格文本,禁止脚本、事件属性、表单、iframe、外链及远程图片/字体。
- MinerU 按显式环境开关固定使用 `pipeline`,由独立布局 Job 在 Intake 持久化 Document 后异步调用,不得阻塞 Intake 预解析。布局必须按 Document 独立版本化,保存 parser revision、状态、checksum、大小、质量问题和 Worker lease;只有成功版本可成为当前布局,失败/超限/旧 Worker 结果不得覆盖上一次成功版本。多附件受单 Intake 文档预算限制;Provider 失败、超预算、结构不匹配或多表命中时回退现有 Dify/人工复核,不得伪造确定性字段。
- MinerU 按显式环境开关固定使用 `pipeline`,由发送后的 Worker 在 Document 物化后异步调用,不得阻塞上传快览。布局必须按 Document 独立版本化,保存 parser revision、状态、checksum、大小、质量问题和 Worker lease;只有成功版本可成为当前布局,失败/超限/旧 Worker 结果不得覆盖上一次成功版本。多附件受单 Run 文档预算限制;Provider 失败、超预算、结构不匹配或多表命中时进入人工复核,不得伪造确定性字段或回退 Dify。
- 人工单元格真值当前允许延期,不阻塞布局版本/任务生命周期建设;但在真值评测完成前,不得宣称 95% 准确率、把 MinerU/OpenCV/文本对齐候选自动标记为 `accepted`,也不得据此开启错误自动建单风险。
- 原生 PDF 可使用 PDFium 字符坐标与 MinerU HTML 生成 `shipping_document_layout.v1` 候选;只允许唯一连续文本或“OpenCV 多参数有框网格 + 原生文本全量一致”两条保守路径。候选必须保持 `needs_review`,扫描 PDF 不得由本阶段伪造 OCR 结果。
- 扫描 PDF 的布局 OCR 必须保留 RapidOCR 原始多边形坐标和置信度,并且只有与严格有框网格及全部非空 cell 文本一致时才能生成 OCR cell 候选。EML HTML table 必须经主动内容/属性白名单清理后按 DOM 行列和跨度生成逻辑布局;原始 HTML 不得进入 Intake 摘要、Dify 或日志。两类结果在人工真值完成前均保持 `needs_review`。
@@ -133,22 +133,22 @@
- 对 MinerU 行列关系错误或数据页表头不完整的 PDF,管理员可基于原生/OCR 字符坐标确认相对字段区域。坐标模板不得依赖数据页完整表头:系统以主行锚点、y-band、物理行相对偏移、前一明细完整性和显式跨页声明综合判定新行/续行;无稳定主行锚点不得默认新明细。合计、税额、条款和签字区必须由排除/终止规则排除。几何位置是主证据,字段内容类型与同行左右顺序仅用于边界歧义辅助。
- 同一订单明细允许由任意连续 N 条物理行构成,不限定两行、三行或四行。管理员可动态增加/删除第 2..N 行版式,每行独立配置相对列边界和固定字段映射,横坐标区间允许跨行重叠;第 1 行必须包含 `line_no` 作为新明细锚点,后续行按 `row_offset` 合并到最近明细。
- 管理员不得被要求从 PDF 截图手工计算 0..1 列边界。系统须基于冻结的 PDF/OCR 字符坐标自动建议物理行数量、每行列边界及列示例文字;人工只确认字段映射,并可在必要时使用高级边界校准。
- 阶段 2 创建 Run 时同步创建 `shipping_order_extraction` Job;Worker 按 Run 冻结快照调用 `shipping.order_extraction` 能力绑定的内部 Provider,并把 Dify 成功结果先于 HXOPS 订单落库独立提交,重试不得重复调用 Dify。
- 应用管理必须显式创建 `exposure_mode=internal` 的 Dify Workflow Provider,再由货代 Agent 绑定 `shipping.order_extraction`。业务代码只识别能力编码和数据库外键,禁止写死 App ID、按名称匹配或从环境变量静默回退;Dify 画布由管理员手工配置。
- Run 冻结 Provider App ID、Base URL 与执行参数;二者变更后旧 Run 必须失败并重新发起。API Key 不进入快照,允许在不重建 Run 的情况下安全轮换。
- 创建 Run 时同步创建 `shipping_order_extraction` Job;发送请求不做深度解析,Worker 先按冻结的附件选择计划物化首轮输入,再按执行快照执行 HXOPS 本地确定性解析与候选落库,不依赖 Dify Workflow、Runtime Binding 或内部 Provider 成功缓存。
- 货代订单抽取由 HXOPS 的确定性解析 Run 和 Worker 执行,不依赖应用管理中的 Dify Workflow Provider、Runtime Binding 或内部执行器;Dify 画布如需保留,仅由管理员独立维护且不参与该执行链路。
- Run 不冻结 Provider App ID、Base URL 或 API Key;订单抽取主链不调用 Provider。Dify 如保留,仅用于独立只读问答且不参与 Run 执行。
- Run 模型声明的执行追溯字段必须由独立 Alembic 增量迁移提供;已经进入任何环境的迁移文件禁止继续追加列。部署验收必须同时核对 Alembic head、数据库实际列和 SQLAlchemy 模型,任一不一致均阻断下一阶段。
- 用户点击发送后,聊天区必须立即显示订单识别进行态;该阶段无法获得可信完成比例,因此使用不确定进度,不展示伪造百分比。
- 首次发送无需先创建聊天消息:Run 创建事务会创建本地 ChatSession 并原子绑定尚未归属会话的 Intake,前端使用返回的 `conversation_id` 更新路由。
- 订单识别状态卡必须可在刷新/重新进入会话后按 Run 列表恢复;活动态只显示不确定进度,不按固定轮询频率重复写 ChatLog,只有业务状态变化才原位持久化。
- 订单抽取进度由 HXOPS 服务端消费专用 Workflow 的 Dify SSE 节点事件并自动按节点类型归并;用户默认查看当前脱敏阶段、真实运行时长和最近活动,可展开时间线。无需手工修改 Dify Workflow;不展示模型思考、节点输入输出、伪百分比或内部运行标识。浏览器继续使用自适应短轮询,不建立订单抽取浏览器长 SSE。
- 订单抽取进度必须来自 HXOPS 持久化的 Run / PDF Unit / Progress Event 数据库事实;用户卡片只展示 `summary/current_activity/available_actions` 及按 PDF 归并结果,不再消费 Dify 节点事件、Workflow 阶段或浏览器 SSE。浏览器继续使用自适应短轮询,页面刷新、重新登录和 Worker 重启后均可恢复同一事实视图。
- 用户状态卡、Run 查询和历史聊天回放只可显示稳定错误码与通用可操作提示;Worker、Provider 或上游异常正文不得进入用户 API、ChatLog 或前端状态。
- 新上线 Run 的完成、待确认和失败状态应在用户离开会话后形成会话级待查看提示;进入对应会话且终态卡片成功加载后才清除。管理员在货代管理域只读诊断 Run、Job Attempt 和脱敏节点时间线;不提供管理端强制操作。
- Run 失败或取消时 Intake 恢复为可重试失败态;切换会话后的迟到轮询响应不得更新当前页面或重启旧 Run 计时器。
- 管理员必须可查询最近 1-168 小时订单抽取 Run 的状态/阶段/错误码分布、失败率、重试数、积压 Run,以及排队、Provider、HXOPS 落库和总耗时;监控视图不得返回文档正文、Provider 配置、原始结果或错误正文。
- 管理员必须可查询最近 1-168 小时订单抽取 Run 的状态、当前活动事件、错误码分布、失败率、重试数、积压 Run,以及排队、处理和总耗时;监控视图不得返回文档正文、Provider 配置、原始结果或错误正文。
- 前端 Run 查询单次最多等待 10 秒;超时或切换会话只取消当前 GET,后台 Run 继续执行,页面保持进行态并按退避策略重试。
- 订单识别终态必须区分新建任务、打开已有任务、待补充/冲突、非发货忽略和已建但缺流程字段,并在刷新或重新进入会话后仍可恢复。
- Dify 错误、网络超时或成功结束但未提交 `orders[]` 时,订单识别必须离开 `extracting` 并显示可重试的失败原因。
- 同一 Intake 同时只允许一个订单识别 Run;已有 Run 处理中时,新请求必须复用相同快照或返回冲突。Provider 结果或订单事实已持久化后,任何 Dify 断流、读超时、Worker 重试或迟到终态都不得重复调用 Dify、回退完成事实,或使附件重新具备自动提交资格。
- 本地解析器、对象存储或 Worker 超时/失败时,订单识别必须离开 `extracting` 并显示可重试的稳定错误码。
- 同一 Intake 同时只允许一个订单识别 Run;已有 Run 处理中时,新请求必须复用相同快照或返回冲突。订单事实已持久化后,Worker 重试或迟到终态不得重复创建 Candidate/Task、回退完成事实,或使附件重新具备自动提交资格。
### 3.x 唯一订单 Schema 与动态字段
@@ -586,12 +586,13 @@
- 本期不在 HXOPS 后端并行调用多个子 Agent,不合并多个 Dify 回答;多路召回与答案融合由聚合 Chatflow 承担。
## 2026-07-22 订单抽取唯一 Manifest 与自动建单策略
- 订单抽取只保留唯一、可冻结的 `execution_manifest`,不提供输入格式切换或回退。
- Manifest 仅向模型提供压缩后的结构化字段候选,不传递版面坐标、HTML、token 或内部映射代码;确定性 accepted 字段不可被模型覆盖。
- 订单抽取只保留由 HXOPS Worker 消费的请求快照与物化执行快照,不提供模型 `execution_manifest`、输入格式切换或回退。
- 执行快照不向 Dify 传递版面坐标、HTML、token 或内部映射代码;确定性 accepted 字段只能由 HXOPS 规则与人工复核产生。
- 人工真值暂缓期间,版面候选保持 `needs_review`,质量验收与 95% 准确率目标延期,不得自动 accepted、自动建单或对外宣称达标。
- L6 要求所有 accepted Observation 具有稳定证据引用;无 cell 的纯文本表格只能形成复核原因,不能作为已验证后端表格证据。跨文档关联必须使用同 Document 强身份,禁止以 Qty 等常见值串接订单行。
- 自动建单配置位于“货代配置 → 订单字段模板”:管理员只维护一个自动建单总开关;每个字段独立标记为建单关键字段并设置自身最低置信度。每个 Run 冻结开关与字段快照;阈值不能绕过必填、证据、冲突、重复和 Reservation 等硬门禁。
- 终态且未消费的订单抽取 Run 支持“按当前规则重新识别”:创建新的可审计 Run,重新冻结当前 Schema、执行绑定、文档 Profile 与 ready 布局;旧候选在新版执行期间不可建单,新版失败后恢复旧版。失败 Run 的基础设施重试仍复用原冻结 Run,不得与重新识别混用。
- **模板自动建单资格**:Profile 发布仅表示可作为受控解析候选,不等于可跳过 Dify。发布前必须有至少 1 份训练样本,且建立与训练/标注样本完全独立的盲测集;所有模板最低仅需 1 份独立样本,其中至少 1 份为多明细真值;声明跨页时还必须覆盖带 `continuation_of` 的续页样本。样本按管理员确认真值通过并由管理员批准后才允许发布;资格与正式 Profile checksum 绑定,checksum 变化立即失效。唯一命中的已批准 Profile 才可确定性建单,未知、多模板、行解析异常或未批准时一律回退 Dify/人工复核。
- **Dify 证据边界**:Dify 输出只能使用冻结 `extraction_contract` 中的 field_id,所有 Observation 必须引用当前 Unit 文档且 quote 可在冻结输入中逐字验证;不得回传确定性上下文字段或覆盖已锁定值。Dify 画布由管理员在最终验收时手工配置,HXOPS 不修改画布。
- **模板自动建单资格**:Profile 发布仅表示可作为受控解析候选,不等于自动冻结资格。发布前必须有至少 1 份训练样本,且建立与训练/标注样本完全独立的盲测集;所有模板最低仅需 1 份独立样本,其中至少 1 份为多明细真值;声明跨页时还必须覆盖带 `continuation_of` 的续页样本。样本按管理员确认真值通过并由管理员批准后才允许发布;资格与正式 Profile checksum 绑定,checksum 变化立即失效。唯一命中的已批准 Profile 才可确定性建单,未知、多模板、行解析异常或未批准时一律人工复核。
- **Dify 边界**:订单抽取不向 Dify 发送字段契约、文档或 Observation,也不消费 Dify 输出。Dify 画布由管理员手工维护,仅提供只读问答与状态查询;HXOPS 不修改画布。
- **客户绑定与冻结**:订单原文、按 `order-customer-fingerprint.v1` 标准化生成的身份指纹、正式 `customer_id` 三层分离保存。Bill-to 是订购客户;只有已人工确认并写明理由的 Bill-to 匹配可以冻结为 Snapshot。调用方不能在冻结请求中自由传入客户或简码;Snapshot 固化客户简码和匹配规则版本,客户后续改名、合并或规则变化不回写历史。
- **自动冻结资格范围**:模板发布资格与自动冻结资格继续分离。每个发布 Profile 版本的自动冻结资格必须独立保存客户白名单、业务场景白名单和“是否仍需客户确认”开关;新模板、新版本和新客户/场景默认人工确认。Run 只能消费当前版本资格和本轮已确认 Bill-to 客户来评估是否进入自动冻结门禁,未配置、越界、冲突或仍需客户确认时一律降级人工复核。
Loaded 100 of 159 files, more files were not shown because too many files have changed in this diff. Show more