Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Write api for sub todo #1443

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions backend/app/alembic/versions/80580dd7587b_add_three_tables.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""add three tables

Revision ID: 80580dd7587b
Revises: 1a31ce608336
Create Date: 2024-12-05 16:24:28.872367

"""
from alembic import op
import sqlalchemy as sa
import sqlmodel.sql.sqltypes


# revision identifiers, used by Alembic.
revision = '80580dd7587b'
down_revision = '1a31ce608336'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('todo',
sa.Column('title', sqlmodel.sql.sqltypes.AutoString(length=255), nullable=False),
sa.Column('desc', sqlmodel.sql.sqltypes.AutoString(length=255), nullable=True),
sa.Column('id', sa.Uuid(), nullable=False),
sa.Column('user_id', sa.Uuid(), nullable=False),
sa.Column('status', sqlmodel.sql.sqltypes.AutoString(length=20), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
op.create_table('subtodo',
sa.Column('title', sqlmodel.sql.sqltypes.AutoString(length=255), nullable=False),
sa.Column('desc', sqlmodel.sql.sqltypes.AutoString(length=255), nullable=True),
sa.Column('id', sa.Uuid(), nullable=False),
sa.Column('todo_id', sa.Uuid(), nullable=False),
sa.Column('status', sqlmodel.sql.sqltypes.AutoString(length=20), nullable=False),
sa.ForeignKeyConstraint(['todo_id'], ['todo.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('subtodo')
op.drop_table('todo')
# ### end Alembic commands ###
63 changes: 63 additions & 0 deletions backend/app/alembic/versions/f2d6aba28d7d_refine_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
"""refine db

Revision ID: f2d6aba28d7d
Revises: 80580dd7587b
Create Date: 2024-12-06 14:59:08.495370

"""
from alembic import op
import sqlalchemy as sa
import sqlmodel.sql.sqltypes


# revision identifiers, used by Alembic.
revision = 'f2d6aba28d7d'
down_revision = '80580dd7587b'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('subtodo', 'desc',
existing_type=sa.VARCHAR(length=255),
nullable=False)
op.alter_column('subtodo', 'status',
existing_type=sa.VARCHAR(length=20),
type_=sqlmodel.sql.sqltypes.AutoString(length=255),
existing_nullable=False)
op.add_column('todo', sa.Column('owner_id', sa.Uuid(), nullable=False))
op.alter_column('todo', 'desc',
existing_type=sa.VARCHAR(length=255),
nullable=False)
op.alter_column('todo', 'status',
existing_type=sa.VARCHAR(length=20),
type_=sqlmodel.sql.sqltypes.AutoString(length=255),
existing_nullable=False)
op.drop_constraint('todo_user_id_fkey', 'todo', type_='foreignkey')
op.create_foreign_key(None, 'todo', 'user', ['owner_id'], ['id'], ondelete='CASCADE')
op.drop_column('todo', 'user_id')
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('todo', sa.Column('user_id', sa.UUID(), autoincrement=False, nullable=False))
op.drop_constraint(None, 'todo', type_='foreignkey')
op.create_foreign_key('todo_user_id_fkey', 'todo', 'user', ['user_id'], ['id'], ondelete='CASCADE')
op.alter_column('todo', 'status',
existing_type=sqlmodel.sql.sqltypes.AutoString(length=255),
type_=sa.VARCHAR(length=20),
existing_nullable=False)
op.alter_column('todo', 'desc',
existing_type=sa.VARCHAR(length=255),
nullable=True)
op.drop_column('todo', 'owner_id')
op.alter_column('subtodo', 'status',
existing_type=sqlmodel.sql.sqltypes.AutoString(length=255),
type_=sa.VARCHAR(length=20),
existing_nullable=False)
op.alter_column('subtodo', 'desc',
existing_type=sa.VARCHAR(length=255),
nullable=True)
# ### end Alembic commands ###
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
72 changes: 72 additions & 0 deletions backend/app/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import uuid
from enum import Enum

from pydantic import EmailStr
from sqlmodel import Field, Relationship, SQLModel
Expand Down Expand Up @@ -44,6 +45,7 @@ class User(UserBase, table=True):
id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
hashed_password: str
items: list["Item"] = Relationship(back_populates="owner", cascade_delete=True)
todos: list["Todo"] = Relationship(back_populates="owner", cascade_delete=True)


# Properties to return via API, id is always required
Expand Down Expand Up @@ -112,3 +114,73 @@ class TokenPayload(SQLModel):
class NewPassword(SQLModel):
token: str
new_password: str = Field(min_length=8, max_length=40)

# Shared properties
class StatusEnum(str, Enum):
pending = "pending"
completed = "completed"
in_progress = "in_progress"

class TodoBase(SQLModel):
title: str = Field(min_length=1, max_length=255)
desc: str = Field(max_length=255)

# Table Todo
class Todo(TodoBase, table=True):
id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
owner_id: uuid.UUID = Field(
foreign_key="user.id", nullable=False, ondelete="CASCADE"
)
status: str = Field(default="in_progress", max_length=255)
owner: User | None = Relationship(back_populates="todos")
subtodos: list["SubTodo"] = Relationship(back_populates="todo")

class TodoCreate(TodoBase):
pass

# Properties to receive on item update
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 | None = Field(default=None, max_length=255)

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

class TodosPublic(SQLModel):
data: list[TodoPublic]
count: int

# Table SubTodo
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(default="in_progress", max_length=255)
todo: Todo | None = Relationship(back_populates="subtodos")

class SubTodoCreate(SubTodoBase):
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: str | None = Field(default=None, max_length=255)

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

class SubTodosPublic(SQLModel):
data: list[SubTodoPublic]
count: int
2 changes: 1 addition & 1 deletion backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ dependencies = [
"alembic<2.0.0,>=1.12.1",
"httpx<1.0.0,>=0.25.1",
"psycopg[binary]<4.0.0,>=3.1.13",
"sqlmodel<1.0.0,>=0.0.21",
"sqlmodel>=0.0.21,<1.0.0",
# Pin bcrypt until passlib supports the latest
"bcrypt==4.0.1",
"pydantic-settings<3.0.0,>=2.2.1",
Expand Down
Loading
Loading