import uuid from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.ext.asyncio import AsyncSession from app.core.deps import get_current_user, get_db_session, require_roles, require_study_member, require_study_roles from app.crud import study as study_crud from app.crud import member as member_crud from app.crud import audit as audit_crud from app.schemas.common import PaginatedResponse from app.schemas.study import StudyCreate, StudyRead, StudyUpdate from app.schemas.member import StudyMemberCreate from app.utils.pagination import paginate router = APIRouter() @router.post("/", response_model=StudyRead, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_roles(["ADMIN"]))]) async def create_study( study_in: StudyCreate, db: AsyncSession = Depends(get_db_session), current_user=Depends(get_current_user), ) -> StudyRead: existing = await study_crud.get_by_code(db, study_in.code) if existing: raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="项目编号已存在") study = await study_crud.create(db, study_in, created_by=current_user.id) # 自动将创建者添加为项目成员,角色为PM member_in = StudyMemberCreate( user_id=current_user.id, role_in_study="PM", is_active=True, ) await member_crud.add_member(db, study.id, member_in) return study @router.get("/", response_model=PaginatedResponse[StudyRead]) async def list_studies( skip: int = 0, limit: int = 100, db: AsyncSession = Depends(get_db_session), current_user=Depends(get_current_user), ) -> PaginatedResponse[StudyRead]: if current_user.role == "ADMIN": studies = await study_crud.list_studies(db, skip=skip, limit=limit) total = await study_crud.list_studies(db, skip=0, limit=10_000_000) else: studies = await study_crud.list_studies_for_user(db, current_user.id, skip=skip, limit=limit) total = await study_crud.list_studies_for_user(db, current_user.id, skip=0, limit=10_000_000) return paginate(list(studies), total=len(total)) @router.get("/{study_id}", response_model=StudyRead, dependencies=[Depends(require_study_member())]) async def get_study( study_id: uuid.UUID, db: AsyncSession = Depends(get_db_session), ) -> StudyRead: study = await study_crud.get(db, study_id) if not study: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="项目不存在") return study @router.patch( "/{study_id}", response_model=StudyRead, dependencies=[Depends(require_study_roles(["PM"]))], ) async def update_study( study_id: uuid.UUID, study_in: StudyUpdate, db: AsyncSession = Depends(get_db_session), ) -> StudyRead: study = await study_crud.get(db, study_id) if not study: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="项目不存在") # 检查项目是否已锁定(除非是解锁操作) if study.is_locked and not (study_in.is_locked is False): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="项目已锁定,无法编辑。请先解锁项目。" ) updated = await study_crud.update(db, study, study_in) return updated @router.delete( "/{study_id}", status_code=status.HTTP_204_NO_CONTENT, dependencies=[Depends(require_roles(["ADMIN"]))], ) async def delete_study( study_id: uuid.UUID, db: AsyncSession = Depends(get_db_session), current_user=Depends(get_current_user), ) -> None: """硬删除项目及其所有关联数据(不可逆操作)""" study = await study_crud.get(db, study_id) if not study: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="项目不存在") # 删除项目及其所有关联数据(包括审计日志) await study_crud.delete(db, study_id) @router.patch( "/{study_id}/lock", response_model=StudyRead, dependencies=[Depends(require_roles(["ADMIN"]))], ) async def lock_study( study_id: uuid.UUID, db: AsyncSession = Depends(get_db_session), current_user=Depends(get_current_user), ) -> StudyRead: """锁定项目(仅管理员)""" study = await study_crud.get(db, study_id) if not study: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="项目不存在") locked_study = await study_crud.lock(db, study_id) # 记录审计日志 await audit_crud.log_action( db, study_id=study_id, entity_type="study", entity_id=study_id, action="LOCK_STUDY", detail=f"项目已锁定:{study.name} ({study.code})", operator_id=current_user.id, operator_role=current_user.role, ) return locked_study @router.patch( "/{study_id}/unlock", response_model=StudyRead, dependencies=[Depends(require_roles(["ADMIN"]))], ) async def unlock_study( study_id: uuid.UUID, db: AsyncSession = Depends(get_db_session), current_user=Depends(get_current_user), ) -> StudyRead: """解锁项目(仅管理员)""" study = await study_crud.get(db, study_id) if not study: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="项目不存在") unlocked_study = await study_crud.unlock(db, study_id) # 记录审计日志 await audit_crud.log_action( db, study_id=study_id, entity_type="study", entity_id=study_id, action="UNLOCK_STUDY", detail=f"项目已解锁:{study.name} ({study.code})", operator_id=current_user.id, operator_role=current_user.role, ) return unlocked_study