70 lines
2.6 KiB
Python
70 lines
2.6 KiB
Python
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.schemas.common import PaginatedResponse
|
|
from app.schemas.study import StudyCreate, StudyRead, StudyUpdate
|
|
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)
|
|
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="项目不存在")
|
|
updated = await study_crud.update(db, study, study_in)
|
|
return updated
|