Skip to content

Commit

Permalink
feat: write api for sub todo
Browse files Browse the repository at this point in the history
  • Loading branch information
bachnguyen-18 committed Dec 6, 2024
1 parent 2913801 commit 79eabf6
Show file tree
Hide file tree
Showing 5 changed files with 171 additions and 13 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""update todo and subtodo table
"""refine db
Revision ID: 9245f5673cb7
Revision ID: f2d6aba28d7d
Revises: 80580dd7587b
Create Date: 2024-12-06 10:53:59.113398
Create Date: 2024-12-06 14:59:08.495370
"""
from alembic import op
Expand All @@ -11,7 +11,7 @@


# revision identifiers, used by Alembic.
revision = '9245f5673cb7'
revision = 'f2d6aba28d7d'
down_revision = '80580dd7587b'
branch_labels = None
depends_on = None
Expand Down
3 changes: 2 additions & 1 deletion backend/app/api/main.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
from fastapi import APIRouter

from app.api.routes import items, login, private, users, utils
from app.api.routes import items, login, private, users, utils, sub_todo
from app.core.config import settings

api_router = APIRouter()
api_router.include_router(login.router)
api_router.include_router(users.router)
api_router.include_router(utils.router)
api_router.include_router(items.router)
api_router.include_router(sub_todo.router)


if settings.ENVIRONMENT == "local":
Expand Down
149 changes: 149 additions & 0 deletions backend/app/api/routes/sub_todo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import uuid
from typing import Any

from fastapi import APIRouter, HTTPException
from sqlmodel import func, select

from app.api.deps import CurrentUser, SessionDep
from app.models import SubTodo, SubTodoCreate, SubTodoPublic, SubTodosPublic, SubTodoUpdate, Message, Todo

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


@router.get("/", response_model=SubTodosPublic)
def read_sub_todos(
session: SessionDep, current_user: CurrentUser, todo_id=uuid.UUID, skip: int = 0, limit: int = 100
) -> Any:
"""
Retrieve sub todos.
"""

if current_user.is_superuser:
count_statement = select(func.count()).select_from(SubTodo)
count = session.exec(count_statement).one()
statement = select(SubTodo).offset(skip).limit(limit)
todos = session.exec(statement).all()
else:
count_statement = (
select(func.count())
.select_from(SubTodo)
.where(SubTodo.todo_id == todo_id)
)
count = session.exec(count_statement).one()
statement = (
select(SubTodo)
.where(SubTodo.todo_id == todo_id)
.offset(skip)
.limit(limit)
)
todos = session.exec(statement).all()

return SubTodosPublic(data=todos, count=count)


@router.get("/{id}", response_model=SubTodoPublic)
def read_item(session: SessionDep, current_user: CurrentUser, id: uuid.UUID) -> Any:
"""
Get sub todo by ID.
"""
sub_todo = session.get(SubTodo, id)
if not sub_todo:
raise HTTPException(status_code=404, detail="Sub todo not found")
return sub_todo

@router.post("/", response_model=SubTodoPublic)
def create_sub_todo(
*, session: SessionDep, sub_todo_in: SubTodoCreate
) -> Any:
"""
Create new sub todo.
"""
todo = session.get(Todo, sub_todo_in.todo_id)
if not todo:
raise HTTPException(status_code=404, detail="Todo not found")
sub_todo = SubTodoCreate.model_validate(sub_todo_in)
create_todo = SubTodo(**dict(sub_todo))
session.add(create_todo)
session.commit()
session.refresh(create_todo)
return create_todo


# @router.put("/{id}", response_model=SubTodoPublic)
# def update_sub_todo(
# *,
# session: SessionDep,
# current_user: CurrentUser,
# id: uuid.UUID,
# todo_in: SubTodoUpdate,
# ) -> Any:
# """
# Update an item.
# """
# sub_todo = session.get(SubTodo, id)
# if not sub_todo:
# raise HTTPException(status_code=404, detail="SubTodo not found")
# if not current_user.is_superuser and (sub_todo.owner_id != current_user.id):
# raise HTTPException(status_code=400, detail="Not enough permissions")
# update_dict = todo_in.model_dump(exclude_unset=True)
# sub_todo.sqlmodel_update(update_dict)
# session.add(sub_todo)
# session.commit()
# session.refresh(sub_todo)
# return sub_todo

@router.put("/{id}", response_model=SubTodoPublic)
def update_sub_todo(
*,
session: SessionDep,
current_user: CurrentUser,
id: uuid.UUID,
sub_todo_in: SubTodoUpdate,
) -> Any:
"""
Update a sub todo by ID.
"""
# Fetch the sub todo by ID
sub_todo = session.get(SubTodo, id)
if not sub_todo:
raise HTTPException(status_code=404, detail="SubTodo not found")

# Fetch the associated parent todo for ownership verification
parent_todo = session.get(Todo, sub_todo.todo_id)
if not parent_todo:
raise HTTPException(status_code=404, detail="Parent Todo not found")

# Permission check: Ensure the user is the owner or a superuser
if not current_user.is_superuser and (parent_todo.owner_id != current_user.id):
raise HTTPException(status_code=403, detail="Not enough permissions")

# Update the SubTodo with the new data
update_data = sub_todo_in.model_dump(exclude_unset=True)
for key, value in update_data.items():
setattr(sub_todo, key, value)

# Commit changes to the database
session.add(sub_todo)
session.commit()
session.refresh(sub_todo)

return sub_todo

@router.delete("/{id}")
def delete_sub_todo(
session: SessionDep, current_user: CurrentUser, id: uuid.UUID
) -> Message:
"""
Delete a sub todo.
"""
sub_todo = session.get(SubTodo, id)
if not sub_todo:
raise HTTPException(status_code=404, detail="SubTodo not found")
todo = session.get(Todo, sub_todo.todo_id)
if not todo:
raise HTTPException(status_code=404, detail="Todo not found")
if not current_user.is_superuser and (todo.owner_id != current_user.id):
raise HTTPException(status_code=400, detail="Not enough permissions")
session.delete(sub_todo)
session.commit()
return Message(message="SubTodo deleted successfully")
9 changes: 8 additions & 1 deletion backend/app/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from sqlmodel import Session, select

from app.core.security import get_password_hash, verify_password
from app.models import Item, ItemCreate, User, UserCreate, UserUpdate
from app.models import Item, ItemCreate, User, UserCreate, UserUpdate, SubTodoCreate


def create_user(*, session: Session, user_create: UserCreate) -> User:
Expand Down Expand Up @@ -52,3 +52,10 @@ def create_item(*, session: Session, item_in: ItemCreate, owner_id: uuid.UUID) -
session.commit()
session.refresh(db_item)
return db_item

def create_subtodo(*, session: Session, item_in: SubTodoCreate, owner_id: uuid.UUID) -> Item:
db_item = Item.model_validate(item_in, update={"owner_id": owner_id})
session.add(db_item)
session.commit()
session.refresh(db_item)
return db_item
15 changes: 8 additions & 7 deletions backend/app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ class Todo(TodoBase, table=True):
owner_id: uuid.UUID = Field(
foreign_key="user.id", nullable=False, ondelete="CASCADE"
)
status: str = Field(max_length=255)
status: str = Field(default="in_progress", max_length=255)
owner: User | None = Relationship(back_populates="todos")
subtodos: list["SubTodo"] = Relationship(back_populates="todo")

Expand All @@ -142,12 +142,12 @@ class TodoCreate(TodoBase):
class TodoUpdate(TodoBase):
title: str | None = Field(default=None, min_length=1, max_length=255) # type: ignore
desc: str | None = Field(default=None, max_length=255)
status: str = Field(max_length=255)
status: str | None = Field(default=None, max_length=255)

class TodoPublic(TodoBase):
id: uuid.UUID
owner_id: uuid.UUID
status: StatusEnum
status: str

class TodosPublic(SQLModel):
data: list[TodoPublic]
Expand All @@ -158,27 +158,28 @@ class SubTodoBase(SQLModel):
title: str = Field(min_length=1, max_length=255)
desc: str = Field(max_length=255)


class SubTodo(SubTodoBase, table=True):
id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
todo_id: uuid.UUID = Field(
foreign_key="todo.id", nullable=False, ondelete="CASCADE"
)
status: str = Field(max_length=255)
status: str = Field(default="in_progress", max_length=255)
todo: Todo | None = Relationship(back_populates="subtodos")

class SubTodoCreate(SubTodoBase):
pass
todo_id: uuid.UUID

# Properties to receive on item update
class SubTodoUpdate(SubTodoBase):
title: str | None = Field(default=None, min_length=1, max_length=255) # type: ignore
desc: str | None = Field(default=None, max_length=255)
status: StatusEnum | None = Field(default=None)
status: str | None = Field(default=None, max_length=255)

class SubTodoPublic(SubTodoBase):
id: uuid.UUID
todo_id: uuid.UUID
status: StatusEnum
status: str

class SubTodosPublic(SQLModel):
data: list[SubTodoPublic]
Expand Down

0 comments on commit 79eabf6

Please sign in to comment.