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_study_member, require_study_roles from app.crud import audit as audit_crud from app.crud import milestone as milestone_crud from app.crud import study as study_crud from app.crud import task as task_crud from app.crud import user as user_crud from app.schemas.task import TaskCreate, TaskRead, TaskUpdate from app.schemas.user import UserDisplay router = APIRouter() ALLOW_ASSIGNEE_UPDATE_STATUS = False 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="Study not found") return study async def _validate_milestone(db: AsyncSession, study_id: uuid.UUID, milestone_id: uuid.UUID | None): if milestone_id is None: return milestone = await milestone_crud.get(db, milestone_id) if not milestone: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Milestone not found") if milestone.study_id != study_id: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Milestone does not belong to study") @router.post( "/", response_model=TaskRead, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_study_roles(["PM"]))], ) async def create_task( study_id: uuid.UUID, task_in: TaskCreate, db: AsyncSession = Depends(get_db_session), current_user=Depends(get_current_user), ) -> TaskRead: await _ensure_study_exists(db, study_id) await _validate_milestone(db, study_id, task_in.milestone_id) task = await task_crud.create(db, study_id, task_in, created_by=current_user.id) assignee = None if task.assignee_id: assignee = await user_crud.get_by_id(db, task.assignee_id) await audit_crud.log_action( db, study_id=study_id, entity_type="task", entity_id=task.id, action="CREATE_TASK", detail=f"Task {task.id} created", operator_id=current_user.id, operator_role=current_user.role, ) return _to_task_read(task, assignee) @router.get( "/", response_model=list[TaskRead], dependencies=[Depends(require_study_member())], ) async def list_tasks( study_id: uuid.UUID, milestone_id: uuid.UUID | None = None, assignee_id: uuid.UUID | None = None, status: str | None = None, db: AsyncSession = Depends(get_db_session), ) -> list[TaskRead]: await _ensure_study_exists(db, study_id) tasks = await task_crud.list_tasks(db, study_id, milestone_id=milestone_id, assignee_id=assignee_id, status=status) assignee_ids = {t.assignee_id for t in tasks if t.assignee_id} users_map = await user_crud.get_users_by_ids(db, assignee_ids) result: list[TaskRead] = [] for t in tasks: user = users_map.get(t.assignee_id) result.append(_to_task_read(t, user)) return result @router.patch( "/{task_id}", response_model=TaskRead, dependencies=[Depends(require_study_roles(["PM"]))], ) async def update_task( study_id: uuid.UUID, task_id: uuid.UUID, task_in: TaskUpdate, db: AsyncSession = Depends(get_db_session), current_user=Depends(get_current_user), ) -> TaskRead: await _ensure_study_exists(db, study_id) task = await task_crud.get(db, task_id) if not task or task.study_id != study_id: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Task not found") if task_in.milestone_id: await _validate_milestone(db, study_id, task_in.milestone_id) old_status = task.status updated = await task_crud.update(db, task, task_in) assignee = None if updated.assignee_id: assignee = await user_crud.get_by_id(db, updated.assignee_id) detail = None if task_in.status and task_in.status != old_status: detail = f"task {task_id} status {old_status} -> {task_in.status}" await audit_crud.log_action( db, study_id=study_id, entity_type="task", entity_id=task_id, action="UPDATE_TASK" if not detail else "TASK_STATUS_CHANGE", detail=detail or "Task updated", operator_id=current_user.id, operator_role=current_user.role, ) return _to_task_read(updated, assignee) def _to_task_read(task, assignee) -> TaskRead: return TaskRead( id=task.id, study_id=task.study_id, milestone_id=task.milestone_id, title=task.title, description=task.description, assignee_id=task.assignee_id, assignee=UserDisplay.model_validate(assignee) if assignee else None, priority=task.priority, due_date=task.due_date, status=task.status, completed_at=task.completed_at, created_by=task.created_by, created_at=task.created_at, updated_at=task.updated_at, )