File size: 2,715 Bytes
6a0ff33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
"""Workflow API endpoints."""

from datetime import datetime
from typing import Optional

from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession

from backend.api.deps import get_current_user, get_db
from backend.db.models import User
from backend.db.repository import create_workflow, get_workflow_by_id, get_workflows_by_user

router = APIRouter(prefix="/api/workflows", tags=["workflows"])


# ── Schemas ──────────────────────────────────────────────────────────

class WorkflowCreateRequest(BaseModel):
    prompt: str = Field(..., min_length=1)


class TaskResponse(BaseModel):
    id: str
    task_type: str
    status: str
    created_at: datetime

    model_config = {"from_attributes": True}


class WorkflowResponse(BaseModel):
    id: str
    prompt: str
    status: str
    created_at: datetime
    updated_at: datetime

    model_config = {"from_attributes": True}


class WorkflowDetailResponse(WorkflowResponse):
    tasks: list[TaskResponse] = []


# ── Routes ───────────────────────────────────────────────────────────

@router.post("", response_model=WorkflowResponse, status_code=status.HTTP_201_CREATED)
async def create(
    body: WorkflowCreateRequest,
    current_user: User = Depends(get_current_user),
    session: AsyncSession = Depends(get_db),
):
    """Create a new workflow (status=pending, no execution yet)."""
    workflow = await create_workflow(session, user_id=current_user.id, prompt=body.prompt)
    return workflow


@router.get("", response_model=list[WorkflowResponse])
async def list_workflows(
    current_user: User = Depends(get_current_user),
    session: AsyncSession = Depends(get_db),
):
    """List all workflows for the current user."""
    workflows = await get_workflows_by_user(session, current_user.id)
    return workflows


@router.get("/{workflow_id}", response_model=WorkflowDetailResponse)
async def get_workflow(
    workflow_id: str,
    current_user: User = Depends(get_current_user),
    session: AsyncSession = Depends(get_db),
):
    """Get a single workflow with its tasks."""
    workflow = await get_workflow_by_id(session, workflow_id)
    if not workflow:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Workflow not found")
    if workflow.user_id != current_user.id:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied")
    return workflow