715 lines
25 KiB
Python
715 lines
25 KiB
Python
"""
|
|
backend/app/api/admin.py
|
|
文件用途:管理员相关 API 路由
|
|
引用文件:flask, models, decorators
|
|
逻辑关系:提供 Agent 配置管理、用户与权限管理接口,供前端 Admin 控制台使用
|
|
"""
|
|
from flask import Blueprint, request, jsonify
|
|
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig
|
|
from app.decorators import require_admin
|
|
from app.config import Config
|
|
from app import db
|
|
from sqlalchemy import func, desc, inspect
|
|
from datetime import datetime
|
|
import csv
|
|
import io
|
|
import requests
|
|
|
|
admin_bp = Blueprint('admin', __name__)
|
|
|
|
@admin_bp.route('/dashboard', methods=['GET'])
|
|
@require_admin
|
|
def dashboard_stats():
|
|
"""
|
|
Dashboard statistics
|
|
"""
|
|
total_users = db.session.query(func.count(User.id)).scalar()
|
|
active_agents = db.session.query(func.count(Agent.id)).filter_by(is_active=True).scalar()
|
|
total_conversations = db.session.query(func.count(ChatLog.id)).scalar()
|
|
|
|
# Average rating
|
|
avg_score = db.session.query(func.avg(Feedback.score)).scalar()
|
|
avg_score = float(avg_score) if avg_score else 0.0
|
|
|
|
# Pending approvals
|
|
pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar()
|
|
|
|
return jsonify({
|
|
'total_users': total_users,
|
|
'active_agents': active_agents,
|
|
'total_conversations': total_conversations,
|
|
'avg_score': round(avg_score, 1),
|
|
'pending_approvals': pending_approvals
|
|
})
|
|
|
|
# --- Departments ---
|
|
@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'): return jsonify({'error': 'Name is required'}), 400
|
|
if db.session.query(Department).filter_by(name=data['name']).first():
|
|
return jsonify({'error': 'Name exists'}), 400
|
|
if data.get('code') and db.session.query(Department).filter_by(code=data['code']).first():
|
|
return jsonify({'error': 'Code exists'}), 400
|
|
|
|
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: return jsonify({'error': 'Not found'}), 404
|
|
data = request.get_json() or {}
|
|
|
|
if 'name' in data:
|
|
if db.session.query(Department).filter(Department.name == data['name'], Department.id != id).first():
|
|
return jsonify({'error': 'Name exists'}), 400
|
|
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():
|
|
return jsonify({'error': 'Code exists'}), 400
|
|
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'})
|
|
|
|
|
|
# --- Agents ---
|
|
@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'): return jsonify({'error': 'Name is required'}), 400
|
|
|
|
agent_type = data.get('type', 'api')
|
|
# 对于 API 类型,必须校验 dify_app_id
|
|
if agent_type == 'api' and not data.get('dify_app_id'):
|
|
return jsonify({'error': 'App ID is required for API agents'}), 400
|
|
|
|
agent = Agent(
|
|
name=data['name'],
|
|
dify_app_id=data.get('dify_app_id') or None, # nullable, convert empty string to None
|
|
dify_api_key=data.get('dify_api_key') or None, # nullable
|
|
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: return jsonify({'error': 'Not found'}), 404
|
|
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:
|
|
return jsonify({'error': 'Not found'}), 404
|
|
|
|
tested_at = datetime.utcnow().isoformat()
|
|
|
|
if agent.type == 'iframe':
|
|
iframe_url = (agent.extra_config or {}).get('iframe_url')
|
|
if not iframe_url:
|
|
return jsonify({
|
|
'success': False,
|
|
'request_url': '',
|
|
'output_info': 'Missing iframe_url in extra_config.',
|
|
'analysis': '测试失败:未配置 iframe URL。',
|
|
'http_status': 0,
|
|
'tested_at': tested_at
|
|
}), 400
|
|
try:
|
|
resp = requests.get(iframe_url, timeout=(5, 15), allow_redirects=True)
|
|
success = 200 <= resp.status_code < 400
|
|
if success and not agent.is_active:
|
|
agent.is_active = True
|
|
db.session.commit()
|
|
return jsonify({
|
|
'success': success,
|
|
'request_url': iframe_url,
|
|
'output_info': f'HTTP {resp.status_code}; response length={len(resp.text)}',
|
|
'analysis': '测试通过:iframe 地址可访问。' if success else '测试失败:iframe 地址不可访问或返回异常状态。',
|
|
'http_status': resp.status_code,
|
|
'tested_at': tested_at
|
|
}), 200
|
|
except requests.RequestException as e:
|
|
return jsonify({
|
|
'success': 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({
|
|
'success': False,
|
|
'request_url': '',
|
|
'output_info': 'Missing dify_api_key.',
|
|
'analysis': '测试失败:未配置 API Key。',
|
|
'http_status': 0,
|
|
'tested_at': tested_at
|
|
}), 400
|
|
|
|
base_url = (agent.api_base_url or Config.DIFY_API_BASE or '').rstrip('/')
|
|
if not base_url:
|
|
return jsonify({
|
|
'success': False,
|
|
'request_url': '',
|
|
'output_info': 'Missing api_base_url.',
|
|
'analysis': '测试失败:未配置 API Base URL。',
|
|
'http_status': 0,
|
|
'tested_at': tested_at
|
|
}), 400
|
|
|
|
request_url = f'{base_url}/chat-messages'
|
|
payload = {
|
|
'inputs': {},
|
|
'query': '系统连通性测试,请简短回复OK。',
|
|
'response_mode': 'blocking',
|
|
'conversation_id': '',
|
|
'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
|
|
success = False
|
|
analysis = f'测试失败:HTTP {resp.status_code}。'
|
|
|
|
try:
|
|
data = resp.json()
|
|
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():
|
|
success = True
|
|
analysis = '测试通过:接口连通正常,已成功返回回答。'
|
|
elif resp.ok:
|
|
analysis = '测试未通过:接口可访问,但未返回有效回答。'
|
|
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():
|
|
success = True
|
|
analysis = '测试通过:接口连通正常,返回了文本内容。'
|
|
|
|
if success and not agent.is_active:
|
|
agent.is_active = True
|
|
db.session.commit()
|
|
|
|
return jsonify({
|
|
'success': success,
|
|
'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({
|
|
'success': False,
|
|
'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: return jsonify({'error': 'Not found'}), 404
|
|
data = request.get_json() or {}
|
|
user_ids = data.get('user_ids', [])
|
|
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
|
|
|
# We need to update the relationship from the other side (User.agents)
|
|
# Strategy:
|
|
# 1. Find all users who currently have this agent
|
|
# 2. For users in user_ids but not in current list -> add agent
|
|
# 3. For users in current list but not in user_ids -> remove agent
|
|
|
|
# Current users with this agent
|
|
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)
|
|
|
|
# Add
|
|
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)
|
|
|
|
# Remove
|
|
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'})
|
|
|
|
# --- Users ---
|
|
@admin_bp.route('/users', methods=['GET'])
|
|
@require_admin
|
|
def list_users():
|
|
users = db.session.query(User).order_by(User.id.asc()).all()
|
|
res = []
|
|
for u in users:
|
|
res.append({
|
|
'id': u.id, 'username': u.username, 'email': u.email,
|
|
'department': u.department, 'role': u.role, 'status': u.status,
|
|
'real_name': u.real_name, 'employee_id': u.employee_id, 'phone_number': u.phone_number,
|
|
'agent_ids': [a.id for a in u.agents]
|
|
})
|
|
return jsonify(res)
|
|
|
|
@admin_bp.route('/users', methods=['POST'])
|
|
@require_admin
|
|
def create_user():
|
|
data = request.get_json() or {}
|
|
if not data.get('username'): return jsonify({'error': 'Username is required'}), 400
|
|
|
|
if db.session.query(User).filter_by(username=data['username']).first():
|
|
return jsonify({'error': 'Username exists'}), 400
|
|
|
|
user = User(
|
|
username=data['username'],
|
|
email=data.get('email'),
|
|
department=data.get('department'),
|
|
role=data.get('role', 'user'),
|
|
status=data.get('status', 'active'),
|
|
real_name=data.get('real_name'),
|
|
employee_id=data.get('employee_id'),
|
|
phone_number=data.get('phone_number')
|
|
)
|
|
if data.get('password'): 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)
|
|
db.session.commit()
|
|
return jsonify({'id': user.id}), 201
|
|
|
|
@admin_bp.route('/users/<int:id>', methods=['PUT'])
|
|
@require_admin
|
|
def update_user(id):
|
|
user = db.session.get(User, id)
|
|
if not user: return jsonify({'error': 'Not found'}), 404
|
|
data = request.get_json() or {}
|
|
|
|
for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
|
if k in data: setattr(user, k, data[k])
|
|
|
|
if data.get('password'): user.set_password(data['password'])
|
|
|
|
if 'agent_ids' in data:
|
|
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
|
user.agents = agents
|
|
|
|
db.session.commit()
|
|
return jsonify({'status': 'ok'})
|
|
|
|
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
|
@require_admin
|
|
def cleanup_rejected_users():
|
|
cnt = db.session.query(User).filter_by(status='rejected').delete()
|
|
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_id = request.headers.get('X-User-Id')
|
|
target_ids = [uid for uid in ids if str(uid) != str(current_user_id)]
|
|
if not target_ids: return jsonify({'error': 'No valid users'}), 400
|
|
cnt = db.session.query(User).filter(User.id.in_(target_ids)).delete(synchronize_session=False)
|
|
db.session.commit()
|
|
return jsonify({'deleted_count': cnt})
|
|
|
|
@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') # add, remove, set
|
|
|
|
if not user_ids:
|
|
return jsonify({'error': 'No users selected'}), 400
|
|
|
|
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 is set and agents is empty, it means clear permissions, which is valid
|
|
# But if action is add/remove and agents is empty, it's a no-op
|
|
if action == 'remove': return jsonify({'status': 'ok'})
|
|
# For add, we might want to warn or just do nothing
|
|
|
|
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)
|
|
|
|
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: return jsonify({'error': 'Not found'}), 404
|
|
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'})
|
|
|
|
|
|
# --- Permission Requests ---
|
|
@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: return jsonify({'error': 'Not found'}), 404
|
|
req.status = 'approved'
|
|
req.reviewed_at = datetime.utcnow()
|
|
|
|
# Grant permission
|
|
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)
|
|
|
|
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: return jsonify({'error': 'Not found'}), 404
|
|
req.status = 'rejected'
|
|
req.reviewed_at = datetime.utcnow()
|
|
db.session.commit()
|
|
return jsonify({'status': 'ok'})
|
|
|
|
|
|
# --- Quick Questions (Common Questions) ---
|
|
@admin_bp.route('/quick-questions', methods=['GET'])
|
|
@require_admin
|
|
def list_quick_questions():
|
|
# Only return global questions (user_id is NULL)
|
|
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'):
|
|
return jsonify({'error': 'Missing required fields'}), 400
|
|
|
|
qq = QuickQuestion(
|
|
user_id=None, # Global
|
|
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: return jsonify({'error': 'Not found'}), 404
|
|
|
|
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'})
|
|
|
|
|
|
# --- Reports ---
|
|
@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]
|
|
})
|
|
|
|
|
|
# --- Database ---
|
|
@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:
|
|
return jsonify({'error': 'Invalid table'}), 400
|
|
|
|
# Build query
|
|
query = db.session.query(model)
|
|
|
|
# Handle filters
|
|
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}%"))
|
|
|
|
# Use db.session.query instead of model.query to avoid ChatLog.query conflict
|
|
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:
|
|
return jsonify({'error': 'ids is required'}), 400
|
|
|
|
ids = []
|
|
for v in raw_ids:
|
|
try:
|
|
ids.append(int(v))
|
|
except (TypeError, ValueError):
|
|
continue
|
|
|
|
if not ids:
|
|
return jsonify({'error': 'No valid ids'}), 400
|
|
|
|
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:
|
|
return jsonify({'error': 'Invalid table'}), 400
|
|
|
|
total = db.session.query(func.count(model.id)).scalar()
|
|
return jsonify({'table': table, 'total': int(total or 0)})
|