ymt-python / routers /operation_log.py
hsailorj's picture
Add application file
551658a
Raw
History Blame Contribute Delete
2.89 kB
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from database import get_db
from models.operation_log import OperationLog
from models.user import User
from schemas.operation_log import OperationLogResponse, OperationLogCreate
from routers.auth import get_current_user, get_current_superadmin, is_admin_user
router = APIRouter()
# 记录操作日志的辅助函数
def create_operation_log(db: Session, user: User, module: str, operation_type: str, operation_detail: str = None, before_data: str = None, after_data: str = None, company_code: str = None):
"""创建操作日志"""
log = OperationLog(
user_id=user.id,
username=user.username,
company_code=company_code,
module=module,
operation_type=operation_type,
operation_detail=operation_detail,
before_data=before_data,
after_data=after_data
)
db.add(log)
db.commit()
db.refresh(log)
return log
# 获取操作日志列表
@router.get("/", response_model=List[OperationLogResponse])
async def get_operation_logs(
module: str = None,
operation_type: str = None,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
"""获取操作日志列表,支持按模块和操作类型过滤"""
query = db.query(OperationLog)
# 数据权限分级:普通用户只能看到自己公司的日志,admin和超级管理员可以看到所有日志
if not is_admin_user(current_user) and not current_user.is_superadmin and current_user.company_code:
query = query.filter(OperationLog.company_code == current_user.company_code)
if module:
query = query.filter(OperationLog.module == module)
if operation_type:
query = query.filter(OperationLog.operation_type == operation_type)
# 只返回前10条,并按照日期倒序排列
logs = query.order_by(OperationLog.created_at.desc()).limit(10).all()
return logs
# 获取指定模块的操作日志
@router.get("/module/{module}", response_model=List[OperationLogResponse])
async def get_operation_logs_by_module(
module: str,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
"""获取指定模块的操作日志"""
query = db.query(OperationLog).filter(
OperationLog.module == module
)
# 数据权限分级:普通用户只能看到自己公司的日志,admin和超级管理员可以看到所有日志
if not is_admin_user(current_user) and not current_user.is_superadmin and current_user.company_code:
query = query.filter(OperationLog.company_code == current_user.company_code)
# 只返回前10条,并按照日期倒序排列
logs = query.order_by(OperationLog.created_at.desc()).limit(10).all()
return logs