120 lines
3.4 KiB
Python

from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import crud, schemas
from app.db.session import get_db
router = APIRouter()
@router.get("/", response_model=List[schemas.Category])
def read_categories(
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100,
name: Optional[str] = None,
) -> Any:
"""
Retrieve categories with optional filtering by name.
"""
categories = crud.category.get_multi(db, skip=skip, limit=limit, name=name)
return categories
@router.post("/", response_model=schemas.Category, status_code=status.HTTP_201_CREATED)
def create_category(
*,
db: Session = Depends(get_db),
category_in: schemas.CategoryCreate,
) -> Any:
"""
Create new category.
"""
# Check if category with the same name already exists
category = crud.category.get_by_name(db, name=category_in.name)
if category:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Category with this name already exists.",
)
category = crud.category.create(db, obj_in=category_in)
return category
@router.get("/{category_id}", response_model=schemas.Category)
def read_category(
*,
db: Session = Depends(get_db),
category_id: str,
) -> Any:
"""
Get category by ID.
"""
category = crud.category.get(db, category_id=category_id)
if not category:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Category not found",
)
return category
@router.put("/{category_id}", response_model=schemas.Category)
def update_category(
*,
db: Session = Depends(get_db),
category_id: str,
category_in: schemas.CategoryUpdate,
) -> Any:
"""
Update a category.
"""
category = crud.category.get(db, category_id=category_id)
if not category:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Category not found",
)
# Check if trying to update to existing name
if category_in.name and category_in.name != category.name:
existing_category = crud.category.get_by_name(db, name=category_in.name)
if existing_category and existing_category.id != category_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Category with this name already exists",
)
category = crud.category.update(db, db_obj=category, obj_in=category_in)
return category
@router.delete("/{category_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
def delete_category(
*,
db: Session = Depends(get_db),
category_id: str,
) -> Any:
"""
Delete a category.
"""
category = crud.category.get(db, category_id=category_id)
if not category:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Category not found",
)
# Check if category has products before deleting
if category.products and len(category.products) > 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Cannot delete category with products. Remove or reassign products first.",
)
crud.category.remove(db, category_id=category_id)
return None