Merge branch 'runny&xinxin' into dev
This commit is contained in:
commit
8d73343bd8
77 files changed
+17955
-274
No files matched your search
+157
-98
@@ -5,7 +5,7 @@ from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_even
|
||||
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.auth_jwt import get_current_user as _auth_current_user
|
||||
from app.auth_jwt import issue_local_access_token
|
||||
from sqlalchemy.exc import IntegrityError, OperationalError
|
||||
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
|
||||
from sqlalchemy import and_, or_, inspect, insert
|
||||
from datetime import datetime, timedelta
|
||||
import uuid
|
||||
@@ -147,6 +147,20 @@ def _get_current_user():
|
||||
"""
|
||||
return _auth_current_user()
|
||||
|
||||
|
||||
def _run_db_with_retry(operation, *, label: str):
|
||||
try:
|
||||
return operation()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('%s failed on first attempt: %s', label, exc)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception as dispose_exc:
|
||||
current_app.logger.warning('%s dispose engine failed: %s', label, dispose_exc)
|
||||
return operation()
|
||||
|
||||
def _is_wecom_configured():
|
||||
return all([
|
||||
current_app.config.get('WECOM_ENABLED'),
|
||||
@@ -891,7 +905,7 @@ def login():
|
||||
'error_code': 'PASSWORD_LOGIN_DISABLED',
|
||||
}), 403
|
||||
|
||||
try:
|
||||
def _attempt_login():
|
||||
data = request.get_json() or {}
|
||||
username = data.get('username')
|
||||
password = data.get('password')
|
||||
@@ -919,12 +933,28 @@ def login():
|
||||
_write_login_audit('password', 'success', user=user)
|
||||
db.session.commit()
|
||||
return jsonify(_build_login_payload(user, 'password'))
|
||||
|
||||
try:
|
||||
return _attempt_login()
|
||||
except OperationalError as e:
|
||||
print(f"Database connection error: {e}")
|
||||
return jsonify({'error': 'Database connection failed'}), 503
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
return _attempt_login()
|
||||
except (OperationalError, DatabaseError) as retry_exc:
|
||||
current_app.logger.warning('Password login retry failed: %s', retry_exc)
|
||||
return jsonify({'error': 'Database connection failed'}), 503
|
||||
except DatabaseError as e:
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
return _attempt_login()
|
||||
except (OperationalError, DatabaseError) as retry_exc:
|
||||
current_app.logger.warning('Password login retry failed: %s', retry_exc)
|
||||
return jsonify({'error': 'Database connection failed'}), 503
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
print(f"Login error: {e}")
|
||||
current_app.logger.exception('Login error: %s', e)
|
||||
return jsonify({'error': 'Internal server error'}), 500
|
||||
|
||||
|
||||
@@ -1720,64 +1750,76 @@ def home():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
|
||||
# Get all agents available to user (including public ones)
|
||||
if user.role == 'admin':
|
||||
agents = db.session.query(Agent).filter_by(is_active=True).all()
|
||||
else:
|
||||
# User permissions
|
||||
agents = user.agents
|
||||
|
||||
# Favorites
|
||||
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
|
||||
favorite_ids = [f.agent_id for f in favorites]
|
||||
|
||||
# Quick Questions (Global + User specific)
|
||||
qqs = db.session.query(QuickQuestion).filter(
|
||||
(QuickQuestion.user_id == user.id) | (QuickQuestion.user_id == None)
|
||||
).all()
|
||||
|
||||
# Layout
|
||||
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||||
layout = layout_config.layout if layout_config else {}
|
||||
|
||||
# Embedded agents
|
||||
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
|
||||
embedded_agents = []
|
||||
for rel in embedded_rel:
|
||||
agent = db.session.get(Agent, rel.agent_id)
|
||||
if agent:
|
||||
embedded_agents.append({
|
||||
|
||||
def _load_home_payload():
|
||||
# Get all agents available to user (including public ones)
|
||||
if user.role == 'admin':
|
||||
agent_rows = (
|
||||
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.all()
|
||||
)
|
||||
else:
|
||||
# User permissions
|
||||
agent_rows = [{
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None
|
||||
})
|
||||
'description': agent.description,
|
||||
'icon_url': agent.icon_url,
|
||||
} for agent in user.agents]
|
||||
|
||||
return jsonify({
|
||||
'user': {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'default_agent_id': user.default_agent_id,
|
||||
'language': user.language,
|
||||
'theme_preference': user.theme_preference or 'system',
|
||||
},
|
||||
'agents': [{
|
||||
'id': a.id,
|
||||
'name': a.name,
|
||||
'description': a.description,
|
||||
'icon_url': a.icon_url
|
||||
} for a in agents],
|
||||
'favorite_agent_ids': favorite_ids,
|
||||
'quick_questions': [{
|
||||
'id': q.id,
|
||||
'title': q.title,
|
||||
'question': q.question,
|
||||
'agent_id': q.agent_id
|
||||
} for q in qqs],
|
||||
'embedded_agents': embedded_agents,
|
||||
'layout': layout
|
||||
})
|
||||
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
|
||||
favorite_ids = [f.agent_id for f in favorites]
|
||||
|
||||
qqs = db.session.query(QuickQuestion).filter(
|
||||
(QuickQuestion.user_id == user.id) | (QuickQuestion.user_id == None)
|
||||
).all()
|
||||
|
||||
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||||
layout = layout_config.layout if layout_config else {}
|
||||
|
||||
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
|
||||
embedded_agents = []
|
||||
for rel in embedded_rel:
|
||||
agent = db.session.get(Agent, rel.agent_id)
|
||||
if agent:
|
||||
embedded_agents.append({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None
|
||||
})
|
||||
|
||||
return jsonify({
|
||||
'user': {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'default_agent_id': user.default_agent_id,
|
||||
'language': user.language,
|
||||
'theme_preference': user.theme_preference or 'system',
|
||||
},
|
||||
'agents': [{
|
||||
'id': a.id if hasattr(a, 'id') else a['id'],
|
||||
'name': a.name if hasattr(a, 'name') else a['name'],
|
||||
'description': a.description if hasattr(a, 'description') else a['description'],
|
||||
'icon_url': a.icon_url if hasattr(a, 'icon_url') else a['icon_url']
|
||||
} for a in agent_rows],
|
||||
'favorite_agent_ids': favorite_ids,
|
||||
'quick_questions': [{
|
||||
'id': q.id,
|
||||
'title': q.title,
|
||||
'question': q.question,
|
||||
'agent_id': q.agent_id
|
||||
} for q in qqs],
|
||||
'embedded_agents': embedded_agents,
|
||||
'layout': layout
|
||||
})
|
||||
|
||||
try:
|
||||
return _run_db_with_retry(_load_home_payload, label='user.home')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('user.home retry failed: %s', exc)
|
||||
return jsonify({'error': 'Database connection failed'}), 503
|
||||
|
||||
@user_bp.route('/favorites/<int:agent_id>', methods=['POST', 'DELETE'])
|
||||
def toggle_favorite(agent_id: int):
|
||||
@@ -1888,41 +1930,45 @@ def user_profile():
|
||||
|
||||
# PUT
|
||||
data = request.get_json() or {}
|
||||
|
||||
if 'real_name' in data:
|
||||
user.real_name = data['real_name']
|
||||
if 'phone_number' in data:
|
||||
user.phone_number = data['phone_number']
|
||||
if 'language' in data:
|
||||
user.language = data['language']
|
||||
if 'theme_preference' in data:
|
||||
if data['theme_preference'] not in ['light', 'dark', 'system']:
|
||||
return jsonify({'error': 'Invalid theme preference'}), 400
|
||||
user.theme_preference = data['theme_preference']
|
||||
|
||||
# Allow editing email, employee_id, department
|
||||
if 'email' in data:
|
||||
# Check uniqueness
|
||||
if data['email']:
|
||||
existing = db.session.query(User).filter_by(email=data['email']).first()
|
||||
if existing and existing.id != user.id:
|
||||
return jsonify({'error': 'Email already exists'}), 400
|
||||
user.email = data['email']
|
||||
|
||||
if 'employee_id' in data:
|
||||
# Check uniqueness
|
||||
if data['employee_id']:
|
||||
existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first()
|
||||
if existing and existing.id != user.id:
|
||||
return jsonify({'error': 'Employee ID already exists'}), 400
|
||||
user.employee_id = data['employee_id']
|
||||
|
||||
if 'department' in data:
|
||||
user.department = data['department']
|
||||
|
||||
try:
|
||||
|
||||
def _update_profile():
|
||||
if 'real_name' in data:
|
||||
user.real_name = data['real_name']
|
||||
if 'phone_number' in data:
|
||||
user.phone_number = data['phone_number']
|
||||
if 'language' in data:
|
||||
user.language = data['language']
|
||||
if 'theme_preference' in data:
|
||||
if data['theme_preference'] not in ['light', 'dark', 'system']:
|
||||
return jsonify({'error': 'Invalid theme preference'}), 400
|
||||
user.theme_preference = data['theme_preference']
|
||||
|
||||
if 'email' in data:
|
||||
if data['email']:
|
||||
existing = db.session.query(User).filter_by(email=data['email']).first()
|
||||
if existing and existing.id != user.id:
|
||||
return jsonify({'error': 'Email already exists'}), 400
|
||||
user.email = data['email']
|
||||
|
||||
if 'employee_id' in data:
|
||||
if data['employee_id']:
|
||||
existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first()
|
||||
if existing and existing.id != user.id:
|
||||
return jsonify({'error': 'Employee ID already exists'}), 400
|
||||
user.employee_id = data['employee_id']
|
||||
|
||||
if 'department' in data:
|
||||
user.department = data['department']
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Profile updated successfully'})
|
||||
|
||||
try:
|
||||
return _run_db_with_retry(_update_profile, label='user.profile.update')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
db.session.rollback()
|
||||
current_app.logger.warning('user.profile.update retry failed: %s', exc)
|
||||
return jsonify({'error': 'Database connection failed'}), 503
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
return jsonify({'error': str(e)}), 500
|
||||
@@ -2055,17 +2101,30 @@ def get_announcements():
|
||||
"""
|
||||
Get active announcements (Public)
|
||||
"""
|
||||
try:
|
||||
anns = db.session.query(Announcement).filter_by(is_active=True).order_by(Announcement.created_at.desc()).all()
|
||||
def _load_announcements():
|
||||
anns = (
|
||||
db.session.query(
|
||||
Announcement.id,
|
||||
Announcement.title,
|
||||
Announcement.content,
|
||||
Announcement.created_at,
|
||||
)
|
||||
.filter(Announcement.is_active.is_(True))
|
||||
.order_by(Announcement.created_at.desc())
|
||||
.all()
|
||||
)
|
||||
return jsonify([{
|
||||
'id': a.id,
|
||||
'title': a.title,
|
||||
'content': a.content,
|
||||
'created_at': a.created_at.isoformat()
|
||||
} for a in anns])
|
||||
except Exception as e:
|
||||
import traceback
|
||||
return jsonify({'error': str(e), 'traceback': traceback.format_exc()}), 500
|
||||
|
||||
try:
|
||||
return _run_db_with_retry(_load_announcements, label='user.announcements')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('user.announcements retry failed: %s', exc)
|
||||
return jsonify({'error': 'Database connection failed'}), 503
|
||||
|
||||
@user_bp.route('/announcements', methods=['POST'])
|
||||
def create_announcement():
|
||||
|
||||
Reference in new issue
Block a user