!20 Merge branch 'dev' into snow

Merge pull request !20 from 王瑞雪/snow
This commit is contained in:
sophie authored and Gitee committed 2026-09-29 05:13:46 +00:00
commit 2065b73610
56 files changed
+4501 -1110

No files matched your search

+78 -47
View File
@@ -15,7 +15,13 @@ import requests
from app import db
from app.core.config.settings import Config
from app.core.errors import NotFoundError, ValidationError
from app.models import Agent, User
from app.models import (
Agent, AgentDirectoryMember, ChatLog, ChatSession, ChatToolRun,
ContractReview, FaqHotCandidate, Feedback, GeneralFeedback,
PermissionRequest, QuickQuestion, ScheduleTask, User,
UserDefaultAgent, UserFavoriteAgent, user_agent_permissions,
)
from sqlalchemy import delete, select, update
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
@@ -112,11 +118,40 @@ def update_agent(agent_id: int, data: dict[str, Any]) -> None:
def delete_agent(agent_id: int) -> None:
"""删除 Agent(不存在时静默成功)。"""
"""
删除 Agent 及其数据库引用,避免 chat_logs 外键导致管理端删除失败。
[STEP 1] 清理权限、目录、收藏、默认入口及业务直接引用。
[STEP 2] 先清理 chat_log 子表,再删除会话日志。
[STEP 3] 最后删除 Agent,整段操作使用当前事务保证原子性。
"""
agent = db.session.get(Agent, agent_id)
if agent:
db.session.delete(agent)
db.session.commit()
if not agent:
return
chat_log_ids = select(ChatLog.id).where(ChatLog.agent_id == agent_id)
db.session.execute(delete(user_agent_permissions).where(user_agent_permissions.c.agent_id == agent_id))
db.session.execute(delete(AgentDirectoryMember).where(
(AgentDirectoryMember.directory_agent_id == agent_id)
| (AgentDirectoryMember.member_agent_id == agent_id)
))
db.session.execute(delete(UserFavoriteAgent).where(UserFavoriteAgent.agent_id == agent_id))
db.session.execute(delete(UserDefaultAgent).where(UserDefaultAgent.agent_id == agent_id))
db.session.execute(update(User).where(User.default_agent_id == agent_id).values(default_agent_id=None))
db.session.execute(update(ScheduleTask).where(ScheduleTask.dify_agent_id == agent_id).values(dify_agent_id=None))
db.session.execute(delete(PermissionRequest).where(PermissionRequest.agent_id == agent_id))
db.session.execute(delete(ContractReview).where(ContractReview.agent_id == agent_id))
db.session.execute(delete(QuickQuestion).where(QuickQuestion.agent_id == agent_id))
db.session.execute(delete(FaqHotCandidate).where(FaqHotCandidate.agent_id == agent_id))
db.session.execute(delete(ChatSession).where(ChatSession.agent_id == agent_id))
db.session.execute(delete(ChatToolRun).where(
(ChatToolRun.agent_id == agent_id) | ChatToolRun.chat_log_id.in_(chat_log_ids)
))
db.session.execute(delete(Feedback).where(Feedback.chat_log_id.in_(chat_log_ids)))
db.session.execute(delete(GeneralFeedback).where(GeneralFeedback.chat_log_id.in_(chat_log_ids)))
db.session.execute(delete(ContractReview).where(ContractReview.chat_log_id.in_(chat_log_ids)))
db.session.execute(delete(ChatLog).where(ChatLog.agent_id == agent_id))
db.session.delete(agent)
db.session.commit()
def test_agent_connectivity(agent_id: int) -> dict[str, Any]:
@@ -170,68 +205,65 @@ def _test_iframe_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
def _test_dify_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
"""
Test Dify endpoint reachability without executing the configured application flow.
The test calls Dify's read-only ``/v1/parameters`` endpoint so a business
Chatflow/Workflow never receives synthetic text such as ``OK`` that could be
passed into a database or other external tool.
"""
if not agent.dify_api_key:
return {
'passed': False,
'request_url': '',
'output_info': 'Missing dify_api_key.',
'analysis': '测试失败:未配置 API Key。',
'analysis': '\u6d4b\u8bd5\u5931\u8d25\uff1a\u672a\u914d\u7f6e API Key\u3002',
'http_status': 0,
'tested_at': tested_at,
}
base_url = (agent.api_base_url or Config.DIFY_API_BASE or '').rstrip('/')
if not base_url:
return {
'passed': False,
'request_url': '',
'output_info': 'Missing api_base_url.',
'analysis': '测试失败:未配置 API Base URL。',
'analysis': '\u6d4b\u8bd5\u5931\u8d25\uff1a\u672a\u914d\u7f6e API Base URL\u3002',
'http_status': 0,
'tested_at': tested_at,
}
dify_app_type = str(agent.dify_app_type or 'chatflow').strip().lower()
if dify_app_type not in ('chatflow', 'workflow'):
dify_app_type = 'chatflow'
if dify_app_type == 'workflow':
request_url = DifyService._build_workflow_url(base_url)
payload = {
'inputs': {'query': '系统连通性测试,请简短回复OK。'},
'response_mode': 'blocking',
'user': 'admin_test',
}
else:
request_url = DifyService._build_chat_messages_url(base_url)
payload = {
'inputs': {},
'query': '系统连通性测试,请简短回复OK。',
'response_mode': 'blocking',
'user': 'admin_test',
}
headers = {'Authorization': f'Bearer {agent.dify_api_key}', 'Content-Type': 'application/json'}
# [STEP 1] Read-only endpoint: never run a business Chatflow/Workflow in an admin connectivity test.
request_url = DifyService._build_parameters_url(base_url)
headers = {'Authorization': f'Bearer {agent.dify_api_key}'}
try:
resp = requests.post(request_url, headers=headers, json=payload, timeout=(5, 25))
raw_text = (resp.text or '')[:4000]
response = requests.get(request_url, headers=headers, timeout=(5, 15))
raw_text = (response.text or '')[:4000]
output_info = raw_text
passed = False
analysis = f'测试失败:HTTP {resp.status_code}。'
if dify_app_type == 'workflow' and 200 <= resp.status_code < 300:
if response.ok:
passed = True
analysis = '测试通过:Workflow 接口可访问且认证通过。'
try:
data = resp.json()
if dify_app_type == 'workflow':
passed, output_info, analysis = _parse_workflow_test_response(resp, data, output_info, analysis)
else:
passed, output_info, analysis = _parse_chatflow_test_response(resp, data, output_info, analysis, passed)
except ValueError:
if resp.ok and raw_text.strip():
passed = True
analysis = (
'测试通过:Workflow 接口可访问并返回了文本内容。'
if dify_app_type == 'workflow'
else '测试通过:Chatflow 接口可访问并返回了文本内容。'
)
if passed and (not agent.is_active):
analysis = '\u6d4b\u8bd5\u901a\u8fc7\uff1aDify \u53c2\u6570\u63a5\u53e3\u53ef\u8bbf\u95ee\u4e14 API Key \u8ba4\u8bc1\u901a\u8fc7\u3002'
try:
body = response.json()
if isinstance(body, dict):
output_info = str(body)[:4000]
except ValueError:
pass
else:
passed = False
analysis = f'\u6d4b\u8bd5\u5931\u8d25\uff1aHTTP {response.status_code}\u3002'
try:
body = response.json()
if isinstance(body, dict) and body.get('message'):
output_info = str(body['message'])[:4000]
except ValueError:
pass
if passed and not agent.is_active:
agent.is_active = True
db.session.commit()
return {
@@ -240,7 +272,7 @@ def _test_dify_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
'request_url': request_url,
'output_info': output_info,
'analysis': analysis,
'http_status': resp.status_code,
'http_status': response.status_code,
'tested_at': tested_at,
}
except requests.RequestException as exc:
@@ -249,12 +281,11 @@ def _test_dify_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
'dify_app_type': dify_app_type,
'request_url': request_url,
'output_info': str(exc),
'analysis': '测试失败:请求异常(网络、超时或认证问题)。',
'analysis': '\u6d4b\u8bd5\u5931\u8d25\uff1a\u8bf7\u6c42\u5f02\u5e38\uff08\u7f51\u7edc\u3001\u8d85\u65f6\u6216\u8ba4\u8bc1\u95ee\u9898\uff09\u3002',
'http_status': 0,
'tested_at': tested_at,
}
def _parse_workflow_test_response(resp, data, output_info: str, analysis: str) -> tuple[bool, str, str]:
passed = 200 <= resp.status_code < 300
workflow_data = data.get('data') if isinstance(data, dict) else None
@@ -10,7 +10,7 @@ from __future__ import annotations
from sqlalchemy import func
from app import db
from app.models import Agent, ChatLog, Feedback, PermissionRequest, User
from app.models import Agent, ChatLog, Feedback, User
def compute_dashboard_summary() -> dict:
@@ -32,29 +32,12 @@ def compute_dashboard_summary() -> dict:
}
def compute_dashboard_badges() -> dict:
"""
聚合侧栏角标所需的待办数量。
Returns:
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
return {
'pending_approvals': pending_approvals,
'pending_requests': pending_requests,
}
def compute_legacy_dashboard_stats() -> dict:
"""遗留 /dashboard 接口响应(summary + badges 字段名兼容早期前端)。"""
summary = compute_dashboard_summary()
badges = compute_dashboard_badges()
return {
'total_users': summary['user_count'],
'active_agents': summary['agent_count'],
'total_conversations': summary['total_conversations'],
'avg_score': summary['avg_score'],
'pending_approvals': badges['pending_approvals'],
'pending_requests': badges['pending_requests'],
}
@@ -19,7 +19,6 @@ from app.models import (
ChatLog,
Department,
Feedback,
PermissionRequest,
QuickQuestion,
User,
UserDefaultAgent,
@@ -33,7 +32,6 @@ ADMIN_TABLE_MODEL_MAP = {
'agents': Agent,
'chat_logs': ChatLog,
'feedbacks': Feedback,
'permission_requests': PermissionRequest,
'departments': Department,
'quick_questions': QuickQuestion,
'user_homepage_configs': UserHomepageConfig,
@@ -52,6 +50,35 @@ def _serialize_model_row(item) -> dict:
return row
def _apply_generic_table_filters(query, model, query_params: dict[str, str]):
"""通用表筛选:created_at 时间范围(created_from/created_to)+ 各列 ILIKE/等值过滤。"""
reserved = {'created_from', 'created_to'}
# 时间范围(支持有 created_at 列的通用表,如 feedbacks 回答评价)
created_from = (query_params.get('created_from') or '').strip()
created_to = (query_params.get('created_to') or '').strip()
if created_from and hasattr(model, 'created_at'):
dt = report_service._parse_datetime(created_from, end_of_day=False)
if dt:
query = query.filter(model.created_at >= dt)
if created_to and hasattr(model, 'created_at'):
dt = report_service._parse_datetime(created_to, end_of_day=True)
if dt:
query = query.filter(model.created_at <= dt)
for key, value in query_params.items():
if key in reserved or not value:
continue
if hasattr(model, key):
col = getattr(model, key)
col_type = getattr(col, 'type', None)
# 整型外键(如 agent_id)用等值过滤,避免 ILIKE '%16%' 误匹配 160
if value.isdigit() and col_type is not None and getattr(col_type, 'python_type', None) is int:
query = query.filter(col == int(value))
else:
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
return query
def get_table_data(table: str, query_params: dict[str, str]) -> list[dict]:
"""
返回管理报表表数据(最多 100 行)。
@@ -62,28 +89,20 @@ def get_table_data(table: str, query_params: dict[str, str]) -> list[dict]:
model = ADMIN_TABLE_MODEL_MAP.get(table)
if not model:
raise ValidationError('Invalid table')
query = db.session.query(model)
for key, value in query_params.items():
if hasattr(model, key) and value:
col = getattr(model, key)
col_type = getattr(col, 'type', None)
# 整型外键(如 agent_id)用等值过滤,避免 ILIKE '%16%' 误匹配 160
if value.isdigit() and col_type is not None and getattr(col_type, 'python_type', None) is int:
query = query.filter(col == int(value))
else:
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
query = _apply_generic_table_filters(db.session.query(model), model, query_params)
items = query.limit(100).all()
return [_serialize_model_row(item) for item in items]
def get_table_count(table: str, query_params: dict[str, str]) -> dict:
"""返回表行数;chat_logs 使用报表筛选。"""
"""返回表行数(应用当前筛选);chat_logs 使用报表筛选。"""
if table == 'chat_logs':
return report_service.count_chat_logs_report(query_params)
model = ADMIN_TABLE_MODEL_MAP.get(table)
if not model:
raise ValidationError('Invalid table')
total = db.session.query(func.count(model.id)).scalar()
query = _apply_generic_table_filters(db.session.query(model), model, query_params)
total = query.count()
return {'table': table, 'total': int(total or 0)}
@@ -9,9 +9,11 @@ from __future__ import annotations
from typing import Any
from sqlalchemy import func
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import Department
from app.models import Department, User
def serialize_department(dept: Department) -> dict:
@@ -27,8 +29,43 @@ def serialize_department(dept: Department) -> dict:
def list_departments() -> list[dict]:
"""返回全部部门(按 name 升序)。"""
depts = db.session.query(Department).order_by(Department.name.asc()).all()
return [serialize_department(d) for d in depts]
rows = (
db.session.query(Department, func.count(User.id).label('member_count'))
.outerjoin(User, User.department == Department.name)
.group_by(Department.id)
.order_by(Department.name.asc())
.all()
)
return [{**serialize_department(dept), 'member_count': int(member_count or 0)} for dept, member_count in rows]
def list_department_members(dept_id: int) -> dict:
"""
查询指定部门的员工名单。
[STEP 1] 通过部门主键读取部门名称。
[STEP 2] 复用现有 users.department 文本关联查询成员。
[STEP 3] 返回人数与脱敏后的管理端成员资料。
"""
dept = db.session.get(Department, dept_id)
if not dept:
raise NotFoundError('Not found')
users = db.session.query(User).filter(User.department == dept.name).order_by(User.real_name.asc(), User.username.asc()).all()
return {
'department': serialize_department(dept),
'count': len(users),
'members': [
{
'id': user.id,
'username': user.username,
'real_name': user.real_name,
'employee_id': user.employee_id,
'email': user.email,
'status': user.status,
}
for user in users
],
}
def create_department(data: dict[str, Any]) -> dict:
@@ -1,35 +1,22 @@
"""
backend/app/services/admin/permission_service.py
用途:用户 Agent 权限批量/单用户更新,以及权限申请审批业务逻辑。
依赖:models、wecom_notify.send_wecom_event_message。
用途:用户 Agent 权限批量/单用户更新业务逻辑。
依赖:models、integrations.wecom.notify.send_wecom_event_message。
逻辑:由 api/admin/permissions.py 调用;users 路由 /users/<id>/permissions 亦委托本模块。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import Agent, PermissionRequest, User
from app.models import Agent, User
from app.services.integrations.wecom.notify import send_wecom_event_message
_BATCH_ACTION_LABELS = {'add': '新增', 'remove': '移除', 'set': '重置为'}
def serialize_permission_request(req: PermissionRequest) -> dict:
"""PermissionRequest ORM → 管理端列表 JSON。"""
return {
'id': req.id,
'user_id': req.user_id,
'agent_id': req.agent_id,
'reason': req.reason,
'status': req.status,
'created_at': req.created_at.isoformat(),
}
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()
@@ -108,67 +95,3 @@ def update_user_permissions(user_id: int, data: dict[str, Any]) -> dict:
user.agents = agents
db.session.commit()
return {'status': 'ok'}
def list_permission_requests() -> list[dict]:
"""返回全部权限申请(按 created_at 降序)。"""
reqs = (
db.session.query(PermissionRequest)
.order_by(PermissionRequest.created_at.desc())
.all()
)
return [serialize_permission_request(r) for r in reqs]
def approve_permission_request(request_id: int) -> dict:
"""
批准权限申请:更新状态并将 Agent 加入用户权限。
Raises:
NotFoundError: 申请不存在。
"""
req = db.session.get(PermissionRequest, request_id)
if not req:
raise NotFoundError('Not found')
user = db.session.get(User, req.user_id)
agent = db.session.get(Agent, req.agent_id)
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:
send_wecom_event_message(
event_type='permission_request_approved',
user=user,
title='权限申请已通过',
content=f'你申请的应用权限已通过:{(agent.name if agent else req.agent_id)}',
jump_path='/workspace',
)
db.session.commit()
return {'status': 'ok'}
def reject_permission_request(request_id: int) -> dict:
"""
拒绝权限申请并通知用户(若已绑定企微)。
Raises:
NotFoundError: 申请不存在。
"""
req = db.session.get(PermissionRequest, request_id)
if not req:
raise NotFoundError('Not found')
req.status = 'rejected'
req.reviewed_at = datetime.utcnow()
user = db.session.get(User, req.user_id)
agent = db.session.get(Agent, req.agent_id)
if user and user.wecom_userid:
send_wecom_event_message(
event_type='permission_request_rejected',
user=user,
title='权限申请未通过',
content=f'你申请的应用权限未通过:{(agent.name if agent else req.agent_id)}',
jump_path='/workspace',
)
db.session.commit()
return {'status': 'ok'}
File diff suppressed because it is too large. Load diff