1456 lines
64 KiB
Python
1456 lines
64 KiB
Python
"""
|
||
backend/app/api/admin.py
|
||
|
||
用途:管理员相关 API 路由(Agent、用户、权限、企业微信等)。
|
||
依赖:flask、models、decorators、app.api.user(Casdoor 用户同步)。
|
||
逻辑:供前端 Admin 控制台调用;创建/编辑用户时委托 user._sync_casdoor_* 与 IdP 保持同步。
|
||
"""
|
||
from flask import Blueprint, request, jsonify, current_app
|
||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit, AgentGuide
|
||
from app.services.minio_service import minio_service
|
||
from app.decorators import require_admin
|
||
from app.config import Config
|
||
from app import db
|
||
from app.env_persistence import persist_env_settings
|
||
from sqlalchemy import func, desc, inspect, or_
|
||
from sqlalchemy.exc import IntegrityError
|
||
from sqlalchemy.orm import joinedload
|
||
from datetime import datetime, timedelta
|
||
import csv
|
||
import io
|
||
import re
|
||
import requests
|
||
import uuid
|
||
from app.services.wecom_notify import send_wecom_event_message
|
||
from app.services.oa_wecom_sync import sync_wecom_userids_from_oa
|
||
from app.services.dify import DifyService
|
||
from app.services.user_admin import delete_admin_users
|
||
from app.auth_jwt import get_current_user as _get_auth_user
|
||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||
admin_bp = Blueprint('admin', __name__)
|
||
|
||
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 _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 = '^[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}$'
|
||
return re.match(pattern, email) is not None
|
||
|
||
def _serialize_wecom_notify_settings():
|
||
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 _serialize_wecom_system_settings():
|
||
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 _default_public_base():
|
||
for key in ('WECOM_PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
|
||
configured = current_app.config.get(key) or ''
|
||
if configured:
|
||
return configured.rstrip('/')
|
||
return request.host_url.rstrip('/')
|
||
|
||
def _serialize_wecom_integration_manifest():
|
||
settings = _serialize_wecom_system_settings()
|
||
public_base = _default_public_base()
|
||
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 request.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 _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_wecom_match_preview(identity: dict, rules: list[str], operator: str) -> dict:
|
||
from app.api import user as user_api
|
||
bind_mode = user_api._get_wecom_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'] = user_api._get_wecom_first_login_input_fields()
|
||
return preview
|
||
matched_users, missing_fields = user_api._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
|
||
|
||
@admin_bp.route('/wecom/debug-user-by-code', methods=['POST'])
|
||
@require_admin
|
||
def debug_wecom_user_by_code():
|
||
from app.api import user as user_api
|
||
if not user_api._is_wecom_configured():
|
||
raise ValidationError('WeCom login is not configured')
|
||
data = request.get_json() or {}
|
||
code = str(data.get('code') or '').strip()
|
||
if not code:
|
||
raise ValidationError('code is required')
|
||
access_token = user_api._get_wecom_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 = user_api._extract_wecom_identity(wecom_user)
|
||
rules, operator = user_api._get_wecom_match_config()
|
||
payload['normalized_identity'] = identity
|
||
payload['match_preview'] = _build_wecom_match_preview(identity, rules, operator)
|
||
return jsonify(payload)
|
||
|
||
def _compute_dashboard_summary():
|
||
"""
|
||
聚合仪表盘四张卡片所需的统计值(仅 COUNT/AVG,不返回列表)。
|
||
|
||
返回字段:
|
||
- agent_count: 启用中的 Agent 数量
|
||
- user_count: 用户总数
|
||
- total_conversations: 对话日志总数
|
||
- avg_score: 反馈平均分(保留 1 位小数)
|
||
"""
|
||
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():
|
||
"""
|
||
聚合侧栏角标所需的待办数量(仅 COUNT,不拉 users / permission_requests 全表)。
|
||
|
||
返回字段:
|
||
- pending_approvals: status=pending 的注册用户数量(「用户审批」角标)
|
||
- pending_requests: status=pending 的权限申请数量(「权限申请」角标)
|
||
"""
|
||
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,
|
||
}
|
||
|
||
@admin_bp.route('/dashboard/summary', methods=['GET'])
|
||
@require_admin
|
||
def dashboard_summary():
|
||
"""
|
||
管理后台仪表盘概览(供 Dashboard 页单次请求)。
|
||
|
||
GET /api/admin/dashboard/summary
|
||
响应示例:{"agent_count": 5, "user_count": 120, "total_conversations": 3000, "avg_score": 4.2}
|
||
"""
|
||
return jsonify(_compute_dashboard_summary())
|
||
|
||
@admin_bp.route('/dashboard/badges', methods=['GET'])
|
||
@require_admin
|
||
def dashboard_badges():
|
||
"""
|
||
管理后台侧栏待办角标(供 AdminLayout 轻量轮询/缓存刷新)。
|
||
|
||
GET /api/admin/dashboard/badges
|
||
响应示例:{"pending_approvals": 2, "pending_requests": 5}
|
||
"""
|
||
return jsonify(_compute_dashboard_badges())
|
||
|
||
@admin_bp.route('/dashboard', methods=['GET'])
|
||
@require_admin
|
||
def dashboard_stats():
|
||
"""
|
||
仪表盘统计(遗留接口,字段名与早期前端兼容;新代码请用 /dashboard/summary 与 /dashboard/badges)。
|
||
|
||
GET /api/admin/dashboard
|
||
响应含 summary 四指标 + pending_approvals / pending_requests。
|
||
"""
|
||
summary = _compute_dashboard_summary()
|
||
badges = _compute_dashboard_badges()
|
||
return jsonify({
|
||
'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'],
|
||
})
|
||
|
||
@admin_bp.route('/departments', methods=['GET'])
|
||
@require_admin
|
||
def list_departments():
|
||
depts = db.session.query(Department).order_by(Department.name.asc()).all()
|
||
return jsonify([{'id': d.id, 'name': d.name, 'code': d.code, 'company': d.company, 'description': d.description} for d in depts])
|
||
|
||
@admin_bp.route('/departments', methods=['POST'])
|
||
@require_admin
|
||
def create_department():
|
||
data = request.get_json() or {}
|
||
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 (jsonify({'id': dept.id, 'name': dept.name}), 201)
|
||
|
||
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
|
||
@require_admin
|
||
def update_department(id):
|
||
dept = db.session.get(Department, id)
|
||
if not dept:
|
||
raise NotFoundError('Not found')
|
||
data = request.get_json() or {}
|
||
if 'name' in data:
|
||
if db.session.query(Department).filter(Department.name == data['name'], Department.id != 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 != 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()
|
||
return jsonify({'status': 'ok'})
|
||
|
||
@admin_bp.route('/departments/<int:id>', methods=['DELETE'])
|
||
@require_admin
|
||
def delete_department(id):
|
||
dept = db.session.get(Department, id)
|
||
if dept:
|
||
db.session.delete(dept)
|
||
db.session.commit()
|
||
return jsonify({'status': 'ok'})
|
||
|
||
@admin_bp.route('/agents', methods=['GET'])
|
||
@require_admin
|
||
def list_agents():
|
||
agents = db.session.query(Agent).order_by(Agent.id.asc()).all()
|
||
return jsonify([{'id': a.id, 'name': a.name, 'dify_app_id': a.dify_app_id, 'dify_api_key': a.dify_api_key, 'is_active': a.is_active, 'description': a.description, 'type': a.type, 'api_base_url': a.api_base_url, 'extra_config': a.extra_config} for a in agents])
|
||
|
||
@admin_bp.route('/agents', methods=['POST'])
|
||
@require_admin
|
||
def create_agent():
|
||
data = request.get_json() or {}
|
||
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 (jsonify({'id': agent.id}), 201)
|
||
|
||
@admin_bp.route('/agents/<int:id>', methods=['PUT'])
|
||
@require_admin
|
||
def update_agent(id):
|
||
agent = db.session.get(Agent, id)
|
||
if not agent:
|
||
raise NotFoundError('Not found')
|
||
data = request.get_json() or {}
|
||
for k in ['name', 'dify_app_id', 'description', 'type', 'api_base_url', 'extra_config', 'is_active']:
|
||
if k in data:
|
||
setattr(agent, k, data[k])
|
||
if 'dify_api_key' in data and data['dify_api_key']:
|
||
agent.dify_api_key = data['dify_api_key']
|
||
db.session.commit()
|
||
return jsonify({'status': 'ok'})
|
||
|
||
@admin_bp.route('/agents/<int:id>', methods=['DELETE'])
|
||
@require_admin
|
||
def delete_agent(id):
|
||
agent = db.session.get(Agent, id)
|
||
if agent:
|
||
db.session.delete(agent)
|
||
db.session.commit()
|
||
return jsonify({'status': 'ok'})
|
||
|
||
@admin_bp.route('/agents/<int:id>/test', methods=['POST'])
|
||
@require_admin
|
||
def test_agent(id):
|
||
"""
|
||
测试应用连通性。
|
||
返回:请求地址、输出信息、结果分析。
|
||
若测试通过,则自动将应用状态置为启用。
|
||
"""
|
||
agent = db.session.get(Agent, id)
|
||
if not agent:
|
||
raise NotFoundError('Not found')
|
||
tested_at = datetime.utcnow().isoformat()
|
||
if agent.type == 'iframe':
|
||
iframe_url = (agent.extra_config or {}).get('iframe_url')
|
||
if not iframe_url:
|
||
return (jsonify({'passed': False, 'request_url': '', 'output_info': 'Missing iframe_url in extra_config.', 'analysis': '测试失败:未配置 iframe URL。', 'http_status': 0, 'tested_at': tested_at}), 200)
|
||
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 (jsonify({'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}), 200)
|
||
except requests.RequestException as e:
|
||
return (jsonify({'passed': False, 'request_url': iframe_url, 'output_info': str(e), 'analysis': '测试失败:请求 iframe 地址异常。', 'http_status': 0, 'tested_at': tested_at}), 200)
|
||
if not agent.dify_api_key:
|
||
return (jsonify({'passed': False, 'request_url': '', 'output_info': 'Missing dify_api_key.', 'analysis': '测试失败:未配置 API Key。', 'http_status': 0, 'tested_at': tested_at}), 200)
|
||
base_url = (agent.api_base_url or Config.DIFY_API_BASE or '').rstrip('/')
|
||
if not base_url:
|
||
return (jsonify({'passed': False, 'request_url': '', 'output_info': 'Missing api_base_url.', 'analysis': '测试失败:未配置 API Base URL。', 'http_status': 0, 'tested_at': tested_at}), 200)
|
||
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':
|
||
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 接口可访问且认证通过(本次未返回业务成功状态)。'
|
||
else:
|
||
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]
|
||
except ValueError:
|
||
if resp.ok and raw_text.strip():
|
||
if dify_app_type == 'workflow':
|
||
passed = True
|
||
analysis = '测试通过:Workflow 接口可访问并返回了文本内容。'
|
||
else:
|
||
passed = True
|
||
analysis = '测试通过:Chatflow 接口可访问并返回了文本内容。'
|
||
if passed and (not agent.is_active):
|
||
agent.is_active = True
|
||
db.session.commit()
|
||
return (jsonify({'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}), 200)
|
||
except requests.RequestException as e:
|
||
return (jsonify({'passed': False, 'dify_app_type': dify_app_type, 'request_url': request_url, 'output_info': str(e), 'analysis': '测试失败:请求异常(网络、超时或认证问题)。', 'http_status': 0, 'tested_at': tested_at}), 200)
|
||
|
||
@admin_bp.route('/agents/<int:id>/permissions', methods=['POST'])
|
||
@require_admin
|
||
def update_agent_permissions(id):
|
||
agent = db.session.get(Agent, id)
|
||
if not agent:
|
||
raise NotFoundError('Not found')
|
||
data = request.get_json() or {}
|
||
user_ids = data.get('user_ids', [])
|
||
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
||
current_users = db.session.query(User).filter(User.agents.contains(agent)).all()
|
||
current_user_ids = set((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 u in users_to_add:
|
||
u.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 u in users_to_remove:
|
||
u.agents.remove(agent)
|
||
db.session.commit()
|
||
return jsonify({'status': 'ok'})
|
||
|
||
def _serialize_admin_user(user: User) -> dict:
|
||
"""将 User ORM 转为管理端列表/详情 JSON 结构。"""
|
||
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_admin_users_filters(query):
|
||
"""
|
||
按 Query 参数过滤用户列表(模糊匹配文本字段)。
|
||
支持:username, email, department, role, status, real_name, employee_id, phone_number, hide_rejected。
|
||
"""
|
||
if request.args.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 = (request.args.get(key) or '').strip()
|
||
if value:
|
||
query = query.filter(column.cast(db.String).ilike(f'%{value}%'))
|
||
return query
|
||
|
||
|
||
@admin_bp.route('/users', methods=['GET'])
|
||
@require_admin
|
||
def list_users():
|
||
"""
|
||
列出管理端用户。无 page 参数时返回全量数组(兼容旧调用);带 page 时分页并支持筛选。
|
||
|
||
Query: page, page_size, username, email, department, role, status, real_name,
|
||
employee_id, phone_number, hide_rejected
|
||
Returns (paginated): { items, total, page, page_size, pages }
|
||
Returns (legacy): User[]
|
||
"""
|
||
query = _apply_admin_users_filters(db.session.query(User))
|
||
|
||
if 'page' not in request.args:
|
||
users = query.options(joinedload(User.agents)).order_by(User.id.asc()).all()
|
||
return jsonify([_serialize_admin_user(u) for u in users])
|
||
|
||
page = request.args.get('page', type=int) or 1
|
||
page_size = request.args.get('page_size', type=int) or 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 jsonify({
|
||
'items': [_serialize_admin_user(u) for u in users],
|
||
'total': int(total),
|
||
'page': page,
|
||
'page_size': page_size,
|
||
'pages': pages,
|
||
})
|
||
|
||
@admin_bp.route('/users', methods=['POST'])
|
||
@require_admin
|
||
def create_user():
|
||
"""
|
||
管理端创建用户:本地入库前先同步 Casdoor add-user,与改密一样保持 IdP 一致。
|
||
核心逻辑:校验 → 构建 User → _sync_casdoor_create_user → commit;Casdoor 失败则 rollback。
|
||
Request JSON: username, password, email, real_name, employee_id, phone_number 等
|
||
Returns:
|
||
201 + { id };Casdoor/唯一约束失败时抛出 AppError/ConflictError
|
||
"""
|
||
from app.api import user as user_api
|
||
data = request.get_json() or {}
|
||
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'})
|
||
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'])
|
||
if data.get('agent_ids'):
|
||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||
user.agents = agents
|
||
db.session.add(user)
|
||
try:
|
||
user_api._sync_casdoor_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 e:
|
||
db.session.rollback()
|
||
_raise_user_integrity_conflict(e)
|
||
except AppError:
|
||
db.session.rollback()
|
||
raise
|
||
except RuntimeError as e:
|
||
db.session.rollback()
|
||
user_api._raise_casdoor_add_user_error(e)
|
||
return (jsonify({'id': user.id}), 201)
|
||
|
||
@admin_bp.route('/users/<int:id>', methods=['PUT'])
|
||
@require_admin
|
||
def update_user(id):
|
||
"""
|
||
管理端编辑用户:本地变更 commit 前先同步 Casdoor update-user / set-password。
|
||
核心逻辑:应用本地字段 → _sync_casdoor_update_user → commit;Casdoor 失败则 rollback。
|
||
Request JSON: email, department, role, status, password 等;password 为空表示不改密
|
||
Returns:
|
||
{ status: ok };Casdoor/唯一约束失败时抛出 AppError/ConflictError
|
||
"""
|
||
from app.api import user as user_api
|
||
user = db.session.get(User, id)
|
||
if not user:
|
||
raise NotFoundError('User not found')
|
||
data = request.get_json() or {}
|
||
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'})
|
||
profile_field_keys = {'email', 'department', 'status', 'real_name', 'phone_number'}
|
||
sync_profile = any(k in data for k in profile_field_keys)
|
||
new_password = _empty_to_none(data.get('password'))
|
||
for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||
if k in data:
|
||
if k in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||
setattr(user, k, _empty_to_none(data[k]))
|
||
else:
|
||
setattr(user, k, data[k])
|
||
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
|
||
try:
|
||
if sync_profile or new_password:
|
||
user_api._sync_casdoor_update_user(
|
||
user,
|
||
new_password=new_password,
|
||
sync_profile=sync_profile,
|
||
)
|
||
db.session.commit()
|
||
except IntegrityError as e:
|
||
db.session.rollback()
|
||
_raise_user_integrity_conflict(e)
|
||
except AppError:
|
||
db.session.rollback()
|
||
raise
|
||
except RuntimeError as e:
|
||
db.session.rollback()
|
||
user_api._raise_casdoor_update_user_error(e)
|
||
return jsonify({'status': 'ok'})
|
||
|
||
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
||
@require_admin
|
||
def cleanup_rejected_users():
|
||
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 jsonify({'deleted_count': cnt})
|
||
|
||
@admin_bp.route('/users/batch-delete', methods=['POST'])
|
||
@require_admin
|
||
def batch_delete_users():
|
||
data = request.get_json() or {}
|
||
ids = data.get('user_ids', [])
|
||
current_user = _get_auth_user()
|
||
current_user_id = current_user.id if current_user else None
|
||
target_ids = [uid for uid in 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 jsonify({'deleted_count': cnt})
|
||
|
||
@admin_bp.route('/users/<int:id>', methods=['DELETE'])
|
||
@require_admin
|
||
def delete_user(id: int):
|
||
"""删除单个用户,复用 delete_admin_users 的关联清理逻辑。"""
|
||
current_user = _get_auth_user()
|
||
if current_user and str(current_user.id) == str(id):
|
||
raise ValidationError('Cannot delete current user')
|
||
user = db.session.get(User, id)
|
||
if not user:
|
||
raise NotFoundError('User not found')
|
||
try:
|
||
delete_admin_users([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 jsonify({'status': 'ok'})
|
||
|
||
@admin_bp.route('/permissions/batch', methods=['POST'])
|
||
@require_admin
|
||
def batch_update_permissions():
|
||
"""
|
||
Batch update user permissions
|
||
"""
|
||
data = request.get_json() or {}
|
||
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 = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
||
agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all()
|
||
if not agents and action != 'set':
|
||
if action == 'remove':
|
||
return jsonify({'status': 'ok'})
|
||
for user in users:
|
||
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)
|
||
if user.wecom_userid:
|
||
action_label = {'add': '新增', 'remove': '移除', 'set': '重置为'}[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')
|
||
db.session.commit()
|
||
return jsonify({'status': 'ok', 'updated_count': len(users)})
|
||
|
||
@admin_bp.route('/users/<int:id>/permissions', methods=['POST'])
|
||
@require_admin
|
||
def update_user_permissions(id):
|
||
user = db.session.get(User, id)
|
||
if not user:
|
||
raise NotFoundError('Not found')
|
||
data = request.get_json() or {}
|
||
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 jsonify({'status': 'ok'})
|
||
|
||
@admin_bp.route('/users/<int:id>/approve', methods=['POST'])
|
||
@require_admin
|
||
def approve_user(id):
|
||
user = db.session.get(User, id)
|
||
if user:
|
||
user.status = 'active'
|
||
db.session.commit()
|
||
return jsonify({'status': 'ok'})
|
||
|
||
@admin_bp.route('/users/<int:id>/reject', methods=['POST'])
|
||
@require_admin
|
||
def reject_user(id):
|
||
user = db.session.get(User, id)
|
||
if user:
|
||
user.status = 'rejected'
|
||
db.session.commit()
|
||
return jsonify({'status': 'ok'})
|
||
|
||
@admin_bp.route('/permission-requests', methods=['GET'])
|
||
@require_admin
|
||
def list_permission_requests():
|
||
reqs = db.session.query(PermissionRequest).order_by(PermissionRequest.created_at.desc()).all()
|
||
return jsonify([{'id': r.id, 'user_id': r.user_id, 'agent_id': r.agent_id, 'reason': r.reason, 'status': r.status, 'created_at': r.created_at.isoformat()} for r in reqs])
|
||
|
||
@admin_bp.route('/permission-requests/<int:id>/approve', methods=['POST'])
|
||
@require_admin
|
||
def approve_request(id):
|
||
req = db.session.get(PermissionRequest, 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 jsonify({'status': 'ok'})
|
||
|
||
@admin_bp.route('/permission-requests/<int:id>/reject', methods=['POST'])
|
||
@require_admin
|
||
def reject_request(id):
|
||
req = db.session.get(PermissionRequest, 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 jsonify({'status': 'ok'})
|
||
|
||
@admin_bp.route('/quick-questions', methods=['GET'])
|
||
@require_admin
|
||
def list_quick_questions():
|
||
qqs = db.session.query(QuickQuestion).filter(QuickQuestion.user_id == None).order_by(QuickQuestion.sort_order.asc()).all()
|
||
res = []
|
||
for q in qqs:
|
||
agent = db.session.get(Agent, q.agent_id)
|
||
res.append({'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id, 'agent_name': agent.name if agent else 'Unknown', 'sort_order': q.sort_order})
|
||
return jsonify(res)
|
||
|
||
@admin_bp.route('/quick-questions', methods=['POST'])
|
||
@require_admin
|
||
def create_quick_question():
|
||
data = request.get_json() or {}
|
||
if not data.get('title') or not data.get('question') or (not data.get('agent_id')):
|
||
raise ValidationError('Missing required fields')
|
||
qq = QuickQuestion(user_id=None, agent_id=data['agent_id'], title=data['title'], question=data['question'], sort_order=data.get('sort_order', 0))
|
||
db.session.add(qq)
|
||
db.session.commit()
|
||
return (jsonify({'id': qq.id}), 201)
|
||
|
||
@admin_bp.route('/quick-questions/<int:id>', methods=['PUT'])
|
||
@require_admin
|
||
def update_quick_question(id):
|
||
qq = db.session.get(QuickQuestion, id)
|
||
if not qq:
|
||
raise NotFoundError('Not found')
|
||
data = request.get_json() or {}
|
||
if 'title' in data:
|
||
qq.title = data['title']
|
||
if 'question' in data:
|
||
qq.question = data['question']
|
||
if 'agent_id' in data:
|
||
qq.agent_id = data['agent_id']
|
||
if 'sort_order' in data:
|
||
qq.sort_order = data['sort_order']
|
||
db.session.commit()
|
||
return jsonify({'status': 'ok'})
|
||
|
||
@admin_bp.route('/quick-questions/<int:id>', methods=['DELETE'])
|
||
@require_admin
|
||
def delete_quick_question(id):
|
||
qq = db.session.get(QuickQuestion, id)
|
||
if qq:
|
||
db.session.delete(qq)
|
||
db.session.commit()
|
||
return jsonify({'status': 'ok'})
|
||
|
||
@admin_bp.route('/reports/usage', methods=['GET'])
|
||
@require_admin
|
||
def usage_report():
|
||
total = db.session.query(ChatLog).count()
|
||
by_user = db.session.query(User.username, func.count(ChatLog.id)).join(ChatLog).group_by(User.username).all()
|
||
by_agent = db.session.query(Agent.name, func.count(ChatLog.id)).join(ChatLog).group_by(Agent.name).all()
|
||
return jsonify({'total': total, 'by_user': [{'username': u, 'count': c} for u, c in by_user], 'by_agent': [{'agent': a, 'count': c} for a, c in by_agent]})
|
||
|
||
@admin_bp.route('/reports/feedback', methods=['GET'])
|
||
@require_admin
|
||
def feedback_report():
|
||
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 jsonify({'total': total, 'avg_score': float(avg), 'distribution': [{'score': s, 'count': c} for s, c in dist]})
|
||
|
||
@admin_bp.route('/reports/general-feedbacks', methods=['GET'])
|
||
@require_admin
|
||
def list_general_feedbacks_report():
|
||
"""
|
||
List rows from general_feedbacks for report page display.
|
||
Supports simple fuzzy filters by column name and optional limit.
|
||
"""
|
||
query = db.session.query(GeneralFeedback, User.real_name.label('real_name'), User.department.label('department')).outerjoin(User, User.id == GeneralFeedback.user_id)
|
||
reserved = {'limit', 'offset', 'page', 'page_size'}
|
||
for key, value in request.args.items():
|
||
if key in reserved:
|
||
continue
|
||
if 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}%'))
|
||
query = query.order_by(desc(GeneralFeedback.created_at), desc(GeneralFeedback.id))
|
||
try:
|
||
limit = int(request.args.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 jsonify(rows)
|
||
|
||
@admin_bp.route('/reports/general-feedbacks/count', methods=['GET'])
|
||
@require_admin
|
||
def count_general_feedbacks_report():
|
||
query = db.session.query(GeneralFeedback).outerjoin(User, User.id == GeneralFeedback.user_id)
|
||
reserved = {'limit', 'offset', 'page', 'page_size'}
|
||
for key, value in request.args.items():
|
||
if key in reserved:
|
||
continue
|
||
if 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}%'))
|
||
total = query.count()
|
||
return jsonify({'table': 'general_feedbacks', 'total': int(total)})
|
||
|
||
@admin_bp.route('/database/<table>', methods=['GET'])
|
||
@require_admin
|
||
def get_table_data(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}
|
||
model = model_map.get(table)
|
||
if not model:
|
||
raise ValidationError('Invalid table')
|
||
query = db.session.query(model)
|
||
for k, v in request.args.items():
|
||
if hasattr(model, k):
|
||
col = getattr(model, k)
|
||
query = query.filter(col.cast(db.String).ilike(f'%{v}%'))
|
||
items = query.limit(100).all()
|
||
res = []
|
||
for item in items:
|
||
d = {}
|
||
for col in item.__table__.columns:
|
||
val = getattr(item, col.name)
|
||
if isinstance(val, datetime):
|
||
val = val.isoformat()
|
||
d[col.name] = val
|
||
res.append(d)
|
||
return jsonify(res)
|
||
|
||
@admin_bp.route('/database/chat_logs/batch-delete', methods=['POST'])
|
||
@require_admin
|
||
def batch_delete_chat_logs():
|
||
"""
|
||
Batch delete chat logs by ids.
|
||
Only accepts chat_log ids to avoid accidental table-wide deletion.
|
||
"""
|
||
data = request.get_json() or {}
|
||
raw_ids = data.get('ids', [])
|
||
if not isinstance(raw_ids, list) or not raw_ids:
|
||
raise ValidationError('ids is required')
|
||
ids = []
|
||
for v in raw_ids:
|
||
try:
|
||
ids.append(int(v))
|
||
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 jsonify({'deleted_count': cnt})
|
||
|
||
@admin_bp.route('/database/<table>/count', methods=['GET'])
|
||
@require_admin
|
||
def get_table_count(table):
|
||
"""
|
||
Return total row count for admin report tables.
|
||
"""
|
||
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}
|
||
model = model_map.get(table)
|
||
if not model:
|
||
raise ValidationError('Invalid table')
|
||
total = db.session.query(func.count(model.id)).scalar()
|
||
return jsonify({'table': table, 'total': int(total or 0)})
|
||
|
||
@admin_bp.route('/wecom/bindings', methods=['GET'])
|
||
@require_admin
|
||
def list_wecom_bindings():
|
||
"""
|
||
分页列出用户企微绑定,支持 keyword 模糊搜索与 bound_only 筛选。
|
||
|
||
Query: bound_only, keyword, page, page_size
|
||
Returns: { items, total, page, page_size, pages }
|
||
"""
|
||
bound_only = request.args.get('bound_only', 'false').lower() == 'true'
|
||
keyword = (request.args.get('keyword') or '').strip()
|
||
page = request.args.get('page', type=int) or 1
|
||
page_size = request.args.get('page_size', type=int) or 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 jsonify({
|
||
'items': items,
|
||
'total': int(total),
|
||
'page': page,
|
||
'page_size': page_size,
|
||
'pages': pages,
|
||
})
|
||
|
||
@admin_bp.route('/guides/upload', methods=['POST'])
|
||
@require_admin
|
||
def upload_guide():
|
||
if 'file' not in request.files:
|
||
raise ValidationError('No file part')
|
||
file = request.files['file']
|
||
if file.filename == '':
|
||
raise ValidationError('No selected file')
|
||
|
||
content_type = file.content_type
|
||
file_size = len(file.read())
|
||
file.seek(0)
|
||
|
||
try:
|
||
object_name = minio_service.upload_file(file, file.filename, content_type, file_size)
|
||
return jsonify({
|
||
'file_path': object_name,
|
||
'file_name': file.filename,
|
||
'file_size': file_size,
|
||
'file_type': 'video' if content_type.startswith('video') else 'pdf' if 'pdf' in content_type else 'image'
|
||
})
|
||
except Exception as e:
|
||
import traceback
|
||
traceback.print_exc()
|
||
raise AppError(f"Upload failed: {str(e)}")
|
||
|
||
@admin_bp.route('/guides', methods=['POST'])
|
||
@require_admin
|
||
def create_guide():
|
||
data = request.json
|
||
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=_get_auth_user().id
|
||
)
|
||
db.session.add(guide)
|
||
db.session.commit()
|
||
return jsonify({'id': guide.id})
|
||
|
||
@admin_bp.route('/guides', methods=['GET'])
|
||
@require_admin
|
||
def list_guides():
|
||
agent_id = request.args.get('agent_id')
|
||
query = db.session.query(AgentGuide)
|
||
if agent_id:
|
||
query = query.filter_by(agent_id=agent_id)
|
||
guides = query.order_by(AgentGuide.sort_order).all()
|
||
|
||
result = []
|
||
for g in guides:
|
||
result.append({
|
||
'id': g.id,
|
||
'agent_id': g.agent_id,
|
||
'file_name': g.file_name,
|
||
'file_type': g.file_type,
|
||
'file_path': g.file_path,
|
||
'file_url': minio_service.get_public_url(g.file_path),
|
||
'file_size': g.file_size,
|
||
'remark': g.remark,
|
||
'sort_order': g.sort_order,
|
||
'status': g.status,
|
||
'created_at': g.created_at.isoformat()
|
||
})
|
||
return jsonify(result)
|
||
|
||
@admin_bp.route('/guides/<int:id>', methods=['PUT'])
|
||
@require_admin
|
||
def update_guide(id):
|
||
guide = db.session.query(AgentGuide).get(id)
|
||
if not guide:
|
||
raise NotFoundError('Guide not found')
|
||
|
||
data = request.json
|
||
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()
|
||
return jsonify({'success': True})
|
||
|
||
@admin_bp.route('/guides/<int:id>', methods=['DELETE'])
|
||
@require_admin
|
||
def delete_guide(id):
|
||
guide = db.session.query(AgentGuide).get(id)
|
||
if not guide:
|
||
raise NotFoundError('Guide not found')
|
||
|
||
minio_service.delete_file(guide.file_path)
|
||
db.session.delete(guide)
|
||
db.session.commit()
|
||
return jsonify({'success': True})
|
||
|
||
@admin_bp.route('/wecom/bind', methods=['POST'])
|
||
@require_admin
|
||
def bind_wecom_user():
|
||
"""
|
||
Bind a local user to a WeCom account (manual operation by admin).
|
||
"""
|
||
data = request.get_json() or {}
|
||
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 jsonify({'status': 'ok', 'message': 'WeCom binding updated'})
|
||
|
||
@admin_bp.route('/wecom/unbind', methods=['POST'])
|
||
@require_admin
|
||
def unbind_wecom_user():
|
||
"""
|
||
Unbind WeCom account from local user by admin.
|
||
"""
|
||
data = request.get_json() or {}
|
||
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 jsonify({'status': 'ok', 'message': 'WeCom account unbound'})
|
||
|
||
@admin_bp.route('/wecom/provision', methods=['POST'])
|
||
@require_admin
|
||
def provision_wecom_user():
|
||
"""
|
||
Atomic admin helper to create user (optional), bind WeCom identity and assign agent permissions.
|
||
"""
|
||
data = request.get_json() or {}
|
||
create_user = 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:
|
||
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'
|
||
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'
|
||
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
|
||
has_agent_ids = 'agent_ids' in data
|
||
if has_agent_ids:
|
||
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 (jsonify({'status': 'ok', 'user_id': user.id, 'binding': binding_status, 'permission_updated': permission_updated}), 201 if create_user else 200)
|
||
|
||
@admin_bp.route('/wecom/login-audits', methods=['GET'])
|
||
@require_admin
|
||
def get_wecom_login_audits():
|
||
"""
|
||
Query login audits for WeCom/password source.
|
||
"""
|
||
source = request.args.get('source')
|
||
status = request.args.get('status')
|
||
limit = request.args.get('limit', 100)
|
||
try:
|
||
limit = max(1, min(int(limit), 500))
|
||
except 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 jsonify([{'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])
|
||
|
||
@admin_bp.route('/wecom/notify-settings', methods=['GET', 'PUT'])
|
||
@require_admin
|
||
def wecom_notify_settings():
|
||
if request.method == 'GET':
|
||
return jsonify(_serialize_wecom_notify_settings())
|
||
data = request.get_json() or {}
|
||
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 jsonify({'status': 'ok', 'settings': _serialize_wecom_notify_settings()})
|
||
|
||
@admin_bp.route('/wecom/system-settings', methods=['GET', 'PUT'])
|
||
@require_admin
|
||
def wecom_system_settings():
|
||
if request.method == 'GET':
|
||
return jsonify(_serialize_wecom_system_settings())
|
||
data = request.get_json() or {}
|
||
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 jsonify({'status': 'ok', 'settings': _serialize_wecom_system_settings()})
|
||
|
||
@admin_bp.route('/wecom/integration-manifest', methods=['GET'])
|
||
@require_admin
|
||
def wecom_integration_manifest():
|
||
return jsonify(_serialize_wecom_integration_manifest())
|
||
|
||
@admin_bp.route('/wecom/notify-metrics', methods=['GET'])
|
||
@require_admin
|
||
def wecom_notify_metrics():
|
||
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 jsonify({'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})
|
||
|
||
|
||
@admin_bp.route('/wecom/binding-stats', methods=['GET'])
|
||
@require_admin
|
||
def wecom_binding_stats():
|
||
"""
|
||
返回活跃用户的企微 userid 绑定统计,供管理端概览卡片使用。
|
||
"""
|
||
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 jsonify(
|
||
{
|
||
'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,
|
||
}
|
||
)
|
||
|
||
|
||
@admin_bp.route('/wecom/sync-userids', methods=['POST'])
|
||
@require_admin
|
||
def sync_wecom_userids_admin():
|
||
"""
|
||
从 OA userInfo_view 按工号同步 users.wecom_userid(workcode→employee_id,id→wecom_userid)。
|
||
Request JSON: { "apply": false }
|
||
"""
|
||
data = request.get_json() or {}
|
||
apply = bool(data.get('apply'))
|
||
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 jsonify(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)
|
||
|