utp_service/backend/app/routers/tasks.py
2026-04-07 00:29:35 +03:00

73 lines
2.2 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import select, desc
from sqlalchemy.orm import selectinload
from sqlalchemy.ext.asyncio import AsyncSession
from app.dependencies import get_current_user, get_db
from app.models.task import Task
from app.models.user import User
from app.plugins.registry import action_registry
from app.schemas.task import ActionInfo, TaskCreate, TaskDetail, TaskRead
from app.services import task as task_service
router = APIRouter(prefix="/api/v1/tasks", tags=["tasks"])
@router.get("/actions", response_model=list[ActionInfo])
async def list_actions(_: User = Depends(get_current_user)):
return [
ActionInfo(
name=a.name,
display_name=a.display_name,
compatible_categories=a.compatible_categories,
params_schema=a.params_schema,
)
for a in action_registry.all()
]
@router.post("", response_model=TaskRead, status_code=status.HTTP_202_ACCEPTED)
async def create_task(
body: TaskCreate,
current_user: User = Depends(get_current_user),
):
try:
task = await task_service.create_task(
action_type=body.type,
target_scope=body.target_scope,
params=body.params,
user_id=current_user.id,
)
except ValueError as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
return task
@router.get("", response_model=list[TaskRead])
async def list_tasks(
limit: int = 50,
offset: int = 0,
db: AsyncSession = Depends(get_db),
_: User = Depends(get_current_user),
):
result = await db.execute(
select(Task).order_by(desc(Task.created_at)).offset(offset).limit(limit)
)
return result.scalars().all()
@router.get("/{task_id}", response_model=TaskDetail)
async def get_task(
task_id: str,
db: AsyncSession = Depends(get_db),
_: User = Depends(get_current_user),
):
result = await db.execute(
select(Task)
.options(selectinload(Task.events), selectinload(Task.device_results))
.where(Task.id == task_id)
)
task = result.scalar_one_or_none()
if task is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Task not found")
return task