Merge branch 'dev' into hugo
This commit is contained in:
commit
97a5a1f106
35 files changed
+3749
-259
No files matched your search
+243
-26
@@ -596,11 +596,11 @@ def create_user():
|
||||
@require_admin
|
||||
def update_user(id):
|
||||
"""
|
||||
管理端编辑用户:本地变更 commit 前先同步 Casdoor update-user / set-password。
|
||||
核心逻辑:应用本地字段 → _sync_casdoor_update_user → commit;Casdoor 失败则 rollback。
|
||||
管理端编辑用户:资料仅写本地库;仅改密时同步 Casdoor set-password。
|
||||
核心逻辑:应用本地字段 →(有 new_password 时)_sync_casdoor_update_user → commit。
|
||||
Request JSON: email, department, role, status, password 等;password 为空表示不改密
|
||||
Returns:
|
||||
{ status: ok };Casdoor/唯一约束失败时抛出 AppError/ConflictError
|
||||
{ status: ok };Casdoor 改密/唯一约束失败时抛出 AppError/ConflictError
|
||||
"""
|
||||
from app.api import user as user_api
|
||||
user = db.session.get(User, id)
|
||||
@@ -611,8 +611,6 @@ def update_user(id):
|
||||
email = _empty_to_none(data.get('email'))
|
||||
if email is not None and (not _is_valid_email(email)):
|
||||
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
|
||||
profile_field_keys = {'email', 'department', 'status', 'real_name', 'phone_number'}
|
||||
sync_profile = any(k in data for k in profile_field_keys)
|
||||
new_password = _empty_to_none(data.get('password'))
|
||||
for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||
if k in data:
|
||||
@@ -626,12 +624,8 @@ def update_user(id):
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
try:
|
||||
if sync_profile or new_password:
|
||||
user_api._sync_casdoor_update_user(
|
||||
user,
|
||||
new_password=new_password,
|
||||
sync_profile=sync_profile,
|
||||
)
|
||||
if new_password:
|
||||
user_api._sync_casdoor_update_user(user, new_password=new_password)
|
||||
db.session.commit()
|
||||
except IntegrityError as e:
|
||||
db.session.rollback()
|
||||
@@ -641,7 +635,7 @@ def update_user(id):
|
||||
raise
|
||||
except RuntimeError as e:
|
||||
db.session.rollback()
|
||||
user_api._raise_casdoor_update_user_error(e)
|
||||
user_api._raise_casdoor_set_password_error(e)
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
||||
@@ -808,39 +802,148 @@ def reject_request(id):
|
||||
@admin_bp.route('/quick-questions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_quick_questions():
|
||||
qqs = db.session.query(QuickQuestion).filter(QuickQuestion.user_id == None).order_by(QuickQuestion.sort_order.asc()).all()
|
||||
"""
|
||||
列出全局常用问题(含 FAQ 缓存字段)。
|
||||
@returns JSON 数组,每项含 answer/cache_enabled/hit_count 等扩展字段
|
||||
"""
|
||||
qqs = (
|
||||
db.session.query(QuickQuestion)
|
||||
.filter(QuickQuestion.user_id.is_(None))
|
||||
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.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})
|
||||
res.append(_serialize_admin_quick_question(q, agent.name if agent else 'Unknown'))
|
||||
return jsonify(res)
|
||||
|
||||
|
||||
def _parse_aliases(raw_aliases) -> list[str]:
|
||||
"""
|
||||
解析别名列表,支持 JSON 数组或换行分隔字符串。
|
||||
@param raw_aliases - 请求体 aliases 字段
|
||||
@returns 去重后的别名字符串列表
|
||||
"""
|
||||
if raw_aliases is None:
|
||||
return []
|
||||
if isinstance(raw_aliases, list):
|
||||
items = [str(item).strip() for item in raw_aliases if str(item).strip()]
|
||||
elif isinstance(raw_aliases, str):
|
||||
items = [line.strip() for line in raw_aliases.splitlines() if line.strip()]
|
||||
else:
|
||||
return []
|
||||
seen: set[str] = set()
|
||||
result: list[str] = []
|
||||
for item in items:
|
||||
if item not in seen:
|
||||
seen.add(item)
|
||||
result.append(item)
|
||||
return result
|
||||
|
||||
|
||||
def _parse_expires_at(raw_value) -> datetime | None:
|
||||
"""
|
||||
解析 FAQ 过期时间。
|
||||
@param raw_value - ISO 字符串或 None
|
||||
@returns datetime 或 None
|
||||
"""
|
||||
if not raw_value:
|
||||
return None
|
||||
text = str(raw_value).strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return datetime.fromisoformat(text.replace('Z', '+00:00')).replace(tzinfo=None)
|
||||
except ValueError:
|
||||
raise ValidationError('Invalid expires_at format')
|
||||
|
||||
|
||||
def _serialize_admin_quick_question(q: QuickQuestion, agent_name: str) -> dict:
|
||||
"""
|
||||
序列化全局常用问题供管理端展示。
|
||||
@param q - QuickQuestion 实例
|
||||
@param agent_name - 所属应用名称
|
||||
@returns 可 JSON 化的字典
|
||||
"""
|
||||
return {
|
||||
'id': q.id,
|
||||
'title': q.title,
|
||||
'question': q.question,
|
||||
'answer': q.answer,
|
||||
'aliases': q.aliases if isinstance(q.aliases, list) else [],
|
||||
'cache_enabled': bool(q.cache_enabled),
|
||||
'is_enabled': bool(q.is_enabled),
|
||||
'hit_count': q.hit_count or 0,
|
||||
'agent_id': q.agent_id,
|
||||
'agent_name': agent_name,
|
||||
'sort_order': q.sort_order,
|
||||
'expires_at': q.expires_at.isoformat() if q.expires_at else None,
|
||||
'updated_at': q.updated_at.isoformat() if getattr(q, 'updated_at', None) else None,
|
||||
}
|
||||
|
||||
|
||||
def _apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answer: bool = False) -> None:
|
||||
"""
|
||||
将请求体字段写入 QuickQuestion 实例。
|
||||
@param qq - 待更新的 QuickQuestion
|
||||
@param data - 请求 JSON
|
||||
@param require_answer - 创建时为 True,cache_enabled 时强制校验 answer
|
||||
"""
|
||||
if 'title' in data:
|
||||
qq.title = str(data['title']).strip()
|
||||
if 'question' in data:
|
||||
qq.question = str(data['question']).strip()
|
||||
if 'agent_id' in data:
|
||||
qq.agent_id = data['agent_id']
|
||||
if 'sort_order' in data:
|
||||
qq.sort_order = data.get('sort_order', 0)
|
||||
if 'answer' in data:
|
||||
qq.answer = str(data['answer']).strip() or None
|
||||
if 'aliases' in data:
|
||||
qq.aliases = _parse_aliases(data['aliases'])
|
||||
if 'cache_enabled' in data:
|
||||
qq.cache_enabled = bool(data['cache_enabled'])
|
||||
if 'is_enabled' in data:
|
||||
qq.is_enabled = bool(data['is_enabled'])
|
||||
if 'expires_at' in data:
|
||||
qq.expires_at = _parse_expires_at(data['expires_at'])
|
||||
|
||||
if qq.cache_enabled and not str(qq.answer or '').strip():
|
||||
raise ValidationError('启用 FAQ 缓存时必须填写标准答案')
|
||||
if require_answer and (not qq.title or not qq.question or not qq.agent_id):
|
||||
raise ValidationError('Missing required fields')
|
||||
|
||||
|
||||
@admin_bp.route('/quick-questions', methods=['POST'])
|
||||
@require_admin
|
||||
def create_quick_question():
|
||||
"""
|
||||
创建全局常用问题,可选启用 FAQ 缓存。
|
||||
@returns 201 + {id}
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
if not data.get('title') or not data.get('question') or (not data.get('agent_id')):
|
||||
raise ValidationError('Missing required fields')
|
||||
qq = QuickQuestion(user_id=None, agent_id=data['agent_id'], title=data['title'], question=data['question'], sort_order=data.get('sort_order', 0))
|
||||
qq = QuickQuestion(user_id=None)
|
||||
_apply_quick_question_payload(qq, data, require_answer=True)
|
||||
qq.updated_at = datetime.utcnow()
|
||||
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):
|
||||
"""
|
||||
更新全局常用问题及 FAQ 缓存配置。
|
||||
@returns {status: ok}
|
||||
"""
|
||||
qq = db.session.get(QuickQuestion, id)
|
||||
if not qq:
|
||||
if not qq or qq.user_id is not None:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json() or {}
|
||||
if 'title' in data:
|
||||
qq.title = data['title']
|
||||
if 'question' in data:
|
||||
qq.question = data['question']
|
||||
if 'agent_id' in data:
|
||||
qq.agent_id = data['agent_id']
|
||||
if 'sort_order' in data:
|
||||
qq.sort_order = data['sort_order']
|
||||
_apply_quick_question_payload(qq, data)
|
||||
qq.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@@ -853,6 +956,120 @@ def delete_quick_question(id):
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates', methods=['GET'])
|
||||
@require_admin
|
||||
def list_faq_candidates():
|
||||
"""
|
||||
列出 PostgreSQL 中的热点 FAQ 候选(离线聚合结果)。
|
||||
@query agent_id - 可选,按应用筛选
|
||||
@returns { items, stats, rules }
|
||||
"""
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
||||
|
||||
agent_id = request.args.get('agent_id', type=int)
|
||||
items = HotFaqCandidateStore.list_candidates(agent_id)
|
||||
stats = HotFaqCandidateStore.summarize(items)
|
||||
return jsonify({
|
||||
'items': items,
|
||||
'stats': stats,
|
||||
'rules': HotFaqAggregator.get_rules_document(),
|
||||
})
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/refresh', methods=['POST'])
|
||||
@require_admin
|
||||
def refresh_faq_candidates():
|
||||
"""
|
||||
手动触发离线热点聚合。
|
||||
@body agent_id - 可选;dry_run - 可选,仅预览
|
||||
@returns 聚合结果摘要
|
||||
"""
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
agent_id = data.get('agent_id')
|
||||
dry_run = bool(data.get('dry_run'))
|
||||
if agent_id is not None:
|
||||
agent_id = int(agent_id)
|
||||
|
||||
result = HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/promote', methods=['POST'])
|
||||
@require_admin
|
||||
def promote_faq_candidate():
|
||||
"""
|
||||
将热点候选晋升为全局 QuickQuestion(启用 FAQ 缓存),同事务更新候选状态。
|
||||
@body agent_id, q_norm - 必填;title - 可选
|
||||
@returns { id } 新建 QuickQuestion 主键
|
||||
"""
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
||||
|
||||
data = request.get_json() or {}
|
||||
agent_id = data.get('agent_id')
|
||||
q_norm = normalize_faq_query(str(data.get('q_norm') or ''))
|
||||
if not agent_id or not q_norm:
|
||||
raise ValidationError('agent_id and q_norm are required')
|
||||
|
||||
candidate = HotFaqCandidateStore.get_candidate(int(agent_id), q_norm)
|
||||
if not candidate:
|
||||
raise NotFoundError('FAQ candidate not found')
|
||||
|
||||
title = str(data.get('title') or candidate.get('canonical_query') or q_norm).strip()[:100]
|
||||
question = str(candidate.get('canonical_query') or q_norm).strip()
|
||||
answer = str(candidate.get('answer') or '').strip()
|
||||
if not answer:
|
||||
raise ValidationError('Candidate has no answer')
|
||||
|
||||
aliases = [q for q in (candidate.get('sample_queries') or []) if normalize_faq_query(q) != q_norm]
|
||||
|
||||
qq = QuickQuestion(
|
||||
user_id=None,
|
||||
agent_id=int(agent_id),
|
||||
title=title,
|
||||
question=question,
|
||||
answer=answer,
|
||||
aliases=aliases or None,
|
||||
cache_enabled=True,
|
||||
is_enabled=True,
|
||||
retriever_resources=candidate.get('retriever_resources') if isinstance(candidate.get('retriever_resources'), list) else None,
|
||||
sort_order=int(data.get('sort_order') or 0),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(qq)
|
||||
db.session.flush()
|
||||
if not HotFaqCandidateStore.mark_promoted(int(agent_id), q_norm, qq.id):
|
||||
db.session.rollback()
|
||||
raise NotFoundError('FAQ candidate not found')
|
||||
db.session.commit()
|
||||
return jsonify({'id': qq.id, 'status': 'ok'})
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/dismiss', methods=['POST'])
|
||||
@require_admin
|
||||
def dismiss_faq_candidate():
|
||||
"""
|
||||
忽略热点候选:标记 dismissed 并设置 deny_until。
|
||||
@body agent_id, q_norm - 必填
|
||||
@returns { status: ok }
|
||||
"""
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
||||
|
||||
data = request.get_json() or {}
|
||||
agent_id = data.get('agent_id')
|
||||
q_norm = normalize_faq_query(str(data.get('q_norm') or ''))
|
||||
if not agent_id or not q_norm:
|
||||
raise ValidationError('agent_id and q_norm are required')
|
||||
|
||||
HotFaqCandidateStore.dismiss(int(agent_id), q_norm)
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@admin_bp.route('/reports/usage', methods=['GET'])
|
||||
@require_admin
|
||||
def usage_report():
|
||||
|
||||
+14
-1
@@ -1153,7 +1153,20 @@ def chat_completions():
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
leave_supported = HRLeaveSQLServerService.supports(query)
|
||||
leave_feature_enabled = _can_use_leave_feature(agent_proxy)
|
||||
if PLMOracleService.supports(query, agent_proxy):
|
||||
|
||||
from app.services.faq_cache import FaqCacheService
|
||||
faq_hit = FaqCacheService.try_match(query, agent_id) if not normalized_files else None
|
||||
|
||||
if faq_hit:
|
||||
generator = FaqCacheService.stream_chat(
|
||||
faq_hit,
|
||||
query,
|
||||
user_proxy,
|
||||
agent_proxy,
|
||||
external_conversation_id,
|
||||
session_id=session.session_id,
|
||||
)
|
||||
elif PLMOracleService.supports(query, agent_proxy):
|
||||
generator = PLMOracleService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
elif leave_supported and leave_feature_enabled:
|
||||
if normalized_files:
|
||||
|
||||
+18
-39
@@ -463,22 +463,19 @@ def _sync_casdoor_admin_set_password(user: User, new_password: str):
|
||||
_raise_casdoor_user_not_in_idp(exc)
|
||||
_raise_casdoor_set_password_error(exc)
|
||||
|
||||
def _sync_casdoor_update_user(user: User, *, new_password: str | None = None, sync_profile: bool = True):
|
||||
def _sync_casdoor_update_user(user: User, *, new_password: str | None = None):
|
||||
"""
|
||||
管理端编辑用户时同步 Casdoor:资料走 update-user,密码走 set-password(管理员 override)。
|
||||
核心逻辑:Casdoor 已配置则必须成功;IdP 无账号且请求含新密码时 fallback add-user 补建。
|
||||
管理端编辑用户时同步 Casdoor:仅改密时 set-password;IdP 无账号则 add-user 补建。
|
||||
核心逻辑:资料字段只写本地库,不调用 update-user;无新密码则跳过 Casdoor。
|
||||
@param user: 已应用本地变更但未 commit 的 User 实例
|
||||
@param new_password: 管理员设置的新密码;None 表示不改密
|
||||
@param sync_profile: 是否同步资料字段(email/姓名/手机/部门/状态)
|
||||
Raises:
|
||||
AppError / ConflictError: Casdoor 同步失败
|
||||
AppError / ConflictError: Casdoor 改密或补建失败
|
||||
"""
|
||||
if not _is_casdoor_configured():
|
||||
if not _is_casdoor_configured() or not new_password:
|
||||
return
|
||||
|
||||
def _provision_missing_user_in_casdoor():
|
||||
if not new_password:
|
||||
_raise_casdoor_user_not_in_idp()
|
||||
_sync_casdoor_create_user(
|
||||
username=user.username,
|
||||
password=new_password,
|
||||
@@ -489,36 +486,13 @@ def _sync_casdoor_update_user(user: User, *, new_password: str | None = None, sy
|
||||
department=user.department,
|
||||
)
|
||||
|
||||
if sync_profile:
|
||||
profile_payload = _build_casdoor_user_profile_payload(
|
||||
username=user.username,
|
||||
email=user.email,
|
||||
real_name=user.real_name,
|
||||
phone_number=user.phone_number,
|
||||
status=user.status,
|
||||
department=user.department,
|
||||
)
|
||||
try:
|
||||
_casdoor_update_user(profile_payload)
|
||||
except AppError as exc:
|
||||
if exc.code == 'CASDOOR_USER_NOT_IN_IDP':
|
||||
_provision_missing_user_in_casdoor()
|
||||
return
|
||||
raise
|
||||
except RuntimeError as exc:
|
||||
if _is_casdoor_user_missing_error(str(exc)):
|
||||
_provision_missing_user_in_casdoor()
|
||||
return
|
||||
_raise_casdoor_update_user_error(exc)
|
||||
|
||||
if new_password:
|
||||
try:
|
||||
_sync_casdoor_admin_set_password(user, new_password)
|
||||
except AppError as exc:
|
||||
if exc.code == 'CASDOOR_USER_NOT_IN_IDP':
|
||||
_provision_missing_user_in_casdoor()
|
||||
return
|
||||
raise
|
||||
try:
|
||||
_sync_casdoor_admin_set_password(user, new_password)
|
||||
except AppError as exc:
|
||||
if exc.code == 'CASDOOR_USER_NOT_IN_IDP':
|
||||
_provision_missing_user_in_casdoor()
|
||||
return
|
||||
raise
|
||||
|
||||
def _is_casdoor_password_error(message: str) -> bool:
|
||||
lowered = (message or '').lower()
|
||||
@@ -1652,7 +1626,12 @@ def home():
|
||||
agent_rows = [{'id': agent.id, 'name': agent.name, 'description': agent.description, 'icon_url': agent.icon_url, 'extra_config': agent.extra_config} for agent in user.agents]
|
||||
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()
|
||||
qqs = db.session.query(QuickQuestion).filter(
|
||||
or_(
|
||||
QuickQuestion.user_id == user.id,
|
||||
and_(QuickQuestion.user_id.is_(None), QuickQuestion.is_enabled.is_(True)),
|
||||
)
|
||||
).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()
|
||||
|
||||
Reference in new issue
Block a user