Files
ctms/backend/app/api/v1/subjects.py
T
2026-06-10 10:20:04 +08:00

276 lines
10 KiB
Python

import json
import uuid
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.deps import get_operator_role_label, get_cra_site_scope, get_current_user, get_db_session, require_study_not_locked, require_api_permission
from app.crud import audit as audit_crud
from app.crud import site as site_crud
from app.crud import subject as subject_crud
from app.crud import study as study_crud
from app.models.ae import AdverseEvent
from app.schemas.subject import SubjectCreate, SubjectRead, SubjectUpdate
router = APIRouter()
def _format_date(value):
return value.isoformat() if value else None
async def _subject_audit_snapshot(db: AsyncSession, subject) -> dict:
site_name = None
if subject.site_id:
site = await site_crud.get_site(db, subject.site_id)
site_name = site.name if site else None
return {
"subject_no": subject.subject_no,
"site_name": site_name,
"status": subject.status,
"screening_date": _format_date(subject.screening_date),
"consent_date": _format_date(subject.consent_date),
"enrollment_date": _format_date(subject.enrollment_date),
"baseline_date": _format_date(subject.baseline_date),
"completion_date": _format_date(subject.completion_date),
"actual_medication_count": subject.actual_medication_count,
"drop_reason": subject.drop_reason,
}
async def _ensure_study_exists(db: AsyncSession, study_id: uuid.UUID):
study = await study_crud.get(db, study_id)
if not study:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="项目不存在")
return study
async def _ensure_subject_active(db: AsyncSession, subject) -> None:
if not subject or not subject.site_id:
return
site = await site_crud.get_site(db, subject.site_id)
if not site or not site.is_active:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="中心已停用")
@router.post(
"/",
response_model=SubjectRead,
status_code=status.HTTP_201_CREATED,
dependencies=[Depends(require_api_permission("subjects:create")), Depends(require_study_not_locked())],
)
async def create_subject(
study_id: uuid.UUID,
subject_in: SubjectCreate,
db: AsyncSession = Depends(get_db_session),
current_user=Depends(get_current_user),
) -> SubjectRead:
await _ensure_study_exists(db, study_id)
cra_scope = await get_cra_site_scope(db, study_id, current_user)
if cra_scope and subject_in.site_id not in cra_scope[0]:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="权限不足")
try:
subject = await subject_crud.create_subject(db, study_id, subject_in)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
after_snapshot = await _subject_audit_snapshot(db, subject)
await audit_crud.log_action(
db,
study_id=study_id,
entity_type="subject",
entity_id=subject.id,
action="CREATE_SUBJECT",
detail=json.dumps(
{
"targetName": subject.subject_no,
"description": f"创建参与者 {subject.subject_no}",
"before": None,
"after": after_snapshot,
},
ensure_ascii=False,
),
operator_id=current_user.id,
operator_role=await get_operator_role_label(db, study_id, current_user),
)
return subject
@router.get(
"/",
response_model=list[SubjectRead],
dependencies=[Depends(require_api_permission("subjects:read"))],
)
async def list_subjects(
study_id: uuid.UUID,
site_id: uuid.UUID | None = None,
db: AsyncSession = Depends(get_db_session),
current_user=Depends(get_current_user),
) -> list[SubjectRead]:
await _ensure_study_exists(db, study_id)
cra_scope = await get_cra_site_scope(db, study_id, current_user)
site_ids = cra_scope[0] if cra_scope else None
if site_id and site_ids is not None and site_id not in site_ids:
return []
subjects = await subject_crud.list_subjects(db, study_id, site_id=site_id, site_ids=site_ids)
subject_list = list(subjects)
if not subject_list:
return []
subject_ids = [subject.id for subject in subject_list]
ae_rows = await db.execute(
select(AdverseEvent.subject_id, AdverseEvent.is_sae, AdverseEvent.is_susar).where(
AdverseEvent.study_id == study_id,
AdverseEvent.subject_id.in_(subject_ids),
)
)
ae_flags: dict[uuid.UUID, dict[str, bool]] = {}
for row in ae_rows.all():
sid = row[0]
if not sid:
continue
if sid not in ae_flags:
ae_flags[sid] = {"has_ae": True, "has_sae": False, "has_susar": False}
if row[1]:
ae_flags[sid]["has_sae"] = True
if row[2]:
ae_flags[sid]["has_susar"] = True
result: list[SubjectRead] = []
for subject in subject_list:
data = SubjectRead.model_validate(subject)
flags = ae_flags.get(subject.id, {"has_ae": False, "has_sae": False, "has_susar": False})
data.has_ae = flags["has_ae"]
data.has_sae = flags["has_sae"]
data.has_susar = flags["has_susar"]
result.append(data)
return result
@router.get(
"/{subject_id}",
response_model=SubjectRead,
dependencies=[Depends(require_api_permission("subjects:read"))],
)
async def get_subject(
study_id: uuid.UUID,
subject_id: uuid.UUID,
db: AsyncSession = Depends(get_db_session),
current_user=Depends(get_current_user),
) -> SubjectRead:
await _ensure_study_exists(db, study_id)
subject = await subject_crud.get_subject(db, subject_id)
if not subject or subject.study_id != study_id:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="参与者不存在")
cra_scope = await get_cra_site_scope(db, study_id, current_user)
if cra_scope and subject.site_id not in cra_scope[0]:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="权限不足")
await _ensure_subject_active(db, subject)
data = SubjectRead.model_validate(subject)
ae_row = await db.execute(
select(AdverseEvent.is_sae, AdverseEvent.is_susar).where(
AdverseEvent.study_id == study_id,
AdverseEvent.subject_id == subject.id,
)
)
ae_flags = {"has_ae": False, "has_sae": False, "has_susar": False}
for row in ae_row.all():
ae_flags["has_ae"] = True
if row[0]:
ae_flags["has_sae"] = True
if row[1]:
ae_flags["has_susar"] = True
data.has_ae = ae_flags["has_ae"]
data.has_sae = ae_flags["has_sae"]
data.has_susar = ae_flags["has_susar"]
return data
@router.patch(
"/{subject_id}",
response_model=SubjectRead,
dependencies=[Depends(require_api_permission("subjects:update")), Depends(require_study_not_locked())],
)
async def update_subject(
study_id: uuid.UUID,
subject_id: uuid.UUID,
subject_in: SubjectUpdate,
db: AsyncSession = Depends(get_db_session),
current_user=Depends(get_current_user),
) -> SubjectRead:
await _ensure_study_exists(db, study_id)
subject = await subject_crud.get_subject(db, subject_id)
if not subject or subject.study_id != study_id:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="参与者不存在")
cra_scope = await get_cra_site_scope(db, study_id, current_user)
if cra_scope and subject.site_id not in cra_scope[0]:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="权限不足")
await _ensure_subject_active(db, subject)
old_status = subject.status
before_snapshot = await _subject_audit_snapshot(db, subject)
updated = await subject_crud.update_subject(db, subject, subject_in)
# 基线/治疗日期是访视计划的唯一推算基准,不能用入组日期替代。
if updated.baseline_date:
await subject_crud.sync_visits_from_baseline(db, updated)
updated = await subject_crud.sync_subject_status(db, updated)
after_snapshot = await _subject_audit_snapshot(db, updated)
description = f"变更参与者 {updated.subject_no} 状态" if updated.status != old_status else f"更新参与者 {updated.subject_no}"
await audit_crud.log_action(
db,
study_id=study_id,
entity_type="subject",
entity_id=subject_id,
action="SUBJECT_STATUS_CHANGE" if updated.status != old_status else "UPDATE_SUBJECT",
detail=json.dumps(
{
"targetName": updated.subject_no,
"description": description,
"before": before_snapshot,
"after": after_snapshot,
},
ensure_ascii=False,
),
operator_id=current_user.id,
operator_role=await get_operator_role_label(db, study_id, current_user),
)
return updated
@router.delete(
"/{subject_id}",
status_code=status.HTTP_204_NO_CONTENT,
dependencies=[Depends(require_api_permission("subjects:delete")), Depends(require_study_not_locked())],
)
async def delete_subject(
study_id: uuid.UUID,
subject_id: uuid.UUID,
db: AsyncSession = Depends(get_db_session),
current_user=Depends(get_current_user),
) -> None:
await _ensure_study_exists(db, study_id)
subject = await subject_crud.get_subject(db, subject_id)
if not subject or subject.study_id != study_id:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="参与者不存在")
cra_scope = await get_cra_site_scope(db, study_id, current_user)
if cra_scope and subject.site_id not in cra_scope[0]:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="权限不足")
before_snapshot = await _subject_audit_snapshot(db, subject)
target_name = subject.subject_no
await subject_crud.delete_subject(db, subject)
await audit_crud.log_action(
db,
study_id=study_id,
entity_type="subject",
entity_id=subject_id,
action="DELETE_SUBJECT",
detail=json.dumps(
{
"targetName": target_name,
"description": f"删除参与者 {target_name}",
"before": before_snapshot,
"after": None,
},
ensure_ascii=False,
),
operator_id=current_user.id,
operator_role=await get_operator_role_label(db, study_id, current_user),
)