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

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

No files matched your search

+6 -72
View File
@@ -14,8 +14,8 @@ import requests
from app import db
from app.core.config.settings import Config
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import Agent, AgentRuntimeBinding, ShippingOrderExtractionRun, User
from app.core.errors import NotFoundError, ValidationError
from app.models import Agent, User
from app.services.agent_directory import normalize_directory_member_ids, replace_directory_members
from app.services.admin.training_exam_pdf_service import parse_training_question_bank_from_guide
from app.services.agent_registry.admin_payload import apply_agent_payload, validate_agent_payload
@@ -29,20 +29,9 @@ def serialize_agent(agent: Agent) -> dict:
return serialize_agent_for_admin(agent)
def list_agents(*, scope: str | None = None) -> list[dict]:
"""按管理域返回 Agent;scope=applications/executors,缺省返回全部兼容旧客户端。"""
query = db.session.query(Agent)
if scope == 'applications':
query = query.filter(Agent.exposure_mode == 'workspace')
elif scope == 'executors':
query = query.filter(Agent.exposure_mode == 'internal')
elif scope not in (None, ''):
raise ValidationError(
'Invalid agent management scope',
code='AGENT.ADMIN_SCOPE_INVALID',
details={'scope': scope},
)
agents = query.order_by(Agent.id.asc()).all()
def list_agents() -> list[dict]:
"""返回全部 Agent(按 id 升序)。"""
agents = db.session.query(Agent).order_by(Agent.id.asc()).all()
return [serialize_agent(a) for a in agents]
@@ -71,24 +60,6 @@ def create_agent(data: dict[str, Any]) -> dict:
db.session.flush()
member_ids = data.get('directory_member_ids') if agent.is_aggregate else []
replace_directory_members(agent, normalize_directory_member_ids(member_ids, directory_agent_id=agent.id))
runtime_binding = data.get('order_extraction_runtime_binding')
if runtime_binding is not None:
if not isinstance(runtime_binding, dict):
raise ValidationError('order_extraction_runtime_binding 必须为 JSON 对象')
try:
provider_agent_id = int(runtime_binding.get('provider_agent_id'))
except (TypeError, ValueError) as exc:
raise ValidationError('provider_agent_id is required') from exc
from app.services.agent_runtime_binding_service import save_runtime_binding
save_runtime_binding(
owner_agent_id=agent.id,
capability_code='shipping.order_extraction',
provider_agent_id=provider_agent_id,
enabled=runtime_binding.get('enabled') is not False,
config=runtime_binding.get('config'),
commit=False,
)
db.session.commit()
return {'id': agent.id}
@@ -115,7 +86,6 @@ def update_agent(agent_id: int, data: dict[str, Any]) -> None:
'runtime_provider': data.get('runtime_provider', agent.runtime_provider),
'conversation_mode': data.get('conversation_mode', agent.conversation_mode),
'dify_app_type': data.get('dify_app_type', agent.dify_app_type),
'exposure_mode': data.get('exposure_mode', agent.exposure_mode),
'iframe_url': data.get('iframe_url', agent.iframe_url),
'category': data.get('category', agent.category),
'sub_category': data.get('sub_category', agent.sub_category),
@@ -138,44 +108,13 @@ def update_agent(agent_id: int, data: dict[str, Any]) -> None:
if 'directory_member_ids' in data or 'is_aggregate' in data:
member_ids = data.get('directory_member_ids') if agent.is_aggregate else []
replace_directory_members(agent, normalize_directory_member_ids(member_ids, directory_agent_id=agent.id))
runtime_binding = data.get('order_extraction_runtime_binding')
if runtime_binding is not None:
if not isinstance(runtime_binding, dict):
raise ValidationError('order_extraction_runtime_binding 必须为 JSON 对象')
try:
provider_agent_id = int(runtime_binding.get('provider_agent_id'))
except (TypeError, ValueError) as exc:
raise ValidationError('provider_agent_id is required') from exc
from app.services.agent_runtime_binding_service import save_runtime_binding
save_runtime_binding(
owner_agent_id=agent.id,
capability_code='shipping.order_extraction',
provider_agent_id=provider_agent_id,
enabled=runtime_binding.get('enabled') is not False,
config=runtime_binding.get('config'),
commit=False,
)
db.session.commit()
def delete_agent(agent_id: int) -> None:
"""删除 Agent;被能力绑定或历史订单抽取 Run 引用时明确阻断。"""
"""删除 Agent(不存在时静默成功)。"""
agent = db.session.get(Agent, agent_id)
if agent:
binding_count = AgentRuntimeBinding.query.filter(
(AgentRuntimeBinding.owner_agent_id == agent.id)
| (AgentRuntimeBinding.provider_agent_id == agent.id)
).count()
run_count = ShippingOrderExtractionRun.query.filter(
(ShippingOrderExtractionRun.owner_agent_id == agent.id)
).count()
if binding_count or run_count:
raise ConflictError(
'Agent is referenced by runtime capability history',
code='AGENT.RUNTIME_PROVIDER_DELETE_BLOCKED',
details={'binding_count': binding_count, 'run_count': run_count},
)
db.session.delete(agent)
db.session.commit()
@@ -356,11 +295,6 @@ def update_agent_permissions(agent_id: int, user_ids: list[int]) -> None:
agent = db.session.get(Agent, agent_id)
if not agent:
raise NotFoundError('Not found')
if agent.exposure_mode == 'internal' and user_ids:
raise ValidationError(
'内部执行器不可授予用户权限',
code='AGENT.INTERNAL_EXECUTOR_PERMISSION_FORBIDDEN',
)
current_users = db.session.query(User).filter(User.agents.contains(agent)).all()
current_user_ids = {u.id for u in current_users}
new_user_ids = set(user_ids)
@@ -20,12 +20,7 @@ def compute_dashboard_summary() -> dict:
agent_count、user_count、total_conversations、avg_score。
"""
total_users = db.session.query(func.count(User.id)).scalar() or 0
active_agents = (
db.session.query(func.count(Agent.id))
.filter(Agent.is_active.is_(True), Agent.exposure_mode == 'workspace')
.scalar()
or 0
)
active_agents = db.session.query(func.count(Agent.id)).filter_by(is_active=True).scalar() or 0
total_conversations = db.session.query(func.count(ChatLog.id)).scalar() or 0
avg_score = db.session.query(func.avg(Feedback.score)).scalar()
avg_score = round(float(avg_score), 1) if avg_score else 0.0
@@ -44,13 +39,7 @@ def compute_dashboard_badges() -> dict:
pending_approvals、pending_requests。
"""
pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar() or 0
pending_requests = (
db.session.query(func.count(PermissionRequest.id))
.join(Agent, Agent.id == PermissionRequest.agent_id)
.filter(PermissionRequest.status == 'pending', Agent.exposure_mode == 'workspace')
.scalar()
or 0
)
pending_requests = db.session.query(func.count(PermissionRequest.id)).filter_by(status='pending').scalar() or 0
return {
'pending_approvals': pending_approvals,
'pending_requests': pending_requests,
-11
View File
@@ -13,7 +13,6 @@ from typing import Any
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import Agent, KbDocument, QuickQuestion
from app.services.agent_user_access import is_user_application, require_user_application
def parse_aliases(raw_aliases) -> list[str]:
@@ -83,7 +82,6 @@ def apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answe
if 'question' in data:
qq.question = str(data['question']).strip()
if 'agent_id' in data:
require_user_application(db.session.get(Agent, data['agent_id']))
qq.agent_id = data['agent_id']
if 'sort_order' in data:
qq.sort_order = data.get('sort_order', 0)
@@ -124,8 +122,6 @@ def list_quick_questions(*, stale_only: bool = False) -> list[dict]:
rows = []
for q in query.all():
agent = db.session.get(Agent, q.agent_id)
if not is_user_application(agent):
continue
stale_doc = db.session.get(KbDocument, q.stale_kb_document_id) if q.stale_kb_document_id else None
rows.append(serialize_quick_question(q, agent.name if agent else 'Unknown', stale_doc))
return rows
@@ -168,8 +164,6 @@ def list_faq_candidates(*, agent_id: int | None = None) -> dict:
from app.services.hot_faq_aggregator import HotFaqAggregator
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
if agent_id is not None:
require_user_application(db.session.get(Agent, agent_id))
items = HotFaqCandidateStore.list_candidates(agent_id)
return {
'items': items,
@@ -182,8 +176,6 @@ def refresh_faq_candidates(*, agent_id: int | None, dry_run: bool) -> dict:
"""手动触发离线热点聚合。"""
from app.services.hot_faq_aggregator import HotFaqAggregator
if agent_id is not None:
require_user_application(db.session.get(Agent, agent_id))
return HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run)
@@ -197,8 +189,6 @@ def promote_faq_candidate(data: dict[str, Any]) -> dict:
q_norm = normalize_faq_query(str(data.get('q_norm') or ''))
if not agent_id or not q_norm:
raise ValidationError('agent_id and q_norm are required')
require_user_application(db.session.get(Agent, agent_id))
candidate = HotFaqCandidateStore.get_candidate(int(agent_id), q_norm)
if not candidate:
raise NotFoundError('FAQ candidate not found')
@@ -242,6 +232,5 @@ def dismiss_faq_candidate(*, agent_id: int, q_norm: str) -> dict:
normalized = normalize_faq_query(q_norm)
if not agent_id or not normalized:
raise ValidationError('agent_id and q_norm are required')
require_user_application(db.session.get(Agent, agent_id))
HotFaqCandidateStore.dismiss(int(agent_id), normalized)
return {'status': 'ok'}
@@ -13,7 +13,6 @@ from typing import Any
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import Agent, PermissionRequest, User
from app.services.agent_user_access import load_grantable_agents, require_user_application
from app.services.wecom_notify import send_wecom_event_message
_BATCH_ACTION_LABELS = {'add': '新增', 'remove': '移除', 'set': '重置为'}
@@ -33,7 +32,7 @@ def serialize_permission_request(req: PermissionRequest) -> dict:
def _load_users_and_agents(user_ids: list[Any], agent_ids: list[Any]) -> tuple[list[User], list[Agent]]:
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
agents = load_grantable_agents(agent_ids)
agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all()
return users, agents
@@ -105,18 +104,16 @@ def update_user_permissions(user_id: int, data: dict[str, Any]) -> dict:
if not user:
raise NotFoundError('Not found')
agent_ids = data.get('agent_ids', [])
agents = load_grantable_agents(agent_ids)
agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all()
user.agents = agents
db.session.commit()
return {'status': 'ok'}
def list_permission_requests() -> list[dict]:
"""返回 workspace 应用的权限申请;内部执行器申请仅保留数据库审计。"""
"""返回全部权限申请(按 created_at 降序)。"""
reqs = (
db.session.query(PermissionRequest)
.join(Agent, Agent.id == PermissionRequest.agent_id)
.filter(Agent.exposure_mode == 'workspace')
.order_by(PermissionRequest.created_at.desc())
.all()
)
@@ -135,9 +132,6 @@ def approve_permission_request(request_id: int) -> dict:
user = db.session.get(User, req.user_id)
agent = db.session.get(Agent, req.agent_id)
if not user:
raise NotFoundError('User not found')
require_user_application(agent)
req.status = 'approved'
req.reviewed_at = datetime.utcnow()
if user and agent and (agent not in user.agents):
@@ -286,7 +286,6 @@ def build_application_report(
.outerjoin(auth_stats, auth_stats.c.agent_id == Agent.id)
.outerjoin(pending_stats, pending_stats.c.agent_id == Agent.id)
.outerjoin(feedback_stats, feedback_stats.c.agent_id == Agent.id)
.filter(Agent.exposure_mode == 'workspace')
)
if status_key == 'active':
query = query.filter(Agent.is_active.is_(True))
+3 -4
View File
@@ -16,7 +16,6 @@ from sqlalchemy.orm import joinedload
from app import db
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.models import Agent, User
from app.services.agent_user_access import is_user_application, load_grantable_agents
from app.services.auth import casdoor_service
from app.services.user_admin import delete_admin_users
@@ -81,7 +80,7 @@ def serialize_admin_user(user: User) -> dict:
'employee_id': user.employee_id,
'phone_number': user.phone_number,
'feature_permissions': user.get_feature_permissions(),
'agent_ids': [agent.id for agent in user.agents if is_user_application(agent)],
'agent_ids': [agent.id for agent in user.agents],
}
@@ -210,7 +209,7 @@ def create_user(data: dict[str, Any]) -> dict:
db.session.add(user)
try:
if data.get('agent_ids'):
agents = load_grantable_agents(data['agent_ids'])
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents
casdoor_service.sync_create_user(
username=user.username,
@@ -262,7 +261,7 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict:
if new_password:
user.set_password(new_password)
if 'agent_ids' in data:
agents = load_grantable_agents(data['agent_ids'])
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents
if new_password:
casdoor_service.sync_update_user(user, new_password=new_password)
@@ -20,7 +20,6 @@ from app import db
from app.core.config.env_persistence import persist_env_settings
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.models import Agent, LoginAudit, User, WecomNotifyAudit
from app.services.agent_user_access import load_grantable_agents
from app.services.auth import wecom_auth_service
from app.services.oa_wecom_sync import sync_wecom_userids_from_oa
@@ -314,11 +313,10 @@ def provision_user(data: dict[str, Any]) -> tuple[dict, int]:
except (TypeError, ValueError):
db.session.rollback()
raise ValidationError('agent_ids must be integer array')
try:
agents = load_grantable_agents(unique_ids)
except ValidationError:
agents = db.session.query(Agent).filter(Agent.id.in_(unique_ids)).all()
if len(agents) != len(unique_ids):
db.session.rollback()
raise
raise ValidationError('Some agent_ids are invalid')
user.agents = agents
else:
user.agents = []