105 lines
3.4 KiB
Python
105 lines
3.4 KiB
Python
"""
|
||
backend/app/services/admin/database_admin_service.py
|
||
|
||
用途:管理后台通用数据表浏览与 chat_logs 批量删除。
|
||
依赖:models、report_service(chat_logs 报表复用)。
|
||
逻辑:由 api/admin/database.py 调用;整型筛选字段对纯数字条件使用等值匹配。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from datetime import datetime
|
||
from typing import Any
|
||
|
||
from sqlalchemy import func
|
||
|
||
from app import db
|
||
from app.core.errors import ValidationError
|
||
from app.models import (
|
||
Agent,
|
||
ChatLog,
|
||
Department,
|
||
Feedback,
|
||
PermissionRequest,
|
||
QuickQuestion,
|
||
User,
|
||
UserDefaultAgent,
|
||
UserFavoriteAgent,
|
||
UserHomepageConfig,
|
||
)
|
||
from app.services.admin import report_service
|
||
|
||
ADMIN_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,
|
||
}
|
||
|
||
|
||
def _serialize_model_row(item) -> dict:
|
||
row = {}
|
||
for col in item.__table__.columns:
|
||
val = getattr(item, col.name)
|
||
if isinstance(val, datetime):
|
||
val = val.isoformat()
|
||
row[col.name] = val
|
||
return row
|
||
|
||
|
||
def get_table_data(table: str, query_params: dict[str, str]) -> list[dict]:
|
||
"""
|
||
返回管理报表表数据(最多 100 行)。
|
||
chat_logs 走专用报表 JOIN 逻辑。
|
||
"""
|
||
if table == 'chat_logs':
|
||
return report_service.list_chat_logs_report(query_params)
|
||
model = ADMIN_TABLE_MODEL_MAP.get(table)
|
||
if not model:
|
||
raise ValidationError('Invalid table')
|
||
query = db.session.query(model)
|
||
for key, value in query_params.items():
|
||
if hasattr(model, key) and value:
|
||
col = getattr(model, key)
|
||
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]
|
||
|
||
|
||
def get_table_count(table: str, query_params: dict[str, str]) -> dict:
|
||
"""返回表行数;chat_logs 使用报表筛选。"""
|
||
if table == 'chat_logs':
|
||
return report_service.count_chat_logs_report(query_params)
|
||
model = ADMIN_TABLE_MODEL_MAP.get(table)
|
||
if not model:
|
||
raise ValidationError('Invalid table')
|
||
total = db.session.query(func.count(model.id)).scalar()
|
||
return {'table': table, 'total': int(total or 0)}
|
||
|
||
|
||
def batch_delete_chat_logs(raw_ids: list[Any]) -> dict:
|
||
"""按 id 批量删除 ChatLog。"""
|
||
if not isinstance(raw_ids, list) or not raw_ids:
|
||
raise ValidationError('ids is required')
|
||
ids = []
|
||
for value in raw_ids:
|
||
try:
|
||
ids.append(int(value))
|
||
except (TypeError, ValueError):
|
||
continue
|
||
if not ids:
|
||
raise ValidationError('No valid ids')
|
||
cnt = db.session.query(ChatLog).filter(ChatLog.id.in_(ids)).delete(synchronize_session=False)
|
||
db.session.commit()
|
||
return {'deleted_count': cnt}
|