2025-05-18 18:02:59 +00:00

117 lines
3.0 KiB
Python

from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.db.session import get_db
from app.db.models.product import Product
from app.db.models.user import User
from app.schemas.product import ProductCreate, ProductResponse, ProductUpdate
from app.core.security import get_current_active_superuser
router = APIRouter()
@router.post("/products/", response_model=ProductResponse, status_code=status.HTTP_201_CREATED)
def create_product(
product_in: ProductCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_active_superuser)
):
"""
Create a new product (superuser only).
"""
product = Product(
name=product_in.name,
description=product_in.description,
price=product_in.price,
stock=product_in.stock,
image_url=product_in.image_url
)
db.add(product)
db.commit()
db.refresh(product)
return product
@router.get("/products/", response_model=List[ProductResponse])
def get_products(
skip: int = 0,
limit: int = 100,
db: Session = Depends(get_db)
):
"""
Get all products.
"""
products = db.query(Product).offset(skip).limit(limit).all()
return products
@router.get("/products/{product_id}", response_model=ProductResponse)
def get_product(
product_id: int,
db: Session = Depends(get_db)
):
"""
Get a specific product by ID.
"""
product = db.query(Product).filter(Product.id == product_id).first()
if not product:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Product not found"
)
return product
@router.patch("/products/{product_id}", response_model=ProductResponse)
def update_product(
product_id: int,
product_in: ProductUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_active_superuser)
):
"""
Update a product (superuser only).
"""
product = db.query(Product).filter(Product.id == product_id).first()
if not product:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Product not found"
)
# Update product fields if provided
update_data = product_in.dict(exclude_unset=True)
for field, value in update_data.items():
setattr(product, field, value)
db.add(product)
db.commit()
db.refresh(product)
return product
@router.delete("/products/{product_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
def delete_product(
product_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_active_superuser)
):
"""
Delete a product (superuser only).
"""
product = db.query(Product).filter(Product.id == product_id).first()
if not product:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Product not found"
)
db.delete(product)
db.commit()
return None