feat: Initial commit with full deployment architecture and scripts
This commit is contained in:
commit
abb3efe114
96 files changed
+16789
No files matched your search
@@ -0,0 +1,427 @@
|
||||
"""
|
||||
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 import db
|
||||
from sqlalchemy import func, desc, inspect
|
||||
from datetime import datetime
|
||||
import csv
|
||||
import io
|
||||
|
||||
admin_bp = Blueprint('admin', __name__)
|
||||
|
||||
# --- 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'})
|
||||
|
||||
|
||||
# --- 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('/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)
|
||||
Reference in new issue
Block a user