feat(shipping-notice): 增强订单抽取功能,添加进度事件和诊断运行管理,优化数据模型和访问控制
This commit is contained in:
1 parent
ce26d6d0c4
commit
c4095b08da
175 files changed
+13064
-1814
No files matched your search
@@ -73,6 +73,10 @@ def create_app(config_name='default'):
|
||||
)
|
||||
register_file_asset_cleanup_schedule_hooks()
|
||||
ensure_default_file_asset_cleanup_schedule()
|
||||
from app.services.shipping_notice.order_extraction_progress_cleanup_schedule import (
|
||||
ensure_default_order_extraction_progress_cleanup_schedule,
|
||||
)
|
||||
ensure_default_order_extraction_progress_cleanup_schedule()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure file-asset-cleanup schedule: %s', exc)
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
|
||||
@@ -69,8 +69,8 @@ def list_agent_intent_routes():
|
||||
@admin_bp.route('/agents', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agents():
|
||||
"""返回全部 Agent 列表。"""
|
||||
return ok(agent_service.list_agents(), request_id=_request_id())
|
||||
"""按管理页签返回应用或内部执行器;缺省 scope 保持旧版全部列表兼容。"""
|
||||
return ok(agent_service.list_agents(scope=request.args.get('scope')), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents', methods=['POST'])
|
||||
|
||||
@@ -12,7 +12,11 @@ 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.shipping_notice.order_extraction_run_service import get_order_extraction_run_health
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
get_order_extraction_run_health,
|
||||
get_order_extraction_diagnostic_run,
|
||||
list_order_extraction_diagnostic_runs,
|
||||
)
|
||||
|
||||
|
||||
def _query_int(name: str, default: int) -> int:
|
||||
@@ -36,3 +40,33 @@ def get_shipping_order_extraction_health():
|
||||
running_stale_seconds=_query_int('running_stale_seconds', 1800),
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-extraction-runs', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_order_extraction_diagnostic_runs():
|
||||
"""分页返回只读订单识别运行摘要;所有管理员默认可查看且访问留痕。"""
|
||||
page = _query_int('page', 1)
|
||||
page_size = _query_int('page_size', 25)
|
||||
if page < 1 or not 1 <= page_size <= 100:
|
||||
raise ValidationError('page must be positive and page_size must be between 1 and 100')
|
||||
payload = list_order_extraction_diagnostic_runs(
|
||||
admin_user_id=g.current_user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
status=request.args.get('status'),
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-extraction-runs/<run_no>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_order_extraction_diagnostic_run_detail(run_no: str):
|
||||
"""读取单次 Run 的脱敏诊断详情;无重试、取消或其他状态变更操作。"""
|
||||
payload = get_order_extraction_diagnostic_run(
|
||||
admin_user_id=g.current_user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
run_no=run_no,
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
@@ -59,6 +59,15 @@ def update_shipping_order_field(field_id: str):
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/fields/order', methods=['PUT'])
|
||||
@require_admin
|
||||
def reorder_shipping_order_fields():
|
||||
"""保存字段目录当前全局顺序,不创建或修改 Schema 版本。"""
|
||||
return _ok(service.reorder_fields(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/fields/<field_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_shipping_order_field(field_id: str):
|
||||
|
||||
@@ -13,6 +13,7 @@ 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
|
||||
@@ -65,7 +66,9 @@ def list_agent_guides(agent_id):
|
||||
获取指定应用的新手指南列表 (需登录)
|
||||
用途:客户端 Chat 界面点击新手指南
|
||||
"""
|
||||
get_current_user() # 确保已登录
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
|
||||
if agent_id == 0:
|
||||
generic_agent = (
|
||||
@@ -79,6 +82,9 @@ 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)
|
||||
@@ -108,7 +114,7 @@ def list_public_agents():
|
||||
"""
|
||||
agents = (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.filter(Agent.is_active.is_(True), Agent.exposure_mode == 'workspace')
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
|
||||
+83
-2
@@ -28,7 +28,7 @@ from app.services.dify import DifyService
|
||||
from app.core.config.settings import Config
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
from app.core.decorators import require_agent_permission
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback, ShippingOrderExtractionRun
|
||||
from app import db
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
@@ -209,7 +209,13 @@ def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str:
|
||||
return value
|
||||
|
||||
|
||||
def _serialize_session(session: ChatSession) -> dict:
|
||||
def _serialize_session(
|
||||
session: ChatSession,
|
||||
*,
|
||||
unseen_order_extraction_count: int = 0,
|
||||
unseen_order_extraction_severity: str | None = None,
|
||||
) -> dict:
|
||||
"""输出会话摘要及订单识别待查看聚合,不返回 Run 内容或错误正文。"""
|
||||
last_active = session.last_active_at or session.created_at
|
||||
return {
|
||||
'id': session.id,
|
||||
@@ -217,9 +223,38 @@ def _serialize_session(session: ChatSession) -> dict:
|
||||
'title': session.title or '',
|
||||
'created_at': last_active.isoformat() if last_active else '',
|
||||
'status': session.status,
|
||||
'unseen_order_extraction_count': max(0, int(unseen_order_extraction_count or 0)),
|
||||
'unseen_order_extraction_severity': unseen_order_extraction_severity,
|
||||
}
|
||||
|
||||
|
||||
def _order_extraction_attention_by_conversation(*, user_id: int, agent_id: int, conversation_ids: set[str]) -> dict[str, tuple[int, str]]:
|
||||
"""聚合阶段4之后生成、且当前用户尚未确认的终态订单识别提醒。"""
|
||||
if not conversation_ids:
|
||||
return {}
|
||||
severity_rank = {'info': 1, 'warning': 2, 'error': 3}
|
||||
status_severity = {'completed': 'info', 'needs_review': 'warning', 'failed': 'error', 'cancelled': 'error'}
|
||||
rows = db.session.query(
|
||||
ShippingOrderExtractionRun.conversation_id,
|
||||
ShippingOrderExtractionRun.status,
|
||||
).filter(
|
||||
ShippingOrderExtractionRun.user_id == user_id,
|
||||
ShippingOrderExtractionRun.owner_agent_id == agent_id,
|
||||
ShippingOrderExtractionRun.conversation_id.in_(conversation_ids),
|
||||
ShippingOrderExtractionRun.attention_generated_at.isnot(None),
|
||||
ShippingOrderExtractionRun.seen_at.is_(None),
|
||||
).all()
|
||||
aggregate: dict[str, tuple[int, str]] = {}
|
||||
for conversation_id, status in rows:
|
||||
severity = status_severity.get(str(status or ''), 'info')
|
||||
current_count, current_severity = aggregate.get(conversation_id, (0, severity))
|
||||
aggregate[conversation_id] = (
|
||||
current_count + 1,
|
||||
severity if severity_rank[severity] >= severity_rank[current_severity] else current_severity,
|
||||
)
|
||||
return aggregate
|
||||
|
||||
|
||||
def _get_chat_session(user_id: int, agent_id: int, session_id: str | None):
|
||||
session_key = str(session_id or '').strip()
|
||||
if not session_key:
|
||||
@@ -1035,6 +1070,15 @@ def get_chat_sessions():
|
||||
})
|
||||
|
||||
sessions.sort(key=lambda item: item.get('created_at') or '', reverse=True)
|
||||
attention_by_conversation = _order_extraction_attention_by_conversation(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_ids={str(item['conversation_id']) for item in sessions if item.get('conversation_id')},
|
||||
)
|
||||
for item in sessions:
|
||||
count, severity = attention_by_conversation.get(str(item.get('conversation_id') or ''), (0, None))
|
||||
item['unseen_order_extraction_count'] = count
|
||||
item['unseen_order_extraction_severity'] = severity
|
||||
return jsonify(sessions[:20])
|
||||
|
||||
@chat_bp.route('/sessions', methods=['DELETE'])
|
||||
@@ -1119,6 +1163,29 @@ def get_chat_messages():
|
||||
ChatLog.conversation_id == conversation_id,
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
def _is_order_extraction_state_card(payload):
|
||||
"""仅识别正式 Run 状态卡,避免用户上传记录在历史回放中被投影成重复助手卡。"""
|
||||
if not isinstance(payload, dict):
|
||||
return False
|
||||
run_no = str(payload.get('order_extraction_run_no') or '').strip()
|
||||
return bool(run_no and payload.get('formId') == f'shipping-order-extraction-run:{run_no}')
|
||||
|
||||
run_nos = {
|
||||
str(log.payload.get('order_extraction_run_no') or '').strip()
|
||||
for log in logs
|
||||
if _is_order_extraction_state_card(log.payload)
|
||||
}
|
||||
order_extraction_runs = {}
|
||||
if run_nos:
|
||||
order_extraction_runs = {
|
||||
run.run_no: run
|
||||
for run in db.session.query(ShippingOrderExtractionRun).filter(
|
||||
ShippingOrderExtractionRun.user_id == g.current_user.id,
|
||||
ShippingOrderExtractionRun.owner_agent_id == g.current_agent.id,
|
||||
ShippingOrderExtractionRun.conversation_id == (session.session_id if session else conversation_id),
|
||||
ShippingOrderExtractionRun.run_no.in_(run_nos),
|
||||
).all()
|
||||
}
|
||||
messages = []
|
||||
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
|
||||
for log in logs:
|
||||
@@ -1129,11 +1196,25 @@ def get_chat_messages():
|
||||
for key, value in raw_payload.items()
|
||||
if key != 'user_attachments'
|
||||
}
|
||||
run_no = str(assistant_payload.get('order_extraction_run_no') or '').strip()
|
||||
is_order_extraction_state_card = _is_order_extraction_state_card(raw_payload)
|
||||
if is_order_extraction_state_card and run_no in order_extraction_runs:
|
||||
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_message_state
|
||||
|
||||
assistant_payload['shipping_order_extraction_state'] = serialize_order_extraction_message_state(
|
||||
order_extraction_runs[run_no],
|
||||
)
|
||||
if log.query or user_attachments:
|
||||
user_msg = {'role': 'user', 'content': _user_facing_chat_query(log.query or '', agent_code=agent_code)}
|
||||
if user_attachments:
|
||||
user_msg['attachments'] = user_attachments
|
||||
messages.append(user_msg)
|
||||
if (
|
||||
str(raw_payload.get('formId') or '').strip()
|
||||
== f'shipping-order-extraction-user:{run_no}'
|
||||
):
|
||||
# 用户上传记录携带 Run 锚点只用于关联,不能再回放为一张助手状态卡。
|
||||
continue
|
||||
if (
|
||||
not log.answer
|
||||
and not log.message_type
|
||||
|
||||
+17
-13
@@ -11,6 +11,11 @@ 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
|
||||
@@ -441,7 +446,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': user.default_agent_id,
|
||||
'default_agent_id': visible_default_agent_id(user),
|
||||
'feature_permissions': user.get_feature_permissions(),
|
||||
'source': source,
|
||||
'access_token': issue_local_access_token(user),
|
||||
@@ -770,7 +775,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': 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})
|
||||
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})
|
||||
except WeComLoginError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
@@ -900,7 +905,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': 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})
|
||||
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})
|
||||
except WeComLoginError:
|
||||
db.session.rollback()
|
||||
current_app.logger.warning('[casdoor_login] business_reject')
|
||||
@@ -1341,6 +1346,7 @@ 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',
|
||||
@@ -1352,20 +1358,20 @@ def home():
|
||||
]
|
||||
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]
|
||||
favorite_ids = [f.agent_id for f in favorites if f.agent_id in allowed_agent_ids]
|
||||
qqs = db.session.query(QuickQuestion).filter(
|
||||
or_(
|
||||
QuickQuestion.user_id == user.id,
|
||||
and_(QuickQuestion.user_id.is_(None), QuickQuestion.is_enabled.is_(True)),
|
||||
)
|
||||
).all()
|
||||
).filter(QuickQuestion.agent_id.in_(allowed_agent_ids)).all() if allowed_agent_ids else []
|
||||
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:
|
||||
if agent and agent.id in allowed_agent_ids:
|
||||
registry = serialize_registry_fields(agent)
|
||||
embedded_agents.append({
|
||||
'id': agent.id,
|
||||
@@ -1374,7 +1380,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': 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})
|
||||
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})
|
||||
try:
|
||||
return _run_db_with_retry(_load_home_payload, label='user.home')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
@@ -1386,6 +1392,7 @@ 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:
|
||||
@@ -1404,6 +1411,7 @@ 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()
|
||||
@@ -1427,6 +1435,7 @@ 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'})
|
||||
@@ -1820,12 +1829,7 @@ def get_agent_details(id):
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
agent = db.session.get(Agent, id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
if user.role != 'admin':
|
||||
has_permission = agent in user.agents
|
||||
if not has_permission:
|
||||
raise ForbiddenError('Access denied')
|
||||
require_user_application_access(agent, user)
|
||||
|
||||
from app.services.agent_registry.resolver import resolve_runtime_provider
|
||||
from app.services.agent_registry.serialization import serialize_agent_for_user_detail
|
||||
|
||||
@@ -918,6 +918,44 @@ def workspace_get_shipping_order_extraction_run(run_no: str):
|
||||
return _ok(serialize_order_extraction_run(get_order_extraction_run(user_id=user.id, run_no=run_no)))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/progress-events', methods=['GET'])
|
||||
def workspace_list_shipping_order_extraction_progress_events(run_no: str):
|
||||
"""返回当前用户展开状态卡时所需的脱敏业务阶段时间线。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_extraction_run_service import list_user_order_extraction_progress_events
|
||||
|
||||
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>/seen', methods=['POST'])
|
||||
def workspace_mark_shipping_order_extraction_run_seen(run_no: str):
|
||||
"""确认当前用户已加载终态订单识别卡片;仅用于会话待查看提醒,不改变业务结果。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_extraction_run_service import mark_order_extraction_run_seen
|
||||
|
||||
seen = mark_order_extraction_run_seen(user_id=user.id, run_no=run_no)
|
||||
db.session.commit()
|
||||
return _ok({'seen': seen})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/retry', methods=['POST'])
|
||||
def workspace_retry_shipping_order_extraction_run(run_no: str):
|
||||
"""复用原附件与冻结快照,重新入队当前用户失败的订单抽取 Run。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
retry_order_extraction_run,
|
||||
serialize_order_extraction_run,
|
||||
)
|
||||
|
||||
run, reused = retry_order_extraction_run(user_id=user.id, run_no=run_no)
|
||||
db.session.commit()
|
||||
return ok(
|
||||
{'run': serialize_order_extraction_run(run), 'reused': reused},
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
status=202,
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs', methods=['GET'])
|
||||
def workspace_list_shipping_order_extraction_runs():
|
||||
"""列出当前用户订单抽取 Run,可按 HXOPS 会话过滤。"""
|
||||
|
||||
@@ -13,8 +13,9 @@ 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, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.services.agent_user_access import require_user_application_access
|
||||
|
||||
|
||||
def _get_current_user() -> User:
|
||||
@@ -47,7 +48,7 @@ def _resolve_request_agent_id() -> str | None:
|
||||
def require_agent_permission(f):
|
||||
"""
|
||||
装饰器:校验当前用户是否拥有指定 Agent 访问权限。
|
||||
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → admin 放行或检查 user.agents。
|
||||
核心逻辑:从 body/query/form 读 agent_id → 阻断内部执行器 → admin 放行 workspace 或检查用户授权。
|
||||
Args:
|
||||
f: 被装饰的视图函数。
|
||||
Returns:
|
||||
@@ -63,13 +64,8 @@ def require_agent_permission(f):
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
agent = Agent.query.get(agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Agent not found')
|
||||
require_user_application_access(agent, user)
|
||||
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
|
||||
|
||||
@@ -8,7 +8,12 @@ backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from types import SimpleNamespace
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
@@ -16,10 +21,80 @@ from app.jobs.context import JobContext
|
||||
from app.jobs.queue import fail_job, finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Agent, Job, ShippingOrderExtractionRun
|
||||
from app.models import (
|
||||
Agent,
|
||||
Job,
|
||||
ShippingOrderExtractionPlan,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction_run_result
|
||||
from app.services.shipping_notice.order_extraction_run_service import transition_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_workflow import execute_order_extraction_workflow
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
mark_order_extraction_persistence_started,
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_workflow import (
|
||||
build_deterministic_unit_orders,
|
||||
execute_order_extraction_workflow,
|
||||
validate_unit_orders,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_progress import (
|
||||
record_order_extraction_progress_event,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_merge import merge_unit_orders
|
||||
from app.services.shipping_notice.order_extraction_provider_guard import (
|
||||
assert_circuit_closed,
|
||||
provider_slot,
|
||||
record_provider_failure,
|
||||
record_provider_success,
|
||||
)
|
||||
|
||||
|
||||
def _execute_dify_unit_with_retry(
|
||||
*, app, run_snapshot: dict, unit_snapshot: dict, provider_snapshot: dict, timeout_seconds: int,
|
||||
max_attempts: int, backoff_ms: int, job_id: int, job_attempt: int,
|
||||
provider_max_concurrency: int, circuit_failure_threshold: int, circuit_cooldown_seconds: int,
|
||||
) -> dict:
|
||||
"""在线程独立应用上下文中用纯快照执行网络调用,并做有限指数退避重试。"""
|
||||
last_error: Exception | None = None
|
||||
started = time.perf_counter()
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
with app.app_context():
|
||||
local_run = SimpleNamespace(**run_snapshot)
|
||||
local_unit = SimpleNamespace(**unit_snapshot)
|
||||
local_provider = SimpleNamespace(**provider_snapshot)
|
||||
|
||||
def observe(event):
|
||||
event['job_id'] = job_id
|
||||
event['attempt_count'] = job_attempt
|
||||
record_order_extraction_progress_event(run_no=local_run.run_no, event=event)
|
||||
|
||||
assert_circuit_closed(local_provider.id)
|
||||
with provider_slot(local_provider.id, max_concurrency=provider_max_concurrency):
|
||||
orders, meta = execute_order_extraction_workflow(
|
||||
run=local_run, unit=local_unit, provider=local_provider,
|
||||
timeout_seconds=timeout_seconds, event_observer=observe,
|
||||
)
|
||||
record_provider_success(local_provider.id)
|
||||
return {
|
||||
'unit_id': local_unit.id, 'orders': orders, 'meta': {**meta, 'execution_mode': 'dify'},
|
||||
'attempts': attempt, 'latency_ms': int((time.perf_counter() - started) * 1000),
|
||||
}
|
||||
except Exception as exc:
|
||||
last_error = exc
|
||||
retryable = not isinstance(exc, AppError) or bool(getattr(exc, 'retryable', False))
|
||||
if retryable:
|
||||
record_provider_failure(
|
||||
int(provider_snapshot['id']), threshold=circuit_failure_threshold,
|
||||
cooldown_seconds=circuit_cooldown_seconds,
|
||||
)
|
||||
if not retryable or attempt >= max_attempts:
|
||||
break
|
||||
delay = (backoff_ms / 1000) * (2 ** (attempt - 1))
|
||||
time.sleep(delay + random.uniform(0, min(delay * 0.25, 0.5)))
|
||||
assert last_error is not None
|
||||
raise last_error
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_ORDER_EXTRACTION)
|
||||
@@ -98,6 +173,9 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
)
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='running', phase='calling_provider')
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
|
||||
ensure_order_extraction_plan(run)
|
||||
run.current_job_id = job.id
|
||||
run.attempt_count = owned_attempt
|
||||
db.session.commit()
|
||||
@@ -110,17 +188,140 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
workflow_meta = saved_provider_result.get('workflow')
|
||||
workflow_meta = workflow_meta if isinstance(workflow_meta, dict) else {}
|
||||
else:
|
||||
orders, workflow_meta = execute_order_extraction_workflow(
|
||||
run=run,
|
||||
provider=provider,
|
||||
timeout_seconds=timeout_seconds,
|
||||
plan = run.extraction_plan
|
||||
units = (
|
||||
ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id)
|
||||
.order_by(ShippingOrderExtractionUnit.position.asc())
|
||||
.all()
|
||||
)
|
||||
orders = []
|
||||
unit_workflows = []
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
dify_units = []
|
||||
for unit in units:
|
||||
if unit.status == 'succeeded' and isinstance(unit.result_json, dict):
|
||||
unit_orders = unit.result_json.get('orders')
|
||||
if isinstance(unit_orders, list):
|
||||
orders.extend(item for item in unit_orders if isinstance(item, dict))
|
||||
unit_workflows.append(dict(unit.result_json.get('workflow') or {}))
|
||||
continue
|
||||
if unit.status == 'failed':
|
||||
transition_order_extraction_unit(unit, target_status='pending')
|
||||
transition_order_extraction_unit(unit, target_status='running')
|
||||
db.session.commit()
|
||||
deterministic_orders = build_deterministic_unit_orders(run, unit=unit)
|
||||
if deterministic_orders is not None:
|
||||
unit_orders = validate_unit_orders(run, unit=unit, orders=deterministic_orders)
|
||||
unit_meta = {'execution_mode': 'deterministic', 'workflow_run_id': None}
|
||||
transition_order_extraction_unit(
|
||||
unit, target_status='succeeded',
|
||||
result={'orders': unit_orders, 'workflow': unit_meta},
|
||||
)
|
||||
db.session.commit()
|
||||
orders.extend(unit_orders)
|
||||
unit_workflows.append(unit_meta)
|
||||
else:
|
||||
dify_units.append(unit)
|
||||
|
||||
config = run.provider_config_json or {}
|
||||
concurrency = int(config.get('unit_concurrency') or 2)
|
||||
unit_max_attempts = int(config.get('unit_max_attempts') or 2)
|
||||
backoff_ms = int(config.get('unit_retry_backoff_ms') or 500)
|
||||
max_model_units = int(config.get('max_model_units') or 20)
|
||||
if len(dify_units) > max_model_units:
|
||||
raise AppError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_MODEL_BUDGET_EXCEEDED',
|
||||
message='订单抽取模型单元数量超过冻结预算', http_status=409,
|
||||
)
|
||||
provider_max_concurrency = int(config.get('provider_max_concurrency') or 4)
|
||||
circuit_failure_threshold = int(config.get('circuit_failure_threshold') or 5)
|
||||
circuit_cooldown_seconds = int(config.get('circuit_cooldown_seconds') or 60)
|
||||
app = current_app._get_current_object()
|
||||
failures: list[tuple[ShippingOrderExtractionUnit, Exception]] = []
|
||||
completed_by_unit: dict[int, dict] = {}
|
||||
with ThreadPoolExecutor(max_workers=min(concurrency, len(dify_units) or 1)) as pool:
|
||||
run_snapshot = {
|
||||
'id': run.id, 'run_no': run.run_no, 'user_id': run.user_id,
|
||||
'input_snapshot_hash': run.input_snapshot_hash,
|
||||
'input_snapshot_json': run.input_snapshot_json,
|
||||
}
|
||||
provider_snapshot = {
|
||||
'id': provider.id, 'api_base_url': provider.api_base_url,
|
||||
'dify_api_key': provider.dify_api_key,
|
||||
}
|
||||
futures = {
|
||||
pool.submit(
|
||||
_execute_dify_unit_with_retry,
|
||||
app=app, run_snapshot=run_snapshot,
|
||||
unit_snapshot={
|
||||
'id': unit.id, 'intake_id': unit.intake_id,
|
||||
'document_id': unit.document_id, 'document_type': unit.document_type,
|
||||
'unit_type': unit.unit_type,
|
||||
},
|
||||
provider_snapshot=provider_snapshot,
|
||||
timeout_seconds=timeout_seconds, max_attempts=unit_max_attempts,
|
||||
backoff_ms=backoff_ms, job_id=job.id, job_attempt=owned_attempt,
|
||||
provider_max_concurrency=provider_max_concurrency,
|
||||
circuit_failure_threshold=circuit_failure_threshold,
|
||||
circuit_cooldown_seconds=circuit_cooldown_seconds,
|
||||
): unit for unit in dify_units
|
||||
}
|
||||
for future in as_completed(futures):
|
||||
unit = futures[future]
|
||||
try:
|
||||
item = future.result()
|
||||
unit.attempt_count = max(int(unit.attempt_count or 0), int(item['attempts']))
|
||||
meta = {**item['meta'], 'latency_ms': item['latency_ms'], 'attempts': item['attempts']}
|
||||
transition_order_extraction_unit(
|
||||
unit, target_status='succeeded',
|
||||
result={'orders': item['orders'], 'workflow': meta},
|
||||
)
|
||||
completed_by_unit[unit.id] = {'orders': item['orders'], 'meta': meta}
|
||||
except Exception as exc:
|
||||
transition_order_extraction_unit(
|
||||
unit, target_status='failed',
|
||||
error_code=str(getattr(exc, 'code', None) or 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED'),
|
||||
error_message=str(exc),
|
||||
)
|
||||
failures.append((unit, exc))
|
||||
db.session.commit()
|
||||
if failures and not orders and not completed_by_unit:
|
||||
raise failures[0][1]
|
||||
for unit in dify_units:
|
||||
item = completed_by_unit.get(unit.id)
|
||||
if item is None:
|
||||
continue
|
||||
orders.extend(item['orders'])
|
||||
unit_workflows.append(item['meta'])
|
||||
schema_snapshot = run.input_snapshot_json.get('schema') or {}
|
||||
orders = merge_unit_orders(
|
||||
orders=orders,
|
||||
schema_definition=schema_snapshot.get('definition') or {},
|
||||
)
|
||||
workflow_meta = {
|
||||
'execution_mode': 'unit_parallel',
|
||||
'unit_count': len(units),
|
||||
'unit_concurrency': concurrency,
|
||||
'dify_unit_count': sum(
|
||||
1 for item in unit_workflows if item.get('execution_mode') == 'dify'
|
||||
),
|
||||
'deterministic_unit_count': sum(
|
||||
1 for item in unit_workflows if item.get('execution_mode') == 'deterministic'
|
||||
),
|
||||
'failed_unit_count': len(failures),
|
||||
'workflow_run_ids': [
|
||||
str(item['workflow_run_id']) for item in unit_workflows if item.get('workflow_run_id')
|
||||
],
|
||||
}
|
||||
# Dify 观察器以独立事务更新进度投影,返回后刷新主Session避免旧对象覆盖投影。
|
||||
db.session.refresh(run)
|
||||
run.provider_result_json = {'orders': orders, 'workflow': workflow_meta}
|
||||
from datetime import datetime
|
||||
|
||||
run.provider_completed_at = datetime.utcnow()
|
||||
if workflow_meta.get('workflow_run_id'):
|
||||
run.dify_workflow_run_id = str(workflow_meta['workflow_run_id'])[:128]
|
||||
if workflow_meta.get('workflow_run_ids'):
|
||||
run.dify_workflow_run_id = str(workflow_meta['workflow_run_ids'][-1])[:128]
|
||||
# [STEP 1] Provider 成功即建立独立提交边界,HXOPS 后续落库重试不得再次调用 Dify。
|
||||
db.session.commit()
|
||||
ctx.logger.info(
|
||||
@@ -130,6 +331,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
owned_attempt,
|
||||
int((time.perf_counter() - handler_started) * 1000),
|
||||
)
|
||||
mark_order_extraction_persistence_started(run)
|
||||
result = submit_order_extraction_run_result(run=run, orders=orders)
|
||||
|
||||
summary = {
|
||||
@@ -140,6 +342,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
'pending_count': int(result.get('pending_count') or 0),
|
||||
'non_shipping_count': int(result.get('non_shipping_count') or 0),
|
||||
'workflow': workflow_meta,
|
||||
'failed_unit_count': int(workflow_meta.get('failed_unit_count') or 0),
|
||||
}
|
||||
transition_order_extraction_run(
|
||||
run,
|
||||
@@ -148,7 +351,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
result=summary,
|
||||
)
|
||||
db.session.commit()
|
||||
final_status = 'needs_review' if summary['pending_count'] else 'completed'
|
||||
final_status = 'needs_review' if summary['pending_count'] or summary['failed_unit_count'] else 'completed'
|
||||
transition_order_extraction_run(run, target_status=final_status, result=summary)
|
||||
db.session.commit()
|
||||
finish_job(job.id, result=summary, message='订单抽取完成', owned_attempt=owned_attempt)
|
||||
@@ -173,6 +376,23 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
str(getattr(exc, 'code', None) or 'UNCLASSIFIED'),
|
||||
)
|
||||
if run is not None and run.status in {'queued', 'running', 'failed'}:
|
||||
running_unit = (
|
||||
ShippingOrderExtractionUnit.query.join(ShippingOrderExtractionPlan)
|
||||
.filter(
|
||||
ShippingOrderExtractionPlan.run_id == run.id,
|
||||
ShippingOrderExtractionUnit.status == 'running',
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if running_unit is not None:
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
transition_order_extraction_unit(
|
||||
running_unit,
|
||||
target_status='failed',
|
||||
error_code=str(getattr(exc, 'code', None) or 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED'),
|
||||
error_message=str(exc),
|
||||
)
|
||||
if retryable and owned_attempt < int(job.max_attempts or 1):
|
||||
if run.status == 'running':
|
||||
transition_order_extraction_run(run, target_status='queued', phase='retry_queued')
|
||||
|
||||
@@ -45,8 +45,12 @@ from app.models.shipping_order_schema import (
|
||||
)
|
||||
from app.models.shipping_order_customer_match import ShippingOrderCustomerMatch
|
||||
from app.models.shipping_order_extraction_run import (
|
||||
ShippingOrderExtractionDiagnosticAudit,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionPlan,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionRunIntake,
|
||||
ShippingOrderExtractionUnit,
|
||||
)
|
||||
from app.models.shipping_inventory_config import (
|
||||
ShippingInventoryField,
|
||||
@@ -136,6 +140,10 @@ __all__ = [
|
||||
'ShippingOrderCustomerMatch',
|
||||
'ShippingOrderExtractionRun',
|
||||
'ShippingOrderExtractionRunIntake',
|
||||
'ShippingOrderExtractionPlan',
|
||||
'ShippingOrderExtractionUnit',
|
||||
'ShippingOrderExtractionProgressEvent',
|
||||
'ShippingOrderExtractionDiagnosticAudit',
|
||||
'ShippingCustomer',
|
||||
'ShippingCustomerIdentifier',
|
||||
'ShippingCustomerExternalRef',
|
||||
|
||||
@@ -11,7 +11,19 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy import (
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
ForeignKeyConstraint,
|
||||
Index,
|
||||
Integer,
|
||||
JSON,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
@@ -32,6 +44,15 @@ class ShippingOrderExtractionRun(Base):
|
||||
Index('ix_shipping_order_extraction_runs_user_created', 'user_id', 'created_at'),
|
||||
Index('ix_shipping_order_extraction_runs_conversation_created', 'conversation_id', 'created_at'),
|
||||
Index('ix_shipping_order_extraction_runs_status_created', 'status', 'created_at'),
|
||||
Index(
|
||||
'uq_shipping_order_extraction_runs_active_conversation',
|
||||
'user_id',
|
||||
'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')"),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -63,6 +84,18 @@ class ShippingOrderExtractionRun(Base):
|
||||
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)
|
||||
# 当前投影只包含用户安全的阶段事实;高频原始事件写入独立明细表。
|
||||
progress_version: Mapped[int] = mapped_column(Integer, default=1, server_default='1', nullable=False)
|
||||
current_stage_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
active_stage_codes_json: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)
|
||||
completed_stage_codes_json: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)
|
||||
progress_message_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
progress_health: Mapped[str] = mapped_column(String(32), default='normal', server_default='normal', nullable=False)
|
||||
last_activity_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
progress_summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
progress_mapping_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
attention_generated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
seen_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
lock_version: Mapped[int] = mapped_column(Integer, default=1, server_default='1', nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
@@ -75,6 +108,9 @@ class ShippingOrderExtractionRun(Base):
|
||||
intakes: Mapped[list['ShippingOrderExtractionRunIntake']] = relationship(
|
||||
back_populates='run', cascade='all, delete-orphan', order_by='ShippingOrderExtractionRunIntake.position',
|
||||
)
|
||||
extraction_plan: Mapped[Optional['ShippingOrderExtractionPlan']] = relationship(
|
||||
back_populates='run', cascade='all, delete-orphan', uselist=False,
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderExtractionRunIntake(Base):
|
||||
@@ -104,3 +140,133 @@ class ShippingOrderExtractionRunIntake(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
run: Mapped['ShippingOrderExtractionRun'] = relationship(back_populates='intakes')
|
||||
|
||||
|
||||
class ShippingOrderExtractionPlan(Base):
|
||||
"""Run 的不可变抽取计划;计划版本和快照哈希共同锚定冻结输入。"""
|
||||
|
||||
__tablename__ = 'shipping_order_extraction_plans'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('run_id', name='uq_shipping_order_extraction_plans_run'),
|
||||
CheckConstraint(
|
||||
"status IN ('planned', 'running', 'completed', 'partial_failed', 'failed')",
|
||||
name='ck_shipping_order_extraction_plans_status',
|
||||
),
|
||||
Index('ix_shipping_order_extraction_plans_status_created', 'status', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
# 版本标识是稳定的可读契约,须容纳带业务命名空间的版本号。
|
||||
plan_version: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='planned', server_default='planned')
|
||||
unit_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
|
||||
run: Mapped['ShippingOrderExtractionRun'] = relationship(back_populates='extraction_plan')
|
||||
units: Mapped[list['ShippingOrderExtractionUnit']] = relationship(
|
||||
back_populates='plan', cascade='all, delete-orphan', order_by='ShippingOrderExtractionUnit.position',
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderExtractionUnit(Base):
|
||||
"""计划内单个冻结文档抽取单元;状态、结果和错误相互隔离。"""
|
||||
|
||||
__tablename__ = 'shipping_order_extraction_units'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('plan_id', 'document_id', name='uq_shipping_order_extraction_units_document'),
|
||||
UniqueConstraint('plan_id', 'position', name='uq_shipping_order_extraction_units_position'),
|
||||
CheckConstraint(
|
||||
"unit_type IN ('document_extraction', 'email_relation')",
|
||||
name='ck_shipping_order_extraction_units_type',
|
||||
),
|
||||
CheckConstraint(
|
||||
"status IN ('pending', 'running', 'succeeded', 'failed', 'skipped')",
|
||||
name='ck_shipping_order_extraction_units_status',
|
||||
),
|
||||
ForeignKeyConstraint(
|
||||
['document_id', 'intake_id'],
|
||||
['shipping_notice_documents.id', 'shipping_notice_documents.intake_id'],
|
||||
name='fk_shipping_order_extraction_units_document_intake',
|
||||
),
|
||||
Index('ix_shipping_order_extraction_units_plan_status', 'plan_id', 'status'),
|
||||
Index('ix_shipping_order_extraction_units_document', 'document_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
plan_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_plans.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
intake_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_intakes.id'), nullable=False)
|
||||
document_id: Mapped[int] = mapped_column(nullable=False)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
unit_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
document_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
content_hash: 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')
|
||||
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)
|
||||
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)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
|
||||
plan: Mapped['ShippingOrderExtractionPlan'] = relationship(back_populates='units')
|
||||
|
||||
|
||||
class ShippingOrderExtractionProgressEvent(Base):
|
||||
"""订单抽取的脱敏进度明细;事件幂等键抵御 SSE 断线重放。"""
|
||||
|
||||
__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'),
|
||||
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'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extraction_runs.id', ondelete='CASCADE'), nullable=False)
|
||||
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)
|
||||
received_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
details_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)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingOrderExtractionDiagnosticAudit(Base):
|
||||
"""管理员订单抽取诊断访问审计;不记录Run业务正文或原始筛选参数。"""
|
||||
|
||||
__tablename__ = 'shipping_order_extraction_diagnostic_audits'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_order_extraction_diagnostic_audits_run_created', 'run_id', 'created_at'),
|
||||
Index('ix_shipping_order_extraction_diagnostic_audits_admin_created', 'admin_user_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
admin_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_extraction_runs.id'), nullable=True)
|
||||
action: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
query_summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
@@ -62,7 +62,7 @@ class ShippingOrderSchema(Base):
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
fields: Mapped[list['ShippingOrderField']] = relationship(
|
||||
back_populates='schema', cascade='all, delete-orphan', order_by='ShippingOrderField.field_code'
|
||||
back_populates='schema', cascade='all, delete-orphan', order_by='ShippingOrderField.display_sequence'
|
||||
)
|
||||
versions: Mapped[list['ShippingOrderSchemaVersion']] = relationship(
|
||||
back_populates='schema', cascade='all, delete-orphan', order_by='ShippingOrderSchemaVersion.version'
|
||||
@@ -99,6 +99,7 @@ class ShippingOrderField(Base):
|
||||
value_type: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
field_category: Mapped[str] = mapped_column(String(32), nullable=False, default=_default_field_category)
|
||||
collection_mode: Mapped[str] = mapped_column(String(32), nullable=False, default='llm_extraction')
|
||||
display_sequence: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
|
||||
published_once: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false'))
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
|
||||
@@ -29,9 +29,20 @@ def serialize_agent(agent: Agent) -> dict:
|
||||
return serialize_agent_for_admin(agent)
|
||||
|
||||
|
||||
def list_agents() -> list[dict]:
|
||||
"""返回全部 Agent(按 id 升序)。"""
|
||||
agents = db.session.query(Agent).order_by(Agent.id.asc()).all()
|
||||
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()
|
||||
return [serialize_agent(a) for a in agents]
|
||||
|
||||
|
||||
@@ -346,6 +357,11 @@ 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,7 +20,12 @@ 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_by(is_active=True).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
|
||||
)
|
||||
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
|
||||
@@ -39,7 +44,13 @@ 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)).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
|
||||
)
|
||||
return {
|
||||
'pending_approvals': pending_approvals,
|
||||
'pending_requests': pending_requests,
|
||||
|
||||
@@ -13,6 +13,7 @@ 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]:
|
||||
@@ -82,6 +83,7 @@ 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)
|
||||
@@ -122,6 +124,8 @@ 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
|
||||
@@ -164,6 +168,8 @@ 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,
|
||||
@@ -176,6 +182,8 @@ 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)
|
||||
|
||||
|
||||
@@ -189,6 +197,7 @@ 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:
|
||||
@@ -233,5 +242,6 @@ 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,6 +13,7 @@ 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': '重置为'}
|
||||
@@ -32,7 +33,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 = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all()
|
||||
agents = load_grantable_agents(agent_ids)
|
||||
return users, agents
|
||||
|
||||
|
||||
@@ -104,16 +105,18 @@ 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 = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all()
|
||||
agents = load_grantable_agents(agent_ids)
|
||||
user.agents = agents
|
||||
db.session.commit()
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
def list_permission_requests() -> list[dict]:
|
||||
"""返回全部权限申请(按 created_at 降序)。"""
|
||||
"""返回 workspace 应用的权限申请;内部执行器申请仅保留数据库审计。"""
|
||||
reqs = (
|
||||
db.session.query(PermissionRequest)
|
||||
.join(Agent, Agent.id == PermissionRequest.agent_id)
|
||||
.filter(Agent.exposure_mode == 'workspace')
|
||||
.order_by(PermissionRequest.created_at.desc())
|
||||
.all()
|
||||
)
|
||||
@@ -130,10 +133,13 @@ def approve_permission_request(request_id: int) -> dict:
|
||||
if not req:
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
req.status = 'approved'
|
||||
req.reviewed_at = datetime.utcnow()
|
||||
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):
|
||||
user.agents.append(agent)
|
||||
if user and user.wecom_userid:
|
||||
|
||||
@@ -286,6 +286,7 @@ 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))
|
||||
|
||||
@@ -16,6 +16,7 @@ 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
|
||||
|
||||
@@ -80,7 +81,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],
|
||||
'agent_ids': [agent.id for agent in user.agents if is_user_application(agent)],
|
||||
}
|
||||
|
||||
|
||||
@@ -209,7 +210,7 @@ def create_user(data: dict[str, Any]) -> dict:
|
||||
db.session.add(user)
|
||||
try:
|
||||
if data.get('agent_ids'):
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
agents = load_grantable_agents(data['agent_ids'])
|
||||
user.agents = agents
|
||||
casdoor_service.sync_create_user(
|
||||
username=user.username,
|
||||
@@ -261,7 +262,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 = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
agents = load_grantable_agents(data['agent_ids'])
|
||||
user.agents = agents
|
||||
if new_password:
|
||||
casdoor_service.sync_update_user(user, new_password=new_password)
|
||||
|
||||
@@ -20,6 +20,7 @@ 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
|
||||
|
||||
@@ -313,10 +314,11 @@ def provision_user(data: dict[str, Any]) -> tuple[dict, int]:
|
||||
except (TypeError, ValueError):
|
||||
db.session.rollback()
|
||||
raise ValidationError('agent_ids must be integer array')
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(unique_ids)).all()
|
||||
if len(agents) != len(unique_ids):
|
||||
try:
|
||||
agents = load_grantable_agents(unique_ids)
|
||||
except ValidationError:
|
||||
db.session.rollback()
|
||||
raise ValidationError('Some agent_ids are invalid')
|
||||
raise
|
||||
user.agents = agents
|
||||
else:
|
||||
user.agents = []
|
||||
|
||||
@@ -17,6 +17,7 @@ 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,
|
||||
@@ -33,6 +34,7 @@ __all__ = [
|
||||
'normalize_capabilities',
|
||||
'resolve_agent_code',
|
||||
'resolve_conversation_mode',
|
||||
'resolve_effective_role',
|
||||
'resolve_capabilities',
|
||||
'resolve_handler',
|
||||
'resolve_handler_for_agent_code',
|
||||
|
||||
@@ -183,6 +183,20 @@ def validate_agent_payload(
|
||||
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 必填')
|
||||
|
||||
@@ -35,7 +35,6 @@ platform:
|
||||
dify_required_providers:
|
||||
- dify
|
||||
- hybrid
|
||||
|
||||
agent_types:
|
||||
generic:
|
||||
label: 通用问答 / 知识库
|
||||
@@ -93,6 +92,7 @@ agent_types:
|
||||
allowed_runtime_providers: [dify]
|
||||
allowed_dify_app_types: [workflow]
|
||||
allowed_exposure_modes: [internal]
|
||||
allowed_effective_roles: [internal_executor]
|
||||
file_check:
|
||||
label: 文件检核
|
||||
conversation_mode_default: task_chat
|
||||
|
||||
@@ -152,6 +152,23 @@ 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,6 +15,7 @@ from app.services.agent_registry.resolver import (
|
||||
resolve_agent_code,
|
||||
resolve_capabilities,
|
||||
resolve_conversation_mode,
|
||||
resolve_effective_role,
|
||||
resolve_progress_contract,
|
||||
resolve_runtime_provider,
|
||||
)
|
||||
@@ -48,6 +49,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),
|
||||
|
||||
@@ -14,6 +14,7 @@ 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
|
||||
|
||||
|
||||
def _capability_definition(owner: Agent, capability_code: str) -> dict[str, Any]:
|
||||
@@ -36,7 +37,13 @@ def _normalize_config(raw: Any) -> dict[str, Any]:
|
||||
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'}
|
||||
unknown = set(raw) - {
|
||||
'timeout_seconds', 'max_attempts', 'unit_concurrency',
|
||||
'unit_max_attempts', 'unit_retry_backoff_ms',
|
||||
'max_model_units', 'provider_max_concurrency',
|
||||
'circuit_failure_threshold', 'circuit_cooldown_seconds',
|
||||
'auto_create_enabled',
|
||||
}
|
||||
if unknown:
|
||||
raise ValidationError(
|
||||
'Unsupported runtime binding config keys',
|
||||
@@ -46,9 +53,17 @@ def _normalize_config(raw: Any) -> dict[str, Any]:
|
||||
try:
|
||||
timeout_seconds = int(raw.get('timeout_seconds', 900))
|
||||
max_attempts = int(raw.get('max_attempts', 3))
|
||||
unit_concurrency = int(raw.get('unit_concurrency', 2))
|
||||
unit_max_attempts = int(raw.get('unit_max_attempts', 2))
|
||||
unit_retry_backoff_ms = int(raw.get('unit_retry_backoff_ms', 500))
|
||||
max_model_units = int(raw.get('max_model_units', 20))
|
||||
provider_max_concurrency = int(raw.get('provider_max_concurrency', 4))
|
||||
circuit_failure_threshold = int(raw.get('circuit_failure_threshold', 5))
|
||||
circuit_cooldown_seconds = int(raw.get('circuit_cooldown_seconds', 60))
|
||||
auto_create_enabled = raw.get('auto_create_enabled', False)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Runtime binding timeout/max_attempts must be integers',
|
||||
'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:
|
||||
@@ -56,7 +71,34 @@ def _normalize_config(raw: Any) -> dict[str, Any]:
|
||||
'Runtime binding config is outside allowed limits',
|
||||
code='AGENT.RUNTIME_BINDING_CONFIG_INVALID',
|
||||
)
|
||||
return {'timeout_seconds': timeout_seconds, 'max_attempts': max_attempts}
|
||||
if not 2 <= unit_concurrency <= 4 or not 1 <= unit_max_attempts <= 3:
|
||||
raise ValidationError(
|
||||
'Runtime binding unit concurrency/attempts are outside allowed limits',
|
||||
code='AGENT.RUNTIME_BINDING_CONFIG_INVALID',
|
||||
)
|
||||
if not 100 <= unit_retry_backoff_ms <= 5000:
|
||||
raise ValidationError(
|
||||
'Runtime binding unit retry backoff is outside allowed limits',
|
||||
code='AGENT.RUNTIME_BINDING_CONFIG_INVALID',
|
||||
)
|
||||
if not 1 <= max_model_units <= 100 or not 1 <= provider_max_concurrency <= 20:
|
||||
raise ValidationError('Runtime binding provider budget is outside allowed limits', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID')
|
||||
if not 2 <= circuit_failure_threshold <= 20 or not 10 <= circuit_cooldown_seconds <= 600:
|
||||
raise ValidationError('Runtime binding circuit settings are outside allowed limits', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID')
|
||||
if not isinstance(auto_create_enabled, bool):
|
||||
raise ValidationError('Runtime binding auto-create gate must be boolean', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID')
|
||||
return {
|
||||
'timeout_seconds': timeout_seconds,
|
||||
'max_attempts': max_attempts,
|
||||
'unit_concurrency': unit_concurrency,
|
||||
'unit_max_attempts': unit_max_attempts,
|
||||
'unit_retry_backoff_ms': unit_retry_backoff_ms,
|
||||
'max_model_units': max_model_units,
|
||||
'provider_max_concurrency': provider_max_concurrency,
|
||||
'circuit_failure_threshold': circuit_failure_threshold,
|
||||
'circuit_cooldown_seconds': circuit_cooldown_seconds,
|
||||
'auto_create_enabled': auto_create_enabled,
|
||||
}
|
||||
|
||||
|
||||
def _validate_provider(provider: Agent, definition: dict[str, Any]) -> None:
|
||||
@@ -64,6 +106,7 @@ def _validate_provider(provider: Agent, definition: dict[str, Any]) -> None:
|
||||
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:
|
||||
@@ -72,6 +115,8 @@ def _validate_provider(provider: Agent, definition: dict[str, Any]) -> None:
|
||||
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()
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
"""
|
||||
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)
|
||||
}
|
||||
@@ -519,6 +519,25 @@ class DifyService:
|
||||
out["_workflow_error_type"] = error_type
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _observe_workflow_event(event_observer, event_type: str, event_data: dict[str, Any], state: dict[str, Any]) -> None:
|
||||
"""向可选观察器发送脱敏 Workflow 生命周期字段;观察器错误不得中断Provider调用。"""
|
||||
if event_observer is None:
|
||||
return
|
||||
node_data = event_data.get('node_data') if isinstance(event_data.get('node_data'), dict) else {}
|
||||
try:
|
||||
event_observer({
|
||||
'event_type': str(event_type),
|
||||
'workflow_run_id': event_data.get('workflow_run_id') or state.get('workflow_run_id'),
|
||||
'node_execution_id': event_data.get('node_execution_id') or event_data.get('node_id'),
|
||||
'node_type': event_data.get('node_type') or node_data.get('type'),
|
||||
'node_title': event_data.get('title') or node_data.get('title'),
|
||||
'event_status': event_data.get('status'),
|
||||
})
|
||||
except Exception:
|
||||
if current_app:
|
||||
current_app.logger.exception('[workflow-streaming] event observer failed')
|
||||
|
||||
@staticmethod
|
||||
def _consume_workflow_stream(
|
||||
*,
|
||||
@@ -527,6 +546,7 @@ class DifyService:
|
||||
payload: dict[str, Any],
|
||||
timeout: tuple[int, int],
|
||||
state: dict[str, Any],
|
||||
event_observer=None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
执行一次 Workflow streaming POST 并消费 SSE 直至 workflow_finished。
|
||||
@@ -558,6 +578,8 @@ class DifyService:
|
||||
continue
|
||||
|
||||
event_type = evt.get("event", "")
|
||||
event_data = evt.get('data') if isinstance(evt.get('data'), dict) else {}
|
||||
DifyService._observe_workflow_event(event_observer, str(event_type), event_data, state)
|
||||
|
||||
if event_type == "workflow_started":
|
||||
run_id = (evt.get("data") or {}).get("workflow_run_id")
|
||||
@@ -596,6 +618,7 @@ class DifyService:
|
||||
inputs: dict[str, Any] | None = None,
|
||||
user: str = "system",
|
||||
timeout: tuple[int, int] = (5, 300),
|
||||
event_observer=None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
调用 Dify Workflow(streaming),并在断连/超时时优先 poll 补偿结果。
|
||||
@@ -639,6 +662,7 @@ class DifyService:
|
||||
payload=payload,
|
||||
timeout=timeout,
|
||||
state=stream_state,
|
||||
event_observer=event_observer,
|
||||
)
|
||||
workflow_run_id = stream_state.get("workflow_run_id")
|
||||
if workflow_run_id:
|
||||
@@ -647,6 +671,9 @@ class DifyService:
|
||||
# [STEP] 连接正常结束但未收到 workflow_finished 时,用 poll 补偿最终结果
|
||||
if not result and workflow_run_id:
|
||||
poll_used = True
|
||||
DifyService._observe_workflow_event(
|
||||
event_observer, 'poll_started', {'workflow_run_id': workflow_run_id}, stream_state,
|
||||
)
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[workflow-streaming] stream closed without finished event, polling run_id=%s",
|
||||
@@ -657,6 +684,10 @@ class DifyService:
|
||||
workflow_run_id=workflow_run_id,
|
||||
max_wait=max_wait,
|
||||
)
|
||||
DifyService._observe_workflow_event(
|
||||
event_observer, 'recovered' if result else 'stream_interrupted',
|
||||
{'workflow_run_id': workflow_run_id, 'status': result.get('status') if result else 'timeout'}, stream_state,
|
||||
)
|
||||
poll_error_type = None if result else "poll_timeout"
|
||||
return DifyService._attach_workflow_reliability_meta(
|
||||
result,
|
||||
@@ -713,6 +744,9 @@ class DifyService:
|
||||
|
||||
if workflow_run_id:
|
||||
poll_used = True
|
||||
DifyService._observe_workflow_event(
|
||||
event_observer, 'stream_interrupted', {'workflow_run_id': workflow_run_id}, stream_state,
|
||||
)
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[workflow-streaming] polling after disconnect run_id=%s error_type=%s",
|
||||
@@ -724,6 +758,10 @@ class DifyService:
|
||||
workflow_run_id=workflow_run_id,
|
||||
max_wait=max_wait,
|
||||
)
|
||||
DifyService._observe_workflow_event(
|
||||
event_observer, 'recovered' if result else 'stream_interrupted',
|
||||
{'workflow_run_id': workflow_run_id, 'status': result.get('status') if result else 'timeout'}, stream_state,
|
||||
)
|
||||
poll_error_type = None if result else "poll_timeout"
|
||||
return DifyService._attach_workflow_reliability_meta(
|
||||
result,
|
||||
@@ -735,6 +773,9 @@ class DifyService:
|
||||
|
||||
if retryable and attempt < max_attempts - 1:
|
||||
retry_count += 1
|
||||
DifyService._observe_workflow_event(
|
||||
event_observer, 'retry_started', {'workflow_run_id': workflow_run_id}, stream_state,
|
||||
)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[workflow-streaming] retrying attempt=%s error_type=%s",
|
||||
|
||||
@@ -151,6 +151,10 @@ def register_file_asset_cleanup_schedule_hooks() -> None:
|
||||
try:
|
||||
with Session(bind) as seed_session:
|
||||
ensure_default_file_asset_cleanup_schedule(commit=True, session=seed_session)
|
||||
from app.services.shipping_notice.order_extraction_progress_cleanup_schedule import (
|
||||
ensure_default_order_extraction_progress_cleanup_schedule,
|
||||
)
|
||||
ensure_default_order_extraction_progress_cleanup_schedule(commit=True, session=seed_session)
|
||||
except Exception as exc: # pragma: no cover - 防御不阻断建用户
|
||||
_LOGGER.warning("ensure file-asset-cleanup after user create failed: %s", exc)
|
||||
|
||||
|
||||
@@ -132,7 +132,17 @@ def _register_builtin_platform_jobs() -> None:
|
||||
from app.services.schedule.file_asset_cleanup_job import run_file_asset_cleanup_schedule
|
||||
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
|
||||
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
from app.services.schedule.shipping_order_extraction_progress_cleanup_job import run_shipping_order_extraction_progress_cleanup_schedule
|
||||
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="shipping-order-extraction-progress-cleanup",
|
||||
label="订单识别进度清理",
|
||||
handler=run_shipping_order_extraction_progress_cleanup_schedule,
|
||||
description="按90天保留期分批清理订单识别脱敏进度事件,不删除Run、Job或诊断审计。",
|
||||
category="shipping",
|
||||
params_schema=({"key": "limit", "type": "number", "label": "单批上限", "required": False, "default": 1000},),
|
||||
defaults={"limit": 1000},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="shipping-inventory-rpa",
|
||||
label="货代库存 RPA",
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
"""订单抽取进度明细保留期清理的 platform Job 入口。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.order_extraction_run_service import cleanup_expired_order_extraction_progress_events
|
||||
|
||||
|
||||
def run_shipping_order_extraction_progress_cleanup_schedule(task: Any, run: Any) -> dict[str, Any]:
|
||||
"""执行90天到期事件的分批清理;不触碰业务Run、Job或管理员审计记录。"""
|
||||
_ = run
|
||||
params = getattr(task, 'job_params', None) or {}
|
||||
return cleanup_expired_order_extraction_progress_events(limit=int(params.get('limit') or 1000))
|
||||
@@ -425,6 +425,7 @@ def persist_documents_and_candidates(
|
||||
uploaded_storage_keys: list[str] | None = None,
|
||||
run_duplicate_detection: bool = True,
|
||||
create_candidates: bool = True,
|
||||
schema_definition: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
从一次解析结果落派生资产、Document,并可选生成规则 Candidate。
|
||||
@@ -446,7 +447,8 @@ def persist_documents_and_candidates(
|
||||
meta = result.meta if isinstance(result.meta, dict) else {}
|
||||
email_meta = meta.get('email') if isinstance(meta.get('email'), dict) else {}
|
||||
body_text = str(email_meta.get('body_text') or '')
|
||||
body_order_rows = build_email_order_index(body_text)
|
||||
definition = schema_definition or {'fields': []}
|
||||
body_order_rows = build_email_order_index(body_text, schema_definition=definition)
|
||||
is_eml = str(meta.get('file_type') or '').lower() == 'eml' or bool(email_meta)
|
||||
|
||||
active_keys: set[str] = set()
|
||||
@@ -461,6 +463,7 @@ def persist_documents_and_candidates(
|
||||
body_summary = parse_intake_business_summary(
|
||||
extracted_text=body_text,
|
||||
source_type='email',
|
||||
schema_definition=definition,
|
||||
)
|
||||
body_class = _classify_document(
|
||||
document_type='email_body',
|
||||
@@ -521,6 +524,7 @@ def persist_documents_and_candidates(
|
||||
mime_type=str(item.get('mime_type') or ''),
|
||||
document_type='attachment',
|
||||
),
|
||||
schema_definition=definition,
|
||||
)
|
||||
fusion = merge_attachment_candidate(
|
||||
attachment_summary=att_summary,
|
||||
@@ -590,6 +594,7 @@ def persist_documents_and_candidates(
|
||||
file_summary = parse_intake_business_summary(
|
||||
extracted_text=str(result.text or ''),
|
||||
source_type=str(result.source_type or 'manual'),
|
||||
schema_definition=definition,
|
||||
)
|
||||
file_class = _classify_document(
|
||||
document_type='attachment',
|
||||
@@ -693,6 +698,7 @@ def persist_intake_documents(
|
||||
parent_asset: FileAsset,
|
||||
result: NoticeIntakeResult,
|
||||
uploaded_storage_keys: list[str] | None = None,
|
||||
schema_definition: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
上传后仅持久化邮件正文与附件 Document,不生成订单 Candidate。
|
||||
@@ -705,6 +711,7 @@ def persist_intake_documents(
|
||||
parent_asset: 原始 EML/附件 FileAsset。
|
||||
result: 已完成文本提取的预解析结果。
|
||||
uploaded_storage_keys: 本轮新写入对象存储的 key,供失败补偿。
|
||||
schema_definition: 本轮预处理明确选择的 published Schema;缺失时只落文档不猜测订单表头。
|
||||
|
||||
Returns:
|
||||
Document 与派生资产数量摘要;candidate_count 恒为 0。
|
||||
@@ -716,6 +723,7 @@ def persist_intake_documents(
|
||||
uploaded_storage_keys=uploaded_storage_keys,
|
||||
run_duplicate_detection=False,
|
||||
create_candidates=False,
|
||||
schema_definition=schema_definition,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/__init__.py
|
||||
|
||||
用途:导出版面结构化公共契约,供 PDF、OCR、HTML 表格解析器和订单抽取链路复用。
|
||||
依赖:document_layout.contracts。
|
||||
逻辑:上游解析器产出统一 LayoutDocument;下游只消费版本化契约,不依赖具体解析引擎。
|
||||
"""
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import (
|
||||
LAYOUT_SCHEMA_VERSION,
|
||||
LayoutCell,
|
||||
LayoutDocument,
|
||||
LayoutPage,
|
||||
LayoutQuality,
|
||||
LayoutRow,
|
||||
LayoutTable,
|
||||
LayoutToken,
|
||||
canonical_layout_checksum,
|
||||
stable_layout_id,
|
||||
validate_layout_document,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.evaluation import (
|
||||
ANNOTATION_SCHEMA_VERSION,
|
||||
LayoutAnnotation,
|
||||
LayoutEvaluation,
|
||||
evaluate_layout,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.coverage import (
|
||||
HtmlSchemaCoverageReport,
|
||||
summarize_html_schema_coverage,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.mineru import (
|
||||
MINERU_SUPPORTED_EXTENSIONS,
|
||||
MinerUCapabilityReport,
|
||||
MinerUClient,
|
||||
MinerUClientConfig,
|
||||
MinerUParseCandidate,
|
||||
MinerUTextCandidate,
|
||||
inspect_mineru_capabilities,
|
||||
parse_mineru_candidate,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_table import (
|
||||
HtmlGrid,
|
||||
HtmlTableMappingResult,
|
||||
map_html_table_to_schema,
|
||||
parse_html_grid,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'LAYOUT_SCHEMA_VERSION',
|
||||
'ANNOTATION_SCHEMA_VERSION',
|
||||
'LayoutAnnotation',
|
||||
'LayoutCell',
|
||||
'LayoutDocument',
|
||||
'LayoutEvaluation',
|
||||
'LayoutPage',
|
||||
'LayoutQuality',
|
||||
'LayoutRow',
|
||||
'LayoutTable',
|
||||
'LayoutToken',
|
||||
'HtmlGrid',
|
||||
'HtmlSchemaCoverageReport',
|
||||
'HtmlTableMappingResult',
|
||||
'MINERU_SUPPORTED_EXTENSIONS',
|
||||
'MinerUCapabilityReport',
|
||||
'MinerUClient',
|
||||
'MinerUClientConfig',
|
||||
'MinerUParseCandidate',
|
||||
'MinerUTextCandidate',
|
||||
'canonical_layout_checksum',
|
||||
'evaluate_layout',
|
||||
'inspect_mineru_capabilities',
|
||||
'parse_mineru_candidate',
|
||||
'map_html_table_to_schema',
|
||||
'parse_html_grid',
|
||||
'stable_layout_id',
|
||||
'summarize_html_schema_coverage',
|
||||
'validate_layout_document',
|
||||
]
|
||||
@@ -0,0 +1,355 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/contracts.py
|
||||
|
||||
用途:定义解析器无关的 shipping_document_layout.v1 契约、稳定标识和完整性校验。
|
||||
依赖:Pydantic 2、标准库 hashlib/json/unicodedata。
|
||||
逻辑:PDF/OCR/HTML 解析器先构造 LayoutDocument;持久化、Schema 映射和评测只接受通过本模块校验的结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
|
||||
LAYOUT_SCHEMA_VERSION = 'shipping_document_layout.v1'
|
||||
_ID_PART_RE = re.compile(r'[^a-z0-9._-]+')
|
||||
|
||||
|
||||
class LayoutContractModel(BaseModel):
|
||||
"""为全部版面对象提供严格字段和赋值校验,防止解析器静默输出漂移。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid', validate_assignment=True)
|
||||
|
||||
|
||||
class LayoutBBox(LayoutContractModel):
|
||||
"""表示左上原点坐标系中的矩形;原始坐标使用页面单位,标准化坐标使用 0..1。"""
|
||||
|
||||
x0: float
|
||||
y0: float
|
||||
x1: float
|
||||
y1: float
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_order(self) -> 'LayoutBBox':
|
||||
"""拒绝倒置或零面积矩形,避免下游列聚类读取无效几何。"""
|
||||
if self.x0 < 0 or self.y0 < 0 or self.x1 <= self.x0 or self.y1 <= self.y0:
|
||||
raise ValueError('bbox must have non-negative origin and positive area')
|
||||
return self
|
||||
|
||||
|
||||
class LayoutParserInfo(LayoutContractModel):
|
||||
"""记录生成版面结果的解析器身份,作为重解析和审计版本边界。"""
|
||||
|
||||
name: str = Field(min_length=1, max_length=100)
|
||||
version: str = Field(min_length=1, max_length=100)
|
||||
|
||||
|
||||
class LayoutIssue(LayoutContractModel):
|
||||
"""记录机器可读质量问题及其最小定位信息,不在日志中复制文档正文。"""
|
||||
|
||||
code: str = Field(min_length=1, max_length=100)
|
||||
severity: Literal['info', 'warning', 'blocking']
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
table_id: str | None = None
|
||||
cell_id: str | None = None
|
||||
details: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class LayoutQuality(LayoutContractModel):
|
||||
"""汇总版面解析是否可被确定性字段映射消费。"""
|
||||
|
||||
status: Literal['accepted', 'needs_review', 'failed', 'unsupported']
|
||||
confidence: float = Field(ge=0, le=1)
|
||||
issues: list[LayoutIssue] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_blocking_status(self) -> 'LayoutQuality':
|
||||
"""阻断问题不得被标记为 accepted,避免错误结构流入自动建单。"""
|
||||
if self.status == 'accepted' and any(item.severity == 'blocking' for item in self.issues):
|
||||
raise ValueError('accepted layout must not contain blocking issues')
|
||||
return self
|
||||
|
||||
|
||||
class LayoutToken(LayoutContractModel):
|
||||
"""保存原生 PDF 或 OCR 的最小文本词元及真实页面坐标。"""
|
||||
|
||||
token_id: str = Field(min_length=1, max_length=160)
|
||||
text: str = Field(min_length=1)
|
||||
normalized_text: str
|
||||
bbox: LayoutBBox
|
||||
normalized_bbox: LayoutBBox
|
||||
source: Literal['native_text', 'ocr']
|
||||
confidence: float = Field(ge=0, le=1)
|
||||
line_id: str | None = None
|
||||
|
||||
@field_validator('normalized_text')
|
||||
@classmethod
|
||||
def validate_normalized_text(cls, value: str) -> str:
|
||||
"""要求规范化文本非空,使单元格匹配不会依赖不可见字符。"""
|
||||
text = str(value or '').strip()
|
||||
if not text:
|
||||
raise ValueError('normalized_text is required')
|
||||
return text
|
||||
|
||||
|
||||
class LayoutCell(LayoutContractModel):
|
||||
"""保存单元格文字、坐标、跨度、来源词元和语义角色。"""
|
||||
|
||||
cell_id: str = Field(min_length=1, max_length=160)
|
||||
row_index: int = Field(ge=0)
|
||||
column_index: int = Field(ge=0)
|
||||
row_span: int = Field(default=1, ge=1)
|
||||
column_span: int = Field(default=1, ge=1)
|
||||
text: str
|
||||
normalized_text: str
|
||||
bbox: LayoutBBox
|
||||
normalized_bbox: LayoutBBox
|
||||
token_ids: list[str] = Field(default_factory=list)
|
||||
source: Literal['native_text', 'ocr', 'html']
|
||||
confidence: float = Field(ge=0, le=1)
|
||||
role: Literal['header', 'data', 'summary', 'deleted', 'footer', 'unknown']
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_text_and_tokens(self) -> 'LayoutCell':
|
||||
"""确保有内容的 PDF/OCR 单元格可追溯到词元;HTML 单元格由 DOM 直接证明。"""
|
||||
if self.text and not self.normalized_text.strip():
|
||||
raise ValueError('non-empty cell text requires normalized_text')
|
||||
if self.source in {'native_text', 'ocr'} and self.text and not self.token_ids:
|
||||
raise ValueError('PDF/OCR cell text requires token_ids')
|
||||
if len(self.token_ids) != len(set(self.token_ids)):
|
||||
raise ValueError('cell token_ids must be unique')
|
||||
return self
|
||||
|
||||
|
||||
class LayoutRow(LayoutContractModel):
|
||||
"""保存表格内稳定行号及其按列排序的单元格。"""
|
||||
|
||||
row_id: str = Field(min_length=1, max_length=160)
|
||||
row_index: int = Field(ge=0)
|
||||
cells: list[LayoutCell]
|
||||
role: Literal['header', 'data', 'summary', 'deleted', 'footer', 'unknown']
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_cells(self) -> 'LayoutRow':
|
||||
"""拒绝空行、重复列和行索引错配,避免解析器将视觉片段伪装为完整数据行。"""
|
||||
if not self.cells:
|
||||
raise ValueError('layout row requires at least one cell')
|
||||
columns = [item.column_index for item in self.cells]
|
||||
if columns != sorted(columns) or len(columns) != len(set(columns)):
|
||||
raise ValueError('row cells must have unique ascending column_index values')
|
||||
if any(item.row_index != self.row_index for item in self.cells):
|
||||
raise ValueError('cell row_index must equal parent row_index')
|
||||
return self
|
||||
|
||||
|
||||
class LayoutTable(LayoutContractModel):
|
||||
"""保存单页表格、表头行、跨页关系和质量状态。"""
|
||||
|
||||
table_id: str = Field(min_length=1, max_length=160)
|
||||
bbox: LayoutBBox
|
||||
normalized_bbox: LayoutBBox
|
||||
rows: list[LayoutRow]
|
||||
header_row_indices: list[int] = Field(default_factory=list)
|
||||
continuation_of: str | None = None
|
||||
confidence: float = Field(ge=0, le=1)
|
||||
status: Literal['accepted', 'needs_review', 'failed']
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_rows(self) -> 'LayoutTable':
|
||||
"""确保行列跨度、表头角色和单元格几何一致,跨页关系交给文档级校验。"""
|
||||
if not self.rows:
|
||||
raise ValueError('layout table requires at least one row')
|
||||
indices = [item.row_index for item in self.rows]
|
||||
if indices != sorted(indices) or len(indices) != len(set(indices)):
|
||||
raise ValueError('table rows must have unique ascending row_index values')
|
||||
if self.header_row_indices != sorted(set(self.header_row_indices)):
|
||||
raise ValueError('header_row_indices must be unique and ascending')
|
||||
if any(index not in set(indices) for index in self.header_row_indices):
|
||||
raise ValueError('header_row_indices must reference table rows')
|
||||
header_indices = set(self.header_row_indices)
|
||||
if any(row.row_index in header_indices and row.role != 'header' for row in self.rows):
|
||||
raise ValueError('header row role must be header')
|
||||
occupied: set[tuple[int, int]] = set()
|
||||
for row in self.rows:
|
||||
for cell in row.cells:
|
||||
if not _bbox_contains(self.bbox, cell.bbox):
|
||||
raise ValueError(f'cell {cell.cell_id} bbox must be within table bbox')
|
||||
if not _bbox_contains(self.normalized_bbox, cell.normalized_bbox):
|
||||
raise ValueError(f'cell {cell.cell_id} normalized_bbox must be within table normalized_bbox')
|
||||
for row_index in range(cell.row_index, cell.row_index + cell.row_span):
|
||||
for column_index in range(cell.column_index, cell.column_index + cell.column_span):
|
||||
position = (row_index, column_index)
|
||||
if position in occupied:
|
||||
raise ValueError('table cells must not have overlapping row/column spans')
|
||||
occupied.add(position)
|
||||
return self
|
||||
|
||||
|
||||
class LayoutPage(LayoutContractModel):
|
||||
"""保存单页尺寸、旋转、词元和表格;所有原始坐标必须落在页面范围内。"""
|
||||
|
||||
page_no: int = Field(ge=1)
|
||||
width: float = Field(gt=0)
|
||||
height: float = Field(gt=0)
|
||||
rotation: Literal[0, 90, 180, 270] = 0
|
||||
tokens: list[LayoutToken] = Field(default_factory=list)
|
||||
tables: list[LayoutTable] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_page_geometry(self) -> 'LayoutPage':
|
||||
"""验证页面内 ID、词元引用及坐标边界,阻止不可追溯的单元格进入持久化。"""
|
||||
token_ids = [item.token_id for item in self.tokens]
|
||||
if len(token_ids) != len(set(token_ids)):
|
||||
raise ValueError('token_id must be unique within a page')
|
||||
table_ids = [item.table_id for item in self.tables]
|
||||
if len(table_ids) != len(set(table_ids)):
|
||||
raise ValueError('table_id must be unique within a page')
|
||||
cell_ids: set[str] = set()
|
||||
known_tokens = set(token_ids)
|
||||
for token in self.tokens:
|
||||
_validate_bbox(token.bbox, width=self.width, height=self.height, label=token.token_id)
|
||||
_validate_normalized_bbox(token.normalized_bbox, label=token.token_id)
|
||||
for table in self.tables:
|
||||
_validate_bbox(table.bbox, width=self.width, height=self.height, label=table.table_id)
|
||||
_validate_normalized_bbox(table.normalized_bbox, label=table.table_id)
|
||||
for row in table.rows:
|
||||
for cell in row.cells:
|
||||
if cell.cell_id in cell_ids:
|
||||
raise ValueError('cell_id must be unique within a page')
|
||||
cell_ids.add(cell.cell_id)
|
||||
_validate_bbox(cell.bbox, width=self.width, height=self.height, label=cell.cell_id)
|
||||
_validate_normalized_bbox(cell.normalized_bbox, label=cell.cell_id)
|
||||
if not set(cell.token_ids).issubset(known_tokens):
|
||||
raise ValueError(f'cell {cell.cell_id} references unknown token_id')
|
||||
return self
|
||||
|
||||
|
||||
class LayoutDocument(LayoutContractModel):
|
||||
"""表示一份 Document 的完整、版本化、可审计版面结果。"""
|
||||
|
||||
schema_version: Literal[LAYOUT_SCHEMA_VERSION] = LAYOUT_SCHEMA_VERSION
|
||||
document_id: int = Field(ge=1)
|
||||
content_hash: str = Field(pattern=r'^[0-9a-f]{64}$')
|
||||
parser: LayoutParserInfo
|
||||
pages: list[LayoutPage]
|
||||
quality: LayoutQuality
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_document_graph(self) -> 'LayoutDocument':
|
||||
"""验证页序、全局 ID 和跨页 continuation,保证引用只指向更早页面的表格。"""
|
||||
if not self.pages:
|
||||
raise ValueError('layout document requires at least one page')
|
||||
page_numbers = [item.page_no for item in self.pages]
|
||||
if page_numbers != list(range(1, len(self.pages) + 1)):
|
||||
raise ValueError('page_no values must be contiguous and start at 1')
|
||||
table_pages: dict[str, int] = {}
|
||||
global_ids: set[str] = set()
|
||||
for page in self.pages:
|
||||
for token in page.tokens:
|
||||
_add_global_id(global_ids, token.token_id)
|
||||
for table in page.tables:
|
||||
_add_global_id(global_ids, table.table_id)
|
||||
table_pages[table.table_id] = page.page_no
|
||||
for row in table.rows:
|
||||
_add_global_id(global_ids, row.row_id)
|
||||
for cell in row.cells:
|
||||
_add_global_id(global_ids, cell.cell_id)
|
||||
for page in self.pages:
|
||||
for table in page.tables:
|
||||
if table.continuation_of is None:
|
||||
continue
|
||||
parent_page = table_pages.get(table.continuation_of)
|
||||
if parent_page is None or parent_page >= page.page_no:
|
||||
raise ValueError('continuation_of must reference a table on an earlier page')
|
||||
return self
|
||||
|
||||
|
||||
def stable_layout_id(prefix: str, *parts: Any) -> str:
|
||||
"""
|
||||
由内容稳定的组成部分生成可读标识,避免重复解析使用随机 UUID。
|
||||
|
||||
Args:
|
||||
prefix: token/table/row/cell 等对象类别。
|
||||
parts: 文档哈希、页码、表序、行列序等稳定组成部分。
|
||||
Returns:
|
||||
规范化前缀加 16 位 SHA-256 摘要。
|
||||
Raises:
|
||||
ValueError: 前缀或组成部分为空。
|
||||
"""
|
||||
safe_prefix = _ID_PART_RE.sub('-', str(prefix or '').strip().lower()).strip('-')
|
||||
values = [str(item).strip() for item in parts]
|
||||
if not safe_prefix or not values or any(not item for item in values):
|
||||
raise ValueError('stable layout id requires prefix and non-empty parts')
|
||||
digest = hashlib.sha256('\x1f'.join(values).encode('utf-8')).hexdigest()[:16]
|
||||
return f'{safe_prefix}-{digest}'
|
||||
|
||||
|
||||
def normalize_layout_text(value: Any) -> str:
|
||||
"""以 NFKC 和空白折叠生成布局匹配文本,同时保留原始 text 作为审计证据。"""
|
||||
text = unicodedata.normalize('NFKC', str(value or ''))
|
||||
return ' '.join(text.split()).strip()
|
||||
|
||||
|
||||
def validate_layout_document(payload: dict[str, Any] | LayoutDocument) -> LayoutDocument:
|
||||
"""
|
||||
将字典或既有对象校验为 LayoutDocument。
|
||||
|
||||
Args:
|
||||
payload: 解析器输出的完整布局字典或 LayoutDocument。
|
||||
Returns:
|
||||
通过严格字段、几何和引用校验的 LayoutDocument。
|
||||
Raises:
|
||||
pydantic.ValidationError: 契约、坐标或引用不合法。
|
||||
"""
|
||||
if isinstance(payload, LayoutDocument):
|
||||
return LayoutDocument.model_validate(payload.model_dump(mode='json'))
|
||||
return LayoutDocument.model_validate(payload)
|
||||
|
||||
|
||||
def canonical_layout_checksum(payload: dict[str, Any] | LayoutDocument) -> str:
|
||||
"""
|
||||
计算布局结果的 canonical SHA-256,供幂等、漂移检测和测试重放使用。
|
||||
|
||||
Args:
|
||||
payload: 必须先通过完整契约校验的布局结果。
|
||||
Returns:
|
||||
64 位小写十六进制 SHA-256。
|
||||
"""
|
||||
document = validate_layout_document(payload)
|
||||
raw = json.dumps(
|
||||
document.model_dump(mode='json'), ensure_ascii=False, sort_keys=True, separators=(',', ':'),
|
||||
)
|
||||
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _validate_bbox(bbox: LayoutBBox, *, width: float, height: float, label: str) -> None:
|
||||
"""验证原始坐标位于页面边界内。"""
|
||||
if bbox.x1 > width or bbox.y1 > height:
|
||||
raise ValueError(f'{label} bbox exceeds page bounds')
|
||||
|
||||
|
||||
def _validate_normalized_bbox(bbox: LayoutBBox, *, label: str) -> None:
|
||||
"""验证标准化坐标完整位于 0..1,供跨页面几何比较。"""
|
||||
if bbox.x1 > 1 or bbox.y1 > 1:
|
||||
raise ValueError(f'{label} normalized_bbox must be within 0..1')
|
||||
|
||||
|
||||
def _bbox_contains(parent: LayoutBBox, child: LayoutBBox) -> bool:
|
||||
"""判断子矩形是否完整落在父矩形内,允许坐标边界相等。"""
|
||||
return (
|
||||
child.x0 >= parent.x0 and child.y0 >= parent.y0
|
||||
and child.x1 <= parent.x1 and child.y1 <= parent.y1
|
||||
)
|
||||
|
||||
|
||||
def _add_global_id(known: set[str], value: str) -> None:
|
||||
"""登记文档内全局 ID,并拒绝不同对象共享同一证据标识。"""
|
||||
if value in known:
|
||||
raise ValueError(f'duplicate layout object id: {value}')
|
||||
known.add(value)
|
||||
@@ -0,0 +1,108 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/coverage.py
|
||||
|
||||
用途:汇总 HTML 表格对冻结订单 Schema 的匿名覆盖指标,供 L0/L4 Review 重复执行。
|
||||
依赖:Pydantic、document_layout.html_table 映射结果。
|
||||
逻辑:调用方完成单表映射后提交结果;本模块只累计计数和受控编码,不保存表头、字段值或证据文本。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
from typing import Iterable
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.services.shipping_notice.document_layout.html_table import HtmlTableMappingResult
|
||||
|
||||
|
||||
class CoverageModel(BaseModel):
|
||||
"""为匿名覆盖报告启用严格字段校验,避免原文意外进入输出。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
|
||||
class HtmlSchemaCoverageReport(CoverageModel):
|
||||
"""保存不含文件、表头、单元格和值的 Schema 映射聚合指标。"""
|
||||
|
||||
table_count: int = Field(ge=0)
|
||||
tables_with_mapped_header: int = Field(ge=0)
|
||||
tables_without_mapped_header: int = Field(ge=0)
|
||||
mapped_columns: int = Field(ge=0)
|
||||
unmapped_columns: int = Field(ge=0)
|
||||
ambiguous_columns: int = Field(ge=0)
|
||||
mapped_column_rate: float = Field(ge=0, le=1)
|
||||
data_rows: int = Field(ge=0)
|
||||
build_complete_rows: int = Field(ge=0)
|
||||
all_required_complete_rows: int = Field(ge=0)
|
||||
build_complete_rate: float = Field(ge=0, le=1)
|
||||
all_required_complete_rate: float = Field(ge=0, le=1)
|
||||
field_code_frequency: dict[str, int]
|
||||
issue_code_frequency: dict[str, int]
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_totals(self) -> 'HtmlSchemaCoverageReport':
|
||||
"""确保分项不超过对应总数,防止评估脚本产生自相矛盾的验收证据。"""
|
||||
if self.tables_with_mapped_header + self.tables_without_mapped_header != self.table_count:
|
||||
raise ValueError('HTML coverage table totals are inconsistent')
|
||||
if self.build_complete_rows > self.data_rows or self.all_required_complete_rows > self.data_rows:
|
||||
raise ValueError('HTML coverage row totals are inconsistent')
|
||||
return self
|
||||
|
||||
|
||||
def summarize_html_schema_coverage(
|
||||
mappings: Iterable[HtmlTableMappingResult],
|
||||
) -> HtmlSchemaCoverageReport:
|
||||
"""
|
||||
汇总多张 HTML 表格的匿名冻结 Schema 覆盖指标。
|
||||
|
||||
Args:
|
||||
mappings: 已完成映射的单表结果;可来自 MinerU、EML HTML 或测试夹具。
|
||||
Returns:
|
||||
只含聚合计数、字段编码和问题编码的 HtmlSchemaCoverageReport。
|
||||
"""
|
||||
counters: Counter[str] = Counter()
|
||||
fields: Counter[str] = Counter()
|
||||
issues: Counter[str] = Counter()
|
||||
for mapping in mappings:
|
||||
counters['table_count'] += 1
|
||||
counters[
|
||||
'tables_with_mapped_header'
|
||||
if mapping.header_row_index is not None
|
||||
else 'tables_without_mapped_header'
|
||||
] += 1
|
||||
for column in mapping.columns:
|
||||
counters[f'{column.status}_columns'] += 1
|
||||
issues.update(mapping.issues)
|
||||
for row in mapping.rows:
|
||||
if row.role != 'data':
|
||||
continue
|
||||
counters['data_rows'] += 1
|
||||
counters['build_complete_rows'] += int(row.complete_build_fields)
|
||||
counters['all_required_complete_rows'] += int(row.complete_required_fields)
|
||||
fields.update(field.field_code for field in row.fields)
|
||||
|
||||
column_count = (
|
||||
counters['mapped_columns']
|
||||
+ counters['unmapped_columns']
|
||||
+ counters['ambiguous_columns']
|
||||
)
|
||||
data_rows = counters['data_rows']
|
||||
return HtmlSchemaCoverageReport(
|
||||
table_count=counters['table_count'],
|
||||
tables_with_mapped_header=counters['tables_with_mapped_header'],
|
||||
tables_without_mapped_header=counters['tables_without_mapped_header'],
|
||||
mapped_columns=counters['mapped_columns'],
|
||||
unmapped_columns=counters['unmapped_columns'],
|
||||
ambiguous_columns=counters['ambiguous_columns'],
|
||||
mapped_column_rate=(counters['mapped_columns'] / column_count if column_count else 0.0),
|
||||
data_rows=data_rows,
|
||||
build_complete_rows=counters['build_complete_rows'],
|
||||
all_required_complete_rows=counters['all_required_complete_rows'],
|
||||
build_complete_rate=(counters['build_complete_rows'] / data_rows if data_rows else 0.0),
|
||||
all_required_complete_rate=(
|
||||
counters['all_required_complete_rows'] / data_rows if data_rows else 0.0
|
||||
),
|
||||
field_code_frequency=dict(sorted(fields.items())),
|
||||
issue_code_frequency=dict(sorted(issues.items())),
|
||||
)
|
||||
@@ -0,0 +1,264 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/evaluation.py
|
||||
|
||||
用途:定义版面解析人工真值格式并计算阶段 L0/L2/L3 的表格与单元格质量指标。
|
||||
依赖:Pydantic 2、document_layout.contracts。
|
||||
逻辑:人工标注保存期望表格/单元格位置;候选解析结果按页与几何交并比匹配,输出可审计指标而非业务订单值。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import (
|
||||
LAYOUT_SCHEMA_VERSION,
|
||||
LayoutBBox,
|
||||
LayoutDocument,
|
||||
validate_layout_document,
|
||||
)
|
||||
|
||||
|
||||
ANNOTATION_SCHEMA_VERSION = 'shipping_document_layout_annotation.v1'
|
||||
|
||||
|
||||
class LayoutAnnotationModel(BaseModel):
|
||||
"""为人工真值对象启用严格字段校验,防止标注格式漂移。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid', validate_assignment=True)
|
||||
|
||||
|
||||
class AnnotatedCell(LayoutAnnotationModel):
|
||||
"""记录人工确认的单元格位置、列归属和可选业务字段,不保存邮件身份信息。"""
|
||||
|
||||
annotation_id: str = Field(min_length=1, max_length=160)
|
||||
page_no: int = Field(ge=1)
|
||||
table_index: int = Field(ge=0)
|
||||
row_index: int = Field(ge=0)
|
||||
column_index: int = Field(ge=0)
|
||||
normalized_bbox: LayoutBBox
|
||||
normalized_text: str
|
||||
role: str
|
||||
expected_field_code: str | None = None
|
||||
|
||||
|
||||
class AnnotatedTable(LayoutAnnotationModel):
|
||||
"""记录人工确认的单页表格区域和单元格集合。"""
|
||||
|
||||
annotation_id: str = Field(min_length=1, max_length=160)
|
||||
page_no: int = Field(ge=1)
|
||||
table_index: int = Field(ge=0)
|
||||
normalized_bbox: LayoutBBox
|
||||
cells: list[AnnotatedCell]
|
||||
continuation_of: str | None = None
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_cells(self) -> 'AnnotatedTable':
|
||||
"""要求标准化坐标有效,且子单元格指向并落在同一父表格内。"""
|
||||
_validate_normalized_bbox(self.normalized_bbox, label=self.annotation_id)
|
||||
ids = [item.annotation_id for item in self.cells]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError('annotated cell ids must be unique')
|
||||
if any(item.page_no != self.page_no or item.table_index != self.table_index for item in self.cells):
|
||||
raise ValueError('annotated cells must reference their parent table')
|
||||
for cell in self.cells:
|
||||
_validate_normalized_bbox(cell.normalized_bbox, label=cell.annotation_id)
|
||||
if not _bbox_contains(self.normalized_bbox, cell.normalized_bbox):
|
||||
raise ValueError('annotated cell bbox must be within parent table bbox')
|
||||
return self
|
||||
|
||||
|
||||
class LayoutAnnotation(LayoutAnnotationModel):
|
||||
"""保存一份脱敏文档的布局人工真值及样本类别标签。"""
|
||||
|
||||
schema_version: str = ANNOTATION_SCHEMA_VERSION
|
||||
layout_schema_version: str = LAYOUT_SCHEMA_VERSION
|
||||
sample_id: str = Field(min_length=1, max_length=160)
|
||||
content_hash: str = Field(pattern=r'^[0-9a-f]{64}$')
|
||||
categories: list[str] = Field(min_length=1)
|
||||
tables: list[AnnotatedTable]
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_annotation(self) -> 'LayoutAnnotation':
|
||||
"""拒绝重复表格标识和悬空跨页引用,保证评测真值自身可信。"""
|
||||
if self.schema_version != ANNOTATION_SCHEMA_VERSION:
|
||||
raise ValueError('unsupported annotation schema_version')
|
||||
if self.layout_schema_version != LAYOUT_SCHEMA_VERSION:
|
||||
raise ValueError('annotation layout schema_version mismatch')
|
||||
table_ids = [item.annotation_id for item in self.tables]
|
||||
if len(table_ids) != len(set(table_ids)):
|
||||
raise ValueError('annotated table ids must be unique')
|
||||
pages = {item.annotation_id: item.page_no for item in self.tables}
|
||||
for table in self.tables:
|
||||
if table.continuation_of is None:
|
||||
continue
|
||||
parent_page = pages.get(table.continuation_of)
|
||||
if parent_page is None or parent_page >= table.page_no:
|
||||
raise ValueError('annotated continuation must reference an earlier page')
|
||||
return self
|
||||
|
||||
|
||||
class LayoutEvaluation(LayoutAnnotationModel):
|
||||
"""汇总表格检测、单元格检测、归行归列和业务字段归属指标。"""
|
||||
|
||||
expected_tables: int
|
||||
matched_tables: int
|
||||
expected_cells: int
|
||||
matched_cells: int
|
||||
correctly_positioned_cells: int
|
||||
field_labeled_cells: int
|
||||
correctly_mapped_fields: int
|
||||
table_detection_recall: float = Field(ge=0, le=1)
|
||||
cell_detection_recall: float = Field(ge=0, le=1)
|
||||
cell_position_accuracy: float = Field(ge=0, le=1)
|
||||
field_mapping_accuracy: float | None = Field(default=None, ge=0, le=1)
|
||||
|
||||
|
||||
def evaluate_layout(
|
||||
annotation: dict | LayoutAnnotation,
|
||||
candidate: dict | LayoutDocument,
|
||||
*,
|
||||
table_iou_threshold: float = 0.8,
|
||||
cell_iou_threshold: float = 0.8,
|
||||
mapped_field_codes: dict[str, str] | None = None,
|
||||
) -> LayoutEvaluation:
|
||||
"""
|
||||
将解析结果与人工真值按页和 bbox IoU 一对一匹配并计算阶段指标。
|
||||
|
||||
Args:
|
||||
annotation: 通过 v1 标注契约的人工真值。
|
||||
candidate: 通过 shipping_document_layout.v1 的解析结果。
|
||||
table_iou_threshold: 表格区域视为命中的最小 IoU。
|
||||
cell_iou_threshold: 单元格区域视为命中的最小 IoU。
|
||||
mapped_field_codes: 可选的 candidate cell_id -> field_code 映射,用于阶段 L4 评测。
|
||||
Returns:
|
||||
表格、单元格、位置和字段映射指标。
|
||||
Raises:
|
||||
ValueError: 阈值不在 0..1 或文档 content_hash 与真值不一致。
|
||||
"""
|
||||
if not 0 <= table_iou_threshold <= 1 or not 0 <= cell_iou_threshold <= 1:
|
||||
raise ValueError('IoU thresholds must be within 0..1')
|
||||
truth = annotation if isinstance(annotation, LayoutAnnotation) else LayoutAnnotation.model_validate(annotation)
|
||||
layout = validate_layout_document(candidate)
|
||||
if truth.content_hash != layout.content_hash:
|
||||
raise ValueError('annotation and candidate content_hash must match')
|
||||
|
||||
candidate_tables = [
|
||||
(page.page_no, table)
|
||||
for page in layout.pages
|
||||
for table in page.tables
|
||||
]
|
||||
matched_table_ids: set[str] = set()
|
||||
matched_tables: list[tuple[AnnotatedTable, object]] = []
|
||||
for expected in truth.tables:
|
||||
hit = _best_unused_match(
|
||||
expected.normalized_bbox,
|
||||
[(table.table_id, table.normalized_bbox, table) for page_no, table in candidate_tables if page_no == expected.page_no],
|
||||
used=matched_table_ids,
|
||||
threshold=table_iou_threshold,
|
||||
)
|
||||
if hit is not None:
|
||||
matched_table_ids.add(hit[0])
|
||||
matched_tables.append((expected, hit[1]))
|
||||
|
||||
expected_cells = sum(len(item.cells) for item in truth.tables)
|
||||
matched_cells = 0
|
||||
positioned_cells = 0
|
||||
field_labeled_cells = 0
|
||||
correctly_mapped_fields = 0
|
||||
field_codes = mapped_field_codes or {}
|
||||
for expected_table, candidate_table in matched_tables:
|
||||
used_cells: set[str] = set()
|
||||
candidates = [
|
||||
(cell.cell_id, cell.normalized_bbox, cell)
|
||||
for row in candidate_table.rows
|
||||
for cell in row.cells
|
||||
]
|
||||
for expected_cell in expected_table.cells:
|
||||
if expected_cell.expected_field_code:
|
||||
field_labeled_cells += 1
|
||||
hit = _best_unused_match(
|
||||
expected_cell.normalized_bbox,
|
||||
candidates,
|
||||
used=used_cells,
|
||||
threshold=cell_iou_threshold,
|
||||
)
|
||||
if hit is None:
|
||||
continue
|
||||
cell_id, candidate_cell = hit
|
||||
used_cells.add(cell_id)
|
||||
matched_cells += 1
|
||||
if (
|
||||
candidate_cell.row_index == expected_cell.row_index
|
||||
and candidate_cell.column_index == expected_cell.column_index
|
||||
):
|
||||
positioned_cells += 1
|
||||
if expected_cell.expected_field_code and field_codes.get(cell_id) == expected_cell.expected_field_code:
|
||||
correctly_mapped_fields += 1
|
||||
|
||||
return LayoutEvaluation(
|
||||
expected_tables=len(truth.tables),
|
||||
matched_tables=len(matched_tables),
|
||||
expected_cells=expected_cells,
|
||||
matched_cells=matched_cells,
|
||||
correctly_positioned_cells=positioned_cells,
|
||||
field_labeled_cells=field_labeled_cells,
|
||||
correctly_mapped_fields=correctly_mapped_fields,
|
||||
table_detection_recall=_ratio(len(matched_tables), len(truth.tables)),
|
||||
cell_detection_recall=_ratio(matched_cells, expected_cells),
|
||||
cell_position_accuracy=_ratio(positioned_cells, matched_cells),
|
||||
field_mapping_accuracy=(
|
||||
_ratio(correctly_mapped_fields, field_labeled_cells) if field_labeled_cells else None
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _best_unused_match(
|
||||
expected: LayoutBBox,
|
||||
candidates: list[tuple[str, LayoutBBox, object]],
|
||||
*,
|
||||
used: set[str],
|
||||
threshold: float,
|
||||
) -> tuple[str, object] | None:
|
||||
"""返回达到阈值且尚未使用的最高 IoU 候选,确保一对一评测。"""
|
||||
best: tuple[str, object] | None = None
|
||||
best_iou = threshold
|
||||
for candidate_id, bbox, value in candidates:
|
||||
if candidate_id in used:
|
||||
continue
|
||||
score = _bbox_iou(expected, bbox)
|
||||
if score >= best_iou:
|
||||
best = (candidate_id, value)
|
||||
best_iou = score
|
||||
return best
|
||||
|
||||
|
||||
def _bbox_iou(left: LayoutBBox, right: LayoutBBox) -> float:
|
||||
"""计算两个标准化矩形的交并比。"""
|
||||
x0 = max(left.x0, right.x0)
|
||||
y0 = max(left.y0, right.y0)
|
||||
x1 = min(left.x1, right.x1)
|
||||
y1 = min(left.y1, right.y1)
|
||||
intersection = max(0.0, x1 - x0) * max(0.0, y1 - y0)
|
||||
left_area = (left.x1 - left.x0) * (left.y1 - left.y0)
|
||||
right_area = (right.x1 - right.x0) * (right.y1 - right.y0)
|
||||
union = left_area + right_area - intersection
|
||||
return intersection / union if union > 0 else 0.0
|
||||
|
||||
|
||||
def _ratio(numerator: int, denominator: int) -> float:
|
||||
"""返回 0..1 比例;没有期望对象时按完全满足处理。"""
|
||||
return 1.0 if denominator == 0 else numerator / denominator
|
||||
|
||||
|
||||
def _validate_normalized_bbox(bbox: LayoutBBox, *, label: str) -> None:
|
||||
"""验证人工真值使用的坐标完整位于 0..1。"""
|
||||
if bbox.x1 > 1 or bbox.y1 > 1:
|
||||
raise ValueError(f'{label} normalized bbox must be within 0..1')
|
||||
|
||||
|
||||
def _bbox_contains(parent: LayoutBBox, child: LayoutBBox) -> bool:
|
||||
"""判断标注单元格是否完整落在标注表格范围内。"""
|
||||
return (
|
||||
child.x0 >= parent.x0 and child.y0 >= parent.y0
|
||||
and child.x1 <= parent.x1 and child.y1 <= parent.y1
|
||||
)
|
||||
@@ -0,0 +1,542 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/html_table.py
|
||||
|
||||
用途:把 MinerU/EML 的 HTML 表格恢复为稳定网格,并按冻结订单 Schema 精确映射列与字段候选。
|
||||
依赖:BeautifulSoup、Pydantic、order_schema.table_contract/field_rules、notice_line_values。
|
||||
逻辑:先展开 rowspan/colspan,再选择最高分表头;只接受冻结别名精确命中,未映射或歧义列保留诊断而不猜字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any, Literal
|
||||
|
||||
from bs4 import BeautifulSoup
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.notice_line_values import parse_number
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
normalize_order_field_value,
|
||||
validate_order_field_value,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import (
|
||||
TableHeaderContract,
|
||||
normalize_table_header,
|
||||
)
|
||||
|
||||
|
||||
class HtmlTableModel(BaseModel):
|
||||
"""为 HTML 网格和映射结果启用严格字段校验。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
|
||||
class HtmlGridCell(HtmlTableModel):
|
||||
"""表示 HTML 单元格在展开网格中的原点、跨度、文字和表头身份。"""
|
||||
|
||||
cell_id: str
|
||||
row_index: int = Field(ge=0)
|
||||
column_index: int = Field(ge=0)
|
||||
row_span: int = Field(ge=1)
|
||||
column_span: int = Field(ge=1)
|
||||
text: str
|
||||
normalized_text: str
|
||||
is_header: bool
|
||||
|
||||
|
||||
class HtmlGridSlot(HtmlTableModel):
|
||||
"""表示网格坐标指向的原始单元格;合并格的多个 Slot 共享 cell_id。"""
|
||||
|
||||
row_index: int = Field(ge=0)
|
||||
column_index: int = Field(ge=0)
|
||||
cell_id: str
|
||||
text: str
|
||||
normalized_text: str
|
||||
is_header: bool
|
||||
origin_row_index: int = Field(ge=0)
|
||||
origin_column_index: int = Field(ge=0)
|
||||
|
||||
|
||||
class HtmlGrid(HtmlTableModel):
|
||||
"""保存按行列展开后的矩形 HTML 表格和原始单元格集合。"""
|
||||
|
||||
row_count: int = Field(ge=1)
|
||||
column_count: int = Field(ge=1)
|
||||
rows: list[list[HtmlGridSlot | None]]
|
||||
cells: list[HtmlGridCell]
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_shape(self) -> 'HtmlGrid':
|
||||
"""确保网格是固定列数矩形,且所有 Slot 引用已知单元格。"""
|
||||
if len(self.rows) != self.row_count or any(len(row) != self.column_count for row in self.rows):
|
||||
raise ValueError('HTML grid shape is inconsistent')
|
||||
ids = {item.cell_id for item in self.cells}
|
||||
if len(ids) != len(self.cells):
|
||||
raise ValueError('HTML cell ids must be unique')
|
||||
if any(slot is not None and slot.cell_id not in ids for row in self.rows for slot in row):
|
||||
raise ValueError('HTML grid slot references unknown cell')
|
||||
return self
|
||||
|
||||
|
||||
class HtmlMappedField(HtmlTableModel):
|
||||
"""保存一项经冻结 Schema 校验的字段候选及其行列表格引用。"""
|
||||
|
||||
field_id: str
|
||||
field_code: str
|
||||
value: Any
|
||||
page_no: int = Field(ge=1)
|
||||
table_id: str
|
||||
row_index: int = Field(ge=0)
|
||||
column_index: int = Field(ge=0)
|
||||
cell_id: str
|
||||
evidence_ref: str
|
||||
|
||||
|
||||
class HtmlMappedRow(HtmlTableModel):
|
||||
"""保存一条 HTML 数据行的字段候选和行级质量状态。"""
|
||||
|
||||
row_index: int = Field(ge=0)
|
||||
role: Literal['data', 'deleted', 'summary', 'empty', 'repeated_header']
|
||||
fields: list[HtmlMappedField] = Field(default_factory=list)
|
||||
complete_build_fields: bool = False
|
||||
complete_required_fields: bool = False
|
||||
missing_required_field_codes: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class HtmlColumnMapping(HtmlTableModel):
|
||||
"""记录一列的表头路径、唯一映射结果或未映射/歧义原因。"""
|
||||
|
||||
column_index: int = Field(ge=0)
|
||||
header_path: list[str]
|
||||
field_code: str | None = None
|
||||
field_id: str | None = None
|
||||
status: Literal['mapped', 'unmapped', 'ambiguous']
|
||||
candidates: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class HtmlTableMappingResult(HtmlTableModel):
|
||||
"""汇总表头选择、列映射、数据行候选和阻断问题。"""
|
||||
|
||||
page_no: int = Field(ge=1)
|
||||
table_id: str
|
||||
header_row_index: int | None = Field(default=None, ge=0)
|
||||
header_score: int = Field(ge=0)
|
||||
columns: list[HtmlColumnMapping]
|
||||
rows: list[HtmlMappedRow]
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
@property
|
||||
def mapped_field_codes(self) -> set[str]:
|
||||
"""返回本表唯一映射的字段编码集合。"""
|
||||
return {item.field_code for item in self.columns if item.field_code}
|
||||
|
||||
|
||||
def parse_html_grid(html: str, *, table_id: str) -> HtmlGrid:
|
||||
"""
|
||||
展开 HTML table 的 rowspan/colspan 为矩形网格。
|
||||
|
||||
Args:
|
||||
html: 必须包含 table/tr/td 或 th 的 MinerU/EML HTML。
|
||||
table_id: 当前文档内稳定表格标识,用于生成 cell_id。
|
||||
Returns:
|
||||
保留原始合并格身份的 HtmlGrid。
|
||||
Raises:
|
||||
ValidationError: HTML 无表格、跨度非法或单元格重叠。
|
||||
"""
|
||||
soup = BeautifulSoup(str(html or ''), 'html.parser')
|
||||
table = soup.find('table')
|
||||
if table is None:
|
||||
raise ValidationError(
|
||||
'HTML table is missing', code='SHIPPING_NOTICE.LAYOUT_HTML_TABLE_INVALID',
|
||||
)
|
||||
raw_rows = [row for row in table.find_all('tr') if row.find_parent('table') is table]
|
||||
if not raw_rows:
|
||||
raise ValidationError(
|
||||
'HTML table has no rows', code='SHIPPING_NOTICE.LAYOUT_HTML_TABLE_INVALID',
|
||||
)
|
||||
occupied: dict[tuple[int, int], HtmlGridSlot] = {}
|
||||
cells: list[HtmlGridCell] = []
|
||||
max_column = 0
|
||||
for row_index, row in enumerate(raw_rows):
|
||||
column_index = 0
|
||||
for element in row.find_all(['td', 'th'], recursive=False):
|
||||
while (row_index, column_index) in occupied:
|
||||
column_index += 1
|
||||
row_span = _positive_span(element.get('rowspan'))
|
||||
column_span = _positive_span(element.get('colspan'))
|
||||
text = ' '.join(element.get_text(' ', strip=True).split()).strip()
|
||||
normalized = normalize_table_header(text)
|
||||
cell_id = f'{table_id}:r{row_index}:c{column_index}'
|
||||
cell = HtmlGridCell(
|
||||
cell_id=cell_id,
|
||||
row_index=row_index,
|
||||
column_index=column_index,
|
||||
row_span=row_span,
|
||||
column_span=column_span,
|
||||
text=text,
|
||||
normalized_text=normalized,
|
||||
is_header=element.name.lower() == 'th',
|
||||
)
|
||||
cells.append(cell)
|
||||
for target_row in range(row_index, row_index + row_span):
|
||||
for target_column in range(column_index, column_index + column_span):
|
||||
position = (target_row, target_column)
|
||||
if position in occupied:
|
||||
raise ValidationError(
|
||||
'HTML table cells overlap',
|
||||
code='SHIPPING_NOTICE.LAYOUT_HTML_TABLE_INVALID',
|
||||
)
|
||||
occupied[position] = HtmlGridSlot(
|
||||
row_index=target_row,
|
||||
column_index=target_column,
|
||||
cell_id=cell_id,
|
||||
text=text,
|
||||
normalized_text=normalized,
|
||||
is_header=cell.is_header,
|
||||
origin_row_index=row_index,
|
||||
origin_column_index=column_index,
|
||||
)
|
||||
max_column = max(max_column, target_column + 1)
|
||||
column_index += column_span
|
||||
row_count = max((position[0] for position in occupied), default=-1) + 1
|
||||
if row_count < 1 or max_column < 1:
|
||||
raise ValidationError(
|
||||
'HTML table grid is empty', code='SHIPPING_NOTICE.LAYOUT_HTML_TABLE_INVALID',
|
||||
)
|
||||
rows = [
|
||||
[occupied.get((row_index, column_index)) for column_index in range(max_column)]
|
||||
for row_index in range(row_count)
|
||||
]
|
||||
return HtmlGrid(row_count=row_count, column_count=max_column, rows=rows, cells=cells)
|
||||
|
||||
|
||||
def map_html_table_to_schema(
|
||||
html: str,
|
||||
*,
|
||||
page_no: int,
|
||||
table_id: str,
|
||||
contract: TableHeaderContract,
|
||||
) -> HtmlTableMappingResult:
|
||||
"""
|
||||
按冻结 Schema 精确映射 HTML 表格列并生成类型化行字段候选。
|
||||
|
||||
Args:
|
||||
html: MinerU 或 EML 解析出的 HTML table。
|
||||
page_no: 1-based 来源页码。
|
||||
table_id: 当前 Document 内稳定表格标识。
|
||||
contract: Run 锁定 Schema 编译出的表头契约。
|
||||
Returns:
|
||||
包含列诊断、有效/删除/汇总行和 evidence_ref 的映射结果。
|
||||
"""
|
||||
grid = parse_html_grid(html, table_id=table_id)
|
||||
header_index, score = _select_header_row(grid, contract)
|
||||
if header_index is None:
|
||||
return HtmlTableMappingResult(
|
||||
page_no=page_no,
|
||||
table_id=table_id,
|
||||
header_row_index=None,
|
||||
header_score=0,
|
||||
columns=[
|
||||
HtmlColumnMapping(
|
||||
column_index=index, header_path=[], status='unmapped', candidates=[],
|
||||
)
|
||||
for index in range(grid.column_count)
|
||||
],
|
||||
rows=[],
|
||||
issues=['html_table_header_not_mapped'],
|
||||
)
|
||||
columns, duplicate_codes = _map_columns(
|
||||
grid, header_index=header_index, contract=contract,
|
||||
)
|
||||
issues: list[str] = []
|
||||
if any(item.status == 'ambiguous' for item in columns):
|
||||
issues.append('html_table_columns_ambiguous')
|
||||
if duplicate_codes:
|
||||
issues.append('html_table_duplicate_field_columns')
|
||||
if _header_contains_appended_numeric_value(
|
||||
grid, header_index=header_index, contract=contract,
|
||||
):
|
||||
issues.append('html_table_header_value_contamination')
|
||||
mapped_rows = [
|
||||
_map_data_row(
|
||||
grid,
|
||||
row_index=row_index,
|
||||
header_index=header_index,
|
||||
columns=columns,
|
||||
page_no=page_no,
|
||||
table_id=table_id,
|
||||
contract=contract,
|
||||
)
|
||||
for row_index in range(grid.row_count)
|
||||
if row_index > header_index
|
||||
]
|
||||
required_codes = {
|
||||
code for code, config in contract.fields_by_code.items()
|
||||
if config.get('scope') == 'line' and config.get('required')
|
||||
}
|
||||
build_codes = {'part_number', 'qty'}
|
||||
for row in mapped_rows:
|
||||
present = {field.field_code for field in row.fields}
|
||||
row.complete_build_fields = row.role == 'data' and build_codes.issubset(present)
|
||||
row.complete_required_fields = row.role == 'data' and required_codes.issubset(present)
|
||||
row.missing_required_field_codes = (
|
||||
sorted(required_codes - present) if row.role == 'data' else []
|
||||
)
|
||||
return HtmlTableMappingResult(
|
||||
page_no=page_no,
|
||||
table_id=table_id,
|
||||
header_row_index=header_index,
|
||||
header_score=score,
|
||||
columns=columns,
|
||||
rows=mapped_rows,
|
||||
issues=issues,
|
||||
)
|
||||
|
||||
|
||||
def _select_header_row(grid: HtmlGrid, contract: TableHeaderContract) -> tuple[int | None, int]:
|
||||
"""扫描整张表选择冻结别名命中最多的表头,支持表头后置但不按位置猜测。"""
|
||||
best_index: int | None = None
|
||||
best_score = 0
|
||||
for row_index in range(grid.row_count):
|
||||
codes: set[str] = set()
|
||||
for column_index in range(grid.column_count):
|
||||
candidates = _header_candidates(grid, row_index=row_index, column_index=column_index)
|
||||
codes.update(
|
||||
contract.header_to_field[item]
|
||||
for item in candidates
|
||||
if item in contract.header_to_field
|
||||
)
|
||||
score = len(codes) * 10
|
||||
if 'part_number' in codes and 'qty' in codes:
|
||||
score += 30
|
||||
if 'reservation_id' in codes:
|
||||
score += 10
|
||||
if {'unit_price', 'amount'} & codes:
|
||||
score += 5
|
||||
if score > best_score:
|
||||
best_index = row_index
|
||||
best_score = score
|
||||
return best_index, best_score
|
||||
|
||||
|
||||
def _map_columns(
|
||||
grid: HtmlGrid, *, header_index: int, contract: TableHeaderContract,
|
||||
) -> tuple[list[HtmlColumnMapping], set[str]]:
|
||||
"""按每列多层表头候选精确匹配字段;多字段命中时显式标记歧义。"""
|
||||
result: list[HtmlColumnMapping] = []
|
||||
for column_index in range(grid.column_count):
|
||||
paths = _header_candidates(grid, row_index=header_index, column_index=column_index)
|
||||
codes = sorted({contract.header_to_field[item] for item in paths if item in contract.header_to_field})
|
||||
if len(codes) == 1:
|
||||
code = codes[0]
|
||||
config = contract.fields_by_code[code]
|
||||
result.append(HtmlColumnMapping(
|
||||
column_index=column_index,
|
||||
header_path=_header_display_path(grid, header_index, column_index),
|
||||
field_code=code,
|
||||
field_id=str(config.get('field_id') or ''),
|
||||
status='mapped',
|
||||
candidates=codes,
|
||||
))
|
||||
else:
|
||||
result.append(HtmlColumnMapping(
|
||||
column_index=column_index,
|
||||
header_path=_header_display_path(grid, header_index, column_index),
|
||||
status='ambiguous' if codes else 'unmapped',
|
||||
candidates=codes,
|
||||
))
|
||||
counts: dict[str, int] = {}
|
||||
for item in result:
|
||||
if item.status == 'mapped' and item.field_code:
|
||||
counts[item.field_code] = counts.get(item.field_code, 0) + 1
|
||||
duplicate_codes = {code for code, count in counts.items() if count > 1}
|
||||
if not duplicate_codes:
|
||||
return result, set()
|
||||
blocked = [
|
||||
item.model_copy(update={
|
||||
'field_code': None,
|
||||
'field_id': None,
|
||||
'status': 'ambiguous',
|
||||
'candidates': [item.field_code],
|
||||
})
|
||||
if item.field_code in duplicate_codes else item
|
||||
for item in result
|
||||
]
|
||||
return blocked, duplicate_codes
|
||||
|
||||
|
||||
def _map_data_row(
|
||||
grid: HtmlGrid,
|
||||
*,
|
||||
row_index: int,
|
||||
header_index: int,
|
||||
columns: list[HtmlColumnMapping],
|
||||
page_no: int,
|
||||
table_id: str,
|
||||
contract: TableHeaderContract,
|
||||
) -> HtmlMappedRow:
|
||||
"""将非表头行按唯一映射列转换为字段候选,并识别空/删除/合计/重复表头。"""
|
||||
row = grid.rows[row_index]
|
||||
texts = [slot.text.strip() if slot is not None else '' for slot in row]
|
||||
normalized = [normalize_table_header(item) for item in texts if item]
|
||||
if not normalized:
|
||||
return HtmlMappedRow(row_index=row_index, role='empty')
|
||||
if _is_repeated_header(grid, row_index=row_index, columns=columns, contract=contract):
|
||||
return HtmlMappedRow(row_index=row_index, role='repeated_header')
|
||||
joined = ' '.join(normalized)
|
||||
if 'item deleted' in joined or 'deleted item' in joined or '项目已删除' in joined or '項目已刪除' in joined:
|
||||
return HtmlMappedRow(row_index=row_index, role='deleted')
|
||||
first = next((item for item in normalized if item), '')
|
||||
if re.fullmatch(r'(grand )?(sub ?)?total|合计|合計|总计|總計', first):
|
||||
return HtmlMappedRow(row_index=row_index, role='summary')
|
||||
if _has_explicit_zero_quantity(row, columns=columns):
|
||||
return HtmlMappedRow(row_index=row_index, role='deleted')
|
||||
fields: list[HtmlMappedField] = []
|
||||
seen_codes: set[str] = set()
|
||||
for column in columns:
|
||||
if column.status != 'mapped' or not column.field_code or column.field_code in seen_codes:
|
||||
continue
|
||||
slot = row[column.column_index]
|
||||
if slot is None or not slot.text.strip():
|
||||
continue
|
||||
config = contract.fields_by_code.get(column.field_code)
|
||||
value = _normalize_html_value(slot.text, config)
|
||||
if value is None:
|
||||
continue
|
||||
seen_codes.add(column.field_code)
|
||||
fields.append(HtmlMappedField(
|
||||
field_id=str(config.get('field_id') or ''),
|
||||
field_code=column.field_code,
|
||||
value=value.isoformat() if hasattr(value, 'isoformat') else value,
|
||||
page_no=page_no,
|
||||
table_id=table_id,
|
||||
row_index=row_index,
|
||||
column_index=column.column_index,
|
||||
cell_id=slot.cell_id,
|
||||
evidence_ref=f'doc:p{page_no}:{table_id}:r{row_index}:c{column.column_index}',
|
||||
))
|
||||
return HtmlMappedRow(row_index=row_index, role='data', fields=fields)
|
||||
|
||||
|
||||
def _normalize_html_value(raw: str, config: dict[str, Any] | None) -> Any:
|
||||
"""按冻结字段类型、normalizer 和 validator 转换 HTML 单元格;非法值留空不跨列补偿。"""
|
||||
if config is None:
|
||||
return None
|
||||
value_type = str(config.get('value_type') or 'string')
|
||||
candidate: Any = raw
|
||||
if value_type in {'decimal', 'integer'}:
|
||||
candidate = parse_number(raw)
|
||||
if candidate is None:
|
||||
return None
|
||||
if value_type == 'integer':
|
||||
if not float(candidate).is_integer():
|
||||
return None
|
||||
candidate = int(candidate)
|
||||
try:
|
||||
value = normalize_order_field_value(candidate, config)
|
||||
return value if value is not None and validate_order_field_value(value, config) else None
|
||||
except (ValidationError, ArithmeticError, TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _has_explicit_zero_quantity(
|
||||
row: list[HtmlGridSlot | None], *, columns: list[HtmlColumnMapping],
|
||||
) -> bool:
|
||||
"""识别冻结 Qty 列中明确数值 0;仅零值删除,负数/空值/非法值继续走质量复核。"""
|
||||
qty_column = next(
|
||||
(
|
||||
column for column in columns
|
||||
if column.status == 'mapped' and column.field_code == 'qty'
|
||||
),
|
||||
None,
|
||||
)
|
||||
if qty_column is None:
|
||||
return False
|
||||
slot = row[qty_column.column_index]
|
||||
if slot is None or not slot.text.strip():
|
||||
return False
|
||||
value = parse_number(slot.text)
|
||||
return value is not None and value == 0
|
||||
|
||||
|
||||
def _header_candidates(grid: HtmlGrid, *, row_index: int, column_index: int) -> list[str]:
|
||||
"""生成叶表头、上层合并表头和组合路径的标准化候选,保持精确匹配。"""
|
||||
displays = _header_display_path(grid, row_index, column_index)
|
||||
normalized = [normalize_table_header(item) for item in displays if normalize_table_header(item)]
|
||||
candidates: list[str] = []
|
||||
for item in reversed(normalized):
|
||||
if item not in candidates:
|
||||
candidates.append(item)
|
||||
for start in range(len(normalized)):
|
||||
joined = normalize_table_header(' '.join(normalized[start:]))
|
||||
if joined and joined not in candidates:
|
||||
candidates.append(joined)
|
||||
return candidates
|
||||
|
||||
|
||||
def _header_display_path(grid: HtmlGrid, row_index: int, column_index: int) -> list[str]:
|
||||
"""收集当前表头行及其上方相同列的去重显示路径。"""
|
||||
path: list[str] = []
|
||||
seen_cells: set[str] = set()
|
||||
for index in range(row_index + 1):
|
||||
slot = grid.rows[index][column_index]
|
||||
if slot is None or slot.cell_id in seen_cells or not slot.text.strip():
|
||||
continue
|
||||
seen_cells.add(slot.cell_id)
|
||||
path.append(slot.text.strip())
|
||||
return path
|
||||
|
||||
|
||||
def _is_repeated_header(
|
||||
grid: HtmlGrid,
|
||||
*,
|
||||
row_index: int,
|
||||
columns: list[HtmlColumnMapping],
|
||||
contract: TableHeaderContract,
|
||||
) -> bool:
|
||||
"""判断数据区是否重复出现同一组已映射表头。"""
|
||||
hits = 0
|
||||
expected = 0
|
||||
for column in columns:
|
||||
if column.status != 'mapped' or not column.field_code:
|
||||
continue
|
||||
expected += 1
|
||||
slot = grid.rows[row_index][column.column_index]
|
||||
if slot and contract.header_to_field.get(slot.normalized_text) == column.field_code:
|
||||
hits += 1
|
||||
return expected >= 2 and hits == expected
|
||||
|
||||
|
||||
def _header_contains_appended_numeric_value(
|
||||
grid: HtmlGrid, *, header_index: int, contract: TableHeaderContract,
|
||||
) -> bool:
|
||||
"""检测已知精确表头后拼接纯数字首值的解析污染,不尝试修剪或映射该单元格。"""
|
||||
for slot in grid.rows[header_index]:
|
||||
if slot is None or not slot.normalized_text or slot.normalized_text in contract.header_to_field:
|
||||
continue
|
||||
for header in contract.header_to_field:
|
||||
prefix = f'{header} '
|
||||
if not slot.normalized_text.startswith(prefix):
|
||||
continue
|
||||
suffix = slot.normalized_text[len(prefix):].strip()
|
||||
if suffix and re.fullmatch(r'\d+(?:\s+\d+)*', suffix):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _positive_span(value: Any) -> int:
|
||||
"""读取 rowspan/colspan,空值为 1,零或非法跨度拒绝。"""
|
||||
if value in (None, ''):
|
||||
return 1
|
||||
try:
|
||||
span = int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'HTML table span is invalid', code='SHIPPING_NOTICE.LAYOUT_HTML_TABLE_INVALID',
|
||||
) from exc
|
||||
if span < 1 or span > 1000:
|
||||
raise ValidationError(
|
||||
'HTML table span is invalid', code='SHIPPING_NOTICE.LAYOUT_HTML_TABLE_INVALID',
|
||||
)
|
||||
return span
|
||||
@@ -0,0 +1,627 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/mineru.py
|
||||
|
||||
用途:安全调用独立 MinerU 服务,并把嵌套 JSON/HTML 解析为不冒充最终证据的版面候选与能力报告。
|
||||
依赖:requests、BeautifulSoup、Pydantic、统一 AppError。
|
||||
逻辑:调用方提交受支持附件;本模块限制请求/响应大小、解包 MinerU 字符串 JSON,并在缺少单元格坐标时阻止转换为确定性证据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
|
||||
|
||||
MINERU_SUPPORTED_EXTENSIONS = frozenset({
|
||||
'.doc', '.docx', '.jpeg', '.jpg', '.pdf', '.png', '.ppt', '.pptx',
|
||||
})
|
||||
MINERU_JSON_FIELDS = ('middle_json', 'model_output', 'content_list')
|
||||
MINERU_CONTENT_COORDINATE_SCALE = 1000.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MinerUClientConfig:
|
||||
"""保存受控 MinerU 连接和资源上限;凭据不属于当前无认证协议。"""
|
||||
|
||||
base_url: str
|
||||
backend: str = 'pipeline'
|
||||
parse_method: str = 'auto'
|
||||
languages: tuple[str, ...] = ('ch',)
|
||||
connect_timeout_seconds: int = 10
|
||||
read_timeout_seconds: int = 300
|
||||
max_upload_bytes: int = 30 * 1024 * 1024
|
||||
max_response_bytes: int = 20 * 1024 * 1024
|
||||
|
||||
def validated_base_url(self) -> str:
|
||||
"""校验受信配置 URL,不允许凭据、query 或 fragment 混入服务地址。"""
|
||||
value = str(self.base_url or '').strip().rstrip('/')
|
||||
parsed = urlparse(value)
|
||||
if (
|
||||
parsed.scheme not in {'http', 'https'} or not parsed.netloc
|
||||
or parsed.username or parsed.password or parsed.query or parsed.fragment
|
||||
):
|
||||
raise ValidationError(
|
||||
'MinerU base URL is invalid',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_CONFIG_INVALID',
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
class MinerUModel(BaseModel):
|
||||
"""为 MinerU 候选结构启用严格字段校验,避免服务升级静默污染下游。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
|
||||
class MinerUTableCandidate(MinerUModel):
|
||||
"""保存 MinerU 表格 HTML 和整表坐标;没有单元格坐标时不得转成最终 LayoutTable。"""
|
||||
|
||||
candidate_id: str
|
||||
page_no: int = Field(ge=1)
|
||||
bbox: LayoutBBox
|
||||
normalized_bbox: LayoutBBox
|
||||
html: str
|
||||
row_count: int = Field(ge=0)
|
||||
cell_count: int = Field(ge=0)
|
||||
has_rowspan: bool
|
||||
has_colspan: bool
|
||||
cell_coordinates_available: bool = False
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_normalized_bbox(self) -> 'MinerUTableCandidate':
|
||||
"""拒绝超出 0..1 的表格坐标,避免错误页面尺寸制造伪几何。"""
|
||||
if self.normalized_bbox.x1 > 1 or self.normalized_bbox.y1 > 1:
|
||||
raise ValueError('MinerU table normalized_bbox must be within 0..1')
|
||||
return self
|
||||
|
||||
|
||||
class MinerUTextCandidate(MinerUModel):
|
||||
"""保存页内非表格文本块及其 bbox,供后续非结构化抽取和表格坐标对齐。"""
|
||||
|
||||
candidate_id: str
|
||||
page_no: int = Field(ge=1)
|
||||
bbox: LayoutBBox
|
||||
normalized_bbox: LayoutBBox
|
||||
text: str
|
||||
content_type: str
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_normalized_bbox(self) -> 'MinerUTextCandidate':
|
||||
"""要求文本块标准化坐标位于 0..1。"""
|
||||
if self.normalized_bbox.x1 > 1 or self.normalized_bbox.y1 > 1:
|
||||
raise ValueError('MinerU text normalized_bbox must be within 0..1')
|
||||
return self
|
||||
|
||||
|
||||
class MinerUPageCandidate(MinerUModel):
|
||||
"""保存一页尺寸及其去重后的表格候选。"""
|
||||
|
||||
page_no: int = Field(ge=1)
|
||||
width: float = Field(gt=0)
|
||||
height: float = Field(gt=0)
|
||||
text_blocks: list[MinerUTextCandidate] = Field(default_factory=list)
|
||||
tables: list[MinerUTableCandidate] = Field(default_factory=list)
|
||||
|
||||
|
||||
class MinerUCapabilityReport(MinerUModel):
|
||||
"""记录 MinerU 输出能否满足页级、表级和单元格级证据要求。"""
|
||||
|
||||
provider_version: str | None = None
|
||||
backend: str | None = None
|
||||
page_count: int = Field(ge=0)
|
||||
page_size_count: int = Field(ge=0)
|
||||
bbox_object_count: int = Field(ge=0)
|
||||
html_table_count: int = Field(ge=0)
|
||||
html_row_count: int = Field(ge=0)
|
||||
html_cell_count: int = Field(ge=0)
|
||||
text_block_count: int = Field(ge=0)
|
||||
cell_bbox_count: int = Field(ge=0)
|
||||
has_page_coordinates: bool
|
||||
has_table_structure: bool
|
||||
has_cell_coordinates: bool
|
||||
deterministic_cell_evidence_ready: bool
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_readiness(self) -> 'MinerUCapabilityReport':
|
||||
"""确定性单元格证据必须同时具备页坐标、表格结构和单元格坐标。"""
|
||||
expected = self.has_page_coordinates and self.has_table_structure and self.has_cell_coordinates
|
||||
if self.deterministic_cell_evidence_ready != expected:
|
||||
raise ValueError('deterministic evidence readiness is inconsistent with capabilities')
|
||||
return self
|
||||
|
||||
|
||||
class MinerUParseCandidate(MinerUModel):
|
||||
"""保存 MinerU 的非最终候选;业务层只能在能力报告准入后转换为 LayoutDocument。"""
|
||||
|
||||
task_id: str | None = None
|
||||
provider_version: str | None = None
|
||||
backend: str | None = None
|
||||
pages: list[MinerUPageCandidate]
|
||||
capability: MinerUCapabilityReport
|
||||
|
||||
|
||||
class MinerUClient:
|
||||
"""同步调用 MinerU `/file_parse`,供 L0 评测和后续异步适配器复用纯解析逻辑。"""
|
||||
|
||||
def __init__(self, config: MinerUClientConfig, *, session: requests.Session | None = None):
|
||||
"""保存已验证配置和可注入 Session,测试不得访问真实服务。"""
|
||||
self.config = config
|
||||
self.base_url = config.validated_base_url()
|
||||
self.session = session or requests.Session()
|
||||
|
||||
def parse_file(self, *, filename: str, content: bytes) -> dict[str, Any]:
|
||||
"""
|
||||
同步提交单个受支持文件并返回已校验 JSON,不记录文件名或正文。
|
||||
|
||||
Args:
|
||||
filename: 仅用于扩展名和 multipart;不得进入异常 details 或日志。
|
||||
content: 文件原始字节,受 max_upload_bytes 限制。
|
||||
Returns:
|
||||
MinerU 顶层任务结果字典。
|
||||
Raises:
|
||||
ValidationError: 文件类型、大小、终态或响应契约不合法。
|
||||
ServiceUnavailableError: 网络、超时、5xx 或响应超限。
|
||||
"""
|
||||
extension = Path(str(filename or '')).suffix.lower()
|
||||
if extension not in MINERU_SUPPORTED_EXTENSIONS:
|
||||
raise ValidationError(
|
||||
'MinerU file type is unsupported',
|
||||
code='SHIPPING_NOTICE.LAYOUT_FILE_TYPE_UNSUPPORTED',
|
||||
details={'extension': extension},
|
||||
)
|
||||
if not content:
|
||||
raise ValidationError(
|
||||
'MinerU input file is empty',
|
||||
code='SHIPPING_NOTICE.LAYOUT_FILE_EMPTY',
|
||||
)
|
||||
if len(content) > self.config.max_upload_bytes:
|
||||
raise ValidationError(
|
||||
'MinerU input file exceeds size limit',
|
||||
code='SHIPPING_NOTICE.LAYOUT_FILE_TOO_LARGE',
|
||||
details={'max_bytes': self.config.max_upload_bytes},
|
||||
)
|
||||
|
||||
data = [
|
||||
('backend', self.config.backend),
|
||||
('parse_method', self.config.parse_method),
|
||||
('formula_enable', 'false'),
|
||||
('table_enable', 'true'),
|
||||
('image_analysis', 'false'),
|
||||
('return_md', 'false'),
|
||||
('return_middle_json', 'true'),
|
||||
('return_model_output', 'true'),
|
||||
('return_content_list', 'true'),
|
||||
('return_images', 'false'),
|
||||
('response_format_zip', 'false'),
|
||||
]
|
||||
data.extend(('lang_list', item) for item in self.config.languages)
|
||||
try:
|
||||
response = self.session.post(
|
||||
f'{self.base_url}/file_parse',
|
||||
files=[('files', (filename, content, _mime_type(extension)))],
|
||||
data=data,
|
||||
stream=True,
|
||||
timeout=(self.config.connect_timeout_seconds, self.config.read_timeout_seconds),
|
||||
)
|
||||
except requests.exceptions.RequestException as exc:
|
||||
raise ServiceUnavailableError(
|
||||
'MinerU request failed',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE',
|
||||
) from exc
|
||||
|
||||
raw = _read_limited_response(response, max_bytes=self.config.max_response_bytes)
|
||||
try:
|
||||
payload = json.loads(raw.decode(response.encoding or 'utf-8'))
|
||||
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
raise ValidationError(
|
||||
'MinerU response is not valid JSON',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
) from exc
|
||||
if not isinstance(payload, dict):
|
||||
raise ValidationError(
|
||||
'MinerU response must be an object',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
if response.status_code >= 500:
|
||||
raise ServiceUnavailableError(
|
||||
'MinerU service failed',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE',
|
||||
details={'status': response.status_code},
|
||||
)
|
||||
if response.status_code >= 400 or str(payload.get('status') or '').lower() != 'completed':
|
||||
raise ValidationError(
|
||||
'MinerU parse task failed',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_PARSE_FAILED',
|
||||
details={
|
||||
'status': response.status_code,
|
||||
'backend': str(payload.get('backend') or ''),
|
||||
'provider_error_code': _provider_error_code(payload.get('error')),
|
||||
},
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def parse_mineru_candidate(payload: dict[str, Any]) -> MinerUParseCandidate:
|
||||
"""
|
||||
解包 MinerU 结果并提取页尺寸、HTML 表格、整表坐标和能力报告。
|
||||
|
||||
Args:
|
||||
payload: `/file_parse` 或异步结果接口返回的完整对象。
|
||||
Returns:
|
||||
不含伪造单元格坐标的 MinerUParseCandidate。
|
||||
Raises:
|
||||
ValidationError: 顶层、results 或嵌套 JSON 结构不合法。
|
||||
"""
|
||||
if not isinstance(payload, dict) or str(payload.get('status') or '').lower() != 'completed':
|
||||
raise ValidationError(
|
||||
'MinerU result is not completed',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
results = payload.get('results')
|
||||
if not isinstance(results, dict) or len(results) != 1:
|
||||
raise ValidationError(
|
||||
'MinerU result must contain exactly one file',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
result = next(iter(results.values()))
|
||||
if not isinstance(result, dict):
|
||||
raise ValidationError(
|
||||
'MinerU file result must be an object',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
decoded = {field: _decode_json_field(result.get(field), field=field) for field in MINERU_JSON_FIELDS}
|
||||
page_sizes = _page_sizes(decoded['middle_json'], decoded['model_output'])
|
||||
tables = _table_candidates(decoded['content_list'], page_sizes=page_sizes)
|
||||
text_blocks = _text_candidates(decoded['content_list'], page_sizes=page_sizes)
|
||||
pages = [
|
||||
MinerUPageCandidate(
|
||||
page_no=page_no,
|
||||
width=size[0],
|
||||
height=size[1],
|
||||
text_blocks=[item for item in text_blocks if item.page_no == page_no],
|
||||
tables=[item for item in tables if item.page_no == page_no],
|
||||
)
|
||||
for page_no, size in sorted(page_sizes.items())
|
||||
]
|
||||
report = inspect_mineru_capabilities(
|
||||
payload,
|
||||
decoded=decoded,
|
||||
pages=pages,
|
||||
)
|
||||
return MinerUParseCandidate(
|
||||
task_id=str(payload.get('task_id') or '') or None,
|
||||
provider_version=str(payload.get('version') or '') or None,
|
||||
backend=str(payload.get('backend') or '') or None,
|
||||
pages=pages,
|
||||
capability=report,
|
||||
)
|
||||
|
||||
|
||||
def inspect_mineru_capabilities(
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
decoded: dict[str, Any] | None = None,
|
||||
pages: list[MinerUPageCandidate] | None = None,
|
||||
) -> MinerUCapabilityReport:
|
||||
"""
|
||||
审计 MinerU 是否具备页级、表级和单元格级坐标证据。
|
||||
|
||||
Args:
|
||||
payload: 完整 MinerU 任务结果。
|
||||
decoded: 可复用的嵌套 JSON,避免重复解码。
|
||||
pages: 可复用的候选页面。
|
||||
Returns:
|
||||
明确 deterministic_cell_evidence_ready 的能力报告。
|
||||
"""
|
||||
if decoded is None or pages is None:
|
||||
candidate = parse_mineru_candidate(payload)
|
||||
return candidate.capability
|
||||
bbox_count = 0
|
||||
cell_bbox_count = 0
|
||||
for value in decoded.values():
|
||||
for item in _walk_dicts(value):
|
||||
if _valid_raw_bbox(item.get('bbox')):
|
||||
bbox_count += 1
|
||||
if _is_cell_coordinate_object(item):
|
||||
cell_bbox_count += 1
|
||||
table_count = sum(len(page.tables) for page in pages)
|
||||
row_count = sum(item.row_count for page in pages for item in page.tables)
|
||||
cell_count = sum(item.cell_count for page in pages for item in page.tables)
|
||||
text_block_count = sum(len(page.text_blocks) for page in pages)
|
||||
has_pages = bool(pages) and all(page.width > 0 and page.height > 0 for page in pages)
|
||||
has_tables = table_count > 0 and row_count > 0 and cell_count > 0
|
||||
has_cells = cell_count > 0 and cell_bbox_count >= cell_count
|
||||
issues: list[str] = []
|
||||
if not has_pages:
|
||||
issues.append('mineru_page_coordinates_missing')
|
||||
if not has_tables:
|
||||
issues.append('mineru_table_structure_missing')
|
||||
if not has_cells:
|
||||
issues.append(
|
||||
'mineru_cell_coordinates_missing'
|
||||
if cell_bbox_count == 0 else 'mineru_cell_coordinates_incomplete'
|
||||
)
|
||||
return MinerUCapabilityReport(
|
||||
provider_version=str(payload.get('version') or '') or None,
|
||||
backend=str(payload.get('backend') or '') or None,
|
||||
page_count=len(pages),
|
||||
page_size_count=sum(1 for page in pages if page.width > 0 and page.height > 0),
|
||||
bbox_object_count=bbox_count,
|
||||
html_table_count=table_count,
|
||||
html_row_count=row_count,
|
||||
html_cell_count=cell_count,
|
||||
text_block_count=text_block_count,
|
||||
cell_bbox_count=cell_bbox_count,
|
||||
has_page_coordinates=has_pages,
|
||||
has_table_structure=has_tables,
|
||||
has_cell_coordinates=has_cells,
|
||||
deterministic_cell_evidence_ready=has_pages and has_tables and has_cells,
|
||||
issues=issues,
|
||||
)
|
||||
|
||||
|
||||
def _read_limited_response(response: requests.Response, *, max_bytes: int) -> bytes:
|
||||
"""按流读取 MinerU 响应并在超过上限时终止,避免大 JSON/ZIP 耗尽 Worker 内存。"""
|
||||
try:
|
||||
content_length = int(response.headers.get('Content-Length') or 0)
|
||||
except (TypeError, ValueError):
|
||||
content_length = 0
|
||||
if content_length > max_bytes:
|
||||
response.close()
|
||||
raise ServiceUnavailableError(
|
||||
'MinerU response exceeds size limit',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_RESPONSE_TOO_LARGE',
|
||||
details={'max_bytes': max_bytes},
|
||||
)
|
||||
chunks: list[bytes] = []
|
||||
size = 0
|
||||
try:
|
||||
for chunk in response.iter_content(chunk_size=64 * 1024):
|
||||
if not chunk:
|
||||
continue
|
||||
size += len(chunk)
|
||||
if size > max_bytes:
|
||||
raise ServiceUnavailableError(
|
||||
'MinerU response exceeds size limit',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_RESPONSE_TOO_LARGE',
|
||||
details={'max_bytes': max_bytes},
|
||||
)
|
||||
chunks.append(chunk)
|
||||
finally:
|
||||
response.close()
|
||||
return b''.join(chunks)
|
||||
|
||||
|
||||
def _decode_json_field(value: Any, *, field: str) -> Any:
|
||||
"""解包 MinerU 将 middle/model/content JSON 作为字符串返回的协议形式。"""
|
||||
parsed = value
|
||||
for _ in range(2):
|
||||
if not isinstance(parsed, str):
|
||||
break
|
||||
try:
|
||||
parsed = json.loads(parsed)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValidationError(
|
||||
f'MinerU {field} is not valid JSON',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
) from exc
|
||||
if not isinstance(parsed, (dict, list)):
|
||||
raise ValidationError(
|
||||
f'MinerU {field} has invalid type',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
return parsed
|
||||
|
||||
|
||||
def _page_sizes(middle_json: Any, model_output: Any) -> dict[int, tuple[float, float]]:
|
||||
"""从 middle_json 优先、model_output 次优读取 1-based 页码与页面宽高。"""
|
||||
result: dict[int, tuple[float, float]] = {}
|
||||
if isinstance(middle_json, dict):
|
||||
pdf_info = middle_json.get('pdf_info')
|
||||
if isinstance(pdf_info, list):
|
||||
for position, page in enumerate(pdf_info):
|
||||
if not isinstance(page, dict):
|
||||
continue
|
||||
size = page.get('page_size')
|
||||
if isinstance(size, (list, tuple)) and len(size) >= 2:
|
||||
_add_page_size(result, position + 1, size[0], size[1])
|
||||
if isinstance(model_output, list):
|
||||
for position, page in enumerate(model_output):
|
||||
if not isinstance(page, dict):
|
||||
continue
|
||||
info = page.get('page_info') if isinstance(page.get('page_info'), dict) else page
|
||||
page_no = _as_int(info.get('page_no'), default=position) + 1
|
||||
_add_page_size(result, page_no, info.get('width'), info.get('height'))
|
||||
return result
|
||||
|
||||
|
||||
def _table_candidates(content_list: Any, *, page_sizes: dict[int, tuple[float, float]]) -> list[MinerUTableCandidate]:
|
||||
"""从 content_list 提取 HTML 表格,并将 MinerU 0..1000 画布坐标映射到 PDF 页面。"""
|
||||
result: list[MinerUTableCandidate] = []
|
||||
seen: set[str] = set()
|
||||
for item in _walk_dicts(content_list):
|
||||
if str(item.get('type') or '').lower() != 'table':
|
||||
continue
|
||||
html = item.get('table_body') or item.get('html')
|
||||
bbox = item.get('bbox')
|
||||
if not isinstance(html, str) or not html.strip() or not _valid_raw_bbox(bbox):
|
||||
continue
|
||||
page_no = _as_int(item.get('page_idx'), default=0) + 1
|
||||
size = page_sizes.get(page_no)
|
||||
if size is None:
|
||||
continue
|
||||
raw_bbox, normalized = _content_bbox_to_page(bbox, page_size=size)
|
||||
soup = BeautifulSoup(html, 'html.parser')
|
||||
row_count = len(soup.find_all('tr'))
|
||||
cell_count = len(soup.find_all(['td', 'th']))
|
||||
fingerprint = hashlib.sha256(
|
||||
f'{page_no}|{bbox}|{html}'.encode('utf-8'),
|
||||
).hexdigest()[:16]
|
||||
if fingerprint in seen:
|
||||
continue
|
||||
seen.add(fingerprint)
|
||||
result.append(MinerUTableCandidate(
|
||||
candidate_id=f'mineru-table-{fingerprint}',
|
||||
page_no=page_no,
|
||||
bbox=raw_bbox,
|
||||
normalized_bbox=normalized,
|
||||
html=html,
|
||||
row_count=row_count,
|
||||
cell_count=cell_count,
|
||||
has_rowspan=bool(soup.find(attrs={'rowspan': True})),
|
||||
has_colspan=bool(soup.find(attrs={'colspan': True})),
|
||||
cell_coordinates_available=False,
|
||||
))
|
||||
return result
|
||||
|
||||
|
||||
def _text_candidates(content_list: Any, *, page_sizes: dict[int, tuple[float, float]]) -> list[MinerUTextCandidate]:
|
||||
"""提取非表格文本块,并将 MinerU 0..1000 画布坐标映射到 PDF 页面。"""
|
||||
result: list[MinerUTextCandidate] = []
|
||||
seen: set[str] = set()
|
||||
for item in _walk_dicts(content_list):
|
||||
content_type = str(item.get('type') or '').lower()
|
||||
if content_type == 'table':
|
||||
continue
|
||||
text = item.get('text')
|
||||
bbox = item.get('bbox')
|
||||
if not isinstance(text, str) or not text.strip() or not _valid_raw_bbox(bbox):
|
||||
continue
|
||||
page_no = _as_int(item.get('page_idx'), default=0) + 1
|
||||
size = page_sizes.get(page_no)
|
||||
if size is None:
|
||||
continue
|
||||
raw_bbox, normalized = _content_bbox_to_page(bbox, page_size=size)
|
||||
fingerprint = hashlib.sha256(
|
||||
f'{page_no}|{bbox}|{content_type}|{text}'.encode('utf-8'),
|
||||
).hexdigest()[:16]
|
||||
if fingerprint in seen:
|
||||
continue
|
||||
seen.add(fingerprint)
|
||||
result.append(MinerUTextCandidate(
|
||||
candidate_id=f'mineru-text-{fingerprint}',
|
||||
page_no=page_no,
|
||||
bbox=raw_bbox,
|
||||
normalized_bbox=normalized,
|
||||
text=text,
|
||||
content_type=content_type or 'text',
|
||||
))
|
||||
return result
|
||||
|
||||
|
||||
def _walk_dicts(value: Any) -> Iterable[dict[str, Any]]:
|
||||
"""深度优先遍历嵌套 MinerU JSON 中的所有对象。"""
|
||||
if isinstance(value, dict):
|
||||
yield value
|
||||
for child in value.values():
|
||||
yield from _walk_dicts(child)
|
||||
elif isinstance(value, list):
|
||||
for child in value:
|
||||
yield from _walk_dicts(child)
|
||||
|
||||
|
||||
def _is_cell_coordinate_object(item: dict[str, Any]) -> bool:
|
||||
"""仅把同时具有 bbox 和明确 cell/row/column 身份的对象计为单元格坐标。"""
|
||||
keys = {str(key).lower() for key in item}
|
||||
return bool(
|
||||
{'cell_id', 'cell_index'} & keys
|
||||
or ({'row_index', 'column_index'} <= keys)
|
||||
or ({'row_idx', 'col_idx'} <= keys)
|
||||
)
|
||||
|
||||
|
||||
def _valid_raw_bbox(value: Any) -> bool:
|
||||
"""判断服务 bbox 是否为四个有序非负数。"""
|
||||
if not isinstance(value, (list, tuple)) or len(value) != 4:
|
||||
return False
|
||||
try:
|
||||
x0, y0, x1, y1 = (float(item) for item in value)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return x0 >= 0 and y0 >= 0 and x1 > x0 and y1 > y0
|
||||
|
||||
|
||||
def _content_bbox_to_page(
|
||||
value: list[Any] | tuple[Any, ...], *, page_size: tuple[float, float],
|
||||
) -> tuple[LayoutBBox, LayoutBBox]:
|
||||
"""
|
||||
将 MinerU content_list 的 0..1000 画布坐标转换为标准化坐标和 PDF 页面单位。
|
||||
|
||||
核心逻辑:MinerU model_output 使用模型页面像素,content_list 再分别按宽高缩放到 1000;
|
||||
因此不能直接用 PDF page_size 做除数,也不能把越界值裁剪到 1。
|
||||
"""
|
||||
x0, y0, x1, y1 = (float(item) for item in value)
|
||||
if x1 > MINERU_CONTENT_COORDINATE_SCALE or y1 > MINERU_CONTENT_COORDINATE_SCALE:
|
||||
raise ValidationError(
|
||||
'MinerU content bbox exceeds coordinate canvas',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
normalized = LayoutBBox(
|
||||
x0=x0 / MINERU_CONTENT_COORDINATE_SCALE,
|
||||
y0=y0 / MINERU_CONTENT_COORDINATE_SCALE,
|
||||
x1=x1 / MINERU_CONTENT_COORDINATE_SCALE,
|
||||
y1=y1 / MINERU_CONTENT_COORDINATE_SCALE,
|
||||
)
|
||||
raw_bbox = LayoutBBox(
|
||||
x0=normalized.x0 * page_size[0],
|
||||
y0=normalized.y0 * page_size[1],
|
||||
x1=normalized.x1 * page_size[0],
|
||||
y1=normalized.y1 * page_size[1],
|
||||
)
|
||||
return raw_bbox, normalized
|
||||
|
||||
|
||||
def _add_page_size(result: dict[int, tuple[float, float]], page_no: int, width: Any, height: Any) -> None:
|
||||
"""写入合法页尺寸;已有 middle_json 结果优先保留。"""
|
||||
try:
|
||||
pair = (float(width), float(height))
|
||||
except (TypeError, ValueError):
|
||||
return
|
||||
if page_no >= 1 and pair[0] > 0 and pair[1] > 0:
|
||||
result.setdefault(page_no, pair)
|
||||
|
||||
|
||||
def _as_int(value: Any, *, default: int) -> int:
|
||||
"""安全解析 MinerU 页序,失败时使用调用方提供的零基默认值。"""
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _mime_type(extension: str) -> str:
|
||||
"""按已允许扩展名返回稳定 multipart MIME,不信任用户传入 Content-Type。"""
|
||||
return {
|
||||
'.pdf': 'application/pdf',
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.doc': 'application/msword',
|
||||
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'.ppt': 'application/vnd.ms-powerpoint',
|
||||
'.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
}[extension]
|
||||
|
||||
|
||||
def _provider_error_code(value: Any) -> str:
|
||||
"""将服务端自由文本错误收敛为有限诊断码,避免文件名或正文进入业务错误详情。"""
|
||||
text = str(value or '').lower()
|
||||
if 'device string must not be empty' in text:
|
||||
return 'device_not_configured'
|
||||
if 'out of memory' in text or 'cuda oom' in text:
|
||||
return 'provider_out_of_memory'
|
||||
if 'unsupported' in text:
|
||||
return 'provider_unsupported_input'
|
||||
return 'provider_parse_failed'
|
||||
@@ -0,0 +1,433 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/opencv_table.py
|
||||
|
||||
用途:在 MinerU 整表区域内用 OpenCV 恢复严格有框表网格,生成待评测的 HTML cell 几何候选。
|
||||
依赖:opencv-python-headless、numpy、document_layout.html_table/contracts。
|
||||
逻辑:多组形态学参数独立检测 cell 轮廓;仅当至少两组结果与 HTML 网格完全一致且边界共识稳定时输出 ready。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.html_table import HtmlGrid
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OpenCVGridConfig:
|
||||
"""保存一组形态学线段尺度;不同配置用于形成独立检测共识。"""
|
||||
|
||||
horizontal_divisor: int
|
||||
vertical_divisor: int
|
||||
close_length: int
|
||||
|
||||
|
||||
DEFAULT_GRID_CONFIGS = (
|
||||
OpenCVGridConfig(horizontal_divisor=30, vertical_divisor=20, close_length=3),
|
||||
OpenCVGridConfig(horizontal_divisor=25, vertical_divisor=18, close_length=5),
|
||||
OpenCVGridConfig(horizontal_divisor=20, vertical_divisor=15, close_length=7),
|
||||
)
|
||||
|
||||
|
||||
class OpenCVTableModel(BaseModel):
|
||||
"""为 OpenCV 网格候选启用严格字段校验,防止实验结果静默漂移。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
|
||||
class OpenCVCellGeometry(OpenCVTableModel):
|
||||
"""保存一个 HTML 原始 cell 在页面坐标和标准化坐标中的候选矩形。"""
|
||||
|
||||
cell_id: str
|
||||
row_index: int = Field(ge=0)
|
||||
column_index: int = Field(ge=0)
|
||||
row_span: int = Field(ge=1)
|
||||
column_span: int = Field(ge=1)
|
||||
bbox: LayoutBBox
|
||||
normalized_bbox: LayoutBBox
|
||||
|
||||
|
||||
class OpenCVTableGeometryResult(OpenCVTableModel):
|
||||
"""汇总多参数网格共识、cell 几何候选和不准入原因。"""
|
||||
|
||||
ready: bool
|
||||
consensus_count: int = Field(ge=0)
|
||||
row_count: int = Field(ge=0)
|
||||
column_count: int = Field(ge=0)
|
||||
cells: list[OpenCVCellGeometry] = Field(default_factory=list)
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_readiness(self) -> 'OpenCVTableGeometryResult':
|
||||
"""ready 结果必须具有多配置共识和完整原始 cell 几何。"""
|
||||
if self.ready and (self.consensus_count < 2 or not self.cells or self.issues):
|
||||
raise ValueError('ready OpenCV table geometry requires stable complete consensus')
|
||||
if not self.ready and self.cells:
|
||||
raise ValueError('non-ready OpenCV table geometry must not expose cell bboxes')
|
||||
return self
|
||||
|
||||
|
||||
class OpenCVTextValidationResult(OpenCVTableModel):
|
||||
"""保存独立 PDF 文本层对 OpenCV cell bbox 的一致性验收结果。"""
|
||||
|
||||
accepted: bool
|
||||
nonempty_cell_count: int = Field(ge=0)
|
||||
matched_cell_count: int = Field(ge=0)
|
||||
match_rate: float = Field(ge=0, le=1)
|
||||
mismatched_cell_ids: list[str] = Field(default_factory=list)
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
def reconstruct_opencv_table_geometry(
|
||||
page_image: np.ndarray,
|
||||
*,
|
||||
page_width: float,
|
||||
page_height: float,
|
||||
table_bbox: LayoutBBox,
|
||||
grid: HtmlGrid,
|
||||
configs: tuple[OpenCVGridConfig, ...] = DEFAULT_GRID_CONFIGS,
|
||||
min_consensus: int = 2,
|
||||
boundary_tolerance_pixels: int = 8,
|
||||
) -> OpenCVTableGeometryResult:
|
||||
"""
|
||||
从渲染页面中恢复与 HTML 网格完全一致的有框表 cell bbox 候选。
|
||||
|
||||
Args:
|
||||
page_image: 左上原点的灰度或 RGB 页面 ndarray。
|
||||
page_width/page_height: MinerU/PDF 页面单位尺寸,必须与 table_bbox 同坐标系。
|
||||
table_bbox: MinerU 整表页面矩形,仅在该区域内检测。
|
||||
grid: 已展开 rowspan/colspan 的 HTML 网格。
|
||||
configs: 至少两组独立形态学配置。
|
||||
min_consensus: 达到 ready 所需的一致配置数量,最小为 2。
|
||||
boundary_tolerance_pixels: 不同配置边界允许的最大像素差。
|
||||
Returns:
|
||||
ready 时包含所有 HTML 原始 cell 的页面 bbox;失败时仅包含问题码。
|
||||
"""
|
||||
if min_consensus < 2 or len(configs) < min_consensus:
|
||||
raise ValueError('OpenCV grid reconstruction requires at least two configurations')
|
||||
image = _grayscale_page(page_image)
|
||||
crop, origin = _table_crop(
|
||||
image,
|
||||
table_bbox=table_bbox,
|
||||
page_width=page_width,
|
||||
page_height=page_height,
|
||||
)
|
||||
if crop is None:
|
||||
return _not_ready(grid, 'opencv_table_crop_invalid')
|
||||
|
||||
detections = [
|
||||
item
|
||||
for config in configs
|
||||
if (item := _detect_grid_boundaries(crop, config=config)) is not None
|
||||
and len(item[0]) == grid.column_count + 1
|
||||
and len(item[1]) == grid.row_count + 1
|
||||
]
|
||||
consensus = _boundary_consensus(
|
||||
detections,
|
||||
min_consensus=min_consensus,
|
||||
tolerance=boundary_tolerance_pixels,
|
||||
)
|
||||
if consensus is None:
|
||||
issue = 'opencv_table_grid_shape_mismatch' if detections else 'opencv_table_grid_not_detected'
|
||||
return _not_ready(grid, issue)
|
||||
x_boundaries, y_boundaries, consensus_count = consensus
|
||||
cells = _cell_geometries(
|
||||
grid,
|
||||
x_boundaries=x_boundaries,
|
||||
y_boundaries=y_boundaries,
|
||||
crop_origin=origin,
|
||||
image_width=image.shape[1],
|
||||
image_height=image.shape[0],
|
||||
page_width=page_width,
|
||||
page_height=page_height,
|
||||
)
|
||||
if len(cells) != len(grid.cells):
|
||||
return _not_ready(grid, 'opencv_table_cell_geometry_incomplete')
|
||||
return OpenCVTableGeometryResult(
|
||||
ready=True,
|
||||
consensus_count=consensus_count,
|
||||
row_count=grid.row_count,
|
||||
column_count=grid.column_count,
|
||||
cells=cells,
|
||||
)
|
||||
|
||||
|
||||
def validate_opencv_cell_text(
|
||||
geometry: OpenCVTableGeometryResult,
|
||||
*,
|
||||
grid: HtmlGrid,
|
||||
bounded_text_reader: Any,
|
||||
minimum_match_rate: float = 0.95,
|
||||
required_cell_ids: set[str] | None = None,
|
||||
) -> OpenCVTextValidationResult:
|
||||
"""
|
||||
用独立 PDF 文本层验收 OpenCV cell bbox,不允许文本参与修正或选择几何边界。
|
||||
|
||||
Args:
|
||||
geometry: 已通过多参数共识的 OpenCV 几何候选。
|
||||
grid: 同一 HTML 展开网格,用于读取原始 cell 文本。
|
||||
bounded_text_reader: 接收 LayoutBBox 并返回该页面矩形内原生 PDF 文本的函数。
|
||||
minimum_match_rate: 全部非空 cell 的最低一致率,默认 95%。
|
||||
required_cell_ids: 必须逐一匹配的高风险 cell ID 集合;任一不一致即拒绝。
|
||||
Returns:
|
||||
仅包含计数、比率和 cell_id 的验收结果,不复制字段值或原文。
|
||||
"""
|
||||
if not geometry.ready:
|
||||
return OpenCVTextValidationResult(
|
||||
accepted=False,
|
||||
nonempty_cell_count=0,
|
||||
matched_cell_count=0,
|
||||
match_rate=0,
|
||||
issues=['opencv_table_geometry_not_ready'],
|
||||
)
|
||||
if not 0 < minimum_match_rate <= 1:
|
||||
raise ValueError('OpenCV text validation match rate must be within (0, 1]')
|
||||
cells_by_id = {cell.cell_id: cell for cell in grid.cells}
|
||||
mismatched: list[str] = []
|
||||
matched = 0
|
||||
nonempty = 0
|
||||
for item in geometry.cells:
|
||||
cell = cells_by_id.get(item.cell_id)
|
||||
if cell is None:
|
||||
mismatched.append(item.cell_id)
|
||||
continue
|
||||
expected = _normalized_cell_text(cell.text)
|
||||
if not expected:
|
||||
continue
|
||||
nonempty += 1
|
||||
actual = _normalized_cell_text(bounded_text_reader(item.bbox))
|
||||
if actual and (expected in actual or actual in expected):
|
||||
matched += 1
|
||||
else:
|
||||
mismatched.append(item.cell_id)
|
||||
match_rate = matched / nonempty if nonempty else 0.0
|
||||
required = set(required_cell_ids or set())
|
||||
required_mismatch = bool(required & set(mismatched))
|
||||
issues: list[str] = []
|
||||
if nonempty == 0:
|
||||
issues.append('opencv_table_text_validation_empty')
|
||||
if match_rate < minimum_match_rate:
|
||||
issues.append('opencv_table_text_match_rate_low')
|
||||
if required_mismatch:
|
||||
issues.append('opencv_table_required_cell_text_mismatch')
|
||||
return OpenCVTextValidationResult(
|
||||
accepted=not issues,
|
||||
nonempty_cell_count=nonempty,
|
||||
matched_cell_count=matched,
|
||||
match_rate=match_rate,
|
||||
mismatched_cell_ids=sorted(mismatched),
|
||||
issues=issues,
|
||||
)
|
||||
|
||||
|
||||
def _grayscale_page(page_image: np.ndarray) -> np.ndarray:
|
||||
"""将受控页面 ndarray 转为 uint8 灰度图,拒绝不支持的维度。"""
|
||||
image = np.asarray(page_image)
|
||||
if image.dtype != np.uint8:
|
||||
image = np.clip(image, 0, 255).astype(np.uint8)
|
||||
if image.ndim == 2:
|
||||
return image
|
||||
if image.ndim == 3 and image.shape[2] in {3, 4}:
|
||||
code = cv2.COLOR_RGBA2GRAY if image.shape[2] == 4 else cv2.COLOR_RGB2GRAY
|
||||
return cv2.cvtColor(image, code)
|
||||
raise ValueError('OpenCV page image must be grayscale, RGB, or RGBA')
|
||||
|
||||
|
||||
def _table_crop(
|
||||
image: np.ndarray,
|
||||
*,
|
||||
table_bbox: LayoutBBox,
|
||||
page_width: float,
|
||||
page_height: float,
|
||||
) -> tuple[np.ndarray | None, tuple[int, int]]:
|
||||
"""把页面单位 table bbox 映射到图像像素并返回受控裁剪及左上原点。"""
|
||||
if page_width <= 0 or page_height <= 0:
|
||||
raise ValueError('OpenCV page dimensions must be positive')
|
||||
scale_x = image.shape[1] / page_width
|
||||
scale_y = image.shape[0] / page_height
|
||||
x0 = max(0, int(round(table_bbox.x0 * scale_x)) - 3)
|
||||
y0 = max(0, int(round(table_bbox.y0 * scale_y)) - 3)
|
||||
x1 = min(image.shape[1], int(round(table_bbox.x1 * scale_x)) + 4)
|
||||
y1 = min(image.shape[0], int(round(table_bbox.y1 * scale_y)) + 4)
|
||||
if x1 - x0 < 16 or y1 - y0 < 16:
|
||||
return None, (x0, y0)
|
||||
return image[y0:y1, x0:x1], (x0, y0)
|
||||
|
||||
|
||||
def _detect_grid_boundaries(
|
||||
crop: np.ndarray, *, config: OpenCVGridConfig,
|
||||
) -> tuple[list[int], list[int]] | None:
|
||||
"""用形态学线段和 cell 轮廓提取基础网格边界;不按文字或预期列宽补线。"""
|
||||
binary = cv2.adaptiveThreshold(
|
||||
crop,
|
||||
255,
|
||||
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
||||
cv2.THRESH_BINARY_INV,
|
||||
31,
|
||||
15,
|
||||
)
|
||||
horizontal_kernel = cv2.getStructuringElement(
|
||||
cv2.MORPH_RECT,
|
||||
(max(10, crop.shape[1] // config.horizontal_divisor), 1),
|
||||
)
|
||||
vertical_kernel = cv2.getStructuringElement(
|
||||
cv2.MORPH_RECT,
|
||||
(1, max(10, crop.shape[0] // config.vertical_divisor)),
|
||||
)
|
||||
horizontal = cv2.morphologyEx(binary, cv2.MORPH_OPEN, horizontal_kernel)
|
||||
vertical = cv2.morphologyEx(binary, cv2.MORPH_OPEN, vertical_kernel)
|
||||
if config.close_length:
|
||||
horizontal = cv2.morphologyEx(
|
||||
horizontal,
|
||||
cv2.MORPH_CLOSE,
|
||||
cv2.getStructuringElement(cv2.MORPH_RECT, (config.close_length, 1)),
|
||||
)
|
||||
vertical = cv2.morphologyEx(
|
||||
vertical,
|
||||
cv2.MORPH_CLOSE,
|
||||
cv2.getStructuringElement(cv2.MORPH_RECT, (1, config.close_length)),
|
||||
)
|
||||
mask = cv2.bitwise_or(horizontal, vertical)
|
||||
contours, _hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
|
||||
edges_x: list[int] = []
|
||||
edges_y: list[int] = []
|
||||
crop_area = crop.shape[0] * crop.shape[1]
|
||||
for contour in contours:
|
||||
x, y, width, height = cv2.boundingRect(contour)
|
||||
area = width * height
|
||||
if width < 8 or height < 8 or area < 50 or area > crop_area * 0.95:
|
||||
continue
|
||||
edges_x.extend((x, x + width))
|
||||
edges_y.extend((y, y + height))
|
||||
x_boundaries = _cluster_boundaries(edges_x, tolerance=8)
|
||||
y_boundaries = _cluster_boundaries(edges_y, tolerance=8)
|
||||
if len(x_boundaries) < 2 or len(y_boundaries) < 2:
|
||||
return None
|
||||
return x_boundaries, y_boundaries
|
||||
|
||||
|
||||
def _cluster_boundaries(values: list[int], *, tolerance: int) -> list[int]:
|
||||
"""把轮廓的近邻边缘聚合成稳定网格线,不补齐未检测到的边界。"""
|
||||
groups: list[list[int]] = []
|
||||
for value in sorted(values):
|
||||
if not groups or value - groups[-1][-1] > tolerance:
|
||||
groups.append([value])
|
||||
else:
|
||||
groups[-1].append(value)
|
||||
return [int(round(sum(group) / len(group))) for group in groups]
|
||||
|
||||
|
||||
def _boundary_consensus(
|
||||
detections: list[tuple[list[int], list[int]]],
|
||||
*,
|
||||
min_consensus: int,
|
||||
tolerance: int,
|
||||
) -> tuple[list[int], list[int], int] | None:
|
||||
"""选择至少 min_consensus 组逐边界一致的检测,并以中位数形成共识。"""
|
||||
for anchor_index, anchor in enumerate(detections):
|
||||
compatible = [anchor]
|
||||
for index, candidate in enumerate(detections):
|
||||
if index == anchor_index:
|
||||
continue
|
||||
if _boundaries_compatible(anchor, candidate, tolerance=tolerance):
|
||||
compatible.append(candidate)
|
||||
if len(compatible) < min_consensus:
|
||||
continue
|
||||
x_values = [
|
||||
int(round(float(np.median([item[0][index] for item in compatible]))))
|
||||
for index in range(len(anchor[0]))
|
||||
]
|
||||
y_values = [
|
||||
int(round(float(np.median([item[1][index] for item in compatible]))))
|
||||
for index in range(len(anchor[1]))
|
||||
]
|
||||
return x_values, y_values, len(compatible)
|
||||
return None
|
||||
|
||||
|
||||
def _boundaries_compatible(
|
||||
left: tuple[list[int], list[int]],
|
||||
right: tuple[list[int], list[int]],
|
||||
*,
|
||||
tolerance: int,
|
||||
) -> bool:
|
||||
"""判断两组等形边界是否逐项落在允许像素容差内。"""
|
||||
return (
|
||||
len(left[0]) == len(right[0])
|
||||
and len(left[1]) == len(right[1])
|
||||
and all(abs(a - b) <= tolerance for a, b in zip(left[0], right[0]))
|
||||
and all(abs(a - b) <= tolerance for a, b in zip(left[1], right[1]))
|
||||
)
|
||||
|
||||
|
||||
def _cell_geometries(
|
||||
grid: HtmlGrid,
|
||||
*,
|
||||
x_boundaries: list[int],
|
||||
y_boundaries: list[int],
|
||||
crop_origin: tuple[int, int],
|
||||
image_width: int,
|
||||
image_height: int,
|
||||
page_width: float,
|
||||
page_height: float,
|
||||
) -> list[OpenCVCellGeometry]:
|
||||
"""按 HTML 原始 cell 的 rowspan/colspan 合并基础网格,并映射回页面坐标。"""
|
||||
scale_x = page_width / image_width
|
||||
scale_y = page_height / image_height
|
||||
result: list[OpenCVCellGeometry] = []
|
||||
for cell in grid.cells:
|
||||
row_end = cell.row_index + cell.row_span
|
||||
column_end = cell.column_index + cell.column_span
|
||||
if row_end >= len(y_boundaries) or column_end >= len(x_boundaries):
|
||||
return []
|
||||
pixel_x0 = crop_origin[0] + x_boundaries[cell.column_index]
|
||||
pixel_y0 = crop_origin[1] + y_boundaries[cell.row_index]
|
||||
pixel_x1 = crop_origin[0] + x_boundaries[column_end]
|
||||
pixel_y1 = crop_origin[1] + y_boundaries[row_end]
|
||||
bbox = LayoutBBox(
|
||||
x0=pixel_x0 * scale_x,
|
||||
y0=pixel_y0 * scale_y,
|
||||
x1=pixel_x1 * scale_x,
|
||||
y1=pixel_y1 * scale_y,
|
||||
)
|
||||
result.append(OpenCVCellGeometry(
|
||||
cell_id=cell.cell_id,
|
||||
row_index=cell.row_index,
|
||||
column_index=cell.column_index,
|
||||
row_span=cell.row_span,
|
||||
column_span=cell.column_span,
|
||||
bbox=bbox,
|
||||
normalized_bbox=LayoutBBox(
|
||||
x0=bbox.x0 / page_width,
|
||||
y0=bbox.y0 / page_height,
|
||||
x1=bbox.x1 / page_width,
|
||||
y1=bbox.y1 / page_height,
|
||||
),
|
||||
))
|
||||
return result
|
||||
|
||||
|
||||
def _not_ready(grid: HtmlGrid, issue: str) -> OpenCVTableGeometryResult:
|
||||
"""构造不暴露任何候选 bbox 的稳定失败结果。"""
|
||||
return OpenCVTableGeometryResult(
|
||||
ready=False,
|
||||
consensus_count=0,
|
||||
row_count=grid.row_count,
|
||||
column_count=grid.column_count,
|
||||
issues=[issue],
|
||||
)
|
||||
|
||||
|
||||
def _normalized_cell_text(value: Any) -> str:
|
||||
"""以 NFKC、大小写折叠和字母数字/中日韩字符保留生成文本一致性比较键。"""
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
text = unicodedata.normalize('NFKC', str(value or '')).casefold()
|
||||
return re.sub(r'[^0-9a-z\u4e00-\u9fff]+', '', text)
|
||||
@@ -0,0 +1,280 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/order_profile.py
|
||||
|
||||
用途:定义订单文档模板级解析 Profile 纯契约,覆盖全局 Schema 无法表达的模板列语义。
|
||||
依赖:Pydantic、HTML 网格、订单字段规则和既有 TEMP 复合料号规则。
|
||||
逻辑:Profile 只在精确结构指纹命中时按固定列执行注册解析器;行结构已丢失的模板显式阻断,不做相似匹配。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.document_layout.html_table import HtmlGrid, parse_html_grid
|
||||
from app.services.shipping_notice.notice_line_values import parse_number
|
||||
from app.services.shipping_notice.notice_lines import resolve_composite_part_numbers
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
normalize_order_field_value,
|
||||
validate_order_field_value,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import (
|
||||
TableHeaderContract,
|
||||
normalize_table_header,
|
||||
)
|
||||
|
||||
|
||||
ORDER_PROFILE_VERSION = 'shipping_order_document_profile.v1'
|
||||
PROFILE_EXTRACTORS = frozenset({'direct', 'temp_internal_parts'})
|
||||
|
||||
|
||||
class OrderProfileModel(BaseModel):
|
||||
"""为模板 Profile 和执行结果启用严格字段及赋值校验。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid', validate_assignment=True)
|
||||
|
||||
|
||||
class OrderProfileColumnRule(OrderProfileModel):
|
||||
"""定义一个固定来源列使用的注册解析器及目标字段编码。"""
|
||||
|
||||
column_index: int = Field(ge=0)
|
||||
extractor_key: Literal['direct', 'temp_internal_parts']
|
||||
target_field_codes: list[str] = Field(min_length=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_extractor_targets(self) -> 'OrderProfileColumnRule':
|
||||
"""限制注册解析器的固定输出形态,禁止自由脚本或任意字段注入。"""
|
||||
targets = set(self.target_field_codes)
|
||||
if len(targets) != len(self.target_field_codes):
|
||||
raise ValueError('order profile target fields must be unique')
|
||||
if self.extractor_key == 'direct' and len(targets) != 1:
|
||||
raise ValueError('direct order profile extractor requires one target field')
|
||||
if self.extractor_key == 'temp_internal_parts' and targets != {
|
||||
'customer_part_number', 'part_number',
|
||||
}:
|
||||
raise ValueError('TEMP/internal extractor targets are fixed')
|
||||
return self
|
||||
|
||||
|
||||
class OrderDocumentProfile(OrderProfileModel):
|
||||
"""保存不可变模板结构、列覆盖、数据起始行和质量策略。"""
|
||||
|
||||
contract_version: Literal[ORDER_PROFILE_VERSION] = ORDER_PROFILE_VERSION
|
||||
profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
|
||||
version: int = Field(ge=1)
|
||||
structure_fingerprint: str = Field(pattern=r'^[0-9a-f]{64}$')
|
||||
header_row_index: int = Field(ge=0)
|
||||
data_start_row_index: int = Field(ge=1)
|
||||
row_structure: Literal['preserved', 'unsupported_row_structure'] = 'preserved'
|
||||
column_rules: list[OrderProfileColumnRule] = Field(default_factory=list)
|
||||
drop_zero_qty: bool = True
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_profile_rules(self) -> 'OrderDocumentProfile':
|
||||
"""禁止列规则重复;不支持的行结构只能作为识别/路由 Profile,不能配置字段解析。"""
|
||||
columns = [item.column_index for item in self.column_rules]
|
||||
if len(columns) != len(set(columns)):
|
||||
raise ValueError('order profile source columns must be unique')
|
||||
if self.data_start_row_index <= self.header_row_index:
|
||||
raise ValueError('order profile data rows must start after the header')
|
||||
if self.row_structure == 'unsupported_row_structure' and self.column_rules:
|
||||
raise ValueError('unsupported row structure profile cannot expose column mappings')
|
||||
if self.row_structure == 'preserved' and not self.column_rules:
|
||||
raise ValueError('preserved row structure profile requires column mappings')
|
||||
return self
|
||||
|
||||
|
||||
class OrderProfileRowResult(OrderProfileModel):
|
||||
"""保存一条模板行的字段值或删除/复核状态,不包含来源原文。"""
|
||||
|
||||
row_index: int = Field(ge=0)
|
||||
status: Literal['parsed', 'deleted', 'needs_review']
|
||||
fields: dict[str, Any] = Field(default_factory=dict)
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class OrderProfileParseResult(OrderProfileModel):
|
||||
"""汇总 Profile 是否精确命中以及模板行解析结果。"""
|
||||
|
||||
matched: bool
|
||||
profile_code: str | None = None
|
||||
profile_version: int | None = Field(default=None, ge=1)
|
||||
rows: list[OrderProfileRowResult] = Field(default_factory=list)
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
def order_profile_structure_fingerprint(
|
||||
grid: HtmlGrid, *, header_row_index: int,
|
||||
) -> str:
|
||||
"""
|
||||
由表头前缀网格的规范化文字、cell 身份和跨度生成精确结构指纹。
|
||||
|
||||
Args:
|
||||
grid: 已展开的 HTML 网格。
|
||||
header_row_index: 模板最后一行表头索引;数据行和值不进入指纹。
|
||||
Returns:
|
||||
64 位 SHA-256 十六进制指纹。
|
||||
"""
|
||||
if header_row_index < 0 or header_row_index >= grid.row_count:
|
||||
raise ValueError('order profile header row index is invalid')
|
||||
cells = [
|
||||
{
|
||||
'row': cell.row_index,
|
||||
'column': cell.column_index,
|
||||
'row_span': cell.row_span,
|
||||
'column_span': cell.column_span,
|
||||
'text': cell.normalized_text,
|
||||
}
|
||||
for cell in grid.cells
|
||||
if cell.row_index <= header_row_index
|
||||
]
|
||||
payload = {
|
||||
'column_count': grid.column_count,
|
||||
'header_row_index': header_row_index,
|
||||
'cells': cells,
|
||||
}
|
||||
encoded = json.dumps(payload, sort_keys=True, ensure_ascii=True, separators=(',', ':')).encode()
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def parse_html_table_with_order_profile(
|
||||
html: str,
|
||||
*,
|
||||
table_id: str,
|
||||
profile: OrderDocumentProfile,
|
||||
contract: TableHeaderContract,
|
||||
) -> OrderProfileParseResult:
|
||||
"""
|
||||
在结构指纹精确命中时按模板列规则解析订单行。
|
||||
|
||||
Args:
|
||||
html: MinerU 或 EML 提供的单张 HTML table。
|
||||
table_id: 当前文档内稳定表格 ID。
|
||||
profile: Run 锁定的 published 模板 Profile 快照。
|
||||
contract: Run 锁定订单 Schema 表头/字段契约。
|
||||
Returns:
|
||||
未命中时不产生行;不支持行结构时返回阻断问题;命中时逐行解析。
|
||||
"""
|
||||
grid = parse_html_grid(html, table_id=table_id)
|
||||
actual = order_profile_structure_fingerprint(
|
||||
grid,
|
||||
header_row_index=profile.header_row_index,
|
||||
)
|
||||
if actual != profile.structure_fingerprint:
|
||||
return OrderProfileParseResult(matched=False, issues=['order_profile_structure_mismatch'])
|
||||
if profile.row_structure == 'unsupported_row_structure':
|
||||
return OrderProfileParseResult(
|
||||
matched=True,
|
||||
profile_code=profile.profile_code,
|
||||
profile_version=profile.version,
|
||||
issues=['order_profile_row_structure_unsupported'],
|
||||
)
|
||||
if any(rule.column_index >= grid.column_count for rule in profile.column_rules):
|
||||
return OrderProfileParseResult(
|
||||
matched=True,
|
||||
profile_code=profile.profile_code,
|
||||
profile_version=profile.version,
|
||||
issues=['order_profile_column_out_of_range'],
|
||||
)
|
||||
rows = [
|
||||
_parse_profile_row(
|
||||
grid,
|
||||
row_index=index,
|
||||
profile=profile,
|
||||
contract=contract,
|
||||
)
|
||||
for index in range(profile.data_start_row_index, grid.row_count)
|
||||
]
|
||||
return OrderProfileParseResult(
|
||||
matched=True,
|
||||
profile_code=profile.profile_code,
|
||||
profile_version=profile.version,
|
||||
rows=rows,
|
||||
)
|
||||
|
||||
|
||||
def _parse_profile_row(
|
||||
grid: HtmlGrid,
|
||||
*,
|
||||
row_index: int,
|
||||
profile: OrderDocumentProfile,
|
||||
contract: TableHeaderContract,
|
||||
) -> OrderProfileRowResult:
|
||||
"""执行一条 preserved 模板行;零 Qty 删除,非法字段保留机器问题码。"""
|
||||
fields: dict[str, Any] = {}
|
||||
issues: list[str] = []
|
||||
explicit_qty: float | None = None
|
||||
for rule in profile.column_rules:
|
||||
slot = grid.rows[row_index][rule.column_index]
|
||||
raw = slot.text.strip() if slot is not None else ''
|
||||
extracted = (
|
||||
{rule.target_field_codes[0]: raw}
|
||||
if rule.extractor_key == 'direct'
|
||||
else _apply_profile_extractor(rule.extractor_key, raw)
|
||||
)
|
||||
for code in rule.target_field_codes:
|
||||
candidate = extracted.get(code)
|
||||
if candidate in (None, ''):
|
||||
continue
|
||||
if code == 'qty':
|
||||
explicit_qty = parse_number(candidate)
|
||||
config = contract.fields_by_code.get(code)
|
||||
value = _normalize_profile_value(candidate, config)
|
||||
if value is None:
|
||||
issues.append(f'order_profile_field_invalid:{code}')
|
||||
continue
|
||||
fields[code] = value.isoformat() if hasattr(value, 'isoformat') else value
|
||||
if profile.drop_zero_qty and explicit_qty == 0:
|
||||
return OrderProfileRowResult(row_index=row_index, status='deleted')
|
||||
required_build = {'part_number', 'qty'}
|
||||
if not required_build.issubset(fields):
|
||||
issues.append('order_profile_build_fields_missing')
|
||||
return OrderProfileRowResult(
|
||||
row_index=row_index,
|
||||
status='parsed' if not issues else 'needs_review',
|
||||
fields=fields,
|
||||
issues=sorted(set(issues)),
|
||||
)
|
||||
|
||||
|
||||
def _apply_profile_extractor(extractor_key: str, raw: str) -> dict[str, Any]:
|
||||
"""执行代码注册的有限解析器;未知 key 不允许运行。"""
|
||||
if extractor_key == 'temp_internal_parts':
|
||||
resolved = resolve_composite_part_numbers(raw)
|
||||
if resolved:
|
||||
return resolved
|
||||
customer = re.search(r'\b(?:AM)?TEMP-[A-Z0-9._-]+\b', raw, re.IGNORECASE)
|
||||
internal = re.search(r'\bD4-[A-Z0-9._-]+\b', raw, re.IGNORECASE)
|
||||
if customer and internal:
|
||||
return {
|
||||
'customer_part_number': customer.group(0),
|
||||
'part_number': internal.group(0),
|
||||
}
|
||||
return {}
|
||||
raise ValueError('order profile extractor is not registered')
|
||||
|
||||
|
||||
def _normalize_profile_value(raw: Any, config: dict[str, Any] | None) -> Any:
|
||||
"""按冻结 Schema 类型和 validator 规范化模板字段;非法值返回 None。"""
|
||||
if config is None:
|
||||
return None
|
||||
value_type = str(config.get('value_type') or 'string')
|
||||
candidate = raw
|
||||
if value_type in {'decimal', 'integer'}:
|
||||
candidate = parse_number(raw)
|
||||
if candidate is None:
|
||||
return None
|
||||
if value_type == 'integer':
|
||||
if not float(candidate).is_integer():
|
||||
return None
|
||||
candidate = int(candidate)
|
||||
try:
|
||||
value = normalize_order_field_value(candidate, config)
|
||||
return value if value is not None and validate_order_field_value(value, config) else None
|
||||
except (ArithmeticError, TypeError, ValueError, ValidationError):
|
||||
return None
|
||||
@@ -12,11 +12,9 @@ import re
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.po_number import enrich_notice_with_po_number
|
||||
from app.services.shipping_notice.reservation_id import find_reservation_id_in_document
|
||||
from app.services.shipping_notice.notice_lines import (
|
||||
enrich_notice_with_document_currency,
|
||||
enrich_notice_with_document_required_date,
|
||||
enrich_notice_with_document_reservation,
|
||||
adjudicate_notice_lines,
|
||||
normalize_notice_lines,
|
||||
parse_notice_table_text,
|
||||
@@ -29,17 +27,32 @@ def _finalize_notice_parse(
|
||||
*,
|
||||
base_confidence: float,
|
||||
raw_text: str = "",
|
||||
schema_definition: dict[str, Any] | None = None,
|
||||
) -> tuple[dict[str, Any], float, list[str]]:
|
||||
enabled_fields = {
|
||||
str(item.get("field_code") or "").strip()
|
||||
for item in (schema_definition or {}).get("fields", [])
|
||||
if isinstance(item, dict) and item.get("enabled", True)
|
||||
}
|
||||
field_enabled = lambda code: not schema_definition or code in enabled_fields
|
||||
parse_source = parsed.get("parse_source")
|
||||
lines = normalize_notice_lines(parsed.get("lines") if isinstance(parsed.get("lines"), list) else [])
|
||||
parsed = enrich_notice_with_document_reservation({**parsed, "lines": lines}, raw_text=raw_text)
|
||||
parsed = enrich_notice_with_document_required_date(parsed)
|
||||
parsed = enrich_notice_with_document_currency(parsed)
|
||||
parsed = enrich_notice_with_po_number(parsed, raw_text=raw_text)
|
||||
lines = normalize_notice_lines(
|
||||
parsed.get("lines") if isinstance(parsed.get("lines"), list) else [],
|
||||
schema_definition=schema_definition,
|
||||
)
|
||||
parsed = {**parsed, "lines": lines}
|
||||
if field_enabled("required_date"):
|
||||
parsed = enrich_notice_with_document_required_date(parsed)
|
||||
if field_enabled("currency"):
|
||||
parsed = enrich_notice_with_document_currency(parsed)
|
||||
if field_enabled("po_number"):
|
||||
parsed = enrich_notice_with_po_number(parsed, raw_text=raw_text)
|
||||
if parse_source:
|
||||
parsed["parse_source"] = parse_source
|
||||
lines = parsed.get("lines") if isinstance(parsed.get("lines"), list) else []
|
||||
lines, parse_issues, validation_status = adjudicate_notice_lines(lines, raw_text=raw_text)
|
||||
lines, parse_issues, validation_status = adjudicate_notice_lines(
|
||||
lines, raw_text=raw_text, schema_definition=schema_definition,
|
||||
)
|
||||
parsed["lines"] = lines
|
||||
parsed["parse_issues"] = parse_issues
|
||||
parsed["validation_status"] = validation_status
|
||||
@@ -57,6 +70,7 @@ def extract_notice_fields(
|
||||
source_type: str = "manual",
|
||||
structured: dict[str, Any] | None = None,
|
||||
notice_files: list[dict[str, Any]] | None = None,
|
||||
schema_definition: dict[str, Any] | None = None,
|
||||
) -> tuple[dict[str, Any], float, list[str]]:
|
||||
"""
|
||||
抽取发货通知单头与订单行,并计算置信度与 warnings。
|
||||
@@ -71,6 +85,7 @@ def extract_notice_fields(
|
||||
source_type: 来源类型(manual/pdf/email 等)。
|
||||
structured: Dify 编排产出的结构化解析结果(最高优先级)。
|
||||
notice_files: 附件元数据列表(预留)。
|
||||
schema_definition: 预处理明确选择的完整订单 Schema;缺失时不执行确定性表格解析。
|
||||
|
||||
Returns:
|
||||
tuple: (parsed 字典, confidence, warnings 列表)。
|
||||
@@ -83,20 +98,27 @@ def extract_notice_fields(
|
||||
payload,
|
||||
base_confidence=float(structured.get("confidence") or 0.95),
|
||||
raw_text=str(structured.get("raw_text") or raw_text),
|
||||
schema_definition=schema_definition,
|
||||
)
|
||||
warnings.extend(line_warnings)
|
||||
return parsed, confidence, warnings
|
||||
|
||||
warnings.append("parse_fallback_heuristic")
|
||||
heuristic, confidence, heuristic_warnings = _heuristic_extract(raw_text)
|
||||
heuristic, confidence, heuristic_warnings = _heuristic_extract(
|
||||
raw_text, schema_definition=schema_definition,
|
||||
)
|
||||
warnings.extend(heuristic_warnings)
|
||||
heuristic["parse_source"] = "heuristic"
|
||||
parsed, confidence, line_warnings = _finalize_notice_parse(heuristic, base_confidence=confidence, raw_text=raw_text)
|
||||
parsed, confidence, line_warnings = _finalize_notice_parse(
|
||||
heuristic, base_confidence=confidence, raw_text=raw_text, schema_definition=schema_definition,
|
||||
)
|
||||
warnings.extend(line_warnings)
|
||||
return parsed, confidence, warnings
|
||||
|
||||
|
||||
def _heuristic_extract(raw_text: str) -> tuple[dict[str, Any], float, list[str]]:
|
||||
def _heuristic_extract(
|
||||
raw_text: str, *, schema_definition: dict[str, Any] | None = None,
|
||||
) -> tuple[dict[str, Any], float, list[str]]:
|
||||
text = str(raw_text or "").strip()
|
||||
warnings: list[str] = []
|
||||
customer_name = ""
|
||||
@@ -104,13 +126,13 @@ def _heuristic_extract(raw_text: str) -> tuple[dict[str, Any], float, list[str]]
|
||||
if m:
|
||||
customer_name = m.group(1)
|
||||
|
||||
lines = parse_notice_table_text(text)
|
||||
if schema_definition:
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
lines = parse_notice_table_text(text, contract=compile_table_header_contract(schema_definition))
|
||||
else:
|
||||
lines = []
|
||||
if lines:
|
||||
doc_rid = find_reservation_id_in_document(text)
|
||||
if doc_rid:
|
||||
for line in lines:
|
||||
if not line.get("reservation_id"):
|
||||
line["reservation_id"] = doc_rid
|
||||
return (
|
||||
{
|
||||
"customer_name": customer_name,
|
||||
@@ -126,7 +148,7 @@ def _heuristic_extract(raw_text: str) -> tuple[dict[str, Any], float, list[str]]
|
||||
|
||||
lines = []
|
||||
for m in re.finditer(r"([A-Za-z0-9\-_]{3,})\s*[xX×*]\s*(\d+(?:\.\d+)?)", text):
|
||||
lines.append({"part_number": m.group(1), "qty": float(m.group(2)), "uom": "EA"})
|
||||
lines.append({"part_number": m.group(1), "qty": float(m.group(2))})
|
||||
|
||||
# 尝试纯数字 Reservation ID + SKU + Qty 的自由文本模式(如 1000140351 10-40594-001 2)
|
||||
if not lines:
|
||||
@@ -139,7 +161,6 @@ def _heuristic_extract(raw_text: str) -> tuple[dict[str, Any], float, list[str]]
|
||||
"reservation_id": m.group("resv"),
|
||||
"part_number": m.group(2),
|
||||
"qty": float(m.group(3)),
|
||||
"uom": "EA",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ from typing import Any
|
||||
|
||||
from app.models import ShippingNoticeDocument
|
||||
from app.services.shipping_notice.notice_lines import normalize_notice_line, parse_notice_table_text
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
ADJUDICATION_SCHEMA_VERSION = "shipping-field-adjudication-v1"
|
||||
ADJUDICATED_LINE_FIELDS = (
|
||||
@@ -127,11 +128,14 @@ def _make_observation(
|
||||
return {"observation_id": _observation_id(payload), **payload}
|
||||
|
||||
|
||||
def _backend_rows(documents: list[ShippingNoticeDocument]) -> list[dict[str, Any]]:
|
||||
def _backend_rows(
|
||||
documents: list[ShippingNoticeDocument], *, schema_definition: dict[str, Any],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""从每个锁定 Document 的保留列边界文本生成后端表格 Observation 原料。"""
|
||||
contract = compile_table_header_contract(schema_definition)
|
||||
rows: list[dict[str, Any]] = []
|
||||
for document in documents:
|
||||
for row in parse_notice_table_text(str(document.extracted_text or "")):
|
||||
for row in parse_notice_table_text(str(document.extracted_text or ""), contract=contract):
|
||||
if isinstance(row, dict):
|
||||
rows.append({**row, "_document_id": int(document.id)})
|
||||
return rows
|
||||
@@ -323,6 +327,7 @@ def adjudicate_order_fields(
|
||||
*,
|
||||
raw_order: dict[str, Any],
|
||||
documents: list[ShippingNoticeDocument],
|
||||
schema_definition: dict[str, Any],
|
||||
field_confidence: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
@@ -334,12 +339,13 @@ def adjudicate_order_fields(
|
||||
summary: 已去除抽取元数据的 Dify 业务摘要。
|
||||
raw_order: Dify 原始订单对象,保留 evidence 与原始复合值。
|
||||
documents: 当前 Intake 的锁定 Document 集合。
|
||||
schema_definition: 与本次输入一同冻结的完整订单 Schema 定义。
|
||||
field_confidence: Dify 自报字段置信度,仅作弱权重。
|
||||
Returns:
|
||||
包含 canonical summary、不可变 observations、decisions 和 conflicts 的裁决结果。
|
||||
"""
|
||||
raw_lines = summary.get("lines") if isinstance(summary.get("lines"), list) else []
|
||||
backend_rows = _backend_rows(documents)
|
||||
backend_rows = _backend_rows(documents, schema_definition=schema_definition)
|
||||
documents_by_id = {int(item.id): item for item in documents}
|
||||
evidence_items = [item for item in (raw_order.get("evidence") or []) if isinstance(item, dict)]
|
||||
confidence = dict(field_confidence or {})
|
||||
|
||||
@@ -218,10 +218,9 @@ def save_definition(data: dict[str, Any], *, actor_id: int | None, request_id: s
|
||||
'Referenced identity definition binding is immutable',
|
||||
code='SHIPPING.IDENTITY_DEFINITION_CONFLICT',
|
||||
)
|
||||
source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {}
|
||||
automation = 'conditional' if source.get('option_key') in {'from_email', 'from_domain'} and target == 'customer' else 'none'
|
||||
requested_automation = clean_text(data.get('max_automation')).lower() if 'max_automation' in data else automation
|
||||
if requested_automation not in {'none', automation}:
|
||||
# 自动化上限由管理员显式授权,任何字段都不会因来源被默认开启自动确认。
|
||||
requested_automation = clean_text(data.get('max_automation')).lower() if 'max_automation' in data else 'none'
|
||||
if requested_automation not in {'none', 'conditional'}:
|
||||
raise ValidationError('Identity definition automation is invalid', code='SHIPPING.IDENTITY_AUTOMATION_FORBIDDEN')
|
||||
before = _definition_payload(row) if row else None
|
||||
try:
|
||||
@@ -233,7 +232,7 @@ def save_definition(data: dict[str, Any], *, actor_id: int | None, request_id: s
|
||||
row = row or ShippingIdentityDefinition(
|
||||
definition_code=code, display_name=display_name, description=description, evidence_label=evidence_label,
|
||||
target_type=target, context_field_id=field.id,
|
||||
default_weight=weight, max_automation=automation,
|
||||
default_weight=weight, max_automation=requested_automation,
|
||||
created_by_id=actor_id,
|
||||
)
|
||||
row.definition_code = code
|
||||
@@ -243,7 +242,7 @@ def save_definition(data: dict[str, Any], *, actor_id: int | None, request_id: s
|
||||
row.target_type = target
|
||||
row.context_field_id = field.id
|
||||
row.default_weight = weight
|
||||
row.max_automation = automation
|
||||
row.max_automation = requested_automation
|
||||
row.updated_by_id = actor_id
|
||||
if row.id is None:
|
||||
db.session.add(row)
|
||||
|
||||
@@ -17,6 +17,7 @@ def parse_intake_business_summary(
|
||||
*,
|
||||
extracted_text: str,
|
||||
source_type: str = 'manual',
|
||||
schema_definition: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将预解析文本转为可序列化业务摘要。
|
||||
@@ -27,6 +28,7 @@ def parse_intake_business_summary(
|
||||
Args:
|
||||
extracted_text: 文本抽取结果。
|
||||
source_type: 来源类型(pdf/email/manual 等)。
|
||||
schema_definition: 预处理开始时明确选择的订单 Schema 定义。
|
||||
|
||||
Returns:
|
||||
含 customer/po/reservation/lines/confidence/parse_source 的摘要字典。
|
||||
@@ -35,6 +37,7 @@ def parse_intake_business_summary(
|
||||
raw_text=str(extracted_text or ''),
|
||||
source_type=str(source_type or 'manual'),
|
||||
structured=None,
|
||||
schema_definition=schema_definition,
|
||||
)
|
||||
lines = parsed.get('lines') if isinstance(parsed.get('lines'), list) else []
|
||||
reservation_ids: list[str] = []
|
||||
|
||||
@@ -559,6 +559,7 @@ def _run_business_dedup_after_parse(
|
||||
business_summary = parse_intake_business_summary(
|
||||
extracted_text=extracted_text,
|
||||
source_type=source_type,
|
||||
schema_definition={'fields': []},
|
||||
)
|
||||
if candidate_dup_results:
|
||||
dup = aggregate_intake_duplicate_from_candidates(intake, candidate_dup_results)
|
||||
@@ -669,12 +670,17 @@ def run_intake_parse(
|
||||
persist_info: dict[str, Any] = {}
|
||||
uploaded_storage_keys: list[str] = []
|
||||
try:
|
||||
from app.models import ShippingOrderSchemaVersion
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
tech_summary = intake_result_to_structured_summary(result)
|
||||
@@ -700,6 +706,7 @@ def run_intake_parse(
|
||||
rule_hints = parse_intake_business_summary(
|
||||
extracted_text=str(result.text or ''),
|
||||
source_type=str(result.source_type or 'manual'),
|
||||
schema_definition=schema_definition,
|
||||
)
|
||||
structured = dict(locked.structured_result_json or {})
|
||||
structured['rule_hints'] = rule_hints
|
||||
|
||||
@@ -569,9 +569,9 @@ def refresh_intake_duplicate_detection(*, user_id: int, intake_no: str) -> dict[
|
||||
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
business_summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else None
|
||||
if not business_summary:
|
||||
# 旧 Intake 没有冻结 Schema 时不重新猜测表头;正式订单结果只由 Run 锁定版本产生。
|
||||
business_summary = parse_intake_business_summary(
|
||||
extracted_text=str(intake.extracted_text or ''),
|
||||
source_type='manual',
|
||||
extracted_text=str(intake.extracted_text or ''), source_type='manual', schema_definition={'fields': []},
|
||||
)
|
||||
structured = {**structured, 'business_summary': business_summary}
|
||||
intake.structured_result_json = structured
|
||||
|
||||
@@ -214,15 +214,27 @@ def _matches_current_configuration(run: ShippingInventoryConfigurationTestRun, s
|
||||
|
||||
|
||||
def _expire_timed_out_runs(source: ShippingInventorySource) -> None:
|
||||
"""将超出库存 RPA 等待窗口的当前测试标记为失败,避免管理端无限轮询。"""
|
||||
"""按批量队列长度延长等待窗口,避免串行站点被单站超时误判。
|
||||
|
||||
同一 RPA Profile 的批量站点由 Windows Worker 串行执行。每个站点沿用单站
|
||||
等待窗口会让排在后面的站点尚未被领取就超时,因此同组按站点数量线性扩展。
|
||||
"""
|
||||
timeout = max(1, int(current_app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS']))
|
||||
deadline = datetime.utcnow() - timedelta(seconds=timeout)
|
||||
runs = ShippingInventoryConfigurationTestRun.query.filter(
|
||||
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
|
||||
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
|
||||
ShippingInventoryConfigurationTestRun.created_at < deadline,
|
||||
).all()
|
||||
for run in runs:
|
||||
multiplier = 1
|
||||
if run.validation_batch_id:
|
||||
same_worker_queue = ShippingInventoryConfigurationTestRun.query.filter(
|
||||
ShippingInventoryConfigurationTestRun.validation_batch_id == run.validation_batch_id,
|
||||
ShippingInventoryConfigurationTestRun.rpa_batch_run_no == run.rpa_batch_run_no,
|
||||
).count()
|
||||
multiplier = max(1, same_worker_queue)
|
||||
deadline = datetime.utcnow() - timedelta(seconds=timeout * multiplier)
|
||||
if run.created_at >= deadline:
|
||||
continue
|
||||
run.status = 'failed'
|
||||
run.stage = 'failed'
|
||||
run.error_message = '测试导出等待 RPA Worker 超时,请重新测试'
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
services/shipping_notice/notice_line_constants.py
|
||||
|
||||
用途:发货通知订单行的字段名、表头映射与展示标签常量。
|
||||
用途:发货通知订单行的稳定字段名与展示标签常量。
|
||||
依赖:无(纯常量模块)。
|
||||
逻辑:由 notice_line_values / notice_line_table / notice_lines 引用;inventory_snapshot 等模块可单独 import 标签常量。
|
||||
逻辑:业务表头映射由冻结动态 Schema 编译,本文件不再维护字段别名副本。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,125 +26,6 @@ NOTICE_LINE_FIELDS = (
|
||||
"inventory_source_hint",
|
||||
)
|
||||
|
||||
# 订单行表头 → 系统字段(发货通知 PDF/Excel/邮件表格)
|
||||
NOTICE_COLUMN_MAP: dict[str, str] = {
|
||||
# 内部料号
|
||||
"料号": "part_number",
|
||||
"Part Number": "part_number",
|
||||
"产品编号": "part_number",
|
||||
"MPN": "part_number",
|
||||
"Vendor Part Number": "part_number",
|
||||
"Vendor Part No": "part_number",
|
||||
"Vendor PN": "part_number",
|
||||
"Supplier Part No": "part_number",
|
||||
"Supplier Part Number": "part_number",
|
||||
# 外部料号
|
||||
"Customer PN": "customer_part_number",
|
||||
"Customer Part Number": "customer_part_number",
|
||||
"Allocated HHPN": "customer_part_number",
|
||||
"Allocated APN": "aws_part_number",
|
||||
"Material": "aws_part_number",
|
||||
"Material No": "aws_part_number",
|
||||
"AWS Sku": "aws_part_number",
|
||||
"AWS SKU": "aws_part_number",
|
||||
# 项次 / Item
|
||||
"项次": "line_no",
|
||||
"line_no": "line_no",
|
||||
"Line No": "line_no",
|
||||
"Line Number": "line_no",
|
||||
"Line #": "line_no",
|
||||
"Line": "line_no",
|
||||
"Item": "line_no",
|
||||
"Item No": "line_no",
|
||||
"Item Number": "line_no",
|
||||
# 需求数量
|
||||
"数量": "qty",
|
||||
"Qty": "qty",
|
||||
"qty": "qty",
|
||||
"Quantity": "qty",
|
||||
"需求数量": "qty",
|
||||
"订购数量": "qty",
|
||||
"Order Qty": "qty",
|
||||
"Ship Qty": "qty",
|
||||
"发货数量": "qty",
|
||||
"Allocated QTY": "qty",
|
||||
# 单价
|
||||
"单价": "unit_price",
|
||||
"Unit Price": "unit_price",
|
||||
"unit_price": "unit_price",
|
||||
"Price": "unit_price",
|
||||
"Unit Cost": "unit_price",
|
||||
"价格": "unit_price",
|
||||
# 金额
|
||||
"金额": "amount",
|
||||
"Amount": "amount",
|
||||
"amount": "amount",
|
||||
"Total": "amount",
|
||||
"Line Amount": "amount",
|
||||
"Line Total": "amount",
|
||||
"小计": "amount",
|
||||
"总价": "amount",
|
||||
"Total Amount": "amount",
|
||||
# 币种
|
||||
"Currency": "currency",
|
||||
"currency": "currency",
|
||||
"Curr": "currency",
|
||||
"CCY": "currency",
|
||||
"币种": "currency",
|
||||
"币别": "currency",
|
||||
# Reservation ID
|
||||
"Reservation ID": "reservation_id",
|
||||
"Reservation Id": "reservation_id",
|
||||
"reservation_id": "reservation_id",
|
||||
"COM ID": "reservation_id",
|
||||
"Reservation Order": "reservation_id",
|
||||
"Reservation No": "reservation_id",
|
||||
"Resv ID": "reservation_id",
|
||||
"PR Number": "reservation_id",
|
||||
"PR No": "reservation_id",
|
||||
"PR#": "reservation_id",
|
||||
"Reservation N.r": "reservation_id",
|
||||
"Reservation Nr": "reservation_id",
|
||||
"External reservation ID": "reservation_id",
|
||||
"External Reservation ID": "reservation_id",
|
||||
# 交货日期
|
||||
"Required Date": "required_date",
|
||||
"Delivery Date": "required_date",
|
||||
"required_date": "required_date",
|
||||
"ETA": "required_date",
|
||||
"交期": "required_date",
|
||||
"交货日期": "required_date",
|
||||
"要求交期": "required_date",
|
||||
"Required Delivery Date": "required_date",
|
||||
"供应商料号": "part_number",
|
||||
# 邮件批量委托索引字段
|
||||
"PO": "po_number",
|
||||
"PO Number": "po_number",
|
||||
"allocation_id": "allocation_id",
|
||||
"Allocation ID": "allocation_id",
|
||||
"source type": "inventory_source_hint",
|
||||
"Source Type": "inventory_source_hint",
|
||||
"Hub Code": "inventory_source_hint",
|
||||
"Hub": "inventory_source_hint",
|
||||
"HUB": "inventory_source_hint",
|
||||
# 单位
|
||||
"单位": "uom",
|
||||
"UOM": "uom",
|
||||
"uom": "uom",
|
||||
"Unit": "uom",
|
||||
}
|
||||
|
||||
# 这些列可能与 Reservation ID 相邻,但业务语义不同,禁止作为 Reservation ID 来源。
|
||||
RESERVATION_ID_FORBIDDEN_HEADERS = frozenset(
|
||||
{
|
||||
"allocation id",
|
||||
"parent allocation id",
|
||||
"commodity group id",
|
||||
"supplier code",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
NOTICE_FIELD_LABELS = {
|
||||
"line_no": "项次 / Item / Line No",
|
||||
"part_number": "内部料号 / Part Number",
|
||||
@@ -160,23 +41,3 @@ NOTICE_FIELD_LABELS = {
|
||||
"allocation_id": "Allocation ID",
|
||||
"inventory_source_hint": "库存来源提示 / Hub Code",
|
||||
}
|
||||
|
||||
HEADER_SKIP_TOKENS = {
|
||||
"sku",
|
||||
"料号",
|
||||
"aws sku",
|
||||
"qty",
|
||||
"quantity",
|
||||
"数量",
|
||||
"reservation id",
|
||||
"com id",
|
||||
"单价",
|
||||
"unit price",
|
||||
"金额",
|
||||
"amount",
|
||||
"currency",
|
||||
"币种",
|
||||
"line no",
|
||||
"item no",
|
||||
"项次",
|
||||
}
|
||||
@@ -2,35 +2,52 @@
|
||||
services/shipping_notice/notice_line_table.py
|
||||
|
||||
用途:从发货通知表格文本或二维行数据中解析订单行。
|
||||
依赖:notice_line_constants、notice_line_values、reservation_id、inventory_snapshot(懒加载表格拆行)。
|
||||
逻辑:由 extract / notice_lines 调用;输出结构化行供 normalize 与库存匹配链路使用。
|
||||
依赖:notice_line_values、动态 Schema 表头契约、reservation_id、inventory_snapshot(懒加载表格拆行)。
|
||||
逻辑:调用方显式传入冻结契约;歧义表头不静默选列,输出诊断供 Run 进入复核。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.notice_line_constants import HEADER_SKIP_TOKENS
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.notice_line_values import (
|
||||
cell,
|
||||
extract_currency,
|
||||
infer_reservation_id_from_row,
|
||||
map_notice_header,
|
||||
normalize_line_no,
|
||||
normalize_required_date,
|
||||
parse_number,
|
||||
resolve_notice_columns,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_id import (
|
||||
extract_reservation_id,
|
||||
find_reservation_id_in_document,
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
normalize_order_field_value,
|
||||
validate_order_field_value,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import TableHeaderContract
|
||||
|
||||
|
||||
def _normalized_cell(
|
||||
row: list[Any] | tuple[Any, ...], index: int | None, config: dict[str, Any] | None,
|
||||
*, numeric: bool = False,
|
||||
) -> Any:
|
||||
"""按冻结字段规则安全解析单元格;非法单值返回 None,不中断整份文档。"""
|
||||
if index is None or config is None:
|
||||
return None
|
||||
raw = cell(row, index)
|
||||
candidate = parse_number(raw) if numeric else raw
|
||||
if numeric and candidate is None:
|
||||
return None
|
||||
try:
|
||||
value = normalize_order_field_value(candidate, config)
|
||||
return value if value is not None and validate_order_field_value(value, config) else None
|
||||
except (ValidationError, ArithmeticError, TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def parse_notice_row(
|
||||
row: list[Any] | tuple[Any, ...],
|
||||
columns: dict[str, int | None],
|
||||
columns: dict[str, Any],
|
||||
*,
|
||||
contract: TableHeaderContract,
|
||||
default_part_number_index: int | None = None,
|
||||
default_qty_index: int = 1,
|
||||
) -> dict[str, Any] | None:
|
||||
@@ -46,21 +63,24 @@ def parse_notice_row(
|
||||
if idx_part_number is None:
|
||||
return None
|
||||
|
||||
part_number = str(cell(row, idx_part_number) or "").strip()
|
||||
if not part_number or "/" in part_number:
|
||||
part_config = contract.fields_by_code.get('part_number')
|
||||
qty_config = contract.fields_by_code.get('qty')
|
||||
if part_config is None or qty_config is None:
|
||||
return None
|
||||
if part_number.lower() in HEADER_SKIP_TOKENS:
|
||||
part_number = _normalized_cell(row, idx_part_number, part_config)
|
||||
if part_number is None:
|
||||
return None
|
||||
|
||||
idx_qty = columns.get("qty")
|
||||
if idx_qty is not None:
|
||||
qty = parse_number(cell(row, idx_qty))
|
||||
qty_raw = cell(row, idx_qty)
|
||||
else:
|
||||
qty = parse_number(cell(row, default_qty_index))
|
||||
if qty is None or qty <= 0:
|
||||
qty_raw = cell(row, default_qty_index)
|
||||
qty = _normalized_cell(row, idx_qty if idx_qty is not None else default_qty_index, qty_config, numeric=True)
|
||||
if qty is None:
|
||||
return None
|
||||
|
||||
parsed: dict[str, Any] = {"part_number": part_number, "qty": qty, "uom": "EA"}
|
||||
parsed: dict[str, Any] = {"part_number": str(part_number), "qty": float(qty)}
|
||||
|
||||
skip_indices: set[int] = {idx_part_number}
|
||||
if idx_qty is not None:
|
||||
@@ -68,15 +88,18 @@ def parse_notice_row(
|
||||
|
||||
idx_line_no = columns.get("line_no")
|
||||
if idx_line_no is not None:
|
||||
line_no = normalize_line_no(cell(row, idx_line_no))
|
||||
config = contract.fields_by_code.get('line_no')
|
||||
line_no = _normalized_cell(row, idx_line_no, config)
|
||||
skip_indices.add(idx_line_no)
|
||||
if line_no:
|
||||
parsed["line_no"] = line_no
|
||||
if line_no is not None:
|
||||
parsed["line_no"] = str(line_no)
|
||||
|
||||
idx_res = columns.get("reservation_id")
|
||||
reservation_id = ""
|
||||
if idx_res is not None:
|
||||
reservation_id = extract_reservation_id(cell(row, idx_res))
|
||||
config = contract.fields_by_code.get('reservation_id')
|
||||
value = _normalized_cell(row, idx_res, config)
|
||||
reservation_id = str(value or '')
|
||||
skip_indices.add(idx_res)
|
||||
if reservation_id:
|
||||
parsed["reservation_id_evidence"] = {
|
||||
@@ -84,8 +107,6 @@ def parse_notice_row(
|
||||
"source_index": idx_res,
|
||||
"raw_value": str(cell(row, idx_res) or "").strip(),
|
||||
}
|
||||
else:
|
||||
reservation_id = infer_reservation_id_from_row(row, skip_indices=skip_indices)
|
||||
if reservation_id:
|
||||
parsed["reservation_id"] = reservation_id
|
||||
|
||||
@@ -93,63 +114,55 @@ def parse_notice_row(
|
||||
price_cell = None
|
||||
if idx_price is not None:
|
||||
price_cell = cell(row, idx_price)
|
||||
unit_price = parse_number(price_cell)
|
||||
if unit_price is not None:
|
||||
parsed["unit_price"] = unit_price
|
||||
config = contract.fields_by_code.get('unit_price')
|
||||
value = _normalized_cell(row, idx_price, config, numeric=True)
|
||||
if value is not None:
|
||||
parsed["unit_price"] = float(value)
|
||||
|
||||
idx_amount = columns.get("amount")
|
||||
amount_cell = None
|
||||
if idx_amount is not None:
|
||||
amount_cell = cell(row, idx_amount)
|
||||
amount = parse_number(amount_cell)
|
||||
if amount is not None:
|
||||
parsed["amount"] = amount
|
||||
config = contract.fields_by_code.get('amount')
|
||||
value = _normalized_cell(row, idx_amount, config, numeric=True)
|
||||
if value is not None:
|
||||
parsed["amount"] = float(value)
|
||||
|
||||
idx_currency = columns.get("currency")
|
||||
currency = extract_currency(
|
||||
cell(row, idx_currency) if idx_currency is not None else None,
|
||||
price_cell,
|
||||
amount_cell,
|
||||
)
|
||||
if currency:
|
||||
parsed["currency"] = currency
|
||||
|
||||
idx_uom = columns.get("uom")
|
||||
if idx_uom is not None:
|
||||
uom = str(cell(row, idx_uom) or "").strip()
|
||||
if uom:
|
||||
parsed["uom"] = uom
|
||||
|
||||
idx_required_date = columns.get("required_date")
|
||||
if idx_required_date is not None:
|
||||
required_date = normalize_required_date(cell(row, idx_required_date))
|
||||
if required_date:
|
||||
parsed["required_date"] = required_date
|
||||
|
||||
for field in ("po_number", "allocation_id", "inventory_source_hint", "customer_part_number", "aws_part_number"):
|
||||
for field in (
|
||||
'currency', 'uom', 'required_date', 'po_number', 'inventory_source_hint',
|
||||
'customer_part_number', 'aws_part_number',
|
||||
):
|
||||
idx = columns.get(field)
|
||||
if idx is None:
|
||||
continue
|
||||
value = str(cell(row, idx) or "").strip()
|
||||
if value:
|
||||
parsed[field] = value
|
||||
config = contract.fields_by_code.get(field)
|
||||
value = _normalized_cell(row, idx, config)
|
||||
if value is not None:
|
||||
parsed[field] = value.isoformat() if hasattr(value, 'isoformat') else str(value)
|
||||
|
||||
if "amount" not in parsed and "unit_price" in parsed:
|
||||
computed = round(parsed["unit_price"] * qty, 4)
|
||||
if computed > 0:
|
||||
parsed["amount"] = computed
|
||||
if 'currency' not in parsed and contract.fields_by_code.get('currency') is not None:
|
||||
currency = extract_currency(price_cell, amount_cell)
|
||||
if currency:
|
||||
parsed['currency'] = currency
|
||||
|
||||
amount_config = contract.fields_by_code.get('amount')
|
||||
if amount_config is not None and "amount" not in parsed and "unit_price" in parsed:
|
||||
computed = round(parsed["unit_price"] * float(qty), 4)
|
||||
normalized = _normalized_cell([computed], 0, amount_config, numeric=True)
|
||||
if normalized is not None:
|
||||
parsed["amount"] = float(normalized)
|
||||
|
||||
return parsed
|
||||
|
||||
|
||||
def score_notice_header_row(cells: list[Any]) -> int:
|
||||
def score_notice_header_row(cells: list[Any], contract: TableHeaderContract | None) -> int:
|
||||
"""为候选表头行打分:映射字段越多、含 part_number+qty 组合时分越高。"""
|
||||
headers = [str(c or "").strip() for c in cells]
|
||||
if len([h for h in headers if h]) < 2:
|
||||
return 0
|
||||
mapped: set[str] = set()
|
||||
for h in headers:
|
||||
field = map_notice_header(h)
|
||||
field = map_notice_header(h, contract)
|
||||
if field:
|
||||
mapped.add(field)
|
||||
score = len(mapped) * 10
|
||||
@@ -162,31 +175,39 @@ def score_notice_header_row(cells: list[Any]) -> int:
|
||||
return score
|
||||
|
||||
|
||||
def find_notice_header_row_index(rows: list[list[Any]], *, max_scan: int = 40) -> int:
|
||||
def find_notice_header_row_index(
|
||||
rows: list[list[Any]], *, contract: TableHeaderContract | None, max_scan: int = 40,
|
||||
) -> int:
|
||||
"""在前 max_scan 行中选取得分最高的表头行索引;无有效表头时返回 0。"""
|
||||
best_idx = 0
|
||||
best_score = 0
|
||||
for i, row in enumerate(rows[:max_scan]):
|
||||
score = score_notice_header_row(list(row))
|
||||
score = score_notice_header_row(list(row), contract)
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best_idx = i
|
||||
return best_idx if best_score > 0 else 0
|
||||
|
||||
|
||||
def parse_notice_table_rows(headers: list[str], data_rows: list[list[Any]]) -> list[dict[str, Any]]:
|
||||
def parse_notice_table_rows(
|
||||
headers: list[str], data_rows: list[list[Any]], *, contract: TableHeaderContract | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
按表头定义解析发货通知表格数据行。
|
||||
|
||||
核心逻辑:根据 headers 推断列映射,仅在识别到有效表头时逐行提取内部料号、数量、金额等字段。
|
||||
"""
|
||||
columns = resolve_notice_columns(headers)
|
||||
if contract is None:
|
||||
return []
|
||||
columns = resolve_notice_columns(headers, contract)
|
||||
if columns.get('_ambiguous_fields'):
|
||||
return []
|
||||
idx_res = columns.get("reservation_id")
|
||||
if idx_res is not None and idx_res < len(headers):
|
||||
columns["_reservation_id_header"] = str(headers[idx_res] or "").strip()
|
||||
has_header = columns.get("part_number") is not None or columns.get("qty") is not None
|
||||
if not has_header and headers:
|
||||
has_header = any(map_notice_header(h) for h in headers)
|
||||
has_header = any(map_notice_header(h, contract) for h in headers)
|
||||
if not has_header:
|
||||
return []
|
||||
|
||||
@@ -194,35 +215,52 @@ def parse_notice_table_rows(headers: list[str], data_rows: list[list[Any]]) -> l
|
||||
for row in data_rows:
|
||||
if not row:
|
||||
continue
|
||||
parsed = parse_notice_row(list(row), columns)
|
||||
parsed = parse_notice_row(list(row), columns, contract=contract)
|
||||
if parsed:
|
||||
lines.append(parsed)
|
||||
return lines
|
||||
|
||||
|
||||
def parse_notice_table_text(raw_text: str) -> list[dict[str, Any]]:
|
||||
def inspect_notice_table_text(
|
||||
raw_text: str, *, contract: TableHeaderContract | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
解析表格并返回表头诊断,供 Run 将歧义配置或重复列转入人工复核。
|
||||
|
||||
Args:
|
||||
raw_text: 保留 TSV/表格边界的文档文本。
|
||||
contract: Run 冻结 Schema 编译结果;缺失时不猜测。
|
||||
Returns:
|
||||
`lines`、`header_found`、`ambiguous_fields` 和表头索引。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text
|
||||
|
||||
text = str(raw_text or '').strip()
|
||||
if not text or contract is None:
|
||||
return {'lines': [], 'header_found': False, 'ambiguous_fields': [], 'header_index': None}
|
||||
rows = _rows_from_table_text(text)
|
||||
if not rows:
|
||||
return {'lines': [], 'header_found': False, 'ambiguous_fields': [], 'header_index': None}
|
||||
header_idx = find_notice_header_row_index(rows, contract=contract)
|
||||
header = [str(c or '').strip() for c in rows[header_idx]]
|
||||
columns = resolve_notice_columns(header, contract)
|
||||
ambiguous = list(columns.get('_ambiguous_fields') or [])
|
||||
header_found = any(map_notice_header(item, contract) for item in header)
|
||||
lines = [] if ambiguous else parse_notice_table_rows(header, rows[header_idx + 1:], contract=contract)
|
||||
return {
|
||||
'lines': lines,
|
||||
'header_found': header_found,
|
||||
'ambiguous_fields': ambiguous,
|
||||
'header_index': header_idx if header_found else None,
|
||||
}
|
||||
|
||||
|
||||
def parse_notice_table_text(
|
||||
raw_text: str, *, contract: TableHeaderContract | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
从发货通知原始文本中的表格片段解析订单行。
|
||||
|
||||
核心逻辑:先借助 inventory_snapshot 的通用表格拆行工具得到二维表,再识别表头并解析数据行。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text
|
||||
|
||||
text = str(raw_text or "").strip()
|
||||
if not text:
|
||||
return []
|
||||
|
||||
rows = _rows_from_table_text(text)
|
||||
if not rows:
|
||||
return []
|
||||
|
||||
header_idx = find_notice_header_row_index(rows)
|
||||
header = [str(c or "").strip() for c in rows[header_idx]]
|
||||
data_rows = rows[header_idx + 1 :]
|
||||
lines = parse_notice_table_rows(header, data_rows)
|
||||
doc_rid = find_reservation_id_in_document(text)
|
||||
if doc_rid:
|
||||
for line in lines:
|
||||
if not line.get("reservation_id"):
|
||||
line["reservation_id"] = doc_rid
|
||||
return lines
|
||||
return list(inspect_notice_table_text(raw_text, contract=contract)['lines'])
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
services/shipping_notice/notice_line_values.py
|
||||
|
||||
用途:订单行单字段值的解析、归一化与表头列映射推断。
|
||||
依赖:notice_line_constants、reservation_id。
|
||||
逻辑:由 notice_line_table 解析表格行、notice_lines 标准化 dict 行时调用;不直接暴露给上游业务模块。
|
||||
用途:订单行基础值解析与冻结 Schema 表头列映射。
|
||||
依赖:notice_line_constants、order_schema.table_contract、reservation_id。
|
||||
逻辑:表头只消费调用方传入的冻结契约;无契约时不进行确定性字段猜测。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,15 +11,10 @@ from __future__ import annotations
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.notice_line_constants import (
|
||||
HEADER_SKIP_TOKENS,
|
||||
NOTICE_COLUMN_MAP,
|
||||
NOTICE_LINE_FIELDS,
|
||||
RESERVATION_ID_FORBIDDEN_HEADERS,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_id import (
|
||||
extract_reservation_id,
|
||||
looks_like_reservation_id,
|
||||
from app.services.shipping_notice.notice_line_constants import NOTICE_LINE_FIELDS
|
||||
from app.services.shipping_notice.order_schema.table_contract import (
|
||||
TableHeaderContract,
|
||||
normalize_table_header,
|
||||
)
|
||||
|
||||
_KNOWN_CURRENCY_CODES = frozenset(
|
||||
@@ -68,51 +63,43 @@ _CURRENCY_ALIASES = {
|
||||
|
||||
|
||||
def norm_header(value: Any) -> str:
|
||||
"""将表头单元格归一化为小写、单空格分隔的字符串,便于别名匹配。"""
|
||||
return re.sub(r"\s+", " ", str(value or "").strip().lower())
|
||||
"""复用动态 Schema 的表头标准化规则,避免保存校验与运行匹配漂移。"""
|
||||
return normalize_table_header(value)
|
||||
|
||||
|
||||
def map_notice_header(header: str, col_map: dict[str, str] | None = None) -> str | None:
|
||||
def map_notice_header(header: str, contract: TableHeaderContract | None) -> str | None:
|
||||
"""
|
||||
将原始表头文本映射为系统字段名。
|
||||
|
||||
核心逻辑:先精确匹配 NOTICE_COLUMN_MAP,再按 norm_header 做大小写/空格无关匹配。
|
||||
核心逻辑:只按冻结 Schema 已编译的标准化映射匹配;无契约时不猜测。
|
||||
"""
|
||||
text = str(header or "").strip()
|
||||
if not text:
|
||||
if contract is None:
|
||||
return None
|
||||
mapping = col_map or NOTICE_COLUMN_MAP
|
||||
if text in mapping:
|
||||
return mapping[text]
|
||||
norm = norm_header(text)
|
||||
for key, field in mapping.items():
|
||||
if norm_header(key) == norm:
|
||||
return field
|
||||
return None
|
||||
return contract.header_to_field.get(norm_header(header))
|
||||
|
||||
|
||||
def resolve_notice_columns(headers: list[str]) -> dict[str, int | None]:
|
||||
def resolve_notice_columns(
|
||||
headers: list[str], contract: TableHeaderContract | None,
|
||||
) -> dict[str, int | list[str] | None]:
|
||||
"""
|
||||
根据表头行推断各系统字段对应的列索引。
|
||||
|
||||
核心逻辑:逐列 map_notice_header;Reservation 列名未命中时使用常见别名兜底。
|
||||
核心逻辑:逐列匹配冻结契约;同一字段命中多个列时记录歧义并清空该映射。
|
||||
"""
|
||||
columns: dict[str, int | None] = {
|
||||
columns: dict[str, int | list[str] | None] = {
|
||||
field: None for field in NOTICE_LINE_FIELDS if field not in {"uom", "remark"}
|
||||
}
|
||||
ambiguous: set[str] = set()
|
||||
for i, header in enumerate(headers):
|
||||
mapped = map_notice_header(header)
|
||||
if mapped and columns.get(mapped) is None:
|
||||
mapped = map_notice_header(header, contract)
|
||||
if not mapped:
|
||||
continue
|
||||
if columns.get(mapped) is None:
|
||||
columns[mapped] = i
|
||||
|
||||
if columns.get("reservation_id") is None:
|
||||
for i, header in enumerate(headers):
|
||||
norm = norm_header(header)
|
||||
if norm in RESERVATION_ID_FORBIDDEN_HEADERS:
|
||||
continue
|
||||
if norm in {"com id", "reservation order", "reservation id", "reservation no", "resv id"}:
|
||||
columns["reservation_id"] = i
|
||||
break
|
||||
else:
|
||||
columns[mapped] = None
|
||||
ambiguous.add(mapped)
|
||||
columns['_ambiguous_fields'] = sorted(ambiguous)
|
||||
return columns
|
||||
|
||||
|
||||
@@ -132,8 +119,6 @@ def normalize_line_no(value: Any) -> str:
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return ""
|
||||
if text.lower() in HEADER_SKIP_TOKENS:
|
||||
return ""
|
||||
num = parse_number(text)
|
||||
if num is not None and num == int(num):
|
||||
compact = text.replace(",", "").replace(",", "")
|
||||
@@ -207,17 +192,3 @@ def parse_number(value: Any) -> float | None:
|
||||
return float(match.group(0))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def infer_reservation_id_from_row(
|
||||
row: list[Any] | tuple[Any, ...],
|
||||
*,
|
||||
skip_indices: set[int],
|
||||
) -> str:
|
||||
"""在未映射 Reservation 列时,从行内其余单元格推断 Reservation ID。"""
|
||||
for i, cell_value in enumerate(row):
|
||||
if i in skip_indices:
|
||||
continue
|
||||
if looks_like_reservation_id(cell_value):
|
||||
return extract_reservation_id(cell_value)
|
||||
return ""
|
||||
@@ -10,12 +10,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.notice_line_constants import (
|
||||
HEADER_SKIP_TOKENS,
|
||||
NOTICE_COLUMN_MAP,
|
||||
NOTICE_FIELD_LABELS,
|
||||
NOTICE_LINE_FIELDS,
|
||||
)
|
||||
from app.services.shipping_notice.notice_line_constants import NOTICE_FIELD_LABELS, NOTICE_LINE_FIELDS
|
||||
from app.services.shipping_notice.notice_line_table import (
|
||||
parse_notice_table_rows,
|
||||
parse_notice_table_text,
|
||||
@@ -37,8 +32,7 @@ from app.services.shipping_notice.reservation_id import (
|
||||
validated_reservation_id,
|
||||
)
|
||||
|
||||
# 向后兼容:旧代码/tests 仍可从 notice_lines 引用私有别名
|
||||
_HEADER_SKIP_TOKENS = HEADER_SKIP_TOKENS
|
||||
# 仅保留无业务配置的值工具私有别名;表头业务别名不再从本模块导出。
|
||||
_extract_currency = extract_currency
|
||||
_norm_header = norm_header
|
||||
_map_notice_header = map_notice_header
|
||||
@@ -109,13 +103,18 @@ def non_atomic_part_number_field(raw: dict[str, Any] | None) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
def normalize_notice_line(
|
||||
raw: dict[str, Any] | None,
|
||||
*,
|
||||
schema_definition: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
标准化单条发货通知订单行。
|
||||
|
||||
核心逻辑:校验原子 part_number 与数量必填项,统一币种、交期和 Reservation ID,并在缺少 amount 时按单价回填。
|
||||
Args:
|
||||
raw: 原始订单行字典,可包含多种字段别名。
|
||||
schema_definition: 冻结 Schema;提供时仅保留其中已启用的字段,且不注入默认 UOM。
|
||||
|
||||
Returns:
|
||||
dict[str, Any] | None: 归一化后的订单行;若缺少关键字段则返回 None。
|
||||
@@ -135,11 +134,16 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
if qty is None or qty <= 0:
|
||||
return None
|
||||
|
||||
line: dict[str, Any] = {
|
||||
"part_number": part_number,
|
||||
"qty": qty,
|
||||
"uom": str(raw.get("uom") or "EA").strip() or "EA",
|
||||
enabled_fields = {
|
||||
str(item.get("field_code") or "").strip()
|
||||
for item in (schema_definition or {}).get("fields", [])
|
||||
if isinstance(item, dict) and item.get("enabled", True)
|
||||
}
|
||||
field_enabled = lambda code: not schema_definition or code in enabled_fields
|
||||
line: dict[str, Any] = {"part_number": part_number, "qty": qty}
|
||||
raw_uom = str(raw.get("uom") or "").strip()
|
||||
if raw_uom and field_enabled("uom"):
|
||||
line["uom"] = raw_uom
|
||||
|
||||
line_no = normalize_line_no(
|
||||
raw.get("line_no")
|
||||
@@ -150,7 +154,7 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
or raw.get("Item")
|
||||
or raw.get("Item No")
|
||||
)
|
||||
if line_no:
|
||||
if line_no and field_enabled("line_no"):
|
||||
line["line_no"] = line_no
|
||||
|
||||
reservation_id = extract_reservation_id(
|
||||
@@ -162,20 +166,20 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
or raw.get("prNumber")
|
||||
or raw.get("PR Number")
|
||||
)
|
||||
if reservation_id:
|
||||
if reservation_id and field_enabled("reservation_id"):
|
||||
line["reservation_id"] = reservation_id
|
||||
evidence = raw.get("reservation_id_evidence")
|
||||
if isinstance(evidence, dict):
|
||||
if isinstance(evidence, dict) and field_enabled("reservation_id"):
|
||||
line["reservation_id_evidence"] = dict(evidence)
|
||||
|
||||
unit_price = parse_number(raw.get("unit_price") if raw.get("unit_price") is not None else raw.get("price"))
|
||||
if unit_price is not None:
|
||||
if unit_price is not None and field_enabled("unit_price"):
|
||||
line["unit_price"] = unit_price
|
||||
|
||||
amount = parse_number(raw.get("amount") if raw.get("amount") is not None else raw.get("total"))
|
||||
if amount is not None:
|
||||
if amount is not None and field_enabled("amount"):
|
||||
line["amount"] = amount
|
||||
elif unit_price is not None:
|
||||
elif unit_price is not None and field_enabled("amount"):
|
||||
line["amount"] = round(unit_price * qty, 4)
|
||||
|
||||
currency = normalize_currency(raw.get("currency") or raw.get("Currency"))
|
||||
@@ -186,7 +190,7 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
raw.get("amount"),
|
||||
raw.get("total"),
|
||||
)
|
||||
if currency:
|
||||
if currency and field_enabled("currency"):
|
||||
line["currency"] = currency
|
||||
|
||||
required_date = normalize_required_date(
|
||||
@@ -196,7 +200,7 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
or raw.get("eta")
|
||||
or raw.get("ETA")
|
||||
)
|
||||
if required_date:
|
||||
if required_date and field_enabled("required_date"):
|
||||
line["required_date"] = required_date
|
||||
|
||||
optional_aliases = {
|
||||
@@ -213,20 +217,25 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
"aws_part_number": ("aws_part_number", "AWS Sku", "AWS SKU"),
|
||||
}
|
||||
if composite.get('customer_part_number'):
|
||||
line['customer_part_number'] = composite['customer_part_number']
|
||||
if field_enabled('customer_part_number'):
|
||||
line['customer_part_number'] = composite['customer_part_number']
|
||||
for field, aliases in optional_aliases.items():
|
||||
value = next((str(raw.get(alias) or "").strip() for alias in aliases if raw.get(alias)), "")
|
||||
if value:
|
||||
if value and field_enabled(field):
|
||||
line[field] = value
|
||||
|
||||
remark = str(raw.get("remark") or raw.get("note") or "").strip()
|
||||
if remark:
|
||||
if remark and field_enabled("remark"):
|
||||
line["remark"] = remark
|
||||
|
||||
return line
|
||||
|
||||
|
||||
def normalize_notice_lines(lines: list[Any] | None) -> list[dict[str, Any]]:
|
||||
def normalize_notice_lines(
|
||||
lines: list[Any] | None,
|
||||
*,
|
||||
schema_definition: dict[str, Any] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
批量标准化订单行列表。
|
||||
|
||||
@@ -236,7 +245,10 @@ def normalize_notice_lines(lines: list[Any] | None) -> list[dict[str, Any]]:
|
||||
return []
|
||||
normalized: list[dict[str, Any]] = []
|
||||
for item in lines:
|
||||
parsed = normalize_notice_line(item if isinstance(item, dict) else None)
|
||||
parsed = normalize_notice_line(
|
||||
item if isinstance(item, dict) else None,
|
||||
schema_definition=schema_definition,
|
||||
)
|
||||
if parsed:
|
||||
normalized.append(parsed)
|
||||
return normalized
|
||||
@@ -246,6 +258,7 @@ def adjudicate_notice_lines(
|
||||
lines: list[dict[str, Any]],
|
||||
*,
|
||||
raw_text: str = "",
|
||||
schema_definition: dict[str, Any] | None = None,
|
||||
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], str]:
|
||||
"""
|
||||
对 LLM 候选订单行执行后端真值裁决,并输出可审计问题清单。
|
||||
@@ -255,11 +268,19 @@ def adjudicate_notice_lines(
|
||||
Args:
|
||||
lines: 已完成基础标准化的 LLM/启发式候选行。
|
||||
raw_text: 原始通知正文;仅 TSV/HTML 保留下来的明确列关系可作为自动纠错证据。
|
||||
schema_definition: 本次处理明确选择的完整订单 Schema;缺失时不生成表格纠错证据。
|
||||
|
||||
Returns:
|
||||
tuple: (裁决后的业务行、parse_issues、validation_status)。
|
||||
"""
|
||||
evidence_lines = parse_notice_table_text(raw_text) if "\t" in str(raw_text or "") else []
|
||||
if schema_definition and "\t" in str(raw_text or ""):
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
evidence_lines = parse_notice_table_text(
|
||||
raw_text, contract=compile_table_header_contract(schema_definition),
|
||||
)
|
||||
else:
|
||||
evidence_lines = []
|
||||
evidence_by_part_number: dict[str, list[dict[str, Any]]] = {}
|
||||
for evidence_line in evidence_lines:
|
||||
part_number = str(evidence_line.get("part_number") or "").strip()
|
||||
@@ -498,7 +519,6 @@ def notice_parse_completeness(lines: list[dict[str, Any]]) -> float:
|
||||
|
||||
|
||||
__all__ = [
|
||||
"NOTICE_COLUMN_MAP",
|
||||
"NOTICE_FIELD_LABELS",
|
||||
"NOTICE_LINE_FIELDS",
|
||||
"enrich_notice_with_document_currency",
|
||||
|
||||
@@ -13,6 +13,7 @@ from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.notice_line_table import parse_notice_table_text
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
from app.services.shipping_notice.po_number import normalize_po_number
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
@@ -32,17 +33,19 @@ def _comparable_value(field: str, value: Any) -> str:
|
||||
return str(value or "").strip().upper()
|
||||
|
||||
|
||||
def build_email_order_index(body_text: str) -> list[dict[str, Any]]:
|
||||
def build_email_order_index(body_text: str, *, schema_definition: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
从邮件正文表格提取订单索引行。
|
||||
|
||||
核心逻辑:复用统一订单表格解析器,并只保留具备 PO 或 Reservation 的有效订单行。
|
||||
Args:
|
||||
body_text: 邮件正文纯文本。
|
||||
schema_definition: 本次预处理明确选择的订单 Schema 定义。
|
||||
Returns:
|
||||
正文订单索引列表。
|
||||
"""
|
||||
rows = parse_notice_table_text(str(body_text or ""))
|
||||
contract = compile_table_header_contract(schema_definition)
|
||||
rows = parse_notice_table_text(str(body_text or ""), contract=contract)
|
||||
return [
|
||||
row for row in rows
|
||||
if normalize_po_number(row.get("po_number"))
|
||||
|
||||
@@ -184,6 +184,7 @@ def persist_order_extraction_result(
|
||||
schema_version_id: int,
|
||||
extraction_source: str = 'dify_workflow',
|
||||
frozen_context_by_intake: dict[int, dict[str, Any]] | None = None,
|
||||
auto_create_enabled: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
持久化后台订单抽取 Run 的结构化结果,并执行后端裁决、判重与自动建单。
|
||||
@@ -199,6 +200,7 @@ def persist_order_extraction_result(
|
||||
schema_version_id: Run 冻结的 published Schema 版本。
|
||||
extraction_source: 固定为后台 Workflow 来源,不接受用户输入。
|
||||
frozen_context_by_intake: Run 按 Intake 冻结的确定性上下文;后台 Run 必须提供。
|
||||
auto_create_enabled: 冻结发布门禁;关闭时只落 Candidate,不自动创建/打开 Task。
|
||||
Returns:
|
||||
自动创建/打开的任务、待处理订单及缺失流程字段摘要。
|
||||
"""
|
||||
@@ -451,9 +453,12 @@ def persist_order_extraction_result(
|
||||
refresh_candidate_shadow_resolution_safely(candidate)
|
||||
document_candidate_keys[int(document.id)].append(candidate_key)
|
||||
document_has_pending[int(document.id)] = document_has_pending[int(document.id)] or bool(reasons)
|
||||
if candidate.selected and candidate.validation_status == 'ready':
|
||||
if candidate.selected and candidate.validation_status == 'ready' and auto_create_enabled:
|
||||
auto_candidates.append(candidate)
|
||||
else:
|
||||
if candidate.validation_status == 'ready' and not auto_create_enabled:
|
||||
candidate.selected = False
|
||||
reasons.append('auto_create_disabled')
|
||||
pending_item = {
|
||||
'candidate_no': candidate.candidate_no,
|
||||
'order_index': index,
|
||||
@@ -767,4 +772,5 @@ def submit_order_extraction_run_result(
|
||||
schema_version_id=int(run.schema_version_id),
|
||||
extraction_source='dify_workflow',
|
||||
frozen_context_by_intake=frozen_context_by_intake,
|
||||
auto_create_enabled=bool((run.provider_config_json or {}).get('auto_create_enabled', False)),
|
||||
)
|
||||
@@ -77,6 +77,7 @@ def adjudicate_order_reservations(
|
||||
summary: dict[str, Any],
|
||||
*,
|
||||
documents: list[ShippingNoticeDocument],
|
||||
schema_definition: dict[str, Any],
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
"""
|
||||
用当前 Intake 的保留列边界文本裁决 Candidate Reservation ID。
|
||||
@@ -87,6 +88,7 @@ def adjudicate_order_reservations(
|
||||
Args:
|
||||
summary: 已完成基础字段标准化的 Candidate 摘要。
|
||||
documents: 当前订单所属 Intake 的全部 Document。
|
||||
schema_definition: Run 锁定的完整 Schema 定义。
|
||||
|
||||
Returns:
|
||||
裁决后的摘要副本,以及需写入 Candidate conflicts 的来源冲突列表。
|
||||
@@ -98,7 +100,9 @@ def adjudicate_order_reservations(
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
raw_text = "\n".join(str(item.extracted_text or "") for item in documents)
|
||||
adjudicated, issues, _status = adjudicate_notice_lines(lines, raw_text=raw_text)
|
||||
adjudicated, issues, _status = adjudicate_notice_lines(
|
||||
lines, raw_text=raw_text, schema_definition=schema_definition,
|
||||
)
|
||||
result["lines"] = adjudicated
|
||||
result["reservation_ids"] = sorted(
|
||||
{
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
"""
|
||||
services/shipping_notice/order_extraction_merge.py
|
||||
|
||||
用途:在 HXOPS 内按稳定业务身份合并文档单元订单,并保留全部字段证据供后续裁决。
|
||||
依赖:Run 冻结动态 Schema field_id/field_code 映射。
|
||||
逻辑:同 Intake 下仅 PO 一致或 Line 的 part_number+reservation_id 一致时合并;不可靠身份保持拆分。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _field_values(fields: Any, field_code: str, codes: dict[str, str]) -> set[str]:
|
||||
"""读取某稳定字段的非空 Observation 值,供身份和冲突比较。"""
|
||||
values: set[str] = set()
|
||||
for field in fields if isinstance(fields, list) else []:
|
||||
if not isinstance(field, dict) or codes.get(str(field.get('field_id') or '')) != field_code:
|
||||
continue
|
||||
for item in field.get('observations') or []:
|
||||
value = str(item.get('value') or '').strip().upper() if isinstance(item, dict) else ''
|
||||
if value:
|
||||
values.add(value)
|
||||
return values
|
||||
|
||||
|
||||
def _line_identity(line: dict[str, Any], codes: dict[str, str]) -> tuple[str, str] | None:
|
||||
"""只有内部料号和 Reservation ID 都唯一时才形成安全行身份。"""
|
||||
part_numbers = _field_values(line.get('fields'), 'part_number', codes)
|
||||
reservations = _field_values(line.get('fields'), 'reservation_id', codes)
|
||||
if len(part_numbers) == 1 and len(reservations) == 1:
|
||||
return next(iter(part_numbers)), next(iter(reservations))
|
||||
return None
|
||||
|
||||
|
||||
def _order_identity(order: dict[str, Any], codes: dict[str, str]) -> tuple[set[str], set[tuple[str, str]]]:
|
||||
"""返回可用于保守合并的 PO 集合和强行身份集合。"""
|
||||
po_numbers = _field_values(order.get('header_fields'), 'po_number', codes)
|
||||
line_keys = {
|
||||
identity for line in order.get('lines') or []
|
||||
if isinstance(line, dict) and (identity := _line_identity(line, codes)) is not None
|
||||
}
|
||||
return po_numbers, line_keys
|
||||
|
||||
|
||||
def _merge_fields(target: list[dict[str, Any]], incoming: Any) -> None:
|
||||
"""按 field_id 合并 Observation;不选择值,让动态 Schema 裁决冲突。"""
|
||||
by_id = {str(item.get('field_id') or ''): item for item in target if isinstance(item, dict)}
|
||||
for raw in incoming if isinstance(incoming, list) else []:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
field_id = str(raw.get('field_id') or '')
|
||||
if field_id not in by_id:
|
||||
cloned = copy.deepcopy(raw)
|
||||
target.append(cloned)
|
||||
by_id[field_id] = cloned
|
||||
continue
|
||||
observations = by_id[field_id].setdefault('observations', [])
|
||||
seen = {
|
||||
(item.get('document_id'), repr(item.get('value')), item.get('quote'))
|
||||
for item in observations if isinstance(item, dict)
|
||||
}
|
||||
for item in raw.get('observations') or []:
|
||||
key = (item.get('document_id'), repr(item.get('value')), item.get('quote')) if isinstance(item, dict) else None
|
||||
if key and key not in seen:
|
||||
observations.append(copy.deepcopy(item))
|
||||
seen.add(key)
|
||||
|
||||
|
||||
def _merge_order(target: dict[str, Any], incoming: dict[str, Any], codes: dict[str, str]) -> None:
|
||||
"""合并 Header 与同身份 Line;新 Line 按来源顺序追加。"""
|
||||
_merge_fields(target.setdefault('header_fields', []), incoming.get('header_fields'))
|
||||
target_lines = target.setdefault('lines', [])
|
||||
target_by_identity = {
|
||||
identity: line for line in target_lines if isinstance(line, dict)
|
||||
if (identity := _line_identity(line, codes)) is not None
|
||||
}
|
||||
for raw_line in incoming.get('lines') or []:
|
||||
if not isinstance(raw_line, dict):
|
||||
continue
|
||||
identity = _line_identity(raw_line, codes)
|
||||
if identity is None or identity not in target_by_identity:
|
||||
cloned = copy.deepcopy(raw_line)
|
||||
target_lines.append(cloned)
|
||||
if identity is not None:
|
||||
target_by_identity[identity] = cloned
|
||||
else:
|
||||
_merge_fields(target_by_identity[identity].setdefault('fields', []), raw_line.get('fields'))
|
||||
target.setdefault('source_document_ids', []).append(incoming.get('primary_document_id'))
|
||||
|
||||
|
||||
def merge_unit_orders(*, orders: list[dict[str, Any]], schema_definition: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""按冻结 Schema 稳定字段身份合并单元订单,返回确定顺序的新列表。"""
|
||||
codes = {
|
||||
str(item.get('field_id') or ''): str(item.get('field_code') or '')
|
||||
for item in schema_definition.get('fields') or [] if isinstance(item, dict)
|
||||
}
|
||||
merged: list[dict[str, Any]] = []
|
||||
for raw in orders:
|
||||
order = copy.deepcopy(raw)
|
||||
intake_no = str(order.get('source_intake_no') or '').strip().upper()
|
||||
po_numbers, line_keys = _order_identity(order, codes)
|
||||
match = None
|
||||
for candidate in merged:
|
||||
if str(candidate.get('source_intake_no') or '').strip().upper() != intake_no:
|
||||
continue
|
||||
candidate_pos, candidate_lines = _order_identity(candidate, codes)
|
||||
if (len(po_numbers) == 1 and po_numbers == candidate_pos) or bool(line_keys & candidate_lines):
|
||||
match = candidate
|
||||
break
|
||||
if match is None:
|
||||
order['source_document_ids'] = [order.get('primary_document_id')]
|
||||
merged.append(order)
|
||||
else:
|
||||
_merge_order(match, order, codes)
|
||||
return merged
|
||||
@@ -0,0 +1,183 @@
|
||||
"""
|
||||
services/shipping_notice/order_extraction_plan.py
|
||||
|
||||
用途:把 Run 冻结快照编译为可恢复、可审计的文档级抽取计划。
|
||||
依赖:ShippingOrderExtractionRun、Plan/Unit ORM、统一校验错误。
|
||||
逻辑:创建 Run 和 Worker 恢复时复用同一幂等入口;正文与附件各自形成独立单元,不复制正文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
ShippingOrderExtractionPlan,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
)
|
||||
|
||||
|
||||
PLAN_VERSION = 'shipping_order_extraction.plan.v1'
|
||||
UNIT_TRANSITIONS = {
|
||||
'pending': {'running', 'skipped'},
|
||||
'running': {'succeeded', 'failed'},
|
||||
'failed': {'pending'},
|
||||
'succeeded': set(),
|
||||
'skipped': set(),
|
||||
}
|
||||
|
||||
|
||||
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 []
|
||||
documents: list[dict[str, Any]] = []
|
||||
for intake_position, intake in enumerate(intakes):
|
||||
if not isinstance(intake, dict):
|
||||
raise ValidationError(
|
||||
'Frozen extraction intake is invalid',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE',
|
||||
)
|
||||
intake_id = intake.get('intake_id')
|
||||
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'):
|
||||
raise ValidationError(
|
||||
'Frozen extraction document reference is invalid',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE',
|
||||
)
|
||||
documents.append({
|
||||
'intake_id': int(intake_id),
|
||||
'document_id': int(document['document_id']),
|
||||
'document_type': str(document.get('document_type') or 'attachment'),
|
||||
'content_hash': str(document.get('content_hash') or '') or None,
|
||||
'intake_position': intake_position,
|
||||
'document_position': document_position,
|
||||
})
|
||||
if not documents:
|
||||
raise ValidationError(
|
||||
'Frozen extraction run contains no document units',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE',
|
||||
)
|
||||
return documents
|
||||
|
||||
|
||||
def ensure_order_extraction_plan(run: ShippingOrderExtractionRun) -> ShippingOrderExtractionPlan:
|
||||
"""
|
||||
幂等创建 Run 的文档级抽取计划。
|
||||
|
||||
Args:
|
||||
run: 已持久化且包含冻结输入快照的订单抽取 Run。
|
||||
Returns:
|
||||
唯一计划;同一 Run 重入时返回已有计划。
|
||||
Raises:
|
||||
ConflictError: 已有计划版本或快照哈希与当前 Run 不一致。
|
||||
"""
|
||||
existing = ShippingOrderExtractionPlan.query.filter_by(run_id=int(run.id)).first()
|
||||
if existing is not None:
|
||||
if (
|
||||
existing.plan_version != PLAN_VERSION
|
||||
or existing.input_snapshot_hash != str(run.input_snapshot_hash)
|
||||
):
|
||||
raise ConflictError(
|
||||
'Order extraction plan does not match the frozen run',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PLAN_CHANGED',
|
||||
)
|
||||
return existing
|
||||
|
||||
documents = _snapshot_documents(run)
|
||||
plan = ShippingOrderExtractionPlan(
|
||||
run_id=run.id,
|
||||
plan_version=PLAN_VERSION,
|
||||
input_snapshot_hash=str(run.input_snapshot_hash),
|
||||
status='planned',
|
||||
unit_count=len(documents),
|
||||
)
|
||||
db.session.add(plan)
|
||||
db.session.flush()
|
||||
for position, document in enumerate(documents):
|
||||
document_type = document['document_type']
|
||||
db.session.add(ShippingOrderExtractionUnit(
|
||||
plan_id=plan.id,
|
||||
intake_id=document['intake_id'],
|
||||
document_id=document['document_id'],
|
||||
position=position,
|
||||
unit_type='email_relation' if document_type == 'email_body' else 'document_extraction',
|
||||
document_type=document_type,
|
||||
content_hash=document['content_hash'],
|
||||
status='pending',
|
||||
))
|
||||
db.session.flush()
|
||||
return plan
|
||||
|
||||
|
||||
def _refresh_plan_status(plan: ShippingOrderExtractionPlan) -> None:
|
||||
"""按所有单元事实汇总计划状态,禁止调用方自行猜测 Run 内完成度。"""
|
||||
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):
|
||||
plan.status = 'running'
|
||||
elif all(status in {'succeeded', 'skipped'} for status in statuses):
|
||||
plan.status = 'completed'
|
||||
elif all(status == 'failed' for status in statuses):
|
||||
plan.status = 'failed'
|
||||
else:
|
||||
plan.status = 'partial_failed'
|
||||
|
||||
|
||||
def transition_order_extraction_unit(
|
||||
unit: ShippingOrderExtractionUnit,
|
||||
*,
|
||||
target_status: str,
|
||||
result: dict[str, Any] | None = None,
|
||||
error_code: str | None = None,
|
||||
error_message: str | None = None,
|
||||
) -> ShippingOrderExtractionUnit:
|
||||
"""
|
||||
单调推进一个文档单元并同步计划汇总状态。
|
||||
|
||||
Args:
|
||||
unit: 已加载且由调用方在事务内持有的计划单元。
|
||||
target_status: 当前状态允许的下一状态;失败重试必须先回到 pending。
|
||||
result: 仅 succeeded 可写的结构化局部结果,不得包含正文或凭据。
|
||||
error_code/error_message: 仅 failed 可写的安全诊断摘要。
|
||||
Returns:
|
||||
已更新但尚未提交的单元。
|
||||
"""
|
||||
current = str(unit.status or '')
|
||||
if target_status not in UNIT_TRANSITIONS.get(current, set()):
|
||||
raise ConflictError(
|
||||
f'Invalid order extraction unit transition: {current} -> {target_status}',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_TRANSITION_INVALID',
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
unit.status = target_status
|
||||
if target_status == 'running':
|
||||
unit.attempt_count = int(unit.attempt_count or 0) + 1
|
||||
unit.started_at = now
|
||||
unit.finished_at = None
|
||||
unit.result_json = None
|
||||
unit.error_code = None
|
||||
unit.error_message = None
|
||||
elif target_status == 'succeeded':
|
||||
unit.result_json = dict(result or {})
|
||||
unit.error_code = None
|
||||
unit.error_message = None
|
||||
unit.finished_at = now
|
||||
elif target_status == 'failed':
|
||||
unit.result_json = 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
|
||||
elif target_status == 'pending':
|
||||
unit.finished_at = None
|
||||
unit.error_code = None
|
||||
unit.error_message = None
|
||||
elif target_status == 'skipped':
|
||||
unit.finished_at = now
|
||||
_refresh_plan_status(unit.plan)
|
||||
return unit
|
||||
@@ -0,0 +1,204 @@
|
||||
"""
|
||||
services/shipping_notice/order_extraction_progress.py
|
||||
|
||||
用途:把已脱敏的 Workflow 生命周期事件持久化为订单抽取 Run 的当前进度与诊断时间线。
|
||||
依赖:Dify 事件观察器、ShippingOrderExtractionRun、独立 SQLAlchemy Session。
|
||||
逻辑:订单 Worker 的长事务只负责业务事实;本模块使用短事务去重并更新可恢复投影,任何记录失败均不影响主链路。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
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 app import db
|
||||
from app.models import ShippingOrderExtractionProgressEvent, ShippingOrderExtractionRun
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
# 数据库列限制为 VARCHAR(32),映射版本必须保持在该上限内。
|
||||
MAPPING_VERSION = 'shipping-order-extract-node-v1'
|
||||
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,
|
||||
}
|
||||
|
||||
|
||||
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 版本生成稳定、无业务正文的去重键。"""
|
||||
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),
|
||||
}
|
||||
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 _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 _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()
|
||||
if run.status in TERMINAL_RUN_STATUSES:
|
||||
return
|
||||
active = {str(item) for item in (run.active_stage_codes_json or []) if str(item)}
|
||||
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')
|
||||
|
||||
if event.get('workflow_run_id'):
|
||||
run.dify_workflow_run_id = _safe_text(event.get('workflow_run_id'), 128)
|
||||
run.active_stage_codes_json = sorted(active)
|
||||
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_mapping_version = MAPPING_VERSION
|
||||
run.last_activity_at = now
|
||||
run.progress_version = int(run.progress_version or 0) + 1
|
||||
|
||||
|
||||
def record_order_extraction_progress_event(*, run_no: str, event: dict[str, Any]) -> bool:
|
||||
"""
|
||||
使用独立短事务写入一个脱敏进度事件与 Run 投影。
|
||||
|
||||
AI 触发时机:无;仅由订单抽取 Worker 的 Dify 观察器或 HXOPS 持久化边界调用。
|
||||
Args:
|
||||
run_no: 订单抽取 Run 编号。
|
||||
event: 已标准化的安全事件,禁止包含节点输入、输出、Prompt、正文或异常堆栈。
|
||||
Returns:
|
||||
是否新增了事件;重复事件或未知 Run 返回 False。
|
||||
"""
|
||||
normalized_no = str(run_no or '').strip()
|
||||
if not normalized_no:
|
||||
return False
|
||||
now = datetime.utcnow()
|
||||
stage = _stage_for_event(event)
|
||||
key = _event_key(event)
|
||||
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
|
||||
except Exception:
|
||||
_LOGGER.exception('order extraction progress recording failed run_no=%s event_type=%s', normalized_no, event.get('event_type'))
|
||||
return False
|
||||
|
||||
|
||||
def record_order_extraction_persistence_started(*, run_no: str, job_id: int, attempt_count: int) -> bool:
|
||||
"""在HXOPS开始落库前写入不可被Dify迟到事件覆盖的持久化阶段。"""
|
||||
return record_order_extraction_progress_event(
|
||||
run_no=run_no,
|
||||
event={
|
||||
'event_type': 'hxops_persistence_started',
|
||||
'event_status': 'running',
|
||||
'job_id': job_id,
|
||||
'attempt_count': attempt_count,
|
||||
'node_type': 'hxops_persistence',
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,67 @@
|
||||
"""确保订单识别进度事件清理的每日默认排程存在。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleTask, User
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
DEFAULT_PROGRESS_CLEANUP_SCHEDULE_NO = 'SCH-SHIPPING-ORDER-EXTRACTION-PROGRESS-CLEANUP'
|
||||
DEFAULT_PROGRESS_CLEANUP_PLATFORM_PATH = 'shipping-order-extraction-progress-cleanup'
|
||||
DEFAULT_PROGRESS_CLEANUP_CRON = '15 3 * * *'
|
||||
|
||||
|
||||
def ensure_default_order_extraction_progress_cleanup_schedule(*, commit: bool = True, session: Any | None = None) -> ScheduleTask | None:
|
||||
"""幂等补种每日进度事件清理排程;没有可用用户时跳过,后续应用启动会再次尝试。"""
|
||||
sess = session if session is not None else db.session
|
||||
existing = sess.query(ScheduleTask).filter(
|
||||
(ScheduleTask.schedule_no == DEFAULT_PROGRESS_CLEANUP_SCHEDULE_NO)
|
||||
| (ScheduleTask.platform_api_path == DEFAULT_PROGRESS_CLEANUP_PLATFORM_PATH),
|
||||
).first()
|
||||
if existing is not None:
|
||||
return existing
|
||||
owner = sess.query(User).filter(User.role == 'admin').order_by(User.id.asc()).first() or sess.query(User).order_by(User.id.asc()).first()
|
||||
if owner is None:
|
||||
_LOGGER.info('skip seed order-extraction progress cleanup schedule: no users yet')
|
||||
return None
|
||||
now = datetime.utcnow()
|
||||
task = ScheduleTask(
|
||||
schedule_no=DEFAULT_PROGRESS_CLEANUP_SCHEDULE_NO,
|
||||
name='订单识别进度事件清理',
|
||||
schedule_type='platform_job',
|
||||
owner_user_id=int(owner.id),
|
||||
cron_expr=DEFAULT_PROGRESS_CLEANUP_CRON,
|
||||
schedule_timezone='Asia/Shanghai',
|
||||
wait_seconds=0,
|
||||
platform_api_path=DEFAULT_PROGRESS_CLEANUP_PLATFORM_PATH,
|
||||
job_params={'limit': 1000},
|
||||
kb_sync_enabled=False,
|
||||
notify_user_ids_json=[],
|
||||
notify_enabled=False,
|
||||
enabled=True,
|
||||
next_run_at=compute_next_run_at(DEFAULT_PROGRESS_CLEANUP_CRON, timezone_name='Asia/Shanghai') or now,
|
||||
created_by=int(owner.id),
|
||||
updated_by=int(owner.id),
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
sess.add(task)
|
||||
if commit:
|
||||
try:
|
||||
sess.commit()
|
||||
except Exception:
|
||||
sess.rollback()
|
||||
existing = sess.query(ScheduleTask).filter(
|
||||
(ScheduleTask.schedule_no == DEFAULT_PROGRESS_CLEANUP_SCHEDULE_NO)
|
||||
| (ScheduleTask.platform_api_path == DEFAULT_PROGRESS_CLEANUP_PLATFORM_PATH),
|
||||
).first()
|
||||
if existing is not None:
|
||||
return existing
|
||||
raise
|
||||
else:
|
||||
sess.flush()
|
||||
return task
|
||||
@@ -0,0 +1,64 @@
|
||||
"""
|
||||
services/shipping_notice/order_extraction_provider_guard.py
|
||||
|
||||
用途:为订单抽取 Provider 提供进程级并发闸门和短期熔断。
|
||||
依赖:线程同步原语、统一 ServiceUnavailableError。
|
||||
逻辑:同 Provider 共享信号量;连续可重试失败开路,成功清零;不持久化凭据或正文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
|
||||
|
||||
_LOCK = threading.Lock()
|
||||
_SEMAPHORES: dict[int, tuple[int, threading.BoundedSemaphore]] = {}
|
||||
_CIRCUITS: dict[int, dict[str, float | int]] = {}
|
||||
|
||||
|
||||
@contextmanager
|
||||
def provider_slot(provider_id: int, *, max_concurrency: int):
|
||||
"""获取 Provider 进程级并发槽;配置变化时安全替换后续使用的信号量。"""
|
||||
with _LOCK:
|
||||
current = _SEMAPHORES.get(provider_id)
|
||||
if current is None or current[0] != max_concurrency:
|
||||
current = (max_concurrency, threading.BoundedSemaphore(max_concurrency))
|
||||
_SEMAPHORES[provider_id] = current
|
||||
current[1].acquire()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
current[1].release()
|
||||
|
||||
|
||||
def assert_circuit_closed(provider_id: int) -> None:
|
||||
"""熔断冷却期内快速失败,避免继续冲击不健康 Provider。"""
|
||||
with _LOCK:
|
||||
state = _CIRCUITS.get(provider_id) or {}
|
||||
if float(state.get('open_until') or 0) > time.monotonic():
|
||||
raise ServiceUnavailableError(
|
||||
'Order extraction provider circuit is open',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_CIRCUIT_OPEN',
|
||||
)
|
||||
|
||||
|
||||
def record_provider_success(provider_id: int) -> None:
|
||||
"""成功调用清除连续失败与开路状态。"""
|
||||
with _LOCK:
|
||||
_CIRCUITS[provider_id] = {'failures': 0, 'open_until': 0.0}
|
||||
|
||||
|
||||
def record_provider_failure(
|
||||
provider_id: int, *, threshold: int, cooldown_seconds: int,
|
||||
) -> None:
|
||||
"""累计连续失败;达到阈值后设置短期开路截止时间。"""
|
||||
with _LOCK:
|
||||
state = _CIRCUITS.setdefault(provider_id, {'failures': 0, 'open_until': 0.0})
|
||||
failures = int(state.get('failures') or 0) + 1
|
||||
state['failures'] = failures
|
||||
if failures >= threshold:
|
||||
state['open_until'] = time.monotonic() + cooldown_seconds
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from datetime import datetime, timedelta
|
||||
@@ -22,8 +23,10 @@ from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
Agent,
|
||||
ChatLog,
|
||||
ChatSession,
|
||||
FileAsset,
|
||||
Job,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtractionRun,
|
||||
@@ -32,6 +35,9 @@ from app.models import (
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.runtime import dify_contract, published_version
|
||||
from app.services.shipping_notice.context_fields.runtime import canonical_mail_context
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
RUN_TRANSITIONS: dict[str, set[str]] = {
|
||||
'queued': {'running', 'cancelled'},
|
||||
@@ -258,6 +264,8 @@ def _build_snapshot(
|
||||
'asset_no': assets[intake.asset_id].asset_no if intake.asset_id in assets else None,
|
||||
'asset_content_hash': assets[intake.asset_id].content_hash if intake.asset_id in assets else None,
|
||||
'parser_version': intake.parser_version,
|
||||
# 仅供HXOPS来源漂移校验与确定性字段落库;Workflow documents 编译时强制剔除。
|
||||
'deterministic_context': canonical_mail_context(intake),
|
||||
'extracted_text': intake.extracted_text or '',
|
||||
'documents': documents_by_intake[intake.id],
|
||||
}
|
||||
@@ -280,6 +288,22 @@ def _active_run_for_intakes(intake_ids: list[int]) -> ShippingOrderExtractionRun
|
||||
)
|
||||
|
||||
|
||||
def _active_run_for_conversation(
|
||||
*, user_id: int, owner_agent_id: int, conversation_id: str,
|
||||
) -> ShippingOrderExtractionRun | None:
|
||||
"""返回同一会话仍在执行的 Run,避免多个状态卡和附件事实并行串扰。"""
|
||||
return (
|
||||
ShippingOrderExtractionRun.query.filter(
|
||||
ShippingOrderExtractionRun.user_id == user_id,
|
||||
ShippingOrderExtractionRun.owner_agent_id == owner_agent_id,
|
||||
ShippingOrderExtractionRun.conversation_id == conversation_id,
|
||||
ShippingOrderExtractionRun.status.in_({'queued', 'running', 'result_persisted'}),
|
||||
)
|
||||
.order_by(ShippingOrderExtractionRun.created_at.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _run_by_idempotency_key(idempotency_key: str) -> ShippingOrderExtractionRun | None:
|
||||
"""按服务端幂等键读取赢家 Run;独立函数便于验证并发唯一约束回落路径。"""
|
||||
return ShippingOrderExtractionRun.query.filter_by(idempotency_key=idempotency_key).first()
|
||||
@@ -347,6 +371,17 @@ def create_order_extraction_run(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_ACTIVE',
|
||||
details={'run_no': active.run_no},
|
||||
)
|
||||
active_in_conversation = _active_run_for_conversation(
|
||||
user_id=user.id,
|
||||
owner_agent_id=owner_agent.id,
|
||||
conversation_id=conversation_id,
|
||||
)
|
||||
if active_in_conversation is not None:
|
||||
raise ConflictError(
|
||||
'An order extraction run is already active in this conversation',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONVERSATION_ACTIVE',
|
||||
details={'run_no': active_in_conversation.run_no},
|
||||
)
|
||||
|
||||
run = ShippingOrderExtractionRun(
|
||||
run_no=_run_no(),
|
||||
@@ -380,6 +415,9 @@ def create_order_extraction_run(
|
||||
for index, intake in enumerate(intakes)
|
||||
])
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
|
||||
ensure_order_extraction_plan(run)
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
|
||||
@@ -410,6 +448,17 @@ def create_order_extraction_run(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_ACTIVE',
|
||||
details={'run_no': active.run_no},
|
||||
)
|
||||
active_in_conversation = _active_run_for_conversation(
|
||||
user_id=user.id,
|
||||
owner_agent_id=owner_agent.id,
|
||||
conversation_id=conversation_id,
|
||||
)
|
||||
if active_in_conversation is not None:
|
||||
raise ConflictError(
|
||||
'An order extraction run is already active in this conversation',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONVERSATION_ACTIVE',
|
||||
details={'run_no': active_in_conversation.run_no},
|
||||
)
|
||||
raise
|
||||
return run, False
|
||||
|
||||
@@ -425,6 +474,101 @@ def get_order_extraction_run(*, user_id: int, run_no: str) -> ShippingOrderExtra
|
||||
return run
|
||||
|
||||
|
||||
def retry_order_extraction_run(*, user_id: int, run_no: str) -> tuple[ShippingOrderExtractionRun, bool]:
|
||||
"""
|
||||
重新入队一次失败的订单抽取 Run,不改变冻结输入和 Provider 成功缓存。
|
||||
|
||||
核心逻辑:锁定 Run 与 Intake 后确认没有其他活动 Run,failed→queued 与新 Job 在同一事务完成;
|
||||
并发重复请求若已进入本次手工重试的 queued/running Job,则幂等返回当前 Run。
|
||||
|
||||
Args:
|
||||
user_id: 当前认证用户 ID,只能重试自己的 Run。
|
||||
run_no: 用户可见订单抽取 Run 编号。
|
||||
|
||||
Returns:
|
||||
`(run, reused)`;reused 表示并发请求复用了已经创建的手工重试 Job。
|
||||
"""
|
||||
run = (
|
||||
db.session.query(ShippingOrderExtractionRun)
|
||||
.filter_by(user_id=user_id, run_no=str(run_no or '').strip())
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if run is None:
|
||||
raise NotFoundError(
|
||||
'Shipping order extraction run not found',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_FOUND',
|
||||
)
|
||||
|
||||
current_job = db.session.get(Job, run.current_job_id) if run.current_job_id else None
|
||||
if (
|
||||
run.status in {'queued', 'running'}
|
||||
and run.phase in {'manual_retry_queued', 'calling_provider'}
|
||||
and current_job is not None
|
||||
and current_job.status in {'queued', 'running'}
|
||||
):
|
||||
return run, True
|
||||
if run.status != 'failed':
|
||||
raise ConflictError(
|
||||
'Only failed order extraction runs can be retried',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_RETRYABLE',
|
||||
details={'status': run.status},
|
||||
)
|
||||
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
snapshot_intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else []
|
||||
if not snapshot_intakes or any(
|
||||
not isinstance(item, dict) or not isinstance(item.get('deterministic_context'), dict)
|
||||
for item in snapshot_intakes
|
||||
):
|
||||
raise ConflictError(
|
||||
'The frozen input uses an obsolete order extraction contract',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE',
|
||||
details={'run_no': run.run_no},
|
||||
)
|
||||
|
||||
intake_ids = [member.intake_id for member in run.intakes]
|
||||
if intake_ids:
|
||||
db.session.query(ShippingNoticeIntake).filter(
|
||||
ShippingNoticeIntake.id.in_(intake_ids),
|
||||
).with_for_update().all()
|
||||
conflicting_run = (
|
||||
db.session.query(ShippingOrderExtractionRun)
|
||||
.join(ShippingOrderExtractionRunIntake)
|
||||
.filter(
|
||||
ShippingOrderExtractionRun.id != run.id,
|
||||
ShippingOrderExtractionRunIntake.intake_id.in_(intake_ids),
|
||||
ShippingOrderExtractionRunIntake.released_at.is_(None),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if conflicting_run is not None:
|
||||
raise ConflictError(
|
||||
'A selected intake already belongs to another active extraction run',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_ACTIVE',
|
||||
details={'run_no': conflicting_run.run_no},
|
||||
)
|
||||
|
||||
transition_order_extraction_run(run, target_status='queued', phase='manual_retry_queued')
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
{'run_no': run.run_no},
|
||||
domain='shipping_notice',
|
||||
business_ref=run.run_no,
|
||||
created_by_id=user_id,
|
||||
max_attempts=int((run.provider_config_json or {}).get('max_attempts') or 3),
|
||||
message='订单抽取等待重新识别',
|
||||
dedupe_statuses=('queued',),
|
||||
commit=False,
|
||||
)
|
||||
run.current_job_id = job_id
|
||||
db.session.flush()
|
||||
return run, False
|
||||
|
||||
|
||||
def list_order_extraction_runs(
|
||||
*, user_id: int, conversation_id: str | None = None, limit: int = 50,
|
||||
) -> list[ShippingOrderExtractionRun]:
|
||||
@@ -436,9 +580,16 @@ def list_order_extraction_runs(
|
||||
|
||||
|
||||
def serialize_order_extraction_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
"""输出用户态 Run 摘要;不返回冻结正文、幂等键或未来 Provider 凭据。"""
|
||||
"""输出用户态 Run 与通用进度投影;不返回正文、Provider、Job 或节点诊断字段。"""
|
||||
intake_snapshot = run.input_snapshot_json.get('intakes', []) if isinstance(run.input_snapshot_json, dict) else []
|
||||
schema_snapshot = run.input_snapshot_json.get('schema', {}) if isinstance(run.input_snapshot_json, dict) else {}
|
||||
now = datetime.utcnow()
|
||||
activity_at = run.last_activity_at or run.started_at or run.created_at
|
||||
idle_seconds = max(0, int((now - activity_at).total_seconds())) if activity_at else 0
|
||||
slow_threshold_seconds = get_order_extraction_user_slow_threshold_seconds(provider_agent_id=run.provider_agent_id)
|
||||
health = 'slow' if run.status in {'queued', 'running', 'result_persisted'} and idle_seconds >= slow_threshold_seconds else (
|
||||
'idle' if run.status in {'queued', 'running', 'result_persisted'} and idle_seconds >= 60 else 'normal'
|
||||
)
|
||||
return {
|
||||
'run_no': run.run_no,
|
||||
'agent_id': run.owner_agent_id,
|
||||
@@ -450,6 +601,15 @@ def serialize_order_extraction_run(run: ShippingOrderExtractionRun) -> dict[str,
|
||||
'schema_version': schema_snapshot.get('version'),
|
||||
'schema_checksum': schema_snapshot.get('checksum'),
|
||||
'attempt_count': int(run.attempt_count or 0),
|
||||
'progress': {
|
||||
'version': int(run.progress_version or 0),
|
||||
'current_stage_code': run.current_stage_code or ('queued' if run.status == 'queued' else None),
|
||||
'active_stage_codes': list(run.active_stage_codes_json or []),
|
||||
'completed_stage_codes': list(run.completed_stage_codes_json or []),
|
||||
'message_code': run.progress_message_code,
|
||||
'health': health,
|
||||
'last_activity_at': run.last_activity_at.isoformat() + 'Z' if run.last_activity_at else None,
|
||||
},
|
||||
'result': run.result_json,
|
||||
'error': (
|
||||
{'code': run.error_code, 'message': run.error_message}
|
||||
@@ -462,6 +622,314 @@ def serialize_order_extraction_run(run: ShippingOrderExtractionRun) -> dict[str,
|
||||
}
|
||||
|
||||
|
||||
def serialize_order_extraction_message_state(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
"""把服务端 Run 事实投影为聊天状态卡;历史恢复和实时持久化必须共用同一映射。"""
|
||||
result = run.result_json if isinstance(run.result_json, dict) else {}
|
||||
failed = run.status in {'failed', 'cancelled'}
|
||||
partial = run.status == 'needs_review'
|
||||
completed = run.status == 'completed'
|
||||
return {
|
||||
'status': 'failed' if failed else 'partially_completed' if partial else 'completed' if completed else 'extracting',
|
||||
'phase': 'failed' if failed else 'result_persisted' if run.status == 'result_persisted' else 'llm_extraction',
|
||||
'message': str(run.error_message or '') if failed else '',
|
||||
'created_count': int(result.get('created_count') or 0),
|
||||
'opened_existing_count': int(result.get('opened_existing_count') or 0),
|
||||
'pending_count': int(result.get('pending_count') or 0),
|
||||
'non_shipping_count': int(result.get('non_shipping_count') or 0),
|
||||
'created_with_missing_fields_count': int(result.get('created_with_missing_fields_count') or 0),
|
||||
'batch_no': result.get('batch_no'),
|
||||
'terminal': failed or partial or completed,
|
||||
'current_stage_code': run.current_stage_code,
|
||||
'health': 'normal' if failed or partial or completed else serialize_order_extraction_run(run)['progress']['health'],
|
||||
'last_activity_at': run.last_activity_at.isoformat() + 'Z' if run.last_activity_at else None,
|
||||
'started_at': (run.started_at or run.created_at).isoformat() + 'Z' if (run.started_at or run.created_at) else None,
|
||||
}
|
||||
|
||||
|
||||
def _sync_order_extraction_chat_log(run: ShippingOrderExtractionRun) -> None:
|
||||
"""在领域事务内同步已存在的 Run 卡;历史接口仍会用 Run 事实兜底晚创建消息。"""
|
||||
form_id = f'shipping-order-extraction-run:{run.run_no}'
|
||||
logs = db.session.query(ChatLog).filter_by(
|
||||
user_id=run.user_id,
|
||||
agent_id=run.owner_agent_id,
|
||||
session_id=run.conversation_id,
|
||||
message_type='text',
|
||||
).order_by(ChatLog.created_at.desc()).limit(20).all()
|
||||
for log in logs:
|
||||
payload = log.payload if isinstance(log.payload, dict) else {}
|
||||
if payload.get('formId') != form_id:
|
||||
continue
|
||||
updated = dict(payload)
|
||||
updated['order_extraction_run_no'] = run.run_no
|
||||
updated['shipping_order_extraction_state'] = serialize_order_extraction_message_state(run)
|
||||
log.payload = updated
|
||||
break
|
||||
|
||||
|
||||
def get_order_extraction_user_slow_threshold_seconds(*, provider_agent_id: int | None = None, min_samples: int = 20) -> int:
|
||||
"""按同Provider近30天终态总耗时P95计算慢响应阈值;样本不足回退180秒且不超过300秒。"""
|
||||
query = ShippingOrderExtractionRun.query.filter(
|
||||
ShippingOrderExtractionRun.finished_at.isnot(None),
|
||||
ShippingOrderExtractionRun.created_at.isnot(None),
|
||||
ShippingOrderExtractionRun.finished_at >= datetime.utcnow() - timedelta(days=30),
|
||||
)
|
||||
if provider_agent_id is not None:
|
||||
query = query.filter(ShippingOrderExtractionRun.provider_agent_id == provider_agent_id)
|
||||
rows = query.order_by(ShippingOrderExtractionRun.finished_at.desc()).limit(200).all()
|
||||
seconds = [max(0, int((row.finished_at - row.created_at).total_seconds())) for row in rows if row.finished_at and row.created_at]
|
||||
if len(seconds) < min_samples:
|
||||
return 180
|
||||
seconds.sort()
|
||||
p95 = seconds[max(0, min(len(seconds) - 1, ((len(seconds) * 95 + 99) // 100) - 1))]
|
||||
return min(300, max(60, p95))
|
||||
|
||||
|
||||
def cleanup_expired_order_extraction_progress_events(*, limit: int = 1000, now: datetime | None = None) -> dict[str, int]:
|
||||
"""分批删除过期的脱敏进度明细;Run摘要、Job与诊断审计长期保留,清理失败由排程重试。"""
|
||||
from app.models import ShippingOrderExtractionProgressEvent
|
||||
|
||||
current = now or datetime.utcnow()
|
||||
rows = ShippingOrderExtractionProgressEvent.query.filter(
|
||||
ShippingOrderExtractionProgressEvent.expires_at.isnot(None),
|
||||
ShippingOrderExtractionProgressEvent.expires_at <= current,
|
||||
).order_by(ShippingOrderExtractionProgressEvent.id.asc()).limit(min(5000, max(1, int(limit)))).all()
|
||||
count = len(rows)
|
||||
for row in rows:
|
||||
db.session.delete(row)
|
||||
db.session.commit()
|
||||
return {'deleted_count': count}
|
||||
|
||||
|
||||
def list_user_order_extraction_progress_events(*, user_id: int, run_no: str) -> list[dict[str, Any]]:
|
||||
"""返回当前用户可见的归并业务阶段,不暴露节点、Workflow或Job诊断字段。"""
|
||||
from app.models import ShippingOrderExtractionProgressEvent
|
||||
|
||||
run = get_order_extraction_run(user_id=user_id, run_no=run_no)
|
||||
rows = (
|
||||
ShippingOrderExtractionProgressEvent.query
|
||||
.filter_by(run_id=run.id)
|
||||
.order_by(ShippingOrderExtractionProgressEvent.created_at.asc(), ShippingOrderExtractionProgressEvent.id.asc())
|
||||
.all()
|
||||
)
|
||||
seen: set[tuple[str, str]] = set()
|
||||
items: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
stage = str(row.stage_code or '').strip()
|
||||
if not stage:
|
||||
continue
|
||||
event_type = str(row.event_type or '').lower()
|
||||
raw_status = str(row.event_status or '').lower()
|
||||
if raw_status in {'started', 'running', 'completed', 'failed', 'recovered'}:
|
||||
public_status = raw_status
|
||||
elif event_type in {'workflow_started', 'node_started', 'poll_started', 'retry_started'}:
|
||||
public_status = 'running'
|
||||
elif event_type in {'workflow_finished', 'node_finished'}:
|
||||
public_status = 'completed'
|
||||
elif event_type == 'recovered':
|
||||
public_status = 'recovered'
|
||||
elif event_type == 'stream_interrupted':
|
||||
public_status = 'failed'
|
||||
else:
|
||||
public_status = 'updated'
|
||||
key = (stage, public_status)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
items.append({
|
||||
'stage_code': stage,
|
||||
'status': public_status,
|
||||
'occurred_at': (row.provider_occurred_at or row.received_at or row.created_at).isoformat() + 'Z',
|
||||
})
|
||||
return items
|
||||
|
||||
|
||||
def mark_order_extraction_run_seen(*, user_id: int, run_no: str) -> bool:
|
||||
"""
|
||||
确认当前用户已经看见一条终态订单抽取卡片。
|
||||
|
||||
仅终态且已生成待查看提醒的 Run 可以被确认;重复确认保持幂等,避免会话加载、轮询与重渲染并发时重复改写。
|
||||
|
||||
Args:
|
||||
user_id: 当前登录用户,只能确认自己的 Run。
|
||||
run_no: 用户可见 Run 编号。
|
||||
|
||||
Returns:
|
||||
本次是否首次写入 `seen_at`。
|
||||
"""
|
||||
run = get_order_extraction_run(user_id=user_id, run_no=run_no)
|
||||
if run.status not in {'completed', 'needs_review', 'failed', 'cancelled'} or run.attention_generated_at is None:
|
||||
return False
|
||||
if run.seen_at is not None:
|
||||
return False
|
||||
run.seen_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
return True
|
||||
|
||||
|
||||
def _diagnostic_iso(value: datetime | None) -> str | None:
|
||||
"""诊断 DTO 统一输出 UTC 风格 ISO 时间;空值不伪造时间。"""
|
||||
return value.isoformat() + 'Z' if value else None
|
||||
|
||||
|
||||
def _diagnostic_elapsed_ms(started_at: datetime | None, finished_at: datetime | None) -> int | None:
|
||||
"""计算可安全展示的耗时毫秒;缺失端点时返回空而非猜测零耗时。"""
|
||||
if started_at is None or finished_at is None:
|
||||
return None
|
||||
return max(0, int((finished_at - started_at).total_seconds() * 1000))
|
||||
|
||||
|
||||
def _serialize_order_extraction_diagnostic_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
"""构建管理员 Run 摘要,只包含状态、标识、计数、时间和脱敏阶段,不含输入输出或错误正文。"""
|
||||
result = run.result_json if isinstance(run.result_json, dict) else {}
|
||||
return {
|
||||
'run_no': run.run_no,
|
||||
'status': run.status,
|
||||
'phase': run.phase,
|
||||
'conversation_id': run.conversation_id,
|
||||
'workflow_run_id': run.dify_workflow_run_id,
|
||||
'attempt_count': int(run.attempt_count or 0),
|
||||
'current_stage_code': run.current_stage_code,
|
||||
'active_stage_codes': list(run.active_stage_codes_json or []),
|
||||
'completed_stage_codes': list(run.completed_stage_codes_json or []),
|
||||
'created_at': _diagnostic_iso(run.created_at),
|
||||
'started_at': _diagnostic_iso(run.started_at),
|
||||
'provider_completed_at': _diagnostic_iso(run.provider_completed_at),
|
||||
'result_persisted_at': _diagnostic_iso(run.result_persisted_at),
|
||||
'finished_at': _diagnostic_iso(run.finished_at),
|
||||
'last_activity_at': _diagnostic_iso(run.last_activity_at),
|
||||
'durations_ms': {
|
||||
'queue': _diagnostic_elapsed_ms(run.created_at, run.started_at),
|
||||
'provider': _diagnostic_elapsed_ms(run.started_at, run.provider_completed_at),
|
||||
'hxops_persistence': _diagnostic_elapsed_ms(run.provider_completed_at, run.result_persisted_at),
|
||||
'total': _diagnostic_elapsed_ms(run.created_at, run.finished_at),
|
||||
},
|
||||
'result_counts': {
|
||||
'created': int(result.get('created_count') or 0),
|
||||
'opened_existing': int(result.get('opened_existing_count') or 0),
|
||||
'pending': int(result.get('pending_count') or 0),
|
||||
'non_shipping': int(result.get('non_shipping_count') or 0),
|
||||
},
|
||||
# 仅错误码可用于运维归类,错误正文可能含上游响应内容,严禁返回。
|
||||
'error_code': run.error_code,
|
||||
}
|
||||
|
||||
|
||||
def _write_order_extraction_diagnostic_audit(
|
||||
*, admin_user_id: int, action: str, request_id: str | None, run_id: int | None = None, summary: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""记录管理员诊断访问,筛选摘要只保留分页/状态等非业务正文元数据。"""
|
||||
from app.models import ShippingOrderExtractionDiagnosticAudit
|
||||
|
||||
db.session.add(ShippingOrderExtractionDiagnosticAudit(
|
||||
admin_user_id=admin_user_id,
|
||||
run_id=run_id,
|
||||
action=action[:64],
|
||||
request_id=(request_id or '')[:64] or None,
|
||||
query_summary_json=summary or None,
|
||||
))
|
||||
|
||||
|
||||
def _commit_order_extraction_diagnostic_audit_safely() -> None:
|
||||
"""尽力提交诊断审计;审计表暂时不可用时回滚其写入但不阻断已构造的只读响应。"""
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
_LOGGER.exception('order extraction diagnostic audit commit failed')
|
||||
|
||||
|
||||
def list_order_extraction_diagnostic_runs(
|
||||
*, admin_user_id: int, request_id: str | None, page: int = 1, page_size: int = 25, status: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""分页读取管理员诊断 Run 摘要,并写入只读访问审计。"""
|
||||
normalized_status = str(status or '').strip() or None
|
||||
if normalized_status and normalized_status not in {'queued', 'running', 'result_persisted', 'completed', 'needs_review', 'failed', 'cancelled'}:
|
||||
raise ValidationError('status is invalid')
|
||||
safe_page = max(1, int(page))
|
||||
safe_page_size = min(100, max(1, int(page_size)))
|
||||
query = ShippingOrderExtractionRun.query
|
||||
if normalized_status:
|
||||
query = query.filter_by(status=normalized_status)
|
||||
total = query.count()
|
||||
rows = query.order_by(ShippingOrderExtractionRun.created_at.desc(), ShippingOrderExtractionRun.id.desc()).offset(
|
||||
(safe_page - 1) * safe_page_size,
|
||||
).limit(safe_page_size).all()
|
||||
payload = {'items': [_serialize_order_extraction_diagnostic_run(row) for row in rows], 'total': total, 'page': safe_page, 'page_size': safe_page_size}
|
||||
_write_order_extraction_diagnostic_audit(
|
||||
admin_user_id=admin_user_id,
|
||||
action='list_runs',
|
||||
request_id=request_id,
|
||||
summary={'page': safe_page, 'page_size': safe_page_size, 'status': normalized_status},
|
||||
)
|
||||
_commit_order_extraction_diagnostic_audit_safely()
|
||||
return payload
|
||||
|
||||
|
||||
def get_order_extraction_diagnostic_run(*, admin_user_id: int, request_id: str | None, run_no: str) -> dict[str, Any]:
|
||||
"""读取一个 Run 的脱敏诊断详情、Job 尝试与节点生命周期,并审计管理员访问。"""
|
||||
from app.models import Job, ShippingOrderExtractionProgressEvent, ShippingOrderExtractionUnit
|
||||
|
||||
run = ShippingOrderExtractionRun.query.filter_by(run_no=run_no).first()
|
||||
if run is None:
|
||||
raise NotFoundError('Shipping order extraction run not found', code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_FOUND')
|
||||
jobs = Job.query.filter(
|
||||
Job.domain == 'shipping_notice',
|
||||
Job.job_type == 'shipping_order_extraction',
|
||||
Job.business_ref == run.run_no,
|
||||
).order_by(Job.created_at.asc(), Job.id.asc()).all()
|
||||
events = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).order_by(
|
||||
ShippingOrderExtractionProgressEvent.created_at.asc(), ShippingOrderExtractionProgressEvent.id.asc(),
|
||||
).all()
|
||||
units = (
|
||||
ShippingOrderExtractionUnit.query.filter_by(plan_id=run.extraction_plan.id)
|
||||
.order_by(ShippingOrderExtractionUnit.position.asc()).all()
|
||||
if run.extraction_plan else []
|
||||
)
|
||||
payload = {
|
||||
'run': _serialize_order_extraction_diagnostic_run(run),
|
||||
'job_attempts': [{
|
||||
'job_id': job.id,
|
||||
'status': job.status,
|
||||
'attempts': int(job.attempts or 0),
|
||||
'max_attempts': int(job.max_attempts or 0),
|
||||
'created_at': _diagnostic_iso(job.created_at),
|
||||
'started_at': _diagnostic_iso(job.started_at),
|
||||
'finished_at': _diagnostic_iso(job.finished_at),
|
||||
'duration_ms': _diagnostic_elapsed_ms(job.started_at, job.finished_at),
|
||||
'message_code': None,
|
||||
# Job message/error/result/payload 可能含输入输出,统一不出现在诊断 DTO。
|
||||
} for job in jobs],
|
||||
'progress_events': [{
|
||||
'event_type': event.event_type,
|
||||
'node_type': event.node_type,
|
||||
'stage_code': event.stage_code,
|
||||
'status': event.event_status,
|
||||
'workflow_run_id': event.workflow_run_id,
|
||||
'node_execution_id': event.node_execution_id,
|
||||
'occurred_at': _diagnostic_iso(event.provider_occurred_at or event.received_at or event.created_at),
|
||||
} for event in events],
|
||||
'units': [{
|
||||
'unit_id': unit.id,
|
||||
'position': unit.position,
|
||||
'unit_type': unit.unit_type,
|
||||
'document_type': unit.document_type,
|
||||
'status': unit.status,
|
||||
'attempt_count': int(unit.attempt_count or 0),
|
||||
'duration_ms': _diagnostic_elapsed_ms(unit.started_at, unit.finished_at),
|
||||
'error_code': unit.error_code,
|
||||
} for unit in units],
|
||||
}
|
||||
_write_order_extraction_diagnostic_audit(
|
||||
admin_user_id=admin_user_id,
|
||||
action='view_run',
|
||||
request_id=request_id,
|
||||
run_id=run.id,
|
||||
summary={'run_no': run.run_no},
|
||||
)
|
||||
_commit_order_extraction_diagnostic_audit_safely()
|
||||
return payload
|
||||
|
||||
|
||||
def transition_order_extraction_run(
|
||||
run: ShippingOrderExtractionRun,
|
||||
*,
|
||||
@@ -504,6 +972,9 @@ def transition_order_extraction_run(
|
||||
run.finished_at = None
|
||||
run.error_code = None
|
||||
run.error_message = None
|
||||
# 手工重试是同一 Run 的新执行周期,下一次终态必须重新生成待查看提醒。
|
||||
run.attention_generated_at = None
|
||||
run.seen_at = None
|
||||
for member in run.intakes:
|
||||
member.released_at = None
|
||||
for intake in intake_rows:
|
||||
@@ -541,11 +1012,33 @@ def transition_order_extraction_run(
|
||||
intake.order_extraction_error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_CANCELLED'
|
||||
intake.order_extraction_error_message = 'Order extraction was cancelled'
|
||||
if target_status in {'completed', 'needs_review', 'failed', 'cancelled'}:
|
||||
# 仅新产生的终态创建提醒;历史 Run 不回填,重复终态路径也不覆盖既有提醒时间。
|
||||
if run.attention_generated_at is None:
|
||||
run.attention_generated_at = now
|
||||
run.seen_at = None
|
||||
for member in run.intakes:
|
||||
member.released_at = now
|
||||
_sync_order_extraction_chat_log(run)
|
||||
return run
|
||||
|
||||
|
||||
def mark_order_extraction_persistence_started(run: ShippingOrderExtractionRun) -> None:
|
||||
"""在主业务事务内投影HXOPS落库阶段,避免与冻结输入校验产生跨Session写竞争。"""
|
||||
if run.status in {'completed', 'needs_review', 'failed', 'cancelled'}:
|
||||
return
|
||||
run.active_stage_codes_json = ['hxops_persistence']
|
||||
completed = {str(item) for item in (run.completed_stage_codes_json or []) if str(item)}
|
||||
completed.add('provider_result_ready')
|
||||
run.completed_stage_codes_json = sorted(completed)
|
||||
run.current_stage_code = 'hxops_persistence'
|
||||
run.progress_message_code = 'shipping.order_extraction.hxops_persistence'
|
||||
from app.services.shipping_notice.order_extraction_progress import MAPPING_VERSION
|
||||
|
||||
run.progress_mapping_version = MAPPING_VERSION
|
||||
run.last_activity_at = datetime.utcnow()
|
||||
run.progress_version = int(run.progress_version or 0) + 1
|
||||
|
||||
|
||||
def sync_order_extraction_run_after_job_recovery(job: Any) -> None:
|
||||
"""
|
||||
通用 Job 超时回收后同步领域 Run,避免 Job 已 queued/failed 而 Run 永久 running。
|
||||
@@ -651,6 +1144,7 @@ def get_order_extraction_run_health(
|
||||
'thresholds': {
|
||||
'queued_stale_seconds': queued_threshold,
|
||||
'running_stale_seconds': running_threshold,
|
||||
'user_slow_response_seconds': get_order_extraction_user_slow_threshold_seconds(),
|
||||
'failure_rate_degraded': 0.2,
|
||||
'failure_rate_min_terminal_runs': 5,
|
||||
},
|
||||
|
||||
@@ -16,10 +16,38 @@ import requests
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.services.dify import DifyService
|
||||
from app.services.shipping_notice.context_fields.dify_exposure import compile_readonly_context
|
||||
from app.services.shipping_notice.notice_line_table import inspect_notice_table_text
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
|
||||
def build_order_extraction_workflow_inputs(run: Any) -> dict[str, str]:
|
||||
"""从 Run 不可变快照构建 Dify Start 输入;确定性字段只能进入独立只读上下文。"""
|
||||
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',
|
||||
)
|
||||
|
||||
|
||||
def build_order_extraction_workflow_inputs(run: Any, *, unit: Any) -> dict[str, str]:
|
||||
"""
|
||||
从 Run 不可变快照构建版本化 Dify 执行清单。
|
||||
|
||||
核心逻辑:将 Run 标识、完整性哈希、LLM 抽取契约、冻结文档和受控只读提示
|
||||
收敛为唯一 Start 输入,防止 Workflow 变量随契约演进而漂移。
|
||||
|
||||
Args:
|
||||
run: 已冻结输入快照的 ShippingOrderExtractionRun。
|
||||
|
||||
Returns:
|
||||
dict[str, str]: 仅含 execution_manifest JSON 字符串的 Dify inputs。
|
||||
"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
schema = (
|
||||
@@ -27,41 +55,74 @@ def build_order_extraction_workflow_inputs(run: Any) -> dict[str, str]:
|
||||
if isinstance(schema_snapshot.get('extraction_contract'), dict)
|
||||
else {}
|
||||
)
|
||||
intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else []
|
||||
# 确定性上下文必须从 documents 剥离,避免绕过版本级暴露策略。
|
||||
dify_intakes = [
|
||||
{key: value for key, value in intake.items() if key != 'deterministic_context'}
|
||||
for intake in intakes if isinstance(intake, dict)
|
||||
]
|
||||
intake, document = _unit_snapshot(run, unit)
|
||||
readonly_snapshot = {**snapshot, 'intakes': [intake]}
|
||||
manifest = {
|
||||
'contract_version': 'shipping_order_extraction.unit.v2',
|
||||
'run': {'run_no': str(run.run_no)},
|
||||
'unit': {
|
||||
'unit_id': int(unit.id),
|
||||
'unit_type': str(unit.unit_type),
|
||||
'intake_id': int(unit.intake_id),
|
||||
'intake_no': str(intake.get('intake_no') or ''),
|
||||
'document_id': int(unit.document_id),
|
||||
'document_type': str(unit.document_type),
|
||||
},
|
||||
'integrity': {'input_snapshot_hash': str(run.input_snapshot_hash)},
|
||||
'extraction_contract': schema,
|
||||
'documents': [{
|
||||
'intake_id': int(unit.intake_id),
|
||||
'intake_no': str(intake.get('intake_no') or ''),
|
||||
'document': dict(document),
|
||||
}],
|
||||
'readonly_hints': compile_readonly_context(readonly_snapshot),
|
||||
}
|
||||
return {
|
||||
'run_no': str(run.run_no),
|
||||
'input_snapshot_hash': str(run.input_snapshot_hash),
|
||||
'schema_contract': json.dumps(schema, ensure_ascii=False, separators=(',', ':')),
|
||||
'documents': json.dumps(dify_intakes, ensure_ascii=False, separators=(',', ':')),
|
||||
'readonly_context': json.dumps(
|
||||
compile_readonly_context(snapshot), ensure_ascii=False, separators=(',', ':'),
|
||||
),
|
||||
'execution_manifest': json.dumps(manifest, ensure_ascii=False, separators=(',', ':')),
|
||||
}
|
||||
|
||||
|
||||
def parse_order_extraction_workflow_result(result: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""校验 Dify Workflow 终态与 orders 输出;禁止从自由文本猜测 JSON。"""
|
||||
"""
|
||||
校验 Dify Workflow 终态与 orders 输出,并兼容 End 节点的有限 JSON 字符串包装。
|
||||
|
||||
核心逻辑:Dify String 输出在不同版本中可能额外被 JSON 序列化一次;最多解包两层,
|
||||
仅接受最终的 orders 数组或 ``{orders: [...]}`` 包装,禁止从自由文本猜测订单。
|
||||
|
||||
Args:
|
||||
result: Dify Workflow 的终态事件数据,必须含 status 与 outputs。
|
||||
|
||||
Returns:
|
||||
list[dict[str, Any]]: 已通过结构类型校验的订单数组。
|
||||
|
||||
Raises:
|
||||
ValidationError: 输出不是合法订单数组,或 Workflow 已结束但输出/节点校验不符合抽取契约。
|
||||
ServiceUnavailableError: Workflow 传输层未返回可解析终态。
|
||||
"""
|
||||
if not isinstance(result, dict):
|
||||
raise ServiceUnavailableError(
|
||||
raise ValidationError(
|
||||
'Dify Workflow returned no structured result',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
status = str(result.get('status') or '').strip().lower()
|
||||
if status not in {'succeeded', 'success'}:
|
||||
raise ServiceUnavailableError(
|
||||
# Workflow 已给出终态,说明连接成功;重试相同冻结 Unit 不能修复画布或模型输出错误。
|
||||
raise ValidationError(
|
||||
str(result.get('error') or 'Dify Workflow failed')[:1000],
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_FAILED',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
outputs = result.get('outputs') if isinstance(result.get('outputs'), dict) else {}
|
||||
raw = outputs.get('orders')
|
||||
if raw is None:
|
||||
raw = outputs.get('order_extraction_result')
|
||||
if isinstance(raw, str):
|
||||
# Dify End 的 String 变量可能被 API 再编码一次;对象解包和字符串解码交替执行。
|
||||
json_decode_count = 0
|
||||
while True:
|
||||
if isinstance(raw, dict) and 'orders' in raw:
|
||||
raw = raw['orders']
|
||||
continue
|
||||
if not isinstance(raw, str) or json_decode_count >= 2:
|
||||
break
|
||||
try:
|
||||
raw = json.loads(raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
@@ -69,8 +130,7 @@ def parse_order_extraction_workflow_result(result: dict[str, Any]) -> list[dict[
|
||||
'Workflow orders output must be valid JSON',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
|
||||
) from exc
|
||||
if isinstance(raw, dict) and isinstance(raw.get('orders'), list):
|
||||
raw = raw['orders']
|
||||
json_decode_count += 1
|
||||
if not isinstance(raw, list) or any(not isinstance(item, dict) for item in raw):
|
||||
raise ValidationError(
|
||||
'Workflow must output an orders array',
|
||||
@@ -79,14 +139,137 @@ def parse_order_extraction_workflow_result(result: dict[str, Any]) -> list[dict[
|
||||
return raw
|
||||
|
||||
|
||||
def execute_order_extraction_workflow(*, run: Any, provider: Any, timeout_seconds: int) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
def validate_unit_orders(run: Any, *, unit: Any, orders: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""强制单元结果只能引用当前 Intake/Document,阻止跨附件伪造关联或证据。"""
|
||||
intake, _document = _unit_snapshot(run, unit)
|
||||
intake_no = str(intake.get('intake_no') or '').strip().upper()
|
||||
for order in orders:
|
||||
if str(order.get('source_intake_no') or '').strip().upper() != intake_no:
|
||||
raise ValidationError(
|
||||
'Unit order source intake does not match the extraction unit',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
if int(order.get('primary_document_id') or 0) != int(unit.document_id):
|
||||
raise ValidationError(
|
||||
'Unit order primary document does not match the extraction unit',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
field_groups = [order.get('header_fields') or []]
|
||||
field_groups.extend(
|
||||
line.get('fields') or []
|
||||
for line in order.get('lines') or []
|
||||
if isinstance(line, dict)
|
||||
)
|
||||
for fields in field_groups:
|
||||
for field in fields if isinstance(fields, list) else []:
|
||||
for observation in field.get('observations') or [] if isinstance(field, dict) else []:
|
||||
if int(observation.get('document_id') or 0) != int(unit.document_id):
|
||||
raise ValidationError(
|
||||
'Unit observation references another document',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
return orders
|
||||
|
||||
|
||||
def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, Any]] | None:
|
||||
"""完整确定性表格单元直接生成动态订单;无法覆盖必填字段时返回 None 交给模型。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
schema = (
|
||||
schema_snapshot.get('extraction_contract')
|
||||
if isinstance(schema_snapshot.get('extraction_contract'), dict)
|
||||
else {}
|
||||
)
|
||||
definition = schema_snapshot.get('definition') if isinstance(schema_snapshot.get('definition'), dict) else {}
|
||||
intake, document = _unit_snapshot(run, unit)
|
||||
inspected = inspect_notice_table_text(
|
||||
str(document.get('extracted_text') or ''),
|
||||
contract=compile_table_header_contract(definition),
|
||||
)
|
||||
rows = inspected.get('lines') if isinstance(inspected.get('lines'), list) else []
|
||||
if not rows or inspected.get('ambiguous_fields'):
|
||||
return None
|
||||
fields = [
|
||||
item for item in definition.get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True)
|
||||
and item.get('collection_mode', 'llm_extraction') == 'llm_extraction'
|
||||
]
|
||||
by_code = {str(item.get('field_code') or ''): item for item in fields}
|
||||
text = str(document.get('extracted_text') or '')
|
||||
|
||||
def quote_for(row: dict[str, Any]) -> str:
|
||||
part_number = str(row.get('part_number') or '')
|
||||
return next((line.strip() for line in text.splitlines() if part_number and part_number in line), part_number)
|
||||
|
||||
line_groups: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
quote = quote_for(row)
|
||||
raw_fields = []
|
||||
for code, value in row.items():
|
||||
config = by_code.get(str(code))
|
||||
if config is None or config.get('scope') != 'line' or value in (None, ''):
|
||||
continue
|
||||
raw_fields.append({
|
||||
'field_id': str(config['field_id']),
|
||||
'observations': [{
|
||||
'value': value,
|
||||
'document_id': int(unit.document_id),
|
||||
'quote': quote,
|
||||
'confidence': 1.0,
|
||||
}],
|
||||
})
|
||||
line_groups.append({'fields': raw_fields})
|
||||
|
||||
header_fields = []
|
||||
for code, config in by_code.items():
|
||||
if config.get('scope') != 'header':
|
||||
continue
|
||||
values = {str(row.get(code)) for row in rows if row.get(code) not in (None, '')}
|
||||
if len(values) == 1:
|
||||
value = next(iter(values))
|
||||
header_fields.append({
|
||||
'field_id': str(config['field_id']),
|
||||
'observations': [{
|
||||
'value': value,
|
||||
'document_id': int(unit.document_id),
|
||||
'quote': quote_for(rows[0]),
|
||||
'confidence': 1.0,
|
||||
}],
|
||||
})
|
||||
|
||||
present_header = {item['field_id'] for item in header_fields}
|
||||
for config in fields:
|
||||
if not config.get('required'):
|
||||
continue
|
||||
field_id = str(config['field_id'])
|
||||
if config.get('scope') == 'header' and field_id not in present_header:
|
||||
return None
|
||||
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
|
||||
return [{
|
||||
'schema_version_id': schema.get('schema_version_id'),
|
||||
'schema_checksum': schema.get('checksum'),
|
||||
'classification': 'shipping_request',
|
||||
'classification_confidence': 1.0,
|
||||
'source_intake_no': str(intake.get('intake_no') or ''),
|
||||
'primary_document_id': int(unit.document_id),
|
||||
'header_fields': header_fields,
|
||||
'lines': line_groups,
|
||||
'conflicts': [],
|
||||
}]
|
||||
|
||||
|
||||
def execute_order_extraction_workflow(*, run: Any, unit: Any, provider: Any, timeout_seconds: int, event_observer=None) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
"""调用绑定 Provider 的 Workflow,并把网络异常归类为可重试业务错误。"""
|
||||
try:
|
||||
result = DifyService.run_workflow_streaming(
|
||||
agent=provider,
|
||||
inputs=build_order_extraction_workflow_inputs(run),
|
||||
inputs=build_order_extraction_workflow_inputs(run, unit=unit),
|
||||
user=f'shipping-order-extraction:{run.user_id}',
|
||||
timeout=(5, timeout_seconds),
|
||||
event_observer=event_observer,
|
||||
)
|
||||
except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout) as exc:
|
||||
raise ServiceUnavailableError(
|
||||
@@ -98,7 +281,9 @@ def execute_order_extraction_workflow(*, run: Any, provider: Any, timeout_second
|
||||
'Dify order extraction workflow request failed',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_FAILED',
|
||||
) from exc
|
||||
orders = parse_order_extraction_workflow_result(result)
|
||||
orders = validate_unit_orders(
|
||||
run, unit=unit, orders=parse_order_extraction_workflow_result(result),
|
||||
)
|
||||
metadata = {
|
||||
'workflow_run_id': result.get('workflow_run_id'),
|
||||
'poll_used': bool(result.get('_workflow_poll_used')),
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_schema/field_rules.py
|
||||
|
||||
用途:执行冻结订单 Schema 的通用字段归一化与 validator,供 Dify Observation 和确定性表格共用。
|
||||
依赖:标准库 Decimal/date、reservation_id 安全校验、统一 ValidationError。
|
||||
逻辑:运行时传入完整字段配置;本模块不查询数据库,也不允许配置绕过 Reservation ID 安全规则。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
|
||||
def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any:
|
||||
"""按冻结字段类型与 normalizer 规范化候选值;类型错误抛稳定业务异常。"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
value_type = str(config.get('value_type') or 'string')
|
||||
normalizer = str(config.get('normalizer_key') or 'trim')
|
||||
try:
|
||||
if value_type == 'decimal':
|
||||
return Decimal(str(value).replace(',', '').strip())
|
||||
if value_type == 'integer':
|
||||
return int(str(value).replace(',', '').strip())
|
||||
if value_type == 'date':
|
||||
text = str(value).strip().replace('/', '-').replace('.', '-')
|
||||
return date.fromisoformat(text)
|
||||
if value_type == 'boolean':
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
lowered = str(value).strip().lower()
|
||||
if lowered in {'true', '1', 'yes', 'y'}:
|
||||
return True
|
||||
if lowered in {'false', '0', 'no', 'n'}:
|
||||
return False
|
||||
raise ValueError('invalid boolean')
|
||||
except (InvalidOperation, ValueError, TypeError) as exc:
|
||||
raise ValidationError(
|
||||
'Dynamic field value type is invalid', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT'
|
||||
) from exc
|
||||
text = str(value).strip()
|
||||
if normalizer == 'uppercase_trim':
|
||||
text = text.upper()
|
||||
elif normalizer == 'lowercase_trim':
|
||||
text = text.lower()
|
||||
if normalizer == 'reservation_id':
|
||||
text = validated_reservation_id(text) or ''
|
||||
if value_type == 'enum' and text not in set(config.get('enum_options') or []):
|
||||
raise ValidationError('Dynamic enum value is invalid', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT')
|
||||
return text or None
|
||||
|
||||
|
||||
def validate_order_field_value(value: Any, config: dict[str, Any]) -> bool:
|
||||
"""执行冻结字段 validator;Reservation ID 永远叠加后端安全校验。"""
|
||||
if str(config.get('field_code') or '') == 'reservation_id' and not validated_reservation_id(value):
|
||||
return False
|
||||
for key in config.get('validator_keys') or []:
|
||||
if key == 'non_empty' and value in (None, ''):
|
||||
return False
|
||||
if key in {'positive_decimal', 'positive_integer'} and Decimal(str(value)) <= 0:
|
||||
return False
|
||||
if key == 'non_negative_decimal' and Decimal(str(value)) < 0:
|
||||
return False
|
||||
if key == 'reservation_id' and not validated_reservation_id(value):
|
||||
return False
|
||||
if key == 'atomic_part_number' and '/' in str(value):
|
||||
return False
|
||||
if key == 'iso_date' and not isinstance(value, date):
|
||||
return False
|
||||
return True
|
||||
@@ -25,13 +25,17 @@ from app.models import (
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice.notice_lines import parse_notice_table_text
|
||||
from app.services.shipping_notice.notice_line_table import inspect_notice_table_text
|
||||
from app.services.shipping_notice.context_fields.runtime import (
|
||||
canonical_mail_context,
|
||||
persist_deterministic_context_fields,
|
||||
)
|
||||
from app.services.shipping_notice.order_customer_matching import refresh_order_customer_matches
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
normalize_order_field_value,
|
||||
validate_order_field_value,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
|
||||
def published_version() -> ShippingOrderSchemaVersion:
|
||||
@@ -70,7 +74,8 @@ def dify_contract(version: ShippingOrderSchemaVersion) -> dict[str, Any]:
|
||||
def _json_value(value: Any) -> Any:
|
||||
"""将 Decimal/date 转为 JSON 可安全持久化的标量。"""
|
||||
if isinstance(value, Decimal):
|
||||
return format(value, 'f')
|
||||
normalized = value.normalize()
|
||||
return format(normalized, 'f')
|
||||
if isinstance(value, date):
|
||||
return value.isoformat()
|
||||
return value
|
||||
@@ -99,64 +104,18 @@ def _input_snapshot(
|
||||
|
||||
|
||||
def _normalize(value: Any, config: dict[str, Any]) -> Any:
|
||||
"""按发布字段类型与 normalizer 规范化候选值。"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
value_type = str(config['value_type'])
|
||||
normalizer = str(config.get('normalizer_key') or 'trim')
|
||||
try:
|
||||
if value_type == 'decimal':
|
||||
return Decimal(str(value).replace(',', '').strip())
|
||||
if value_type == 'integer':
|
||||
return int(str(value).replace(',', '').strip())
|
||||
if value_type == 'date':
|
||||
return date.fromisoformat(str(value).strip())
|
||||
if value_type == 'boolean':
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
lowered = str(value).strip().lower()
|
||||
if lowered in {'true', '1', 'yes', 'y'}:
|
||||
return True
|
||||
if lowered in {'false', '0', 'no', 'n'}:
|
||||
return False
|
||||
raise ValueError('invalid boolean')
|
||||
except (InvalidOperation, ValueError, TypeError) as exc:
|
||||
raise ValidationError(
|
||||
'Dynamic field value type is invalid', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT'
|
||||
) from exc
|
||||
text = str(value).strip()
|
||||
if normalizer == 'uppercase_trim':
|
||||
text = text.upper()
|
||||
elif normalizer == 'lowercase_trim':
|
||||
text = text.lower()
|
||||
if normalizer == 'reservation_id':
|
||||
text = validated_reservation_id(text) or ''
|
||||
if value_type == 'enum' and text not in set(config.get('enum_options') or []):
|
||||
raise ValidationError('Dynamic enum value is invalid', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT')
|
||||
return text or None
|
||||
"""复用冻结 Schema 通用规则规范化 Dify 或后端表格候选。"""
|
||||
return normalize_order_field_value(value, config)
|
||||
|
||||
|
||||
def _validate(value: Any, config: dict[str, Any]) -> bool:
|
||||
"""执行发布契约中受控 validator;返回值决定字段是否可被接受。"""
|
||||
for key in config.get('validator_keys') or []:
|
||||
if key == 'non_empty' and value in (None, ''):
|
||||
return False
|
||||
if key in {'positive_decimal', 'positive_integer'} and Decimal(str(value)) <= 0:
|
||||
return False
|
||||
if key == 'non_negative_decimal' and Decimal(str(value)) < 0:
|
||||
return False
|
||||
if key == 'reservation_id' and not validated_reservation_id(value):
|
||||
return False
|
||||
if key == 'atomic_part_number' and '/' in str(value):
|
||||
return False
|
||||
if key == 'iso_date' and not isinstance(value, date):
|
||||
return False
|
||||
return True
|
||||
"""复用冻结 Schema 通用 validator,并保留后端安全硬规则。"""
|
||||
return validate_order_field_value(value, config)
|
||||
|
||||
|
||||
def _source_type(document: ShippingNoticeDocument) -> str:
|
||||
"""把 Document 技术类型映射为 Schema 证据来源类型。"""
|
||||
return 'email_body_text' if document.document_type == 'body' else 'attachment_text'
|
||||
return 'email_body_text' if document.document_type == 'email_body' else 'attachment_text'
|
||||
|
||||
|
||||
def _quote_supports_value(value: Any, config: dict[str, Any], quote: str) -> bool:
|
||||
@@ -313,20 +272,32 @@ def _persist_field(*, extraction: ShippingOrderExtraction, line_id: int | None,
|
||||
return value, status, observations, decision_payload
|
||||
|
||||
|
||||
def _backend_rows(documents: list[ShippingNoticeDocument]) -> list[dict[str, Any]]:
|
||||
def _backend_rows(
|
||||
documents: list[ShippingNoticeDocument], *, schema_definition: dict[str, Any],
|
||||
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""从 EML/PDF Document 保留列边界的文本生成后端表格观察原料。"""
|
||||
contract = compile_table_header_contract(schema_definition)
|
||||
rows: list[dict[str, Any]] = []
|
||||
issues: list[dict[str, Any]] = []
|
||||
for document in documents:
|
||||
for position, raw in enumerate(parse_notice_table_text(str(document.extracted_text or ''))):
|
||||
inspected = inspect_notice_table_text(str(document.extracted_text or ''), contract=contract)
|
||||
parsed_rows = inspected['lines']
|
||||
if inspected['ambiguous_fields']:
|
||||
issues.append({
|
||||
'document_id': int(document.id),
|
||||
'reason': 'ambiguous_table_headers',
|
||||
'field_codes': list(inspected['ambiguous_fields']),
|
||||
})
|
||||
for position, raw in enumerate(parsed_rows):
|
||||
if isinstance(raw, dict):
|
||||
rows.append({**raw, '_document': document, '_position': position})
|
||||
return rows
|
||||
return rows, issues
|
||||
|
||||
|
||||
def _associated_backend_rows(raw_fields: list[Any], configs: dict[str, dict[str, Any]],
|
||||
rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""使用当前动态行任一稳定字段值关联后端表格行,避免按行号或目标字段自证。"""
|
||||
signatures: list[tuple[str, str]] = []
|
||||
signatures: list[tuple[str, Any]] = []
|
||||
for raw in raw_fields:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
@@ -338,18 +309,17 @@ def _associated_backend_rows(raw_fields: list[Any], configs: dict[str, dict[str,
|
||||
continue
|
||||
value = _normalize(item.get('value'), config)
|
||||
if value is not None:
|
||||
signatures.append((str(config['field_code']), str(_json_value(value))))
|
||||
matched = [
|
||||
row for row in rows
|
||||
if any(
|
||||
row.get(code) not in (None, '')
|
||||
and str(_json_value(_normalize(row.get(code), configs[next(
|
||||
field_id for field_id, item in configs.items() if item['field_code'] == code
|
||||
)]))) == value
|
||||
for code, value in signatures
|
||||
if any(item['field_code'] == code for item in configs.values())
|
||||
)
|
||||
]
|
||||
signatures.append((str(config['field_code']), value))
|
||||
configs_by_code = {str(item['field_code']): item for item in configs.values()}
|
||||
matched = []
|
||||
for row in rows:
|
||||
for code, expected in signatures:
|
||||
config = configs_by_code.get(code)
|
||||
if config is None or row.get(code) in (None, ''):
|
||||
continue
|
||||
if _normalize(row.get(code), config) == expected:
|
||||
matched.append(row)
|
||||
break
|
||||
return matched
|
||||
|
||||
|
||||
@@ -437,7 +407,9 @@ def persist_dynamic_order(
|
||||
observations.extend(context_observations)
|
||||
decisions.extend(context_decisions)
|
||||
blocked.extend(context_blocked)
|
||||
backend_rows = _backend_rows(documents)
|
||||
backend_rows, table_issues = _backend_rows(documents, schema_definition=version.definition_json or {})
|
||||
for issue in table_issues:
|
||||
blocked.extend(str(code) for code in issue['field_codes'])
|
||||
groups: list[tuple[int | None, int | None, str, list[Any], dict[str, Any]]] = [
|
||||
(None, None, 'header', raw_order.get('header_fields') or [], header)
|
||||
]
|
||||
@@ -480,13 +452,15 @@ def persist_dynamic_order(
|
||||
field_id = str(config['field_id'])
|
||||
if config.get('scope') != scope or (line_id, field_id) in seen:
|
||||
continue
|
||||
_value, status, field_observations, decision = _persist_field(
|
||||
value, status, field_observations, decision = _persist_field(
|
||||
extraction=extraction, line_id=line_id, raw={}, config=config, documents=document_map,
|
||||
backend_candidates=_backend_candidates(config, rows=associated_rows),
|
||||
)
|
||||
decision['line_position'] = position
|
||||
observations.extend(field_observations)
|
||||
decisions.append(decision)
|
||||
if value is not None:
|
||||
projection[str(config['field_code'])] = _json_value(value)
|
||||
if config.get('required') and status not in {'accepted', 'corroborated'}:
|
||||
blocked.append(str(config['field_code']))
|
||||
|
||||
@@ -500,7 +474,10 @@ def persist_dynamic_order(
|
||||
if config['scope'] == 'line' and (not line_projections or any(code not in line for line in line_projections)):
|
||||
blocked.append(code)
|
||||
extraction.normalized_result_json = {'header': header, 'lines': line_projections}
|
||||
extraction.validation_result_json = {'blocked_fields': sorted(set(blocked))}
|
||||
extraction.validation_result_json = {
|
||||
'blocked_fields': sorted(set(blocked)),
|
||||
'deterministic_table_issues': table_issues,
|
||||
}
|
||||
extraction.status = 'needs_review' if blocked else 'accepted'
|
||||
extraction.updated_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
|
||||
@@ -52,6 +52,7 @@ from app.services.shipping_notice.order_schema.registry import (
|
||||
VALIDATORS,
|
||||
catalog,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
from app.services.shipping_notice.order_schema.diff import compare_definitions
|
||||
|
||||
SCHEMA_CODE = 'SHIPPING_ORDER'
|
||||
@@ -93,6 +94,7 @@ def _field_payload(field: ShippingOrderField) -> dict[str, Any]:
|
||||
'value_type': field.value_type,
|
||||
'field_category': field.field_category,
|
||||
'collection_mode': field.collection_mode,
|
||||
'display_sequence': int(field.display_sequence or 0),
|
||||
'status': field.status,
|
||||
'published_once': bool(field.published_once),
|
||||
'created_at': _iso(field.created_at),
|
||||
@@ -310,7 +312,7 @@ def get_state() -> dict[str, Any]:
|
||||
# Retired fields remain available to historical records, not the current configuration workspace.
|
||||
'fields': [_field_payload(item) for item in ShippingOrderField.query.filter_by(
|
||||
schema_id=schema.id, status='active',
|
||||
).order_by(ShippingOrderField.field_code).all()],
|
||||
).order_by(ShippingOrderField.display_sequence, ShippingOrderField.field_code).all()],
|
||||
'versions': [
|
||||
_version_payload(item)
|
||||
for item in reversed(schema.versions)
|
||||
@@ -644,6 +646,12 @@ def save_field(
|
||||
) != immutable_shape:
|
||||
raise ConflictError('Published field identity shape is immutable', code='SHIPPING.ORDER_FIELD_IMMUTABLE')
|
||||
previous_code = field.field_code if field else None
|
||||
if field is None:
|
||||
next_sequence = (
|
||||
db.session.query(func.max(ShippingOrderField.display_sequence))
|
||||
.filter(ShippingOrderField.schema_id == schema.id)
|
||||
.scalar() or 0
|
||||
) + 1
|
||||
field = field or ShippingOrderField(
|
||||
schema_id=schema.id,
|
||||
field_code=code,
|
||||
@@ -651,6 +659,7 @@ def save_field(
|
||||
value_type=value_type,
|
||||
field_category=field_category,
|
||||
collection_mode=collection_mode,
|
||||
display_sequence=next_sequence,
|
||||
created_by_id=actor_id,
|
||||
)
|
||||
field.field_code = code
|
||||
@@ -683,6 +692,29 @@ def save_field(
|
||||
return _field_payload(field)
|
||||
|
||||
|
||||
def reorder_fields(data: dict[str, Any], *, actor_id: int | None, request_id: str | None = None) -> dict[str, Any]:
|
||||
"""保存字段目录全局顺序;与草稿、发布版本和纳入状态完全独立。"""
|
||||
schema = _require_schema()
|
||||
ordered_ids = data.get('field_ids')
|
||||
if not isinstance(ordered_ids, list) or not ordered_ids or len(set(map(str, ordered_ids))) != len(ordered_ids):
|
||||
raise ValidationError('field_ids must be a unique non-empty list', code='SHIPPING.ORDER_FIELD_ORDER_INVALID')
|
||||
fields = ShippingOrderField.query.filter_by(schema_id=schema.id, status='active').all()
|
||||
by_id = {field.id: field for field in fields}
|
||||
normalized_ids = [str(field_id) for field_id in ordered_ids]
|
||||
if set(normalized_ids) != set(by_id):
|
||||
raise ValidationError('field_ids must contain all active fields', code='SHIPPING.ORDER_FIELD_ORDER_INVALID')
|
||||
before = [{'field_id': field.id, 'display_sequence': field.display_sequence} for field in fields]
|
||||
for sequence, field_id in enumerate(normalized_ids, start=1):
|
||||
by_id[field_id].display_sequence = sequence
|
||||
_write_audit(
|
||||
schema_id=schema.id, version_id=None, event_type='field_saved', actor_id=actor_id,
|
||||
request_id=request_id, before={'fields': before},
|
||||
after={'fields': [{'field_id': field_id, 'display_sequence': index} for index, field_id in enumerate(normalized_ids, start=1)]},
|
||||
)
|
||||
db.session.commit()
|
||||
return {'fields': [_field_payload(by_id[field_id]) for field_id in normalized_ids]}
|
||||
|
||||
|
||||
def retire_field(
|
||||
field_id: str, *, actor_id: int | None = None, request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
@@ -980,6 +1012,7 @@ def save_draft(
|
||||
'sequence': sequence,
|
||||
})
|
||||
after = {'schema_code': version.schema.schema_code, 'version': version.version, 'fields': normalized_fields}
|
||||
compile_table_header_contract(after)
|
||||
version.definition_json = after
|
||||
version.lock_version += 1
|
||||
version.change_note = str(data.get('change_note') or version.change_note or '').strip() or None
|
||||
@@ -1013,6 +1046,7 @@ def publish(
|
||||
)
|
||||
definition = _definition(version)
|
||||
_validate_published_context_sources(definition)
|
||||
compile_table_header_contract(definition)
|
||||
enabled_configs = _enabled_fields(definition)
|
||||
if not enabled_configs:
|
||||
raise ValidationError('Schema version requires at least one field', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_schema/table_contract.py
|
||||
|
||||
用途:把冻结订单 Schema 编译为确定性表格表头契约,并校验别名碰撞与安全禁用表头。
|
||||
依赖:AppError 校验契约、reservation_id 后端安全边界。
|
||||
逻辑:Schema 保存/发布和 Run 运行时共用同一纯函数;解析器只消费编译结果,不读取当前数据库配置。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
|
||||
TABLE_FIELD_CODES = frozenset({
|
||||
'line_no', 'part_number', 'qty', 'unit_price', 'amount', 'currency',
|
||||
'reservation_id', 'required_date', 'customer_part_number',
|
||||
'aws_part_number', 'uom', 'remark', 'po_number', 'inventory_source_hint',
|
||||
})
|
||||
|
||||
# 这些技术/业务标识与 Reservation ID 语义不同,管理员配置不得覆盖安全边界。
|
||||
RESERVATION_ID_FORBIDDEN_HEADERS = frozenset({
|
||||
'allocation id', 'parent allocation id', 'commodity group id',
|
||||
'supplier code', 'uuid', 'internal id',
|
||||
})
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TableHeaderContract:
|
||||
"""冻结 Schema 编译出的确定性表头映射及字段配置。"""
|
||||
|
||||
header_to_field: dict[str, str]
|
||||
fields_by_code: dict[str, dict[str, Any]]
|
||||
|
||||
|
||||
def normalize_table_header(value: Any) -> str:
|
||||
"""以 NFKC、大小写折叠和标点空白折叠生成稳定表头比较键。"""
|
||||
text = unicodedata.normalize('NFKC', str(value or '')).strip().casefold()
|
||||
text = re.sub(r"[^\w\u4e00-\u9fff]+", ' ', text, flags=re.UNICODE)
|
||||
return re.sub(r'[_\s]+', ' ', text).strip()
|
||||
|
||||
|
||||
def compile_table_header_contract(definition: dict[str, Any]) -> TableHeaderContract:
|
||||
"""
|
||||
从冻结 Schema 定义编译确定性表头契约。
|
||||
|
||||
Args:
|
||||
definition: Run 冻结或待发布的完整 definition_json;不得传当前可变字段目录拼装结果。
|
||||
Returns:
|
||||
仅包含解析器支持字段的标准化表头映射与完整字段配置。
|
||||
Raises:
|
||||
ValidationError: 不同字段占用同一标准化表头,或 Reservation ID 使用安全禁用表头。
|
||||
"""
|
||||
mapping: dict[str, str] = {}
|
||||
configs: dict[str, dict[str, Any]] = {}
|
||||
origins: dict[str, str] = {}
|
||||
collisions: list[dict[str, str]] = []
|
||||
forbidden: list[str] = []
|
||||
for raw in definition.get('fields') or []:
|
||||
if not isinstance(raw, dict) or not raw.get('enabled', True):
|
||||
continue
|
||||
field_code = str(raw.get('field_code') or '').strip()
|
||||
if field_code not in TABLE_FIELD_CODES:
|
||||
continue
|
||||
configs[field_code] = dict(raw)
|
||||
candidates = [field_code, raw.get('display_name'), *(raw.get('aliases') or [])]
|
||||
for candidate in candidates:
|
||||
normalized = normalize_table_header(candidate)
|
||||
if not normalized:
|
||||
continue
|
||||
if field_code == 'reservation_id' and normalized in RESERVATION_ID_FORBIDDEN_HEADERS:
|
||||
forbidden.append(str(candidate))
|
||||
continue
|
||||
previous = mapping.get(normalized)
|
||||
if previous and previous != field_code:
|
||||
collisions.append({
|
||||
'header': str(candidate),
|
||||
'normalized_header': normalized,
|
||||
'field_code': field_code,
|
||||
'conflicts_with': previous,
|
||||
'first_header': origins[normalized],
|
||||
})
|
||||
continue
|
||||
mapping[normalized] = field_code
|
||||
origins.setdefault(normalized, str(candidate))
|
||||
if collisions or forbidden:
|
||||
raise ValidationError(
|
||||
'Deterministic table header aliases are ambiguous or unsafe',
|
||||
code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID',
|
||||
details={'table_header_collisions': collisions, 'forbidden_reservation_headers': forbidden},
|
||||
)
|
||||
return TableHeaderContract(header_to_field=mapping, fields_by_code=configs)
|
||||
@@ -30,6 +30,7 @@ from app.models import (
|
||||
from app.services.shipping_notice.task_order_field_editor import (
|
||||
current_header_field_values_or_empty,
|
||||
current_line_field_values_or_empty,
|
||||
current_order_field_display_or_empty,
|
||||
)
|
||||
|
||||
EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
@@ -583,6 +584,7 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
|
||||
if projection == TaskProjection.DETAIL:
|
||||
step_payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
header = current_header_field_values_or_empty(task)
|
||||
order_field_display = current_order_field_display_or_empty(task)
|
||||
data = serialize_task(task, TaskProjection.SUMMARY)
|
||||
data.update({
|
||||
"customer_code": header.get('customer_code'),
|
||||
@@ -594,6 +596,9 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
|
||||
"export_version": task.export_version,
|
||||
"idempotency_key": task.idempotency_key,
|
||||
"lines": current_line_field_values_or_empty(task),
|
||||
"order_header": header,
|
||||
"order_header_fields": order_field_display['header_fields'],
|
||||
"order_line_fields": order_field_display['line_fields'],
|
||||
"shortage": task.shortage_json,
|
||||
"line_results": task.line_results_json or [],
|
||||
"parse_confidence": task.parse_confidence,
|
||||
|
||||
@@ -15,6 +15,7 @@ from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
ShippingOrderExtraction, ShippingOrderFieldDecision,
|
||||
ShippingOrderField,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingTask,
|
||||
@@ -71,6 +72,53 @@ def current_header_field_values_or_empty(task: ShippingTask) -> dict[str, Any]:
|
||||
return {}
|
||||
|
||||
|
||||
def current_order_field_display(task: ShippingTask) -> dict[str, Any]:
|
||||
"""按当前字段目录顺序展示锁定 Schema 字段,历史缺失字段回退版本 sequence。"""
|
||||
extraction = _current_extraction(task)
|
||||
global_sequences = {
|
||||
field.id: int(field.display_sequence or 0)
|
||||
for field in ShippingOrderField.query.filter_by(schema_id=extraction.schema_version.schema_id).all()
|
||||
}
|
||||
fields = sorted(
|
||||
[
|
||||
dict(item) for item in (extraction.schema_version.definition_json or {}).get('fields') or []
|
||||
if item.get('enabled', True)
|
||||
],
|
||||
key=lambda item: (
|
||||
global_sequences.get(str(item.get('field_id')), 1_000_000 + int(item.get('sequence') or 0)),
|
||||
int(item.get('sequence') or 0),
|
||||
str(item.get('field_code') or ''),
|
||||
),
|
||||
)
|
||||
return {
|
||||
'header_fields': [
|
||||
_display_field_config(item) for item in fields if item.get('field_category') == 'order_header'
|
||||
],
|
||||
'line_fields': [
|
||||
_display_field_config(item) for item in fields if item.get('field_category') == 'order_line'
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def current_order_field_display_or_empty(task: ShippingTask) -> dict[str, Any]:
|
||||
"""任务尚无已接受 Extraction 时返回空展示契约。"""
|
||||
try:
|
||||
return current_order_field_display(task)
|
||||
except ConflictError:
|
||||
return {'header_fields': [], 'line_fields': []}
|
||||
|
||||
|
||||
def _display_field_config(config: dict[str, Any]) -> dict[str, Any]:
|
||||
"""裁剪对话展示所需的字段标识、名称、位置与顺序。"""
|
||||
return {
|
||||
'field_code': str(config.get('field_code') or ''),
|
||||
'display_name': str(config.get('display_name') or config.get('field_code') or ''),
|
||||
'scope': str(config.get('scope') or ''),
|
||||
'value_type': str(config.get('value_type') or 'string'),
|
||||
'sequence': int(config.get('sequence') or 0),
|
||||
}
|
||||
|
||||
|
||||
def bump_order_data_version(task: ShippingTask) -> None:
|
||||
"""订单 FieldValue 发生业务变更后递增乐观锁版本。"""
|
||||
task.order_data_version = int(task.order_data_version or 1) + 1
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""
|
||||
用途:清理内部执行器误进入用户授权、收藏、默认应用和待审批申请的历史关系。
|
||||
依赖:f51a2b3c4d5e 订单上下文字段迁移;agents.exposure_mode 用户/内部角色划分。
|
||||
逻辑:仅移除或失效 exposure_mode=internal 的用户侧关系,不删除 Agent、内容或业务记录。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'a62b3c4d5e6f'
|
||||
down_revision = 'f51a2b3c4d5e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""移除内部执行器的用户侧授权状态,并拒绝尚未处理的历史权限申请。"""
|
||||
op.execute(
|
||||
"""
|
||||
DELETE FROM user_agent_permissions
|
||||
WHERE agent_id IN (SELECT id FROM agents WHERE exposure_mode = 'internal')
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"""
|
||||
DELETE FROM user_favorite_agents
|
||||
WHERE agent_id IN (SELECT id FROM agents WHERE exposure_mode = 'internal')
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"""
|
||||
DELETE FROM user_default_agents
|
||||
WHERE agent_id IN (SELECT id FROM agents WHERE exposure_mode = 'internal')
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"""
|
||||
UPDATE users
|
||||
SET default_agent_id = NULL
|
||||
WHERE default_agent_id IN (SELECT id FROM agents WHERE exposure_mode = 'internal')
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"""
|
||||
UPDATE permission_requests
|
||||
SET status = 'rejected', reviewed_at = CURRENT_TIMESTAMP
|
||||
WHERE status = 'pending'
|
||||
AND agent_id IN (SELECT id FROM agents WHERE exposure_mode = 'internal')
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""清理结果不可逆;回滚不得伪造已删除的用户授权和收藏关系。"""
|
||||
pass
|
||||
@@ -0,0 +1,115 @@
|
||||
"""Add order extraction progress, attention, and diagnostic audit foundation.
|
||||
|
||||
Revision ID: a63b4c5d6e7f
|
||||
Revises: a62b3c4d5e6f
|
||||
Create Date: 2026-07-21 13:30:00.000000
|
||||
|
||||
用途:为订单抽取 Run 增加当前进度投影、90天脱敏事件明细、管理员诊断审计与同会话单活动约束。
|
||||
依赖:shipping_order_extraction_runs、jobs、users。
|
||||
逻辑:建立进度数据基础,供现有 Dify 事件观察器写入脱敏技术事件并向用户投影通用阶段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'a63b4c5d6e7f'
|
||||
down_revision = 'a62b3c4d5e6f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""新增进度投影列、进度/诊断审计表及会话活动 Run 唯一约束。"""
|
||||
with op.batch_alter_table('shipping_order_extraction_runs') as batch_op:
|
||||
batch_op.add_column(sa.Column('progress_version', sa.Integer(), server_default='1', nullable=False))
|
||||
batch_op.add_column(sa.Column('current_stage_code', sa.String(length=64), nullable=True))
|
||||
batch_op.add_column(sa.Column('active_stage_codes_json', sa.JSON(), nullable=True))
|
||||
batch_op.add_column(sa.Column('completed_stage_codes_json', sa.JSON(), nullable=True))
|
||||
batch_op.add_column(sa.Column('progress_message_code', sa.String(length=128), nullable=True))
|
||||
batch_op.add_column(sa.Column('progress_health', sa.String(length=32), server_default='normal', nullable=False))
|
||||
batch_op.add_column(sa.Column('last_activity_at', sa.DateTime(), nullable=True))
|
||||
batch_op.add_column(sa.Column('progress_summary_json', sa.JSON(), nullable=True))
|
||||
batch_op.add_column(sa.Column('progress_mapping_version', sa.String(length=32), nullable=True))
|
||||
batch_op.add_column(sa.Column('attention_generated_at', sa.DateTime(), nullable=True))
|
||||
batch_op.add_column(sa.Column('seen_at', sa.DateTime(), nullable=True))
|
||||
|
||||
op.create_index(
|
||||
'uq_shipping_order_extraction_runs_active_conversation',
|
||||
'shipping_order_extraction_runs',
|
||||
['user_id', 'owner_agent_id', 'conversation_id'],
|
||||
unique=True,
|
||||
postgresql_where=sa.text("status IN ('queued', 'running', 'result_persisted')"),
|
||||
sqlite_where=sa.text("status IN ('queued', 'running', 'result_persisted')"),
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
'shipping_order_extraction_progress_events',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('run_id', sa.Integer(), nullable=False),
|
||||
sa.Column('job_id', sa.Integer(), 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('node_title', sa.String(length=255), 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.ForeignKeyConstraint(['job_id'], ['jobs.id']),
|
||||
sa.ForeignKeyConstraint(['run_id'], ['shipping_order_extraction_runs.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
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'])
|
||||
|
||||
op.create_table(
|
||||
'shipping_order_extraction_diagnostic_audits',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('admin_user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('run_id', sa.Integer(), nullable=True),
|
||||
sa.Column('action', sa.String(length=64), nullable=False),
|
||||
sa.Column('request_id', sa.String(length=64), nullable=True),
|
||||
sa.Column('query_summary_json', sa.JSON(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['admin_user_id'], ['users.id']),
|
||||
sa.ForeignKeyConstraint(['run_id'], ['shipping_order_extraction_runs.id']),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
op.create_index('ix_shipping_order_extraction_diagnostic_audits_run_created', 'shipping_order_extraction_diagnostic_audits', ['run_id', 'created_at'])
|
||||
op.create_index('ix_shipping_order_extraction_diagnostic_audits_admin_created', 'shipping_order_extraction_diagnostic_audits', ['admin_user_id', 'created_at'])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除尚未承载历史兼容职责的进度基础结构。"""
|
||||
op.drop_index('ix_shipping_order_extraction_diagnostic_audits_admin_created', table_name='shipping_order_extraction_diagnostic_audits')
|
||||
op.drop_index('ix_shipping_order_extraction_diagnostic_audits_run_created', table_name='shipping_order_extraction_diagnostic_audits')
|
||||
op.drop_table('shipping_order_extraction_diagnostic_audits')
|
||||
op.drop_index('ix_shipping_order_extraction_progress_events_workflow_node', table_name='shipping_order_extraction_progress_events')
|
||||
op.drop_index('ix_shipping_order_extraction_progress_events_expires_id', table_name='shipping_order_extraction_progress_events')
|
||||
op.drop_index('ix_shipping_order_extraction_progress_events_run_created', table_name='shipping_order_extraction_progress_events')
|
||||
op.drop_table('shipping_order_extraction_progress_events')
|
||||
op.drop_index('uq_shipping_order_extraction_runs_active_conversation', table_name='shipping_order_extraction_runs')
|
||||
with op.batch_alter_table('shipping_order_extraction_runs') as batch_op:
|
||||
batch_op.drop_column('seen_at')
|
||||
batch_op.drop_column('attention_generated_at')
|
||||
batch_op.drop_column('progress_mapping_version')
|
||||
batch_op.drop_column('progress_summary_json')
|
||||
batch_op.drop_column('last_activity_at')
|
||||
batch_op.drop_column('progress_health')
|
||||
batch_op.drop_column('progress_message_code')
|
||||
batch_op.drop_column('completed_stage_codes_json')
|
||||
batch_op.drop_column('active_stage_codes_json')
|
||||
batch_op.drop_column('current_stage_code')
|
||||
batch_op.drop_column('progress_version')
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
"""Remove sensitive order extraction progress node title.
|
||||
|
||||
Revision ID: a64c5d6e7f80
|
||||
Revises: a63b4c5d6e7f
|
||||
Create Date: 2026-07-21 15:50:00.000000
|
||||
|
||||
用途:停止持久化可能包含客户或业务意图的 Dify 自定义节点标题。
|
||||
依赖:a63b4c5d6e7f 创建的 shipping_order_extraction_progress_events。
|
||||
逻辑:仅移除诊断列;阶段映射继续使用受控事件类型和技术节点类型。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'a64c5d6e7f80'
|
||||
down_revision = 'a63b4c5d6e7f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""删除不再采集的自定义节点标题列。"""
|
||||
with op.batch_alter_table('shipping_order_extraction_progress_events') as batch_op:
|
||||
batch_op.drop_column('node_title')
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""仅为迁移回滚恢复可空列;运行时仍不会写入标题。"""
|
||||
with op.batch_alter_table('shipping_order_extraction_progress_events') as batch_op:
|
||||
batch_op.add_column(sa.Column('node_title', sa.String(length=255), nullable=True))
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Add persisted order extraction plans and document units.
|
||||
|
||||
Revision ID: a65d6e7f8091
|
||||
Revises: a64c5d6e7f80
|
||||
Create Date: 2026-07-21 18:00:00.000000
|
||||
|
||||
用途:为冻结 Run 建立可恢复的文档级抽取计划和局部状态单元。
|
||||
依赖:shipping_order_extraction_runs、shipping_notice_intakes、shipping_notice_documents。
|
||||
逻辑:每个 Run 唯一计划,每个冻结 Document 在计划内唯一;不复制正文或 Provider 凭据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'a65d6e7f8091'
|
||||
down_revision = 'a64c5d6e7f80'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建抽取计划与文档单元表。"""
|
||||
op.create_table(
|
||||
'shipping_order_extraction_plans',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('run_id', sa.Integer(), nullable=False),
|
||||
sa.Column('plan_version', sa.String(length=32), nullable=False),
|
||||
sa.Column('input_snapshot_hash', sa.String(length=64), nullable=False),
|
||||
sa.Column('status', sa.String(length=32), server_default='planned', nullable=False),
|
||||
sa.Column('unit_count', sa.Integer(), server_default='0', nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.CheckConstraint(
|
||||
"status IN ('planned', 'running', 'completed', 'partial_failed', 'failed')",
|
||||
name='ck_shipping_order_extraction_plans_status',
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
['run_id'], ['shipping_order_extraction_runs.id'], ondelete='CASCADE',
|
||||
),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('run_id', name='uq_shipping_order_extraction_plans_run'),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_extraction_plans_status_created',
|
||||
'shipping_order_extraction_plans',
|
||||
['status', 'created_at'],
|
||||
unique=False,
|
||||
)
|
||||
op.create_table(
|
||||
'shipping_order_extraction_units',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
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('position', sa.Integer(), nullable=False),
|
||||
sa.Column('unit_type', sa.String(length=32), nullable=False),
|
||||
sa.Column('document_type', sa.String(length=32), nullable=False),
|
||||
sa.Column('content_hash', sa.String(length=64), nullable=True),
|
||||
sa.Column('status', sa.String(length=32), server_default='pending', nullable=False),
|
||||
sa.Column('attempt_count', sa.Integer(), server_default='0', nullable=False),
|
||||
sa.Column('result_json', sa.JSON(), nullable=True),
|
||||
sa.Column('error_code', sa.String(length=64), nullable=True),
|
||||
sa.Column('error_message', sa.Text(), nullable=True),
|
||||
sa.Column('started_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('finished_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.CheckConstraint(
|
||||
"status IN ('pending', 'running', 'succeeded', 'failed', 'skipped')",
|
||||
name='ck_shipping_order_extraction_units_status',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"unit_type IN ('document_extraction', 'email_relation')",
|
||||
name='ck_shipping_order_extraction_units_type',
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
['intake_id'], ['shipping_notice_intakes.id'],
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
['document_id', 'intake_id'],
|
||||
['shipping_notice_documents.id', 'shipping_notice_documents.intake_id'],
|
||||
name='fk_shipping_order_extraction_units_document_intake',
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
['plan_id'], ['shipping_order_extraction_plans.id'], ondelete='CASCADE',
|
||||
),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint(
|
||||
'plan_id', 'document_id', name='uq_shipping_order_extraction_units_document',
|
||||
),
|
||||
sa.UniqueConstraint(
|
||||
'plan_id', 'position', name='uq_shipping_order_extraction_units_position',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_extraction_units_document',
|
||||
'shipping_order_extraction_units',
|
||||
['document_id'],
|
||||
unique=False,
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_extraction_units_plan_status',
|
||||
'shipping_order_extraction_units',
|
||||
['plan_id', 'status'],
|
||||
unique=False,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""按依赖顺序删除单元和计划表。"""
|
||||
op.drop_index(
|
||||
'ix_shipping_order_extraction_units_plan_status',
|
||||
table_name='shipping_order_extraction_units',
|
||||
)
|
||||
op.drop_index(
|
||||
'ix_shipping_order_extraction_units_document',
|
||||
table_name='shipping_order_extraction_units',
|
||||
)
|
||||
op.drop_table('shipping_order_extraction_units')
|
||||
op.drop_index(
|
||||
'ix_shipping_order_extraction_plans_status_created',
|
||||
table_name='shipping_order_extraction_plans',
|
||||
)
|
||||
op.drop_table('shipping_order_extraction_plans')
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Expand order extraction plan version capacity.
|
||||
|
||||
Revision ID: a66e7f8091a2
|
||||
Revises: a65d6e7f8091
|
||||
Create Date: 2026-07-21 19:15:00.000000
|
||||
|
||||
用途:修正订单抽取计划版本标识超过初始32字符列上限时无法创建 Run 的问题。
|
||||
依赖:a65d6e7f8091 创建的 shipping_order_extraction_plans。
|
||||
逻辑:仅扩展 plan_version 容量,不修改既有版本值或业务计划事实。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'a66e7f8091a2'
|
||||
down_revision = 'a65d6e7f8091'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""将计划版本列扩至64字符,保留所有已存计划记录。"""
|
||||
with op.batch_alter_table('shipping_order_extraction_plans') as batch_op:
|
||||
batch_op.alter_column(
|
||||
'plan_version',
|
||||
existing_type=sa.String(length=32),
|
||||
type_=sa.String(length=64),
|
||||
existing_nullable=False,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回滚到初始容量;只应在确认没有超过32字符的版本值时执行。"""
|
||||
with op.batch_alter_table('shipping_order_extraction_plans') as batch_op:
|
||||
batch_op.alter_column(
|
||||
'plan_version',
|
||||
existing_type=sa.String(length=64),
|
||||
type_=sa.String(length=32),
|
||||
existing_nullable=False,
|
||||
)
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Add global display sequence to order fields.
|
||||
|
||||
Revision ID: a67f8091a2b3
|
||||
Revises: a66e7f8091a2
|
||||
Create Date: 2026-07-21 20:40:00.000000
|
||||
|
||||
用途:保存订单字段目录的当前全局顺序,使页面刷新、草稿和发布版本之外仍有稳定排序。
|
||||
依赖:shipping_order_fields 稳定字段目录。
|
||||
逻辑:新增非空 display_sequence,并按当前字段编号稳定回填;版本快照 sequence 保持不变。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'a67f8091a2b3'
|
||||
down_revision = 'a66e7f8091a2'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""新增并回填字段目录全局显示顺序。"""
|
||||
op.add_column(
|
||||
'shipping_order_fields',
|
||||
sa.Column('display_sequence', sa.Integer(), nullable=False, server_default='0'),
|
||||
)
|
||||
connection = op.get_bind()
|
||||
rows = connection.execute(sa.text(
|
||||
'SELECT id FROM shipping_order_fields ORDER BY schema_id, field_code, id'
|
||||
)).fetchall()
|
||||
for sequence, row in enumerate(rows, start=1):
|
||||
connection.execute(
|
||||
sa.text('UPDATE shipping_order_fields SET display_sequence = :sequence WHERE id = :field_id'),
|
||||
{'sequence': sequence, 'field_id': row[0]},
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除字段目录全局显示顺序。"""
|
||||
op.drop_column('shipping_order_fields', 'display_sequence')
|
||||
@@ -6,7 +6,7 @@ tests/services/admin/test_permission_service.py
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.core.errors import ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import Agent, PermissionRequest, User
|
||||
from app.services.admin import permission_service
|
||||
|
||||
@@ -50,6 +50,31 @@ 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')
|
||||
@@ -77,3 +102,25 @@ 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
|
||||
@@ -3,8 +3,11 @@ tests/services/admin/test_user_service.py
|
||||
|
||||
用途:user_service 管理端用户 CRUD 单元测试。
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.services.admin import user_service
|
||||
|
||||
|
||||
@@ -52,3 +55,22 @@ def test_list_users_sort_by_username_and_department(app):
|
||||
|
||||
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
|
||||
@@ -3,8 +3,11 @@ tests/services/admin/test_wecom_admin_service.py
|
||||
|
||||
用途:wecom_admin_service 绑定统计单元测试。
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.services.admin import wecom_admin_service
|
||||
|
||||
|
||||
@@ -19,3 +22,27 @@ def test_binding_stats(app):
|
||||
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
|
||||
@@ -19,6 +19,7 @@ from app.services.shipping_notice.order_schema import service as order_schema_se
|
||||
|
||||
def _published_header_field(
|
||||
*, code: str = 'sender_email', available: bool = True, option_key: str | None = 'from_email',
|
||||
scope: str = 'header', field_category: str | None = None,
|
||||
) -> ShippingOrderField:
|
||||
"""创建已发布 Header 字段;available 决定是否能进入客户识别目录。"""
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
||||
@@ -27,15 +28,15 @@ def _published_header_field(
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
field = ShippingOrderField(
|
||||
schema_id=schema.id, field_code=code, scope='header', value_type='string',
|
||||
field_category='general_context' if option_key else 'order_header',
|
||||
schema_id=schema.id, field_code=code, scope=scope, value_type='string',
|
||||
field_category=field_category or ('general_context' if option_key else 'order_header'),
|
||||
collection_mode='deterministic_context' if option_key else 'llm_extraction',
|
||||
)
|
||||
db.session.add(field)
|
||||
db.session.flush()
|
||||
config = {
|
||||
'field_id': field.id, 'field_code': field.field_code, 'display_name': code,
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True,
|
||||
'scope': scope, 'value_type': 'string', 'enabled': True,
|
||||
'available_for_customer_identity': available, 'normalizer_key': 'lowercase_trim',
|
||||
}
|
||||
if option_key:
|
||||
@@ -78,18 +79,74 @@ def test_catalog_only_lists_published_identity_enabled_header_fields(app):
|
||||
assert 'source_adapters' not in catalog['catalog']
|
||||
|
||||
|
||||
def test_definition_uses_context_field_only_and_derives_automation(app):
|
||||
"""定义只保存 context_field_id;邮箱字段自动化上限由发布字段来源推导。"""
|
||||
def test_definition_uses_context_field_only_and_defaults_to_manual_review(app):
|
||||
"""定义只保存 context_field_id;未显式授权时任何字段都默认人工确认。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field()
|
||||
created = _definition(field)
|
||||
|
||||
assert created['context_field_id'] == field.id
|
||||
assert created['context_field']['field_code'] == 'sender_email'
|
||||
assert created['max_automation'] == 'conditional'
|
||||
assert created['max_automation'] == 'none'
|
||||
assert not {'source_adapter_key', 'source_selector', 'order_field_id', 'attribute_key'} & set(created)
|
||||
|
||||
|
||||
def test_order_header_field_can_be_identity_evidence_without_automatic_confirmation(app):
|
||||
"""订单信息 Header 可进入客户识别,但不能单独获得自动确认能力。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field(code='bill_to_customer', option_key=None)
|
||||
|
||||
created = _definition(field)
|
||||
catalog = service.list_definitions()
|
||||
|
||||
assert created['context_field_id'] == field.id
|
||||
assert created['max_automation'] == 'none'
|
||||
assert [item['field_id'] for item in catalog['context_fields']] == [field.id]
|
||||
|
||||
|
||||
def test_order_header_automation_can_be_explicitly_authorized(app):
|
||||
"""订单 Header 默认人工确认,但管理员可显式授权受控自动确认。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field(code='bill_to_customer', option_key=None)
|
||||
|
||||
created = _definition(field, automation='conditional')
|
||||
|
||||
assert created['max_automation'] == 'conditional'
|
||||
|
||||
|
||||
def test_order_line_field_cannot_be_enabled_for_customer_identity(app):
|
||||
"""货品明细即使发布快照误标为可识别,也不能进入目录或建立识别定义。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field(
|
||||
code='customer_part_number', option_key=None, scope='line', field_category='order_line',
|
||||
)
|
||||
|
||||
assert service.list_definitions()['context_fields'] == []
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
_definition(field)
|
||||
assert caught.value.code == 'SHIPPING.IDENTITY_ORDER_FIELD_INVALID'
|
||||
|
||||
|
||||
def test_published_rule_set_contains_saved_order_header_definition(app):
|
||||
"""保存规则集勾选后发布,客户证据目录必须读取同一份已发布 Header 定义。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field(code='bill_to_customer', option_key=None)
|
||||
definition = _definition(field)
|
||||
draft = service.create_rule_set({}, actor_id=1)
|
||||
saved = service.save_rule_set(draft['id'], {
|
||||
'expected_lock_version': draft['lock_version'], 'definition_ids': [definition['id']],
|
||||
}, actor_id=1)
|
||||
|
||||
published = service.publish_rule_set(
|
||||
draft['id'], expected_lock_version=saved['lock_version'], actor_id=1,
|
||||
)
|
||||
|
||||
published_ids = [item['id'] for item in published['definition']['definitions']]
|
||||
evidence_catalog = service.list_published_evidence_definitions(target_type='customer')
|
||||
assert published_ids == [definition['id']]
|
||||
assert [item['id'] for item in evidence_catalog['definitions']] == [definition['id']]
|
||||
|
||||
|
||||
def test_unpublished_or_identity_disabled_field_is_rejected(app):
|
||||
"""未开放客户识别的字段不能通过伪造 payload 建立定义。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -40,6 +40,74 @@ 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,6 +20,7 @@ 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,
|
||||
@@ -101,6 +102,13 @@ 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,6 +35,7 @@ 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,
|
||||
@@ -51,6 +52,7 @@ 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():
|
||||
@@ -58,6 +60,7 @@ 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},
|
||||
@@ -74,6 +77,7 @@ 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():
|
||||
|
||||
@@ -10,6 +10,8 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from copy import deepcopy
|
||||
from unittest.mock import patch
|
||||
from datetime import datetime, timedelta
|
||||
@@ -21,20 +23,28 @@ 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.handlers.shipping_order_extraction import (
|
||||
_execute_dify_unit_with_retry,
|
||||
run_shipping_order_extraction,
|
||||
)
|
||||
from app.jobs.queue import claim_next_job, recover_stale_jobs
|
||||
from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
Agent, AgentRuntimeBinding, Job, ShippingNoticeCandidate, ShippingOrderExtraction,
|
||||
ShippingOrderExtractionRun, User,
|
||||
Agent, AgentRuntimeBinding, Job, ShippingNoticeCandidate, ShippingNoticeDocument,
|
||||
ShippingOrderExtraction, ShippingOrderExtractionRun, ShippingOrderSchemaVersion, User,
|
||||
)
|
||||
from app.services.agent_runtime_binding_service import resolve_runtime_binding, save_runtime_binding
|
||||
from app.services.admin.agent_service import update_agent_permissions
|
||||
from app.services.admin.agent_service import list_agents
|
||||
from app.services.shipping_notice.order_extraction_workflow import (
|
||||
build_order_extraction_workflow_inputs, execute_order_extraction_workflow,
|
||||
parse_order_extraction_workflow_result, validate_unit_orders,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
create_order_extraction_run,
|
||||
retry_order_extraction_run,
|
||||
sync_order_extraction_run_after_job_recovery,
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
@@ -63,6 +73,59 @@ def test_binding_rejects_non_internal_or_non_workflow_provider(app):
|
||||
assert caught.value.code == 'AGENT.RUNTIME_PROVIDER_INVALID'
|
||||
|
||||
|
||||
def test_binding_catalog_exposes_internal_executor_role_constraint(app):
|
||||
"""订单抽取能力目录必须明确要求 internal_executor,避免仅靠界面约定。"""
|
||||
with app.app_context():
|
||||
owner = Agent(name='Owner', agent_code='shipping_notice', runtime_provider='hybrid')
|
||||
provider = Agent(
|
||||
name='Workflow Provider', agent_code='generic', runtime_provider='dify',
|
||||
dify_app_type='workflow', exposure_mode='internal', dify_app_id='workflow-provider',
|
||||
dify_api_key='key', api_base_url='http://dify.example/v1', is_active=True,
|
||||
)
|
||||
db.session.add_all([owner, provider])
|
||||
db.session.commit()
|
||||
|
||||
binding = save_runtime_binding(
|
||||
owner_agent_id=owner.id,
|
||||
capability_code='shipping.order_extraction',
|
||||
provider_agent_id=provider.id,
|
||||
enabled=True,
|
||||
config={},
|
||||
)
|
||||
assert binding.provider_agent.exposure_mode == 'internal'
|
||||
|
||||
|
||||
def test_internal_executor_cannot_receive_user_permissions(app):
|
||||
"""内部执行器只能被运行时绑定,不能进入用户授权关系。"""
|
||||
with app.app_context():
|
||||
user = User(username='internal-permission-user', email='internal-permission@example.com', password_hash='x')
|
||||
provider = Agent(
|
||||
name='Internal Workflow', agent_code='generic', runtime_provider='dify',
|
||||
dify_app_type='workflow', exposure_mode='internal', dify_app_id='provider',
|
||||
dify_api_key='key', api_base_url='http://dify.example/v1', is_active=True,
|
||||
)
|
||||
db.session.add_all([user, provider])
|
||||
db.session.commit()
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
update_agent_permissions(provider.id, [user.id])
|
||||
assert caught.value.code == 'AGENT.INTERNAL_EXECUTOR_PERMISSION_FORBIDDEN'
|
||||
|
||||
|
||||
def test_admin_agent_list_scopes_separate_applications_and_executors(app):
|
||||
"""管理页签后端列表必须按 workspace/internal 隔离。"""
|
||||
with app.app_context():
|
||||
application = Agent(name='Workspace App', exposure_mode='workspace', agent_code='generic')
|
||||
executor = Agent(
|
||||
name='Internal Executor', exposure_mode='internal',
|
||||
runtime_provider='dify', dify_app_type='workflow', dify_app_id='scope-provider',
|
||||
dify_api_key='key', api_base_url='http://dify.example/v1',
|
||||
)
|
||||
db.session.add_all([application, executor])
|
||||
db.session.commit()
|
||||
assert {item['exposure_mode'] for item in list_agents(scope='applications')} == {'workspace'}
|
||||
assert {item['exposure_mode'] for item in list_agents(scope='executors')} == {'internal'}
|
||||
|
||||
|
||||
def test_run_creation_requires_explicit_binding(app):
|
||||
"""删除显式绑定后创建 Run 必须阻断,且不得产生 Run 或 Job。"""
|
||||
with app.app_context():
|
||||
@@ -116,6 +179,18 @@ def test_runtime_binding_admin_api_and_internal_agent_hidden(app, client, admin_
|
||||
)
|
||||
assert saved.status_code == 200
|
||||
assert saved.get_json()['data']['provider_agent_id'] == provider_id
|
||||
assert saved.get_json()['data']['config'] == {
|
||||
'timeout_seconds': 600,
|
||||
'max_attempts': 2,
|
||||
'unit_concurrency': 2,
|
||||
'unit_max_attempts': 2,
|
||||
'unit_retry_backoff_ms': 500,
|
||||
'max_model_units': 20,
|
||||
'provider_max_concurrency': 4,
|
||||
'circuit_failure_threshold': 5,
|
||||
'circuit_cooldown_seconds': 60,
|
||||
'auto_create_enabled': False,
|
||||
}
|
||||
assert 'dify_api_key' not in saved.get_json()['data']
|
||||
|
||||
listed = client.get('/api/agents', headers=auth)
|
||||
@@ -361,38 +436,463 @@ def test_workflow_request_errors_are_classified(app, upstream_error, expected_co
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
provider = db.session.get(Agent, run.provider_agent_id)
|
||||
unit = run.extraction_plan.units[0]
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_workflow.DifyService.run_workflow_streaming',
|
||||
side_effect=upstream_error,
|
||||
), pytest.raises(Exception) as caught:
|
||||
execute_order_extraction_workflow(run=run, provider=provider, timeout_seconds=30)
|
||||
execute_order_extraction_workflow(run=run, unit=unit, provider=provider, timeout_seconds=30)
|
||||
|
||||
assert getattr(caught.value, 'code', None) == expected_code
|
||||
assert getattr(caught.value, 'retryable', False) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'workflow_result',
|
||||
[
|
||||
None,
|
||||
{'status': 'failed', 'error': 'inventory_source_hint must not be a line number'},
|
||||
{'status': 'succeeded', 'outputs': {'orders': 'not-json'}},
|
||||
],
|
||||
)
|
||||
def test_workflow_terminal_or_output_contract_errors_are_not_retryable(workflow_result):
|
||||
"""Dify 已返回终态的画布/输出错误不得触发 Unit 重试或 Provider 熔断。"""
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
parse_order_extraction_workflow_result(workflow_result)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE'
|
||||
assert caught.value.retryable is False
|
||||
|
||||
|
||||
def test_dify_terminal_contract_error_does_not_retry_or_open_circuit(app):
|
||||
"""Dify 已返回画布校验失败时,同一 Unit 不重复调用且不累计 Provider 熔断失败。"""
|
||||
error = ValidationError(
|
||||
'inventory_source_hint must not be a line number',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
run_snapshot = {
|
||||
'id': 1, 'run_no': 'SNER-CONTRACT-ERROR', 'user_id': 1,
|
||||
'input_snapshot_hash': 'a' * 64, 'input_snapshot_json': {},
|
||||
}
|
||||
unit_snapshot = {
|
||||
'id': 1, 'intake_id': 1, 'document_id': 1,
|
||||
'document_type': 'attachment', 'unit_type': 'document_extraction',
|
||||
}
|
||||
provider_snapshot = {'id': 998877, 'api_base_url': 'http://dify.example/v1', 'dify_api_key': 'key'}
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
side_effect=error,
|
||||
) as execute, patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.record_provider_failure',
|
||||
) as record_failure, pytest.raises(ValidationError) as caught:
|
||||
_execute_dify_unit_with_retry(
|
||||
app=app, run_snapshot=run_snapshot, unit_snapshot=unit_snapshot,
|
||||
provider_snapshot=provider_snapshot, timeout_seconds=30,
|
||||
max_attempts=3, backoff_ms=1, job_id=1, job_attempt=1,
|
||||
provider_max_concurrency=1, circuit_failure_threshold=2,
|
||||
circuit_cooldown_seconds=60,
|
||||
)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE'
|
||||
assert execute.call_count == 1
|
||||
record_failure.assert_not_called()
|
||||
|
||||
|
||||
def test_workflow_inputs_use_frozen_extraction_contract_only(app):
|
||||
"""Workflow 分离冻结 LLM 契约与只读上下文,完整定义和 documents 均不得旁路泄露。"""
|
||||
"""Workflow manifest 仅含冻结抽取契约与受控提示,完整定义不得旁路泄露。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
inputs = build_order_extraction_workflow_inputs(run)
|
||||
schema = json.loads(inputs['schema_contract'])
|
||||
documents = json.loads(inputs['documents'])
|
||||
readonly_context = json.loads(inputs['readonly_context'])
|
||||
unit = run.extraction_plan.units[0]
|
||||
inputs = build_order_extraction_workflow_inputs(run, unit=unit)
|
||||
manifest = json.loads(inputs['execution_manifest'])
|
||||
schema = manifest['extraction_contract']
|
||||
documents = manifest['documents']
|
||||
readonly_context = manifest['readonly_hints']
|
||||
|
||||
assert schema == run.input_snapshot_json['schema']['extraction_contract']
|
||||
assert manifest['contract_version'] == 'shipping_order_extraction.unit.v2'
|
||||
assert manifest['run']['run_no'] == run.run_no
|
||||
assert manifest['unit']['unit_id'] == unit.id
|
||||
assert manifest['unit']['document_id'] == unit.document_id
|
||||
assert manifest['integrity']['input_snapshot_hash'] == run.input_snapshot_hash
|
||||
assert 'definition' not in schema
|
||||
assert schema['fields'][0]['field_id'] == 'qty-id'
|
||||
assert 'deterministic_context' not in documents[0]
|
||||
assert 'sales-' not in inputs['documents'].lower()
|
||||
assert len(documents) == 1
|
||||
assert set(documents[0]) == {'intake_id', 'intake_no', 'document'}
|
||||
assert documents[0]['document']['document_id'] == unit.document_id
|
||||
assert 'sales-' not in repr(documents).lower()
|
||||
assert readonly_context == []
|
||||
assert set(inputs) == {
|
||||
'run_no', 'input_snapshot_hash', 'schema_contract', 'documents', 'readonly_context',
|
||||
assert set(inputs) == {'execution_manifest'}
|
||||
|
||||
|
||||
def test_workflow_execution_sends_only_versioned_manifest(app):
|
||||
"""Workflow 调用边界只能发送 execution_manifest,禁止回退到旧五变量契约。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
provider = db.session.get(Agent, run.provider_agent_id)
|
||||
unit = run.extraction_plan.units[0]
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_workflow.DifyService.run_workflow_streaming',
|
||||
return_value={'status': 'succeeded', 'outputs': {'orders': []}, 'workflow_run_id': 'wf-manifest'},
|
||||
) as mocked_run:
|
||||
orders, metadata = execute_order_extraction_workflow(
|
||||
run=run, unit=unit, provider=provider, timeout_seconds=30,
|
||||
)
|
||||
|
||||
inputs = mocked_run.call_args.kwargs['inputs']
|
||||
manifest = json.loads(inputs['execution_manifest'])
|
||||
assert set(inputs) == {'execution_manifest'}
|
||||
assert manifest['contract_version'] == 'shipping_order_extraction.unit.v2'
|
||||
assert manifest['run']['run_no'] == run.run_no
|
||||
assert manifest['unit']['unit_id'] == unit.id
|
||||
assert manifest['integrity']['input_snapshot_hash'] == run.input_snapshot_hash
|
||||
assert orders == []
|
||||
assert metadata['workflow_run_id'] == 'wf-manifest'
|
||||
|
||||
|
||||
def test_deterministic_complete_table_skips_dify_and_persists_unit_result(app):
|
||||
"""冻结 Schema 可完整解析的表格单元必须零模型调用,并缓存可恢复的局部订单。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='DETERMINISTIC')
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
version.definition_json = {'fields': [
|
||||
{
|
||||
'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'required': True,
|
||||
'aliases': ['Part Number'], 'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
{
|
||||
'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line',
|
||||
'value_type': 'decimal', 'enabled': True, 'required': True,
|
||||
'aliases': ['Qty'], 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal'],
|
||||
},
|
||||
]}
|
||||
document.extracted_text = 'Part Number\tQty\nPN-001\t3'
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='deterministic-worker',
|
||||
)
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
) as execute, patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
return_value={
|
||||
'batch_no': None, 'created_count': 0, 'opened_existing_count': 0,
|
||||
'pending_count': 0, 'non_shipping_count': 0,
|
||||
},
|
||||
) as submit:
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
finished = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
unit = finished.extraction_plan.units[0]
|
||||
assert execute.call_count == 0
|
||||
assert submit.call_args.kwargs['orders'][0]['lines'][0]['fields']
|
||||
assert unit.status == 'succeeded'
|
||||
assert unit.result_json['workflow']['execution_mode'] == 'deterministic'
|
||||
assert finished.provider_result_json['workflow']['deterministic_unit_count'] == 1
|
||||
|
||||
|
||||
def test_unit_manifest_never_contains_sibling_document(app):
|
||||
"""单元级模型输入只能包含当前冻结 Document,禁止重新拼成整封邮件。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, first = _seed_run_input(suffix='COMPACT')
|
||||
second = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='attachment',
|
||||
attachment_key='second.pdf',
|
||||
filename='second.pdf',
|
||||
content_hash='d' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='SIBLING-SECRET-CONTENT',
|
||||
)
|
||||
db.session.add(second)
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = next(item for item in run.extraction_plan.units if item.document_id == first.id)
|
||||
|
||||
manifest = json.loads(build_order_extraction_workflow_inputs(
|
||||
run, unit=unit,
|
||||
)['execution_manifest'])
|
||||
|
||||
assert len(manifest['documents']) == 1
|
||||
assert manifest['documents'][0]['document']['document_id'] == first.id
|
||||
assert 'SIBLING-SECRET-CONTENT' not in repr(manifest)
|
||||
|
||||
|
||||
def test_unit_result_cannot_reference_sibling_document(app):
|
||||
"""即使模型猜到兄弟 Document ID,单元边界也必须在局部结果落库前拒绝。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, first = _seed_run_input(suffix='UNIT-SCOPE')
|
||||
second = ShippingNoticeDocument(
|
||||
intake_id=intake.id, document_type='attachment', attachment_key='sibling.pdf',
|
||||
content_hash='e' * 64, classification='order_notice', parse_status='parsed',
|
||||
extracted_text='Sibling evidence',
|
||||
)
|
||||
db.session.add(second)
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = next(item for item in run.extraction_plan.units if item.document_id == first.id)
|
||||
orders = [{
|
||||
'source_intake_no': intake.intake_no,
|
||||
'primary_document_id': first.id,
|
||||
'header_fields': [],
|
||||
'lines': [{'fields': [{
|
||||
'field_id': 'qty-id',
|
||||
'observations': [{'value': 1, 'document_id': second.id, 'quote': 'Sibling evidence'}],
|
||||
}]}],
|
||||
}]
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
validate_unit_orders(run, unit=unit, orders=orders)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE'
|
||||
|
||||
|
||||
def test_worker_runs_dify_units_with_frozen_concurrency_limit(app):
|
||||
"""多个模型单元应实际并行,且同时在途数量不得超过 Run 冻结配置。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _first = _seed_run_input(suffix='PARALLEL')
|
||||
for index in range(2):
|
||||
db.session.add(ShippingNoticeDocument(
|
||||
intake_id=intake.id, document_type='attachment',
|
||||
attachment_key=f'parallel-{index}.pdf', content_hash=str(index + 1) * 64,
|
||||
classification='order_notice', parse_status='parsed',
|
||||
extracted_text=f'Unstructured document {index}',
|
||||
))
|
||||
binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one()
|
||||
binding.config_json = {
|
||||
'timeout_seconds': 900, 'max_attempts': 3, 'unit_concurrency': 2,
|
||||
'unit_max_attempts': 1, 'unit_retry_backoff_ms': 100,
|
||||
}
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='parallel-worker',
|
||||
)
|
||||
lock = threading.Lock()
|
||||
active = 0
|
||||
peak = 0
|
||||
|
||||
def execute(*, unit, **_kwargs):
|
||||
nonlocal active, peak
|
||||
with lock:
|
||||
active += 1
|
||||
peak = max(peak, active)
|
||||
time.sleep(0.08)
|
||||
with lock:
|
||||
active -= 1
|
||||
return [], {'workflow_run_id': f'wf-{unit.id}', 'provider_status': 'succeeded'}
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
side_effect=execute,
|
||||
), patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
return_value={
|
||||
'batch_no': None, 'created_count': 0, 'opened_existing_count': 0,
|
||||
'pending_count': 0, 'non_shipping_count': 0,
|
||||
},
|
||||
):
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
finished = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
assert peak == 2
|
||||
assert finished.provider_result_json['workflow']['unit_concurrency'] == 2
|
||||
assert finished.provider_result_json['workflow']['dify_unit_count'] == 3
|
||||
assert all(unit.status == 'succeeded' for unit in finished.extraction_plan.units)
|
||||
|
||||
|
||||
def test_worker_retries_only_failed_unit_locally(app):
|
||||
"""单元首次网络失败后只重试该单元,并保存 attempt/latency 指标。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='LOCAL-RETRY')
|
||||
binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one()
|
||||
binding.config_json = {
|
||||
'timeout_seconds': 900, 'max_attempts': 3, 'unit_concurrency': 2,
|
||||
'unit_max_attempts': 2, 'unit_retry_backoff_ms': 100,
|
||||
}
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='local-retry-worker',
|
||||
)
|
||||
calls = 0
|
||||
|
||||
def execute(**_kwargs):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls == 1:
|
||||
raise requests.exceptions.ReadTimeout('temporary slow unit')
|
||||
return [], {'workflow_run_id': 'wf-local-retry', 'provider_status': 'succeeded'}
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
side_effect=execute,
|
||||
), patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
return_value={
|
||||
'batch_no': None, 'created_count': 0, 'opened_existing_count': 0,
|
||||
'pending_count': 0, 'non_shipping_count': 0,
|
||||
},
|
||||
):
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
unit = db.session.get(ShippingOrderExtractionRun, run.id).extraction_plan.units[0]
|
||||
assert calls == 2
|
||||
assert unit.status == 'succeeded'
|
||||
assert unit.attempt_count == 2
|
||||
assert unit.result_json['workflow']['attempts'] == 2
|
||||
assert unit.result_json['workflow']['latency_ms'] >= 100
|
||||
|
||||
|
||||
def test_worker_persists_successful_units_when_one_unit_exhausts_retries(app):
|
||||
"""一个单元永久失败时,成功单元仍提交,Run 以 needs_review 收口。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, first = _seed_run_input(suffix='PARTIAL')
|
||||
second = ShippingNoticeDocument(
|
||||
intake_id=intake.id, document_type='attachment', attachment_key='partial-2.pdf',
|
||||
content_hash='f' * 64, classification='order_notice', parse_status='parsed',
|
||||
extracted_text='Second unstructured document',
|
||||
)
|
||||
db.session.add(second)
|
||||
binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one()
|
||||
binding.config_json = {
|
||||
'timeout_seconds': 900, 'max_attempts': 1, 'unit_concurrency': 2,
|
||||
'unit_max_attempts': 1, 'unit_retry_backoff_ms': 100,
|
||||
}
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='partial-worker',
|
||||
)
|
||||
submitted = {}
|
||||
|
||||
def execute(*, unit, **_kwargs):
|
||||
if unit.document_id == second.id:
|
||||
raise requests.exceptions.ReadTimeout('permanent unit timeout')
|
||||
return [], {'workflow_run_id': f'wf-{first.id}', 'provider_status': 'succeeded'}
|
||||
|
||||
def submit(*, orders, **_kwargs):
|
||||
submitted['orders'] = orders
|
||||
return {
|
||||
'batch_no': None, 'created_count': 0, 'opened_existing_count': 0,
|
||||
'pending_count': 0, 'non_shipping_count': 0,
|
||||
}
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
side_effect=execute,
|
||||
), patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
side_effect=submit,
|
||||
):
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
finished = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
statuses = {unit.document_id: unit.status for unit in finished.extraction_plan.units}
|
||||
assert submitted['orders'] == []
|
||||
assert statuses[first.id] == 'succeeded'
|
||||
assert statuses[second.id] == 'failed'
|
||||
assert finished.status == 'needs_review'
|
||||
assert finished.result_json['failed_unit_count'] == 1
|
||||
|
||||
|
||||
def test_worker_blocks_model_calls_when_frozen_unit_budget_is_exceeded(app):
|
||||
"""需要模型的文档数超过 Run 冻结预算时必须在发请求前阻断。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='BUDGET')
|
||||
db.session.add(ShippingNoticeDocument(
|
||||
intake_id=intake.id, document_type='attachment', attachment_key='budget-2.pdf',
|
||||
content_hash='9' * 64, classification='order_notice', parse_status='parsed',
|
||||
extracted_text='Another unstructured document',
|
||||
))
|
||||
binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one()
|
||||
binding.config_json = {
|
||||
'timeout_seconds': 900, 'max_attempts': 1, 'unit_concurrency': 2,
|
||||
'unit_max_attempts': 1, 'unit_retry_backoff_ms': 100,
|
||||
'max_model_units': 1, 'provider_max_concurrency': 4,
|
||||
'circuit_failure_threshold': 5, 'circuit_cooldown_seconds': 60,
|
||||
}
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='budget-worker',
|
||||
)
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
) as execute:
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
assert execute.call_count == 0
|
||||
failed = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
assert failed.status == 'failed'
|
||||
assert failed.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_MODEL_BUDGET_EXCEEDED'
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'orders_output',
|
||||
[
|
||||
[{'classification': 'shipping_request'}],
|
||||
json.dumps([{'classification': 'shipping_request'}]),
|
||||
json.dumps(json.dumps([{'classification': 'shipping_request'}])),
|
||||
json.dumps({'orders': [{'classification': 'shipping_request'}]}),
|
||||
{'orders': json.dumps([{'classification': 'shipping_request'}])},
|
||||
],
|
||||
)
|
||||
def test_workflow_result_accepts_dify_orders_serialization_variants(orders_output):
|
||||
"""Dify End 的数组和最多两层 String 包装均须还原为订单数组。"""
|
||||
assert parse_order_extraction_workflow_result({
|
||||
'status': 'succeeded', 'outputs': {'orders': orders_output},
|
||||
}) == [{'classification': 'shipping_request'}]
|
||||
|
||||
|
||||
def test_workflow_readonly_context_uses_run_frozen_values(app):
|
||||
@@ -414,7 +914,10 @@ def test_workflow_readonly_context_uses_run_frozen_values(app):
|
||||
intake.structured_result_json = {'email': {'from': 'changed@later.example'}}
|
||||
db.session.commit()
|
||||
|
||||
readonly_context = json.loads(build_order_extraction_workflow_inputs(run)['readonly_context'])
|
||||
manifest = json.loads(build_order_extraction_workflow_inputs(
|
||||
run, unit=run.extraction_plan.units[0],
|
||||
)['execution_manifest'])
|
||||
readonly_context = manifest['readonly_hints']
|
||||
|
||||
assert readonly_context[0]['fields'][0]['value'] == 'frozen@example.com'
|
||||
assert 'changed@later.example' not in repr(readonly_context)
|
||||
@@ -465,6 +968,48 @@ def test_worker_recovers_persisted_run_facts_without_duplicate_dify(app):
|
||||
assert db.session.get(Job, job.id).status == 'success'
|
||||
|
||||
|
||||
def test_manual_retry_reuses_cached_provider_result_without_duplicate_dify(app):
|
||||
"""失败卡片手工重试若已有 Provider 成功结果,只重跑 HXOPS 落库阶段。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='MANUAL-RETRY-CACHE')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
original_job = db.session.get(Job, run.current_job_id)
|
||||
run.provider_result_json = {'orders': [], 'workflow': {'workflow_run_id': 'wf-manual-cache'}}
|
||||
transition_order_extraction_run(run, target_status='running', phase='persisting_result')
|
||||
transition_order_extraction_run(run, target_status='failed', error_message='database temporarily failed')
|
||||
original_job.status = 'failed'
|
||||
db.session.commit()
|
||||
|
||||
retried, reused = retry_order_extraction_run(user_id=user.id, run_no=run.run_no)
|
||||
db.session.commit()
|
||||
assert reused is False
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], worker_id='manual-retry-worker',
|
||||
)
|
||||
assert job.id == retried.current_job_id
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
) as execute, patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
return_value={
|
||||
'batch_no': None,
|
||||
'created_count': 0,
|
||||
'opened_existing_count': 0,
|
||||
'pending_count': 0,
|
||||
'non_shipping_count': 0,
|
||||
},
|
||||
):
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
assert execute.call_count == 0
|
||||
assert db.session.get(ShippingOrderExtractionRun, run.id).status == 'completed'
|
||||
assert db.session.get(Job, job.id).status == 'success'
|
||||
|
||||
|
||||
def test_worker_recovers_consumed_empty_result_without_duplicate_dify(app):
|
||||
"""空订单/非发货结果已消费 Intake 后,重试应补 submission 并完成 Run。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -85,6 +85,43 @@ def test_workflow_streaming_normal_finished(monkeypatch):
|
||||
assert result["_workflow_retry_count"] == 0
|
||||
|
||||
|
||||
def test_workflow_streaming_observer_normalizes_node_events_and_isolates_failure(monkeypatch):
|
||||
"""节点事件应脱敏传给观察器;观察器抛错不能阻断 Workflow 结果。"""
|
||||
lines = _sse_lines(
|
||||
{"event": "workflow_started", "data": {"workflow_run_id": "wf-observe"}},
|
||||
{
|
||||
"event": "node_started",
|
||||
"data": {
|
||||
"workflow_run_id": "wf-observe",
|
||||
"node_execution_id": "node-exec-1",
|
||||
"node_data": {"type": "llm", "title": "Extract orders"},
|
||||
"inputs": {"secret": "must not be forwarded"},
|
||||
},
|
||||
},
|
||||
{"event": "workflow_finished", "data": {"status": "succeeded", "workflow_run_id": "wf-observe"}},
|
||||
)
|
||||
_mock_stream_response(monkeypatch, lines=lines)
|
||||
observed = []
|
||||
|
||||
def _observer(event):
|
||||
observed.append(event)
|
||||
if event["event_type"] == "node_started":
|
||||
raise RuntimeError("diagnostics unavailable")
|
||||
|
||||
result = DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"}, event_observer=_observer)
|
||||
|
||||
assert result["status"] == "succeeded"
|
||||
node_event = next(event for event in observed if event["event_type"] == "node_started")
|
||||
assert node_event == {
|
||||
"event_type": "node_started",
|
||||
"workflow_run_id": "wf-observe",
|
||||
"node_execution_id": "node-exec-1",
|
||||
"node_type": "llm",
|
||||
"node_title": "Extract orders",
|
||||
"event_status": None,
|
||||
}
|
||||
|
||||
|
||||
def test_workflow_streaming_read_timeout_polls_success(monkeypatch):
|
||||
lines = _sse_lines({"event": "workflow_started", "data": {"workflow_run_id": "wf-poll"}})
|
||||
_mock_stream_response(
|
||||
|
||||
@@ -103,6 +103,98 @@ def test_worker_keeps_same_profile_sources_in_one_session_group():
|
||||
assert [item['source_code'] for item in grouped[('dsv360', 'DBS_US_B')]] == ['DBS_CMH']
|
||||
|
||||
|
||||
def test_worker_opens_clean_page_without_discarding_shared_login_context():
|
||||
"""批量第二站必须隔离上一站报表页,但继续使用同一浏览器登录上下文。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
closed: list[str] = []
|
||||
|
||||
class _PreviousPage:
|
||||
def close(self) -> None:
|
||||
closed.append('previous')
|
||||
|
||||
class _Context:
|
||||
def new_page(self) -> str:
|
||||
return 'fresh-page'
|
||||
|
||||
assert worker._open_clean_batch_page(_Context(), _PreviousPage()) == 'fresh-page'
|
||||
assert closed == ['previous']
|
||||
|
||||
|
||||
def test_dsv_sso_blank_transition_refreshes_once_before_portal_wait(monkeypatch):
|
||||
"""登录后空白授权页只刷新一次,随后回 Portal 时立即结束 SSO 等待。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
session = worker.dsv_session
|
||||
import dsv_auth
|
||||
events: list[str] = []
|
||||
clock = {'value': 0.0}
|
||||
|
||||
class _Page:
|
||||
url = 'https://auth.dbschenker.com/as/authorization.ping'
|
||||
|
||||
def title(self) -> str:
|
||||
return ''
|
||||
|
||||
def reload(self, **_kwargs) -> None:
|
||||
events.append('reload')
|
||||
self.url = 'https://s360.dbschenker.com/main/portal'
|
||||
|
||||
def monotonic() -> float:
|
||||
clock['value'] += 3.0
|
||||
return clock['value']
|
||||
|
||||
monkeypatch.setenv('SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS', '5000')
|
||||
monkeypatch.setattr(session.time, 'monotonic', monotonic)
|
||||
monkeypatch.setattr(session.time, 'sleep', lambda _seconds: None)
|
||||
monkeypatch.setattr(session, '_debug_dsv_stage', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(session, '_report_debug_event', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(session, '_has_dsv_report_nav_usable', lambda page: 's360.dbschenker.com' in page.url)
|
||||
monkeypatch.setattr(session, '_wait_for_visible_selector', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(session, '_is_dsv_on_portal_home', lambda _page: False)
|
||||
monkeypatch.setattr(session, '_has_dsv_portal_shell', lambda _page: False)
|
||||
monkeypatch.setattr(dsv_auth, 'is_dsv_blank_auth_transition', lambda _page: True)
|
||||
monkeypatch.setattr(dsv_auth, 'has_dsv_password_upgrade_prompt', lambda *_args, **_kwargs: False)
|
||||
|
||||
assert session._wait_for_dsv_app_after_login(_Page(), timeout_ms=1_000) is True
|
||||
# 关键断言:空白授权页只允许一次受控刷新,避免对认证服务形成循环压力。
|
||||
assert events == ['reload']
|
||||
|
||||
|
||||
def test_dsv_sso_return_timeout_is_explicit(monkeypatch):
|
||||
"""认证页持续不回 Portal 时,必须报 SSO 回跳超时而非笼统的测试超时。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
session = worker.dsv_session
|
||||
import dsv_auth
|
||||
monkeypatch.setenv('SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS', '30000')
|
||||
|
||||
class _Page:
|
||||
url = 'https://auth.dbschenker.com/as/authorization.ping'
|
||||
|
||||
def title(self) -> str:
|
||||
return ''
|
||||
|
||||
def reload(self, **_kwargs) -> None:
|
||||
pass
|
||||
|
||||
ticks = iter([0.0, 0.0, 0.0, 0.0, 0.0, 31.0, 31.0, 31.0])
|
||||
|
||||
def monotonic() -> float:
|
||||
return next(ticks)
|
||||
|
||||
monkeypatch.setattr(session.time, 'monotonic', monotonic)
|
||||
monkeypatch.setattr(session.time, 'sleep', lambda _seconds: None)
|
||||
monkeypatch.setattr(session, '_debug_dsv_stage', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(session, '_report_debug_event', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(session, '_has_dsv_report_nav_usable', lambda _page: False)
|
||||
monkeypatch.setattr(session, '_wait_for_visible_selector', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(session, '_is_dsv_on_portal_home', lambda _page: False)
|
||||
monkeypatch.setattr(session, '_has_dsv_portal_shell', lambda _page: False)
|
||||
monkeypatch.setattr(dsv_auth, 'is_dsv_blank_auth_transition', lambda _page: False)
|
||||
monkeypatch.setattr(dsv_auth, 'has_dsv_password_upgrade_prompt', lambda *_args, **_kwargs: False)
|
||||
|
||||
with pytest.raises(RuntimeError, match='SSO authorization return timed out'):
|
||||
session._wait_for_dsv_app_after_login(_Page(), timeout_ms=1_000)
|
||||
|
||||
|
||||
def test_worker_uses_profile_envelope_only_within_execution_scope(monkeypatch):
|
||||
"""worker 解密 Profile 密文后必须在退出执行范围时恢复原有环境。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""
|
||||
用途:验证内部执行器不会通过用户列表、详情、授权序列化或统一访问策略暴露。
|
||||
依赖:通用 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'
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""
|
||||
用途:验证内部执行器用户侧历史关系清理迁移的数据边界与幂等性。
|
||||
依赖: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'
|
||||
|
||||
@@ -486,6 +486,32 @@ def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
|
||||
assert ShippingInventoryConfigurationTestRun.query.filter_by(run_no=started['run_no']).one().analysis_id is None
|
||||
|
||||
|
||||
def test_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, tmp_path):
|
||||
"""同连接批量站点在 Worker 串行等待时,不得按单站时限提前失败。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS'] = 10
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
first = _source('TIMEOUT_QUEUE_A', 'TIMEOUT_QUEUE_LOGIN')
|
||||
second = _source('TIMEOUT_QUEUE_B', 'TIMEOUT_QUEUE_LOGIN_B')
|
||||
second_model = db.session.get(ShippingInventorySource, second['id'])
|
||||
second_model.rpa_profile_id = first['rpa_profile_id']
|
||||
second_model.config_version += 1
|
||||
db.session.commit()
|
||||
seed = _complete_test_run(first, tmp_path)
|
||||
profile = _publish_profile_from_analysis(seed['analysis_id'], _published_order_field(), code='TIMEOUT_QUEUE_PROFILE')
|
||||
shipping_inventory_service.bind_source_parsing_profile([first['id'], second['id']], profile['id'], actor_id=None, operation='bulk')
|
||||
batch = inventory_configuration_test.start_batch_test_export([first['id'], second['id']], actor_id=None)
|
||||
queued_run = ShippingInventoryConfigurationTestRun.query.filter_by(inventory_source_id=second['id']).one()
|
||||
queued_run.created_at = datetime.utcnow() - timedelta(seconds=15)
|
||||
db.session.commit()
|
||||
|
||||
recovered = inventory_configuration_test.get_validation_batch(batch['id'])
|
||||
# 关键断言:第二站可等待同组第一站完成,20 秒总窗口内不应被单站 10 秒误判。
|
||||
assert next(run for run in recovered['runs'] if run['inventory_source_id'] == second['id'])['status'] == 'awaiting_rpa'
|
||||
|
||||
|
||||
def test_confirming_test_profile_binds_only_compatible_published_profile(app, tmp_path):
|
||||
"""确认本次测试推荐的已发布方案后,才绑定库存站点并形成有效测试证据。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
backend/tests/test_order_extraction_merge.py
|
||||
|
||||
用途:验证跨文档订单保守合并、证据保留与错误拆分边界。
|
||||
依赖:order_extraction_merge、冻结 Schema 稳定字段 ID。
|
||||
逻辑:PO 或强行身份可合并;弱身份不得合并;冲突 Observation 全量保留给后续裁决。
|
||||
"""
|
||||
|
||||
from app.services.shipping_notice.order_extraction_merge import merge_unit_orders
|
||||
|
||||
|
||||
DEFINITION = {'fields': [
|
||||
{'field_id': 'po-id', 'field_code': 'po_number'},
|
||||
{'field_id': 'part-id', 'field_code': 'part_number'},
|
||||
{'field_id': 'res-id', 'field_code': 'reservation_id'},
|
||||
{'field_id': 'qty-id', 'field_code': 'qty'},
|
||||
]}
|
||||
|
||||
|
||||
def _field(field_id, value, document_id):
|
||||
return {'field_id': field_id, 'observations': [{
|
||||
'value': value, 'document_id': document_id, 'quote': str(value), 'confidence': 0.9,
|
||||
}]}
|
||||
|
||||
|
||||
def _order(document_id, *, po='PO-1', part='PN-1', reservation='R-1', qty=1):
|
||||
return {
|
||||
'source_intake_no': 'SNI-1', 'primary_document_id': document_id,
|
||||
'header_fields': [_field('po-id', po, document_id)] if po else [],
|
||||
'lines': [{'fields': [
|
||||
_field('part-id', part, document_id), _field('res-id', reservation, document_id),
|
||||
_field('qty-id', qty, document_id),
|
||||
]}],
|
||||
}
|
||||
|
||||
|
||||
def test_same_po_merges_observations_and_preserves_conflicting_values():
|
||||
"""同一 PO 合并后 Qty 冲突证据必须同时存在,交由动态字段裁决阻断。"""
|
||||
merged = merge_unit_orders(
|
||||
orders=[_order(1, qty=1), _order(2, qty=2)], schema_definition=DEFINITION,
|
||||
)
|
||||
|
||||
assert len(merged) == 1
|
||||
assert merged[0]['source_document_ids'] == [1, 2]
|
||||
qty = next(item for item in merged[0]['lines'][0]['fields'] if item['field_id'] == 'qty-id')
|
||||
assert {item['value'] for item in qty['observations']} == {1, 2}
|
||||
|
||||
|
||||
def test_part_number_without_same_reservation_does_not_merge_without_po():
|
||||
"""只有料号相同属于弱身份,Reservation 不同且无 PO 时必须保持两个订单。"""
|
||||
merged = merge_unit_orders(
|
||||
orders=[
|
||||
_order(1, po='', reservation='R-1'),
|
||||
_order(2, po='', reservation='R-2'),
|
||||
],
|
||||
schema_definition=DEFINITION,
|
||||
)
|
||||
|
||||
assert len(merged) == 2
|
||||
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
backend/tests/test_order_extraction_plan_migration.py
|
||||
|
||||
用途:隔离验证抽取计划与文档单元迁移可完整 upgrade/downgrade。
|
||||
依赖:Alembic Operations、SQLAlchemy 内存数据库、a65d6e7f8091 增量迁移。
|
||||
逻辑:构造最小前置外键表,检查表/约束/索引后回滚且无残留。
|
||||
"""
|
||||
|
||||
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('shipping_order_extraction_runs', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table('shipping_notice_intakes', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table(
|
||||
'shipping_notice_documents', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('intake_id', sa.Integer(), nullable=False),
|
||||
sa.UniqueConstraint('id', 'intake_id'),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
|
||||
def test_order_extraction_plan_migration_round_trip():
|
||||
"""迁移应建立计划/单元唯一性和状态结构,并可完整回滚。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_pre_migration_schema(engine)
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.a65d6e7f8091_add_order_extraction_plans'
|
||||
)
|
||||
with engine.begin() as connection:
|
||||
original_op = migration.op
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
try:
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert {
|
||||
'shipping_order_extraction_plans', 'shipping_order_extraction_units',
|
||||
} <= set(inspector.get_table_names())
|
||||
assert {
|
||||
'plan_version', 'input_snapshot_hash', 'status', 'unit_count',
|
||||
} <= {column['name'] for column in inspector.get_columns('shipping_order_extraction_plans')}
|
||||
plan_version = next(column for column in inspector.get_columns('shipping_order_extraction_plans') if column['name'] == 'plan_version')
|
||||
assert plan_version['type'].length == 32
|
||||
assert {
|
||||
'plan_id', 'intake_id', 'document_id', 'unit_type', 'content_hash',
|
||||
'attempt_count', 'result_json', 'error_code',
|
||||
} <= {column['name'] for column in inspector.get_columns('shipping_order_extraction_units')}
|
||||
assert {
|
||||
constraint['name'] for constraint in inspector.get_unique_constraints(
|
||||
'shipping_order_extraction_units'
|
||||
)
|
||||
} == {
|
||||
'uq_shipping_order_extraction_units_document',
|
||||
'uq_shipping_order_extraction_units_position',
|
||||
}
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_order_extraction_units' not in inspector.get_table_names()
|
||||
assert 'shipping_order_extraction_plans' not in inspector.get_table_names()
|
||||
finally:
|
||||
migration.op = original_op
|
||||
|
||||
|
||||
def test_order_extraction_plan_version_capacity_migration_round_trip():
|
||||
"""版本容量迁移必须将32字符列扩展至64字符并可回滚。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_pre_migration_schema(engine)
|
||||
create_migration = importlib.import_module('migrations.versions.a65d6e7f8091_add_order_extraction_plans')
|
||||
capacity_migration = importlib.import_module('migrations.versions.a66e7f8091a2_expand_order_extraction_plan_version')
|
||||
with engine.begin() as connection:
|
||||
original_create_op = create_migration.op
|
||||
original_capacity_op = capacity_migration.op
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
create_migration.op = operations
|
||||
capacity_migration.op = operations
|
||||
try:
|
||||
create_migration.upgrade()
|
||||
capacity_migration.upgrade()
|
||||
column = next(item for item in sa.inspect(connection).get_columns('shipping_order_extraction_plans') if item['name'] == 'plan_version')
|
||||
assert column['type'].length == 64
|
||||
capacity_migration.downgrade()
|
||||
reverted = next(item for item in sa.inspect(connection).get_columns('shipping_order_extraction_plans') if item['name'] == 'plan_version')
|
||||
assert reverted['type'].length == 32
|
||||
finally:
|
||||
create_migration.op = original_create_op
|
||||
capacity_migration.op = original_capacity_op
|
||||
@@ -0,0 +1,103 @@
|
||||
"""
|
||||
backend/tests/test_order_extraction_progress_migration.py
|
||||
|
||||
用途:隔离验证订单抽取进度基础迁移可完整 upgrade/downgrade。
|
||||
依赖:Alembic Operations、SQLAlchemy 内存数据库、a63b4c5d6e7f/a64c5d6e7f80 增量迁移。
|
||||
逻辑:构造迁移前最小依赖表,依次检查进度基础和节点标题移除,再按相反顺序回滚。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
RUN_PROGRESS_COLUMNS = {
|
||||
'progress_version', 'current_stage_code', 'active_stage_codes_json',
|
||||
'completed_stage_codes_json', 'progress_message_code', 'progress_health',
|
||||
'last_activity_at', 'progress_summary_json', 'progress_mapping_version',
|
||||
'attention_generated_at', 'seen_at',
|
||||
}
|
||||
|
||||
|
||||
def _pre_migration_schema(engine: sa.Engine) -> None:
|
||||
"""创建迁移外键及 batch alter 所需的最小前置结构。"""
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('users', 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),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
|
||||
def test_order_extraction_progress_migration_round_trip():
|
||||
"""迁移应创建完整进度结构且不采集节点标题,并可无残留回滚。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_pre_migration_schema(engine)
|
||||
foundation = importlib.import_module(
|
||||
'migrations.versions.a63b4c5d6e7f_add_order_extraction_progress_foundation'
|
||||
)
|
||||
privacy = importlib.import_module(
|
||||
'migrations.versions.a64c5d6e7f80_remove_order_extraction_progress_node_title'
|
||||
)
|
||||
with engine.begin() as connection:
|
||||
original_foundation_op = foundation.op
|
||||
original_privacy_op = privacy.op
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
foundation.op = operations
|
||||
privacy.op = operations
|
||||
try:
|
||||
foundation.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert RUN_PROGRESS_COLUMNS <= {
|
||||
column['name'] for column in inspector.get_columns('shipping_order_extraction_runs')
|
||||
}
|
||||
assert {
|
||||
'shipping_order_extraction_progress_events',
|
||||
'shipping_order_extraction_diagnostic_audits',
|
||||
} <= set(inspector.get_table_names())
|
||||
event_columns = {
|
||||
column['name'] for column in inspector.get_columns('shipping_order_extraction_progress_events')
|
||||
}
|
||||
assert 'node_title' in event_columns
|
||||
assert {
|
||||
'run_id', 'job_id', 'workflow_run_id', 'node_execution_id', 'node_type',
|
||||
'stage_code', 'idempotency_key', 'expires_at',
|
||||
} <= event_columns
|
||||
run_indexes = {
|
||||
index['name']: index
|
||||
for index in inspector.get_indexes('shipping_order_extraction_runs')
|
||||
}
|
||||
assert run_indexes['uq_shipping_order_extraction_runs_active_conversation']['unique'] == 1
|
||||
|
||||
privacy.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'node_title' not in {
|
||||
column['name'] for column in inspector.get_columns('shipping_order_extraction_progress_events')
|
||||
}
|
||||
|
||||
privacy.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'node_title' in {
|
||||
column['name'] for column in inspector.get_columns('shipping_order_extraction_progress_events')
|
||||
}
|
||||
|
||||
foundation.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_order_extraction_progress_events' not in inspector.get_table_names()
|
||||
assert 'shipping_order_extraction_diagnostic_audits' not in inspector.get_table_names()
|
||||
assert not RUN_PROGRESS_COLUMNS & {
|
||||
column['name'] for column in inspector.get_columns('shipping_order_extraction_runs')
|
||||
}
|
||||
finally:
|
||||
foundation.op = original_foundation_op
|
||||
privacy.op = original_privacy_op
|
||||
@@ -0,0 +1,29 @@
|
||||
"""
|
||||
backend/tests/test_order_extraction_provider_guard.py
|
||||
|
||||
用途:验证 Provider 进程级并发闸门与短期熔断状态机。
|
||||
依赖:order_extraction_provider_guard、统一 ServiceUnavailableError。
|
||||
逻辑:连续失败开路,成功复位;测试不接触真实 Provider。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.order_extraction_provider_guard import (
|
||||
assert_circuit_closed,
|
||||
record_provider_failure,
|
||||
record_provider_success,
|
||||
)
|
||||
|
||||
|
||||
def test_provider_circuit_opens_at_threshold_and_success_resets():
|
||||
"""连续失败达到阈值后快速失败,成功记录可恢复关闭状态。"""
|
||||
provider_id = 987654
|
||||
record_provider_success(provider_id)
|
||||
record_provider_failure(provider_id, threshold=2, cooldown_seconds=60)
|
||||
assert_circuit_closed(provider_id)
|
||||
record_provider_failure(provider_id, threshold=2, cooldown_seconds=60)
|
||||
with pytest.raises(Exception) as caught:
|
||||
assert_circuit_closed(provider_id)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_CIRCUIT_OPEN'
|
||||
record_provider_success(provider_id)
|
||||
assert_circuit_closed(provider_id)
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
用途:验证订单字段目录全局顺序迁移可升级、回填并降级。
|
||||
依赖:Alembic migration、临时 SQLite 数据库。
|
||||
逻辑:构造最小字段表,执行迁移后检查 display_sequence,再验证降级移除列。
|
||||
"""
|
||||
|
||||
from importlib import import_module
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_order_field_display_sequence_migration(monkeypatch, tmp_path):
|
||||
"""迁移应按稳定字段编号回填全局顺序并支持降级。"""
|
||||
engine = sa.create_engine(f"sqlite:///{tmp_path / 'order-field-sequence.db'}")
|
||||
metadata = sa.MetaData()
|
||||
fields = sa.Table(
|
||||
'shipping_order_fields', metadata,
|
||||
sa.Column('id', sa.String(36), primary_key=True),
|
||||
sa.Column('schema_id', sa.Integer(), nullable=False),
|
||||
sa.Column('field_code', sa.String(64), nullable=False),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
migration = import_module('migrations.versions.a67f8091a2b3_add_order_field_display_sequence')
|
||||
with engine.begin() as connection:
|
||||
connection.execute(fields.insert(), [
|
||||
{'id': 'field-b', 'schema_id': 1, 'field_code': 'beta'},
|
||||
{'id': 'field-a', 'schema_id': 1, 'field_code': 'alpha'},
|
||||
])
|
||||
monkeypatch.setattr(migration, 'op', Operations(MigrationContext.configure(connection)))
|
||||
migration.upgrade()
|
||||
rows = connection.execute(sa.text(
|
||||
'SELECT field_code, display_sequence FROM shipping_order_fields ORDER BY display_sequence'
|
||||
)).fetchall()
|
||||
assert rows == [('alpha', 1), ('beta', 2)]
|
||||
migration.downgrade()
|
||||
assert 'display_sequence' not in {
|
||||
column['name'] for column in sa.inspect(connection).get_columns('shipping_order_fields')
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
"""
|
||||
backend/tests/test_order_schema_table_contract.py
|
||||
|
||||
用途:验证冻结动态 Schema 的确定性表头编译、碰撞门禁和运行时歧义处理。
|
||||
依赖:table_contract、notice_line_table、统一 ValidationError。
|
||||
逻辑:用最小 definition 直接验证配置变化决定解析结果,禁止生产硬编码别名或静默选首列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.notice_line_table import (
|
||||
inspect_notice_table_text,
|
||||
parse_notice_table_text,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
|
||||
def _field(
|
||||
code: str,
|
||||
aliases: list[str],
|
||||
*,
|
||||
value_type: str = 'string',
|
||||
enabled: bool = True,
|
||||
collection_mode: str = 'llm_extraction',
|
||||
) -> dict:
|
||||
"""构造一个启用的最小 Schema 字段配置。"""
|
||||
return {
|
||||
'field_id': f'id-{code}', 'field_code': code, 'scope': 'line',
|
||||
'value_type': value_type, 'enabled': enabled, 'display_name': code,
|
||||
'aliases': aliases, 'normalizer_key': 'trim',
|
||||
'validator_keys': ['positive_decimal'] if code == 'qty' else [],
|
||||
'collection_mode': collection_mode,
|
||||
}
|
||||
|
||||
|
||||
def _definition(*fields: dict) -> dict:
|
||||
"""包装字段为完整 Schema definition。"""
|
||||
return {'schema_code': 'SHIPPING_ORDER', 'version': 1, 'fields': list(fields)}
|
||||
|
||||
|
||||
def test_table_contract_is_driven_only_by_explicit_schema_aliases():
|
||||
"""同一文本只有在冻结 Schema 配置对应别名时才产生确定性订单行。"""
|
||||
text = 'Custom SKU\tCustom Qty\nABC-1\t2'
|
||||
configured = compile_table_header_contract(_definition(
|
||||
_field('part_number', ['Custom SKU']), _field('qty', ['Custom Qty'], value_type='decimal'),
|
||||
))
|
||||
unconfigured = compile_table_header_contract(_definition(
|
||||
_field('part_number', ['Other SKU']), _field('qty', ['Other Qty'], value_type='decimal'),
|
||||
))
|
||||
|
||||
assert parse_notice_table_text(text, contract=configured)[0]['part_number'] == 'ABC-1'
|
||||
assert parse_notice_table_text(text, contract=unconfigured) == []
|
||||
assert parse_notice_table_text(text, contract=None) == []
|
||||
|
||||
|
||||
def test_table_contract_rejects_normalized_alias_collision():
|
||||
"""大小写、全半角或标点差异归一后冲突时必须阻断 Schema 保存/发布。"""
|
||||
definition = _definition(
|
||||
_field('part_number', ['Customer P/N']),
|
||||
_field('customer_part_number', ['customer p n']),
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
compile_table_header_contract(definition)
|
||||
|
||||
assert caught.value.code == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID'
|
||||
assert caught.value.details['table_header_collisions']
|
||||
|
||||
|
||||
def test_table_contract_rejects_forbidden_reservation_header():
|
||||
"""管理员不得把 Allocation/Internal/UUID 类表头配置成 Reservation ID。"""
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
compile_table_header_contract(_definition(_field('reservation_id', ['Allocation ID'])))
|
||||
|
||||
assert caught.value.details['forbidden_reservation_headers'] == ['Allocation ID']
|
||||
|
||||
|
||||
def test_runtime_reports_duplicate_columns_as_ambiguous():
|
||||
"""同一字段在一行命中多个列时不得静默选第一列。"""
|
||||
contract = compile_table_header_contract(_definition(
|
||||
_field('part_number', ['MPN', 'Part Number']),
|
||||
_field('qty', ['Qty'], value_type='decimal'),
|
||||
))
|
||||
inspected = inspect_notice_table_text(
|
||||
'MPN\tPart Number\tQty\nA-1\tB-2\t3', contract=contract,
|
||||
)
|
||||
|
||||
assert inspected['lines'] == []
|
||||
assert inspected['ambiguous_fields'] == ['part_number']
|
||||
assert inspected['header_found'] is True
|
||||
|
||||
|
||||
def test_table_contract_excludes_disabled_and_unsupported_context_fields():
|
||||
"""禁用字段和非表格业务上下文字段不得因配置别名进入确定性表头映射。"""
|
||||
contract = compile_table_header_contract(_definition(
|
||||
_field('part_number', ['Disabled SKU'], enabled=False),
|
||||
_field('sender_email', ['Sender'], collection_mode='deterministic_context'),
|
||||
_field('qty', ['Qty'], value_type='decimal'),
|
||||
))
|
||||
|
||||
assert 'disabled sku' not in contract.header_to_field
|
||||
assert 'sender' not in contract.header_to_field
|
||||
assert contract.header_to_field['qty'] == 'qty'
|
||||
|
||||
|
||||
def test_flat_table_parser_drops_zero_quantity_row():
|
||||
"""拍平表格入口同样不得把零数量行解析为有效订单行。"""
|
||||
contract = compile_table_header_contract(_definition(
|
||||
_field('part_number', ['Vendor PN']),
|
||||
_field('qty', ['Qty'], value_type='decimal'),
|
||||
))
|
||||
|
||||
assert parse_notice_table_text(
|
||||
'Vendor PN\tQty\nINTERNAL-ZERO\t0\nINTERNAL-VALID\t2',
|
||||
contract=contract,
|
||||
) == [{'part_number': 'INTERNAL-VALID', 'qty': 2.0}]
|
||||
@@ -0,0 +1,199 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_contract.py
|
||||
|
||||
用途:验证 shipping_document_layout.v1 的几何、引用、跨页关系、稳定 ID 和 checksum。
|
||||
依赖:document_layout.contracts、Pydantic ValidationError。
|
||||
逻辑:使用不可逆构造样本覆盖阶段 L0 契约门禁,不依赖客户原始 PDF 或敏感业务数据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import (
|
||||
canonical_layout_checksum,
|
||||
stable_layout_id,
|
||||
validate_layout_document,
|
||||
)
|
||||
|
||||
|
||||
def _bbox(x0: float, y0: float, x1: float, y1: float) -> dict:
|
||||
"""构造原始或标准化矩形。"""
|
||||
return {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1}
|
||||
|
||||
|
||||
def _token(token_id: str, text: str, x0: float, x1: float) -> dict:
|
||||
"""构造一页内的原生 PDF 词元。"""
|
||||
return {
|
||||
'token_id': token_id,
|
||||
'text': text,
|
||||
'normalized_text': text,
|
||||
'bbox': _bbox(x0, 10, x1, 20),
|
||||
'normalized_bbox': _bbox(x0 / 100, 0.1, x1 / 100, 0.2),
|
||||
'source': 'native_text',
|
||||
'confidence': 1,
|
||||
'line_id': 'line-1',
|
||||
}
|
||||
|
||||
|
||||
def _cell(cell_id: str, *, row: int, column: int, text: str, token_id: str) -> dict:
|
||||
"""构造可追溯到一个词元的表格单元格。"""
|
||||
x0 = 10 + column * 40
|
||||
return {
|
||||
'cell_id': cell_id,
|
||||
'row_index': row,
|
||||
'column_index': column,
|
||||
'text': text,
|
||||
'normalized_text': text,
|
||||
'bbox': _bbox(x0, 10 + row * 20, x0 + 30, 25 + row * 20),
|
||||
'normalized_bbox': _bbox(x0 / 100, (10 + row * 20) / 100, (x0 + 30) / 100, (25 + row * 20) / 100),
|
||||
'token_ids': [token_id],
|
||||
'source': 'native_text',
|
||||
'confidence': 1,
|
||||
'role': 'header' if row == 0 else 'data',
|
||||
}
|
||||
|
||||
|
||||
def _table(table_id: str, *, continuation_of: str | None = None) -> dict:
|
||||
"""构造两列表格;调用方负责提供同页对应 token。"""
|
||||
suffix = table_id.rsplit('-', 1)[-1]
|
||||
return {
|
||||
'table_id': table_id,
|
||||
'bbox': _bbox(5, 5, 95, 55),
|
||||
'normalized_bbox': _bbox(0.05, 0.05, 0.95, 0.55),
|
||||
'rows': [
|
||||
{
|
||||
'row_id': f'row-{suffix}-0',
|
||||
'row_index': 0,
|
||||
'role': 'header',
|
||||
'cells': [
|
||||
_cell(f'cell-{suffix}-0-0', row=0, column=0, text='Part', token_id=f'token-{suffix}-part'),
|
||||
_cell(f'cell-{suffix}-0-1', row=0, column=1, text='Qty', token_id=f'token-{suffix}-qty'),
|
||||
],
|
||||
},
|
||||
],
|
||||
'header_row_indices': [0],
|
||||
'continuation_of': continuation_of,
|
||||
'confidence': 1,
|
||||
'status': 'accepted',
|
||||
}
|
||||
|
||||
|
||||
def _page(page_no: int, table_id: str, *, continuation_of: str | None = None) -> dict:
|
||||
"""构造含真实坐标词元和单个表格的页面。"""
|
||||
suffix = table_id.rsplit('-', 1)[-1]
|
||||
return {
|
||||
'page_no': page_no,
|
||||
'width': 100,
|
||||
'height': 100,
|
||||
'rotation': 0,
|
||||
'tokens': [
|
||||
_token(f'token-{suffix}-part', 'Part', 10, 40),
|
||||
_token(f'token-{suffix}-qty', 'Qty', 50, 80),
|
||||
],
|
||||
'tables': [_table(table_id, continuation_of=continuation_of)],
|
||||
}
|
||||
|
||||
|
||||
def _document() -> dict:
|
||||
"""构造带合法跨页 continuation 的完整布局文档。"""
|
||||
return {
|
||||
'schema_version': 'shipping_document_layout.v1',
|
||||
'document_id': 42,
|
||||
'content_hash': 'a' * 64,
|
||||
'parser': {'name': 'fixture-parser', 'version': '1.0.0'},
|
||||
'pages': [
|
||||
_page(1, 'table-p1'),
|
||||
_page(2, 'table-p2', continuation_of='table-p1'),
|
||||
],
|
||||
'quality': {'status': 'accepted', 'confidence': 1, 'issues': []},
|
||||
}
|
||||
|
||||
|
||||
def test_layout_contract_accepts_traceable_cross_page_table():
|
||||
"""合法结果必须保留页、表、行、列、单元格、词元和向前跨页引用。"""
|
||||
result = validate_layout_document(_document())
|
||||
|
||||
assert result.schema_version == 'shipping_document_layout.v1'
|
||||
assert result.pages[1].tables[0].continuation_of == 'table-p1'
|
||||
assert result.pages[0].tables[0].rows[0].cells[0].token_ids == ['token-p1-part']
|
||||
|
||||
|
||||
def test_layout_contract_rejects_unknown_cell_token_reference():
|
||||
"""PDF/OCR 单元格引用不存在的词元时必须拒绝,防止证据链断裂。"""
|
||||
payload = _document()
|
||||
payload['pages'][0]['tables'][0]['rows'][0]['cells'][0]['token_ids'] = ['missing-token']
|
||||
|
||||
with pytest.raises(ValidationError, match='unknown token_id'):
|
||||
validate_layout_document(payload)
|
||||
|
||||
|
||||
def test_layout_contract_rejects_out_of_page_and_non_normalized_bbox():
|
||||
"""原始坐标越界或标准化坐标超过 0..1 均不能进入下游。"""
|
||||
outside_page = _document()
|
||||
outside_page['pages'][0]['tokens'][0]['bbox']['x1'] = 101
|
||||
with pytest.raises(ValidationError, match='exceeds page bounds'):
|
||||
validate_layout_document(outside_page)
|
||||
|
||||
outside_normalized = _document()
|
||||
outside_normalized['pages'][0]['tables'][0]['normalized_bbox']['x1'] = 1.1
|
||||
with pytest.raises(ValidationError, match='within 0..1'):
|
||||
validate_layout_document(outside_normalized)
|
||||
|
||||
|
||||
def test_layout_contract_rejects_cell_outside_table_and_overlapping_span():
|
||||
"""单元格超出表格或 rowspan/colspan 相互覆盖时必须拒绝。"""
|
||||
outside_table = _document()
|
||||
outside_table['pages'][0]['tables'][0]['rows'][0]['cells'][0]['bbox']['x0'] = 1
|
||||
with pytest.raises(ValidationError, match='within table bbox'):
|
||||
validate_layout_document(outside_table)
|
||||
|
||||
overlapping = _document()
|
||||
cells = overlapping['pages'][0]['tables'][0]['rows'][0]['cells']
|
||||
cells[0]['column_span'] = 2
|
||||
with pytest.raises(ValidationError, match='overlapping'):
|
||||
validate_layout_document(overlapping)
|
||||
|
||||
|
||||
def test_layout_contract_rejects_forward_or_missing_continuation():
|
||||
"""跨页表只能引用更早页面的已知表,禁止循环、前向或悬空关系。"""
|
||||
forward = _document()
|
||||
forward['pages'][0]['tables'][0]['continuation_of'] = 'table-p2'
|
||||
with pytest.raises(ValidationError, match='earlier page'):
|
||||
validate_layout_document(forward)
|
||||
|
||||
missing = _document()
|
||||
missing['pages'][1]['tables'][0]['continuation_of'] = 'table-missing'
|
||||
with pytest.raises(ValidationError, match='earlier page'):
|
||||
validate_layout_document(missing)
|
||||
|
||||
|
||||
def test_layout_contract_rejects_accepted_quality_with_blocking_issue():
|
||||
"""存在阻断质量问题的布局不能伪装成 accepted。"""
|
||||
payload = _document()
|
||||
payload['quality']['issues'] = [{
|
||||
'code': 'table_columns_ambiguous',
|
||||
'severity': 'blocking',
|
||||
'page_no': 1,
|
||||
'table_id': 'table-p1',
|
||||
'details': {},
|
||||
}]
|
||||
|
||||
with pytest.raises(ValidationError, match='must not contain blocking issues'):
|
||||
validate_layout_document(payload)
|
||||
|
||||
|
||||
def test_stable_id_and_checksum_are_deterministic_and_content_sensitive():
|
||||
"""相同输入必须生成相同标识/checksum,任何结构变化必须改变 checksum。"""
|
||||
payload = _document()
|
||||
copied = deepcopy(payload)
|
||||
|
||||
assert stable_layout_id('cell', 'a' * 64, 1, 0, 0) == stable_layout_id('cell', 'a' * 64, 1, 0, 0)
|
||||
assert canonical_layout_checksum(payload) == canonical_layout_checksum(copied)
|
||||
|
||||
copied['pages'][0]['tables'][0]['rows'][0]['cells'][0]['text'] = 'Changed Part'
|
||||
copied['pages'][0]['tables'][0]['rows'][0]['cells'][0]['normalized_text'] = 'Changed Part'
|
||||
assert canonical_layout_checksum(payload) != canonical_layout_checksum(copied)
|
||||
@@ -0,0 +1,87 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_coverage.py
|
||||
|
||||
用途:验证 HTML Schema 覆盖评估只输出聚合指标,并正确区分建单与全部必填完整性。
|
||||
依赖:document_layout.coverage/html_table、order_schema.table_contract。
|
||||
逻辑:用包含字段值和证据引用的映射结果生成报告,断言统计准确且敏感内容不进入序列化结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.document_layout.coverage import summarize_html_schema_coverage
|
||||
from app.services.shipping_notice.document_layout.html_table import map_html_table_to_schema
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
|
||||
def _field(code: str, aliases: list[str], *, required: bool = False, value_type: str = 'string') -> dict:
|
||||
"""构造覆盖评估所需的最小冻结行字段。"""
|
||||
return {
|
||||
'field_id': f'id-{code}', 'field_code': code, 'scope': 'line',
|
||||
'value_type': value_type, 'enabled': True, 'required': required,
|
||||
'display_name': code, 'aliases': aliases, 'normalizer_key': 'trim',
|
||||
'validator_keys': [], 'collection_mode': 'llm_extraction',
|
||||
}
|
||||
|
||||
|
||||
def _contract():
|
||||
"""创建同时包含建单字段和跨文档 Reservation 缺口的冻结契约。"""
|
||||
return compile_table_header_contract({'fields': [
|
||||
_field('part_number', ['Vendor PN'], required=True),
|
||||
_field('qty', ['Qty'], required=True, value_type='integer'),
|
||||
_field('reservation_id', ['Reservation ID'], required=True),
|
||||
]})
|
||||
|
||||
|
||||
def test_coverage_report_counts_headers_columns_rows_and_missing_required_fields():
|
||||
"""报告应正确统计命中列、未命中列以及 build/all-required 两层完整率。"""
|
||||
contract = _contract()
|
||||
complete_build = map_html_table_to_schema(
|
||||
'<table><tr><th>Vendor PN</th><th>Qty</th><th>Description</th></tr>'
|
||||
'<tr><td>SECRET-PART</td><td>2</td><td>SECRET-DESC</td></tr></table>',
|
||||
page_no=1, table_id='secret-table', contract=contract,
|
||||
)
|
||||
no_header = map_html_table_to_schema(
|
||||
'<table><tr><th>Unknown A</th><th>Unknown B</th></tr>'
|
||||
'<tr><td>SECRET-A</td><td>SECRET-B</td></tr></table>',
|
||||
page_no=2, table_id='other-table', contract=contract,
|
||||
)
|
||||
|
||||
report = summarize_html_schema_coverage([complete_build, no_header])
|
||||
|
||||
assert report.table_count == 2
|
||||
assert report.tables_with_mapped_header == 1
|
||||
assert report.tables_without_mapped_header == 1
|
||||
assert (report.mapped_columns, report.unmapped_columns, report.ambiguous_columns) == (2, 3, 0)
|
||||
assert report.mapped_column_rate == 0.4
|
||||
assert report.data_rows == 1
|
||||
assert report.build_complete_rows == 1
|
||||
assert report.all_required_complete_rows == 0
|
||||
assert report.build_complete_rate == 1.0
|
||||
assert report.all_required_complete_rate == 0.0
|
||||
assert report.field_code_frequency == {'part_number': 1, 'qty': 1}
|
||||
|
||||
|
||||
def test_coverage_report_serialization_contains_no_source_content_or_evidence_identity():
|
||||
"""聚合报告不得泄露字段值、表格 ID、单元格引用、表头或证据文本。"""
|
||||
mapping = map_html_table_to_schema(
|
||||
'<table><tr><th>Vendor PN</th><th>Qty</th></tr>'
|
||||
'<tr><td>PRIVATE-PART-9988</td><td>7</td></tr></table>',
|
||||
page_no=9, table_id='private-table-id', contract=_contract(),
|
||||
)
|
||||
|
||||
serialized = summarize_html_schema_coverage([mapping]).model_dump_json()
|
||||
|
||||
for forbidden in ('PRIVATE-PART-9988', 'private-table-id', 'Vendor PN', 'evidence_ref', 'cell_id'):
|
||||
assert forbidden not in serialized
|
||||
|
||||
|
||||
def test_empty_coverage_report_has_zero_rates_and_empty_frequencies():
|
||||
"""没有表格时报告必须给出稳定零值,便于自动 Review 比较。"""
|
||||
report = summarize_html_schema_coverage([])
|
||||
|
||||
assert report.table_count == 0
|
||||
assert report.mapped_column_rate == 0
|
||||
assert report.build_complete_rate == 0
|
||||
assert report.all_required_complete_rate == 0
|
||||
assert report.field_code_frequency == {}
|
||||
assert report.issue_code_frequency == {}
|
||||
@@ -0,0 +1,110 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_evaluation.py
|
||||
|
||||
用途:验证阶段 L0 人工真值契约和表格/单元格评测指标。
|
||||
依赖:document_layout.evaluation、布局契约测试构造器。
|
||||
逻辑:以不可逆构造样本模拟完整命中、漏单元格、字段错配和哈希漂移。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.services.shipping_notice.document_layout.evaluation import evaluate_layout
|
||||
from tests.test_shipping_document_layout_contract import _document
|
||||
|
||||
|
||||
def _annotation() -> dict:
|
||||
"""为构造布局生成两页、两表、四单元格的人工真值。"""
|
||||
tables = []
|
||||
for page_no, suffix, continuation in ((1, 'p1', None), (2, 'p2', 'truth-p1')):
|
||||
cells = []
|
||||
for column, text, field_code in ((0, 'Part', 'part_number'), (1, 'Qty', 'qty')):
|
||||
x0 = 10 + column * 40
|
||||
cells.append({
|
||||
'annotation_id': f'truth-cell-{suffix}-{column}',
|
||||
'page_no': page_no,
|
||||
'table_index': 0,
|
||||
'row_index': 0,
|
||||
'column_index': column,
|
||||
'normalized_bbox': {
|
||||
'x0': x0 / 100, 'y0': 0.1, 'x1': (x0 + 30) / 100, 'y1': 0.25,
|
||||
},
|
||||
'normalized_text': text,
|
||||
'role': 'header',
|
||||
'expected_field_code': field_code,
|
||||
})
|
||||
tables.append({
|
||||
'annotation_id': f'truth-{suffix}',
|
||||
'page_no': page_no,
|
||||
'table_index': 0,
|
||||
'normalized_bbox': {'x0': 0.05, 'y0': 0.05, 'x1': 0.95, 'y1': 0.55},
|
||||
'cells': cells,
|
||||
'continuation_of': continuation,
|
||||
})
|
||||
return {
|
||||
'schema_version': 'shipping_document_layout_annotation.v1',
|
||||
'layout_schema_version': 'shipping_document_layout.v1',
|
||||
'sample_id': 'synthetic-two-page-table',
|
||||
'content_hash': 'a' * 64,
|
||||
'categories': ['native_pdf', 'cross_page_table'],
|
||||
'tables': tables,
|
||||
}
|
||||
|
||||
|
||||
def test_evaluation_reports_perfect_layout_and_field_mapping():
|
||||
"""几何、行列和字段映射全部正确时四项指标均为 1。"""
|
||||
mapped = {
|
||||
'cell-p1-0-0': 'part_number', 'cell-p1-0-1': 'qty',
|
||||
'cell-p2-0-0': 'part_number', 'cell-p2-0-1': 'qty',
|
||||
}
|
||||
|
||||
result = evaluate_layout(_annotation(), _document(), mapped_field_codes=mapped)
|
||||
|
||||
assert result.table_detection_recall == 1
|
||||
assert result.cell_detection_recall == 1
|
||||
assert result.cell_position_accuracy == 1
|
||||
assert result.field_mapping_accuracy == 1
|
||||
|
||||
|
||||
def test_evaluation_separates_detection_position_and_field_errors():
|
||||
"""漏单元格与字段错配必须反映在不同指标,便于定位解析层或映射层问题。"""
|
||||
candidate = _document()
|
||||
candidate['pages'][1]['tables'][0]['rows'][0]['cells'].pop()
|
||||
mapped = {
|
||||
'cell-p1-0-0': 'qty',
|
||||
'cell-p1-0-1': 'qty',
|
||||
'cell-p2-0-0': 'part_number',
|
||||
}
|
||||
|
||||
result = evaluate_layout(_annotation(), candidate, mapped_field_codes=mapped)
|
||||
|
||||
assert result.table_detection_recall == 1
|
||||
assert result.cell_detection_recall == 0.75
|
||||
assert result.cell_position_accuracy == 1
|
||||
assert result.field_mapping_accuracy == 0.5
|
||||
|
||||
|
||||
def test_evaluation_rejects_annotation_for_another_file():
|
||||
"""人工真值与候选文件哈希不一致时不得产生误导性指标。"""
|
||||
annotation = deepcopy(_annotation())
|
||||
annotation['content_hash'] = 'b' * 64
|
||||
|
||||
with pytest.raises(ValueError, match='content_hash'):
|
||||
evaluate_layout(annotation, _document())
|
||||
|
||||
|
||||
def test_evaluation_rejects_invalid_annotation_geometry():
|
||||
"""人工真值坐标越界或单元格超出父表时必须在评测前拒绝。"""
|
||||
outside_page = _annotation()
|
||||
outside_page['tables'][0]['normalized_bbox']['x1'] = 1.1
|
||||
with pytest.raises(ValidationError, match='within 0..1'):
|
||||
evaluate_layout(outside_page, _document())
|
||||
|
||||
outside_table = _annotation()
|
||||
outside_table['tables'][0]['cells'][0]['normalized_bbox']['x0'] = 0.01
|
||||
with pytest.raises(ValidationError, match='within parent table'):
|
||||
evaluate_layout(outside_table, _document())
|
||||
@@ -0,0 +1,318 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_html_table.py
|
||||
|
||||
用途:验证 HTML 表格网格恢复和冻结订单 Schema 的确定性列映射不会发生跨列猜测。
|
||||
依赖:document_layout.html_table、order_schema.table_contract、统一 ValidationError。
|
||||
逻辑:构造最小 HTML 与动态别名契约,覆盖合并格、后置表头、特殊行和历史错位场景。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.document_layout.html_table import (
|
||||
map_html_table_to_schema,
|
||||
parse_html_grid,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import (
|
||||
compile_table_header_contract,
|
||||
)
|
||||
|
||||
|
||||
def _field(
|
||||
code: str,
|
||||
aliases: list[str],
|
||||
*,
|
||||
value_type: str = 'string',
|
||||
required: bool = False,
|
||||
normalizer_key: str = 'trim',
|
||||
validator_keys: list[str] | None = None,
|
||||
) -> dict:
|
||||
"""构造由测试显式控制别名和校验器的最小行字段配置。"""
|
||||
return {
|
||||
'field_id': f'id-{code}',
|
||||
'field_code': code,
|
||||
'scope': 'line',
|
||||
'value_type': value_type,
|
||||
'enabled': True,
|
||||
'required': required,
|
||||
'display_name': code,
|
||||
'aliases': aliases,
|
||||
'normalizer_key': normalizer_key,
|
||||
'validator_keys': validator_keys or [],
|
||||
'collection_mode': 'llm_extraction',
|
||||
}
|
||||
|
||||
|
||||
def _contract(*fields: dict):
|
||||
"""把测试字段冻结为与生产 Run 相同形态的表头契约。"""
|
||||
return compile_table_header_contract({
|
||||
'schema_code': 'SHIPPING_ORDER',
|
||||
'version': 1,
|
||||
'fields': list(fields),
|
||||
})
|
||||
|
||||
|
||||
def _map(html: str, *fields: dict):
|
||||
"""以固定页码和表 ID 映射 HTML,便于断言短证据引用。"""
|
||||
return map_html_table_to_schema(
|
||||
html,
|
||||
page_no=2,
|
||||
table_id='table-1',
|
||||
contract=_contract(*fields),
|
||||
)
|
||||
|
||||
|
||||
def test_parse_html_grid_expands_rowspan_and_colspan():
|
||||
"""rowspan/colspan 必须展开成矩形 Slot,同时保留共同原始 cell_id。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th rowspan="2">PO</th><th colspan="2">Line</th></tr>'
|
||||
'<tr><th>Part</th><th>Qty</th></tr><tr><td>P1</td><td>A1</td><td>2</td></tr></table>',
|
||||
table_id='t',
|
||||
)
|
||||
|
||||
assert (grid.row_count, grid.column_count) == (3, 3)
|
||||
assert grid.rows[0][0].cell_id == grid.rows[1][0].cell_id
|
||||
assert grid.rows[0][1].cell_id == grid.rows[0][2].cell_id
|
||||
|
||||
|
||||
def test_multilevel_header_maps_only_explicit_combined_aliases():
|
||||
"""多层表头可按组合路径命中,但没有配置的兄弟列必须保持未映射。"""
|
||||
result = _map(
|
||||
'<table><tr><th colspan="2">Order</th></tr>'
|
||||
'<tr><th>Part</th><th>Description</th></tr><tr><td>A-1</td><td>Rack</td></tr></table>',
|
||||
_field('part_number', ['Order Part'], required=True),
|
||||
)
|
||||
|
||||
assert result.header_row_index == 1
|
||||
assert [column.status for column in result.columns] == ['mapped', 'unmapped']
|
||||
data = next(row for row in result.rows if row.role == 'data')
|
||||
assert [(field.field_code, field.value) for field in data.fields] == [('part_number', 'A-1')]
|
||||
assert data.complete_required_fields is True
|
||||
|
||||
|
||||
def test_header_can_appear_after_an_unrelated_intro_row():
|
||||
"""表头不在首行时仍按最高精确命中选择,前置说明行不得改变列归属。"""
|
||||
result = _map(
|
||||
'<table><tr><td>Customer supplied table</td><td></td></tr>'
|
||||
'<tr><td>SKU</td><td>Quantity</td></tr><tr><td>A-1</td><td>3</td></tr></table>',
|
||||
_field('part_number', ['SKU']),
|
||||
_field('qty', ['Quantity'], value_type='decimal', validator_keys=['positive_decimal']),
|
||||
)
|
||||
|
||||
assert result.header_row_index == 1
|
||||
data = result.rows[-1]
|
||||
assert {field.field_code: field.value for field in data.fields} == {
|
||||
'part_number': 'A-1',
|
||||
'qty': Decimal('3'),
|
||||
}
|
||||
|
||||
|
||||
def test_repeated_header_deleted_summary_and_empty_rows_are_not_data():
|
||||
"""分页重复表头、删除、合计与空行必须显式分类,禁止生成订单行字段。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Part</th><th>Qty</th></tr>'
|
||||
'<tr><td>Part</td><td>Qty</td></tr><tr><td>Item deleted</td><td></td></tr>'
|
||||
'<tr><td>Total</td><td>2</td></tr><tr><td></td><td></td></tr></table>',
|
||||
_field('part_number', ['Part']),
|
||||
_field('qty', ['Qty'], value_type='decimal'),
|
||||
)
|
||||
|
||||
assert [row.role for row in result.rows] == [
|
||||
'repeated_header', 'deleted', 'summary', 'empty',
|
||||
]
|
||||
assert all(not row.fields for row in result.rows)
|
||||
|
||||
|
||||
def test_explicit_zero_quantity_row_is_deleted_without_field_candidates():
|
||||
"""冻结 Qty 列明确为零的订单行必须删除,不能作为不完整 Candidate 流入后续。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Vendor Part Number</th><th>Qty</th></tr>'
|
||||
'<tr><td>INTERNAL-ZERO</td><td>0 EA</td></tr>'
|
||||
'<tr><td>INTERNAL-VALID</td><td>3 EA</td></tr></table>',
|
||||
_field('part_number', ['Vendor Part Number'], required=True),
|
||||
_field('qty', ['Qty'], value_type='integer', required=True),
|
||||
)
|
||||
|
||||
assert result.rows[0].role == 'deleted'
|
||||
assert result.rows[0].fields == []
|
||||
assert result.rows[1].role == 'data'
|
||||
assert {field.field_code: field.value for field in result.rows[1].fields} == {
|
||||
'part_number': 'INTERNAL-VALID',
|
||||
'qty': 3,
|
||||
}
|
||||
|
||||
|
||||
def test_negative_or_invalid_quantity_is_not_classified_as_deleted():
|
||||
"""负数或非法数量不是业务删除指令,必须保留为数据质量问题而非静默删除。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Vendor Part Number</th><th>Qty</th></tr>'
|
||||
'<tr><td>INTERNAL-NEG</td><td>-1</td></tr>'
|
||||
'<tr><td>INTERNAL-BAD</td><td>N/A</td></tr></table>',
|
||||
_field('part_number', ['Vendor Part Number'], required=True),
|
||||
_field('qty', ['Qty'], value_type='integer', required=True, validator_keys=['positive_integer']),
|
||||
)
|
||||
|
||||
assert [row.role for row in result.rows] == ['data', 'data']
|
||||
assert all(row.missing_required_field_codes == ['qty'] for row in result.rows)
|
||||
|
||||
|
||||
def test_unknown_business_columns_never_shift_into_known_fields():
|
||||
"""历史错位值只能留在未映射列,不能按值形态变成 AWS、Reservation 或料号。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Description</th><th>Legacy Ref</th><th>Hub</th><th>Material</th><th>Qty</th></tr>'
|
||||
'<tr><td>A01 SET,RACK,ENCLOSURE</td><td>D4-A08AR12000002</td>'
|
||||
'<td>AWS HUB</td><td>6Y70B2501901</td><td>30</td></tr></table>',
|
||||
_field('aws_part_number', ['AWS Part Number']),
|
||||
_field('reservation_id', ['Reservation ID'], normalizer_key='reservation_id'),
|
||||
_field('part_number', ['Part Number']),
|
||||
_field('inventory_source_hint', ['Inventory Source']),
|
||||
_field('qty', ['Qty'], value_type='integer'),
|
||||
)
|
||||
|
||||
assert [column.status for column in result.columns] == [
|
||||
'unmapped', 'unmapped', 'unmapped', 'unmapped', 'mapped',
|
||||
]
|
||||
data = result.rows[0]
|
||||
assert [(field.field_code, field.value) for field in data.fields] == [('qty', 30)]
|
||||
|
||||
|
||||
def test_inventory_source_maps_only_when_schema_alias_explicitly_allows_it():
|
||||
"""同一 Hub 表头仅在冻结 Schema 明确声明别名后才映射库存来源。"""
|
||||
result = _map(
|
||||
'<table><tr><th>AWS HUB</th><th>Qty</th></tr><tr><td>SIN</td><td>1</td></tr></table>',
|
||||
_field('inventory_source_hint', ['AWS HUB']),
|
||||
_field('qty', ['Qty'], value_type='integer'),
|
||||
)
|
||||
|
||||
assert {field.field_code: field.value for field in result.rows[0].fields} == {
|
||||
'inventory_source_hint': 'SIN',
|
||||
'qty': 1,
|
||||
}
|
||||
|
||||
|
||||
def test_material_maps_to_customer_part_number_only_when_schema_declares_it():
|
||||
"""业务确认的 Material 别名只能产生客户料号,不得自动复制为内部或 AWS 料号。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Material No</th><th>Vendor Part Number</th><th>AWS SKU</th><th>Qty</th></tr>'
|
||||
'<tr><td>CUSTOMER-1</td><td>INTERNAL-1</td><td>AWS-1</td><td>2</td></tr></table>',
|
||||
_field('customer_part_number', ['Material No']),
|
||||
_field('part_number', ['Vendor Part Number']),
|
||||
_field('aws_part_number', ['AWS SKU']),
|
||||
_field('qty', ['Qty'], value_type='integer'),
|
||||
)
|
||||
|
||||
assert {field.field_code: field.value for field in result.rows[0].fields} == {
|
||||
'customer_part_number': 'CUSTOMER-1',
|
||||
'part_number': 'INTERNAL-1',
|
||||
'aws_part_number': 'AWS-1',
|
||||
'qty': 2,
|
||||
}
|
||||
|
||||
|
||||
def test_missing_reservation_preserves_build_complete_order_row():
|
||||
"""PDF 缺 Reservation 时仍保留 part_number+qty 候选,并显式列出跨文档补充缺口。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Vendor Part Number</th><th>Qty</th></tr>'
|
||||
'<tr><td>INTERNAL-1</td><td>2</td></tr></table>',
|
||||
_field('part_number', ['Vendor Part Number'], required=True),
|
||||
_field('qty', ['Qty'], value_type='integer', required=True),
|
||||
_field('reservation_id', ['Reservation ID'], required=True),
|
||||
)
|
||||
|
||||
row = result.rows[0]
|
||||
assert row.complete_build_fields is True
|
||||
assert row.complete_required_fields is False
|
||||
assert row.missing_required_field_codes == ['reservation_id']
|
||||
|
||||
|
||||
def test_customer_material_without_internal_part_is_not_build_complete():
|
||||
"""只有客户 Material+Qty 时不得冒充内部料号形成可建单行。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Material No</th><th>Qty</th></tr>'
|
||||
'<tr><td>CUSTOMER-1</td><td>2</td></tr></table>',
|
||||
_field('customer_part_number', ['Material No']),
|
||||
_field('part_number', ['Vendor Part Number'], required=True),
|
||||
_field('qty', ['Qty'], value_type='integer', required=True),
|
||||
_field('reservation_id', ['Reservation ID'], required=True),
|
||||
)
|
||||
|
||||
row = result.rows[0]
|
||||
assert row.complete_build_fields is False
|
||||
assert row.missing_required_field_codes == ['part_number', 'reservation_id']
|
||||
|
||||
|
||||
def test_header_with_appended_first_numeric_value_is_flagged_not_trimmed():
|
||||
"""已知表头后拼首条数字值时标记版面污染,禁止修剪后自动映射。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Item No 00010</th><th>Vendor Part Number</th><th>Qty</th></tr>'
|
||||
'<tr><td>00020</td><td>INTERNAL-1</td><td>2</td></tr></table>',
|
||||
_field('line_no', ['Item No']),
|
||||
_field('part_number', ['Vendor Part Number'], required=True),
|
||||
_field('qty', ['Qty'], value_type='integer', required=True),
|
||||
)
|
||||
|
||||
assert result.columns[0].status == 'unmapped'
|
||||
assert 'html_table_header_value_contamination' in result.issues
|
||||
assert {field.field_code for field in result.rows[0].fields} == {'part_number', 'qty'}
|
||||
|
||||
|
||||
def test_legitimate_alphanumeric_header_is_not_numeric_value_contamination():
|
||||
"""未命中“精确别名+纯数字后缀”的普通业务表头不得被污染规则误报。"""
|
||||
result = _map(
|
||||
'<table><tr><th>RoHS2</th><th>Vendor Part Number</th><th>Qty</th></tr>'
|
||||
'<tr><td>Y</td><td>INTERNAL-1</td><td>2</td></tr></table>',
|
||||
_field('part_number', ['Vendor Part Number'], required=True),
|
||||
_field('qty', ['Qty'], value_type='integer', required=True),
|
||||
)
|
||||
|
||||
assert 'html_table_header_value_contamination' not in result.issues
|
||||
|
||||
|
||||
def test_duplicate_columns_for_one_field_are_all_blocked():
|
||||
"""同一字段命中多个列时所有冲突列都标歧义,数据行不得静默选首列。"""
|
||||
result = _map(
|
||||
'<table><tr><th>MPN</th><th>Part Number</th><th>Qty</th></tr>'
|
||||
'<tr><td>A-1</td><td>B-2</td><td>3</td></tr></table>',
|
||||
_field('part_number', ['MPN', 'Part Number']),
|
||||
_field('qty', ['Qty'], value_type='integer'),
|
||||
)
|
||||
|
||||
assert [column.status for column in result.columns] == ['ambiguous', 'ambiguous', 'mapped']
|
||||
assert 'html_table_columns_ambiguous' in result.issues
|
||||
assert 'html_table_duplicate_field_columns' in result.issues
|
||||
assert [(field.field_code, field.value) for field in result.rows[0].fields] == [('qty', 3)]
|
||||
|
||||
|
||||
def test_reservation_validator_rejects_line_number_shape():
|
||||
"""即使表头正确,Reservation 安全校验仍须拒绝纯行号,避免历史错误进入候选。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Reservation ID</th><th>Qty</th></tr><tr><td>00010</td><td>1</td></tr></table>',
|
||||
_field('reservation_id', ['Reservation ID'], normalizer_key='reservation_id'),
|
||||
_field('qty', ['Qty'], value_type='integer'),
|
||||
)
|
||||
|
||||
assert [(field.field_code, field.value) for field in result.rows[0].fields] == [('qty', 1)]
|
||||
|
||||
|
||||
def test_nested_table_rows_do_not_pollute_parent_grid():
|
||||
"""主表单元格内的嵌套展示表格不得被重复解析成主表数据行。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th>Part</th><th>Detail</th></tr><tr><td>A-1</td>'
|
||||
'<td><table><tr><td>nested</td></tr></table></td></tr></table>',
|
||||
table_id='outer',
|
||||
)
|
||||
|
||||
assert (grid.row_count, grid.column_count) == (2, 2)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('attribute', ['rowspan="0"', 'colspan="bad"'])
|
||||
def test_invalid_span_is_rejected(attribute: str):
|
||||
"""零值或非数字跨度必须拒绝,禁止产生不稳定网格。"""
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
parse_html_grid(f'<table><tr><td {attribute}>A</td></tr></table>', table_id='t')
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.LAYOUT_HTML_TABLE_INVALID'
|
||||
@@ -0,0 +1,275 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_mineru.py
|
||||
|
||||
用途:验证 MinerU 客户端资源门禁、字符串 JSON 解包、HTML 表格候选和单元格证据准入。
|
||||
依赖:document_layout.mineru、统一 AppError、requests Response 协议最小替身。
|
||||
逻辑:全部使用脱敏构造响应,不访问真实 MinerU 服务,也不把文件正文写入失败输出。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.services.shipping_notice.document_layout.mineru import (
|
||||
MinerUClient,
|
||||
MinerUClientConfig,
|
||||
parse_mineru_candidate,
|
||||
)
|
||||
|
||||
|
||||
def _mineru_payload(*, with_cell_coordinates: bool = False) -> dict:
|
||||
"""构造与 MinerU 3.1.14 pipeline 相同的字符串 JSON 包装。"""
|
||||
cell_coordinate = ([
|
||||
{'row_idx': 0, 'col_idx': 0, 'bbox': [10, 20, 50, 40]},
|
||||
{'row_idx': 0, 'col_idx': 1, 'bbox': [50, 20, 90, 40]},
|
||||
{'row_idx': 1, 'col_idx': 0, 'bbox': [10, 40, 50, 60]},
|
||||
{'row_idx': 1, 'col_idx': 1, 'bbox': [50, 40, 90, 60]},
|
||||
] if with_cell_coordinates else [])
|
||||
return {
|
||||
'task_id': 'task-layout-fixture',
|
||||
'status': 'completed',
|
||||
'backend': 'pipeline',
|
||||
'version': '3.1.14',
|
||||
'results': {
|
||||
'fixture': {
|
||||
'middle_json': json.dumps({
|
||||
'pdf_info': [{
|
||||
'page_idx': 0,
|
||||
'page_size': [100, 200],
|
||||
'blocks': [{'type': 'text', 'bbox': [5, 5, 20, 15]}],
|
||||
}],
|
||||
'cell_coordinates': cell_coordinate,
|
||||
}),
|
||||
'model_output': json.dumps([{
|
||||
'page_info': {'page_no': 0, 'width': 100, 'height': 200},
|
||||
'layout_dets': [{'label': 'table', 'bbox': [10, 20, 90, 120]}],
|
||||
}]),
|
||||
'content_list': json.dumps([{
|
||||
'type': 'table',
|
||||
'page_idx': 0,
|
||||
'bbox': [10, 20, 90, 120],
|
||||
'table_body': (
|
||||
'<table><tr><th>Part</th><th>Qty</th></tr>'
|
||||
'<tr><td>A-1</td><td>2</td></tr></table>'
|
||||
),
|
||||
}, {
|
||||
'type': 'text',
|
||||
'page_idx': 0,
|
||||
'bbox': [5, 5, 20, 15],
|
||||
'text': 'Header context',
|
||||
}]),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class _FakeResponse:
|
||||
"""实现 MinerUClient 使用的 requests.Response 最小协议。"""
|
||||
|
||||
def __init__(self, payload: dict, *, status_code: int = 200, content_length: int | None = None):
|
||||
self.status_code = status_code
|
||||
self.encoding = 'utf-8'
|
||||
self.raw = json.dumps(payload, separators=(',', ':')).encode('utf-8')
|
||||
self.headers = {
|
||||
'Content-Length': str(len(self.raw) if content_length is None else content_length),
|
||||
}
|
||||
self.closed = False
|
||||
|
||||
def iter_content(self, chunk_size: int):
|
||||
"""按客户端指定大小分块返回构造 JSON。"""
|
||||
for index in range(0, len(self.raw), chunk_size):
|
||||
yield self.raw[index:index + chunk_size]
|
||||
|
||||
def close(self):
|
||||
"""记录响应已关闭,验证资源上限分支不泄漏连接。"""
|
||||
self.closed = True
|
||||
|
||||
|
||||
class _FakeSession:
|
||||
"""记录 multipart 调用并返回预设响应。"""
|
||||
|
||||
def __init__(self, response: _FakeResponse):
|
||||
self.response = response
|
||||
self.calls: list[dict] = []
|
||||
|
||||
def post(self, url: str, **kwargs):
|
||||
"""保存非敏感调用元数据;文件字节仅验证长度,不保存到测试输出。"""
|
||||
files = kwargs.get('files') or []
|
||||
self.calls.append({
|
||||
'url': url,
|
||||
'timeout': kwargs.get('timeout'),
|
||||
'stream': kwargs.get('stream'),
|
||||
'file_size': len(files[0][1][1]) if files else 0,
|
||||
'data': list(kwargs.get('data') or []),
|
||||
})
|
||||
return self.response
|
||||
|
||||
|
||||
def test_mineru_candidate_preserves_table_structure_but_blocks_cell_evidence():
|
||||
"""只有整表 bbox + HTML 时必须保留行列候选并阻止确定性单元格证据。"""
|
||||
candidate = parse_mineru_candidate(_mineru_payload())
|
||||
|
||||
assert len(candidate.pages) == 1
|
||||
assert candidate.pages[0].text_blocks[0].text == 'Header context'
|
||||
assert candidate.pages[0].tables[0].row_count == 2
|
||||
assert candidate.pages[0].tables[0].cell_count == 4
|
||||
assert candidate.pages[0].tables[0].normalized_bbox.model_dump() == {
|
||||
'x0': 0.01, 'y0': 0.02, 'x1': 0.09, 'y1': 0.12,
|
||||
}
|
||||
assert candidate.pages[0].tables[0].bbox.model_dump() == {
|
||||
'x0': 1.0, 'y0': 4.0, 'x1': 9.0, 'y1': 24.0,
|
||||
}
|
||||
assert candidate.capability.has_page_coordinates is True
|
||||
assert candidate.capability.has_table_structure is True
|
||||
assert candidate.capability.has_cell_coordinates is False
|
||||
assert candidate.capability.deterministic_cell_evidence_ready is False
|
||||
assert candidate.capability.issues == ['mineru_cell_coordinates_missing']
|
||||
|
||||
|
||||
def test_mineru_capability_accepts_explicit_cell_coordinate_objects():
|
||||
"""服务未来直接返回带行列身份的 cell bbox 时能力报告才能标记证据就绪。"""
|
||||
candidate = parse_mineru_candidate(_mineru_payload(with_cell_coordinates=True))
|
||||
|
||||
assert candidate.capability.cell_bbox_count == 4
|
||||
assert candidate.capability.has_cell_coordinates is True
|
||||
assert candidate.capability.deterministic_cell_evidence_ready is True
|
||||
assert candidate.capability.issues == []
|
||||
|
||||
|
||||
def test_mineru_capability_rejects_partial_cell_coordinates():
|
||||
"""部分单元格有坐标仍不足以证明整表,必须保持确定性证据未就绪。"""
|
||||
payload = _mineru_payload(with_cell_coordinates=True)
|
||||
middle = json.loads(payload['results']['fixture']['middle_json'])
|
||||
middle['cell_coordinates'] = middle['cell_coordinates'][:1]
|
||||
payload['results']['fixture']['middle_json'] = json.dumps(middle)
|
||||
|
||||
candidate = parse_mineru_candidate(payload)
|
||||
|
||||
assert candidate.capability.cell_bbox_count == 1
|
||||
assert candidate.capability.html_cell_count == 4
|
||||
assert candidate.capability.has_cell_coordinates is False
|
||||
assert candidate.capability.deterministic_cell_evidence_ready is False
|
||||
assert candidate.capability.issues == ['mineru_cell_coordinates_incomplete']
|
||||
|
||||
|
||||
def test_mineru_client_sends_bounded_single_file_request():
|
||||
"""客户端只提交单文件、关闭图片/公式输出,并使用配置化超时。"""
|
||||
response = _FakeResponse(_mineru_payload())
|
||||
session = _FakeSession(response)
|
||||
client = MinerUClient(
|
||||
MinerUClientConfig(
|
||||
base_url='http://mineru.internal:8100/',
|
||||
backend='pipeline',
|
||||
connect_timeout_seconds=3,
|
||||
read_timeout_seconds=45,
|
||||
),
|
||||
session=session,
|
||||
)
|
||||
|
||||
payload = client.parse_file(filename='fixture.pdf', content=b'%PDF-fixture')
|
||||
|
||||
assert payload['status'] == 'completed'
|
||||
assert session.calls == [{
|
||||
'url': 'http://mineru.internal:8100/file_parse',
|
||||
'timeout': (3, 45),
|
||||
'stream': True,
|
||||
'file_size': 12,
|
||||
'data': [
|
||||
('backend', 'pipeline'), ('parse_method', 'auto'), ('formula_enable', 'false'),
|
||||
('table_enable', 'true'), ('image_analysis', 'false'), ('return_md', 'false'),
|
||||
('return_middle_json', 'true'), ('return_model_output', 'true'),
|
||||
('return_content_list', 'true'), ('return_images', 'false'),
|
||||
('response_format_zip', 'false'), ('lang_list', 'ch'),
|
||||
],
|
||||
}]
|
||||
assert response.closed is True
|
||||
|
||||
|
||||
def test_mineru_client_rejects_unsupported_empty_and_large_files_before_network():
|
||||
"""文件类型、空内容和上传上限必须在 HTTP 请求前拒绝。"""
|
||||
session = _FakeSession(_FakeResponse(_mineru_payload()))
|
||||
client = MinerUClient(
|
||||
MinerUClientConfig(base_url='http://mineru.internal:8100', max_upload_bytes=4),
|
||||
session=session,
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as unsupported:
|
||||
client.parse_file(filename='fixture.xlsx', content=b'1234')
|
||||
assert unsupported.value.code == 'SHIPPING_NOTICE.LAYOUT_FILE_TYPE_UNSUPPORTED'
|
||||
|
||||
with pytest.raises(ValidationError) as empty:
|
||||
client.parse_file(filename='fixture.pdf', content=b'')
|
||||
assert empty.value.code == 'SHIPPING_NOTICE.LAYOUT_FILE_EMPTY'
|
||||
|
||||
with pytest.raises(ValidationError) as large:
|
||||
client.parse_file(filename='fixture.pdf', content=b'12345')
|
||||
assert large.value.code == 'SHIPPING_NOTICE.LAYOUT_FILE_TOO_LARGE'
|
||||
assert session.calls == []
|
||||
|
||||
|
||||
def test_mineru_client_stops_oversized_response_and_closes_connection():
|
||||
"""Content-Length 已超限时不得读取响应正文,并必须关闭连接。"""
|
||||
response = _FakeResponse(_mineru_payload(), content_length=10_000)
|
||||
client = MinerUClient(
|
||||
MinerUClientConfig(base_url='http://mineru.internal:8100', max_response_bytes=100),
|
||||
session=_FakeSession(response),
|
||||
)
|
||||
|
||||
with pytest.raises(ServiceUnavailableError) as caught:
|
||||
client.parse_file(filename='fixture.pdf', content=b'%PDF')
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.LAYOUT_PROVIDER_RESPONSE_TOO_LARGE'
|
||||
assert response.closed is True
|
||||
|
||||
|
||||
def test_mineru_client_classifies_terminal_provider_error_without_filename_leak():
|
||||
"""MinerU 409 终态失败应返回稳定非重试错误,details 不得包含上传文件名。"""
|
||||
response = _FakeResponse({
|
||||
'task_id': 'failed-task',
|
||||
'status': 'failed',
|
||||
'backend': 'hybrid-auto-engine',
|
||||
'file_names': ['sensitive-order-name'],
|
||||
'error': 'Device string must not be empty',
|
||||
}, status_code=409)
|
||||
client = MinerUClient(
|
||||
MinerUClientConfig(base_url='http://mineru.internal:8100'),
|
||||
session=_FakeSession(response),
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
client.parse_file(filename='sensitive-order-name.pdf', content=b'%PDF')
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.LAYOUT_PROVIDER_PARSE_FAILED'
|
||||
assert caught.value.retryable is False
|
||||
assert 'sensitive-order-name' not in json.dumps(caught.value.details)
|
||||
assert caught.value.details['provider_error_code'] == 'device_not_configured'
|
||||
|
||||
|
||||
def test_mineru_candidate_rejects_invalid_nested_json_and_multiple_files():
|
||||
"""嵌套 JSON 损坏或批量结果不得被单 Document 适配器接受。"""
|
||||
invalid_json = _mineru_payload()
|
||||
invalid_json['results']['fixture']['middle_json'] = 'not-json'
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
parse_mineru_candidate(invalid_json)
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE'
|
||||
|
||||
multiple = _mineru_payload()
|
||||
multiple['results']['other'] = dict(multiple['results']['fixture'])
|
||||
with pytest.raises(ValidationError, match='exactly one file'):
|
||||
parse_mineru_candidate(multiple)
|
||||
|
||||
|
||||
def test_mineru_candidate_rejects_content_bbox_outside_provider_canvas():
|
||||
"""content_list bbox 超过 MinerU 0..1000 画布时不得截断或猜测坐标。"""
|
||||
payload = _mineru_payload()
|
||||
content = json.loads(payload['results']['fixture']['content_list'])
|
||||
content[0]['bbox'] = [10, 20, 1001, 120]
|
||||
payload['results']['fixture']['content_list'] = json.dumps(content)
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
parse_mineru_candidate(payload)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE'
|
||||
@@ -0,0 +1,230 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_opencv_table.py
|
||||
|
||||
用途:验证 OpenCV 有框表多参数共识只在网格完整稳定时输出 HTML cell 几何候选。
|
||||
依赖:numpy、opencv_table、html_table、LayoutBBox。
|
||||
逻辑:使用合成页面覆盖标准网格、rowspan/colspan、无框表、形状不匹配和参数不足门禁。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.opencv_table import (
|
||||
DEFAULT_GRID_CONFIGS,
|
||||
reconstruct_opencv_table_geometry,
|
||||
validate_opencv_cell_text,
|
||||
)
|
||||
|
||||
|
||||
def _page_with_grid(*, rows: int, columns: int, width: int = 600, height: int = 400) -> np.ndarray:
|
||||
"""生成具有清晰闭合边界的合成灰度表格页面。"""
|
||||
image = np.full((height, width), 255, dtype=np.uint8)
|
||||
x_values = np.linspace(100, 500, columns + 1).astype(int)
|
||||
y_values = np.linspace(80, 320, rows + 1).astype(int)
|
||||
for x in x_values:
|
||||
cv2.line(image, (x, y_values[0]), (x, y_values[-1]), 0, 2)
|
||||
for y in y_values:
|
||||
cv2.line(image, (x_values[0], y), (x_values[-1], y), 0, 2)
|
||||
return image
|
||||
|
||||
|
||||
def _bbox() -> LayoutBBox:
|
||||
"""返回与合成表格略带外边距的页面单位 bbox。"""
|
||||
return LayoutBBox(x0=95, y0=75, x1=505, y1=325)
|
||||
|
||||
|
||||
def test_opencv_grid_consensus_returns_all_html_cell_geometries():
|
||||
"""多参数检测一致且形状匹配时应为每个 HTML cell 返回页面 bbox。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th>A</th><th>B</th></tr><tr><td>C</td><td>D</td></tr></table>',
|
||||
table_id='t',
|
||||
)
|
||||
|
||||
result = reconstruct_opencv_table_geometry(
|
||||
_page_with_grid(rows=2, columns=2),
|
||||
page_width=600,
|
||||
page_height=400,
|
||||
table_bbox=_bbox(),
|
||||
grid=grid,
|
||||
)
|
||||
|
||||
assert result.ready is True
|
||||
assert result.consensus_count >= 2
|
||||
assert len(result.cells) == 4
|
||||
assert result.cells[0].bbox.x0 < result.cells[1].bbox.x0
|
||||
assert result.cells[0].normalized_bbox.x1 <= 1
|
||||
|
||||
|
||||
def test_opencv_grid_uses_html_spans_to_merge_base_cells():
|
||||
"""rowspan/colspan 由 HTML 决定,几何候选必须跨越对应基础网格边界。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th rowspan="2">A</th><th>B</th></tr><tr><td>C</td></tr></table>',
|
||||
table_id='span',
|
||||
)
|
||||
|
||||
result = reconstruct_opencv_table_geometry(
|
||||
_page_with_grid(rows=2, columns=2),
|
||||
page_width=600,
|
||||
page_height=400,
|
||||
table_bbox=_bbox(),
|
||||
grid=grid,
|
||||
)
|
||||
|
||||
assert result.ready is True
|
||||
merged = next(cell for cell in result.cells if cell.row_span == 2)
|
||||
ordinary = next(cell for cell in result.cells if cell.row_index == 0 and cell.column_index == 1)
|
||||
assert merged.bbox.y1 > ordinary.bbox.y1
|
||||
|
||||
|
||||
def test_opencv_grid_rejects_shape_mismatch_without_exposing_cells():
|
||||
"""图像三列表与 HTML 两列表不一致时必须失败,不能裁剪或合并到预期形状。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th>A</th><th>B</th></tr><tr><td>C</td><td>D</td></tr></table>',
|
||||
table_id='mismatch',
|
||||
)
|
||||
|
||||
result = reconstruct_opencv_table_geometry(
|
||||
_page_with_grid(rows=2, columns=3),
|
||||
page_width=600,
|
||||
page_height=400,
|
||||
table_bbox=_bbox(),
|
||||
grid=grid,
|
||||
)
|
||||
|
||||
assert result.ready is False
|
||||
assert result.cells == []
|
||||
assert result.issues
|
||||
|
||||
|
||||
def test_opencv_grid_rejects_borderless_table():
|
||||
"""无框页面不得按 HTML 行列数均分生成伪 cell bbox。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th>A</th><th>B</th></tr><tr><td>C</td><td>D</td></tr></table>',
|
||||
table_id='borderless',
|
||||
)
|
||||
page = np.full((400, 600), 255, dtype=np.uint8)
|
||||
cv2.putText(page, 'A B', (120, 120), cv2.FONT_HERSHEY_SIMPLEX, 0.8, 0, 2)
|
||||
cv2.putText(page, 'C D', (120, 220), cv2.FONT_HERSHEY_SIMPLEX, 0.8, 0, 2)
|
||||
|
||||
result = reconstruct_opencv_table_geometry(
|
||||
page,
|
||||
page_width=600,
|
||||
page_height=400,
|
||||
table_bbox=_bbox(),
|
||||
grid=grid,
|
||||
)
|
||||
|
||||
assert result.ready is False
|
||||
assert result.cells == []
|
||||
|
||||
|
||||
def test_opencv_grid_requires_multiple_detection_configurations():
|
||||
"""单参数结果不能形成共识,避免特定阈值偶然命中进入证据链。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th>A</th><th>B</th></tr><tr><td>C</td><td>D</td></tr></table>',
|
||||
table_id='config',
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match='at least two configurations'):
|
||||
reconstruct_opencv_table_geometry(
|
||||
_page_with_grid(rows=2, columns=2),
|
||||
page_width=600,
|
||||
page_height=400,
|
||||
table_bbox=_bbox(),
|
||||
grid=grid,
|
||||
configs=(DEFAULT_GRID_CONFIGS[0],),
|
||||
)
|
||||
|
||||
|
||||
def test_opencv_text_validation_accepts_matching_cells_and_required_subset():
|
||||
"""几何候选文本全部一致且高风险 cell 命中时才通过独立验收。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th>Part</th><th>Qty</th></tr><tr><td>A-1</td><td>2</td></tr></table>',
|
||||
table_id='text-ok',
|
||||
)
|
||||
geometry = reconstruct_opencv_table_geometry(
|
||||
_page_with_grid(rows=2, columns=2),
|
||||
page_width=600,
|
||||
page_height=400,
|
||||
table_bbox=_bbox(),
|
||||
grid=grid,
|
||||
)
|
||||
values = {cell.cell_id: cell.text for cell in grid.cells}
|
||||
by_box = {
|
||||
(item.bbox.x0, item.bbox.y0, item.bbox.x1, item.bbox.y1): values[item.cell_id]
|
||||
for item in geometry.cells
|
||||
}
|
||||
|
||||
result = validate_opencv_cell_text(
|
||||
geometry,
|
||||
grid=grid,
|
||||
bounded_text_reader=lambda box: by_box[(box.x0, box.y0, box.x1, box.y1)],
|
||||
required_cell_ids={grid.cells[2].cell_id, grid.cells[3].cell_id},
|
||||
)
|
||||
|
||||
assert result.accepted is True
|
||||
assert result.match_rate == 1
|
||||
assert result.mismatched_cell_ids == []
|
||||
|
||||
|
||||
def test_opencv_text_validation_rejects_required_cell_mismatch_even_above_rate():
|
||||
"""高风险 cell 文本不一致时,即使总体比例达到阈值也必须拒绝整表。"""
|
||||
html = '<table><tr>' + ''.join(f'<th>H{i}</th>' for i in range(10)) + '</tr></table>'
|
||||
grid = parse_html_grid(html, table_id='required-fail')
|
||||
geometry = reconstruct_opencv_table_geometry(
|
||||
_page_with_grid(rows=1, columns=10),
|
||||
page_width=600,
|
||||
page_height=400,
|
||||
table_bbox=_bbox(),
|
||||
grid=grid,
|
||||
)
|
||||
required_id = grid.cells[-1].cell_id
|
||||
values = {cell.cell_id: cell.text for cell in grid.cells}
|
||||
by_box = {
|
||||
(item.bbox.x0, item.bbox.y0, item.bbox.x1, item.bbox.y1): (
|
||||
'WRONG' if item.cell_id == required_id else values[item.cell_id]
|
||||
)
|
||||
for item in geometry.cells
|
||||
}
|
||||
|
||||
result = validate_opencv_cell_text(
|
||||
geometry,
|
||||
grid=grid,
|
||||
bounded_text_reader=lambda box: by_box[(box.x0, box.y0, box.x1, box.y1)],
|
||||
minimum_match_rate=0.9,
|
||||
required_cell_ids={required_id},
|
||||
)
|
||||
|
||||
assert result.match_rate == 0.9
|
||||
assert result.accepted is False
|
||||
assert 'opencv_table_required_cell_text_mismatch' in result.issues
|
||||
|
||||
|
||||
def test_opencv_text_validation_rejects_low_overall_match_rate():
|
||||
"""非高风险 cell 大量错位也必须因整表一致率不足而拒绝。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th>A</th><th>B</th></tr><tr><td>C</td><td>D</td></tr></table>',
|
||||
table_id='rate-fail',
|
||||
)
|
||||
geometry = reconstruct_opencv_table_geometry(
|
||||
_page_with_grid(rows=2, columns=2),
|
||||
page_width=600,
|
||||
page_height=400,
|
||||
table_bbox=_bbox(),
|
||||
grid=grid,
|
||||
)
|
||||
|
||||
result = validate_opencv_cell_text(
|
||||
geometry,
|
||||
grid=grid,
|
||||
bounded_text_reader=lambda _box: 'WRONG',
|
||||
)
|
||||
|
||||
assert result.accepted is False
|
||||
assert result.match_rate == 0
|
||||
assert 'opencv_table_text_match_rate_low' in result.issues
|
||||
@@ -21,6 +21,33 @@ from app.services.shipping_notice.reservation_id import (
|
||||
looks_like_reservation_id,
|
||||
normalize_reservation_id,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
|
||||
def _table_schema_definition() -> dict:
|
||||
"""构造本文件表格样本使用的显式动态 Schema,禁止依赖生产硬编码别名。"""
|
||||
aliases = {
|
||||
'line_no': ['Line No'], 'part_number': ['Part Number', 'MPN', 'Vendor Part Number'],
|
||||
'qty': ['Qty', 'Quantity', 'Order Qty', 'Allocated QTY'], 'unit_price': ['Unit Price'],
|
||||
'amount': ['Amount'], 'currency': ['Currency'],
|
||||
'reservation_id': ['Reservation ID', 'Reservation Order', 'Reservation N.r', 'External reservation ID'],
|
||||
'required_date': ['ETA'], 'customer_part_number': ['Allocated HHPN'],
|
||||
'aws_part_number': ['Allocated APN', 'Material', 'AWS Sku'],
|
||||
'inventory_source_hint': ['source type'], 'po_number': ['PO'],
|
||||
}
|
||||
decimal_fields = {'qty', 'unit_price', 'amount'}
|
||||
return {'fields': [{
|
||||
'field_id': f'test-{code}', 'field_code': code,
|
||||
'scope': 'header' if code == 'po_number' else 'line',
|
||||
'value_type': 'decimal' if code in decimal_fields else 'date' if code == 'required_date' else 'string',
|
||||
'enabled': True, 'display_name': code, 'aliases': values, 'normalizer_key': 'trim',
|
||||
'validator_keys': ['positive_decimal'] if code == 'qty' else ['reservation_id'] if code == 'reservation_id' else [],
|
||||
} for code, values in aliases.items()]}
|
||||
|
||||
|
||||
def _table_contract():
|
||||
"""编译测试共享的冻结表头契约。"""
|
||||
return compile_table_header_contract(_table_schema_definition())
|
||||
|
||||
|
||||
def _minimal_pdf_bytes(marker: str) -> bytes:
|
||||
@@ -146,7 +173,7 @@ S-ENC-FOBU260702-286\t2000485916\tVMI-FRA01\tTEMP-S000218922\t504-006043-001\t30
|
||||
S-BRA-FOBU260702-187\t2000485915\tVMI-FRA01\tTEMP-S000196207\t504-006076-001\t60\tD4-AR1200115A1\tFRA01\t4510039228
|
||||
S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD4-A08AR12000001\tDUB\t4510039229
|
||||
"""
|
||||
rows = build_email_order_index(body)
|
||||
rows = build_email_order_index(body, schema_definition=_table_schema_definition())
|
||||
assert len(rows) == 3
|
||||
assert rows[0]['po_number'] == '4510039227'
|
||||
assert rows[0]['reservation_id'] == '2000485916'
|
||||
@@ -1247,7 +1274,9 @@ def test_external_reservation_id_corrects_invalid_llm_candidate_with_column_evid
|
||||
}
|
||||
]
|
||||
|
||||
adjudicated, issues, status = adjudicate_notice_lines(lines, raw_text=raw_text)
|
||||
adjudicated, issues, status = adjudicate_notice_lines(
|
||||
lines, raw_text=raw_text, schema_definition=_table_schema_definition(),
|
||||
)
|
||||
|
||||
assert status == "ready"
|
||||
assert adjudicated[0]["reservation_id"] == "3000092917"
|
||||
@@ -1280,7 +1309,9 @@ def test_flattened_text_does_not_guess_external_reservation_id():
|
||||
}
|
||||
]
|
||||
|
||||
adjudicated, issues, status = adjudicate_notice_lines(lines, raw_text=raw_text)
|
||||
adjudicated, issues, status = adjudicate_notice_lines(
|
||||
lines, raw_text=raw_text, schema_definition=_table_schema_definition(),
|
||||
)
|
||||
|
||||
assert status == "needs_review"
|
||||
assert "reservation_id" not in adjudicated[0]
|
||||
@@ -1293,28 +1324,30 @@ def test_adjudication_supports_non_numeric_reservation_templates():
|
||||
raw_text = "Part Number\tReservation Order\tQty\nA001\tAWS-311\t2"
|
||||
lines = [{"part_number": "A001", "reservation_id": "", "qty": 2, "uom": "EA"}]
|
||||
|
||||
adjudicated, issues, status = adjudicate_notice_lines(lines, raw_text=raw_text)
|
||||
adjudicated, issues, status = adjudicate_notice_lines(
|
||||
lines, raw_text=raw_text, schema_definition=_table_schema_definition(),
|
||||
)
|
||||
|
||||
assert status == "ready"
|
||||
assert adjudicated[0]["reservation_id"] == "AWS-311"
|
||||
assert issues[0]["reason"] == "value_corrected"
|
||||
|
||||
|
||||
def test_wistron_po_table_with_pr_number_in_document():
|
||||
def test_wistron_po_table_does_not_broadcast_document_reservation_to_every_line():
|
||||
text = """
|
||||
Vendor: HOXIN
|
||||
PR Number: ADU_S-ENCWIW260528126265@1000140351
|
||||
Line No\tMaterial\tVendor Part Number\tDescription\tQuantity\tETA\tUnit Price\tAmount
|
||||
10\t504-010213-001\tB3-A08AR11000001\tENCLOSURE\t9.000 PCS\t2026/06/15\t1,607.72 USD\t14,469.48 USD
|
||||
"""
|
||||
lines = parse_notice_table_text(text)
|
||||
lines = parse_notice_table_text(text, contract=_table_contract())
|
||||
assert len(lines) == 1
|
||||
assert lines[0]["part_number"] == "B3-A08AR11000001"
|
||||
assert lines[0]["line_no"] == "10"
|
||||
assert lines[0]["qty"] == 9.0
|
||||
assert lines[0]["unit_price"] == 1607.72
|
||||
assert lines[0]["amount"] == 14469.48
|
||||
assert lines[0]["reservation_id"] == "1000140351"
|
||||
assert "reservation_id" not in lines[0]
|
||||
assert lines[0]["required_date"] == "2026-06-15"
|
||||
assert lines[0]["aws_part_number"] == "504-010213-001"
|
||||
assert lines[0]["currency"] == "USD"
|
||||
@@ -1331,15 +1364,15 @@ def test_parse_notice_table_numeric_reservation_id():
|
||||
Part Number\tReservation ID\tQty\tUnit Price\tAmount
|
||||
10-40594-001\t1000140351\t2\t15.5\t31.0
|
||||
"""
|
||||
lines = parse_notice_table_text(text)
|
||||
lines = parse_notice_table_text(text, contract=_table_contract())
|
||||
assert lines[0]["reservation_id"] == "1000140351"
|
||||
|
||||
|
||||
def test_infer_reservation_id_without_header():
|
||||
def test_does_not_infer_reservation_id_without_configured_header():
|
||||
headers = ["Part Number", "Ref", "Qty"]
|
||||
rows = [["10-40594-001", 1000140351, 2]]
|
||||
lines = parse_notice_table_rows(headers, rows)
|
||||
assert lines[0]["reservation_id"] == "1000140351"
|
||||
lines = parse_notice_table_rows(headers, rows, contract=_table_contract())
|
||||
assert "reservation_id" not in lines[0]
|
||||
|
||||
|
||||
def test_parse_notice_table_with_all_fields():
|
||||
@@ -1348,7 +1381,7 @@ Part Number\tReservation ID\tQty\tUnit Price\tAmount
|
||||
10-40594-001\tAWS-311\t2\t15.5\t31.0
|
||||
10-40594-002\tORD-3002\t1\t20\t20
|
||||
"""
|
||||
lines = parse_notice_table_text(text)
|
||||
lines = parse_notice_table_text(text, contract=_table_contract())
|
||||
assert len(lines) == 2
|
||||
assert lines[0]["part_number"] == "10-40594-001"
|
||||
assert lines[0]["reservation_id"] == "AWS-311"
|
||||
@@ -1375,7 +1408,6 @@ def test_normalize_notice_line_aliases():
|
||||
"line_no": "10",
|
||||
"part_number": "A-001",
|
||||
"qty": 3.0,
|
||||
"uom": "EA",
|
||||
"reservation_id": "COM-99",
|
||||
"unit_price": 12.5,
|
||||
"amount": 37.5,
|
||||
@@ -1412,6 +1444,7 @@ def test_parse_notice_table_maps_three_part_number_roles():
|
||||
lines = parse_notice_table_rows(
|
||||
["MPN", "Allocated HHPN", "Allocated APN", "Allocated QTY"],
|
||||
[["D4-A08AR12000002", "TEMP-S000218929", "504-006055-001", 10]],
|
||||
contract=_table_contract(),
|
||||
)
|
||||
|
||||
assert lines == [{
|
||||
@@ -1419,7 +1452,6 @@ def test_parse_notice_table_maps_three_part_number_roles():
|
||||
"customer_part_number": "TEMP-S000218929",
|
||||
"aws_part_number": "504-006055-001",
|
||||
"qty": 10.0,
|
||||
"uom": "EA",
|
||||
}]
|
||||
|
||||
|
||||
@@ -1428,6 +1460,7 @@ def test_parse_notice_table_rejects_aws_only_as_internal_part_number():
|
||||
assert parse_notice_table_rows(
|
||||
["AWS Sku", "Reservation ID", "Qty"],
|
||||
[["504-006055-001", "3000092917", 10]],
|
||||
contract=_table_contract(),
|
||||
) == []
|
||||
|
||||
|
||||
@@ -1500,7 +1533,7 @@ Shipping Notice
|
||||
Part Number\tReservation Order\tOrder Qty\tUnit Price\tLine Amount
|
||||
10-40594-001\tORD-3002\t4\t5\t20
|
||||
"""
|
||||
parsed, confidence, _ = _heuristic_extract(text)
|
||||
parsed, confidence, _ = _heuristic_extract(text, schema_definition=_table_schema_definition())
|
||||
assert len(parsed["lines"]) == 1
|
||||
assert parsed["lines"][0]["part_number"] == "10-40594-001"
|
||||
assert parsed["lines"][0]["reservation_id"] == "ORD-3002"
|
||||
@@ -1530,7 +1563,9 @@ def test_extract_notice_fields_structured_over_heuristic():
|
||||
def test_extract_notice_fields_heuristic_fallback():
|
||||
"""无 structured 时走后端启发式兜底。"""
|
||||
text = "Part Number\tReservation Order\tOrder Qty\n10-40594-001\tORD-3002\t4"
|
||||
parsed, _, warnings = extract_notice_fields(raw_text=text)
|
||||
parsed, _, warnings = extract_notice_fields(
|
||||
raw_text=text, schema_definition=_table_schema_definition(),
|
||||
)
|
||||
assert parsed["parse_source"] == "heuristic"
|
||||
assert parsed["lines"][0]["part_number"] == "10-40594-001"
|
||||
assert "parse_fallback_heuristic" in warnings
|
||||
@@ -17,6 +17,27 @@ from app.services.shipping_notice.field_adjudication import (
|
||||
)
|
||||
|
||||
|
||||
def _schema_definition() -> dict:
|
||||
"""构造裁决测试使用的显式行字段 Schema。"""
|
||||
return {'fields': [
|
||||
{
|
||||
'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
|
||||
'enabled': True, 'display_name': '内部料号', 'aliases': ['MPN'],
|
||||
'normalizer_key': 'uppercase_trim', 'validator_keys': ['atomic_part_number'],
|
||||
},
|
||||
{
|
||||
'field_id': 'qty', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal',
|
||||
'enabled': True, 'display_name': '数量', 'aliases': ['Qty'],
|
||||
'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'],
|
||||
},
|
||||
{
|
||||
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string',
|
||||
'enabled': True, 'display_name': '预约单号', 'aliases': ['Reservation ID'],
|
||||
'normalizer_key': 'trim', 'validator_keys': ['reservation_id'],
|
||||
},
|
||||
]}
|
||||
|
||||
|
||||
def _document(document_id: int, text: str):
|
||||
"""构造裁决服务所需的最小 Document 测试替身。"""
|
||||
return SimpleNamespace(id=document_id, extracted_text=text)
|
||||
@@ -55,6 +76,7 @@ def test_adjudication_uses_verified_dify_when_backend_has_no_table():
|
||||
{"lines": [line]},
|
||||
raw_order=raw_order,
|
||||
documents=[document],
|
||||
schema_definition=_schema_definition(),
|
||||
field_confidence=raw_order["field_confidence"],
|
||||
)
|
||||
|
||||
@@ -72,6 +94,7 @@ def test_adjudication_uses_backend_when_dify_field_is_missing():
|
||||
{"lines": [{"qty": 10}]},
|
||||
raw_order=raw_order,
|
||||
documents=[document],
|
||||
schema_definition=_schema_definition(),
|
||||
)
|
||||
|
||||
assert result["summary"]["lines"][0]["part_number"] == "D4-A08AR12000002"
|
||||
@@ -89,6 +112,7 @@ def test_adjudication_marks_consensus_without_overwriting_observations():
|
||||
{"lines": [line]},
|
||||
raw_order=raw_order,
|
||||
documents=[document],
|
||||
schema_definition=_schema_definition(),
|
||||
field_confidence=raw_order["field_confidence"],
|
||||
)
|
||||
|
||||
@@ -113,6 +137,7 @@ def test_adjudication_blocks_two_trusted_different_values():
|
||||
{"lines": [line]},
|
||||
raw_order=raw_order,
|
||||
documents=[document],
|
||||
schema_definition=_schema_definition(),
|
||||
field_confidence=raw_order["field_confidence"],
|
||||
)
|
||||
|
||||
@@ -132,6 +157,7 @@ def test_adjudication_prefers_backend_when_dify_quote_is_unverified():
|
||||
{"lines": [line]},
|
||||
raw_order=raw_order,
|
||||
documents=[document],
|
||||
schema_definition=_schema_definition(),
|
||||
field_confidence=raw_order["field_confidence"],
|
||||
)
|
||||
|
||||
@@ -151,6 +177,7 @@ def test_adjudication_builds_multiple_lines_from_backend_only():
|
||||
{"lines": []},
|
||||
raw_order={"lines": [], "evidence": []},
|
||||
documents=[document],
|
||||
schema_definition=_schema_definition(),
|
||||
)
|
||||
|
||||
assert [line["part_number"] for line in result["summary"]["lines"]] == ["D4-A", "D4-B"]
|
||||
|
||||
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user