Merge branch 'dev' into hugo-shipping-notice
# Conflicts: # backend/app/api/workspace_shipping_notice.py
This commit is contained in:
commit
60dd0c0f58
102 files changed
+6189
-4044
No files matched your search
@@ -2,5 +2,32 @@
|
||||
backend/app/services/admin/__init__.py
|
||||
|
||||
用途:管理后台业务服务包。
|
||||
逻辑:Wave 3 从 api/admin/_legacy 抽取 users/agents/departments/settings 等。
|
||||
逻辑:Wave 3 从 api/admin 抽取;子模块按需 import。
|
||||
"""
|
||||
from . import (
|
||||
agent_service,
|
||||
announcement_service,
|
||||
dashboard_service,
|
||||
database_admin_service,
|
||||
department_service,
|
||||
faq_service,
|
||||
guide_service,
|
||||
permission_service,
|
||||
report_service,
|
||||
user_service,
|
||||
wecom_admin_service,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'agent_service',
|
||||
'announcement_service',
|
||||
'dashboard_service',
|
||||
'database_admin_service',
|
||||
'department_service',
|
||||
'faq_service',
|
||||
'guide_service',
|
||||
'permission_service',
|
||||
'report_service',
|
||||
'user_service',
|
||||
'wecom_admin_service',
|
||||
]
|
||||
@@ -1,5 +1,290 @@
|
||||
"""
|
||||
backend/app/services/admin/agent_service.py
|
||||
|
||||
用途:Agent CRUD、权限、guide 配置。
|
||||
用途:管理端 Agent CRUD、连通性测试、用户权限绑定。
|
||||
依赖:models、DifyService、Config、requests。
|
||||
逻辑:由 api/admin/agents.py 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
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.services.dify import DifyService
|
||||
|
||||
|
||||
def serialize_agent(agent: Agent) -> dict:
|
||||
"""Agent ORM → 管理端列表 JSON。"""
|
||||
return {
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'dify_app_id': agent.dify_app_id,
|
||||
'dify_api_key': agent.dify_api_key,
|
||||
'is_active': agent.is_active,
|
||||
'description': agent.description,
|
||||
'type': agent.type,
|
||||
'api_base_url': agent.api_base_url,
|
||||
'extra_config': agent.extra_config,
|
||||
}
|
||||
|
||||
|
||||
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]
|
||||
|
||||
|
||||
def create_agent(data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
创建 Agent。
|
||||
Returns:
|
||||
{ id }。
|
||||
Raises:
|
||||
ValidationError: name 缺失或 API 类型缺少 dify_app_id。
|
||||
"""
|
||||
if not data.get('name'):
|
||||
raise ValidationError('Name is required')
|
||||
agent_type = data.get('type', 'api')
|
||||
if agent_type == 'api' and (not data.get('dify_app_id')):
|
||||
raise ValidationError('App ID is required for API agents')
|
||||
agent = Agent(
|
||||
name=data['name'],
|
||||
dify_app_id=data.get('dify_app_id') or None,
|
||||
dify_api_key=data.get('dify_api_key') or None,
|
||||
description=data.get('description'),
|
||||
type=agent_type,
|
||||
api_base_url=data.get('api_base_url'),
|
||||
extra_config=data.get('extra_config'),
|
||||
is_active=data.get('is_active', True),
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
return {'id': agent.id}
|
||||
|
||||
|
||||
def update_agent(agent_id: int, data: dict[str, Any]) -> None:
|
||||
"""更新 Agent 字段;dify_api_key 仅在非空时覆盖。"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
for key in ['name', 'dify_app_id', 'description', 'type', 'api_base_url', 'extra_config', 'is_active']:
|
||||
if key in data:
|
||||
setattr(agent, key, data[key])
|
||||
if data.get('dify_api_key'):
|
||||
agent.dify_api_key = data['dify_api_key']
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def delete_agent(agent_id: int) -> None:
|
||||
"""删除 Agent(不存在时静默成功)。"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if agent:
|
||||
db.session.delete(agent)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_agent_connectivity(agent_id: int) -> dict[str, Any]:
|
||||
"""
|
||||
测试 Agent 连通性(iframe GET 或 Dify chatflow/workflow POST)。
|
||||
核心逻辑:通过则可选自动 is_active=True。
|
||||
Returns:
|
||||
passed、request_url、output_info、analysis、http_status、tested_at 等。
|
||||
Raises:
|
||||
NotFoundError: Agent 不存在。
|
||||
"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
tested_at = datetime.utcnow().isoformat()
|
||||
if agent.type == 'iframe':
|
||||
return _test_iframe_agent(agent, tested_at)
|
||||
return _test_dify_agent(agent, tested_at)
|
||||
|
||||
|
||||
def _test_iframe_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||||
iframe_url = (agent.extra_config or {}).get('iframe_url')
|
||||
if not iframe_url:
|
||||
return {
|
||||
'passed': False,
|
||||
'request_url': '',
|
||||
'output_info': 'Missing iframe_url in extra_config.',
|
||||
'analysis': '测试失败:未配置 iframe URL。',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
try:
|
||||
resp = requests.get(iframe_url, timeout=(5, 15), allow_redirects=True)
|
||||
passed = 200 <= resp.status_code < 400
|
||||
if passed and (not agent.is_active):
|
||||
agent.is_active = True
|
||||
db.session.commit()
|
||||
return {
|
||||
'passed': passed,
|
||||
'request_url': iframe_url,
|
||||
'output_info': f'HTTP {resp.status_code}; response length={len(resp.text)}',
|
||||
'analysis': '测试通过:iframe 地址可访问。' if passed else '测试失败:iframe 地址不可访问或返回异常状态。',
|
||||
'http_status': resp.status_code,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
except requests.RequestException as exc:
|
||||
return {
|
||||
'passed': False,
|
||||
'request_url': iframe_url,
|
||||
'output_info': str(exc),
|
||||
'analysis': '测试失败:请求 iframe 地址异常。',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
|
||||
|
||||
def _test_dify_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||||
if not agent.dify_api_key:
|
||||
return {
|
||||
'passed': False,
|
||||
'request_url': '',
|
||||
'output_info': 'Missing dify_api_key.',
|
||||
'analysis': '测试失败:未配置 API Key。',
|
||||
'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。',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
extra_config = agent.extra_config or {}
|
||||
dify_app_type = str(extra_config.get('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'}
|
||||
try:
|
||||
resp = requests.post(request_url, headers=headers, json=payload, timeout=(5, 25))
|
||||
raw_text = (resp.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:
|
||||
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):
|
||||
agent.is_active = True
|
||||
db.session.commit()
|
||||
return {
|
||||
'passed': passed,
|
||||
'dify_app_type': dify_app_type,
|
||||
'request_url': request_url,
|
||||
'output_info': output_info,
|
||||
'analysis': analysis,
|
||||
'http_status': resp.status_code,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
except requests.RequestException as exc:
|
||||
return {
|
||||
'passed': False,
|
||||
'dify_app_type': dify_app_type,
|
||||
'request_url': request_url,
|
||||
'output_info': str(exc),
|
||||
'analysis': '测试失败:请求异常(网络、超时或认证问题)。',
|
||||
'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
|
||||
outputs = workflow_data.get('outputs') if isinstance(workflow_data, dict) else None
|
||||
status = workflow_data.get('status') if isinstance(workflow_data, dict) else None
|
||||
message = data.get('message') if isinstance(data, dict) else None
|
||||
if isinstance(outputs, dict) and outputs:
|
||||
output_info = str(outputs)[:4000]
|
||||
elif isinstance(message, str) and message.strip():
|
||||
output_info = message[:4000]
|
||||
elif isinstance(data, dict):
|
||||
output_info = str(data)[:4000]
|
||||
if resp.ok and status in ('succeeded', 'success'):
|
||||
analysis = '测试通过:Workflow 接口可访问且业务返回成功。'
|
||||
elif resp.ok:
|
||||
analysis = '测试通过:Workflow 接口可访问且认证通过(本次未返回业务成功状态)。'
|
||||
return passed, output_info, analysis
|
||||
|
||||
|
||||
def _parse_chatflow_test_response(resp, data, output_info: str, analysis: str, passed: bool) -> tuple[bool, str, str]:
|
||||
answer = data.get('answer') if isinstance(data, dict) else None
|
||||
if answer:
|
||||
output_info = str(answer)[:4000]
|
||||
if resp.ok and isinstance(answer, str) and answer.strip():
|
||||
passed = True
|
||||
analysis = '测试通过:Chatflow 接口可访问且已返回回答。'
|
||||
elif resp.ok:
|
||||
analysis = '测试未通过:Chatflow 接口可访问,但未返回有效回答。'
|
||||
else:
|
||||
message = data.get('message') if isinstance(data, dict) else None
|
||||
if message:
|
||||
output_info = str(message)[:4000]
|
||||
return passed, output_info, analysis
|
||||
|
||||
|
||||
def update_agent_permissions(agent_id: int, user_ids: list[int]) -> None:
|
||||
"""
|
||||
将 Agent 的授权用户集合设为 user_ids(增量 add/remove)。
|
||||
Raises:
|
||||
NotFoundError: Agent 不存在。
|
||||
"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
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)
|
||||
to_add = new_user_ids - current_user_ids
|
||||
if to_add:
|
||||
users_to_add = db.session.query(User).filter(User.id.in_(to_add)).all()
|
||||
for user in users_to_add:
|
||||
user.agents.append(agent)
|
||||
to_remove = current_user_ids - new_user_ids
|
||||
if to_remove:
|
||||
users_to_remove = db.session.query(User).filter(User.id.in_(to_remove)).all()
|
||||
for user in users_to_remove:
|
||||
user.agents.remove(agent)
|
||||
db.session.commit()
|
||||
@@ -0,0 +1,93 @@
|
||||
"""
|
||||
backend/app/services/admin/announcement_service.py
|
||||
|
||||
用途:系统公告 CRUD 与活跃公告列表(管理端 + 工作台/登录页只读)。
|
||||
依赖:models.Announcement、app.core.errors。
|
||||
逻辑:api/admin/announcements.py 管理 CRUD;api/workspace/announcements.py 只读活跃列表。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Announcement
|
||||
|
||||
|
||||
def serialize_announcement(ann: Announcement, *, include_active: bool = False) -> dict:
|
||||
"""Announcement ORM → API dict。"""
|
||||
row = {
|
||||
'id': ann.id,
|
||||
'title': ann.title,
|
||||
'content': ann.content,
|
||||
'created_at': ann.created_at.isoformat() if ann.created_at else None,
|
||||
}
|
||||
if include_active:
|
||||
row['is_active'] = bool(ann.is_active)
|
||||
return row
|
||||
|
||||
|
||||
def list_active_announcements() -> list[dict]:
|
||||
"""返回已发布(is_active)公告,供工作台/登录页展示。"""
|
||||
rows = (
|
||||
db.session.query(Announcement)
|
||||
.filter(Announcement.is_active.is_(True))
|
||||
.order_by(Announcement.created_at.desc())
|
||||
.all()
|
||||
)
|
||||
return [serialize_announcement(a) for a in rows]
|
||||
|
||||
|
||||
def list_announcements() -> list[dict]:
|
||||
"""管理端列表:含全部公告及 is_active 字段。"""
|
||||
rows = db.session.query(Announcement).order_by(Announcement.created_at.desc()).all()
|
||||
return [serialize_announcement(a, include_active=True) for a in rows]
|
||||
|
||||
|
||||
def create_announcement(data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
创建公告。
|
||||
Returns:
|
||||
{ id, message }。
|
||||
Raises:
|
||||
ValidationError: title/content 缺失。
|
||||
"""
|
||||
if not data.get('title') or not data.get('content'):
|
||||
raise ValidationError('Missing fields')
|
||||
ann = Announcement(
|
||||
title=data['title'],
|
||||
content=data['content'],
|
||||
is_active=bool(data.get('is_active', True)),
|
||||
)
|
||||
db.session.add(ann)
|
||||
db.session.commit()
|
||||
return {'message': 'Created', 'id': ann.id}
|
||||
|
||||
|
||||
def update_announcement(announcement_id: int, data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
更新公告 title/content(及可选 is_active)。
|
||||
Raises:
|
||||
NotFoundError: 公告不存在。
|
||||
ValidationError: title/content 缺失。
|
||||
"""
|
||||
if not data.get('title') or not data.get('content'):
|
||||
raise ValidationError('Missing fields')
|
||||
ann = db.session.get(Announcement, announcement_id)
|
||||
if not ann:
|
||||
raise NotFoundError('Not found')
|
||||
ann.title = data['title']
|
||||
ann.content = data['content']
|
||||
if 'is_active' in data:
|
||||
ann.is_active = bool(data['is_active'])
|
||||
db.session.commit()
|
||||
return {'message': 'Updated'}
|
||||
|
||||
|
||||
def delete_announcement(announcement_id: int) -> dict:
|
||||
"""删除公告(不存在时静默成功)。"""
|
||||
ann = db.session.get(Announcement, announcement_id)
|
||||
if ann:
|
||||
db.session.delete(ann)
|
||||
db.session.commit()
|
||||
return {'message': 'Deleted'}
|
||||
@@ -1,5 +1,60 @@
|
||||
"""
|
||||
backend/app/services/admin/dashboard_service.py
|
||||
|
||||
用途:管理后台仪表盘统计聚合。
|
||||
用途:管理后台仪表盘统计与侧栏角标聚合。
|
||||
依赖:models、SQLAlchemy func。
|
||||
逻辑:由 api/admin/dashboard.py 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ChatLog, Feedback, PermissionRequest, User
|
||||
|
||||
|
||||
def compute_dashboard_summary() -> dict:
|
||||
"""
|
||||
聚合仪表盘四张卡片所需的统计值(仅 COUNT/AVG,不返回列表)。
|
||||
Returns:
|
||||
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
|
||||
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
|
||||
return {
|
||||
'agent_count': active_agents,
|
||||
'user_count': total_users,
|
||||
'total_conversations': total_conversations,
|
||||
'avg_score': avg_score,
|
||||
}
|
||||
|
||||
|
||||
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'],
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
"""
|
||||
backend/app/services/admin/database_admin_service.py
|
||||
|
||||
用途:管理后台通用数据表浏览与 chat_logs 批量删除。
|
||||
依赖:models、report_service(chat_logs 报表复用)。
|
||||
逻辑:由 api/admin/database.py 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import (
|
||||
Agent,
|
||||
ChatLog,
|
||||
Department,
|
||||
Feedback,
|
||||
PermissionRequest,
|
||||
QuickQuestion,
|
||||
User,
|
||||
UserDefaultAgent,
|
||||
UserFavoriteAgent,
|
||||
UserHomepageConfig,
|
||||
)
|
||||
from app.services.admin import report_service
|
||||
|
||||
ADMIN_TABLE_MODEL_MAP = {
|
||||
'users': User,
|
||||
'agents': Agent,
|
||||
'chat_logs': ChatLog,
|
||||
'feedbacks': Feedback,
|
||||
'permission_requests': PermissionRequest,
|
||||
'departments': Department,
|
||||
'quick_questions': QuickQuestion,
|
||||
'user_homepage_configs': UserHomepageConfig,
|
||||
'user_favorite_agents': UserFavoriteAgent,
|
||||
'user_default_agents': UserDefaultAgent,
|
||||
}
|
||||
|
||||
|
||||
def _serialize_model_row(item) -> dict:
|
||||
row = {}
|
||||
for col in item.__table__.columns:
|
||||
val = getattr(item, col.name)
|
||||
if isinstance(val, datetime):
|
||||
val = val.isoformat()
|
||||
row[col.name] = val
|
||||
return row
|
||||
|
||||
|
||||
def get_table_data(table: str, query_params: dict[str, str]) -> list[dict]:
|
||||
"""
|
||||
返回管理报表表数据(最多 100 行)。
|
||||
chat_logs 走专用报表 JOIN 逻辑。
|
||||
"""
|
||||
if table == 'chat_logs':
|
||||
return report_service.list_chat_logs_report(query_params)
|
||||
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)
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
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 使用报表筛选。"""
|
||||
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()
|
||||
return {'table': table, 'total': int(total or 0)}
|
||||
|
||||
|
||||
def batch_delete_chat_logs(raw_ids: list[Any]) -> dict:
|
||||
"""按 id 批量删除 ChatLog。"""
|
||||
if not isinstance(raw_ids, list) or not raw_ids:
|
||||
raise ValidationError('ids is required')
|
||||
ids = []
|
||||
for value in raw_ids:
|
||||
try:
|
||||
ids.append(int(value))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if not ids:
|
||||
raise ValidationError('No valid ids')
|
||||
cnt = db.session.query(ChatLog).filter(ChatLog.id.in_(ids)).delete(synchronize_session=False)
|
||||
db.session.commit()
|
||||
return {'deleted_count': cnt}
|
||||
@@ -1,5 +1,91 @@
|
||||
"""
|
||||
backend/app/services/admin/department_service.py
|
||||
|
||||
用途:部门 CRUD。
|
||||
用途:管理端部门 CRUD 业务编排。
|
||||
依赖:models.Department、app.core.errors。
|
||||
逻辑:由 api/admin/departments.py 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Department
|
||||
|
||||
|
||||
def serialize_department(dept: Department) -> dict:
|
||||
"""部门 ORM → API dict。"""
|
||||
return {
|
||||
'id': dept.id,
|
||||
'name': dept.name,
|
||||
'code': dept.code,
|
||||
'company': dept.company,
|
||||
'description': dept.description,
|
||||
}
|
||||
|
||||
|
||||
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]
|
||||
|
||||
|
||||
def create_department(data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
创建部门。
|
||||
Returns:
|
||||
{ id, name }。
|
||||
Raises:
|
||||
ValidationError: name 缺失或 name/code 重复。
|
||||
"""
|
||||
if not data.get('name'):
|
||||
raise ValidationError('Name is required')
|
||||
if db.session.query(Department).filter_by(name=data['name']).first():
|
||||
raise ValidationError('Name exists')
|
||||
if data.get('code') and db.session.query(Department).filter_by(code=data['code']).first():
|
||||
raise ValidationError('Code exists')
|
||||
dept = Department(
|
||||
name=data['name'],
|
||||
code=data.get('code'),
|
||||
company=data.get('company'),
|
||||
description=data.get('description'),
|
||||
)
|
||||
db.session.add(dept)
|
||||
db.session.commit()
|
||||
return {'id': dept.id, 'name': dept.name}
|
||||
|
||||
|
||||
def update_department(dept_id: int, data: dict[str, Any]) -> None:
|
||||
"""
|
||||
更新部门字段。
|
||||
Raises:
|
||||
NotFoundError: 部门不存在。
|
||||
ValidationError: name/code 与其它记录冲突。
|
||||
"""
|
||||
dept = db.session.get(Department, dept_id)
|
||||
if not dept:
|
||||
raise NotFoundError('Not found')
|
||||
if 'name' in data:
|
||||
if db.session.query(Department).filter(Department.name == data['name'], Department.id != dept_id).first():
|
||||
raise ValidationError('Name exists')
|
||||
dept.name = data['name']
|
||||
if 'code' in data:
|
||||
if data['code'] and db.session.query(Department).filter(
|
||||
Department.code == data['code'], Department.id != dept_id
|
||||
).first():
|
||||
raise ValidationError('Code exists')
|
||||
dept.code = data['code']
|
||||
if 'company' in data:
|
||||
dept.company = data['company']
|
||||
if 'description' in data:
|
||||
dept.description = data['description']
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def delete_department(dept_id: int) -> None:
|
||||
"""删除部门(不存在时静默成功)。"""
|
||||
dept = db.session.get(Department, dept_id)
|
||||
if dept:
|
||||
db.session.delete(dept)
|
||||
db.session.commit()
|
||||
@@ -0,0 +1,237 @@
|
||||
"""
|
||||
backend/app/services/admin/faq_service.py
|
||||
|
||||
用途:全局常用问题(QuickQuestion)与热点 FAQ 候选管理。
|
||||
依赖:models、faq_kb_invalidation、hot_faq_* services。
|
||||
逻辑:由 api/admin/quick_questions.py、faq_candidates.py 调用。
|
||||
"""
|
||||
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, KbDocument, QuickQuestion
|
||||
|
||||
|
||||
def parse_aliases(raw_aliases) -> list[str]:
|
||||
"""解析别名列表,支持 JSON 数组或换行分隔字符串。"""
|
||||
if raw_aliases is None:
|
||||
return []
|
||||
if isinstance(raw_aliases, list):
|
||||
items = [str(item).strip() for item in raw_aliases if str(item).strip()]
|
||||
elif isinstance(raw_aliases, str):
|
||||
items = [line.strip() for line in raw_aliases.splitlines() if line.strip()]
|
||||
else:
|
||||
return []
|
||||
seen: set[str] = set()
|
||||
result: list[str] = []
|
||||
for item in items:
|
||||
if item not in seen:
|
||||
seen.add(item)
|
||||
result.append(item)
|
||||
return result
|
||||
|
||||
|
||||
def parse_expires_at(raw_value) -> datetime | None:
|
||||
"""解析 FAQ 过期时间 ISO 字符串。"""
|
||||
if not raw_value:
|
||||
return None
|
||||
text = str(raw_value).strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return datetime.fromisoformat(text.replace('Z', '+00:00')).replace(tzinfo=None)
|
||||
except ValueError as exc:
|
||||
raise ValidationError('Invalid expires_at format') from exc
|
||||
|
||||
|
||||
def serialize_quick_question(
|
||||
q: QuickQuestion,
|
||||
agent_name: str,
|
||||
stale_kb_document: KbDocument | None = None,
|
||||
) -> dict:
|
||||
"""序列化全局常用问题供管理端展示。"""
|
||||
return {
|
||||
'id': q.id,
|
||||
'title': q.title,
|
||||
'question': q.question,
|
||||
'answer': q.answer,
|
||||
'aliases': q.aliases if isinstance(q.aliases, list) else [],
|
||||
'cache_enabled': bool(q.cache_enabled),
|
||||
'is_enabled': bool(q.is_enabled),
|
||||
'hit_count': q.hit_count or 0,
|
||||
'agent_id': q.agent_id,
|
||||
'agent_name': agent_name,
|
||||
'sort_order': q.sort_order,
|
||||
'expires_at': q.expires_at.isoformat() if q.expires_at else None,
|
||||
'updated_at': q.updated_at.isoformat() if getattr(q, 'updated_at', None) else None,
|
||||
'source_kb_document_ids': q.source_kb_document_ids if isinstance(q.source_kb_document_ids, list) else [],
|
||||
'stale_at': q.stale_at.isoformat() if getattr(q, 'stale_at', None) else None,
|
||||
'stale_reason': q.stale_reason,
|
||||
'stale_kb_document_id': q.stale_kb_document_id,
|
||||
'stale_kb_document_title': stale_kb_document.title if stale_kb_document else None,
|
||||
}
|
||||
|
||||
|
||||
def apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answer: bool = False) -> None:
|
||||
"""将请求体字段写入 QuickQuestion 实例。"""
|
||||
if 'title' in data:
|
||||
qq.title = str(data['title']).strip()
|
||||
if 'question' in data:
|
||||
qq.question = str(data['question']).strip()
|
||||
if 'agent_id' in data:
|
||||
qq.agent_id = data['agent_id']
|
||||
if 'sort_order' in data:
|
||||
qq.sort_order = data.get('sort_order', 0)
|
||||
if 'answer' in data:
|
||||
qq.answer = str(data['answer']).strip() or None
|
||||
if 'aliases' in data:
|
||||
qq.aliases = parse_aliases(data['aliases'])
|
||||
if 'cache_enabled' in data:
|
||||
qq.cache_enabled = bool(data['cache_enabled'])
|
||||
if 'is_enabled' in data:
|
||||
qq.is_enabled = bool(data['is_enabled'])
|
||||
if 'expires_at' in data:
|
||||
qq.expires_at = parse_expires_at(data['expires_at'])
|
||||
if 'retriever_resources' in data and isinstance(data.get('retriever_resources'), list):
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
|
||||
apply_retriever_resources_to_faq(qq, data['retriever_resources'])
|
||||
if data.get('clear_stale'):
|
||||
from app.services.faq_kb_invalidation import clear_faq_stale
|
||||
|
||||
clear_faq_stale(qq)
|
||||
|
||||
if qq.cache_enabled and not str(qq.answer or '').strip():
|
||||
raise ValidationError('启用 FAQ 缓存时必须填写标准答案')
|
||||
if require_answer and (not qq.title or not qq.question or not qq.agent_id):
|
||||
raise ValidationError('Missing required fields')
|
||||
|
||||
|
||||
def list_quick_questions(*, stale_only: bool = False) -> list[dict]:
|
||||
"""列出全局常用问题(user_id IS NULL)。"""
|
||||
query = (
|
||||
db.session.query(QuickQuestion)
|
||||
.filter(QuickQuestion.user_id.is_(None))
|
||||
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
|
||||
)
|
||||
if stale_only:
|
||||
query = query.filter(QuickQuestion.stale_at.isnot(None))
|
||||
rows = []
|
||||
for q in query.all():
|
||||
agent = db.session.get(Agent, q.agent_id)
|
||||
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
|
||||
|
||||
|
||||
def create_quick_question(data: dict[str, Any]) -> dict:
|
||||
"""创建全局 QuickQuestion。"""
|
||||
qq = QuickQuestion(user_id=None)
|
||||
apply_quick_question_payload(qq, data, require_answer=True)
|
||||
if isinstance(data.get('retriever_resources'), list):
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
|
||||
apply_retriever_resources_to_faq(qq, data['retriever_resources'])
|
||||
qq.updated_at = datetime.utcnow()
|
||||
db.session.add(qq)
|
||||
db.session.commit()
|
||||
return {'id': qq.id}
|
||||
|
||||
|
||||
def update_quick_question(question_id: int, data: dict[str, Any]) -> None:
|
||||
"""更新全局 QuickQuestion。"""
|
||||
qq = db.session.get(QuickQuestion, question_id)
|
||||
if not qq or qq.user_id is not None:
|
||||
raise NotFoundError('Not found')
|
||||
apply_quick_question_payload(qq, data)
|
||||
qq.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def delete_quick_question(question_id: int) -> None:
|
||||
"""删除 QuickQuestion(不存在时静默成功)。"""
|
||||
qq = db.session.get(QuickQuestion, question_id)
|
||||
if qq:
|
||||
db.session.delete(qq)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def list_faq_candidates(*, agent_id: int | None = None) -> dict:
|
||||
"""列出热点 FAQ 候选及统计。"""
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
||||
|
||||
items = HotFaqCandidateStore.list_candidates(agent_id)
|
||||
return {
|
||||
'items': items,
|
||||
'stats': HotFaqCandidateStore.summarize(items),
|
||||
'rules': HotFaqAggregator.get_rules_document(),
|
||||
}
|
||||
|
||||
|
||||
def refresh_faq_candidates(*, agent_id: int | None, dry_run: bool) -> dict:
|
||||
"""手动触发离线热点聚合。"""
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
|
||||
return HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run)
|
||||
|
||||
|
||||
def promote_faq_candidate(data: dict[str, Any]) -> dict:
|
||||
"""将热点候选晋升为全局 QuickQuestion。"""
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
||||
|
||||
agent_id = data.get('agent_id')
|
||||
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')
|
||||
|
||||
candidate = HotFaqCandidateStore.get_candidate(int(agent_id), q_norm)
|
||||
if not candidate:
|
||||
raise NotFoundError('FAQ candidate not found')
|
||||
|
||||
title = str(data.get('title') or candidate.get('canonical_query') or q_norm).strip()[:100]
|
||||
question = str(candidate.get('canonical_query') or q_norm).strip()
|
||||
answer = str(candidate.get('answer') or '').strip()
|
||||
if not answer:
|
||||
raise ValidationError('Candidate has no answer')
|
||||
|
||||
aliases = [q for q in (candidate.get('sample_queries') or []) if normalize_faq_query(q) != q_norm]
|
||||
retriever_resources = candidate.get('retriever_resources') if isinstance(candidate.get('retriever_resources'), list) else None
|
||||
qq = QuickQuestion(
|
||||
user_id=None,
|
||||
agent_id=int(agent_id),
|
||||
title=title,
|
||||
question=question,
|
||||
answer=answer,
|
||||
aliases=aliases or None,
|
||||
cache_enabled=True,
|
||||
is_enabled=True,
|
||||
retriever_resources=retriever_resources,
|
||||
sort_order=int(data.get('sort_order') or 0),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
apply_retriever_resources_to_faq(qq, retriever_resources)
|
||||
db.session.add(qq)
|
||||
db.session.flush()
|
||||
if not HotFaqCandidateStore.mark_promoted(int(agent_id), q_norm, qq.id):
|
||||
db.session.rollback()
|
||||
raise NotFoundError('FAQ candidate not found')
|
||||
db.session.commit()
|
||||
return {'id': qq.id, 'status': 'ok'}
|
||||
|
||||
|
||||
def dismiss_faq_candidate(*, agent_id: int, q_norm: str) -> dict:
|
||||
"""忽略热点 FAQ 候选。"""
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
||||
|
||||
normalized = normalize_faq_query(q_norm)
|
||||
if not agent_id or not normalized:
|
||||
raise ValidationError('agent_id and q_norm are required')
|
||||
HotFaqCandidateStore.dismiss(int(agent_id), normalized)
|
||||
return {'status': 'ok'}
|
||||
@@ -0,0 +1,122 @@
|
||||
"""
|
||||
backend/app/services/admin/guide_service.py
|
||||
|
||||
用途:Agent 引导资料(视频/PDF/图片)CRUD 与 MinIO 上传。
|
||||
依赖:models.AgentGuide、minio_service。
|
||||
逻辑:由 api/admin/guides.py 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.models import AgentGuide
|
||||
from app.services.minio_service import minio_service
|
||||
|
||||
|
||||
def _infer_file_type(content_type: str | None) -> str:
|
||||
ct = str(content_type or '')
|
||||
if ct.startswith('video'):
|
||||
return 'video'
|
||||
if 'pdf' in ct:
|
||||
return 'pdf'
|
||||
return 'image'
|
||||
|
||||
|
||||
def serialize_guide(guide: AgentGuide) -> dict:
|
||||
"""AgentGuide ORM → API dict(含公开 URL)。"""
|
||||
return {
|
||||
'id': guide.id,
|
||||
'agent_id': guide.agent_id,
|
||||
'file_name': guide.file_name,
|
||||
'file_type': guide.file_type,
|
||||
'file_path': guide.file_path,
|
||||
'file_url': minio_service.get_public_url(guide.file_path),
|
||||
'file_size': guide.file_size,
|
||||
'remark': guide.remark,
|
||||
'sort_order': guide.sort_order,
|
||||
'status': guide.status,
|
||||
'created_at': guide.created_at.isoformat() if guide.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
def upload_guide_file(file_storage: FileStorage | None) -> dict:
|
||||
"""
|
||||
上传引导文件至 MinIO。
|
||||
Returns:
|
||||
file_path、file_name、file_size、file_type。
|
||||
Raises:
|
||||
ValidationError: 无文件。
|
||||
AppError: 上传失败。
|
||||
"""
|
||||
if not file_storage or file_storage.filename == '':
|
||||
raise ValidationError('No selected file' if file_storage else 'No file part')
|
||||
content_type = file_storage.content_type
|
||||
file_size = len(file_storage.read())
|
||||
file_storage.seek(0)
|
||||
try:
|
||||
object_name = minio_service.upload_file(file_storage, file_storage.filename, content_type, file_size)
|
||||
return {
|
||||
'file_path': object_name,
|
||||
'file_name': file_storage.filename,
|
||||
'file_size': file_size,
|
||||
'file_type': _infer_file_type(content_type),
|
||||
}
|
||||
except Exception as exc:
|
||||
raise AppError(f'Upload failed: {str(exc)}')
|
||||
|
||||
|
||||
def list_guides(*, agent_id: int | None = None) -> list[dict]:
|
||||
"""按 agent_id 可选过滤返回引导列表。"""
|
||||
query = db.session.query(AgentGuide)
|
||||
if agent_id is not None:
|
||||
query = query.filter_by(agent_id=agent_id)
|
||||
guides = query.order_by(AgentGuide.sort_order).all()
|
||||
return [serialize_guide(g) for g in guides]
|
||||
|
||||
|
||||
def create_guide(data: dict[str, Any], *, created_by_id: int | None) -> dict:
|
||||
"""创建 AgentGuide 记录。"""
|
||||
guide = AgentGuide(
|
||||
agent_id=data['agent_id'],
|
||||
file_name=data['file_name'],
|
||||
file_type=data['file_type'],
|
||||
file_path=data['file_path'],
|
||||
file_size=data.get('file_size'),
|
||||
remark=data.get('remark'),
|
||||
sort_order=data.get('sort_order', 0),
|
||||
status=data.get('status', 1),
|
||||
created_by=created_by_id,
|
||||
)
|
||||
db.session.add(guide)
|
||||
db.session.commit()
|
||||
return {'id': guide.id}
|
||||
|
||||
|
||||
def update_guide(guide_id: int, data: dict[str, Any]) -> None:
|
||||
"""更新引导元数据。"""
|
||||
guide = db.session.get(AgentGuide, guide_id)
|
||||
if not guide:
|
||||
raise NotFoundError('Guide not found')
|
||||
if 'file_name' in data:
|
||||
guide.file_name = data['file_name']
|
||||
if 'remark' in data:
|
||||
guide.remark = data['remark']
|
||||
if 'sort_order' in data:
|
||||
guide.sort_order = data['sort_order']
|
||||
if 'status' in data:
|
||||
guide.status = data['status']
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def delete_guide(guide_id: int) -> None:
|
||||
"""删除引导并移除 MinIO 对象。"""
|
||||
guide = db.session.get(AgentGuide, guide_id)
|
||||
if not guide:
|
||||
raise NotFoundError('Guide not found')
|
||||
minio_service.delete_file(guide.file_path)
|
||||
db.session.delete(guide)
|
||||
db.session.commit()
|
||||
@@ -1,5 +1,174 @@
|
||||
"""
|
||||
backend/app/services/admin/permission_service.py
|
||||
|
||||
用途:权限申请、批量授权业务逻辑。
|
||||
用途:用户 Agent 权限批量/单用户更新,以及权限申请审批业务逻辑。
|
||||
依赖:models、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.services.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()
|
||||
return users, agents
|
||||
|
||||
|
||||
def _apply_user_agent_action(user: User, agents: list[Agent], action: str) -> None:
|
||||
"""对单个用户执行 add / remove / set 权限变更。"""
|
||||
if action == 'set':
|
||||
user.agents = agents
|
||||
elif action == 'add':
|
||||
for agent in agents:
|
||||
if agent not in user.agents:
|
||||
user.agents.append(agent)
|
||||
elif action == 'remove':
|
||||
for agent in agents:
|
||||
if agent in user.agents:
|
||||
user.agents.remove(agent)
|
||||
|
||||
|
||||
def _notify_batch_permission_update(user: User, agents: list[Agent], action: str) -> None:
|
||||
"""批量权限变更后向已绑定企微的用户推送通知。"""
|
||||
if not user.wecom_userid:
|
||||
return
|
||||
action_label = _BATCH_ACTION_LABELS.get(action, action)
|
||||
agent_names = '、'.join([a.name for a in agents]) if agents else '无'
|
||||
send_wecom_event_message(
|
||||
event_type='permission_batch_updated',
|
||||
user=user,
|
||||
title='应用权限已更新',
|
||||
content=f'管理员已{action_label}你的应用权限:{agent_names}',
|
||||
jump_path='/workspace',
|
||||
)
|
||||
|
||||
|
||||
def batch_update_permissions(data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
批量更新多用户的 Agent 权限(add / remove / set)。
|
||||
Returns:
|
||||
{ status, updated_count }。
|
||||
Raises:
|
||||
ValidationError: 未选择用户。
|
||||
"""
|
||||
user_ids = data.get('user_ids', [])
|
||||
agent_ids = data.get('agent_ids', [])
|
||||
action = data.get('action', 'add')
|
||||
if not user_ids:
|
||||
raise ValidationError('No users selected')
|
||||
|
||||
users, agents = _load_users_and_agents(user_ids, agent_ids)
|
||||
if not agents and action != 'set':
|
||||
if action == 'remove':
|
||||
return {'status': 'ok', 'updated_count': 0}
|
||||
|
||||
for user in users:
|
||||
_apply_user_agent_action(user, agents, action)
|
||||
_notify_batch_permission_update(user, agents, action)
|
||||
|
||||
db.session.commit()
|
||||
return {'status': 'ok', 'updated_count': len(users)}
|
||||
|
||||
|
||||
def update_user_permissions(user_id: int, data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
将指定用户的 Agent 权限重置为 agent_ids 列表(全量替换)。
|
||||
Returns:
|
||||
{ status }。
|
||||
Raises:
|
||||
NotFoundError: 用户不存在。
|
||||
"""
|
||||
user = db.session.get(User, user_id)
|
||||
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()
|
||||
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')
|
||||
|
||||
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 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'}
|
||||
@@ -0,0 +1,194 @@
|
||||
"""
|
||||
backend/app/services/admin/report_service.py
|
||||
|
||||
用途:管理后台报表(使用分析、反馈、聊天日志)数据聚合。
|
||||
依赖:models、SQLAlchemy func。
|
||||
逻辑:由 api/admin/reports.py、database_admin_service 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import desc, func
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ChatLog, Feedback, GeneralFeedback, User
|
||||
|
||||
USAGE_BY_USER_TOP_LIMIT = 50
|
||||
|
||||
|
||||
def build_usage_report(*, user_page: int, user_page_size: int) -> dict:
|
||||
"""聊天使用分析报表。"""
|
||||
total = db.session.query(ChatLog).count()
|
||||
by_agent = (
|
||||
db.session.query(Agent.name, func.count(ChatLog.id))
|
||||
.join(ChatLog)
|
||||
.group_by(Agent.name)
|
||||
.order_by(desc(func.count(ChatLog.id)), Agent.name)
|
||||
.all()
|
||||
)
|
||||
user_page = max(1, user_page)
|
||||
user_page_size = max(1, min(user_page_size, USAGE_BY_USER_TOP_LIMIT))
|
||||
by_user_top = (
|
||||
db.session.query(User.username, func.count(ChatLog.id))
|
||||
.join(ChatLog)
|
||||
.group_by(User.username)
|
||||
.order_by(desc(func.count(ChatLog.id)), User.username)
|
||||
.limit(USAGE_BY_USER_TOP_LIMIT)
|
||||
.all()
|
||||
)
|
||||
user_total = len(by_user_top)
|
||||
user_pages = max(1, math.ceil(user_total / user_page_size)) if user_total else 1
|
||||
user_page = min(user_page, user_pages)
|
||||
offset = (user_page - 1) * user_page_size
|
||||
by_user_page = by_user_top[offset:offset + user_page_size]
|
||||
return {
|
||||
'total': total,
|
||||
'by_user': [{'username': u, 'count': c} for u, c in by_user_page],
|
||||
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent],
|
||||
'user_total': user_total,
|
||||
'user_page': user_page,
|
||||
'user_page_size': user_page_size,
|
||||
'user_pages': user_pages,
|
||||
'user_top_limit': USAGE_BY_USER_TOP_LIMIT,
|
||||
}
|
||||
|
||||
|
||||
def build_feedback_report() -> dict:
|
||||
"""反馈评分分布报表。"""
|
||||
total = db.session.query(Feedback).count()
|
||||
avg = db.session.query(func.avg(Feedback.score)).scalar() or 0
|
||||
dist = db.session.query(Feedback.score, func.count(Feedback.id)).group_by(Feedback.score).all()
|
||||
return {
|
||||
'total': total,
|
||||
'avg_score': float(avg),
|
||||
'distribution': [{'score': s, 'count': c} for s, c in dist],
|
||||
}
|
||||
|
||||
|
||||
def _apply_general_feedback_filters(query, query_params: dict[str, str]):
|
||||
reserved = {'limit', 'offset', 'page', 'page_size'}
|
||||
for key, value in query_params.items():
|
||||
if key in reserved or not value:
|
||||
continue
|
||||
if hasattr(GeneralFeedback, key):
|
||||
col = getattr(GeneralFeedback, key)
|
||||
elif key == 'real_name':
|
||||
col = User.real_name
|
||||
elif key == 'department':
|
||||
col = User.department
|
||||
else:
|
||||
continue
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
return query
|
||||
|
||||
|
||||
def list_general_feedbacks_report(query_params: dict[str, str]) -> list[dict]:
|
||||
"""通用反馈列表(报表页)。"""
|
||||
query = (
|
||||
db.session.query(
|
||||
GeneralFeedback,
|
||||
User.real_name.label('real_name'),
|
||||
User.department.label('department'),
|
||||
)
|
||||
.outerjoin(User, User.id == GeneralFeedback.user_id)
|
||||
)
|
||||
query = _apply_general_feedback_filters(query, query_params)
|
||||
query = query.order_by(desc(GeneralFeedback.created_at), desc(GeneralFeedback.id))
|
||||
try:
|
||||
limit = int(query_params.get('limit', 200))
|
||||
except (TypeError, ValueError):
|
||||
limit = 200
|
||||
limit = max(1, min(limit, 1000))
|
||||
items = query.limit(limit).all()
|
||||
rows = []
|
||||
for item, real_name, department in items:
|
||||
row = {}
|
||||
for col in item.__table__.columns:
|
||||
val = getattr(item, col.name)
|
||||
if isinstance(val, datetime):
|
||||
val = val.isoformat()
|
||||
row[col.name] = val
|
||||
row['real_name'] = real_name
|
||||
row['department'] = department
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def count_general_feedbacks_report(query_params: dict[str, str]) -> dict:
|
||||
"""通用反馈计数。"""
|
||||
query = db.session.query(GeneralFeedback).outerjoin(User, User.id == GeneralFeedback.user_id)
|
||||
query = _apply_general_feedback_filters(query, query_params)
|
||||
total = query.count()
|
||||
return {'table': 'general_feedbacks', 'total': int(total)}
|
||||
|
||||
|
||||
def chat_logs_report_query():
|
||||
"""ChatLog JOIN User、Agent 基础查询。"""
|
||||
return (
|
||||
db.session.query(
|
||||
ChatLog,
|
||||
User.username.label('username'),
|
||||
User.real_name.label('real_name'),
|
||||
Agent.name.label('agent_name'),
|
||||
)
|
||||
.join(User, User.id == ChatLog.user_id)
|
||||
.join(Agent, Agent.id == ChatLog.agent_id)
|
||||
)
|
||||
|
||||
|
||||
def serialize_chat_log_report_row(
|
||||
log: ChatLog,
|
||||
username: str | None,
|
||||
real_name: str | None,
|
||||
agent_name: str | None,
|
||||
) -> dict:
|
||||
"""ChatLog 报表行序列化。"""
|
||||
return {
|
||||
'id': log.id,
|
||||
'agent_name': agent_name or '',
|
||||
'username': username or '',
|
||||
'real_name': real_name or '',
|
||||
'created_at': log.created_at.isoformat() if log.created_at else None,
|
||||
'query': log.query,
|
||||
'answer': log.answer,
|
||||
'tokens_used': log.tokens_used,
|
||||
}
|
||||
|
||||
|
||||
def apply_chat_logs_report_filters(query, query_params: dict[str, str]):
|
||||
"""对聊天日志报表查询应用列筛选。"""
|
||||
reserved = {'limit', 'offset', 'page', 'page_size'}
|
||||
for key, value in query_params.items():
|
||||
if key in reserved or not value:
|
||||
continue
|
||||
if key == 'agent_name':
|
||||
query = query.filter(Agent.name.cast(db.String).ilike(f'%{value}%'))
|
||||
elif key == 'username':
|
||||
query = query.filter(User.username.cast(db.String).ilike(f'%{value}%'))
|
||||
elif key == 'real_name':
|
||||
query = query.filter(User.real_name.cast(db.String).ilike(f'%{value}%'))
|
||||
elif hasattr(ChatLog, key):
|
||||
col = getattr(ChatLog, key)
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
return query
|
||||
|
||||
|
||||
def list_chat_logs_report(query_params: dict[str, str]) -> list[dict]:
|
||||
"""聊天日志报表列表(最多 100 条)。"""
|
||||
query = apply_chat_logs_report_filters(chat_logs_report_query(), query_params)
|
||||
query = query.order_by(desc(ChatLog.created_at), desc(ChatLog.id))
|
||||
items = query.limit(100).all()
|
||||
return [
|
||||
serialize_chat_log_report_row(log, username, real_name, agent_name)
|
||||
for log, username, real_name, agent_name in items
|
||||
]
|
||||
|
||||
|
||||
def count_chat_logs_report(query_params: dict[str, str]) -> dict:
|
||||
"""聊天日志报表计数。"""
|
||||
query = apply_chat_logs_report_filters(chat_logs_report_query(), query_params)
|
||||
total = query.count()
|
||||
return {'table': 'chat_logs', 'total': int(total or 0)}
|
||||
@@ -1,5 +1,305 @@
|
||||
"""
|
||||
backend/app/services/admin/user_service.py
|
||||
|
||||
用途:管理端用户 CRUD、权限分配。
|
||||
用途:管理端用户 CRUD、审批与批量删除;创建/改密时同步 Casdoor。
|
||||
依赖:models、user_admin.delete_admin_users、services/auth/casdoor_service。
|
||||
逻辑:由 api/admin/users.py 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
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.auth import casdoor_service
|
||||
from app.services.user_admin import delete_admin_users
|
||||
|
||||
|
||||
def empty_to_none(value):
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, str) and value.strip() == '':
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def is_valid_email(email: str) -> bool:
|
||||
if not isinstance(email, str):
|
||||
return False
|
||||
email = email.strip()
|
||||
if len(email) > 254:
|
||||
return False
|
||||
pattern = r'^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$'
|
||||
return re.match(pattern, email) is not None
|
||||
|
||||
|
||||
def raise_user_integrity_conflict(exc: IntegrityError) -> None:
|
||||
message = str(getattr(exc, 'orig', exc))
|
||||
if 'users_email_key' in message:
|
||||
raise ConflictError('Email already exists', code='USER.EMAIL_EXISTS')
|
||||
if 'users_employee_id_key' in message:
|
||||
raise ConflictError('Employee ID already exists', code='USER.EMPLOYEE_ID_EXISTS')
|
||||
if 'users_phone_number_key' in message:
|
||||
raise ConflictError('Phone number already exists', code='USER.PHONE_EXISTS')
|
||||
if 'users_username_key' in message or 'ix_users_username' in message:
|
||||
raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS')
|
||||
raise ConflictError('Data uniqueness conflict', code='USER.UNIQUENESS_CONFLICT')
|
||||
|
||||
|
||||
def assert_user_unique_fields(exclude_user_id: int | None, **fields: str | None) -> None:
|
||||
checks = (
|
||||
('email', 'USER.EMAIL_EXISTS', 'Email already exists'),
|
||||
('employee_id', 'USER.EMPLOYEE_ID_EXISTS', 'Employee ID already exists'),
|
||||
('phone_number', 'USER.PHONE_EXISTS', 'Phone number already exists'),
|
||||
)
|
||||
for field, code, message in checks:
|
||||
value = fields.get(field)
|
||||
if value is None:
|
||||
continue
|
||||
query = db.session.query(User.id).filter(getattr(User, field) == value)
|
||||
if exclude_user_id is not None:
|
||||
query = query.filter(User.id != exclude_user_id)
|
||||
if query.first():
|
||||
raise ConflictError(message, code=code, details={'field': field})
|
||||
|
||||
|
||||
def serialize_admin_user(user: User) -> dict:
|
||||
return {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'email': user.email,
|
||||
'department': user.department,
|
||||
'role': user.role,
|
||||
'status': user.status,
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
'phone_number': user.phone_number,
|
||||
'agent_ids': [agent.id for agent in user.agents],
|
||||
}
|
||||
|
||||
|
||||
def apply_users_filters(query, query_params: dict[str, str]):
|
||||
if query_params.get('hide_rejected', 'false').lower() == 'true':
|
||||
query = query.filter(User.status != 'rejected')
|
||||
filter_columns = {
|
||||
'username': User.username,
|
||||
'email': User.email,
|
||||
'department': User.department,
|
||||
'role': User.role,
|
||||
'status': User.status,
|
||||
'real_name': User.real_name,
|
||||
'employee_id': User.employee_id,
|
||||
'phone_number': User.phone_number,
|
||||
}
|
||||
for key, column in filter_columns.items():
|
||||
value = (query_params.get(key) or '').strip()
|
||||
if value:
|
||||
query = query.filter(column.cast(db.String).ilike(f'%{value}%'))
|
||||
return query
|
||||
|
||||
|
||||
def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
||||
query = apply_users_filters(db.session.query(User), query_params)
|
||||
if 'page' not in query_params:
|
||||
users = query.options(joinedload(User.agents)).order_by(User.id.asc()).all()
|
||||
return [serialize_admin_user(u) for u in users]
|
||||
|
||||
try:
|
||||
page = int(query_params.get('page') or 1)
|
||||
except (TypeError, ValueError):
|
||||
page = 1
|
||||
try:
|
||||
page_size = int(query_params.get('page_size') or 20)
|
||||
except (TypeError, ValueError):
|
||||
page_size = 20
|
||||
page = max(1, page)
|
||||
page_size = max(1, min(100, page_size))
|
||||
|
||||
total = query.count()
|
||||
pages = max(1, (total + page_size - 1) // page_size) if total else 1
|
||||
if page > pages:
|
||||
page = pages
|
||||
|
||||
users = (
|
||||
query.options(joinedload(User.agents))
|
||||
.order_by(User.id.asc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
'items': [serialize_admin_user(u) for u in users],
|
||||
'total': int(total),
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'pages': pages,
|
||||
}
|
||||
|
||||
|
||||
def create_user(data: dict[str, Any]) -> dict:
|
||||
required_field_errors = (
|
||||
('username', 'USER.USERNAME_REQUIRED', 'Username is required'),
|
||||
('password', 'USER.PASSWORD_REQUIRED', 'Password is required'),
|
||||
('email', 'USER.EMAIL_REQUIRED', 'Email is required'),
|
||||
('real_name', 'USER.REAL_NAME_REQUIRED', 'Real name is required'),
|
||||
('employee_id', 'USER.EMPLOYEE_ID_REQUIRED', 'Employee ID is required'),
|
||||
('phone_number', 'USER.PHONE_REQUIRED', 'Phone number is required'),
|
||||
)
|
||||
for field, code, message in required_field_errors:
|
||||
if empty_to_none(data.get(field)) is None:
|
||||
raise AppError(code=code, message=message, http_status=400, details={'field': field})
|
||||
if db.session.query(User).filter_by(username=data['username']).first():
|
||||
raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS', details={'field': 'username'})
|
||||
email = empty_to_none(data.get('email'))
|
||||
if not is_valid_email(email):
|
||||
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
|
||||
assert_user_unique_fields(
|
||||
None,
|
||||
email=email,
|
||||
employee_id=empty_to_none(data.get('employee_id')),
|
||||
phone_number=empty_to_none(data.get('phone_number')),
|
||||
)
|
||||
user = User(
|
||||
username=data['username'],
|
||||
email=email,
|
||||
department=empty_to_none(data.get('department')),
|
||||
role=data.get('role', 'user'),
|
||||
status=data.get('status', 'active'),
|
||||
real_name=empty_to_none(data.get('real_name')),
|
||||
employee_id=empty_to_none(data.get('employee_id')),
|
||||
phone_number=empty_to_none(data.get('phone_number')),
|
||||
)
|
||||
user.set_password(data['password'])
|
||||
db.session.add(user)
|
||||
try:
|
||||
if data.get('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,
|
||||
password=data['password'],
|
||||
email=email,
|
||||
real_name=user.real_name,
|
||||
phone_number=user.phone_number,
|
||||
status=user.status,
|
||||
department=user.department,
|
||||
)
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise_user_integrity_conflict(exc)
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except RuntimeError as exc:
|
||||
db.session.rollback()
|
||||
casdoor_service.raise_add_user_error(exc)
|
||||
return {'id': user.id}
|
||||
|
||||
|
||||
def update_user(user_id: int, data: dict[str, Any]) -> dict:
|
||||
user = db.session.get(User, user_id)
|
||||
if not user:
|
||||
raise NotFoundError('User not found')
|
||||
if 'email' in data:
|
||||
email = empty_to_none(data.get('email'))
|
||||
if email is not None and (not is_valid_email(email)):
|
||||
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
|
||||
unique_updates = {
|
||||
field: empty_to_none(data[field])
|
||||
for field in ('email', 'employee_id', 'phone_number')
|
||||
if field in data
|
||||
}
|
||||
assert_user_unique_fields(user_id, **unique_updates)
|
||||
new_password = empty_to_none(data.get('password'))
|
||||
try:
|
||||
for key in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||
if key in data:
|
||||
if key in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||
setattr(user, key, empty_to_none(data[key]))
|
||||
else:
|
||||
setattr(user, key, data[key])
|
||||
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()
|
||||
user.agents = agents
|
||||
if new_password:
|
||||
casdoor_service.sync_update_user(user, new_password=new_password)
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise_user_integrity_conflict(exc)
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except RuntimeError as exc:
|
||||
db.session.rollback()
|
||||
casdoor_service.raise_set_password_error(exc)
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
def cleanup_rejected_users() -> dict:
|
||||
rejected_ids = [row[0] for row in db.session.query(User.id).filter_by(status='rejected').all()]
|
||||
cnt = delete_admin_users(rejected_ids)
|
||||
db.session.commit()
|
||||
return {'deleted_count': cnt}
|
||||
|
||||
|
||||
def batch_delete_users(user_ids: list[Any], *, current_user_id: int | None) -> dict:
|
||||
target_ids = [uid for uid in user_ids if str(uid) != str(current_user_id)]
|
||||
if not target_ids:
|
||||
raise ValidationError('No valid users')
|
||||
try:
|
||||
cnt = delete_admin_users(target_ids)
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise AppError(
|
||||
code='USER.DELETE_BLOCKED',
|
||||
message='Unable to delete user because related records still exist',
|
||||
http_status=409,
|
||||
details={'reason': str(getattr(exc, 'orig', exc))},
|
||||
) from exc
|
||||
return {'deleted_count': cnt}
|
||||
|
||||
|
||||
def delete_user(user_id: int, *, current_user_id: int | None) -> dict:
|
||||
if current_user_id is not None and str(current_user_id) == str(user_id):
|
||||
raise ValidationError('Cannot delete current user')
|
||||
user = db.session.get(User, user_id)
|
||||
if not user:
|
||||
raise NotFoundError('User not found')
|
||||
try:
|
||||
delete_admin_users([user_id])
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise AppError(
|
||||
code='USER.DELETE_BLOCKED',
|
||||
message='Unable to delete user because related records still exist',
|
||||
http_status=409,
|
||||
details={'reason': str(getattr(exc, 'orig', exc))},
|
||||
) from exc
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
def approve_user(user_id: int) -> dict:
|
||||
user = db.session.get(User, user_id)
|
||||
if user:
|
||||
user.status = 'active'
|
||||
db.session.commit()
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
def reject_user(user_id: int) -> dict:
|
||||
user = db.session.get(User, user_id)
|
||||
if user:
|
||||
user.status = 'rejected'
|
||||
db.session.commit()
|
||||
return {'status': 'ok'}
|
||||
@@ -0,0 +1,576 @@
|
||||
"""
|
||||
backend/app/services/admin/wecom_admin_service.py
|
||||
|
||||
用途:管理端企微绑定、配置、诊断与 OA userid 同步。
|
||||
依赖:wecom_auth_service、oa_wecom_sync、env_persistence、models。
|
||||
逻辑:由 api/admin/wecom.py 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
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.auth import wecom_auth_service
|
||||
from app.services.oa_wecom_sync import sync_wecom_userids_from_oa
|
||||
|
||||
|
||||
def serialize_debug_match_user(user: User) -> dict:
|
||||
return {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
'phone_number': user.phone_number,
|
||||
'email': user.email,
|
||||
'status': user.status,
|
||||
'wecom_userid': user.wecom_userid,
|
||||
'wecom_unionid': user.wecom_unionid,
|
||||
}
|
||||
|
||||
|
||||
def build_match_preview(identity: dict, rules: list[str], operator: str) -> dict:
|
||||
bind_mode = wecom_auth_service.get_first_login_bind_mode()
|
||||
preview = {
|
||||
'bind_mode': bind_mode,
|
||||
'rules': {'fields': rules, 'operator': operator},
|
||||
'auto_create_user': bool(current_app.config.get('WECOM_AUTO_CREATE_USER', True)),
|
||||
}
|
||||
bound_user = None
|
||||
if identity.get('wecom_userid'):
|
||||
bound_user = db.session.query(User).filter_by(wecom_userid=identity['wecom_userid']).first()
|
||||
if not bound_user and identity.get('wecom_unionid'):
|
||||
bound_user = db.session.query(User).filter_by(wecom_unionid=identity['wecom_unionid']).first()
|
||||
if bound_user:
|
||||
preview['decision'] = 'already_bound'
|
||||
preview['bound_user'] = serialize_debug_match_user(bound_user)
|
||||
return preview
|
||||
if bind_mode == 'input_verify':
|
||||
preview['decision'] = 'input_verification_required'
|
||||
preview['allowed_fields'] = wecom_auth_service.get_first_login_input_fields()
|
||||
return preview
|
||||
matched_users, missing_fields = wecom_auth_service.find_users_by_match_rules(identity, rules, operator)
|
||||
preview['missing_fields'] = missing_fields
|
||||
preview['matched_users'] = [serialize_debug_match_user(user) for user in matched_users]
|
||||
if missing_fields:
|
||||
preview['decision'] = 'missing_match_fields'
|
||||
elif len(matched_users) == 1:
|
||||
preview['decision'] = 'matched_existing_user'
|
||||
elif len(matched_users) > 1:
|
||||
preview['decision'] = 'ambiguous_match'
|
||||
elif preview['auto_create_user']:
|
||||
preview['decision'] = 'would_auto_create_user'
|
||||
else:
|
||||
preview['decision'] = 'bind_required'
|
||||
return preview
|
||||
|
||||
|
||||
def debug_user_by_code(code: str) -> dict:
|
||||
"""通过 OAuth code 拉取企微用户并返回匹配预览(管理端诊断)。"""
|
||||
if not wecom_auth_service.is_configured():
|
||||
raise ValidationError('WeCom login is not configured')
|
||||
code = str(code or '').strip()
|
||||
if not code:
|
||||
raise ValidationError('code is required')
|
||||
|
||||
access_token = wecom_auth_service.get_access_token()
|
||||
info_resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo',
|
||||
params={'access_token': access_token, 'code': code},
|
||||
timeout=8,
|
||||
)
|
||||
auth_info = info_resp.json()
|
||||
userid = auth_info.get('userid') or auth_info.get('UserId')
|
||||
openid = auth_info.get('openid') or auth_info.get('OpenId')
|
||||
payload = {'auth_info': auth_info}
|
||||
if auth_info.get('errcode') != 0:
|
||||
raise AppError(
|
||||
code='WECOM_AUTH_FAILED',
|
||||
message=f"WeCom auth failed: {auth_info.get('errmsg', 'unknown error')}",
|
||||
http_status=401,
|
||||
details={'auth_info': auth_info},
|
||||
)
|
||||
if not userid:
|
||||
raise AppError(
|
||||
code='WECOM_NOT_IN_AGENT_SCOPE',
|
||||
message='当前 code 对应的账号不在应用可见范围内,或不是本企业成员。',
|
||||
http_status=401,
|
||||
details={'auth_info': auth_info, 'openid': openid},
|
||||
)
|
||||
user_resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/user/get',
|
||||
params={'access_token': access_token, 'userid': userid},
|
||||
timeout=8,
|
||||
)
|
||||
wecom_user = user_resp.json()
|
||||
payload['wecom_user'] = wecom_user
|
||||
if wecom_user.get('errcode') != 0:
|
||||
raise AppError(
|
||||
code='WECOM_USER_FETCH_FAILED',
|
||||
message=f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}",
|
||||
http_status=401,
|
||||
details={'auth_info': auth_info, 'wecom_user': wecom_user},
|
||||
)
|
||||
identity = wecom_auth_service.extract_identity(wecom_user)
|
||||
rules, operator = wecom_auth_service.get_match_config()
|
||||
payload['normalized_identity'] = identity
|
||||
payload['match_preview'] = build_match_preview(identity, rules, operator)
|
||||
return payload
|
||||
|
||||
|
||||
def list_bindings(query_params: dict[str, str]) -> dict:
|
||||
bound_only = query_params.get('bound_only', 'false').lower() == 'true'
|
||||
keyword = (query_params.get('keyword') or '').strip()
|
||||
try:
|
||||
page = int(query_params.get('page') or 1)
|
||||
except (TypeError, ValueError):
|
||||
page = 1
|
||||
try:
|
||||
page_size = int(query_params.get('page_size') or 20)
|
||||
except (TypeError, ValueError):
|
||||
page_size = 20
|
||||
page = max(1, page)
|
||||
page_size = max(1, min(100, page_size))
|
||||
|
||||
query = db.session.query(User)
|
||||
if bound_only:
|
||||
query = query.filter(User.wecom_userid.isnot(None))
|
||||
if keyword:
|
||||
pattern = f'%{keyword}%'
|
||||
query = query.filter(or_(
|
||||
User.username.ilike(pattern),
|
||||
User.real_name.ilike(pattern),
|
||||
User.employee_id.ilike(pattern),
|
||||
User.wecom_userid.ilike(pattern),
|
||||
))
|
||||
|
||||
total = query.count()
|
||||
pages = max(1, (total + page_size - 1) // page_size) if total else 1
|
||||
if page > pages:
|
||||
page = pages
|
||||
|
||||
users = (
|
||||
query.order_by(User.id.asc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
items = [
|
||||
{
|
||||
'id': u.id,
|
||||
'username': u.username,
|
||||
'real_name': u.real_name,
|
||||
'employee_id': u.employee_id,
|
||||
'email': u.email,
|
||||
'role': u.role,
|
||||
'status': u.status,
|
||||
'wecom_userid': u.wecom_userid,
|
||||
'wecom_unionid': u.wecom_unionid,
|
||||
'bound': bool(u.wecom_userid),
|
||||
}
|
||||
for u in users
|
||||
]
|
||||
return {
|
||||
'items': items,
|
||||
'total': int(total),
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'pages': pages,
|
||||
}
|
||||
|
||||
|
||||
def bind_user(data: dict[str, Any]) -> dict:
|
||||
user_id = data.get('user_id')
|
||||
wecom_userid = data.get('wecom_userid')
|
||||
wecom_unionid = data.get('wecom_unionid')
|
||||
if not user_id or not wecom_userid:
|
||||
raise ValidationError('user_id and wecom_userid are required')
|
||||
try:
|
||||
user_id = int(user_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('user_id must be integer')
|
||||
user = db.session.get(User, user_id)
|
||||
if not user:
|
||||
raise NotFoundError('User not found')
|
||||
dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first()
|
||||
if dup:
|
||||
raise ValidationError(f'wecom_userid already bound to user {dup.username}')
|
||||
if wecom_unionid:
|
||||
dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first()
|
||||
if dup_union:
|
||||
raise ValidationError(f'wecom_unionid already bound to user {dup_union.username}')
|
||||
user.wecom_userid = wecom_userid
|
||||
if wecom_unionid is not None:
|
||||
user.wecom_unionid = wecom_unionid
|
||||
db.session.commit()
|
||||
return {'status': 'ok', 'message': 'WeCom binding updated'}
|
||||
|
||||
|
||||
def unbind_user(data: dict[str, Any]) -> dict:
|
||||
user_id = data.get('user_id')
|
||||
if not user_id:
|
||||
raise ValidationError('user_id is required')
|
||||
try:
|
||||
user_id = int(user_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('user_id must be integer')
|
||||
user = db.session.get(User, user_id)
|
||||
if not user:
|
||||
raise NotFoundError('User not found')
|
||||
user.wecom_userid = None
|
||||
user.wecom_unionid = None
|
||||
db.session.commit()
|
||||
return {'status': 'ok', 'message': 'WeCom account unbound'}
|
||||
|
||||
|
||||
def provision_user(data: dict[str, Any]) -> tuple[dict, int]:
|
||||
create_user_flag = bool(data.get('create_user', True))
|
||||
user_data = data.get('user') or {}
|
||||
bind_data = data.get('bind') or {}
|
||||
user_id = data.get('user_id')
|
||||
permission_updated = False
|
||||
wecom_userid = (bind_data.get('wecom_userid') or '').strip()
|
||||
wecom_unionid = (bind_data.get('wecom_unionid') or '').strip()
|
||||
if not wecom_userid:
|
||||
raise ValidationError('bind.wecom_userid is required')
|
||||
|
||||
if create_user_flag:
|
||||
username = (user_data.get('username') or '').strip()
|
||||
if not username:
|
||||
raise ValidationError('user.username is required when create_user=true')
|
||||
if db.session.query(User).filter_by(username=username).first():
|
||||
raise ValidationError('Username exists')
|
||||
email = (user_data.get('email') or '').strip() or None
|
||||
employee_id = (user_data.get('employee_id') or '').strip() or None
|
||||
phone_number = (user_data.get('phone_number') or '').strip() or None
|
||||
if email and db.session.query(User).filter_by(email=email).first():
|
||||
raise ValidationError('Email already exists')
|
||||
if employee_id and db.session.query(User).filter_by(employee_id=employee_id).first():
|
||||
raise ValidationError('Employee ID already exists')
|
||||
if phone_number and db.session.query(User).filter_by(phone_number=phone_number).first():
|
||||
raise ValidationError('Phone number already exists')
|
||||
user = User(
|
||||
username=username,
|
||||
email=email,
|
||||
department=user_data.get('department'),
|
||||
role=user_data.get('role', 'user'),
|
||||
status=user_data.get('status', 'active'),
|
||||
real_name=user_data.get('real_name'),
|
||||
employee_id=employee_id,
|
||||
phone_number=phone_number,
|
||||
)
|
||||
password = user_data.get('password')
|
||||
user.set_password(password or uuid.uuid4().hex)
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
binding_status = 'created'
|
||||
status_code = 201
|
||||
else:
|
||||
if user_id is None:
|
||||
user_id = user_data.get('id')
|
||||
if user_id is None:
|
||||
raise ValidationError('user_id is required when create_user=false')
|
||||
try:
|
||||
user_id = int(user_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('user_id must be integer')
|
||||
user = db.session.get(User, user_id)
|
||||
if not user:
|
||||
raise NotFoundError('User not found')
|
||||
binding_status = 'updated'
|
||||
status_code = 200
|
||||
|
||||
dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first()
|
||||
if dup:
|
||||
db.session.rollback()
|
||||
raise ValidationError(f'wecom_userid already bound to user {dup.username}')
|
||||
if wecom_unionid:
|
||||
dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first()
|
||||
if dup_union:
|
||||
db.session.rollback()
|
||||
raise ValidationError(f'wecom_unionid already bound to user {dup_union.username}')
|
||||
user.wecom_userid = wecom_userid
|
||||
if wecom_unionid:
|
||||
user.wecom_unionid = wecom_unionid
|
||||
|
||||
if 'agent_ids' in data:
|
||||
agent_ids = data.get('agent_ids', [])
|
||||
if not isinstance(agent_ids, list):
|
||||
db.session.rollback()
|
||||
raise ValidationError('agent_ids must be array')
|
||||
if agent_ids:
|
||||
try:
|
||||
unique_ids = sorted({int(i) for i in agent_ids})
|
||||
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):
|
||||
db.session.rollback()
|
||||
raise ValidationError('Some agent_ids are invalid')
|
||||
user.agents = agents
|
||||
else:
|
||||
user.agents = []
|
||||
permission_updated = True
|
||||
|
||||
try:
|
||||
db.session.commit()
|
||||
except IntegrityError:
|
||||
db.session.rollback()
|
||||
raise ValidationError('Provision failed due to data uniqueness conflict')
|
||||
|
||||
return (
|
||||
{
|
||||
'status': 'ok',
|
||||
'user_id': user.id,
|
||||
'binding': binding_status,
|
||||
'permission_updated': permission_updated,
|
||||
},
|
||||
status_code,
|
||||
)
|
||||
|
||||
|
||||
def list_login_audits(query_params: dict[str, str]) -> list[dict]:
|
||||
source = query_params.get('source')
|
||||
status = query_params.get('status')
|
||||
try:
|
||||
limit = max(1, min(int(query_params.get('limit', 100)), 500))
|
||||
except (TypeError, ValueError):
|
||||
limit = 100
|
||||
query = db.session.query(LoginAudit)
|
||||
if source:
|
||||
query = query.filter(LoginAudit.source == source)
|
||||
if status:
|
||||
query = query.filter(LoginAudit.status == status)
|
||||
rows = query.order_by(LoginAudit.created_at.desc()).limit(limit).all()
|
||||
return [
|
||||
{
|
||||
'id': r.id,
|
||||
'user_id': r.user_id,
|
||||
'username': r.username,
|
||||
'source': r.source,
|
||||
'status': r.status,
|
||||
'reason': r.reason,
|
||||
'error_code': r.error_code,
|
||||
'match_rules': r.match_rules,
|
||||
'match_operator': r.match_operator,
|
||||
'match_result': r.match_result,
|
||||
'wecom_userid': r.wecom_userid,
|
||||
'ip': r.ip,
|
||||
'user_agent': r.user_agent,
|
||||
'created_at': r.created_at.isoformat() if r.created_at else None,
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
def serialize_notify_settings() -> dict:
|
||||
return {
|
||||
'enabled': bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)),
|
||||
'base_url': current_app.config.get('WECOM_NOTIFY_BASE_URL') or '',
|
||||
'events': [x for x in str(current_app.config.get('WECOM_NOTIFY_EVENTS', '')).split(',') if x],
|
||||
}
|
||||
|
||||
|
||||
def update_notify_settings(data: dict[str, Any]) -> dict:
|
||||
updates = {}
|
||||
if 'enabled' in data:
|
||||
updates['WECOM_NOTIFY_ENABLED'] = bool(data.get('enabled'))
|
||||
if 'base_url' in data:
|
||||
updates['WECOM_NOTIFY_BASE_URL'] = str(data.get('base_url') or '').strip()
|
||||
if 'events' in data:
|
||||
events = data.get('events') or []
|
||||
if isinstance(events, list):
|
||||
updates['WECOM_NOTIFY_EVENTS'] = ','.join([str(x).strip() for x in events if str(x).strip()])
|
||||
for key, value in updates.items():
|
||||
current_app.config[key] = value
|
||||
persist_env_settings(updates)
|
||||
return {'status': 'ok', 'settings': serialize_notify_settings()}
|
||||
|
||||
|
||||
def serialize_system_settings() -> dict:
|
||||
return {
|
||||
'enabled': bool(current_app.config.get('WECOM_ENABLED', False)),
|
||||
'corp_id': current_app.config.get('WECOM_CORP_ID') or '',
|
||||
'agent_id': str(current_app.config.get('WECOM_AGENT_ID') or ''),
|
||||
'secret': current_app.config.get('WECOM_SECRET') or '',
|
||||
'redirect_uri': current_app.config.get('WECOM_REDIRECT_URI') or '',
|
||||
'auto_create_user': bool(current_app.config.get('WECOM_AUTO_CREATE_USER', True)),
|
||||
'match_rules': current_app.config.get('WECOM_MATCH_RULES') or 'employee_id,mobile',
|
||||
'match_operator': str(current_app.config.get('WECOM_MATCH_OPERATOR') or 'AND').upper(),
|
||||
'first_login_bind_mode': str(current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE') or 'match_rules').lower(),
|
||||
'first_login_input_fields': current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS') or 'employee_id,mobile,email',
|
||||
'employee_id_source': current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE') or 'userid',
|
||||
'mobile_normalize': bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True)),
|
||||
'callback_token': current_app.config.get('WECOM_CALLBACK_TOKEN') or '',
|
||||
'encoding_aes_key': current_app.config.get('WECOM_ENCODING_AES_KEY') or '',
|
||||
'callback_url': current_app.config.get('WECOM_CALLBACK_URL') or '',
|
||||
'homepage_url': current_app.config.get('WECOM_HOMEPAGE_URL') or '',
|
||||
'trusted_domain': current_app.config.get('WECOM_TRUSTED_DOMAIN') or '',
|
||||
'public_base_url': current_app.config.get('WECOM_PUBLIC_BASE_URL') or '',
|
||||
}
|
||||
|
||||
|
||||
def update_system_settings(data: dict[str, Any]) -> dict:
|
||||
bool_keys = {
|
||||
'enabled': 'WECOM_ENABLED',
|
||||
'auto_create_user': 'WECOM_AUTO_CREATE_USER',
|
||||
'mobile_normalize': 'WECOM_MOBILE_NORMALIZE',
|
||||
}
|
||||
str_keys = {
|
||||
'corp_id': 'WECOM_CORP_ID',
|
||||
'agent_id': 'WECOM_AGENT_ID',
|
||||
'secret': 'WECOM_SECRET',
|
||||
'redirect_uri': 'WECOM_REDIRECT_URI',
|
||||
'match_rules': 'WECOM_MATCH_RULES',
|
||||
'match_operator': 'WECOM_MATCH_OPERATOR',
|
||||
'first_login_bind_mode': 'WECOM_FIRST_LOGIN_BIND_MODE',
|
||||
'first_login_input_fields': 'WECOM_FIRST_LOGIN_INPUT_FIELDS',
|
||||
'employee_id_source': 'WECOM_EMPLOYEE_ID_SOURCE',
|
||||
'callback_token': 'WECOM_CALLBACK_TOKEN',
|
||||
'encoding_aes_key': 'WECOM_ENCODING_AES_KEY',
|
||||
'callback_url': 'WECOM_CALLBACK_URL',
|
||||
'homepage_url': 'WECOM_HOMEPAGE_URL',
|
||||
'trusted_domain': 'WECOM_TRUSTED_DOMAIN',
|
||||
'public_base_url': 'WECOM_PUBLIC_BASE_URL',
|
||||
}
|
||||
updates = {}
|
||||
for req_key, cfg_key in bool_keys.items():
|
||||
if req_key in data:
|
||||
updates[cfg_key] = bool(data.get(req_key))
|
||||
for req_key, cfg_key in str_keys.items():
|
||||
if req_key in data:
|
||||
updates[cfg_key] = str(data.get(req_key) or '').strip()
|
||||
for key, value in updates.items():
|
||||
current_app.config[key] = value
|
||||
if current_app.config.get('WECOM_MATCH_OPERATOR') not in {'AND', 'OR'}:
|
||||
current_app.config['WECOM_MATCH_OPERATOR'] = 'AND'
|
||||
updates['WECOM_MATCH_OPERATOR'] = 'AND'
|
||||
if current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE') not in {'match_rules', 'input_verify'}:
|
||||
current_app.config['WECOM_FIRST_LOGIN_BIND_MODE'] = 'match_rules'
|
||||
updates['WECOM_FIRST_LOGIN_BIND_MODE'] = 'match_rules'
|
||||
persist_env_settings(updates)
|
||||
return {'status': 'ok', 'settings': serialize_system_settings()}
|
||||
|
||||
|
||||
def integration_manifest(*, host_url: str, host: str) -> dict:
|
||||
settings = serialize_system_settings()
|
||||
public_base = (settings.get('public_base_url') or '').rstrip('/')
|
||||
if not public_base:
|
||||
for key in ('WECOM_PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
|
||||
configured = current_app.config.get(key) or ''
|
||||
if configured:
|
||||
public_base = configured.rstrip('/')
|
||||
break
|
||||
if not public_base:
|
||||
public_base = host_url.rstrip('/')
|
||||
callback_url = settings.get('callback_url') or f'{public_base}/api/user/wecom/callback'
|
||||
homepage_url = settings.get('homepage_url') or f'{public_base}/workspace'
|
||||
trusted_domain = settings.get('trusted_domain') or host.split(':')[0]
|
||||
return {
|
||||
'public_base_url': public_base,
|
||||
'callback_url': callback_url,
|
||||
'callback_token': settings.get('callback_token') or '',
|
||||
'encoding_aes_key': settings.get('encoding_aes_key') or '',
|
||||
'oauth_redirect_uri': settings.get('redirect_uri') or homepage_url,
|
||||
'homepage_url': homepage_url,
|
||||
'trusted_domain': trusted_domain,
|
||||
'authorize_api': f'{public_base}/api/user/wecom/authorize-url',
|
||||
'login_api': f'{public_base}/api/user/wecom/login',
|
||||
}
|
||||
|
||||
|
||||
def notify_metrics() -> dict:
|
||||
now = datetime.utcnow()
|
||||
from_time = now - timedelta(days=30)
|
||||
total = db.session.query(func.count(WecomNotifyAudit.id)).filter(WecomNotifyAudit.created_at >= from_time).scalar() or 0
|
||||
sent = db.session.query(func.count(WecomNotifyAudit.id)).filter(
|
||||
WecomNotifyAudit.created_at >= from_time,
|
||||
WecomNotifyAudit.status == 'sent',
|
||||
).scalar() or 0
|
||||
opened_24h = db.session.query(func.count(WecomNotifyAudit.id)).filter(
|
||||
WecomNotifyAudit.created_at >= from_time,
|
||||
WecomNotifyAudit.opened_at.isnot(None),
|
||||
).scalar() or 0
|
||||
by_event_rows = (
|
||||
db.session.query(WecomNotifyAudit.event_type, WecomNotifyAudit.status, func.count(WecomNotifyAudit.id))
|
||||
.filter(WecomNotifyAudit.created_at >= from_time)
|
||||
.group_by(WecomNotifyAudit.event_type, WecomNotifyAudit.status)
|
||||
.all()
|
||||
)
|
||||
by_event = {}
|
||||
for event_type, status, cnt in by_event_rows:
|
||||
if event_type not in by_event:
|
||||
by_event[event_type] = {'sent': 0, 'failed': 0}
|
||||
by_event[event_type][status] = int(cnt)
|
||||
return {
|
||||
'window_days': 30,
|
||||
'total': int(total),
|
||||
'sent': int(sent),
|
||||
'failed': int(total - sent),
|
||||
'send_success_rate': round(sent / total * 100, 2) if total else 0,
|
||||
'opened_24h': int(opened_24h),
|
||||
'opened_24h_rate': round(opened_24h / sent * 100, 2) if sent else 0,
|
||||
'by_event': by_event,
|
||||
}
|
||||
|
||||
|
||||
def binding_stats() -> dict:
|
||||
total_active = db.session.query(func.count(User.id)).filter(User.status == 'active').scalar() or 0
|
||||
bound = (
|
||||
db.session.query(func.count(User.id))
|
||||
.filter(User.status == 'active', User.wecom_userid.isnot(None), User.wecom_userid != '')
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
total_active = int(total_active)
|
||||
bound = int(bound)
|
||||
return {
|
||||
'total_active': total_active,
|
||||
'bound': bound,
|
||||
'unbound': max(total_active - bound, 0),
|
||||
'bound_rate': round(bound / total_active * 100, 2) if total_active else 0,
|
||||
}
|
||||
|
||||
|
||||
def sync_userids(*, apply: bool) -> dict:
|
||||
try:
|
||||
summary = sync_wecom_userids_from_oa(apply=apply)
|
||||
current_app.logger.info(
|
||||
'[wecom_sync] oa apply=%s updated=%s would_update=%s conflicts=%s local_matched=%s',
|
||||
apply,
|
||||
summary.get('updated'),
|
||||
summary.get('would_update'),
|
||||
len(summary.get('conflicts') or []),
|
||||
summary.get('local_matched'),
|
||||
)
|
||||
return summary
|
||||
except RuntimeError as exc:
|
||||
message = str(exc)
|
||||
if 'conflicts detected' in message.lower():
|
||||
raise ConflictError(message, details={'error_code': 'WECOM_SYNC_CONFLICTS'})
|
||||
if '未找到可用的 SQL Server ODBC 驱动' in message or 'pyodbc' in message.lower():
|
||||
raise AppError(
|
||||
code='SYSTEM.SERVICE_UNAVAILABLE',
|
||||
message='OA SQL Server driver is not available on this server',
|
||||
http_status=503,
|
||||
details={'error_code': 'OA_SQLSERVER_DRIVER_MISSING', 'technical': message[:300]},
|
||||
)
|
||||
raise AppError(
|
||||
code='SYSTEM.HTTP_ERROR',
|
||||
message='OA SQL Server sync failed. Check OA_SQLSERVER_* env and network access.',
|
||||
http_status=502,
|
||||
details={'error_code': 'OA_SQLSERVER_SYNC_FAILED', 'technical': message[:300]},
|
||||
)
|
||||
except Exception as exc:
|
||||
current_app.logger.exception('[wecom_sync] oa unexpected failure: %s', exc)
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500)
|
||||
@@ -2,5 +2,8 @@
|
||||
backend/app/services/auth/__init__.py
|
||||
|
||||
用途:认证域业务(Casdoor OIDC、企微 OAuth)。
|
||||
逻辑:Wave 3 从 api/user/_legacy auth 相关路由抽取。
|
||||
逻辑:Wave 3 从 api/user 抽取;api/user 保留薄 re-export 兼容旧测试。
|
||||
"""
|
||||
from . import casdoor_service, wecom_auth_service
|
||||
|
||||
__all__ = ['casdoor_service', 'wecom_auth_service']
|
||||
@@ -1,5 +1,373 @@
|
||||
"""
|
||||
backend/app/services/auth/casdoor_service.py
|
||||
|
||||
用途:Casdoor OIDC 登录、token 交换、用户同步业务逻辑。
|
||||
用途:Casdoor IdP 用户同步与 OAuth 错误映射(管理端创建/改密、用户域登录共用)。
|
||||
依赖:flask.current_app、requests、app.core.errors。
|
||||
逻辑:由 services/admin/user_service、api/user 登录路由调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from app.core.errors import AppError, ConflictError, ValidationError
|
||||
from app.models import User
|
||||
|
||||
|
||||
def clean_str(value) -> str | None:
|
||||
"""Trim 字符串;空串返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, str):
|
||||
value = value.strip()
|
||||
return value or None
|
||||
return str(value).strip() or None
|
||||
|
||||
|
||||
def is_casdoor_configured() -> bool:
|
||||
"""Casdoor 基础配置是否齐全。"""
|
||||
if not clean_str(current_app.config.get('CASDOOR_ORGANIZATION')):
|
||||
return False
|
||||
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
|
||||
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
|
||||
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
|
||||
return bool(base and client_id and client_secret)
|
||||
|
||||
|
||||
def casdoor_user_owner() -> str:
|
||||
"""返回 Casdoor organization owner。"""
|
||||
owner = clean_str(current_app.config.get('CASDOOR_ORGANIZATION'))
|
||||
if not owner:
|
||||
raise RuntimeError('CASDOOR_ORGANIZATION is not configured')
|
||||
return owner
|
||||
|
||||
|
||||
def extract_error_payload(source) -> dict:
|
||||
"""从 Casdoor 响应或异常文本解析 JSON 错误体。"""
|
||||
if isinstance(source, dict):
|
||||
return source
|
||||
text = str(source or '')
|
||||
match = re.search(r'\{.*\}', text, re.DOTALL)
|
||||
if match:
|
||||
try:
|
||||
parsed = ast.literal_eval(match.group(0))
|
||||
if isinstance(parsed, dict):
|
||||
return parsed
|
||||
except (SyntaxError, ValueError):
|
||||
pass
|
||||
try:
|
||||
parsed = json.loads(text)
|
||||
if isinstance(parsed, dict):
|
||||
return parsed
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
return {}
|
||||
|
||||
|
||||
def is_user_exists_error(message: str) -> bool:
|
||||
lowered = (message or '').lower()
|
||||
return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered
|
||||
|
||||
|
||||
def is_password_error(message: str) -> bool:
|
||||
lowered = (message or '').lower()
|
||||
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
|
||||
|
||||
|
||||
def is_user_missing_error(message: str) -> bool:
|
||||
lowered = (message or '').lower()
|
||||
return (
|
||||
"doesn't exist" in lowered
|
||||
or 'does not exist' in lowered
|
||||
or 'user not found' in lowered
|
||||
or 'no such user' in lowered
|
||||
)
|
||||
|
||||
|
||||
def raise_user_not_in_idp(source=None) -> None:
|
||||
data = extract_error_payload(source)
|
||||
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
|
||||
raise AppError(
|
||||
code='CASDOOR_USER_NOT_IN_IDP',
|
||||
message='Your account has not been registered in the authentication system. Please contact the administrator.',
|
||||
http_status=409,
|
||||
details={'technical': msg_text or str(source or '')[:300]},
|
||||
)
|
||||
|
||||
|
||||
def raise_add_user_error(source) -> None:
|
||||
"""将 Casdoor add-user 失败映射为稳定业务错误码。"""
|
||||
data = extract_error_payload(source)
|
||||
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
|
||||
lowered = (msg_text or str(source or '')).lower()
|
||||
if is_user_exists_error(lowered):
|
||||
raise ConflictError(
|
||||
'Username already exists in Casdoor',
|
||||
code='USER.USERNAME_EXISTS',
|
||||
details={'field': 'username', 'technical': msg_text},
|
||||
)
|
||||
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
|
||||
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='Password does not meet security requirements', http_status=400)
|
||||
raise AppError(
|
||||
code='CASDOOR_ADD_USER_FAILED',
|
||||
message='Failed to create user in authentication system. Please try again or contact the administrator.',
|
||||
http_status=502,
|
||||
details={'technical': msg_text or str(source or '')[:300]},
|
||||
)
|
||||
|
||||
|
||||
def raise_update_user_error(source) -> None:
|
||||
"""将 Casdoor update-user 失败映射为稳定业务错误码。"""
|
||||
data = extract_error_payload(source)
|
||||
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
|
||||
lowered = (msg_text or str(source or '')).lower()
|
||||
if is_user_missing_error(lowered):
|
||||
raise_user_not_in_idp(source)
|
||||
if is_user_exists_error(lowered) or ('email' in lowered and 'already' in lowered):
|
||||
raise ConflictError(
|
||||
'Email already exists in Casdoor',
|
||||
code='USER.EMAIL_EXISTS',
|
||||
details={'field': 'email', 'technical': msg_text},
|
||||
)
|
||||
raise AppError(
|
||||
code='CASDOOR_UPDATE_USER_FAILED',
|
||||
message='Failed to update user in authentication system. Please try again or contact the administrator.',
|
||||
http_status=502,
|
||||
details={'technical': msg_text or str(source or '')[:300]},
|
||||
)
|
||||
|
||||
|
||||
def raise_set_password_error(source) -> None:
|
||||
"""将 Casdoor set-password 失败映射为稳定业务错误码。"""
|
||||
data = extract_error_payload(source)
|
||||
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
|
||||
lowered = (msg_text or str(source or '')).lower()
|
||||
if is_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
|
||||
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect current password', http_status=401)
|
||||
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
|
||||
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400)
|
||||
if is_user_missing_error(lowered):
|
||||
raise_user_not_in_idp(source)
|
||||
raise AppError(
|
||||
code='CASDOOR_SET_PASSWORD_FAILED',
|
||||
message='Failed to change password. Please try again or contact the administrator.',
|
||||
http_status=502,
|
||||
details={'technical': msg_text or str(source)[:300]},
|
||||
)
|
||||
|
||||
|
||||
def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
|
||||
"""Map Casdoor OAuth/API failures to stable business error codes."""
|
||||
data = extract_error_payload(source)
|
||||
raw = str(source or '')
|
||||
oauth_error = clean_str(data.get('error')).lower()
|
||||
if not oauth_error and 'invalid_grant' in raw.lower():
|
||||
oauth_error = 'invalid_grant'
|
||||
if not oauth_error and 'invalid_client' in raw.lower():
|
||||
oauth_error = 'invalid_client'
|
||||
if oauth_error == 'invalid_grant' or is_password_error(raw):
|
||||
if context in ('password', 'verify'):
|
||||
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401)
|
||||
raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401)
|
||||
if oauth_error in ('invalid_client', 'unauthorized_client'):
|
||||
raise AppError(
|
||||
code='CASDOOR_CONFIG_ERROR',
|
||||
message='Authentication service is misconfigured. Please contact the administrator.',
|
||||
http_status=503,
|
||||
details={'casdoor_error': oauth_error},
|
||||
)
|
||||
if oauth_error == 'access_denied':
|
||||
raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403)
|
||||
if 'token endpoint missing' in raw.lower() or 'casdoor_base_url is not configured' in raw.lower() or 'casdoor is not configured' in raw.lower():
|
||||
raise AppError(
|
||||
code='CASDOOR_CONFIG_ERROR',
|
||||
message='Authentication service is not configured. Please contact the administrator.',
|
||||
http_status=503,
|
||||
)
|
||||
if 'invalid or expired casdoor state' in raw.lower():
|
||||
raise ValidationError('Invalid or expired Casdoor state')
|
||||
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s raw=%s', context, data, raw[:500])
|
||||
raise AppError(
|
||||
code='CASDOOR_AUTH_FAILED',
|
||||
message='Authentication failed, please try again',
|
||||
http_status=status_code,
|
||||
details={'casdoor_error': oauth_error or None, 'technical': raw[:300]},
|
||||
)
|
||||
|
||||
|
||||
def build_user_profile_payload(
|
||||
*,
|
||||
username: str,
|
||||
email: str,
|
||||
real_name=None,
|
||||
phone_number=None,
|
||||
status='active',
|
||||
department=None,
|
||||
) -> dict:
|
||||
"""组装 Casdoor 用户资料字段(不含 password)。"""
|
||||
display_name = clean_str(real_name) or username
|
||||
payload = {
|
||||
'owner': casdoor_user_owner(),
|
||||
'name': username,
|
||||
'email': email or '',
|
||||
'displayName': display_name,
|
||||
'realName': clean_str(real_name) or '',
|
||||
'phone': clean_str(phone_number) or '',
|
||||
'isForbidden': clean_str(status) not in (None, 'active'),
|
||||
}
|
||||
department_value = clean_str(department)
|
||||
if department_value:
|
||||
payload['affiliation'] = department_value
|
||||
return payload
|
||||
|
||||
|
||||
def build_user_payload(
|
||||
*,
|
||||
username: str,
|
||||
password: str,
|
||||
email: str,
|
||||
real_name=None,
|
||||
phone_number=None,
|
||||
status='active',
|
||||
department=None,
|
||||
) -> dict:
|
||||
"""组装 Casdoor add-user 请求体。"""
|
||||
payload = build_user_profile_payload(
|
||||
username=username,
|
||||
email=email,
|
||||
real_name=real_name,
|
||||
phone_number=phone_number,
|
||||
status=status,
|
||||
department=department,
|
||||
)
|
||||
payload['password'] = password
|
||||
return payload
|
||||
|
||||
|
||||
def casdoor_add_user(user_payload: dict) -> None:
|
||||
"""调用 Casdoor /api/add-user 创建 IdP 用户。"""
|
||||
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
|
||||
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
|
||||
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
|
||||
if not base or not client_id or not client_secret:
|
||||
raise RuntimeError('Casdoor is not configured')
|
||||
url = f'{base}/api/add-user'
|
||||
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
|
||||
try:
|
||||
data = resp.json() or {}
|
||||
except ValueError:
|
||||
raise RuntimeError(f'Casdoor add-user failed: HTTP {resp.status_code} {resp.text[:200]}')
|
||||
if data.get('status') != 'ok':
|
||||
raise_add_user_error(data)
|
||||
|
||||
|
||||
def casdoor_update_user(user_payload: dict) -> None:
|
||||
"""调用 Casdoor /api/update-user 更新 IdP 用户资料。"""
|
||||
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
|
||||
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
|
||||
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
|
||||
if not base or not client_id or not client_secret:
|
||||
raise RuntimeError('Casdoor is not configured')
|
||||
url = f'{base}/api/update-user'
|
||||
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
|
||||
try:
|
||||
data = resp.json() or {}
|
||||
except ValueError:
|
||||
raise RuntimeError(f'Casdoor update-user failed: HTTP {resp.status_code} {resp.text[:200]}')
|
||||
if data.get('status') != 'ok':
|
||||
raise_update_user_error(data)
|
||||
|
||||
|
||||
def casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str) -> None:
|
||||
"""调用 Casdoor /api/set-password。"""
|
||||
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
|
||||
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
|
||||
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
|
||||
if not base or not client_id or not client_secret:
|
||||
raise RuntimeError('Casdoor is not configured')
|
||||
url = f'{base}/api/set-password'
|
||||
resp = requests.post(
|
||||
url,
|
||||
files={
|
||||
'userOwner': (None, user_owner),
|
||||
'userName': (None, user_name),
|
||||
'oldPassword': (None, old_password),
|
||||
'newPassword': (None, new_password),
|
||||
},
|
||||
auth=(client_id, client_secret),
|
||||
timeout=8,
|
||||
)
|
||||
try:
|
||||
data = resp.json() or {}
|
||||
except ValueError:
|
||||
raise RuntimeError(f'Casdoor set-password failed: HTTP {resp.status_code} {resp.text[:200]}')
|
||||
if data.get('status') != 'ok':
|
||||
raise_set_password_error(data)
|
||||
|
||||
|
||||
def sync_create_user(
|
||||
*,
|
||||
username: str,
|
||||
password: str,
|
||||
email: str,
|
||||
real_name=None,
|
||||
phone_number=None,
|
||||
status='active',
|
||||
department=None,
|
||||
) -> None:
|
||||
"""管理端创建用户时同步至 Casdoor。"""
|
||||
if not is_casdoor_configured():
|
||||
return
|
||||
payload = build_user_payload(
|
||||
username=username,
|
||||
password=password,
|
||||
email=email,
|
||||
real_name=real_name,
|
||||
phone_number=phone_number,
|
||||
status=status,
|
||||
department=department,
|
||||
)
|
||||
casdoor_add_user(payload)
|
||||
|
||||
|
||||
def sync_admin_set_password(user: User, new_password: str) -> None:
|
||||
"""管理端重设密码时同步 Casdoor(无旧密码)。"""
|
||||
if not is_casdoor_configured():
|
||||
return
|
||||
user_owner = casdoor_user_owner()
|
||||
try:
|
||||
casdoor_set_password(user_owner, user.username, '', new_password)
|
||||
except RuntimeError as exc:
|
||||
if is_user_missing_error(str(exc)):
|
||||
raise_user_not_in_idp(exc)
|
||||
raise_set_password_error(exc)
|
||||
|
||||
|
||||
def sync_update_user(user: User, *, new_password: str | None = None) -> None:
|
||||
"""管理端编辑用户时同步 Casdoor:仅改密;IdP 无账号则 add-user 补建。"""
|
||||
if not is_casdoor_configured() or not new_password:
|
||||
return
|
||||
|
||||
def _provision_missing_user_in_casdoor():
|
||||
sync_create_user(
|
||||
username=user.username,
|
||||
password=new_password,
|
||||
email=user.email,
|
||||
real_name=user.real_name,
|
||||
phone_number=user.phone_number,
|
||||
status=user.status,
|
||||
department=user.department,
|
||||
)
|
||||
|
||||
try:
|
||||
sync_admin_set_password(user, new_password)
|
||||
except AppError as exc:
|
||||
if exc.code == 'CASDOOR_USER_NOT_IN_IDP':
|
||||
_provision_missing_user_in_casdoor()
|
||||
return
|
||||
raise
|
||||
@@ -1,5 +1,235 @@
|
||||
"""
|
||||
backend/app/services/auth/wecom_auth_service.py
|
||||
|
||||
用途:企业微信 OAuth、绑定、解绑业务逻辑。
|
||||
用途:企业微信 OAuth 身份解析、匹配规则与 access_token 缓存。
|
||||
依赖:flask.current_app、requests、models.User。
|
||||
逻辑:由 api/user 企微登录路由、services/admin/wecom_admin_service 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
from sqlalchemy import and_, or_
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
|
||||
ACCESS_TOKEN_CACHE: dict = {'token': None, 'expires_at': None}
|
||||
STATE_CACHE: dict = {}
|
||||
BIND_SESSION_CACHE: dict = {}
|
||||
|
||||
ALLOWED_MATCH_FIELDS = {'employee_id', 'mobile', 'email'}
|
||||
|
||||
|
||||
def clean_str(value) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, str):
|
||||
value = value.strip()
|
||||
return value or None
|
||||
return str(value).strip() or None
|
||||
|
||||
|
||||
def parse_field_list(raw_value, default_fields: list[str]) -> list[str]:
|
||||
"""解析逗号分隔的企微匹配/输入字段列表。"""
|
||||
if isinstance(raw_value, str):
|
||||
pieces = [item.strip().lower() for item in raw_value.split(',')]
|
||||
elif isinstance(raw_value, (list, tuple)):
|
||||
pieces = [str(item).strip().lower() for item in raw_value]
|
||||
else:
|
||||
pieces = []
|
||||
result = []
|
||||
for piece in pieces:
|
||||
if piece in ALLOWED_MATCH_FIELDS and piece not in result:
|
||||
result.append(piece)
|
||||
return result or list(default_fields)
|
||||
|
||||
|
||||
def get_config_missing_fields() -> list[str]:
|
||||
"""返回缺失的企微登录配置键名。"""
|
||||
missing = []
|
||||
if not current_app.config.get('WECOM_ENABLED'):
|
||||
missing.append('WECOM_ENABLED')
|
||||
if not clean_str(current_app.config.get('WECOM_CORP_ID')):
|
||||
missing.append('WECOM_CORP_ID')
|
||||
if not clean_str(current_app.config.get('WECOM_AGENT_ID')):
|
||||
missing.append('WECOM_AGENT_ID')
|
||||
if not clean_str(current_app.config.get('WECOM_SECRET')):
|
||||
missing.append('WECOM_SECRET')
|
||||
return missing
|
||||
|
||||
|
||||
def is_configured() -> bool:
|
||||
return len(get_config_missing_fields()) == 0
|
||||
|
||||
|
||||
def get_access_token() -> str:
|
||||
"""获取企微 access_token(带进程内缓存)。"""
|
||||
now = datetime.utcnow()
|
||||
token = ACCESS_TOKEN_CACHE.get('token')
|
||||
expires_at = ACCESS_TOKEN_CACHE.get('expires_at')
|
||||
if token and expires_at and (now < expires_at):
|
||||
return token
|
||||
corp_id = current_app.config.get('WECOM_CORP_ID')
|
||||
secret = current_app.config.get('WECOM_SECRET')
|
||||
resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/gettoken',
|
||||
params={'corpid': corp_id, 'corpsecret': secret},
|
||||
timeout=8,
|
||||
)
|
||||
data = resp.json()
|
||||
if data.get('errcode') != 0 or not data.get('access_token'):
|
||||
raise RuntimeError(f'Failed to fetch WeCom token: {data}')
|
||||
ACCESS_TOKEN_CACHE['token'] = data['access_token']
|
||||
ACCESS_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60))
|
||||
return data['access_token']
|
||||
|
||||
|
||||
def normalize_mobile(mobile: str) -> str | None:
|
||||
mobile = clean_str(mobile)
|
||||
if not mobile:
|
||||
return None
|
||||
digits = re.sub(r'\D', '', mobile)
|
||||
if not digits:
|
||||
return mobile
|
||||
if digits.startswith('0086'):
|
||||
digits = digits[4:]
|
||||
elif digits.startswith('86') and len(digits) > 11:
|
||||
digits = digits[2:]
|
||||
return digits
|
||||
|
||||
|
||||
def extract_extattr_value(wecom_user: dict, key: str) -> str | None:
|
||||
extattr = wecom_user.get('extattr') or {}
|
||||
attrs = extattr.get('attrs') if isinstance(extattr, dict) else None
|
||||
if not isinstance(attrs, list):
|
||||
return None
|
||||
for attr in attrs:
|
||||
if not isinstance(attr, dict):
|
||||
continue
|
||||
if clean_str(attr.get('name')) != key:
|
||||
continue
|
||||
raw = attr.get('value')
|
||||
if isinstance(raw, dict):
|
||||
raw = raw.get('text') or raw.get('web') or raw.get('value')
|
||||
return clean_str(raw)
|
||||
return None
|
||||
|
||||
|
||||
def get_match_config() -> tuple[list[str], str]:
|
||||
raw_rules = current_app.config.get('WECOM_MATCH_RULES', 'employee_id,mobile')
|
||||
rules = parse_field_list(raw_rules, ['employee_id', 'mobile'])
|
||||
operator = str(current_app.config.get('WECOM_MATCH_OPERATOR', 'AND')).upper()
|
||||
if operator not in {'AND', 'OR'}:
|
||||
operator = 'AND'
|
||||
return rules, operator
|
||||
|
||||
|
||||
def get_first_login_bind_mode() -> str:
|
||||
mode = clean_str(current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE')) or 'match_rules'
|
||||
mode = mode.lower()
|
||||
if mode not in {'match_rules', 'input_verify'}:
|
||||
mode = 'match_rules'
|
||||
return mode
|
||||
|
||||
|
||||
def get_first_login_input_fields() -> list[str]:
|
||||
raw_fields = current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS', 'employee_id,mobile,email')
|
||||
return parse_field_list(raw_fields, ['employee_id', 'mobile', 'email'])
|
||||
|
||||
|
||||
def extract_identity(wecom_user: dict) -> dict:
|
||||
"""从企微 user/get 响应提取标准化身份字段。"""
|
||||
userid = clean_str(wecom_user.get('userid'))
|
||||
unionid = clean_str(wecom_user.get('unionid'))
|
||||
email = clean_str(wecom_user.get('email'))
|
||||
mobile_raw = clean_str(wecom_user.get('mobile'))
|
||||
normalize_flag = bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True))
|
||||
mobile = normalize_mobile(mobile_raw) if normalize_flag else mobile_raw
|
||||
employee_id_source = clean_str(current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE')) or 'userid'
|
||||
if employee_id_source == 'userid':
|
||||
employee_id = userid
|
||||
elif employee_id_source.startswith('extattr:'):
|
||||
employee_id = extract_extattr_value(wecom_user, employee_id_source.split(':', 1)[1])
|
||||
else:
|
||||
employee_id = clean_str(wecom_user.get(employee_id_source))
|
||||
return {
|
||||
'wecom_userid': userid,
|
||||
'wecom_unionid': unionid,
|
||||
'name': clean_str(wecom_user.get('name')) or userid or 'wecom_user',
|
||||
'email': email,
|
||||
'mobile': mobile,
|
||||
'mobile_raw': mobile_raw,
|
||||
'employee_id': employee_id,
|
||||
}
|
||||
|
||||
|
||||
def _mobile_candidates(identity: dict) -> list[str]:
|
||||
values = []
|
||||
for item in [identity.get('mobile'), identity.get('mobile_raw')]:
|
||||
item = clean_str(item)
|
||||
if item and item not in values:
|
||||
values.append(item)
|
||||
return values
|
||||
|
||||
|
||||
def find_users_by_input_field(field: str, value):
|
||||
field = clean_str(field)
|
||||
if field not in ALLOWED_MATCH_FIELDS:
|
||||
return [], 'invalid_field'
|
||||
if field == 'employee_id':
|
||||
needle = clean_str(value)
|
||||
if not needle:
|
||||
return [], 'employee_id'
|
||||
return db.session.query(User).filter(User.employee_id == needle).all(), None
|
||||
if field == 'email':
|
||||
needle = clean_str(value)
|
||||
if not needle:
|
||||
return [], 'email'
|
||||
return db.session.query(User).filter(User.email == needle).all(), None
|
||||
if field == 'mobile':
|
||||
raw_mobile = clean_str(value)
|
||||
normalized_mobile = normalize_mobile(raw_mobile)
|
||||
candidates = []
|
||||
for item in [normalized_mobile, raw_mobile]:
|
||||
item = clean_str(item)
|
||||
if item and item not in candidates:
|
||||
candidates.append(item)
|
||||
if not candidates:
|
||||
return [], 'mobile'
|
||||
return db.session.query(User).filter(User.phone_number.in_(candidates)).all(), None
|
||||
return [], 'invalid_field'
|
||||
|
||||
|
||||
def find_users_by_match_rules(identity: dict, rules: list, operator: str) -> tuple[list[User], list[str]]:
|
||||
filters = []
|
||||
missing = []
|
||||
for rule in rules:
|
||||
if rule == 'employee_id':
|
||||
employee_id = clean_str(identity.get('employee_id'))
|
||||
if not employee_id:
|
||||
missing.append('employee_id')
|
||||
else:
|
||||
filters.append(User.employee_id == employee_id)
|
||||
elif rule == 'mobile':
|
||||
candidates = _mobile_candidates(identity)
|
||||
if not candidates:
|
||||
missing.append('mobile')
|
||||
else:
|
||||
filters.append(User.phone_number.in_(candidates))
|
||||
elif rule == 'email':
|
||||
email = clean_str(identity.get('email'))
|
||||
if not email:
|
||||
missing.append('email')
|
||||
else:
|
||||
filters.append(User.email == email)
|
||||
if missing:
|
||||
return [], missing
|
||||
if not filters:
|
||||
return [], ['match_rules']
|
||||
clause = and_(*filters) if operator == 'AND' else or_(*filters)
|
||||
users = db.session.query(User).filter(clause).all()
|
||||
return users, []
|
||||
@@ -3,7 +3,7 @@ backend/app/services/hot_faq_aggregator.py
|
||||
|
||||
用途:从 ChatLog 离线聚合热点 FAQ 候选,写入 PostgreSQL 候选表(不含在线命中)。
|
||||
依赖:ChatLog、Feedback、QuickQuestion、faq_text_utils、hot_faq_candidate_store。
|
||||
逻辑:CLI `flask faq-aggregate-hot` 与管理端「刷新」调用 aggregate_hot_faq_candidates。
|
||||
逻辑:管理端「刷新聚合」调用 aggregate_hot_faq_candidates。
|
||||
|
||||
## 热点选取规则(HOT_FAQ_SELECTION_RULES)
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str
|
||||
|
||||
def run_faq_hot_aggregate_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""
|
||||
执行 FAQ 热点离线聚合(等同 flask faq-aggregate-hot,非 dry-run)。
|
||||
执行 FAQ 热点离线聚合(非 dry-run)。
|
||||
核心逻辑:委托 HotFaqAggregator;可选 dify_agent_id 限定 Agent。
|
||||
@param task - 排程任务;dify_agent_id 可选作 agent_id 过滤
|
||||
@param run - 当前执行批次(未写入 run 字段,由 scheduler_service 汇总)
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""
|
||||
backend/app/services/schedule/import_service.py
|
||||
|
||||
用途:排程任务 JSON 批量导入(upsert by schedule_no)。
|
||||
依赖:models、scheduler_service、sql_config。
|
||||
逻辑:由 api/schedule/tasks.py import 路由调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ScheduleTask
|
||||
from app.services.schedule.scheduler_service import create_task, update_task
|
||||
from app.services.schedule.sql_config import upsert_schedule_task_config
|
||||
|
||||
|
||||
def import_schedules_from_payload(schedules: list[Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""
|
||||
批量导入排程 JSON。
|
||||
Args:
|
||||
schedules: 导出文件中的 schedules 数组。
|
||||
actor_id: 当前管理员 user id。
|
||||
Returns:
|
||||
ok、imported、skipped、errors(最多 20 条)。
|
||||
Raises:
|
||||
ValidationError: schedules 非 list。
|
||||
"""
|
||||
if not isinstance(schedules, list):
|
||||
raise ValidationError('Invalid import file: schedules missing')
|
||||
|
||||
imported = 0
|
||||
skipped = 0
|
||||
errors: list[str] = []
|
||||
for item in schedules:
|
||||
if not isinstance(item, dict):
|
||||
skipped += 1
|
||||
continue
|
||||
try:
|
||||
name = str(item.get('name') or '').strip()
|
||||
cron_expr = str(item.get('cron_expr') or '').strip()
|
||||
owner_user_id = int(item.get('owner_user_id'))
|
||||
if not name or not cron_expr:
|
||||
raise ValueError('name or cron_expr missing')
|
||||
existing = None
|
||||
schedule_no = str(item.get('schedule_no') or '').strip()
|
||||
if schedule_no:
|
||||
existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first()
|
||||
task_payload = {
|
||||
'name': name,
|
||||
'schedule_type': str(item.get('schedule_type') or 'platform_app'),
|
||||
'owner_user_id': owner_user_id,
|
||||
'cron_expr': cron_expr,
|
||||
'schedule_timezone': item.get('schedule_timezone'),
|
||||
'wait_seconds': int(item.get('wait_seconds') or 0),
|
||||
'dify_agent_id': item.get('dify_agent_id'),
|
||||
'platform_api_path': item.get('platform_api_path'),
|
||||
'notify_user_ids_json': item.get('notify_user_ids_json')
|
||||
if isinstance(item.get('notify_user_ids_json'), list)
|
||||
else [],
|
||||
'notify_enabled': bool(item.get('notify_enabled', True)),
|
||||
'enabled': bool(item.get('enabled', True)),
|
||||
'data_source_type': str(item.get('data_source_type') or 'database'),
|
||||
'kb_sync_enabled': bool(item.get('kb_sync_enabled', False)),
|
||||
'kb_group_id': item.get('kb_group_id'),
|
||||
}
|
||||
cfg = item.get('config') if isinstance(item.get('config'), dict) else None
|
||||
if existing:
|
||||
update_task(existing, payload=task_payload, actor_id=actor_id)
|
||||
existing.data_source_type = task_payload['data_source_type']
|
||||
if cfg:
|
||||
upsert_schedule_task_config(existing.id, cfg)
|
||||
else:
|
||||
task = create_task(
|
||||
name=name,
|
||||
schedule_type=task_payload['schedule_type'],
|
||||
owner_user_id=owner_user_id,
|
||||
cron_expr=cron_expr,
|
||||
schedule_timezone=task_payload['schedule_timezone'],
|
||||
wait_seconds=task_payload['wait_seconds'],
|
||||
dify_agent_id=task_payload['dify_agent_id'],
|
||||
platform_api_path=task_payload['platform_api_path'],
|
||||
notify_user_ids_json=task_payload['notify_user_ids_json'],
|
||||
notify_enabled=task_payload['notify_enabled'],
|
||||
enabled=task_payload['enabled'],
|
||||
actor_id=actor_id,
|
||||
)
|
||||
task.data_source_type = task_payload['data_source_type']
|
||||
task.kb_sync_enabled = task_payload['kb_sync_enabled']
|
||||
task.kb_group_id = (
|
||||
int(task_payload['kb_group_id'])
|
||||
if task_payload.get('kb_group_id') not in (None, '', 0, '0')
|
||||
else None
|
||||
)
|
||||
db.session.commit()
|
||||
if cfg:
|
||||
upsert_schedule_task_config(task.id, cfg)
|
||||
imported += 1
|
||||
except Exception as exc:
|
||||
errors.append(str(exc))
|
||||
skipped += 1
|
||||
db.session.commit()
|
||||
return {'ok': True, 'imported': imported, 'skipped': skipped, 'errors': errors[:20]}
|
||||
@@ -0,0 +1,22 @@
|
||||
"""
|
||||
backend/app/services/schedule/serialization.py
|
||||
|
||||
用途:排程域 JSON 序列化辅助(SQL 预览、测试跑结果)。
|
||||
依赖:标准库 decimal/datetime。
|
||||
逻辑:api/schedule/common 与 test_run_service 共用;不依赖 api 层。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import decimal
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
|
||||
def safe_json_value(value):
|
||||
"""将 SQL 查询结果中的 Decimal/datetime 转为 JSON 可序列化类型。"""
|
||||
if isinstance(value, decimal.Decimal):
|
||||
return float(value)
|
||||
if isinstance(value, (date, datetime)):
|
||||
return value.isoformat()
|
||||
if isinstance(value, timedelta):
|
||||
return str(value)
|
||||
return value
|
||||
@@ -0,0 +1,55 @@
|
||||
"""
|
||||
backend/app/services/schedule/sql_preview_service.py
|
||||
|
||||
用途:排程抓取 SQL 预览(test-sql 业务编排)。
|
||||
依赖:services/schedule、sql_config、srm_service。
|
||||
逻辑:由 api/schedule/config.py 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError, NotFoundError
|
||||
from app.services.schedule import _build_srm_conn_str
|
||||
from app.services.schedule.serialization import safe_json_value
|
||||
from app.services.schedule.srm_service import _fetch_records
|
||||
from app.services.schedule.sql_config import _build_fetch_sql, get_schedule_sql_config_by_task_id
|
||||
|
||||
|
||||
def preview_fetch_sql(task_id: int, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
执行抓取 SQL 预览查询。
|
||||
Args:
|
||||
task_id: ScheduleTask 主键。
|
||||
data: 可选 fetch_where_conditions、fetch_order_by、limit。
|
||||
Returns:
|
||||
total、showing、limit、sql、columns、rows。
|
||||
Raises:
|
||||
NotFoundError: 任务配置不存在。
|
||||
AppError: SQL 执行失败。
|
||||
"""
|
||||
cfg = get_schedule_sql_config_by_task_id(task_id)
|
||||
if not cfg:
|
||||
raise NotFoundError(f'Config for task {task_id} not found')
|
||||
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
|
||||
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
|
||||
limit = min(int(data.get('limit') or 10), 100)
|
||||
base = cfg.base_fetch_sql or cfg.fetch_sql
|
||||
sql = _build_fetch_sql(base, custom_where, custom_order_by) if cfg.base_fetch_sql else base
|
||||
try:
|
||||
if cfg.data_source and (not cfg.data_source.is_empty()):
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
rows = _fetch_records(conn_str, sql)
|
||||
result_rows = [{k: safe_json_value(v) for k, v in r.items()} for r in rows[:limit]]
|
||||
return {
|
||||
'total': len(rows),
|
||||
'showing': len(result_rows),
|
||||
'limit': limit,
|
||||
'sql': sql,
|
||||
'columns': list(result_rows[0].keys()) if result_rows else [],
|
||||
'rows': result_rows,
|
||||
}
|
||||
except Exception as exc:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(exc), http_status=400, details={'sql': sql})
|
||||
@@ -0,0 +1,293 @@
|
||||
"""
|
||||
backend/app/services/schedule/test_run_service.py
|
||||
|
||||
用途:排程 test-run 同步小规模试跑编排。
|
||||
依赖:models、scheduler_service、excel_service、srm_service、kb_sync。
|
||||
逻辑:由 api/schedule/config.py test-run 路由调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time as _time
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule import _build_srm_conn_str, _resolve_dify_agent, _resolve_schedule_user
|
||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||
from app.services.schedule.scheduler_service import _generate_test_run_no, _notify_schedule_run_wecom
|
||||
from app.services.schedule.serialization import safe_json_value
|
||||
from app.services.schedule.srm_service import (
|
||||
_build_record_text,
|
||||
_execute_writeback,
|
||||
_fetch_records,
|
||||
_run_check_job_loop,
|
||||
)
|
||||
from app.services.schedule.sql_config import _build_fetch_sql, get_schedule_sql_config_by_task_id
|
||||
|
||||
|
||||
def _parse_kb_sync_flag(raw_value: Any) -> bool:
|
||||
if isinstance(raw_value, str):
|
||||
return raw_value.strip().lower() in ('1', 'true', 'yes', 'on')
|
||||
return bool(raw_value)
|
||||
|
||||
|
||||
def _build_test_run_callbacks(cfg, test_sql: str):
|
||||
"""构建 test-run 用的 fetch/writeback/pre_dify/build_record 回调。"""
|
||||
def _test_fetch_fn(conn_str_arg):
|
||||
return _fetch_records(conn_str_arg, test_sql)
|
||||
|
||||
def _test_writeback_fn(conn_str_arg, *, row_id, run_no, dify_result, dify_message):
|
||||
_execute_writeback(conn_str_arg, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id)))
|
||||
|
||||
test_pre_dify = None
|
||||
test_build_record = None
|
||||
if cfg.detail_sql:
|
||||
|
||||
def _test_pre_dify(conn_str_arg, item, row_id_value):
|
||||
try:
|
||||
detail_rows = _fetch_records(conn_str_arg, cfg.detail_sql, params=(str(row_id_value),))
|
||||
except Exception as detail_exc:
|
||||
return {
|
||||
'dify_result': '人工判定',
|
||||
'dify_message': f'查询成分明细失败:{detail_exc}',
|
||||
'writeback_srm': False,
|
||||
'writeback_err': str(detail_exc),
|
||||
}
|
||||
detail_lines = []
|
||||
for dr in detail_rows:
|
||||
parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order]
|
||||
detail_lines.append(', '.join(parts))
|
||||
item['detail_text'] = '; '.join(detail_lines) if detail_lines else ''
|
||||
item['_detail_rows'] = detail_rows
|
||||
return None
|
||||
|
||||
test_pre_dify = _test_pre_dify
|
||||
|
||||
def _test_build_with_detail(conn_str_arg, item, row_id_value):
|
||||
detail_rows = item.get('_detail_rows', [])
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order)
|
||||
return (text, item.get('attachment'))
|
||||
|
||||
test_build_record = _test_build_with_detail
|
||||
else:
|
||||
|
||||
def _test_build_simple(conn_str_arg, item, row_id_value):
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels)
|
||||
return (text, item.get('attachment'))
|
||||
|
||||
test_build_record = _test_build_simple
|
||||
|
||||
return _test_fetch_fn, _test_writeback_fn, test_pre_dify, test_build_record
|
||||
|
||||
|
||||
def _finalize_run_status(total_count: int, success_count: int, failed_count: int, errors: list) -> str:
|
||||
if total_count == 0 and (not errors):
|
||||
return 'success'
|
||||
if failed_count == 0:
|
||||
return 'success'
|
||||
if success_count == 0:
|
||||
return 'failed'
|
||||
return 'partial_failed'
|
||||
|
||||
|
||||
def execute_test_run(
|
||||
task_id: int,
|
||||
data: dict[str, Any],
|
||||
*,
|
||||
triggered_by_user_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
同步执行排程 test-run。
|
||||
Args:
|
||||
task_id: ScheduleTask 主键。
|
||||
data: fetch_where/order、limit、kb_sync_enabled 等。
|
||||
triggered_by_user_id: 触发用户 id。
|
||||
Returns:
|
||||
test-run API 响应 dict。
|
||||
Raises:
|
||||
NotFoundError: 任务或配置不存在。
|
||||
AppError: 执行过程异常。
|
||||
"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg = get_schedule_sql_config_by_task_id(task_id)
|
||||
if not cfg:
|
||||
raise NotFoundError(f'Config for task {task_id} not found')
|
||||
|
||||
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
|
||||
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
|
||||
limit = min(int(data.get('limit') or 3), 10)
|
||||
test_kb_sync_enabled = _parse_kb_sync_flag(data.get('kb_sync_enabled', False))
|
||||
base = cfg.base_fetch_sql or cfg.fetch_sql
|
||||
test_sql = _build_fetch_sql(base, custom_where, custom_order_by) if cfg.base_fetch_sql else base
|
||||
if cfg.data_source and (not cfg.data_source.is_empty()):
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
agent = _resolve_dify_agent(task) if task else None
|
||||
user = _resolve_schedule_user(task) if task else 'test_user'
|
||||
wait_seconds = task.wait_seconds if task else 120
|
||||
dify_agent_id = task.dify_agent_id if task else None
|
||||
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_test_run_no(),
|
||||
schedule_task_id=task_id,
|
||||
trigger_type='test',
|
||||
triggered_by_user_id=triggered_by_user_id,
|
||||
started_at=datetime.utcnow(),
|
||||
status='running',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
|
||||
capture_dify_execution_snapshot(run, task)
|
||||
db.session.commit()
|
||||
|
||||
if not cfg.fetch_sql:
|
||||
run.status = 'success'
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.error_message = '无抓取SQL,跳过外部系统数据抓取'
|
||||
try:
|
||||
if task.notify_enabled:
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
except Exception as wecom_exc:
|
||||
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
|
||||
db.session.commit()
|
||||
return {
|
||||
'run_no': run.run_no,
|
||||
'run_id': run.id,
|
||||
'sql': '',
|
||||
'limit': 0,
|
||||
'total_count': 0,
|
||||
'success_count': 0,
|
||||
'failed_count': 0,
|
||||
'skipped_count': 0,
|
||||
'details': [],
|
||||
'errors': [],
|
||||
'step_logs': [{'step': 'no_fetch_sql', 'status': 'skipped', 'detail': '无抓取SQL,跳过外部系统数据抓取'}],
|
||||
'dify_agent_id': dify_agent_id,
|
||||
}
|
||||
|
||||
fetch_fn, writeback_fn, pre_dify_fn, build_record_fn = _build_test_run_callbacks(cfg, test_sql)
|
||||
start_ts = _time.time()
|
||||
try:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop(
|
||||
conn_str=conn_str,
|
||||
run_no=run.run_no,
|
||||
agent=agent,
|
||||
user=user,
|
||||
wait_seconds=wait_seconds,
|
||||
run_id=run.id,
|
||||
fetch_fn=fetch_fn,
|
||||
build_record_fn=build_record_fn,
|
||||
writeback_fn=writeback_fn,
|
||||
writeback_sql=cfg.writeback_sql,
|
||||
row_id_key=cfg.row_id_key,
|
||||
log_prefix=cfg.log_prefix,
|
||||
fetch_sql=test_sql,
|
||||
max_rows=limit,
|
||||
pre_dify_fn=pre_dify_fn,
|
||||
dify_system_prompt=cfg.dify_system_prompt,
|
||||
)
|
||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||
status = _finalize_run_status(total_count, success_count, failed_count, errors)
|
||||
header_order = cfg.alias_order if cfg.alias_order else None
|
||||
header_labels = cfg.header_labels if cfg.header_labels else None
|
||||
detail_alias_order = cfg.detail_alias_order or []
|
||||
try:
|
||||
file_data, file_name, file_size = export_schedule_result_excel(
|
||||
run_no=run.run_no,
|
||||
summary={
|
||||
'status': status,
|
||||
'total_count': total_count,
|
||||
'success_count': success_count,
|
||||
'failed_count': failed_count,
|
||||
'duration_ms': duration_ms,
|
||||
},
|
||||
details=details,
|
||||
header_order=header_order,
|
||||
header_labels=header_labels,
|
||||
detail_alias_order=detail_alias_order,
|
||||
)
|
||||
except Exception as excel_exc:
|
||||
current_app.logger.error('[schedule-test-run] excel export failed: %s', excel_exc, exc_info=True)
|
||||
file_data, file_name, file_size = (None, None, 0)
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = duration_ms
|
||||
run.status = status
|
||||
run.total_count = total_count
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = skipped_count
|
||||
run.step_logs = step_logs if step_logs else None
|
||||
run.error_message = '; '.join(errors[:3]) if errors else None
|
||||
run.excel_file_data = file_data
|
||||
run.excel_file_name = file_name
|
||||
run.excel_file_size = file_size or 0
|
||||
db.session.commit()
|
||||
|
||||
if test_kb_sync_enabled:
|
||||
try:
|
||||
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
|
||||
|
||||
db.session.refresh(task)
|
||||
db.session.refresh(run)
|
||||
sync_schedule_run_excel_to_kb(task, run, enabled=True, process_inline=True)
|
||||
db.session.refresh(run)
|
||||
except Exception as kb_exc:
|
||||
db.session.rollback()
|
||||
db.session.refresh(run)
|
||||
current_app.logger.error('[schedule-test-run] kb sync failed: %s', kb_exc, exc_info=True)
|
||||
run.kb_sync_status = 'failed'
|
||||
run.kb_group_id = getattr(task, 'kb_group_id', None)
|
||||
run.kb_sync_error = str(kb_exc)
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
if task.notify_enabled:
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
except Exception as wecom_exc:
|
||||
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
|
||||
|
||||
safe_details = [{k: safe_json_value(v) for k, v in item.items()} for item in details]
|
||||
return {
|
||||
'run_no': run.run_no,
|
||||
'run_id': run.id,
|
||||
'sql': test_sql,
|
||||
'limit': limit,
|
||||
'total_count': total_count,
|
||||
'success_count': success_count,
|
||||
'failed_count': failed_count,
|
||||
'skipped_count': skipped_count,
|
||||
'details': safe_details,
|
||||
'errors': errors,
|
||||
'step_logs': step_logs,
|
||||
'dify_agent_id': dify_agent_id,
|
||||
'dify_execution_snapshot': run.dify_execution_snapshot,
|
||||
'kb_sync_status': run.kb_sync_status,
|
||||
'kb_sync_error': run.kb_sync_error,
|
||||
'kb_document_id': run.kb_document_id,
|
||||
}
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
run = db.session.get(ScheduleRun, run.id)
|
||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = duration_ms
|
||||
run.status = 'failed'
|
||||
run.error_message = str(exc)
|
||||
db.session.commit()
|
||||
raise AppError(
|
||||
code='SYSTEM.HTTP_ERROR',
|
||||
message=str(exc),
|
||||
http_status=400,
|
||||
details={'sql': test_sql, 'traceback': traceback.format_exc()},
|
||||
)
|
||||
Reference in new issue
Block a user