feat: Initial commit with full deployment architecture and scripts

This commit is contained in:
super committed 2026-02-24 16:45:11 +08:00
commit abb3efe114
96 files changed
+16789

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
# backend/Dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
# 使用 Gunicorn + Gevent 启动
CMD ["gunicorn", "-c", "gunicorn_config.py", "run:app"]
+38
View File
@@ -0,0 +1,38 @@
"""
backend/app/__init__.py
应用工厂
"""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_cors import CORS
from app.config import config
db = SQLAlchemy()
migrate = Migrate()
def create_app(config_name='default'):
app = Flask(__name__)
app.config.from_object(config[config_name])
db.init_app(app)
migrate.init_app(app, db)
CORS(app) # 允许跨域
# 注册 Blueprints
from app.api.chat import chat_bp
from app.api.admin import admin_bp
from app.api.agents import agents_bp
from app.api.user import user_bp
# 聊天相关接口
app.register_blueprint(chat_bp, url_prefix='/api/chat')
# 管理员相关接口
app.register_blueprint(admin_bp, url_prefix='/api/admin')
# 普通用户可见的 Agent 列表接口
app.register_blueprint(agents_bp, url_prefix='/api/agents')
# 当前用户相关接口(首页、常用问题等)
app.register_blueprint(user_bp, url_prefix='/api/user')
return app
+427
View File
@@ -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)
+42
View File
@@ -0,0 +1,42 @@
"""
backend/app/api/agents.py
文件用途:普通用户可见的 Agent 列表接口
引用文件:flask, models, decorators
逻辑关系:根据当前用户的权限返回其可访问的 Agent 集合
"""
from flask import Blueprint, jsonify, g
from app.models import Agent, User
from app.decorators import _get_current_user # 内部工具函数
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
agents_bp = Blueprint('agents', __name__)
@agents_bp.route('', methods=['GET'])
def list_user_agents():
"""
获取当前用户可见的 Agent 列表
用途:Workspace 页面展示应用网格
"""
# 获取当前用户(目前固定为 admin 用户,用于演示)
user: User = _get_current_user()
# 管理员:返回所有激活的 Agent
if user.role == 'admin':
agents = Agent.query.filter_by(is_active=True).order_by(Agent.id.asc()).all()
else:
# 普通用户:仅返回多对多关系中已授权的 Agent
agents = [a for a in user.agents if a.is_active]
# 序列化为前端所需字段
data = [
{
'id': a.id,
'name': a.name,
'description': a.description,
'icon_url': a.icon_url,
}
for a in agents
]
return jsonify(data)
+195
View File
@@ -0,0 +1,195 @@
"""
backend/app/api/chat.py
文件用途:定义聊天相关 API 路由
引用文件:flask, services.dify, decorators, models
逻辑关系:作为前端与 Dify 之间的 BFF 层,负责转发请求并流式返回结果
"""
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app
from sqlalchemy import func, desc
from app.services.dify import DifyService
from app.decorators import require_agent_permission
from app.models import Agent, ChatLog, Feedback
from app import db
# 定义 Blueprint,用于在应用工厂中注册路由前缀 /api/chat
chat_bp = Blueprint('chat', __name__)
@chat_bp.route('/sessions', methods=['GET'])
@require_agent_permission
def get_chat_sessions():
"""
获取当前用户与当前 Agent 的历史会话列表
"""
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
return jsonify({'error': 'Missing context'}), 500
# 聚合查询:按 conversation_id 分组,获取最新时间
# 注意:这里简化处理,直接取最新一条记录的 query 作为标题(或者第一条,取决于需求)
# 为了性能,这里我们取 max(created_at) 和 max(query) - 这只是一个近似值
# 更严谨的做法是先查出 conversation_ids,再查详情。
# 这里为了简单,我们假设 query 不为空
# 修正逻辑:先查出最近的 20 个 conversation_id
subquery = db.session.query(
ChatLog.conversation_id,
func.max(ChatLog.created_at).label('last_active')
).filter_by(
user_id=user.id,
agent_id=agent.id
).group_by(ChatLog.conversation_id).subquery()
# 联表查询获取详细信息,按时间倒序
results = db.session.query(
subquery.c.conversation_id,
subquery.c.last_active,
ChatLog.query
).join(
ChatLog,
(ChatLog.conversation_id == subquery.c.conversation_id) &
(ChatLog.created_at == subquery.c.last_active)
).order_by(desc(subquery.c.last_active)).limit(20).all()
sessions = []
for row in results:
if not row.conversation_id:
continue
sessions.append({
'id': 0, # 前端需要 id key
'conversation_id': row.conversation_id,
'title': row.query[:30] + ('...' if len(row.query) > 30 else '') if row.query else 'New Chat',
'created_at': row.last_active.isoformat()
})
return jsonify(sessions)
@chat_bp.route('/messages', methods=['GET'])
@require_agent_permission
def get_chat_messages():
"""
获取指定会话的消息记录
"""
conversation_id = request.args.get('conversation_id')
if not conversation_id:
return jsonify([])
logs = ChatLog.query.filter_by(
conversation_id=conversation_id
).order_by(ChatLog.created_at.asc()).all()
messages = []
for log in logs:
messages.append({'role': 'user', 'content': log.query})
messages.append({'role': 'assistant', 'content': log.answer})
return jsonify(messages)
@chat_bp.route('/completions', methods=['POST'])
@require_agent_permission
def chat_completions():
"""
SSE 流式聊天接口
用途:接收前端问题,调用 DifyService.stream_chat,并以 text/event-stream 形式返回
核心逻辑:
1. 从请求体中读取 query / agent_id / conversation_id
2. 通过装饰器已完成权限校验,并在 g 中注入 current_user / current_agent
3. 使用 Flask 的 stream_with_context 包裹生成器,实现流式推送
传入参数:
无(从 request.json 读取)
返回值:
Flask Response 对象,mimetype=text/event-stream
"""
# 解析 JSON 请求体
data = request.get_json() or {}
# 提取用户提问内容
query = data.get('query')
# 提取会话 ID(可选)
conversation_id = data.get('conversation_id')
# 从全局 g 中获取装饰器注入的用户和 Agent 对象
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
# 安全兜底:如果装饰器未正确注入,返回错误
if user is None or agent is None:
return jsonify({'error': 'Missing user or agent context'}), 500
# 返回 SSE 响应,mimetype 设为 text/event-stream
return Response(
stream_with_context(
DifyService.stream_chat(query, user.id, agent, conversation_id)
),
mimetype='text/event-stream',
headers={
'Cache-Control': 'no-cache',
# 对于 Nginx 反向代理,需要关闭缓冲以支持实时流式传输
'X-Accel-Buffering': 'no'
}
)
@chat_bp.route('/feedback', methods=['POST'])
@require_agent_permission
def submit_feedback():
"""
提交对回答的评分与评论
用途:在对话结束后,由前端发送评分(1~5)和文字意见
核心逻辑:
1. 从请求体中读取 score/comment/conversation_id
2. 根据当前 user/agent 与 conversation_id 查找最近一条 ChatLog
3. 为该 ChatLog 创建或更新 Feedback 记录
"""
data = request.get_json() or {}
score = data.get('score')
comment = data.get('comment') or ''
conversation_id = data.get('conversation_id')
if not current_app.config.get('FEEDBACK_ENABLED', True):
return jsonify({'error': 'feedback is disabled'}), 403
if score is None:
return jsonify({'error': 'score is required'}), 400
try:
score_value = int(score)
except (TypeError, ValueError):
return jsonify({'error': 'score must be an integer'}), 400
if score_value < 1 or score_value > 5:
return jsonify({'error': 'score must be between 1 and 5'}), 400
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
return jsonify({'error': 'Missing user or agent context'}), 500
# 构造查询:限定在当前用户和 Agent 范围内
query = ChatLog.query.filter_by(user_id=user.id, agent_id=agent.id)
if conversation_id:
query = query.filter_by(conversation_id=conversation_id)
# 取最新一条对话日志
chat_log = query.order_by(ChatLog.created_at.desc()).first()
if not chat_log:
return jsonify({'error': 'ChatLog not found'}), 404
# 如果已存在反馈,则更新;否则新建
if chat_log.feedback:
chat_log.feedback.score = score_value
chat_log.feedback.comment = comment
else:
fb = Feedback(
chat_log_id=chat_log.id,
score=score_value,
comment=comment,
)
db.session.add(fb)
db.session.commit()
return jsonify({'status': 'ok'})
+191
View File
@@ -0,0 +1,191 @@
"""
backend/app/api/user.py
文件用途:用户相关 API 路由
引用文件:flask, models, decorators
逻辑关系:提供用户登录、首页配置、收藏夹、常用问题等接口
"""
from flask import Blueprint, jsonify, request, g, current_app
from app import db
from app.models import User, Agent, UserFavoriteAgent, UserHomepageConfig, QuickQuestion, UserDefaultAgent
from app.decorators import _get_current_user
user_bp = Blueprint('user', __name__)
@user_bp.route('/login', methods=['POST'])
def login():
data = request.get_json() or {}
username = data.get('username')
password = data.get('password')
user = User.query.filter_by(username=username).first()
if user and user.check_password(password):
return jsonify({
'id': user.id,
'username': user.username,
'role': user.role,
'token': 'dummy-token' # In real app use JWT
})
return jsonify({'error': 'Invalid credentials'}), 401
@user_bp.route('/home', methods=['GET'])
def get_user_home():
user = _get_current_user()
# Favorites
favorites = db.session.query(Agent).join(UserFavoriteAgent).filter(UserFavoriteAgent.user_id == user.id).all()
favorite_ids = [a.id for a in favorites]
# Layout
config = UserHomepageConfig.query.get(user.id)
layout = config.layout if config else {}
# Embedded agents
embedded_agents = []
udas = UserDefaultAgent.query.filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
for uda in udas:
agent = Agent.query.get(uda.agent_id)
if agent:
embedded_agents.append({
'id': agent.id,
'name': agent.name,
'icon_url': agent.icon_url,
'description': agent.description
})
# Quick questions
qqs = QuickQuestion.query.filter_by(user_id=user.id).all()
quick_questions = [{
'id': q.id,
'title': q.title,
'question': q.question,
'agent_id': q.agent_id
} for q in qqs]
# All active agents (for selection)
all_agents = Agent.query.filter_by(is_active=True).all()
agents_list = [{
'id': a.id,
'name': a.name
} for a in all_agents]
return jsonify({
'user': {
'id': user.id,
'username': user.username,
'role': user.role,
'real_name': user.real_name,
'department': user.department
},
'favorite_agent_ids': favorite_ids,
'layout': layout,
'embedded_agents': embedded_agents,
'quick_questions': quick_questions,
'agents': agents_list
})
@user_bp.route('/agents/<int:agent_id>', methods=['GET'])
def get_agent_details(agent_id):
"""
获取单个 Agent 详情
"""
user = _get_current_user()
agent = Agent.query.get(agent_id)
if not agent:
return jsonify({'error': 'Agent not found'}), 404
# Check permission (optional, but good practice)
# For now, allow if active or user is admin
if not agent.is_active and user.role != 'admin':
return jsonify({'error': 'Agent is not active'}), 403
return jsonify({
'id': agent.id,
'name': agent.name,
'description': agent.description,
'icon_url': agent.icon_url,
'type': agent.type,
'extra_config': agent.extra_config
})
@user_bp.route('/config', methods=['GET'])
def get_user_config():
"""
获取用户/系统配置
"""
user = _get_current_user()
return jsonify({
'feedback_enabled': current_app.config.get('FEEDBACK_ENABLED', True)
})
@user_bp.route('/favorites/<int:agent_id>', methods=['POST'])
def add_favorite(agent_id):
user = _get_current_user()
if not UserFavoriteAgent.query.filter_by(user_id=user.id, agent_id=agent_id).first():
fav = UserFavoriteAgent(user_id=user.id, agent_id=agent_id)
db.session.add(fav)
db.session.commit()
return jsonify({'status': 'ok'})
@user_bp.route('/favorites/<int:agent_id>', methods=['DELETE'])
def remove_favorite(agent_id):
user = _get_current_user()
fav = UserFavoriteAgent.query.filter_by(user_id=user.id, agent_id=agent_id).first()
if fav:
db.session.delete(fav)
db.session.commit()
return jsonify({'status': 'ok'})
@user_bp.route('/homepage-layout', methods=['PUT'])
def update_layout():
user = _get_current_user()
data = request.get_json() or {}
config = UserHomepageConfig.query.get(user.id)
if not config:
config = UserHomepageConfig(user_id=user.id)
db.session.add(config)
config.layout = data.get('layout', {})
db.session.commit()
return jsonify({'status': 'ok'})
@user_bp.route('/embedded-agents', methods=['PUT'])
def update_embedded_agents():
user = _get_current_user()
data = request.get_json() or {}
agent_ids = data.get('agent_ids', [])
if len(agent_ids) > 2:
return jsonify({'error': 'Max 2 embedded agents'}), 400
# Clear existing
UserDefaultAgent.query.filter_by(user_id=user.id).delete()
for i, aid in enumerate(agent_ids):
uda = UserDefaultAgent(user_id=user.id, agent_id=aid, sort_order=i)
db.session.add(uda)
db.session.commit()
return jsonify({'status': 'ok'})
@user_bp.route('/quick-questions/<int:qq_id>', methods=['PUT'])
def update_quick_question(qq_id: int):
"""
更新常用问题
"""
user = _get_current_user()
data = request.get_json() or {}
qq = db.session.query(QuickQuestion).filter_by(id=qq_id, user_id=user.id).first()
if not qq:
return jsonify({"error": "QuickQuestion not found"}), 404
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']
db.session.commit()
return jsonify({"status": "ok"})
+56
View File
@@ -0,0 +1,56 @@
"""
backend/app/config.py
配置类,区分开发/生产环境
"""
import os
class Config:
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.getenv('SECRET_KEY', 'dev-secret-key')
# 数据库连接池配置
SQLALCHEMY_ENGINE_OPTIONS = {
'pool_size': 20,
'max_overflow': 10,
'pool_recycle': 3600,
'pool_pre_ping': True
}
# Dify 网关配置
DIFY_API_BASE = os.getenv('DIFY_API_BASE', 'https://api.dify.ai/v1')
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
# Redis 连接配置,默认使用本地 Redis + 密码
REDIS_URL = os.getenv('REDIS_URL', 'redis://:difyai123456@localhost:6379/0')
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
HR_WORKFLOW_IFRAME_URL = os.getenv(
'HR_WORKFLOW_IFRAME_URL',
'http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg'
)
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE', 'http://127.0.0.1:5001/v1')
HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY')
class DevelopmentConfig(Config):
DEBUG = True
# 本地 MacBook PostgreSQL 配置(数据库: hxops_db,用户: postgres, 密码: difyai123456)
SQLALCHEMY_DATABASE_URI = os.getenv(
'DATABASE_URL',
'postgresql://postgres:difyai123456@localhost:5432/hxops_db'
)
class ProductionConfig(Config):
DEBUG = False
# 服务器 Ubuntu PostgreSQL 配置
# 注意:在服务器上通过环境变量覆盖,但此处保留默认模板
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL', 'postgresql://postgres:difyai123456@localhost:5432/hxops_prod')
class TestingConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
WTF_CSRF_ENABLED = False
SQLALCHEMY_ENGINE_OPTIONS = {}
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
}
+138
View File
@@ -0,0 +1,138 @@
"""
backend/app/decorators.py
文件用途:权限控制装饰器集合
引用文件:flask, functools, models, db
逻辑关系:为需要鉴权的 API 提供统一的用户获取、权限校验入口
"""
from functools import wraps
from flask import request, jsonify, g
from app import db
from app.models import Agent, User
def _get_current_user() -> User:
"""
内部工具函数:获取当前登录用户
支持从请求头识别用户并创建用户,读取 X-User-Id / X-Username / X-Role。
"""
user_id = request.headers.get('X-User-Id')
username = request.headers.get('X-Username')
role = request.headers.get('X-Role', 'user')
user = None
if user_id:
try:
user = User.query.get(int(user_id))
except ValueError:
user = None
if user is None and username:
user = User.query.filter_by(username=username).first()
if not user:
if user_id:
safe_id = int(user_id)
user = User(
id=safe_id,
username=username or f'user_{safe_id}',
email=f'{username or f"user_{safe_id}"}@example.com',
department='IT',
role=role,
)
db.session.add(user)
db.session.commit()
elif username:
user = User(
username=username,
email=f'{username}@example.com',
department='IT',
role=role,
)
db.session.add(user)
db.session.commit()
else:
# Check if guest user exists
user = User.query.filter_by(username='guest').first()
if not user:
user = User(
username='guest',
email='guest@example.com',
department='',
role='guest',
)
db.session.add(user)
db.session.commit()
g.current_user = user
return user
def require_agent_permission(f):
"""
装饰器:检查当前用户是否有指定 Agent 的访问权限
核心逻辑:
1. 从请求体中读取 agent_id
2. 获取当前用户 (临时固定为 ID=1)
3. 如果用户是 admin,则放行
4. 否则检查 user.agents 是否包含该 agent
传入参数:
f: 被装饰的视图函数
返回值:
包装后的视图函数
"""
@wraps(f)
def decorated_function(*args, **kwargs):
# 从 JSON 请求体中解析数据
data = request.get_json() or {}
# 获取 agent_id
agent_id = data.get('agent_id')
# 如果未提供 agent_id,则返回 400 错误
if not agent_id:
return jsonify({'error': 'agent_id is required'}), 400
# 获取当前用户(此处固定为 admin 用户,用于演示)
user = _get_current_user()
# 查询目标 Agent 是否存在
agent = Agent.query.get(agent_id)
if not agent:
return jsonify({'error': 'Agent not found'}), 404
# 将 agent 对象挂在 g 上,方便下游使用
g.current_agent = agent
# 如果用户是管理员,跳过权限检查直接放行
if user.role == 'admin':
return f(*args, **kwargs)
# 非管理员:检查多对多关联表中是否存在权限
if agent not in user.agents:
return jsonify({'error': 'Permission denied for this agent'}), 403
# 鉴权通过,调用原始视图函数
return f(*args, **kwargs)
return decorated_function
def require_admin(f):
"""
装饰器:限制只有管理员角色才能访问的接口
核心逻辑:
1. 获取当前用户
2. 判断 user.role 是否为 'admin'
"""
@wraps(f)
def decorated_function(*args, **kwargs):
# 获取当前用户(自动创建 admin)
user = _get_current_user()
# 如果不是管理员,则返回 403
if user.role != 'admin':
return jsonify({'error': 'Admin privilege required'}), 403
# 是管理员则放行
return f(*args, **kwargs)
return decorated_function
+237
View File
@@ -0,0 +1,237 @@
from datetime import datetime
from typing import Optional, List
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app import db
class Base(db.Model):
"""
基础模型类,设置为抽象基类
"""
__abstract__ = True
# RBAC 关联表:用户与 Agent 的多对多关系
# 用于存储用户拥有哪些 Agent 的访问权限
user_agent_permissions = db.Table(
'user_agent_permissions',
db.Column('user_id', ForeignKey('users.id'), primary_key=True),
db.Column('agent_id', ForeignKey('agents.id'), primary_key=True)
)
from werkzeug.security import generate_password_hash, check_password_hash
class ZlLanguage(Base):
"""
多语言配置表
用途:存储系统支持的语言列表
"""
__tablename__ = 'zl_languages'
id: Mapped[int] = mapped_column(primary_key=True)
code: Mapped[str] = mapped_column(String(10), unique=True) # en, zh-CN, zh-TW, th
name: Mapped[str] = mapped_column(String(50)) # English, 简体中文, ...
is_active: Mapped[bool] = mapped_column(default=True)
class Department(Base):
"""
部门表
用途:存储公司部门列表
"""
__tablename__ = 'departments'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100), unique=True)
code: Mapped[Optional[str]] = mapped_column(String(50), unique=True) # 部门编号
company: Mapped[Optional[str]] = mapped_column(String(100)) # 所属公司
description: Mapped[Optional[str]] = mapped_column(Text)
class UserHomepageConfig(Base):
"""
用户首页配置表
用途:存储用户自定义的首页布局与配置
"""
__tablename__ = 'user_homepage_configs'
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
layout: Mapped[dict] = mapped_column(JSON, default={}) # 存储模块布局配置
# 示例: { "modules": [{"id": "favorites", "x": 0, "y": 0}, {"id": "agents", "x": 0, "y": 1}] }
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
class UserFavoriteAgent(Base):
"""
用户收藏 Agent 表
用途:存储用户收藏的 Agent
"""
__tablename__ = 'user_favorite_agents'
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), primary_key=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
class UserDefaultAgent(Base):
"""
用户默认 Agent 表 (嵌入首页)
用途:存储用户设置的默认嵌入 Agent (最多2个)
"""
__tablename__ = 'user_default_agents'
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
sort_order: Mapped[int] = mapped_column(default=0) # 排序,0为第一个,1为第二个
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
class User(Base):
"""
用户表
用途:存储系统用户信息
核心逻辑:包含部门、角色等字段,关联 Agent 权限
"""
__tablename__ = 'users'
# 主键 ID
id: Mapped[int] = mapped_column(primary_key=True)
# 用户名,唯一且带索引
username: Mapped[str] = mapped_column(String(50), unique=True, index=True)
# 邮箱,唯一
email: Mapped[str] = mapped_column(String(100), unique=True)
# 部门信息
department: Mapped[Optional[str]] = mapped_column(String(100))
# 角色:admin 或 user
role: Mapped[str] = mapped_column(String(20), default='user')
# 账号状态:active (正常), pending (待审批), disabled (禁用)
status: Mapped[str] = mapped_column(String(20), default='active')
# 密码哈希
password_hash: Mapped[Optional[str]] = mapped_column(String(255))
# 首选语言
language: Mapped[str] = mapped_column(String(10), default='zh-CN')
# 真实姓名
real_name: Mapped[Optional[str]] = mapped_column(String(50))
# 公司工号,唯一
employee_id: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
# 手机号,唯一
phone_number: Mapped[Optional[str]] = mapped_column(String(20), unique=True)
# 默认嵌入的 Agent ID (忽略权限检查)
default_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'))
# 关系:用户拥有的 Agent 权限 (多对多)
agents: Mapped[List["Agent"]] = relationship(
secondary=user_agent_permissions,
back_populates="users"
)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
if not self.password_hash:
return False
return check_password_hash(self.password_hash, password)
class Agent(Base):
"""
AI 应用配置表
用途:存储接入的 Dify Agent 配置信息
核心逻辑:存储 Dify App ID 和 API Key,控制应用开关
"""
__tablename__ = 'agents'
id: Mapped[int] = mapped_column(primary_key=True)
# 应用名称
name: Mapped[str] = mapped_column(String(100))
# 应用描述
description: Mapped[Optional[str]] = mapped_column(Text)
# 图标 URL
icon_url: Mapped[Optional[str]] = mapped_column(String(255))
# Dify 配置:App ID (唯一,对于 iframe 模式可选)
dify_app_id: Mapped[Optional[str]] = mapped_column(String(100), unique=True, nullable=True)
# Dify 配置:API Key (实际生产应加密存储,对于 iframe 模式可选)
dify_api_key: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
# 类型:api (默认) 或 iframe
type: Mapped[str] = mapped_column(String(20), default='api')
# 自定义 API Base URL (覆盖全局配置)
api_base_url: Mapped[Optional[str]] = mapped_column(String(255))
# 额外配置 (JSON),用于存储 iframe_url 等
extra_config: Mapped[Optional[dict]] = mapped_column(JSON)
# 是否激活
is_active: Mapped[bool] = mapped_column(default=True)
# 创建时间
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
# 关系:拥有该应用权限的用户 (多对多)
users: Mapped[List["User"]] = relationship(
secondary=user_agent_permissions,
back_populates="agents"
)
class ChatLog(Base):
"""
对话日志表
用途:存储用户与 Agent 的对话记录
"""
__tablename__ = 'chat_logs'
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
query: Mapped[str] = mapped_column(Text)
answer: Mapped[str] = mapped_column(Text)
latency: Mapped[float] = mapped_column(default=0.0) # 响应耗时
conversation_id: Mapped[Optional[str]] = mapped_column(String(100)) # Dify 会话 ID
tokens_used: Mapped[Optional[int]] = mapped_column(Integer, default=0) # 消耗 token 数
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
# 关联 Feedback
feedback: Mapped[Optional["Feedback"]] = relationship(back_populates="chat_log", uselist=False)
class Feedback(Base):
"""
反馈表
用途:存储用户对回答的评分与评价
"""
__tablename__ = 'feedbacks'
id: Mapped[int] = mapped_column(primary_key=True)
chat_log_id: Mapped[int] = mapped_column(ForeignKey('chat_logs.id'), unique=True)
score: Mapped[int] = mapped_column(Integer) # 1-5
comment: Mapped[Optional[str]] = mapped_column(Text)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
chat_log: Mapped["ChatLog"] = relationship(back_populates="feedback")
class PermissionRequest(Base):
"""
权限申请表
用途:存储用户的权限申请记录
"""
__tablename__ = 'permission_requests'
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
reason: Mapped[str] = mapped_column(Text)
status: Mapped[str] = mapped_column(String(20), default='pending') # pending, approved, rejected
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
reviewed_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
class QuickQuestion(Base):
"""
常用问题表
用途:存储用户自定义的常用问题
"""
__tablename__ = 'quick_questions'
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
title: Mapped[str] = mapped_column(String(100))
question: Mapped[str] = mapped_column(Text)
sort_order: Mapped[int] = mapped_column(default=0)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
+137
View File
@@ -0,0 +1,137 @@
"""
backend/app/services/dify.py
文件用途:Dify API 集成服务
引用文件:requests, json, models, config
逻辑关系:负责与 Dify 平台进行 HTTP 通信,处理 SSE 流式响应,并记录审计日志
"""
import requests
import json
import time
from flask import current_app
from app.models import ChatLog, db
from app.config import Config
class DifyService:
"""
Dify 服务类
用途:封装与 Dify API 的交互逻辑
"""
@staticmethod
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
"""
生成器函数:向 Dify 发起请求并流式返回
用途:处理 /v1/chat-messages 接口的流式响应
核心逻辑:
1. 构造请求头与 Payload
2. 使用 requests.post(stream=True) 发起请求
3. 逐行读取 SSE 数据
4. 解析 'data: ' 开头的行,透传给前端
5. 在 'message_end' 事件中记录完整日志到数据库
参数:
query: 用户提问内容
user_id: 当前用户 ID
agent: Agent 模型对象,包含 API Key
conversation_id: 会话 ID (可选)
输出:
Yields SSE 格式字符串 "data: {...}\n\n"
"""
# 使用 Agent 自定义的 API Base URL,若未配置则使用全局配置
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
# 移除末尾斜杠以避免双斜杠问题
base_url = base_url.rstrip('/')
url = f"{base_url}/chat-messages"
headers = {
'Authorization': f'Bearer {agent.dify_api_key}',
'Content-Type': 'application/json'
}
payload = {
"inputs": {},
"query": query,
"response_mode": "streaming",
"conversation_id": conversation_id,
"user": str(user_id)
}
# 记录开始时间,用于计算耗时
start_time = time.time()
# 用于收集流式片段拼接完整回答
full_answer = []
try:
# stream=True 关键参数,建立长连接
# 设置连接超时为 5 秒,读取超时为 60 秒
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response:
response.raise_for_status()
# 逐行迭代响应内容
for line in response.iter_lines():
if line:
decoded_line = line.decode('utf-8')
# 识别 SSE 数据行
if decoded_line.startswith('data: '):
json_str = decoded_line[6:]
try:
data = json.loads(json_str)
event = data.get('event')
# 核心:将 Dify 的原始数据透传给前端
yield f"data: {json_str}\n\n"
# 收集完整回答用于日志
if event == 'message':
full_answer.append(data.get('answer', ''))
elif event == 'message_end':
# 对话结束,记录日志
# 异步或在此处记录日志(为了演示简单,此处同步记录,生产环境建议放入 Celery/RQ)
latency = int((time.time() - start_time) * 1000)
metadata = data.get('metadata', {})
usage = metadata.get('usage', {})
# 创建日志条目
# 注意:在生成器中操作 DB 需要确保应用上下文存在
DifyService._log_chat(
user_id=user_id,
agent_id=agent.id,
conversation_id=data.get('conversation_id'),
query=query,
answer="".join(full_answer),
tokens=usage.get('total_tokens', 0),
latency=latency
)
except json.JSONDecodeError:
continue
else:
# 处理 keep-alive 等其他行
pass
except requests.exceptions.RequestException as e:
# 异常处理:返回标准错误格式给前端
error_msg = json.dumps({"event": "error", "message": str(e)})
yield f"data: {error_msg}\n\n"
@staticmethod
def _log_chat(user_id, agent_id, conversation_id, query, answer, tokens, latency):
"""
内部方法:写入数据库日志
用途:将对话详情持久化到 ChatLog 表
"""
try:
# 确保在应用上下文中(Flask stream_with_context 会保持上下文)
chat_log = ChatLog(
user_id=user_id,
agent_id=agent_id,
conversation_id=conversation_id,
query=query,
answer=answer,
tokens_used=tokens,
latency=latency
)
db.session.add(chat_log)
db.session.commit()
except Exception as e:
current_app.logger.error(f"Failed to log chat: {e}")
db.session.rollback()
+9
View File
@@ -0,0 +1,9 @@
from app import create_app, db
from app.models import User
app = create_app()
with app.app_context():
users = User.query.all()
for u in users:
print(f"ID: {u.id}, User: {u.username}, Role: {u.role}")
+40
View File
@@ -0,0 +1,40 @@
"""
gunicorn_config.py
Gunicorn 生产环境配置文件
"""
import multiprocessing
import os
# 绑定地址
bind = "127.0.0.1:5000"
# 工作模式
# 使用 gevent 处理高并发和长连接 (SSE)
worker_class = "gevent"
# 进程数
# 公式: 2 * CPU核心数 + 1
workers = multiprocessing.cpu_count() * 2 + 1
# 每个 Worker 的最大并发连接数
worker_connections = 1000
# 超时设置 (秒)
# SSE 流式响应通常需要较长的超时时间
timeout = 120
keepalive = 5
# 日志
accesslog = "/var/log/hxops/access.log"
errorlog = "/var/log/hxops/error.log"
loglevel = "info"
# 守护进程模式 (由 Supervisor 管理时通常设为 False)
daemon = False
# 进程名称
proc_name = "hxops_backend"
# 预加载应用 (加快启动速度)
preload_app = True
+26
View File
@@ -0,0 +1,26 @@
from app import create_app, db
from app.models import User
app = create_app()
with app.app_context():
# Check for admin user
admin = User.query.filter_by(username='admin').first()
if admin:
print(f"Found admin user. Current role: {admin.role}")
if admin.role != 'admin':
admin.role = 'admin'
db.session.commit()
print("Updated admin user role to 'admin'")
else:
print("Admin user not found. Creating...")
admin = User(username='admin', email='admin@example.com', role='admin')
admin.set_password('Hxit@54321')
db.session.add(admin)
db.session.commit()
print("Created admin user with role 'admin'")
# Also check if there are other users that should be admin but aren't
users = User.query.all()
for u in users:
print(f"User: {u.username}, Role: {u.role}")
+28
View File
@@ -0,0 +1,28 @@
"""
backend/gunicorn_config.py
生产环境 Gunicorn 配置 (支持高并发)
"""
import multiprocessing
# 绑定地址
bind = "0.0.0.0:8000"
# 核心:使用 Gevent 异步 Worker
worker_class = "gevent"
# Worker 数量:通常 CPU 核数 * 2 + 1
workers = multiprocessing.cpu_count() * 2 + 1
# 核心:每个 Worker 最大并发连接数
# Gevent 下这个值可以设置得很高,支持海量 SSE 连接
worker_connections = 2000
# 超时设置 (SSE 长连接需要较长超时)
timeout = 120
keepalive = 5
# 日志
accesslog = "-"
errorlog = "-"
loglevel = "info"
+108
View File
@@ -0,0 +1,108 @@
"""
backend/init_db.py
文件用途:初始化 PostgreSQL 数据库 hxops_db 并创建所有表
引用文件:psycopg2, urllib.parse, app
逻辑关系:
1. 从配置中解析 SQLALCHEMY_DATABASE_URI
2. 连接 postgres 系统库,检查 hxops_db 是否存在,不存在则创建
3. 使用 Flask 应用上下文调用 db.create_all() 创建所有表结构
使用方式:
在项目根目录下执行:
cd backend
python init_db.py
"""
import urllib.parse
import psycopg2
from app import create_app, db
from app.config import DevelopmentConfig
def _parse_db_url(url: str):
"""
解析 SQLAlchemy 风格的数据库 URL
输入示例: postgresql://user:password@localhost:5432/hxops_db
输出:字典包含 user/password/host/port/dbname
"""
# 使用 urllib.parse 解析 URL
parsed = urllib.parse.urlparse(url)
# 从 netloc 中解析用户名和密码
if parsed.username:
user = urllib.parse.unquote(parsed.username)
else:
user = 'postgres'
if parsed.password:
password = urllib.parse.unquote(parsed.password)
else:
password = ''
host = parsed.hostname or 'localhost'
port = parsed.port or 5432
# 去掉路径前导斜杠得到数据库名
dbname = parsed.path.lstrip('/') or 'postgres'
return {
'user': user,
'password': password,
'host': host,
'port': port,
'dbname': dbname,
}
def ensure_database():
"""
确保 hxops_db 数据库存在
核心逻辑:
1. 解析 DevelopmentConfig.SQLALCHEMY_DATABASE_URI
2. 使用 psycopg2 连接到 postgres 系统数据库
3. 查询 pg_database,如果不存在则执行 CREATE DATABASE
"""
# 从开发配置中获取数据库 URL
url = DevelopmentConfig.SQLALCHEMY_DATABASE_URI
info = _parse_db_url(url)
target_db = info['dbname']
# 连接系统数据库 postgres
conn = psycopg2.connect(
dbname='postgres',
user=info['user'],
password=info['password'],
host=info['host'],
port=info['port'],
)
conn.autocommit = True
try:
cur = conn.cursor()
# 查询目标数据库是否已存在
cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", (target_db,))
exists = cur.fetchone() is not None
if not exists:
# 创建数据库
cur.execute(f'CREATE DATABASE "{target_db}"')
print(f'Created database {target_db}')
else:
print(f'Database {target_db} already exists')
cur.close()
finally:
conn.close()
def create_tables():
"""
在 hxops_db 中创建所有表结构
核心逻辑:
1. 创建 Flask 应用实例
2. 在应用上下文中调用 db.create_all()
"""
app = create_app('development')
with app.app_context():
db.create_all()
print('All tables created in hxops_db')
if __name__ == '__main__':
# 第一步:确保数据库存在
ensure_database()
# 第二步:创建所有表
create_tables()
+55
View File
@@ -0,0 +1,55 @@
from app import create_app, db
from app.models import Agent
import uuid
app = create_app()
with app.app_context():
# 1. 方式一:嵌入到网站中 (Iframe)
# <iframe src=" http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg " style="width: 100%; height: 100%; min-height: 700px" frameborder="0" allow="microphone"> </iframe>
agent_iframe = Agent.query.filter_by(name='人事规章(网页版)').first()
if not agent_iframe:
agent_iframe = Agent(
name='人事规章(网页版)',
description='嵌入式人事规章助手',
dify_app_id=str(uuid.uuid4()), # Placeholder unique ID
dify_api_key='placeholder',
type='iframe',
extra_config={'iframe_url': 'http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg'},
icon_url='ri-article-line'
)
db.session.add(agent_iframe)
print("Added Iframe Agent")
else:
agent_iframe.type = 'iframe'
agent_iframe.extra_config = {'iframe_url': 'http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg'}
agent_iframe.icon_url = 'ri-article-line'
print("Updated Iframe Agent")
# 2. 方式二:API
# 基础URL: http://127.0.0.1:5001/v1
# API密钥:app-xdiejQibWQy8ZQWXcdxJjS9I
agent_api = Agent.query.filter_by(name='人事规章(API版)').first()
if not agent_api:
agent_api = Agent(
name='人事规章(API版)',
description='API调用人事规章助手',
dify_app_id=str(uuid.uuid4()), # Placeholder unique ID
dify_api_key='app-xdiejQibWQy8ZQWXcdxJjS9I',
type='api',
api_base_url='http://127.0.0.1:5001/v1',
icon_url='ri-robot-line'
)
db.session.add(agent_api)
print("Added API Agent")
else:
agent_api.type = 'api'
agent_api.dify_api_key = 'app-xdiejQibWQy8ZQWXcdxJjS9I'
agent_api.api_base_url = 'http://127.0.0.1:5001/v1'
agent_api.icon_url = 'ri-robot-line'
print("Updated API Agent")
db.session.commit()
+15
View File
@@ -0,0 +1,15 @@
"""
backend/manage.py
数据库迁移管理脚本
"""
from app import create_app, db
from flask_migrate import Migrate
app = create_app('development')
migrate = Migrate(app, db)
if __name__ == '__main__':
# 仅作为 CLI 入口
# 使用: flask --app manage db init/migrate/upgrade
pass
+1
View File
@@ -0,0 +1 @@
Single-database configuration for Flask.
+50
View File
@@ -0,0 +1,50 @@
# A generic, single database configuration.
[alembic]
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic,flask_migrate
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[logger_flask_migrate]
level = INFO
handlers =
qualname = flask_migrate
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
+113
View File
@@ -0,0 +1,113 @@
import logging
from logging.config import fileConfig
from flask import current_app
from alembic import context
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')
def get_engine():
try:
# this works with Flask-SQLAlchemy<3 and Alchemical
return current_app.extensions['migrate'].db.get_engine()
except (TypeError, AttributeError):
# this works with Flask-SQLAlchemy>=3
return current_app.extensions['migrate'].db.engine
def get_engine_url():
try:
return get_engine().url.render_as_string(hide_password=False).replace(
'%', '%%')
except AttributeError:
return str(get_engine().url).replace('%', '%%')
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
config.set_main_option('sqlalchemy.url', get_engine_url())
target_db = current_app.extensions['migrate'].db
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def get_metadata():
if hasattr(target_db, 'metadatas'):
return target_db.metadatas[None]
return target_db.metadata
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url, target_metadata=get_metadata(), literal_binds=True
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
logger.info('No changes in schema detected.')
conf_args = current_app.extensions['migrate'].configure_args
if conf_args.get("process_revision_directives") is None:
conf_args["process_revision_directives"] = process_revision_directives
connectable = get_engine()
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=get_metadata(),
**conf_args
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+24
View File
@@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}
@@ -0,0 +1,34 @@
"""add phone_number to user
Revision ID: 08f34c125a73
Revises: 5b797d05f412
Create Date: 2026-02-23 17:10:37.613505
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '08f34c125a73'
down_revision = '5b797d05f412'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('phone_number', sa.String(length=20), nullable=True))
batch_op.create_unique_constraint(None, ['phone_number'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='unique')
batch_op.drop_column('phone_number')
# ### end Alembic commands ###
@@ -0,0 +1,32 @@
"""add_tokens_used_to_chatlog
Revision ID: 439e501ac52b
Revises: 7797942bfa85
Create Date: 2026-02-24 08:51:08.086113
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '439e501ac52b'
down_revision = '7797942bfa85'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.add_column(sa.Column('tokens_used', sa.Integer(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.drop_column('tokens_used')
# ### end Alembic commands ###
@@ -0,0 +1,34 @@
"""Add default_agent_id to User
Revision ID: 48f1ca8fa73a
Revises: 08f34c125a73
Create Date: 2026-02-23 20:39:30.511482
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '48f1ca8fa73a'
down_revision = '08f34c125a73'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('default_agent_id', sa.Integer(), nullable=True))
batch_op.create_foreign_key(None, 'agents', ['default_agent_id'], ['id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='foreignkey')
batch_op.drop_column('default_agent_id')
# ### end Alembic commands ###
@@ -0,0 +1,50 @@
"""Initial migration
Revision ID: 510db8a4f806
Revises:
Create Date: 2026-02-23 11:16:09.218508
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '510db8a4f806'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('agents', schema=None) as batch_op:
batch_op.alter_column('type',
existing_type=sa.VARCHAR(length=20),
nullable=False,
existing_server_default=sa.text("'api'::character varying"))
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.alter_column('status',
existing_type=sa.VARCHAR(length=20),
nullable=False,
existing_server_default=sa.text("'active'::character varying"))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.alter_column('status',
existing_type=sa.VARCHAR(length=20),
nullable=True,
existing_server_default=sa.text("'active'::character varying"))
with op.batch_alter_table('agents', schema=None) as batch_op:
batch_op.alter_column('type',
existing_type=sa.VARCHAR(length=20),
nullable=True,
existing_server_default=sa.text("'api'::character varying"))
# ### end Alembic commands ###
@@ -0,0 +1,36 @@
"""Add real_name and employee_id
Revision ID: 5b797d05f412
Revises: 80382a78c530
Create Date: 2026-02-23 12:43:47.707814
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5b797d05f412'
down_revision = '80382a78c530'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('real_name', sa.String(length=50), nullable=True))
batch_op.add_column(sa.Column('employee_id', sa.String(length=50), nullable=True))
batch_op.create_unique_constraint(None, ['employee_id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='unique')
batch_op.drop_column('employee_id')
batch_op.drop_column('real_name')
# ### end Alembic commands ###
@@ -0,0 +1,34 @@
"""Add Department table
Revision ID: 60b4aee3ad2d
Revises: 48f1ca8fa73a
Create Date: 2026-02-23 20:56:21.095082
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '60b4aee3ad2d'
down_revision = '48f1ca8fa73a'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('departments',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('departments')
# ### end Alembic commands ###
@@ -0,0 +1,32 @@
"""add_conversation_id_to_chatlog
Revision ID: 7797942bfa85
Revises: b1246a8b37fa
Create Date: 2026-02-24 08:50:46.391292
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7797942bfa85'
down_revision = 'b1246a8b37fa'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.add_column(sa.Column('conversation_id', sa.String(length=100), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.drop_column('conversation_id')
# ### end Alembic commands ###
@@ -0,0 +1,97 @@
"""add_zl_language_and_user_lang
Revision ID: 80382a78c530
Revises: 510db8a4f806
Create Date: 2026-02-23 12:06:43.705586
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '80382a78c530'
down_revision = '510db8a4f806'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('zl_languages',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('code', sa.String(length=10), nullable=False),
sa.Column('name', sa.String(length=50), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('code')
)
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.add_column(sa.Column('latency', sa.Float(), nullable=False, server_default='0.0'))
batch_op.alter_column('answer',
existing_type=sa.TEXT(),
nullable=False)
batch_op.drop_index(batch_op.f('ix_chat_logs_agent_id'))
batch_op.drop_index(batch_op.f('ix_chat_logs_conversation_id'))
batch_op.drop_index(batch_op.f('ix_chat_logs_created_at'))
batch_op.drop_index(batch_op.f('ix_chat_logs_user_id'))
batch_op.drop_column('tokens_used')
batch_op.drop_column('conversation_id')
batch_op.drop_column('latency_ms')
with op.batch_alter_table('feedbacks', schema=None) as batch_op:
batch_op.add_column(sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()))
batch_op.drop_column('tags')
with op.batch_alter_table('permission_requests', schema=None) as batch_op:
batch_op.alter_column('reason',
existing_type=sa.TEXT(),
nullable=False)
batch_op.drop_index(batch_op.f('ix_permission_requests_agent_id'))
batch_op.drop_index(batch_op.f('ix_permission_requests_user_id'))
with op.batch_alter_table('quick_questions', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_quick_questions_agent_id'))
batch_op.drop_index(batch_op.f('ix_quick_questions_user_id'))
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('language', sa.String(length=10), nullable=False, server_default='zh-CN'))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_column('language')
with op.batch_alter_table('quick_questions', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_quick_questions_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_quick_questions_agent_id'), ['agent_id'], unique=False)
with op.batch_alter_table('permission_requests', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_permission_requests_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_permission_requests_agent_id'), ['agent_id'], unique=False)
batch_op.alter_column('reason',
existing_type=sa.TEXT(),
nullable=True)
with op.batch_alter_table('feedbacks', schema=None) as batch_op:
batch_op.add_column(sa.Column('tags', postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=True))
batch_op.drop_column('created_at')
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.add_column(sa.Column('latency_ms', sa.INTEGER(), autoincrement=False, nullable=False))
batch_op.add_column(sa.Column('conversation_id', sa.VARCHAR(length=100), autoincrement=False, nullable=False))
batch_op.add_column(sa.Column('tokens_used', sa.INTEGER(), autoincrement=False, nullable=False))
batch_op.create_index(batch_op.f('ix_chat_logs_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_created_at'), ['created_at'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_conversation_id'), ['conversation_id'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_agent_id'), ['agent_id'], unique=False)
batch_op.alter_column('answer',
existing_type=sa.TEXT(),
nullable=True)
batch_op.drop_column('latency')
op.drop_table('zl_languages')
# ### end Alembic commands ###
@@ -0,0 +1,205 @@
"""sync schema with global questions
Revision ID: a3dcfbe69b00
Revises: f0f24c20e91a
Create Date: 2026-02-23 22:28:18.892924
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.engine.reflection import Inspector
# revision identifiers, used by Alembic.
revision = 'a3dcfbe69b00'
down_revision = 'f0f24c20e91a'
branch_labels = None
depends_on = None
def upgrade():
conn = op.get_bind()
inspector = Inspector.from_engine(conn)
tables = inspector.get_table_names()
if 'agents' not in tables:
op.create_table('agents',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('icon_url', sa.String(length=255), nullable=True),
sa.Column('dify_app_id', sa.String(length=100), nullable=False),
sa.Column('dify_api_key', sa.String(length=100), nullable=False),
sa.Column('type', sa.String(length=20), nullable=False),
sa.Column('api_base_url', sa.String(length=255), nullable=True),
sa.Column('extra_config', sa.JSON(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('dify_app_id')
)
if 'departments' not in tables:
op.create_table('departments',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('code', sa.String(length=50), nullable=True),
sa.Column('company', sa.String(length=100), nullable=True),
sa.Column('description', sa.Text(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('code'),
sa.UniqueConstraint('name')
)
else:
columns = [c['name'] for c in inspector.get_columns('departments')]
if 'code' not in columns:
op.add_column('departments', sa.Column('code', sa.String(length=50), nullable=True))
op.create_unique_constraint(None, 'departments', ['code'])
if 'company' not in columns:
op.add_column('departments', sa.Column('company', sa.String(length=100), nullable=True))
if 'zl_languages' not in tables:
op.create_table('zl_languages',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('code', sa.String(length=10), nullable=False),
sa.Column('name', sa.String(length=50), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('code')
)
if 'users' not in tables:
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=50), nullable=False),
sa.Column('email', sa.String(length=100), nullable=False),
sa.Column('department', sa.String(length=100), nullable=True),
sa.Column('role', sa.String(length=20), nullable=False),
sa.Column('status', sa.String(length=20), nullable=False),
sa.Column('password_hash', sa.String(length=255), nullable=True),
sa.Column('language', sa.String(length=10), nullable=False),
sa.Column('real_name', sa.String(length=50), nullable=True),
sa.Column('employee_id', sa.String(length=50), nullable=True),
sa.Column('phone_number', sa.String(length=20), nullable=True),
sa.Column('default_agent_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['default_agent_id'], ['agents.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('email'),
sa.UniqueConstraint('employee_id'),
sa.UniqueConstraint('phone_number')
)
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_users_username'), ['username'], unique=True)
else:
columns = [c['name'] for c in inspector.get_columns('users')]
if 'default_agent_id' not in columns:
op.add_column('users', sa.Column('default_agent_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'users', 'agents', ['default_agent_id'], ['id'])
if 'real_name' not in columns:
op.add_column('users', sa.Column('real_name', sa.String(length=50), nullable=True))
if 'employee_id' not in columns:
op.add_column('users', sa.Column('employee_id', sa.String(length=50), nullable=True))
try:
op.create_unique_constraint(None, 'users', ['employee_id'])
except: pass
if 'phone_number' not in columns:
op.add_column('users', sa.Column('phone_number', sa.String(length=20), nullable=True))
try:
op.create_unique_constraint(None, 'users', ['phone_number'])
except: pass
if 'chat_logs' not in tables:
op.create_table('chat_logs',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('query', sa.Text(), nullable=False),
sa.Column('answer', sa.Text(), nullable=False),
sa.Column('latency', sa.Float(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
if 'permission_requests' not in tables:
op.create_table('permission_requests',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('reason', sa.Text(), nullable=False),
sa.Column('status', sa.String(length=20), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('reviewed_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
if 'quick_questions' not in tables:
op.create_table('quick_questions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(length=100), nullable=False),
sa.Column('question', sa.Text(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
if 'user_agent_permissions' not in tables:
op.create_table('user_agent_permissions',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id', 'agent_id')
)
if 'user_default_agents' not in tables:
op.create_table('user_default_agents',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
if 'user_favorite_agents' not in tables:
op.create_table('user_favorite_agents',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id', 'agent_id')
)
if 'user_homepage_configs' not in tables:
op.create_table('user_homepage_configs',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('layout', sa.JSON(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id')
)
if 'feedbacks' not in tables:
op.create_table('feedbacks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('chat_log_id', sa.Integer(), nullable=False),
sa.Column('score', sa.Integer(), nullable=False),
sa.Column('comment', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['chat_log_id'], ['chat_logs.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('chat_log_id')
)
def downgrade():
pass
@@ -0,0 +1,42 @@
"""make dify credentials nullable
Revision ID: b1246a8b37fa
Revises: a3dcfbe69b00
Create Date: 2026-02-23 22:43:26.470122
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b1246a8b37fa'
down_revision = 'a3dcfbe69b00'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('agents', schema=None) as batch_op:
batch_op.alter_column('dify_app_id',
existing_type=sa.VARCHAR(length=100),
nullable=True)
batch_op.alter_column('dify_api_key',
existing_type=sa.VARCHAR(length=100),
nullable=True)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('agents', schema=None) as batch_op:
batch_op.alter_column('dify_api_key',
existing_type=sa.VARCHAR(length=100),
nullable=False)
batch_op.alter_column('dify_app_id',
existing_type=sa.VARCHAR(length=100),
nullable=False)
# ### end Alembic commands ###
@@ -0,0 +1,64 @@
"""Add UserHomepageConfig, UserFavoriteAgent, UserDefaultAgent and Update Department
Revision ID: f0f24c20e91a
Revises: 60b4aee3ad2d
Create Date: 2026-02-23 21:13:19.814958
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f0f24c20e91a'
down_revision = '60b4aee3ad2d'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('user_default_agents',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user_favorite_agents',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id', 'agent_id')
)
op.create_table('user_homepage_configs',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('layout', sa.JSON(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id')
)
with op.batch_alter_table('departments', schema=None) as batch_op:
batch_op.add_column(sa.Column('code', sa.String(length=50), nullable=True))
batch_op.add_column(sa.Column('company', sa.String(length=100), nullable=True))
batch_op.create_unique_constraint(None, ['code'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('departments', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='unique')
batch_op.drop_column('company')
batch_op.drop_column('code')
op.drop_table('user_homepage_configs')
op.drop_table('user_favorite_agents')
op.drop_table('user_default_agents')
# ### end Alembic commands ###
+12
View File
@@ -0,0 +1,12 @@
flask
flask-sqlalchemy
flask-migrate
flask-cors
psycopg2-binary
redis
requests
gunicorn
gevent
pydantic
python-dotenv
+17
View File
@@ -0,0 +1,17 @@
"""
backend/run.py
开发环境启动脚本
"""
from app import create_app, db
from app.models import User, Agent
app = create_app('development')
@app.shell_context_processor
def make_shell_context():
return {'db': db, 'User': User, 'Agent': Agent}
if __name__ == '__main__':
# MacOS ControlCenter uses port 5000, so we use 5002
app.run(host='0.0.0.0', port=5002)
+24
View File
@@ -0,0 +1,24 @@
from app import create_app, db
from app.models import ZlLanguage
app = create_app('development')
with app.app_context():
languages = [
{'code': 'zh-CN', 'name': '简体中文'},
{'code': 'zh-TW', 'name': '繁體中文'},
{'code': 'en', 'name': 'English'},
{'code': 'th', 'name': 'ไทย'},
]
for lang in languages:
exists = ZlLanguage.query.filter_by(code=lang['code']).first()
if not exists:
print(f"Adding language: {lang['name']}")
db.session.add(ZlLanguage(code=lang['code'], name=lang['name'], is_active=True))
else:
print(f"Language exists: {lang['name']}")
db.session.commit()
print("Done seeding languages.")
+32
View File
@@ -0,0 +1,32 @@
import pytest
from app import create_app, db
from app.models import User
@pytest.fixture
def app():
app = create_app('testing')
with app.app_context():
db.create_all()
yield app
db.session.remove()
db.drop_all()
@pytest.fixture
def client(app):
return app.test_client()
@pytest.fixture
def admin_headers():
return {
'X-Username': 'admin',
'X-Role': 'admin',
'Content-Type': 'application/json'
}
@pytest.fixture
def user_headers():
return {
'X-Username': 'user',
'X-Role': 'user',
'Content-Type': 'application/json'
}
+71
View File
@@ -0,0 +1,71 @@
import requests
import json
import sys
BASE_URL = "http://127.0.0.1:5001/api"
HEADERS = {
"X-Username": "admin",
"X-Role": "admin",
"Content-Type": "application/json"
}
def test_create_iframe_agent():
print("\n--- Testing Iframe Agent Creation ---")
payload = {
"name": "Test Iframe Agent",
"type": "iframe",
"description": "Auto-test Iframe Agent",
"extra_config": {
"iframe_url": "http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg"
}
}
try:
response = requests.post(f"{BASE_URL}/admin/agents", headers=HEADERS, json=payload)
print(f"Status Code: {response.status_code}")
print(f"Response: {response.text}")
if response.status_code == 201:
print("SUCCESS: Iframe Agent created")
return response.json()['id']
else:
print("FAILURE: Could not create Iframe Agent")
sys.exit(1)
except Exception as e:
print(f"ERROR: {e}")
sys.exit(1)
def test_create_api_agent():
print("\n--- Testing API Agent Creation ---")
payload = {
"name": "Test API Agent",
"type": "api",
"description": "Auto-test API Agent",
"dify_app_id": "test-app-id-123", # Dummy ID for testing constraint
"dify_api_key": "app-xdiejQibWQy8ZQWXcdxJjS9I",
"api_base_url": "http://127.0.0.1:5001/v1"
}
try:
response = requests.post(f"{BASE_URL}/admin/agents", headers=HEADERS, json=payload)
print(f"Status Code: {response.status_code}")
print(f"Response: {response.text}")
if response.status_code == 201:
print("SUCCESS: API Agent created")
return response.json()['id']
else:
# Handle unique constraint if it already exists from previous run
if "integrity error" in response.text.lower() or "unique" in response.text.lower():
print("WARNING: Agent likely already exists (Integrity Error).")
else:
print("FAILURE: Could not create API Agent")
sys.exit(1)
except Exception as e:
print(f"ERROR: {e}")
sys.exit(1)
if __name__ == "__main__":
iframe_id = test_create_iframe_agent()
api_id = test_create_api_agent()
print("\nAll automated tests passed!")
+112
View File
@@ -0,0 +1,112 @@
import pytest
from app import create_app, db
from app.models import Agent, User
import json
@pytest.fixture
def client():
# Use 'testing' config to ensure SQLite in-memory DB is used
app = create_app('testing')
with app.app_context():
db.create_all()
# Create admin user for auth
# Ensure all required fields are provided
admin = User(
username='admin',
email='admin@example.com',
role='admin'
)
admin.set_password('admin')
db.session.add(admin)
db.session.commit()
yield app.test_client()
db.session.remove()
db.drop_all()
def get_headers():
return {
'X-Username': 'admin',
'X-Role': 'admin',
'Content-Type': 'application/json'
}
def test_create_iframe_agent(client):
"""
Test creating an Iframe agent with user provided data.
"""
data = {
"name": "Test Iframe Agent",
"type": "iframe",
"description": "Auto-test Iframe Agent",
"iframe_url": "http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg"
}
# Frontend logic: extra_config = { iframe_url: ... }
payload = {
"name": data["name"],
"type": data["type"],
"description": data["description"],
"dify_app_id": "", # Frontend sends empty string
"dify_api_key": "", # Frontend sends empty string
"extra_config": {
"iframe_url": data["iframe_url"]
}
}
response = client.post('/api/admin/agents', json=payload, headers=get_headers())
assert response.status_code == 201, f"Failed to create Iframe agent: {response.text}"
resp_data = response.get_json()
assert 'id' in resp_data
# Verify DB
# Need to access DB within app context or use client application context if possible
# But db.session is bound to the app context.
# We can use client.application.app_context() if needed, but db.session should work if we are in the same thread/process and using shared memory (for sqlite).
# Since we yielded app.test_client(), the app context in fixture is gone.
# But we can access the app from client.application
with client.application.app_context():
agent = db.session.get(Agent, resp_data['id'])
assert agent is not None
assert agent.type == 'iframe'
# Ensure empty string was converted to None
assert agent.dify_app_id is None
assert agent.extra_config['iframe_url'] == data['iframe_url']
def test_create_api_agent(client):
"""
Test creating an API agent with user provided data.
"""
data = {
"name": "Test API Agent",
"type": "api",
"api_base_url": "http://127.0.0.1:5001/v1",
"dify_api_key": "app-xdiejQibWQy8ZQWXcdxJjS9I"
}
# We need to provide a dify_app_id because it is required for API agents
payload = {
"name": data["name"],
"type": data["type"],
"dify_app_id": "test-api-agent-id", # Dummy ID
"dify_api_key": data["dify_api_key"],
"api_base_url": data["api_base_url"]
}
response = client.post('/api/admin/agents', json=payload, headers=get_headers())
assert response.status_code == 201, f"Failed to create API agent: {response.text}"
resp_data = response.get_json()
assert 'id' in resp_data
# Verify DB
with client.application.app_context():
agent = db.session.get(Agent, resp_data['id'])
assert agent is not None
assert agent.type == 'api'
assert agent.dify_api_key == data['dify_api_key']
assert agent.api_base_url == data['api_base_url']
+91
View File
@@ -0,0 +1,91 @@
import requests
import json
from app import create_app, db
from app.models import Agent, ChatLog, User
def setup_data():
app = create_app()
with app.app_context():
# Create a user first (needed for chat log)
user = User.query.filter_by(username="repro_user").first()
if not user:
user = User(username="repro_user", email="repro@test.com", role="admin")
user.set_password("password")
db.session.add(user)
db.session.commit()
# Create the "Test Agent Report" agent
agent = Agent.query.filter_by(name="Test Agent Report").first()
if not agent:
agent = Agent(
name="Test Agent Report",
type="api",
dify_app_id="repro_app_id",
dify_api_key="repro_key",
is_active=True
)
db.session.add(agent)
db.session.commit()
print(f"Created Agent: {agent.id}")
else:
print(f"Agent exists: {agent.id}")
# Create a ChatLog to enforce FK constraint
chat = ChatLog(
user_id=user.id,
agent_id=agent.id,
query="test",
answer="test"
)
db.session.add(chat)
db.session.commit()
print("Created ChatLog dependency.")
return agent.id, user.username
def test_delete(agent_id, username):
print(f"\n--- Testing DELETE Agent {agent_id} ---")
headers = {
"X-Username": username,
"X-Role": "admin"
}
url = f"http://127.0.0.1:5000/api/admin/agents/{agent_id}"
try:
res = requests.delete(url, headers=headers)
print(f"Status: {res.status_code}")
print(f"Content: {res.text}")
except Exception as e:
print(f"Request failed: {e}")
def test_update(agent_id, username):
print(f"\n--- Testing UPDATE Agent {agent_id} ---")
headers = {
"X-Username": username,
"X-Role": "admin",
"Content-Type": "application/json"
}
url = f"http://127.0.0.1:5000/api/admin/agents/{agent_id}"
data = {
"dify_api_key": "updated_key_123",
"name": "Test Agent Report", # Send name as well
"dify_app_id": "repro_app_id",
"type": "api",
"is_active": True
}
try:
res = requests.put(url, headers=headers, json=data)
print(f"Status: {res.status_code}")
print(f"Content: {res.text}")
except Exception as e:
print(f"Request failed: {e}")
if __name__ == "__main__":
# Ensure data exists
try:
agent_id, username = setup_data()
# Test Delete (Expect fail due to FK)
test_delete(agent_id, username)
# Test Update (Expect success)
test_update(agent_id, username)
except Exception as e:
print(f"Setup failed: {e}")
@@ -0,0 +1,51 @@
import pytest
from app import create_app, db
from app.models import Agent, User
@pytest.fixture
def client():
app = create_app('testing')
with app.app_context():
db.create_all()
# Create an active agent
agent = Agent(name="Test Agent", type="api", is_active=True)
db.session.add(agent)
# Create a regular user (no permissions)
user = User(username='test_user', role='user', email='test@example.com')
db.session.add(user)
db.session.commit()
yield app.test_client()
db.session.remove()
db.drop_all()
def test_user_home_agents_visibility(client):
"""
Test that a regular user can see active agents in /api/user/home
even if they don't have explicit permission (visibility vs access).
"""
# Login as regular user
client.post('/api/user/login', json={'username': 'test_user', 'password': ''})
# Mock headers for auth (since login might not set session in test client depending on implementation)
# user.py uses _get_current_user which checks headers
headers = {
'X-Username': 'test_user',
'X-Role': 'user'
}
response = client.get('/api/user/home', headers=headers)
assert response.status_code == 200
data = response.get_json()
agents = data.get('agents', [])
# Current behavior (Bug): agents is empty for regular user
# Desired behavior: agents should contain the active agent
print(f"Agents found: {len(agents)}")
assert len(agents) > 0, "Agents list should not be empty for regular user"
+116
View File
@@ -0,0 +1,116 @@
import pytest
from app.models import Agent, User
from app import db
import uuid
def test_delete_user_success(client, admin_headers):
"""
Verify DELETE /api/admin/users/<id> works (after fix).
"""
# Create a user to delete
user = User(username=f"del_{uuid.uuid4().hex[:8]}", email=f"del_{uuid.uuid4().hex[:8]}@test.com", role="user")
user.set_password("password")
db.session.add(user)
db.session.commit()
user_id = user.id
print(f"\nCreated user {user_id} for DELETE test.")
# Test DELETE Endpoint
res = client.delete(f'/api/admin/users/{user_id}', headers=admin_headers)
print(f"DELETE /users/{user_id} status: {res.status_code}")
if res.status_code == 200:
print("DELETE /api/admin/users/<id> success.")
# Verify user is gone
assert User.query.get(user_id) is None
else:
print(f"DELETE failed with {res.status_code}: {res.text}")
pytest.fail(f"DELETE failed: {res.status_code}")
def test_update_agent_api_key_scenarios(client, admin_headers):
"""
Test various Agent API Key update scenarios.
"""
# Create an agent
app_id = f"app-{uuid.uuid4().hex[:8]}"
agent = Agent(
name="UpdateKeyTest",
type="api",
dify_app_id=app_id,
dify_api_key="orig_key",
is_active=True
)
db.session.add(agent)
db.session.commit()
agent_id = agent.id
print(f"\nCreated agent {agent_id} for update test.")
# Scenario 1: Update Key Success
new_key = "new_secret_key"
data = {
"dify_api_key": new_key
}
res = client.put(f'/api/admin/agents/{agent_id}', json=data, headers=admin_headers)
assert res.status_code == 200
updated_agent = Agent.query.get(agent_id)
assert updated_agent.dify_api_key == new_key
print("Scenario 1 (Success): Key updated.")
# Scenario 2: Update with Empty String (Should allow it? Or ignore?)
# Current behavior: updates to empty string.
data = {
"dify_api_key": ""
}
res = client.put(f'/api/admin/agents/{agent_id}', json=data, headers=admin_headers)
assert res.status_code == 200
updated_agent = Agent.query.get(agent_id)
assert updated_agent.dify_api_key == ""
print("Scenario 2 (Empty String): Key updated to empty string.")
# Scenario 3: Update with Duplicate App ID (Should fail)
# Create another agent first
other_app_id = f"app-{uuid.uuid4().hex[:8]}"
other_agent = Agent(
name="OtherAgent",
type="api",
dify_app_id=other_app_id,
dify_api_key="key2",
is_active=True
)
db.session.add(other_agent)
db.session.commit()
# Try to update first agent to use second agent's App ID
data = {
"dify_app_id": other_app_id
}
res = client.put(f'/api/admin/agents/{agent_id}', json=data, headers=admin_headers)
print(f"Scenario 3 (Duplicate App ID) status: {res.status_code}")
# This should fail with 400 (caught exception) or 500
# Our code catches Exception and returns 400
assert res.status_code == 400
assert "error" in res.json
print("Scenario 3 (Duplicate App ID): Correctly failed.")
# Scenario 4: Update with Very Long Key (Should fail if > 100)
long_key = "a" * 101
data = {
"dify_api_key": long_key
}
res = client.put(f'/api/admin/agents/{agent_id}', json=data, headers=admin_headers)
print(f"Scenario 4 (Long Key) status: {res.status_code}")
# Should fail due to DB constraint (String(100))
# Caught by try-except block -> 400
if res.status_code == 400:
print("Scenario 4 (Long Key): Correctly failed.")
else:
print(f"Scenario 4 (Long Key): Unexpected success? Status: {res.status_code}")
# If SQLite, it might not enforce length. If Postgres, it will.
# We are using SQLite (implied by file structure/lack of PG setup in context, but wait, env says postgres?)
# "mcp_PostgreSQL_query" tool suggests Postgres.
# But locally it might be SQLite.
pass
+194
View File
@@ -0,0 +1,194 @@
import pytest
from app.models import Agent, User, PermissionRequest
from app import db
def test_agent_lifecycle(client, admin_headers):
"""
Test complete lifecycle of an Agent: Create -> Read -> Update -> Delete
"""
# 1. Create Agent
new_agent = {
"name": "Test Agent",
"description": "Initial Description",
"type": "api",
"dify_app_id": "app-123",
"dify_api_key": "key-123",
"is_active": True
}
response = client.post('/api/admin/agents', json=new_agent, headers=admin_headers)
assert response.status_code == 201
agent_id = response.json['id']
# 2. Read Agent List
response = client.get('/api/admin/agents', headers=admin_headers)
assert response.status_code == 200
agents = response.json
assert len(agents) == 1
assert agents[0]['name'] == "Test Agent"
assert agents[0]['description'] == "Initial Description"
# 3. Update Agent
updated_data = {
"name": "Updated Agent",
"description": "Updated Description"
}
response = client.put(f'/api/admin/agents/{agent_id}', json=updated_data, headers=admin_headers)
assert response.status_code == 200
# Verify Update
response = client.get('/api/admin/agents', headers=admin_headers)
agents = response.json
assert agents[0]['name'] == "Updated Agent"
assert agents[0]['description'] == "Updated Description"
# 4. Delete Agent
response = client.delete(f'/api/admin/agents/{agent_id}', headers=admin_headers)
assert response.status_code == 200
# Verify Deletion
response = client.get('/api/admin/agents', headers=admin_headers)
assert len(response.json) == 0
def test_user_management(client, admin_headers):
"""
Test user creation, approval, and permission assignment
"""
# 1. Create User
new_user = {
"username": "newuser",
"email": "new@example.com",
"role": "user",
"password": "password123",
"real_name": "Test User",
"employee_id": "EMP001"
}
response = client.post('/api/admin/users', json=new_user, headers=admin_headers)
assert response.status_code == 201
user_id = response.json['id']
# 2. Approve User
response = client.post(f'/api/admin/users/{user_id}/approve', headers=admin_headers)
assert response.status_code == 200
# Verify Status and Fields
response = client.get('/api/admin/users', headers=admin_headers)
users = response.json
target_user = next(u for u in users if u['id'] == user_id)
assert target_user['status'] == 'active'
assert target_user['real_name'] == "Test User"
assert target_user['employee_id'] == "EMP001"
# 3. Assign Permissions (needs an Agent first)
agent_res = client.post('/api/admin/agents', json={
"name": "Permission Agent",
"type": "api",
"dify_app_id": "p1",
"dify_api_key": "k1"
}, headers=admin_headers)
agent_id = agent_res.json['id']
response = client.post(f'/api/admin/users/{user_id}/permissions', json={
"agent_ids": [agent_id]
}, headers=admin_headers)
assert response.status_code == 200
# Verify Permissions
response = client.get('/api/admin/users', headers=admin_headers)
target_user = next(u for u in response.json if u['id'] == user_id)
assert agent_id in target_user['agent_ids']
# 4. Delete User (New Endpoint)
response = client.delete(f'/api/admin/users/{user_id}', headers=admin_headers)
assert response.status_code == 200
# Verify Deletion
response = client.get('/api/admin/users', headers=admin_headers)
users = response.json
assert not any(u['id'] == user_id for u in users)
def test_agent_update_validation(client, admin_headers):
"""
Test validation when updating agents (especially API mode constraints)
"""
# Create Agent
new_agent = {
"name": "Validation Agent",
"type": "api",
"dify_app_id": "v-app-1",
"dify_api_key": "v-key-1",
"is_active": True
}
response = client.post('/api/admin/agents', json=new_agent, headers=admin_headers)
agent_id = response.json['id']
# 1. Update with Valid Data
response = client.put(f'/api/admin/agents/{agent_id}', json={"dify_api_key": "new-key"}, headers=admin_headers)
assert response.status_code == 200
# 2. Try to Clear Key for API Agent (Should Fail)
response = client.put(f'/api/admin/agents/{agent_id}', json={"dify_api_key": ""}, headers=admin_headers)
assert response.status_code == 400
assert "API mode requires Dify API Key" in response.json['error']
# 3. Try to Clear App ID for API Agent (Should Fail)
response = client.put(f'/api/admin/agents/{agent_id}', json={"dify_app_id": ""}, headers=admin_headers)
assert response.status_code == 400
assert "API mode requires Dify App ID" in response.json['error']
def test_permission_requests(client, app, admin_headers):
"""
Test permission request approval/rejection flow
"""
# Setup: Create User, Agent, and Request manually
with app.app_context():
user = User(username="requester", email="req@example.com", role="user")
agent = Agent(name="Requested Agent", type="api", dify_app_id="r1", dify_api_key="k1", is_active=True)
db.session.add(user)
db.session.add(agent)
db.session.commit()
req = PermissionRequest(user_id=user.id, agent_id=agent.id, reason="Need access", status="pending")
db.session.add(req)
db.session.commit()
req_id = req.id
user_id = user.id
agent_id = agent.id
# 1. List Requests
response = client.get('/api/admin/permission-requests', headers=admin_headers)
assert response.status_code == 200
requests = response.json
assert len(requests) == 1
assert requests[0]['reason'] == "Need access"
# 2. Approve Request
response = client.post(f'/api/admin/permission-requests/{req_id}/approve', headers=admin_headers)
assert response.status_code == 200
# Verify Request Status
response = client.get('/api/admin/permission-requests', headers=admin_headers)
requests = response.json
assert requests[0]['status'] == 'approved'
# Verify User Permission Updated
response = client.get('/api/admin/users', headers=admin_headers)
users = response.json
target_user = next(u for u in users if u['id'] == user_id)
assert agent_id in target_user['agent_ids']
def test_reports(client, admin_headers):
"""
Test report endpoints
"""
response = client.get('/api/admin/reports/usage', headers=admin_headers)
assert response.status_code == 200
data = response.json
assert 'total' in data
assert 'by_user' in data
assert 'by_agent' in data
response = client.get('/api/admin/reports/feedback', headers=admin_headers)
assert response.status_code == 200
data = response.json
assert 'avg_score' in data
assert 'distribution' in data
+149
View File
@@ -0,0 +1,149 @@
import pytest
from app import create_app, db
from app.models import User, Agent, Department, PermissionRequest
@pytest.fixture
def client():
app = create_app()
app.config['TESTING'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
with app.test_client() as client:
with app.app_context():
db.create_all()
# Create admin user
admin = User(username='admin', role='admin', email='admin@example.com')
admin.set_password('admin')
db.session.add(admin)
db.session.commit()
yield client
db.session.remove()
db.drop_all()
def get_headers(client, username='admin', password='admin'):
res = client.post('/api/user/login', json={'username': username, 'password': password})
data = res.get_json()
return {
'X-User-Id': str(data['id']),
'X-Username': data['username'],
'X-Role': data['role']
}
def test_department_crud(client):
headers = get_headers(client)
# Create
res = client.post('/api/admin/departments', json={
'name': 'IT Dept',
'code': 'IT001',
'company': 'Tech Corp',
'description': 'Information Technology'
}, headers=headers)
assert res.status_code == 201
dept_id = res.get_json()['id']
# List
res = client.get('/api/admin/departments', headers=headers)
assert res.status_code == 200
depts = res.get_json()
assert len(depts) == 1
assert depts[0]['code'] == 'IT001'
assert depts[0]['company'] == 'Tech Corp'
# Update
res = client.put(f'/api/admin/departments/{dept_id}', json={
'name': 'IT Department',
'code': 'IT002'
}, headers=headers)
assert res.status_code == 200
# Verify Update
res = client.get('/api/admin/departments', headers=headers)
depts = res.get_json()
assert depts[0]['name'] == 'IT Department'
assert depts[0]['code'] == 'IT002'
# Delete
res = client.delete(f'/api/admin/departments/{dept_id}', headers=headers)
assert res.status_code == 200
res = client.get('/api/admin/departments', headers=headers)
assert len(res.get_json()) == 0
def test_agent_crud(client):
headers = get_headers(client)
# Create
res = client.post('/api/admin/agents', json={
'name': 'Test Agent',
'dify_app_id': 'app-123',
'description': 'Test Description'
}, headers=headers)
assert res.status_code == 201
agent_id = res.get_json()['id']
# List
res = client.get('/api/admin/agents', headers=headers)
assert res.status_code == 200
agents = res.get_json()
assert len(agents) == 1
assert agents[0]['name'] == 'Test Agent'
# Update
res = client.put(f'/api/admin/agents/{agent_id}', json={
'name': 'Updated Agent'
}, headers=headers)
assert res.status_code == 200
# Verify Update
res = client.get('/api/admin/agents', headers=headers)
assert res.get_json()[0]['name'] == 'Updated Agent'
# Delete
res = client.delete(f'/api/admin/agents/{agent_id}', headers=headers)
assert res.status_code == 200
res = client.get('/api/admin/agents', headers=headers)
assert len(res.get_json()) == 0
def test_permission_flow(client):
admin_headers = get_headers(client)
# Create Agent
client.post('/api/admin/agents', json={
'name': 'Test Agent',
'dify_app_id': 'app-123'
}, headers=admin_headers)
agent_id = 1
# Create User
client.post('/api/user/register', json={
'username': 'user1', 'password': 'password', 'email': 'u1@example.com',
'real_name': 'User One', 'employee_id': 'U001', 'phone_number': '1234567890'
})
# Approve User
client.post('/api/admin/users/2/approve', headers=admin_headers) # ID 2 because admin is 1
# User Login
user_headers = get_headers(client, 'user1', 'password')
# Request Permission
res = client.post('/api/user/permission-requests', json={
'agent_id': agent_id,
'reason': 'I need it'
}, headers=user_headers)
assert res.status_code == 201
req_id = res.get_json()['id']
# Admin List Requests
res = client.get('/api/admin/permission-requests', headers=admin_headers)
assert len(res.get_json()) == 1
# Admin Approve
res = client.post(f'/api/admin/permission-requests/{req_id}/approve', headers=admin_headers)
assert res.status_code == 200
# User Check Home (should have agent now)
res = client.get('/api/user/home', headers=user_headers)
data = res.get_json()
assert len(data['agents']) == 1
assert data['agents'][0]['id'] == agent_id
+131
View File
@@ -0,0 +1,131 @@
import pytest
from app import create_app, db
from app.models import User, Agent
from flask import json
@pytest.fixture
def client():
app = create_app('testing')
with app.test_client() as client:
with app.app_context():
db.create_all()
# Create Admin
admin = User(username='admin', role='admin', email='admin@example.com')
admin.set_password('password')
db.session.add(admin)
# Create Users
u1 = User(username='u1', role='user', email='u1@example.com')
u2 = User(username='u2', role='user', email='u2@example.com')
db.session.add_all([u1, u2])
# Create Agents
a1 = Agent(name='a1', dify_app_id='1', dify_api_key='1')
a2 = Agent(name='a2', dify_app_id='2', dify_api_key='2')
db.session.add_all([a1, a2])
db.session.commit()
yield client
db.session.remove()
db.drop_all()
def login(client, username, password):
return client.post('/api/user/login', json={'username': username, 'password': password})
def test_batch_update_users(client):
login_res = login(client, 'admin', 'password')
token_headers = {
'X-Username': 'admin',
'X-Role': 'admin',
'X-User-Id': str(login_res.json['id'])
}
# Get user IDs
u1 = User.query.filter_by(username='u1').first()
u2 = User.query.filter_by(username='u2').first()
# Batch update
res = client.put('/api/admin/users/batch', headers=token_headers, json={
'user_ids': [u1.id, u2.id],
'data': {'department': 'Engineering', 'status': 'disabled'}
})
assert res.status_code == 200
# Verify
u1 = User.query.get(u1.id)
u2 = User.query.get(u2.id)
assert u1.department == 'Engineering'
assert u1.status == 'disabled'
assert u2.department == 'Engineering'
assert u2.status == 'disabled'
def test_batch_update_permissions(client):
login_res = login(client, 'admin', 'password')
token_headers = {
'X-Username': 'admin',
'X-Role': 'admin',
'X-User-Id': str(login_res.json['id'])
}
u1 = User.query.filter_by(username='u1').first()
u2 = User.query.filter_by(username='u2').first()
a1 = Agent.query.filter_by(name='a1').first()
a2 = Agent.query.filter_by(name='a2').first()
# Grant a1 to u1 initially
u1.agents.append(a1)
db.session.commit()
# Batch Add a2 to u1, u2
res = client.post('/api/admin/permissions/batch', headers=token_headers, json={
'user_ids': [u1.id, u2.id],
'agent_ids': [a2.id],
'action': 'add'
})
assert res.status_code == 200
u1 = User.query.get(u1.id)
u2 = User.query.get(u2.id)
assert a1 in u1.agents
assert a2 in u1.agents
assert a2 in u2.agents
# Batch Set a1 for u1, u2 (should remove a2)
res = client.post('/api/admin/permissions/batch', headers=token_headers, json={
'user_ids': [u1.id, u2.id],
'agent_ids': [a1.id],
'action': 'set'
})
assert res.status_code == 200
u1 = User.query.get(u1.id)
u2 = User.query.get(u2.id)
assert len(u1.agents) == 1
assert u1.agents[0].id == a1.id
assert len(u2.agents) == 1
assert u2.agents[0].id == a1.id
def test_user_default_agent(client):
# Login as u1
u1 = User.query.filter_by(username='u1').first()
u1.set_password('password')
db.session.commit()
login_res = login(client, 'u1', 'password')
token_headers = {
'X-Username': 'u1',
'X-Role': 'user',
'X-User-Id': str(u1.id)
}
a1 = Agent.query.filter_by(name='a1').first()
# Set default agent
res = client.put('/api/user/profile', headers=token_headers, json={
'default_agent_id': a1.id
})
assert res.status_code == 200
# Verify via Home API
res = client.get('/api/user/home', headers=token_headers)
data = res.json
assert data['user']['default_agent_id'] == a1.id
+237
View File
@@ -0,0 +1,237 @@
import pytest
import json
from app.models import User, Agent
# -----------------------------------------------------------------------------
# Test File: backend/tests/test_comprehensive.py
# Purpose: Comprehensive automated tests for backend functionalities including
# User Management, Agent Management, and Permissions.
# References: backend/app/api/admin.py, backend/app/api/user.py, backend/app/models.py
# Logic:
# 1. Test User Registration (with new fields)
# 2. Test Admin User Approval
# 3. Test Admin User Rejection
# 4. Test Agent CRUD (Create, Update, Delete)
# 5. Test Permission Assignment (User-Agent linkage)
# -----------------------------------------------------------------------------
@pytest.fixture
def auth_headers(client):
"""
Helper fixture to get auth headers for a standard user.
Note: In real app, we might need a token, but here we use mock headers from conftest
or simulate login if needed. For admin, we use admin_headers fixture.
"""
return {
'Content-Type': 'application/json'
}
def test_user_registration_flow(client):
"""
Test the user registration process with all new fields.
Steps:
1. Register a new user with phone_number, real_name, employee_id.
2. Verify successful response.
3. Verify data in database.
4. Try to register with duplicate phone_number/employee_id and verify failure.
"""
# 1. Register a new user
payload = {
'username': 'testuser_new',
'password': 'password123',
'email': 'testuser_new@example.com',
'real_name': 'Test User Real',
'employee_id': 'EMP001',
'phone_number': '13800138000'
}
# Call /api/user/register (Assuming this is the public registration endpoint)
# If not, we might use /api/admin/users for admin creation.
# Let's check api/user.py for register endpoint, usually it is /api/user/register
response = client.post('/api/user/register', json=payload)
# 2. Verify response
assert response.status_code == 201 or response.status_code == 200
data = response.get_json()
assert 'id' in data or 'status' in data
# 3. Verify database
user = User.query.filter_by(username='testuser_new').first()
assert user is not None
assert user.real_name == 'Test User Real'
assert user.employee_id == 'EMP001'
assert user.phone_number == '13800138000'
assert user.status == 'pending' # Default status for registration
# 4. Duplicate checks
# Duplicate Phone
payload_dup_phone = payload.copy()
payload_dup_phone['username'] = 'testuser_dup_phone'
payload_dup_phone['email'] = 'dup_phone@example.com'
payload_dup_phone['employee_id'] = 'EMP002' # Different ID
# Same phone '13800138000'
response = client.post('/api/user/register', json=payload_dup_phone)
assert response.status_code == 400
assert 'Phone number already exists' in response.get_json()['error']
# Duplicate Employee ID
payload_dup_emp = payload.copy()
payload_dup_emp['username'] = 'testuser_dup_emp'
payload_dup_emp['email'] = 'dup_emp@example.com'
payload_dup_emp['phone_number'] = '13900139000' # Different phone
# Same employee_id 'EMP001'
response = client.post('/api/user/register', json=payload_dup_emp)
assert response.status_code == 400
assert 'Employee ID already exists' in response.get_json()['error']
def test_admin_approve_reject_user(client, admin_headers):
"""
Test Admin approval and rejection of users.
Steps:
1. Create two pending users (via register endpoint or direct DB).
2. Admin approves User A. Verify status 'active'.
3. Admin rejects User B. Verify status 'rejected'.
"""
# 1. Create users
# We can use the register endpoint or admin create endpoint
user_a = User(username='user_a', email='a@test.com', status='pending', role='user')
user_a.set_password('123')
user_b = User(username='user_b', email='b@test.com', status='pending', role='user')
user_b.set_password('123')
# Need to access db session. conftest app fixture handles db creation/drop
# but we need to import db from app to add
from app import db
db.session.add(user_a)
db.session.add(user_b)
db.session.commit()
# 2. Approve User A
response = client.post(f'/api/admin/users/{user_a.id}/approve', headers=admin_headers)
assert response.status_code == 200
# Refresh from DB
db.session.refresh(user_a)
assert user_a.status == 'active'
# 3. Reject User B
response = client.post(f'/api/admin/users/{user_b.id}/reject', headers=admin_headers)
assert response.status_code == 200
db.session.refresh(user_b)
assert user_b.status == 'rejected'
def test_agent_management(client, admin_headers):
"""
Test CRUD operations for Agents.
Steps:
1. Admin creates a new Agent.
2. Admin updates the Agent.
3. Admin deletes the Agent.
"""
from app import db
# 1. Create Agent
payload = {
'name': 'Test Agent',
'dify_app_id': 'app-uuid-123',
'dify_api_key': 'key-secret-123',
'description': 'A test agent',
'type': 'api'
}
response = client.post('/api/admin/agents', json=payload, headers=admin_headers)
assert response.status_code == 201
data = response.get_json()
agent_id = data['id']
# Verify DB
agent = Agent.query.get(agent_id)
assert agent.name == 'Test Agent'
# 2. Update Agent
update_payload = {
'name': 'Updated Agent Name',
'description': 'Updated description'
}
response = client.put(f'/api/admin/agents/{agent_id}', json=update_payload, headers=admin_headers)
assert response.status_code == 200
db.session.refresh(agent)
assert agent.name == 'Updated Agent Name'
assert agent.description == 'Updated description'
# 3. Delete Agent
response = client.delete(f'/api/admin/agents/{agent_id}', headers=admin_headers)
assert response.status_code == 200
agent = Agent.query.get(agent_id)
assert agent is None
def test_permission_management(client, admin_headers):
"""
Test assigning Agents to Users (Permissions).
Steps:
1. Create a User and an Agent.
2. Verify User initially has no agents.
3. Admin updates User to assign the Agent.
4. Verify User has the Agent.
5. Admin removes the Agent.
6. Verify User has no agents.
"""
from app import db
# 1. Setup Data
user = User(username='perm_user', email='perm@test.com', role='user', status='active')
user.set_password('123')
agent = Agent(name='Perm Agent', dify_app_id='app-perm', dify_api_key='key-perm')
db.session.add(user)
db.session.add(agent)
db.session.commit()
user_id = user.id
agent_id = agent.id
# 2. Verify initial state
assert len(user.agents) == 0
# 3. Assign Agent
# The update_user endpoint accepts 'agent_ids' list
payload = {
'agent_ids': [agent_id]
}
response = client.put(f'/api/admin/users/{user_id}', json=payload, headers=admin_headers)
assert response.status_code == 200
# 4. Verify assignment
# Need to expire/refresh to see changes in relationship
db.session.expire(user)
# Or query again
user = User.query.get(user_id)
assert len(user.agents) == 1
assert user.agents[0].id == agent_id
# 5. Remove Agent (assign empty list)
payload = {
'agent_ids': []
}
response = client.put(f'/api/admin/users/{user_id}', json=payload, headers=admin_headers)
assert response.status_code == 200
# 6. Verify removal
db.session.expire(user)
user = User.query.get(user_id)
assert len(user.agents) == 0
+56
View File
@@ -0,0 +1,56 @@
import pytest
from app import create_app, db
from app.models import Agent
@pytest.fixture
def app():
app = create_app('testing')
with app.app_context():
db.create_all()
yield app
db.session.remove()
db.drop_all()
@pytest.fixture
def client(app):
return app.test_client()
def test_public_agents_access(client):
"""
测试未登录用户访问公开应用列表
"""
# 1. 初始状态:无应用
res = client.get('/api/user/public-agents')
assert res.status_code == 200
assert len(res.json) == 0
# 2. 创建应用
with client.application.app_context():
a1 = Agent(name="Public Agent 1", dify_app_id="p1", dify_api_key="k1", is_active=True)
a2 = Agent(name="Public Agent 2", dify_app_id="p2", dify_api_key="k2", is_active=True)
a3 = Agent(name="Private Agent", dify_app_id="p3", dify_api_key="k3", is_active=False)
db.session.add_all([a1, a2, a3])
db.session.commit()
# 3. 再次访问,应只返回 Active 的应用
res = client.get('/api/user/public-agents')
assert res.status_code == 200
data = res.json
assert len(data) == 2
names = [a['name'] for a in data]
assert "Public Agent 1" in names
assert "Public Agent 2" in names
assert "Private Agent" not in names
def test_user_home_access_denied(client):
"""
测试未登录用户访问 /api/user/home 返回 Guest 身份
"""
# 无 Header 访问
res = client.get('/api/user/home')
assert res.status_code == 200
data = res.json
assert data['user']['role'] == 'guest'
# Guest 用户通常没有 Agents 权限
assert len(data['agents']) == 0
+55
View File
@@ -0,0 +1,55 @@
import pytest
from app import create_app, db
from app.models import User, Agent, QuickQuestion
@pytest.fixture
def client():
app = create_app()
app.config['TESTING'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
with app.test_client() as client:
with app.app_context():
db.create_all()
yield client
db.session.remove()
db.drop_all()
def test_quick_question_crud(client):
# Setup
user = User(username='testuser', email='test@example.com', role='user')
user.set_password('password')
agent = Agent(name='Test Agent', dify_app_id='app-123', dify_api_key='key-123')
db.session.add(user)
db.session.add(agent)
db.session.commit()
# Login
login_res = client.post('/api/user/login', json={'username': 'testuser', 'password': 'password'})
assert login_res.status_code == 200
user_data = login_res.get_json()
headers = {'X-User-Id': str(user_data['id']), 'X-Username': user_data['username'], 'X-Role': user_data['role']}
# Create
res = client.post('/api/user/quick-questions', json={
'title': 'Test Q',
'question': 'How are you?',
'agent_id': agent.id
}, headers=headers)
assert res.status_code == 201
qq_id = res.get_json()['id']
# Read (via Home)
res = client.get('/api/user/home', headers=headers)
assert res.status_code == 200
data = res.get_json()
assert len(data['quick_questions']) == 1
assert data['quick_questions'][0]['title'] == 'Test Q'
# Delete
res = client.delete(f'/api/user/quick-questions/{qq_id}', headers=headers)
assert res.status_code == 200
# Verify Delete
res = client.get('/api/user/home', headers=headers)
assert len(res.get_json()['quick_questions']) == 0
+624
View File
@@ -0,0 +1,624 @@
"""
backend/tests/test_unit_mock.py
文件用途:自动化单元测试,使用 Mock 技术隔离外部依赖
测试范围:User, Admin, Agent, Chat, Permission, QuickQuestion 等核心模块
技术栈:pytest, unittest.mock, flask
设计原则:AAA 模式 (Arrange-Act-Assert),全面 Mock,独立性
"""
import pytest
import json
from unittest.mock import MagicMock, patch
from flask import g
from app import create_app, db
from app.models import User, Agent, ChatLog, Feedback, PermissionRequest, QuickQuestion
# -----------------------------------------------------------------------------
# Fixtures (Setup & Teardown)
# -----------------------------------------------------------------------------
@pytest.fixture
def app_instance():
"""
创建 Flask 应用实例,配置为测试模式
"""
app = create_app('testing')
app.config['TESTING'] = True
# 禁用反馈功能检查,方便测试
app.config['FEEDBACK_ENABLED'] = True
return app
@pytest.fixture(autouse=True)
def app_context(app_instance):
"""
自动激活应用上下文,解决 "Working outside of application context" 问题
"""
with app_instance.app_context():
yield
@pytest.fixture
def client(app_instance):
"""
Flask 测试客户端
"""
return app_instance.test_client()
@pytest.fixture
def mock_db_session(mocker):
"""
Mock 数据库 Session
用途:拦截 db.session.add, commit, rollback, delete 等操作
"""
return mocker.patch('app.db.session')
@pytest.fixture
def mock_user_query(mocker):
"""Mock User.query"""
return mocker.patch('app.models.User.query')
@pytest.fixture
def mock_agent_query(mocker):
"""Mock Agent.query"""
return mocker.patch('app.models.Agent.query')
@pytest.fixture
def mock_chat_log_query(mocker):
"""Mock ChatLog.query"""
return mocker.patch('app.models.ChatLog.query')
@pytest.fixture
def mock_permission_request_query(mocker):
"""Mock PermissionRequest.query"""
return mocker.patch('app.models.PermissionRequest.query')
@pytest.fixture
def mock_quick_question_query(mocker):
"""Mock QuickQuestion.query"""
return mocker.patch('app.models.QuickQuestion.query')
@pytest.fixture
def admin_headers():
return {
'Content-Type': 'application/json',
'X-Role': 'admin',
'X-Username': 'admin'
}
@pytest.fixture
def user_headers():
return {
'Content-Type': 'application/json',
'X-Role': 'user',
'X-Username': 'test_user',
'X-User-Id': '1'
}
# -----------------------------------------------------------------------------
# 1. User Authentication & Management Tests
# -----------------------------------------------------------------------------
def test_user_register_success(client, mock_user_query, mock_db_session):
"""
[User] 注册成功 (Happy Path)
"""
# Arrange
payload = {
"username": "new_user",
"password": "password123",
"email": "new@example.com",
"real_name": "New User",
"employee_id": "EMP001",
"phone_number": "13800000001"
}
# Mock query to return None (no duplicate)
mock_user_query.filter_by.return_value.first.return_value = None
# Act
response = client.post('/api/user/register', json=payload)
# Assert
assert response.status_code == 201
mock_db_session.add.assert_called_once()
mock_db_session.commit.assert_called_once()
data = response.get_json()
assert data['status'] == 'pending'
def test_user_register_missing_fields(client):
"""
[User] 注册失败 - 缺少必填字段 (Boundary)
"""
# Arrange
payload = {
"username": "new_user"
# Missing password, email, etc.
}
# Act
response = client.post('/api/user/register', json=payload)
# Assert
assert response.status_code == 400
assert "required" in response.get_json()['error']
def test_user_register_duplicate_username(client, mock_user_query):
"""
[User] 注册失败 - 用户名重复 (Error)
"""
# Arrange
payload = {
"username": "dup_user",
"password": "pwd",
"email": "dup@example.com",
"real_name": "Dup User",
"employee_id": "EMP002",
"phone_number": "13800000002"
}
# Mock existing user
mock_user_query.filter_by.return_value.first.return_value = User(username="dup_user")
# Act
response = client.post('/api/user/register', json=payload)
# Assert
assert response.status_code == 400
assert "Username already exists" in response.get_json()['error']
def test_user_login_success(client, mock_user_query):
"""
[User] 登录成功 (Happy Path)
"""
# Arrange
mock_user = User(id=1, username="test_user", role="user", status="active", password_hash="hashed_pwd")
mock_user_query.filter_by.return_value.first.return_value = mock_user
# Mock check_password_hash via class method or instance
# Note: User.check_password logic uses check_password_hash internally.
# We can mock check_password method on the instance.
mock_user.check_password = MagicMock(return_value=True)
# Act
response = client.post('/api/user/login', json={"username": "test_user", "password": "correct_pwd"})
# Assert
assert response.status_code == 200
data = response.get_json()
assert data['username'] == "test_user"
assert data['role'] == "user"
def test_user_login_invalid_password(client, mock_user_query):
"""
[User] 登录失败 - 密码错误 (Error)
"""
# Arrange
mock_user = User(id=1, username="test_user", status="active", password_hash="hashed")
mock_user_query.filter_by.return_value.first.return_value = mock_user
# Ensure check_password returns False
mock_user.check_password = MagicMock(return_value=False)
# Act
response = client.post('/api/user/login', json={"username": "test_user", "password": "wrong_pwd"})
# Assert
assert response.status_code == 401
assert "Invalid password" in response.get_json()['error']
def test_user_login_inactive_user(client, mock_user_query):
"""
[User] 登录失败 - 账号未激活 (Error)
"""
# Arrange
# Explicitly set status to pending.
# Note: User constructor might set default 'active' if not handled by init (SQLAlchemy magic).
# So we set it explicitly after creation or ensure it's respected.
mock_user = User(id=1, username="pending_user", status="pending", password_hash="hashed")
mock_user_query.filter_by.return_value.first.return_value = mock_user
mock_user.check_password = MagicMock(return_value=True)
# Act
response = client.post('/api/user/login', json={"username": "pending_user", "password": "pwd"})
# Assert
assert response.status_code == 403
assert "Account is not active" in response.get_json()['error']
def test_get_user_home(client, mocker):
"""
[User] 获取首页数据 (Happy Path)
"""
# Arrange
mock_user = User(id=1, role='user', agents=[])
mocker.patch('app.api.user._get_current_user', return_value=mock_user)
# Mock related queries using patching of models directly if fixtures not used,
# OR better: mock the DB session query if the code uses db.session.query
# app/api/user.py uses:
# agents = Agent.query.filter_by...
# quick_questions = db.session.query(QuickQuestion)...
# permission_requests = PermissionRequest.query...
# total_calls = db.session.query(ChatLog)...
# Mock Agent.query
mock_agent_query = mocker.patch('app.models.Agent.query')
mock_agent_query.filter_by.return_value.order_by.return_value.all.return_value = []
# Mock db.session.query for QuickQuestion and ChatLog
mock_query = mocker.patch('app.db.session.query')
# We need to handle different calls to db.session.query
# Since it's hard to distinguish by arg, we can make it return a generic mock that returns empty list/0
mock_query_obj = MagicMock()
mock_query.return_value = mock_query_obj
mock_query_obj.filter.return_value.count.return_value = 0
mock_query_obj.filter_by.return_value.order_by.return_value.all.return_value = []
mock_query_obj.filter_by.return_value.count.return_value = 0
mock_query_obj.filter_by.return_value.order_by.return_value.first.return_value = None
# Mock PermissionRequest.query
mock_pr_query = mocker.patch('app.models.PermissionRequest.query')
mock_pr_query.filter_by.return_value.order_by.return_value.all.return_value = []
# Act
response = client.get('/api/user/home')
# Assert
assert response.status_code == 200
data = response.get_json()
assert 'user' in data
assert 'agents' in data
assert 'report' in data
# -----------------------------------------------------------------------------
# 2. Admin Management Tests
# -----------------------------------------------------------------------------
def test_admin_create_agent_success(client, admin_headers, mock_db_session, mocker):
"""
[Admin] 创建 Agent (Happy Path)
"""
# Arrange
payload = {
"name": "HR Bot",
"type": "api",
"dify_app_id": "app-uuid",
"dify_api_key": "sk-secret"
}
# Mock _get_current_user for require_admin
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.post('/api/admin/agents', json=payload, headers=admin_headers)
# Assert
assert response.status_code == 201
mock_db_session.add.assert_called_once()
mock_db_session.commit.assert_called_once()
def test_admin_create_agent_missing_fields(client, admin_headers, mocker):
"""
[Admin] 创建 Agent 失败 - 缺少必要字段 (Boundary)
"""
# Arrange
payload = {
"name": "Bad Bot",
"type": "api"
# Missing dify_app_id and dify_api_key
}
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.post('/api/admin/agents', json=payload, headers=admin_headers)
# Assert
assert response.status_code == 400
assert "API mode requires app_id" in response.get_json()['error']
def test_admin_delete_agent(client, admin_headers, mock_agent_query, mock_db_session, mocker):
"""
[Admin] 删除 Agent (Happy Path)
"""
# Arrange
mock_agent = Agent(id=1, name="Old Bot")
mock_agent_query.get.return_value = mock_agent
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.delete('/api/admin/agents/1', headers=admin_headers)
# Assert
assert response.status_code == 200
mock_db_session.delete.assert_called_once_with(mock_agent)
mock_db_session.commit.assert_called_once()
def test_admin_approve_user(client, admin_headers, mock_user_query, mock_db_session, mocker):
"""
[Admin] 审批用户 (Happy Path)
"""
# Arrange
mock_user = User(id=2, status="pending")
mock_user_query.get.return_value = mock_user
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.post('/api/admin/users/2/approve', headers=admin_headers)
# Assert
assert response.status_code == 200
assert mock_user.status == 'active'
mock_db_session.commit.assert_called_once()
def test_admin_reject_user(client, admin_headers, mock_user_query, mock_db_session, mocker):
"""
[Admin] 拒绝用户 (Happy Path)
"""
# Arrange
mock_user = User(id=3, status="pending")
mock_user_query.get.return_value = mock_user
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.post('/api/admin/users/3/reject', headers=admin_headers)
# Assert
assert response.status_code == 200
assert mock_user.status == 'rejected'
mock_db_session.commit.assert_called_once()
# -----------------------------------------------------------------------------
# 3. Chat System Tests (Mocking External API)
# -----------------------------------------------------------------------------
def test_chat_completions_stream_success(client, mocker, mock_agent_query):
"""
[Chat] 发送消息并流式返回 (Happy Path)
核心:Mock requests.post 以避免真实网络请求
"""
# Arrange
mock_post = mocker.patch('requests.post')
mock_response = MagicMock()
mock_response.status_code = 200
# Mock SSE stream lines
mock_response.iter_lines.return_value = [
b'data: {"event": "message", "answer": "Hello"}',
b'',
b'data: {"event": "message", "answer": " World"}',
b'',
b'data: {"event": "message_end", "metadata": {"usage": {"total_tokens": 10}}}'
]
mock_post.return_value.__enter__.return_value = mock_response
# Mock DB logging
mocker.patch('app.services.dify.DifyService._log_chat')
# Setup decorator mocks
mock_user = User(id=1, username="test_user")
mock_agent = Agent(id=1, name="Test Agent", dify_api_key="key", api_base_url="http://mock-api")
mock_user.agents = [mock_agent] # Grant permission
# Mock decorator dependencies
# IMPORTANT: require_agent_permission calls _get_current_user() from app.decorators
# We use side_effect to ensure g.current_user is set, as the real function does
def mock_get_user():
g.current_user = mock_user
return mock_user
mocker.patch('app.decorators._get_current_user', side_effect=mock_get_user)
# Mock Agent.query.get used in require_agent_permission
mock_agent_query.get.return_value = mock_agent
# Act
payload = {
"query": "Hello",
"agent_id": 1,
"response_mode": "streaming"
}
headers = {'Content-Type': 'application/json'}
response = client.post('/api/chat/completions', json=payload, headers=headers)
# Assert
assert response.status_code == 200
assert response.mimetype == 'text/event-stream'
assert b'data: {"event": "message", "answer": "Hello"}' in response.data
def test_chat_completions_no_permission(client, mocker, mock_agent_query):
"""
[Chat] 无权限访问 Agent (Error)
"""
# Arrange
mock_user = User(id=1, username="test_user")
mock_agent = Agent(id=2, name="Restricted Agent")
mock_user.agents = [] # No permission
mocker.patch('app.decorators._get_current_user', return_value=mock_user)
mock_agent_query.get.return_value = mock_agent
# Act
payload = {"query": "Hello", "agent_id": 2}
response = client.post('/api/chat/completions', json=payload)
# Assert
assert response.status_code == 403
assert "Permission denied" in response.get_json()['error']
def test_submit_feedback_success(client, mocker, mock_chat_log_query, mock_agent_query, mock_db_session):
"""
[Chat] 提交反馈 (Happy Path)
"""
# Arrange
mock_user = User(id=1)
mock_agent = Agent(id=1)
mock_user.agents = [mock_agent]
def mock_get_user():
g.current_user = mock_user
return mock_user
mocker.patch('app.decorators._get_current_user', side_effect=mock_get_user)
mock_agent_query.get.return_value = mock_agent
# Mock ChatLog query
mock_log = ChatLog(id=100, user_id=1, agent_id=1, feedback=None)
mock_chat_log_query.filter_by.return_value.filter_by.return_value.order_by.return_value.first.return_value = mock_log
# Act
payload = {
"agent_id": 1,
"conversation_id": "conv_123",
"score": 5,
"comment": "Great!"
}
response = client.post('/api/chat/feedback', json=payload)
# Assert
assert response.status_code == 200
mock_db_session.add.assert_called_once()
mock_db_session.commit.assert_called_once()
def test_submit_feedback_invalid_score(client, mocker, mock_agent_query):
"""
[Chat] 提交反馈 - 分数无效 (Boundary)
"""
# Arrange
mock_user = User(id=1)
mock_agent = Agent(id=1)
mock_user.agents = [mock_agent]
mocker.patch('app.decorators._get_current_user', return_value=mock_user)
mock_agent_query.get.return_value = mock_agent
# Act
payload = {"agent_id": 1, "score": 6} # Score > 5
response = client.post('/api/chat/feedback', json=payload)
# Assert
assert response.status_code == 400
assert "between 1 and 5" in response.get_json()['error']
# -----------------------------------------------------------------------------
# 4. Permission Request Tests
# -----------------------------------------------------------------------------
def test_create_permission_request(client, mocker, mock_db_session, mock_agent_query, mock_permission_request_query):
"""
[Permission] 用户申请权限 (Happy Path)
"""
# Arrange
mock_user = User(id=1, agents=[])
mock_agent = Agent(id=5)
mocker.patch('app.api.user._get_current_user', return_value=mock_user)
mock_agent_query.get.return_value = mock_agent
# Ensure no existing pending request
mock_permission_request_query.filter_by.return_value.first.return_value = None
# Act
payload = {"agent_id": 5, "reason": "Need access"}
response = client.post('/api/user/permission-requests', json=payload)
# Assert
assert response.status_code == 201
mock_db_session.add.assert_called_once()
mock_db_session.commit.assert_called_once()
def test_create_permission_request_already_exists(client, mocker, mock_agent_query, mock_permission_request_query):
"""
[Permission] 用户重复申请权限 (Error)
"""
# Arrange
mock_user = User(id=1, agents=[])
mock_agent = Agent(id=5)
mocker.patch('app.api.user._get_current_user', return_value=mock_user)
mock_agent_query.get.return_value = mock_agent
# Mock existing pending request
mock_permission_request_query.filter_by.return_value.first.return_value = PermissionRequest(id=1)
# Act
payload = {"agent_id": 5}
response = client.post('/api/user/permission-requests', json=payload)
# Assert
assert response.status_code == 400
assert "Request already pending" in response.get_json()['error']
def test_admin_approve_permission_request(client, admin_headers, mock_permission_request_query, mock_user_query, mock_agent_query, mock_db_session, mocker):
"""
[Admin] 同意权限申请 (Happy Path)
"""
# Arrange
mock_pr = PermissionRequest(id=1, user_id=2, agent_id=5, status='pending')
mock_user = User(id=2, agents=[])
mock_agent = Agent(id=5)
# Mock PermissionRequest.query.get
mock_permission_request_query.get.return_value = mock_pr
# Mock User.query.get
mock_user_query.get.return_value = mock_user
# Mock Agent.query.get
mock_agent_query.get.return_value = mock_agent
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.post('/api/admin/permission-requests/1/approve', headers=admin_headers)
# Assert
assert response.status_code == 200
assert mock_pr.status == 'approved'
assert mock_agent in mock_user.agents
mock_db_session.commit.assert_called_once()
# -----------------------------------------------------------------------------
# 5. Quick Question Tests
# -----------------------------------------------------------------------------
def test_add_quick_question(client, mocker, mock_db_session):
"""
[QuickQuestion] 添加常用问题 (Happy Path)
"""
# Arrange
mock_user = User(id=1)
mocker.patch('app.api.user._get_current_user', return_value=mock_user)
# Act
payload = {
"title": "Daily Report",
"question": "Generate report...",
"agent_id": 1
}
response = client.post('/api/user/quick-questions', json=payload)
# Assert
assert response.status_code == 201
mock_db_session.add.assert_called_once()
mock_db_session.commit.assert_called_once()
def test_delete_quick_question(client, mocker, mock_db_session):
"""
[QuickQuestion] 删除常用问题 (Happy Path)
"""
# Arrange
mock_user = User(id=1)
mocker.patch('app.api.user._get_current_user', return_value=mock_user)
mock_qq = QuickQuestion(id=10, user_id=1)
# Mock query: filter_by(id=10, user_id=1).first() -> mock_qq
mocker.patch('app.db.session.query').return_value.filter_by.return_value.first.return_value = mock_qq
# Act
response = client.delete('/api/user/quick-questions/10')
# Assert
assert response.status_code == 200
mock_db_session.delete.assert_called_once_with(mock_qq)
mock_db_session.commit.assert_called_once()
+114
View File
@@ -0,0 +1,114 @@
import pytest
from app import create_app, db
from app.models import User, Agent, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig
@pytest.fixture
def client():
app = create_app('testing')
with app.test_client() as client:
with app.app_context():
db.create_all()
# Create user
user = User(username='testuser', role='user', email='test@example.com')
user.set_password('password')
db.session.add(user)
# Create agents
a1 = Agent(name='Agent 1', dify_app_id='app-1', dify_api_key='key-1')
a2 = Agent(name='Agent 2', dify_app_id='app-2', dify_api_key='key-2')
a3 = Agent(name='Agent 3', dify_app_id='app-3', dify_api_key='key-3')
db.session.add_all([a1, a2, a3])
# Grant permission
user.agents.append(a1)
user.agents.append(a2)
user.agents.append(a3)
db.session.commit()
yield client
db.session.remove()
db.drop_all()
def get_headers(client):
res = client.post('/api/user/login', json={'username': 'testuser', 'password': 'password'})
data = res.get_json()
return {
'X-User-Id': str(data['id']),
'X-Username': data['username'],
'X-Role': data['role']
}
def get_agent_id(client, name):
# Helper to get agent ID by name (since we can't query DB directly easily outside context without binding)
# But we can use the API
# Or just rely on order since we are in a fresh DB
# Let's assume IDs are 1, 2, 3 for now if using SQLite.
# To be safe, let's fetch from public-agents or user-home
# But we need headers for user-home.
pass
def test_favorites(client):
headers = get_headers(client)
# Get agent ID
res = client.get('/api/user/home', headers=headers)
agents = res.get_json()['agents']
agent_id = agents[0]['id']
# Add favorite
res = client.post(f'/api/user/favorites/{agent_id}', headers=headers)
assert res.status_code == 200
# Check home
res = client.get('/api/user/home', headers=headers)
data = res.get_json()
assert agent_id in data['favorite_agent_ids']
# Remove favorite
res = client.delete(f'/api/user/favorites/{agent_id}', headers=headers)
assert res.status_code == 200
# Check home
res = client.get('/api/user/home', headers=headers)
data = res.get_json()
assert agent_id not in data['favorite_agent_ids']
def test_homepage_layout(client):
headers = get_headers(client)
layout = {'sections': [{'id': 'favorites'}, {'id': 'all_agents'}]}
# Update layout
res = client.put('/api/user/homepage-layout', json={'layout': layout}, headers=headers)
assert res.status_code == 200
# Check home
res = client.get('/api/user/home', headers=headers)
data = res.get_json()
assert data['layout']['sections'][0]['id'] == 'favorites'
def test_embedded_agents(client):
headers = get_headers(client)
# Get agent IDs
res = client.get('/api/user/home', headers=headers)
agents = res.get_json()['agents']
id1 = agents[0]['id']
id2 = agents[1]['id']
id3 = agents[2]['id']
# Update embedded agents
res = client.put('/api/user/embedded-agents', json={'agent_ids': [id1, id2]}, headers=headers)
assert res.status_code == 200
# Check home
res = client.get('/api/user/home', headers=headers)
data = res.get_json()
assert len(data['embedded_agents']) == 2
assert data['embedded_agents'][0]['id'] == id1
assert data['embedded_agents'][1]['id'] == id2
# Try more than 2
res = client.put('/api/user/embedded-agents', json={'agent_ids': [id1, id2, id3]}, headers=headers)
assert res.status_code == 400
+87
View File
@@ -0,0 +1,87 @@
import pytest
from app.models import User
from app import db
def test_register_fields_validation(client):
"""
Test user registration field validation
"""
# 1. Missing fields
response = client.post('/api/user/register', json={
"username": "missing",
"password": "pwd",
"email": "m@e.com"
})
assert response.status_code == 400
assert "Real name and Employee ID are required" in response.json['error']
# 2. Duplicate Employee ID
# First create a user (via admin to bypass check or register with valid data)
# Let's register one valid user
valid_user = {
"username": "user1",
"password": "pwd",
"email": "u1@e.com",
"real_name": "User One",
"employee_id": "EMP100",
"phone_number": "13800000001"
}
response = client.post('/api/user/register', json=valid_user)
assert response.status_code == 201
# Now try to register another user with SAME employee_id
dup_user = {
"username": "user2",
"password": "pwd",
"email": "u2@e.com",
"real_name": "User Two",
"employee_id": "EMP100",
"phone_number": "13800000002"
}
response = client.post('/api/user/register', json=dup_user)
assert response.status_code == 400
assert "Employee ID already exists" in response.json['error']
def test_admin_duplicate_employee_id(client, admin_headers):
"""
Test admin user creation duplicate employee_id check
"""
# 1. Create first user
u1 = {
"username": "adm_u1",
"password": "pwd",
"email": "au1@e.com",
"real_name": "Admin User 1",
"employee_id": "ADM001"
}
response = client.post('/api/admin/users', json=u1, headers=admin_headers)
assert response.status_code == 201
# 2. Create second user with same ID
u2 = {
"username": "adm_u2",
"password": "pwd",
"email": "au2@e.com",
"real_name": "Admin User 2",
"employee_id": "ADM001"
}
response = client.post('/api/admin/users', json=u2, headers=admin_headers)
assert response.status_code == 400
assert "Employee ID already exists" in response.json['error']
# 3. Update user to duplicate ID
# Create u3 with valid ID
u3 = {
"username": "adm_u3",
"password": "pwd",
"email": "au3@e.com",
"real_name": "Admin User 3",
"employee_id": "ADM003"
}
res = client.post('/api/admin/users', json=u3, headers=admin_headers)
u3_id = res.json['id']
# Update u3 to ADM001 (which exists)
res = client.put(f'/api/admin/users/{u3_id}', json={"employee_id": "ADM001"}, headers=admin_headers)
assert res.status_code == 400
assert "Employee ID already exists" in res.json['error']