后端: - Ticket model 新增 ticket_no 字段(格式: YYYYMMDDHHmmss+ms+seq, 如20260522160543841) - create_ticket 自动生成工单编号(flush后生成) - _enrich_ticket 新增 instance_name, current_approver_name 字段 - current_approver: 从 ticket_approvals 查询第一个 pending 状态的审批步骤获取审核人 - TicketResponse schema 新增 ticket_no, instance_name, current_approver_name - 新增 /instances/accessible endpoint(按用户权限组过滤实例, 无admin bypass) - instance_group response_model 改为 InstanceGroupDetailResponse(含readonly/write实例) - instance_group_members 脏数据清理, 重建 group_id=2 正确数据 - notification 模板修复: \n→\n 换行, 钉钉 \n→\n\n 双换行 - test_notification endpoint 改为真正调用 NotificationSender.send() - auditor 角色添加到 audit_rule/ticket 只读端点 - seed_data() 创建4个默认用户(admin/zhangsan/laoliu/lurenjia) - SQLite ALTER TABLE 添加 ticket_no 列, 迁移现有6条工单数据 前端: - TicketsPage 完全重设计: 工单编号/实例名称/提交人/当前审核人/状态/操作 - 状态映射简化: pending/reviewing/approved→审核中, success→完成, failed→失败 - 执行详情弹框: 解析 execute_result JSON 展示状态/影响行数/耗时/验证/原始输出/错误信息 - 状态流程可视化(提交→审批→通过→执行→完成) - 快速筛选: 全部/待审批/执行中/完成/失败 (合并 pending+reviewing+approved 统计) - TicketCreatePage: 去掉数据库类型选择器, 用 accessible(write) 过滤变更实例 - QueriesPage: 用 accessible(readonly) 过滤查询实例 - instance.ts 新增 accessible 方法 - 分页优化: 动态计算页码范围(总页>5时中间滚动)
296 lines
11 KiB
Python
296 lines
11 KiB
Python
import json
|
|
from typing import Optional, List
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.database import get_db
|
|
from app.core.security import get_current_user, require_role
|
|
from app.core.permissions import check_instance_access, get_user_accessible_group_ids
|
|
from app.models.user import User
|
|
from app.models.instance import Instance
|
|
from app.models.instance_group import user_groups
|
|
from app.schemas.instance import InstanceCreate, InstanceUpdate, InstanceResponse, ConnectionTestResult
|
|
from app.services.instance_service import InstanceService
|
|
from app.core.crypto import encrypt_password, decrypt_password
|
|
from app.services.audit_log_service import AuditLogService
|
|
|
|
router = APIRouter(prefix="/instances", tags=["数据源管理"])
|
|
|
|
|
|
def _serialize_json_fields(instance: Instance, workflow_name: str = None) -> dict:
|
|
"""将 Instance 的 JSON text 字段反序列化为 dict/list,返回 Response dict"""
|
|
d = {
|
|
"id": instance.id,
|
|
"name": instance.name,
|
|
"db_type": instance.db_type,
|
|
"host": instance.host,
|
|
"port": instance.port,
|
|
"username": instance.username,
|
|
"database": instance.database,
|
|
"env": instance.env,
|
|
"description": instance.description,
|
|
"status": instance.status,
|
|
"version": instance.version,
|
|
"access_mode": instance.access_mode or "readwrite",
|
|
"workflow_id": instance.workflow_id,
|
|
"workflow_name": workflow_name,
|
|
"excluded_databases": json.loads(instance.excluded_databases) if instance.excluded_databases else None,
|
|
"mask_fields": json.loads(instance.mask_fields) if instance.mask_fields else None,
|
|
"created_at": instance.created_at,
|
|
}
|
|
return d
|
|
|
|
|
|
async def _get_workflow_names(db: AsyncSession, instances: list) -> dict:
|
|
"""批量获取 workflow_id -> name 映射"""
|
|
from app.models.workflow import WorkflowDefinition
|
|
wids = list({i.workflow_id for i in instances if i.workflow_id})
|
|
if not wids:
|
|
return {}
|
|
result = await db.execute(select(WorkflowDefinition).where(WorkflowDefinition.id.in_(wids)))
|
|
return {w.id: w.name for w in result.scalars().all()}
|
|
|
|
|
|
@router.get("/accessible", response_model=List[InstanceResponse])
|
|
async def list_accessible_instances(
|
|
access_type: str = "readonly",
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: User = Depends(get_current_user),
|
|
):
|
|
"""返回当前用户有权访问的实例列表(按权限组的 access_type 过滤)。
|
|
|
|
所有用户(包括 admin)统一按权限组关联过滤:
|
|
user_groups → instance_group_members(access_type) → 返回对应实例
|
|
access_type: readonly=查询授权, write=变更授权
|
|
"""
|
|
from app.models.instance_group import instance_group_members, user_groups as ug_table
|
|
|
|
# 查用户关联的所有权限组
|
|
grp_result = await db.execute(
|
|
select(ug_table.c.group_id).where(ug_table.c.user_id == current_user.id)
|
|
)
|
|
group_ids = [row[0] for row in grp_result.all()]
|
|
if not group_ids:
|
|
return []
|
|
|
|
# 从 instance_group_members 中获取指定 access_type 的 instance_id
|
|
mem_result = await db.execute(
|
|
select(instance_group_members.c.instance_id)
|
|
.where(
|
|
instance_group_members.c.group_id.in_(group_ids),
|
|
instance_group_members.c.access_type == access_type,
|
|
)
|
|
.distinct()
|
|
)
|
|
instance_ids = [row[0] for row in mem_result.all()]
|
|
if not instance_ids:
|
|
return []
|
|
|
|
# 查实例详情
|
|
stmt = select(Instance).where(Instance.id.in_(instance_ids)).order_by(Instance.id)
|
|
result = await db.execute(stmt)
|
|
instances = result.scalars().all()
|
|
wnames = await _get_workflow_names(db, instances)
|
|
return [_serialize_json_fields(i, wnames.get(i.workflow_id)) for i in instances]
|
|
|
|
|
|
@router.get("", response_model=List[InstanceResponse])
|
|
async def list_instances(
|
|
db_type: Optional[str] = None,
|
|
env: Optional[str] = None,
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: User = Depends(get_current_user),
|
|
):
|
|
stmt = select(Instance).order_by(Instance.id)
|
|
if db_type:
|
|
stmt = stmt.where(Instance.db_type == db_type)
|
|
if env:
|
|
stmt = stmt.where(Instance.env == env)
|
|
|
|
# P0: 权限组过滤 — 非 admin 只能看到自己权限组内的 + 公开实例
|
|
if current_user.role != "admin":
|
|
result = await db.execute(
|
|
select(user_groups.c.group_id).where(user_groups.c.user_id == current_user.id)
|
|
)
|
|
user_group_ids = [row[0] for row in result.all()]
|
|
if user_group_ids:
|
|
stmt = stmt.where(
|
|
(Instance.group_id.in_(user_group_ids)) | (Instance.group_id.is_(None))
|
|
)
|
|
else:
|
|
# 没有任何权限组,只能看公开实例
|
|
stmt = stmt.where(Instance.group_id.is_(None))
|
|
|
|
result = await db.execute(stmt)
|
|
instances = result.scalars().all()
|
|
wnames = await _get_workflow_names(db, instances)
|
|
return [_serialize_json_fields(i, wnames.get(i.workflow_id)) for i in instances]
|
|
|
|
|
|
@router.post("", response_model=InstanceResponse, status_code=201)
|
|
async def create_instance(
|
|
data: InstanceCreate,
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: User = Depends(require_role("admin", "dba")),
|
|
):
|
|
instance = Instance(
|
|
name=data.name,
|
|
db_type=data.db_type,
|
|
host=data.host,
|
|
port=data.port,
|
|
username=data.username,
|
|
password=encrypt_password(data.password),
|
|
database=data.database,
|
|
env=data.env,
|
|
description=data.description,
|
|
access_mode=data.access_mode,
|
|
workflow_id=data.workflow_id,
|
|
excluded_databases=json.dumps(data.excluded_databases, ensure_ascii=False) if data.excluded_databases else None,
|
|
mask_fields=json.dumps([m.model_dump() for m in data.mask_fields], ensure_ascii=False) if data.mask_fields else None,
|
|
)
|
|
db.add(instance)
|
|
await db.flush()
|
|
await AuditLogService.log(
|
|
db, user_id=current_user.id, action="CREATE_INSTANCE",
|
|
target_type="instance", target_id=instance.id,
|
|
detail=f"创建数据源: {data.name} ({data.db_type}@{data.host}:{data.port})",
|
|
)
|
|
await db.commit()
|
|
await db.refresh(instance)
|
|
wnames = await _get_workflow_names(db, [instance])
|
|
return _serialize_json_fields(instance, wnames.get(instance.workflow_id))
|
|
|
|
|
|
@router.post("/test-connection", response_model=ConnectionTestResult)
|
|
async def test_new_connection(
|
|
data: InstanceCreate,
|
|
current_user: User = Depends(require_role("admin", "dba")),
|
|
):
|
|
"""测试连接参数(不保存实例)"""
|
|
fake = Instance(
|
|
name=data.name, db_type=data.db_type, host=data.host, port=data.port,
|
|
username=data.username, password=data.password, database=data.database,
|
|
env=data.env, access_mode=data.access_mode,
|
|
)
|
|
return await InstanceService.test_connection(fake)
|
|
|
|
|
|
@router.get("/{instance_id}", response_model=InstanceResponse)
|
|
async def get_instance(
|
|
instance_id: int,
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: User = Depends(get_current_user),
|
|
):
|
|
result = await db.execute(select(Instance).where(Instance.id == instance_id))
|
|
instance = result.scalar_one_or_none()
|
|
if not instance:
|
|
raise HTTPException(status_code=404, detail="数据源不存在")
|
|
# P0: 检查访问权限
|
|
await check_instance_access(current_user, instance, db)
|
|
wnames = await _get_workflow_names(db, [instance])
|
|
return _serialize_json_fields(instance, wnames.get(instance.workflow_id))
|
|
|
|
|
|
@router.put("/{instance_id}", response_model=InstanceResponse)
|
|
async def update_instance(
|
|
instance_id: int,
|
|
data: InstanceUpdate,
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: User = Depends(require_role("admin", "dba")),
|
|
):
|
|
result = await db.execute(select(Instance).where(Instance.id == instance_id))
|
|
instance = result.scalar_one_or_none()
|
|
if not instance:
|
|
raise HTTPException(status_code=404, detail="数据源不存在")
|
|
|
|
update_data = data.model_dump(exclude_unset=True)
|
|
if "password" in update_data:
|
|
update_data["password"] = encrypt_password(update_data["password"])
|
|
# workflow_id: 0 means clear
|
|
if "workflow_id" in update_data and update_data["workflow_id"] == 0:
|
|
update_data["workflow_id"] = None
|
|
if "excluded_databases" in update_data:
|
|
update_data["excluded_databases"] = json.dumps(update_data["excluded_databases"], ensure_ascii=False) if update_data["excluded_databases"] else None
|
|
if "mask_fields" in update_data:
|
|
update_data["mask_fields"] = json.dumps([m if isinstance(m, dict) else m for m in update_data["mask_fields"]], ensure_ascii=False) if update_data["mask_fields"] else None
|
|
|
|
for key, value in update_data.items():
|
|
setattr(instance, key, value)
|
|
await db.commit()
|
|
await db.refresh(instance)
|
|
wnames = await _get_workflow_names(db, [instance])
|
|
return _serialize_json_fields(instance, wnames.get(instance.workflow_id))
|
|
|
|
|
|
@router.delete("/{instance_id}")
|
|
async def delete_instance(
|
|
instance_id: int,
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: User = Depends(require_role("admin", "dba")),
|
|
):
|
|
result = await db.execute(select(Instance).where(Instance.id == instance_id))
|
|
instance = result.scalar_one_or_none()
|
|
if not instance:
|
|
raise HTTPException(status_code=404, detail="数据源不存在")
|
|
|
|
await AuditLogService.log(
|
|
db, user_id=current_user.id, action="DELETE_INSTANCE",
|
|
target_type="instance", target_id=instance.id,
|
|
detail=f"删除数据源: {instance.name}",
|
|
)
|
|
await db.delete(instance)
|
|
await db.commit()
|
|
return {"message": "数据源已删除"}
|
|
|
|
|
|
@router.post("/{instance_id}/test", response_model=ConnectionTestResult)
|
|
async def test_connection(
|
|
instance_id: int,
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: User = Depends(require_role("admin", "dba")),
|
|
):
|
|
result = await db.execute(select(Instance).where(Instance.id == instance_id))
|
|
instance = result.scalar_one_or_none()
|
|
if not instance:
|
|
raise HTTPException(status_code=404, detail="数据源不存在")
|
|
|
|
instance.password = decrypt_password(instance.password)
|
|
return await InstanceService.test_connection(instance)
|
|
|
|
|
|
@router.get("/{instance_id}/databases")
|
|
async def list_databases(
|
|
instance_id: int,
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: User = Depends(get_current_user),
|
|
):
|
|
result = await db.execute(select(Instance).where(Instance.id == instance_id))
|
|
instance = result.scalar_one_or_none()
|
|
if not instance:
|
|
raise HTTPException(status_code=404, detail="数据源不存在")
|
|
|
|
# P0: 检查访问权限
|
|
await check_instance_access(current_user, instance, db)
|
|
|
|
return await InstanceService.list_databases(instance)
|
|
|
|
|
|
@router.get("/{instance_id}/databases/{database}/tables")
|
|
async def list_tables(
|
|
instance_id: int,
|
|
database: str,
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: User = Depends(get_current_user),
|
|
):
|
|
result = await db.execute(select(Instance).where(Instance.id == instance_id))
|
|
instance = result.scalar_one_or_none()
|
|
if not instance:
|
|
raise HTTPException(status_code=404, detail="数据源不存在")
|
|
|
|
# P0: 检查访问权限
|
|
await check_instance_access(current_user, instance, db)
|
|
|
|
return await InstanceService.list_tables(instance, database)
|