2025-06-02 11:37:11 +00:00

109 lines
3.0 KiB
Python

from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from app.core.deps import get_current_active_user, get_current_superuser
from app.db.session import get_db
from app.models.user import User
from app.schemas.product import Product, ProductCreate, ProductUpdate
from app.services import product as product_service
router = APIRouter()
@router.get("/", response_model=List[Product])
def read_products(
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100,
active_only: bool = Query(False, description="Filter only active products"),
current_user: User = Depends(get_current_active_user),
) -> Any:
"""
Retrieve products.
"""
products = product_service.get_multi(
db, skip=skip, limit=limit, active_only=active_only
)
return products
@router.post("/", response_model=Product)
def create_product(
*,
db: Session = Depends(get_db),
product_in: ProductCreate,
current_user: User = Depends(get_current_superuser),
) -> Any:
"""
Create new product. Requires superuser access.
"""
product = product_service.get_by_sku(db, sku=product_in.sku)
if product:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A product with this SKU already exists",
)
product = product_service.create(db, obj_in=product_in)
return product
@router.get("/{product_id}", response_model=Product)
def read_product(
*,
db: Session = Depends(get_db),
product_id: int,
current_user: User = Depends(get_current_active_user),
) -> Any:
"""
Get product by ID.
"""
product = product_service.get(db, product_id=product_id)
if not product:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Product not found",
)
return product
@router.put("/{product_id}", response_model=Product)
def update_product(
*,
db: Session = Depends(get_db),
product_id: int,
product_in: ProductUpdate,
current_user: User = Depends(get_current_superuser),
) -> Any:
"""
Update a product. Requires superuser access.
"""
product = product_service.get(db, product_id=product_id)
if not product:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Product not found",
)
product = product_service.update(db, db_obj=product, obj_in=product_in)
return product
@router.delete("/{product_id}", response_model=Product)
def delete_product(
*,
db: Session = Depends(get_db),
product_id: int,
current_user: User = Depends(get_current_superuser),
) -> Any:
"""
Delete a product. Requires superuser access.
"""
product = product_service.get(db, product_id=product_id)
if not product:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Product not found",
)
product = product_service.remove(db, product_id=product_id)
return product