feat(shipping-notice): 增强订单抽取功能,添加进度事件和诊断运行管理,优化数据模型和访问控制

This commit is contained in:
hugo committed 2026-07-21 23:17:29 +08:00
1 parent ce26d6d0c4
commit c4095b08da
175 files changed
+13064 -1814

No files matched your search

+19 -3
View File
@@ -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,
+10
View File
@@ -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))
+4 -3
View File
@@ -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 = []