refactor(backend): 重构后端admin和schedule部分
This commit is contained in:
1 parent
9f5493185d
commit
4a14960e01
74 files changed
+5937
-3644
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)
|
||||
Reference in new issue
Block a user