Merge branch 'dev' into hugo-shipping-notice

This commit is contained in:
hugo committed 2026-07-14 21:18:10 +08:00
commit bc86720744
49 files changed
+2950 -458

No files matched your search

+30 -1
View File
@@ -3,7 +3,7 @@ backend/app/api/admin/reports.py
用途:管理后台报表 API(薄路由层)。
依赖:admin.blueprint、services/admin/report_service。
逻辑:/reports/* 路由。
逻辑:/reports/usage、/reports/applications、feedback 与 general-feedbacks 路由。
"""
from flask import jsonify, request
@@ -38,6 +38,35 @@ def usage_report():
)
@admin_bp.route('/reports/applications', methods=['GET'])
@require_admin
def applications_report():
"""
应用运营报表:按应用聚合使用 / 权限 / 评分。
Query: range, status, usage, q, sort, order, page, page_size。
"""
try:
page = int(request.args.get('page', 1))
except (TypeError, ValueError):
page = 1
try:
page_size = int(request.args.get('page_size', 20))
except (TypeError, ValueError):
page_size = 20
return jsonify(
report_service.build_application_report(
range_key=request.args.get('range'),
status=request.args.get('status'),
usage=request.args.get('usage'),
q=request.args.get('q'),
sort=request.args.get('sort'),
order=request.args.get('order'),
page=page,
page_size=page_size,
)
)
@admin_bp.route('/reports/feedback', methods=['GET'])
@require_admin
def feedback_report():
+47 -80
View File
@@ -8,6 +8,8 @@ backend/app/api/chat.py
import io
import ipaddress
import mimetypes
import ntpath
import posixpath
import tempfile
import os
import subprocess
@@ -226,26 +228,60 @@ def _update_chat_session(
return session
def _normalize_windows_share_path(path_value: str) -> str:
normalized = str(path_value or '').strip().strip('"').replace('/', '\\')
if normalized.startswith('\\\\'):
return '\\\\' + normalized[2:].rstrip('\\')
return normalized.rstrip('\\')
def _normalize_allowed_share_path(path_value: str) -> tuple[str, str]:
"""
统一归一化 Windows UNC / Windows 本地盘符 / Linux 挂载目录路径。
Returns:
(path_kind, normalized_path)
- path_kind: 'windows' | 'posix' | ''
- normalized_path: 归一化后的绝对路径文本
"""
raw_value = str(path_value or '').strip().strip('"')
if not raw_value:
return ('', '')
if raw_value.startswith('\\\\'):
normalized = raw_value.replace('/', '\\')
normalized = '\\\\' + normalized[2:].rstrip('\\')
return ('windows', normalized)
if len(raw_value) >= 3 and raw_value[1] == ':' and raw_value[2] in ('\\', '/'):
normalized = ntpath.normpath(raw_value.replace('/', '\\')).rstrip('\\')
return ('windows', normalized)
if raw_value.startswith('/'):
normalized = posixpath.normpath(raw_value.replace('\\', '/'))
return ('posix', normalized.rstrip('/'))
return ('', '')
def _is_path_within_allowed_root(target_path: str, root_path: str) -> bool:
target_kind, normalized_target = _normalize_allowed_share_path(target_path)
root_kind, normalized_root = _normalize_allowed_share_path(root_path)
if not normalized_target or not normalized_root or target_kind != root_kind:
return False
if target_kind == 'windows':
target_lower = normalized_target.lower()
root_lower = normalized_root.lower()
return target_lower == root_lower or target_lower.startswith(root_lower.rstrip('\\') + '\\')
return normalized_target == normalized_root or normalized_target.startswith(normalized_root.rstrip('/') + '/')
def _is_allowed_share_path(target_url: str) -> bool:
normalized_target = _normalize_windows_share_path(target_url)
if not normalized_target.startswith('\\\\'):
target_kind, normalized_target = _normalize_allowed_share_path(target_url)
if not normalized_target:
return False
history_share_root = ''
history_local_root = ''
if has_request_context():
history_share_root = str(current_app.config.get('FIXED_ASSET_HISTORY_SHARE_ROOT') or '').strip()
history_local_root = str(current_app.config.get('FIXED_ASSET_HISTORY_LOCAL_ROOT') or '').strip()
if not history_share_root:
history_share_root = str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or '').strip()
if not history_local_root:
history_local_root = str(Config.FIXED_ASSET_HISTORY_LOCAL_ROOT or '').strip()
roots = [
_normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT),
_normalize_windows_share_path(history_share_root),
PLM_PREVIEW_SHARE_ROOT,
history_share_root,
history_local_root,
]
return any(root and normalized_target.lower().startswith(root.lower()) for root in roots)
return any(root and _is_path_within_allowed_root(normalized_target, root) for root in roots)
def _is_allowed_preview_url(target_url: str) -> bool:
"""
@@ -300,7 +336,7 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
import sqlalchemy as sa
from urllib.parse import parse_qs
if _is_allowed_share_path(file_url):
normalized_path = _normalize_windows_share_path(file_url)
_path_kind, normalized_path = _normalize_allowed_share_path(file_url)
try:
if not os.path.isfile(normalized_path):
return (None, None, ('source file not found', 404))
@@ -1166,31 +1202,6 @@ def search_asset_history_files():
asset_name = (request.args.get('asset_name') or '').strip()
limit = request.args.get('limit', type=int) or 20
limit = max(1, min(limit, 50))
# #region debug-point C:asset-history-api-entry
import json as _debug_json
import urllib.request as _debug_urllib_request
try:
_debug_payload = _debug_json.dumps({
'sessionId': 'asset-history-click',
'runId': 'pre-fix',
'hypothesisId': 'C',
'location': 'backend/chat.py:search_asset_history_files',
'msg': '[DEBUG] asset history api entry',
'data': {
'asset_id': asset_id,
'asset_name': asset_name,
'limit': limit,
},
}).encode('utf-8')
_debug_urllib_request.urlopen(_debug_urllib_request.Request(
'http://127.0.0.1:7777/event',
data=_debug_payload,
headers={'Content-Type': 'application/json'},
method='POST',
), timeout=2).read()
except Exception:
pass
# #endregion
if not asset_id and not asset_name:
raise ValidationError('asset_id or asset_name is required')
@@ -1198,27 +1209,6 @@ def search_asset_history_files():
from app.services.fixed_asset_history import FixedAssetHistoryService
if not FixedAssetHistoryService.is_enabled():
# #region debug-point C:asset-history-api-disabled
try:
_debug_payload = _debug_json.dumps({
'sessionId': 'asset-history-click',
'runId': 'pre-fix',
'hypothesisId': 'C',
'location': 'backend/chat.py:search_asset_history_files',
'msg': '[DEBUG] asset history api disabled',
'data': {
'share_root': str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or ''),
},
}).encode('utf-8')
_debug_urllib_request.urlopen(_debug_urllib_request.Request(
'http://127.0.0.1:7777/event',
data=_debug_payload,
headers={'Content-Type': 'application/json'},
method='POST',
), timeout=2).read()
except Exception:
pass
# #endregion
raise ServiceUnavailableError('asset history share is not configured')
items = FixedAssetHistoryService.search_history_files(
@@ -1226,29 +1216,6 @@ def search_asset_history_files():
asset_name=asset_name,
limit=limit,
)
# #region debug-point C:asset-history-api-success
try:
_debug_payload = _debug_json.dumps({
'sessionId': 'asset-history-click',
'runId': 'pre-fix',
'hypothesisId': 'C',
'location': 'backend/chat.py:search_asset_history_files',
'msg': '[DEBUG] asset history api success',
'data': {
'asset_id': asset_id,
'asset_name': asset_name,
'item_count': len(items),
},
}).encode('utf-8')
_debug_urllib_request.urlopen(_debug_urllib_request.Request(
'http://127.0.0.1:7777/event',
data=_debug_payload,
headers={'Content-Type': 'application/json'},
method='POST',
), timeout=2).read()
except Exception:
pass
# #endregion
return jsonify({
'asset_id': asset_id,
'asset_name': asset_name,
+1
View File
@@ -343,6 +343,7 @@ class Config:
FIXED_ASSETS_HISTORY_KEEP_COUNT = int(os.getenv('FIXED_ASSETS_HISTORY_KEEP_COUNT', '3') or '3')
FIXED_ASSETS_STORAGE_ROOT = _data_path('FIXED_ASSETS_STORAGE_ROOT', 'fixed_assets')
FIXED_ASSET_HISTORY_SHARE_ROOT = os.getenv('FIXED_ASSET_HISTORY_SHARE_ROOT', '').strip()
FIXED_ASSET_HISTORY_LOCAL_ROOT = os.getenv('FIXED_ASSET_HISTORY_LOCAL_ROOT', '').strip()
FIXED_ASSET_HISTORY_SHARE_USERNAME = os.getenv('FIXED_ASSET_HISTORY_SHARE_USERNAME', '').strip()
FIXED_ASSET_HISTORY_SHARE_PASSWORD = os.getenv('FIXED_ASSET_HISTORY_SHARE_PASSWORD', '')
FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS = int(os.getenv('FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS', '20') or '20')
@@ -3,7 +3,7 @@ backend/app/services/admin/database_admin_service.py
用途:管理后台通用数据表浏览与 chat_logs 批量删除。
依赖:models、report_service(chat_logs 报表复用)。
逻辑:由 api/admin/database.py 调用。
逻辑:由 api/admin/database.py 调用;整型筛选字段对纯数字条件使用等值匹配。
"""
from __future__ import annotations
@@ -66,7 +66,12 @@ def get_table_data(table: str, query_params: dict[str, str]) -> list[dict]:
for key, value in query_params.items():
if hasattr(model, key) and value:
col = getattr(model, key)
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
col_type = getattr(col, 'type', None)
# 整型外键(如 agent_id)用等值过滤,避免 ILIKE '%16%' 误匹配 160
if value.isdigit() and col_type is not None and getattr(col_type, 'python_type', None) is int:
query = query.filter(col == int(value))
else:
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
items = query.limit(100).all()
return [_serialize_model_row(item) for item in items]
+248 -7
View File
@@ -1,8 +1,8 @@
"""
backend/app/services/admin/report_service.py
用途:管理后台报表(使用分析、反馈、聊天日志)数据聚合。
依赖:models、SQLAlchemy func。
用途:管理后台报表(使用分析、应用运营、反馈、聊天日志)数据聚合。
依赖:models、SQLAlchemy func、user_agent_permissions。
逻辑:由 api/admin/reports.py、database_admin_service 调用。
"""
from __future__ import annotations
@@ -11,12 +11,25 @@ import math
from datetime import datetime, timedelta
from typing import Any
from sqlalchemy import desc, func
from sqlalchemy import asc, desc, func, or_
from app import db
from app.models import Agent, ChatLog, Feedback, GeneralFeedback, User
from app.models import Agent, ChatLog, Feedback, GeneralFeedback, PermissionRequest, User
from app.models.base import user_agent_permissions
USAGE_BY_USER_TOP_LIMIT = 50
APPLICATION_REPORT_PAGE_SIZE_MAX = 100
APPLICATION_REPORT_SORT_KEYS = frozenset({
'name',
'chat_count',
'unique_users',
'last_active_at',
'authorized_users',
'pending_requests',
'avg_score',
'tokens_used',
})
DEFAULT_APPLICATION_SORT = 'chat_count'
# 使用分析时间范围:key → 回溯天数(与前端下拉选项一致)
USAGE_RANGE_DAYS = {
@@ -52,10 +65,15 @@ def build_usage_report(*, user_page: int, user_page_size: int, range_key: str |
"""
聊天使用分析报表(按应用 / 按用户),限定时间范围内的 ChatLog。
核心逻辑:按 Agent / User 聚合 ChatLog 次数;按用户统计同时返回 username 与 real_name。
Args:
user_page: 按用户统计分页页码。
user_page_size: 每页条数(上限 USAGE_BY_USER_TOP_LIMIT)。
range_key: 时间范围 key,见 USAGE_RANGE_DAYS。
Returns:
含 total / by_user(username、real_name、count)/ by_agent 及用户分页字段的字典。
"""
normalized_range, since = resolve_usage_range_start(range_key)
base_filter = ChatLog.created_at >= since
@@ -69,13 +87,22 @@ def build_usage_report(*, user_page: int, user_page_size: int, range_key: str |
.order_by(desc(func.count(ChatLog.id)), Agent.name)
.all()
)
# [STEP 1] 按日期聚合趋势,供管理端判断近几天是否出现使用高峰或低谷。
by_day = (
db.session.query(func.date(ChatLog.created_at), func.count(ChatLog.id))
.filter(base_filter)
.group_by(func.date(ChatLog.created_at))
.order_by(asc(func.date(ChatLog.created_at)))
.all()
)
user_page = max(1, user_page)
user_page_size = max(1, min(user_page_size, USAGE_BY_USER_TOP_LIMIT))
# [STEP 1] 按用户聚合对话量,一并选出真实姓名供管理端展示
by_user_top = (
db.session.query(User.username, func.count(ChatLog.id))
db.session.query(User.username, User.real_name, func.count(ChatLog.id))
.join(ChatLog)
.filter(base_filter)
.group_by(User.username)
.group_by(User.username, User.real_name)
.order_by(desc(func.count(ChatLog.id)), User.username)
.limit(USAGE_BY_USER_TOP_LIMIT)
.all()
@@ -88,8 +115,12 @@ def build_usage_report(*, user_page: int, user_page_size: int, range_key: str |
return {
'total': total,
'range': normalized_range,
'by_user': [{'username': u, 'count': c} for u, c in by_user_page],
'by_user': [
{'username': u, 'real_name': rn or '', 'count': c}
for u, rn, c in by_user_page
],
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent],
'by_day': [{'date': str(day), 'count': c} for day, c in by_day],
'user_total': user_total,
'user_page': user_page,
'user_page_size': user_page_size,
@@ -110,6 +141,214 @@ def build_feedback_report() -> dict:
}
def build_application_report(
*,
range_key: str | None = None,
status: str | None = None,
usage: str | None = None,
q: str | None = None,
sort: str | None = None,
order: str | None = None,
page: int = 1,
page_size: int = 20,
) -> dict:
"""
应用运营报表:以 Agent 为主表,聚合时间范围内的使用 / 权限 / 评分指标。
核心逻辑:ChatLog 聚合对话与用户;user_agent_permissions 统计授权人数;
PermissionRequest 统计待审;Feedback JOIN ChatLog 统计均分。不含 API Key 等配置敏感字段。
Args:
range_key: 时间范围 key(7d/30d/90d/180d/365d),非法值回退近一月。
status: all | active | inactive,按 is_active 过滤。
usage: all | used | unused,按时间范围内是否有对话过滤。
q: 应用名称模糊搜索。
sort: 排序字段,见 APPLICATION_REPORT_SORT_KEYS。
order: asc | desc,默认 desc。
page: 页码(从 1 起)。
page_size: 每页条数,上限 APPLICATION_REPORT_PAGE_SIZE_MAX。
Returns:
含 summary / items / 分页字段的字典。
"""
normalized_range, since = resolve_usage_range_start(range_key)
status_key = (status or 'all').strip().lower()
if status_key not in {'all', 'active', 'inactive'}:
status_key = 'all'
usage_key = (usage or 'all').strip().lower()
if usage_key not in {'all', 'used', 'unused'}:
usage_key = 'all'
sort_key = (sort or DEFAULT_APPLICATION_SORT).strip().lower()
if sort_key not in APPLICATION_REPORT_SORT_KEYS:
sort_key = DEFAULT_APPLICATION_SORT
order_key = (order or 'desc').strip().lower()
if order_key not in {'asc', 'desc'}:
order_key = 'desc'
page = max(1, int(page or 1))
page_size = max(1, min(int(page_size or 20), APPLICATION_REPORT_PAGE_SIZE_MAX))
keyword = (q or '').strip()
# [STEP 1] 子查询:时间范围内对话 / 授权 / 待审 / 评分
chat_stats = (
db.session.query(
ChatLog.agent_id.label('agent_id'),
func.count(ChatLog.id).label('chat_count'),
func.count(func.distinct(ChatLog.user_id)).label('unique_users'),
func.max(ChatLog.created_at).label('last_active_at'),
func.coalesce(func.sum(ChatLog.tokens_used), 0).label('tokens_used'),
func.avg(ChatLog.latency).label('avg_latency_ms'),
)
.filter(ChatLog.created_at >= since)
.group_by(ChatLog.agent_id)
.subquery()
)
auth_stats = (
db.session.query(
user_agent_permissions.c.agent_id.label('agent_id'),
func.count(user_agent_permissions.c.user_id).label('authorized_users'),
)
.group_by(user_agent_permissions.c.agent_id)
.subquery()
)
pending_stats = (
db.session.query(
PermissionRequest.agent_id.label('agent_id'),
func.count(PermissionRequest.id).label('pending_requests'),
)
.filter(PermissionRequest.status == 'pending')
.group_by(PermissionRequest.agent_id)
.subquery()
)
feedback_stats = (
db.session.query(
ChatLog.agent_id.label('agent_id'),
func.avg(Feedback.score).label('avg_score'),
func.count(Feedback.id).label('feedback_count'),
)
.join(Feedback, Feedback.chat_log_id == ChatLog.id)
.filter(ChatLog.created_at >= since)
.group_by(ChatLog.agent_id)
.subquery()
)
chat_count_col = func.coalesce(chat_stats.c.chat_count, 0)
unique_users_col = func.coalesce(chat_stats.c.unique_users, 0)
authorized_col = func.coalesce(auth_stats.c.authorized_users, 0)
pending_col = func.coalesce(pending_stats.c.pending_requests, 0)
tokens_col = func.coalesce(chat_stats.c.tokens_used, 0)
# [STEP 2] Agent 左连接各聚合,应用筛选
query = (
db.session.query(
Agent.id,
Agent.name,
Agent.is_active,
Agent.category,
chat_count_col.label('chat_count'),
unique_users_col.label('unique_users'),
chat_stats.c.last_active_at,
authorized_col.label('authorized_users'),
pending_col.label('pending_requests'),
feedback_stats.c.avg_score,
func.coalesce(feedback_stats.c.feedback_count, 0).label('feedback_count'),
tokens_col.label('tokens_used'),
chat_stats.c.avg_latency_ms,
)
.outerjoin(chat_stats, chat_stats.c.agent_id == Agent.id)
.outerjoin(auth_stats, auth_stats.c.agent_id == Agent.id)
.outerjoin(pending_stats, pending_stats.c.agent_id == Agent.id)
.outerjoin(feedback_stats, feedback_stats.c.agent_id == Agent.id)
)
if status_key == 'active':
query = query.filter(Agent.is_active.is_(True))
elif status_key == 'inactive':
query = query.filter(Agent.is_active.is_(False))
if usage_key == 'used':
query = query.filter(chat_count_col > 0)
elif usage_key == 'unused':
query = query.filter(or_(chat_stats.c.chat_count.is_(None), chat_stats.c.chat_count == 0))
if keyword:
query = query.filter(Agent.name.ilike(f'%{keyword}%'))
# [STEP 3] 一次拉取筛选结果,内存排序分页(应用数量通常较小;兼容 SQLite 测试)
filtered_rows = list(query.all())
agent_total = len(filtered_rows)
active_agents = sum(1 for row in filtered_rows if row.is_active)
used_agents = sum(1 for row in filtered_rows if int(row.chat_count or 0) > 0)
unused_agents = agent_total - used_agents
pending_permission_total = sum(int(row.pending_requests or 0) for row in filtered_rows)
def _row_sort_key(row: Any) -> tuple:
"""
构造排序键:(是否空值, 业务值, 名称, id)。
空值(无最近活跃 / 无评分)始终排在末尾。
"""
if sort_key == 'name':
return (0, (row.name or '').lower(), row.name or '', row.id)
if sort_key in {'chat_count', 'unique_users', 'authorized_users', 'pending_requests', 'tokens_used'}:
return (0, int(getattr(row, sort_key) or 0), row.name or '', row.id)
raw = getattr(row, sort_key, None)
if raw is None:
return (1, None, row.name or '', row.id)
if sort_key == 'avg_score':
return (0, float(raw), row.name or '', row.id)
return (0, raw, row.name or '', row.id)
reverse = order_key == 'desc'
non_null = [r for r in filtered_rows if _row_sort_key(r)[0] == 0]
nulls = [r for r in filtered_rows if _row_sort_key(r)[0] == 1]
non_null.sort(key=_row_sort_key, reverse=reverse)
nulls.sort(key=lambda r: (r.name or '', r.id))
filtered_rows = non_null + nulls
pages = max(1, math.ceil(agent_total / page_size)) if agent_total else 1
page = min(page, pages)
offset = (page - 1) * page_size
page_rows = filtered_rows[offset:offset + page_size]
items = []
for row in page_rows:
avg_score = float(row.avg_score) if row.avg_score is not None else None
avg_latency = float(row.avg_latency_ms) if row.avg_latency_ms is not None else None
last_active = row.last_active_at.isoformat() if row.last_active_at else None
items.append({
'agent_id': row.id,
'name': row.name,
'is_active': bool(row.is_active),
'category': row.category or '',
'chat_count': int(row.chat_count or 0),
'unique_users': int(row.unique_users or 0),
'last_active_at': last_active,
'authorized_users': int(row.authorized_users or 0),
'pending_requests': int(row.pending_requests or 0),
'avg_score': round(avg_score, 2) if avg_score is not None else None,
'feedback_count': int(row.feedback_count or 0),
'tokens_used': int(row.tokens_used or 0),
'avg_latency_ms': round(avg_latency, 1) if avg_latency is not None else None,
})
return {
'range': normalized_range,
'status': status_key,
'usage': usage_key,
'q': keyword,
'sort': sort_key,
'order': order_key,
'summary': {
'agent_total': agent_total,
'active_agents': active_agents,
'used_agents': used_agents,
'unused_agents': unused_agents,
'pending_permission_total': pending_permission_total,
},
'items': items,
'total': agent_total,
'page': page,
'page_size': page_size,
'pages': pages,
}
def _apply_general_feedback_filters(query, query_params: dict[str, str]):
reserved = {'limit', 'offset', 'page', 'page_size'}
for key, value in query_params.items():
@@ -208,6 +447,8 @@ def apply_chat_logs_report_filters(query, query_params: dict[str, str]):
continue
if key == 'agent_name':
query = query.filter(Agent.name.cast(db.String).ilike(f'%{value}%'))
elif key == 'agent_id' and value.isdigit():
query = query.filter(ChatLog.agent_id == int(value))
elif key == 'username':
query = query.filter(User.username.cast(db.String).ilike(f'%{value}%'))
elif key == 'real_name':
+48 -5
View File
@@ -86,9 +86,23 @@ def list_directory_member_agents(agent_id: int, *, active_only: bool = False) ->
return query.all()
def serialize_directory_member(agent: Agent) -> dict[str, Any]:
"""Serialize one member Agent for Admin and Dify runtime metadata."""
return {
def serialize_directory_member(
agent: Agent,
*,
active_only: bool = False,
max_depth: int = 0,
visited_ids: set[int] | None = None,
) -> dict[str, Any]:
"""
Serialize one member Agent for Admin, user navigation, and Dify metadata.
Args:
active_only: True 时只展开启用中的子应用。
max_depth: 允许向下展开的聚合层级,避免用户列表中聚合子应用丢失展开能力。
visited_ids: 已访问 Agent ID,用于防止循环配置导致递归。
"""
is_aggregate = bool(getattr(agent, 'is_aggregate', False))
payload = {
'id': agent.id,
'name': agent.name,
'description': agent.description,
@@ -97,12 +111,41 @@ def serialize_directory_member(agent: Agent) -> dict[str, Any]:
'dify_app_id': agent.dify_app_id,
'category': agent.category,
'sub_category': agent.sub_category,
'sort_order': int(getattr(agent, 'sort_order', 0) or 0),
'is_aggregate': is_aggregate,
}
if is_aggregate and max_depth > 0:
next_visited = set(visited_ids or set())
if agent.id not in next_visited:
next_visited.add(agent.id)
payload['directory_members'] = serialize_directory_members(
agent.id,
active_only=active_only,
max_depth=max_depth - 1,
visited_ids=next_visited,
)
return payload
def serialize_directory_members(agent_id: int, *, active_only: bool = False) -> list[dict[str, Any]]:
def serialize_directory_members(
agent_id: int,
*,
active_only: bool = False,
max_depth: int = 0,
visited_ids: set[int] | None = None,
) -> list[dict[str, Any]]:
"""Serialize configured member Agents for a directory Agent."""
visited = set(visited_ids or set())
if agent_id in visited:
return []
visited.add(agent_id)
return [
serialize_directory_member(agent)
serialize_directory_member(
agent,
active_only=active_only,
max_depth=max_depth,
visited_ids=visited,
)
for agent in list_directory_member_agents(agent_id, active_only=active_only)
if agent.id not in visited
]
+117 -36
View File
@@ -3,7 +3,9 @@ backend/app/services/fixed_asset_history.py
用途:为固资管理提供“资产履历”共享盘检索能力,按资产编号/资产名称匹配履历文件。
依赖:app.core.config.settings.Config、chat.py 里的预览代理会复用这里返回的共享盘文件路径。
逻辑:聊天表格点击资产编号 -> chat API 调用本服务检索共享盘 -> 前端拿到候选履历文件后继续走既有预览弹窗。
逻辑:聊天表格点击资产编号 -> chat API 调用本服务检索履历目录 -> 前端拿到候选履历文件后继续走既有预览弹窗;
支持 Windows 直接访问 UNC 共享盘,也支持 Linux 通过本地挂载目录访问同一批履历文件;
编号命中优先;共享盘按设备名归档时,允许用资产名称匹配文件夹/文件名作为回退。
"""
from __future__ import annotations
@@ -17,6 +19,7 @@ from dataclasses import dataclass
from flask import current_app, has_app_context
from app.core.config.settings import Config
from app.core.errors import ServiceUnavailableError
_CONNECT_LOCK = threading.Lock()
@@ -75,12 +78,64 @@ class FixedAssetHistoryService:
@classmethod
def is_enabled(cls) -> bool:
return bool(cls.get_share_root())
return bool(cls.get_local_root() or cls.get_share_root())
@classmethod
def get_share_root(cls) -> str:
return cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_ROOT').strip()
@classmethod
def get_local_root(cls) -> str:
return cls._get_runtime_setting('FIXED_ASSET_HISTORY_LOCAL_ROOT').strip()
@classmethod
def get_access_root(cls) -> str:
"""
返回当前环境实际用于检索/预览履历文件的可访问根目录。
AI 触发时机:
- Windows 本地开发环境通常直接访问 UNC 共享盘;
- Linux 测试/生产环境通常通过宿主机或容器挂载目录访问共享盘;
- 因此优先读取 `FIXED_ASSET_HISTORY_LOCAL_ROOT`,未配置时再回退到原共享盘根目录。
"""
return cls.get_local_root() or cls.get_share_root()
@classmethod
def _resolve_share_root(cls) -> str:
"""
解析并校验资产履历共享盘根目录。
AI 触发时机:当用户点击资产编号查询履历时,必须先确认后端能访问配置的共享盘;
若测试/生产环境未挂载成功,不应误报成“未找到履历文件”,而应返回更准确的环境异常提示。
"""
root = cls.get_access_root()
if not root:
raise ServiceUnavailableError('asset history share is not configured')
if not os.path.exists(root):
cls._ensure_share_connected(root)
if not os.path.exists(root):
raise ServiceUnavailableError('asset history share is unreachable')
if not os.path.isdir(root):
raise ServiceUnavailableError('asset history share is invalid')
return root
@classmethod
def _build_asset_id_variants(cls, asset_id: str) -> tuple[str, ...]:
"""
生成资产编号匹配变体。
AI 触发时机:测试/生产环境的共享盘文件名可能出现“带前缀 A”与“不带前缀”两种写法;
这里统一构造多个匹配 key,避免因为命名差一个前缀就查不到履历。
"""
normalized = cls._normalize_keyword(asset_id)
if not normalized:
return tuple()
variants = [normalized]
stripped = re.sub(r'^[a-z]+', '', normalized)
if stripped and stripped not in variants:
variants.append(stripped)
return tuple(variants)
@classmethod
def search_history_files(
cls,
@@ -97,17 +152,12 @@ class FixedAssetHistoryService:
[STEP 3] 再用资产名称命中同名文件夹/文件,补足部分历史文件只按设备名称归档的情况。
"""
asset_id_value = cls._normalize_keyword(asset_id)
asset_id_variants = cls._build_asset_id_variants(asset_id)
asset_name_value = cls._normalize_keyword(asset_name)
if not asset_id_value and not asset_name_value:
if not asset_id_variants and not asset_name_value:
return []
root = cls.get_share_root()
if not root:
return []
if not os.path.exists(root):
cls._ensure_share_connected(root)
if not os.path.isdir(root):
return []
root = cls._resolve_share_root()
max_results = max(
1,
@@ -115,13 +165,13 @@ class FixedAssetHistoryService:
)
candidates: dict[str, AssetHistoryCandidate] = {}
if asset_id_value:
if asset_id_variants:
for current_root, _dirs, files in os.walk(root):
for filename in files:
candidate = cls._build_candidate(
root=root,
file_path=os.path.join(current_root, filename),
asset_id=asset_id_value,
asset_id_variants=asset_id_variants,
asset_name=asset_name_value,
match_reason="asset_id",
)
@@ -135,7 +185,7 @@ class FixedAssetHistoryService:
candidate = cls._build_candidate(
root=root,
file_path=os.path.join(current_root, filename),
asset_id=asset_id_value,
asset_id_variants=asset_id_variants,
asset_name=asset_name_value,
match_reason="asset_name_folder",
)
@@ -143,18 +193,18 @@ class FixedAssetHistoryService:
cls._merge_candidate(candidates, candidate)
if asset_name_value:
for entry in os.scandir(root):
if not entry.is_file():
continue
candidate = cls._build_candidate(
root=root,
file_path=entry.path,
asset_id=asset_id_value,
asset_name=asset_name_value,
match_reason="asset_name_file",
)
if candidate:
cls._merge_candidate(candidates, candidate)
# 全树按资产名称匹配文件名(共享盘常见「设备名+履历.xls」,不一定含资产编号)
for current_root, _dirs, files in os.walk(root):
for filename in files:
candidate = cls._build_candidate(
root=root,
file_path=os.path.join(current_root, filename),
asset_id_variants=asset_id_variants,
asset_name=asset_name_value,
match_reason="asset_name_file",
)
if candidate:
cls._merge_candidate(candidates, candidate)
ordered = sorted(
candidates.values(),
@@ -191,10 +241,18 @@ class FixedAssetHistoryService:
*,
root: str,
file_path: str,
asset_id: str,
asset_id_variants: tuple[str, ...],
asset_name: str,
match_reason: str,
) -> AssetHistoryCandidate | None:
"""
将单个文件构造成履历候选;按匹配原因施加不同门槛。
核心逻辑:
- asset_id:文件名/相对路径必须包含资产编号(或去字母前缀变体);
- asset_name_folder / asset_name_file:共享盘大量按设备名归档,不强制编号出现在文件名;
名称文件夹命中后,目录内履历文件均可作为候选。
"""
if not os.path.isfile(file_path):
return None
ext = os.path.splitext(file_path)[1].strip().lower()
@@ -210,15 +268,23 @@ class FixedAssetHistoryService:
if not searchable_text:
return None
if asset_id and asset_id not in searchable_text:
return None
if asset_name and asset_name not in searchable_text and match_reason != "asset_id":
# [STEP] 按匹配原因分流门槛,避免“有资产编号就永远要求文件名含编号”导致设备名归档全部 miss
if match_reason == "asset_id":
if not asset_id_variants or not any(variant in searchable_text for variant in asset_id_variants):
return None
elif match_reason == "asset_name_file":
if not asset_name or asset_name not in searchable_text:
return None
elif match_reason == "asset_name_folder":
# 文件夹已按资产名称命中;文件本身可不含编号/全名
pass
else:
return None
score = cls._score_candidate(
searchable_text=searchable_text,
filename=cls._normalize_keyword(filename),
asset_id=asset_id,
asset_id_variants=asset_id_variants,
asset_name=asset_name,
match_reason=match_reason,
)
@@ -243,21 +309,33 @@ class FixedAssetHistoryService:
*,
searchable_text: str,
filename: str,
asset_id: str,
asset_id_variants: tuple[str, ...],
asset_name: str,
match_reason: str,
) -> int:
"""
为履历候选打分;编号命中优先于名称命中。
核心逻辑:编号精确/模糊命中给高分;名称命中与「履历」关键字加分;
纯名称归档场景(无编号)至少要靠名称或文件夹命中拿到正分,否则会被过滤。
"""
score = 0
if asset_id:
if asset_id in filename:
score += 120
elif asset_id in searchable_text:
score += 80
if asset_id_variants:
for index, asset_id in enumerate(asset_id_variants):
exact_bonus = 120 if index == 0 else 100
fuzzy_bonus = 80 if index == 0 else 60
if asset_id in filename:
score = max(score, exact_bonus)
elif asset_id in searchable_text:
score = max(score, fuzzy_bonus)
if asset_name:
if asset_name in filename:
score += 60
elif asset_name in searchable_text:
score += 40
elif match_reason == "asset_name_folder":
# 文件夹已按名称命中,目录内文件给基础分,避免 score=0 被丢弃
score += 30
if "履历" in filename:
score += 20
if match_reason == "asset_name_folder":
@@ -277,7 +355,10 @@ class FixedAssetHistoryService:
尝试用配置的账号密码建立共享盘会话。
账号密码只从环境变量读取,避免把敏感信息写进仓库。
Linux 测试/生产环境应优先通过挂载目录访问共享盘,此处仅作为 Windows UNC 共享盘的兜底建连。
"""
if os.name != 'nt':
return
username = cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_USERNAME').strip()
password = cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_PASSWORD')
if not username or not password:
+54 -13
View File
@@ -1,8 +1,49 @@
"""
backend/app/services/oa_sqlserver.py
用途:封装 OA SQL Server 的员工检索与组织信息查询能力,供请假代理人/申请人选择等场景复用。
依赖:pyodbc、OA ecology 数据库视图 userInfo_view / HrmDepartment / HrmSubCompany / HrmJobTitles。
逻辑:通过只读 SQL 查询返回 OA 用户与组织字段;对于 OA 中夹带的多语言包装串,统一在服务层清洗成可直接展示的中文文本。
"""
import os
import re
import pyodbc
from flask import current_app
_OA_MULTILINGUAL_WRAPPER_PATTERN = re.compile(
r"~`~`7\s*(.*?)\s*~`8\s*(.*?)\s*~`9\s*(.*?)\s*~`~"
)
class OASQLServerService:
@staticmethod
def _normalize_oa_text(value) -> str:
"""
清洗 OA 多语言包装字段。
AI 触发时机:当 OA 视图返回的姓名、部门、分部、职务等字段中夹带
`~`~`7 中文 ~`8 English ~`9 繁中 ~`~` 这类原始包装串时,需统一提取
可直接给用户展示的文本,避免在代理人选择弹窗中看到乱码样式的标记串。
Args:
value: 来自 OA SQL Server 的原始字段值。
Returns:
优先返回简体中文,其次英文、繁中;若未命中包装规则,则返回原始去空白文本。
"""
text = str(value or "").strip()
if not text:
return ""
matched = _OA_MULTILINGUAL_WRAPPER_PATTERN.search(text)
if not matched:
return text
simplified, english, traditional = (
segment.strip().strip("`").strip()
for segment in matched.groups()
)
return simplified or english or traditional or text
@staticmethod
def _pick_driver():
drivers = pyodbc.drivers()
@@ -96,13 +137,13 @@ class OASQLServerService:
items.append({
"uid": str(row.id) if row.id is not None else "",
"employeeId": str(row.workcode) if row.workcode is not None else "",
"name": str(row.lastname) if row.lastname is not None else "",
"jobtitle": str(row.jobtitle) if row.jobtitle is not None else "",
"name": cls._normalize_oa_text(row.lastname),
"jobtitle": cls._normalize_oa_text(row.jobtitle),
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
"departmentName": str(row.departmentname).strip() if row.departmentname else "",
"subcompanyName": str(row.subcompanyname).strip() if row.subcompanyname else "",
"jobtitleName": str(row.jobtitlename).strip() if row.jobtitlename else "",
"departmentName": cls._normalize_oa_text(row.departmentname),
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
})
return {
@@ -145,13 +186,13 @@ class OASQLServerService:
return {
"uid": str(row.id) if row.id is not None else "",
"employeeId": str(row.workcode) if row.workcode is not None else "",
"name": str(row.lastname) if row.lastname is not None else "",
"jobtitle": str(row.jobtitle) if row.jobtitle is not None else "",
"name": cls._normalize_oa_text(row.lastname),
"jobtitle": cls._normalize_oa_text(row.jobtitle),
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
"departmentName": str(row.departmentname).strip() if row.departmentname else "",
"subcompanyName": str(row.subcompanyname).strip() if row.subcompanyname else "",
"jobtitleName": str(row.jobtitlename).strip() if row.jobtitlename else "",
"departmentName": cls._normalize_oa_text(row.departmentname),
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
}
finally:
try:
@@ -171,7 +212,7 @@ class OASQLServerService:
[department_id.strip()],
)
row = cursor.fetchone()
return str(row.departmentname).strip() if row and row.departmentname else ""
return cls._normalize_oa_text(row.departmentname) if row and row.departmentname else ""
finally:
try:
cursor.close()
@@ -190,7 +231,7 @@ class OASQLServerService:
[subcompany_id.strip()],
)
row = cursor.fetchone()
return str(row.subcompanyname).strip() if row and row.subcompanyname else ""
return cls._normalize_oa_text(row.subcompanyname) if row and row.subcompanyname else ""
finally:
try:
cursor.close()
@@ -209,7 +250,7 @@ class OASQLServerService:
[jobtitle_id.strip()],
)
row = cursor.fetchone()
return str(row.jobtitlename).strip() if row and row.jobtitlename else ""
return cls._normalize_oa_text(row.jobtitlename) if row and row.jobtitlename else ""
finally:
try:
cursor.close()