refactor(agent, shipping): 简化代理模型并完善订单抽取业务
- 移除 Agent 的 exposure_mode 与 internal_executor 相关逻辑,清理关联的过滤、序列化代码 - 删除废弃的 AgentRuntimeBinding 模型及其依赖 - 新增订单抽取上传批次、请求快照等数据库迁移与业务逻辑 - 修复附件完整性检测、订单抽取状态映射问题 - 更新多语言错误文案与前端单元测试配置 - 清理平台配置中不再使用的暴露模式配置
This commit is contained in:
1 parent
1f3ecb87b7
commit
61ac6403c4
159 files changed
+12883
-5099
No files matched your search
@@ -9,7 +9,6 @@ from flask import g, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.admin import agent_service
|
||||
|
||||
@@ -69,8 +68,8 @@ def list_agent_intent_routes():
|
||||
@admin_bp.route('/agents', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agents():
|
||||
"""按管理页签返回应用或内部执行器;缺省 scope 保持旧版全部列表兼容。"""
|
||||
return ok(agent_service.list_agents(scope=request.args.get('scope')), request_id=_request_id())
|
||||
"""列出全部应用。"""
|
||||
return ok(agent_service.list_agents(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents', methods=['POST'])
|
||||
@@ -107,38 +106,6 @@ def test_agent(id: int):
|
||||
return ok(payload, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/runtime-bindings', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agent_runtime_bindings(id: int):
|
||||
"""列出入口 Agent 的显式运行能力绑定。"""
|
||||
from app.services.agent_runtime_binding_service import list_runtime_bindings
|
||||
|
||||
return ok(list_runtime_bindings(id), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/runtime-bindings/<path:capability_code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def save_agent_runtime_binding(id: int, capability_code: str):
|
||||
"""保存单个能力 Provider;API Key 仍由 Provider Agent 自身配置管理。"""
|
||||
body = request.get_json(silent=True)
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('JSON body must be an object')
|
||||
try:
|
||||
provider_agent_id = int(body.get('provider_agent_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('provider_agent_id is required') from exc
|
||||
from app.services.agent_runtime_binding_service import save_runtime_binding, serialize_runtime_binding
|
||||
|
||||
binding = save_runtime_binding(
|
||||
owner_agent_id=id,
|
||||
capability_code=capability_code,
|
||||
provider_agent_id=provider_agent_id,
|
||||
enabled=body.get('enabled') is not False,
|
||||
config=body.get('config'),
|
||||
)
|
||||
return ok(serialize_runtime_binding(binding), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/permissions', methods=['POST'])
|
||||
@require_admin
|
||||
def update_agent_permissions(id: int):
|
||||
|
||||
@@ -223,6 +223,23 @@ def suspend_order_document_profile_auto_freeze_qualification(profile_id: int):
|
||||
return _ok(quality.serialize_qualification(qualification))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/auto-freeze-qualification/scope', methods=['POST'])
|
||||
@require_admin
|
||||
def configure_order_document_profile_auto_freeze_scope(profile_id: int):
|
||||
"""配置模板版本的客户/业务场景自动冻结范围;空列表表示清空授权范围。"""
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
qualification = quality.configure_auto_freeze_qualification_scope(
|
||||
profile_id=profile_id,
|
||||
actor_id=int(_actor_id() or 0),
|
||||
customer_ids=data.get('customer_ids'),
|
||||
business_scenarios=data.get('business_scenarios'),
|
||||
requires_customer_confirmation=bool(data.get('requires_customer_confirmation', True)),
|
||||
)
|
||||
return _ok(quality.serialize_qualification(qualification))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_order_document_profile(profile_id: int):
|
||||
|
||||
@@ -15,7 +15,6 @@ from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError
|
||||
from app.models import Agent, User, AgentGuide
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.agent_user_access import require_user_application_access
|
||||
from app.services.minio_service import minio_service
|
||||
|
||||
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
|
||||
@@ -41,11 +40,11 @@ def _list_active_agents_for_user(user: User) -> list[Agent]:
|
||||
if user.role == 'admin':
|
||||
return (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True), Agent.exposure_mode == 'workspace')
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [agent for agent in user.agents if agent.is_active and agent.exposure_mode == 'workspace']
|
||||
return [agent for agent in user.agents if agent.is_active]
|
||||
|
||||
|
||||
@agents_bp.route('', methods=['GET'])
|
||||
@@ -68,14 +67,12 @@ def list_agent_guides(agent_id):
|
||||
获取指定应用的新手指南列表 (需登录)
|
||||
用途:客户端 Chat 界面点击新手指南
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
get_current_user() # Ensure user is logged in.
|
||||
|
||||
if agent_id == 0:
|
||||
generic_agent = (
|
||||
db.session.query(Agent)
|
||||
.filter_by(agent_code='generic', is_active=True, exposure_mode='workspace')
|
||||
.filter_by(agent_code='generic', is_active=True)
|
||||
.order_by(Agent.sort_order.asc(), Agent.id.asc())
|
||||
.first()
|
||||
)
|
||||
@@ -84,9 +81,6 @@ def list_agent_guides(agent_id):
|
||||
else:
|
||||
return jsonify([])
|
||||
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
require_user_application_access(agent, user)
|
||||
|
||||
guides = (
|
||||
db.session.query(AgentGuide)
|
||||
.filter_by(agent_id=agent_id, status=1)
|
||||
@@ -116,7 +110,7 @@ def list_public_agents():
|
||||
"""
|
||||
agents = (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True), Agent.exposure_mode == 'workspace')
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
|
||||
@@ -229,7 +229,13 @@ def _order_extraction_attention_by_conversation(
|
||||
if not conversation_ids:
|
||||
return {}
|
||||
severity_rank = {'info': 1, 'warning': 2, 'error': 3}
|
||||
status_severity = {'completed': 'info', 'needs_review': 'warning', 'failed': 'error', 'cancelled': 'error'}
|
||||
status_severity = {
|
||||
'completed': 'info',
|
||||
'partially_completed': 'warning',
|
||||
'review_required': 'warning',
|
||||
'failed': 'error',
|
||||
'cancelled': 'error',
|
||||
}
|
||||
rows = db.session.query(
|
||||
ShippingOrderExtractionRun.conversation_id,
|
||||
ShippingOrderExtractionRun.status,
|
||||
|
||||
+13
-24
@@ -11,11 +11,6 @@ from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaul
|
||||
from app.services.feedback_notify import send_feedback_group_notification
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.agent_registry.serialization import serialize_registry_fields
|
||||
from app.services.agent_user_access import (
|
||||
require_user_application_access,
|
||||
visible_agent_ids,
|
||||
visible_default_agent_id,
|
||||
)
|
||||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.core.auth.jwt import get_current_user as _auth_current_user
|
||||
@@ -446,7 +441,7 @@ def _build_login_payload(user: User, source: str='password', bind_status: str=No
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'default_agent_id': visible_default_agent_id(user),
|
||||
'default_agent_id': user.default_agent_id,
|
||||
'feature_permissions': user.get_feature_permissions(),
|
||||
'source': source,
|
||||
'access_token': issue_local_access_token(user),
|
||||
@@ -775,7 +770,7 @@ def casdoor_password_login():
|
||||
_write_login_audit('casdoor', 'success', user=user)
|
||||
db.session.commit()
|
||||
api_bearer_token = id_token or access_token
|
||||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': visible_default_agent_id(user), 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||||
except WeComLoginError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
@@ -905,7 +900,7 @@ def casdoor_login():
|
||||
_write_login_audit('casdoor', 'success', user=user)
|
||||
db.session.commit()
|
||||
api_bearer_token = id_token or access_token
|
||||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': visible_default_agent_id(user), 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||||
except WeComLoginError:
|
||||
db.session.rollback()
|
||||
current_app.logger.warning('[casdoor_login] business_reject')
|
||||
@@ -1346,32 +1341,26 @@ def home():
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
|
||||
def _load_home_payload():
|
||||
allowed_agent_ids = visible_agent_ids(user)
|
||||
if user.role == 'admin':
|
||||
agent_rows = Agent.query.filter(
|
||||
Agent.is_active.is_(True), Agent.exposure_mode == 'workspace',
|
||||
).all()
|
||||
agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all()
|
||||
else:
|
||||
agent_rows = [
|
||||
agent for agent in user.agents
|
||||
if agent.is_active and agent.exposure_mode == 'workspace'
|
||||
]
|
||||
agent_rows = [agent for agent in user.agents if agent.is_active]
|
||||
agent_rows = sort_agent_rows(agent_rows)
|
||||
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
|
||||
favorite_ids = [f.agent_id for f in favorites if f.agent_id in allowed_agent_ids]
|
||||
favorite_ids = [f.agent_id for f in favorites]
|
||||
qqs = db.session.query(QuickQuestion).filter(
|
||||
or_(
|
||||
QuickQuestion.user_id == user.id,
|
||||
and_(QuickQuestion.user_id.is_(None), QuickQuestion.is_enabled.is_(True)),
|
||||
)
|
||||
).filter(QuickQuestion.agent_id.in_(allowed_agent_ids)).all() if allowed_agent_ids else []
|
||||
).all()
|
||||
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||||
layout = layout_config.layout if layout_config else {}
|
||||
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
|
||||
embedded_agents = []
|
||||
for rel in embedded_rel:
|
||||
agent = db.session.get(Agent, rel.agent_id)
|
||||
if agent and agent.id in allowed_agent_ids:
|
||||
if agent:
|
||||
registry = serialize_registry_fields(agent)
|
||||
embedded_agents.append({
|
||||
'id': agent.id,
|
||||
@@ -1380,7 +1369,7 @@ def home():
|
||||
'runtime_provider': registry.get('runtime_provider'),
|
||||
'conversation_mode': registry.get('conversation_mode'),
|
||||
})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': visible_default_agent_id(user), 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
try:
|
||||
return _run_db_with_retry(_load_home_payload, label='user.home')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
@@ -1392,7 +1381,6 @@ def toggle_favorite(agent_id: int):
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
require_user_application_access(db.session.get(Agent, agent_id), user)
|
||||
if request.method == 'POST':
|
||||
exists = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).first()
|
||||
if not exists:
|
||||
@@ -1411,7 +1399,6 @@ def add_quick_question():
|
||||
data = request.get_json() or {}
|
||||
if not data.get('title') or not data.get('question') or (not data.get('agent_id')):
|
||||
raise ValidationError('Missing fields')
|
||||
require_user_application_access(db.session.get(Agent, data['agent_id']), user)
|
||||
qq = QuickQuestion(user_id=user.id, title=data['title'], question=data['question'], agent_id=data['agent_id'])
|
||||
db.session.add(qq)
|
||||
db.session.commit()
|
||||
@@ -1435,7 +1422,6 @@ def update_quick_question(qq_id: int):
|
||||
if 'question' in data:
|
||||
qq.question = data['question']
|
||||
if 'agent_id' in data:
|
||||
require_user_application_access(db.session.get(Agent, data['agent_id']), user)
|
||||
qq.agent_id = data['agent_id']
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
@@ -1829,7 +1815,10 @@ def get_agent_details(id):
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
agent = db.session.get(Agent, id)
|
||||
require_user_application_access(agent, user)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
if user.role != 'admin' and agent not in user.agents:
|
||||
raise ForbiddenError('Access denied')
|
||||
|
||||
from app.services.agent_registry.resolver import resolve_runtime_provider
|
||||
from app.services.agent_registry.serialization import serialize_agent_for_user_detail
|
||||
|
||||
@@ -971,6 +971,17 @@ def workspace_create_shipping_order_extraction_run():
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_AGENT_INVALID',
|
||||
) from exc
|
||||
conversation_id = str(body.get('conversation_id') or '').strip()
|
||||
upload_batch_id = str(body.get('upload_batch_id') or '').strip()
|
||||
if not upload_batch_id:
|
||||
raise ValidationError(
|
||||
'upload_batch_id is required',
|
||||
code='SHIPPING_NOTICE.UPLOAD_BATCH_REQUIRED',
|
||||
)
|
||||
if len(upload_batch_id) > 36:
|
||||
raise ValidationError(
|
||||
'upload_batch_id is too long',
|
||||
code='SHIPPING_NOTICE.UPLOAD_BATCH_INVALID',
|
||||
)
|
||||
intake_nos = body.get('intake_nos')
|
||||
if not isinstance(intake_nos, list):
|
||||
raise ValidationError(
|
||||
@@ -987,6 +998,7 @@ def workspace_create_shipping_order_extraction_run():
|
||||
agent_id=agent_id,
|
||||
conversation_id=conversation_id,
|
||||
intake_nos=intake_nos,
|
||||
upload_batch_id=upload_batch_id,
|
||||
)
|
||||
db.session.commit()
|
||||
return ok(
|
||||
@@ -1017,6 +1029,15 @@ def workspace_list_shipping_order_extraction_progress_events(run_no: str):
|
||||
return _ok({'items': list_user_order_extraction_progress_events(user_id=user.id, run_no=run_no)})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/documents', methods=['GET'])
|
||||
def workspace_list_shipping_order_extraction_documents(run_no: str):
|
||||
"""返回当前用户一次订单抽取的按 PDF 归并详情。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_extraction_run_service import list_user_order_extraction_documents
|
||||
|
||||
return _ok({'items': list_user_order_extraction_documents(user_id=user.id, run_no=run_no)})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/seen', methods=['POST'])
|
||||
def workspace_mark_shipping_order_extraction_run_seen(run_no: str):
|
||||
"""确认当前用户已加载终态订单识别卡片;仅用于会话待查看提醒,不改变业务结果。"""
|
||||
@@ -1103,12 +1124,23 @@ def workspace_create_shipping_notice_intake():
|
||||
if not asset_no:
|
||||
raise ValidationError('asset_no is required')
|
||||
conversation_id = str(body.get('conversation_id') or '').strip() or None
|
||||
upload_batch_id = str(body.get('upload_batch_id') or '').strip()
|
||||
if not upload_batch_id:
|
||||
raise ValidationError(
|
||||
'upload_batch_id is required',
|
||||
code='SHIPPING_NOTICE.UPLOAD_BATCH_REQUIRED',
|
||||
)
|
||||
if len(upload_batch_id) > 36:
|
||||
raise ValidationError(
|
||||
'upload_batch_id is too long',
|
||||
code='SHIPPING_NOTICE.UPLOAD_BATCH_INVALID',
|
||||
)
|
||||
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
|
||||
|
||||
data = create_shipping_notice_intake(
|
||||
user_id=user.id,
|
||||
asset_no=asset_no,
|
||||
conversation_id=conversation_id,
|
||||
upload_batch_id=upload_batch_id,
|
||||
)
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=202)
|
||||
|
||||
|
||||
Reference in new issue
Block a user