103 lines
2.7 KiB
Python
103 lines
2.7 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.Supplier])
|
|
def read_suppliers(
|
|
db: Session = Depends(get_db),
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
name: Optional[str] = None,
|
|
) -> Any:
|
|
"""
|
|
Retrieve suppliers with optional filtering by name.
|
|
"""
|
|
suppliers = crud.supplier.get_multi(db, skip=skip, limit=limit, name=name)
|
|
return suppliers
|
|
|
|
|
|
@router.post("/", response_model=schemas.Supplier, status_code=status.HTTP_201_CREATED)
|
|
def create_supplier(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
supplier_in: schemas.SupplierCreate,
|
|
) -> Any:
|
|
"""
|
|
Create new supplier.
|
|
"""
|
|
supplier = crud.supplier.create(db, obj_in=supplier_in)
|
|
return supplier
|
|
|
|
|
|
@router.get("/{supplier_id}", response_model=schemas.Supplier)
|
|
def read_supplier(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
supplier_id: str,
|
|
) -> Any:
|
|
"""
|
|
Get supplier by ID.
|
|
"""
|
|
supplier = crud.supplier.get(db, supplier_id=supplier_id)
|
|
if not supplier:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Supplier not found",
|
|
)
|
|
return supplier
|
|
|
|
|
|
@router.put("/{supplier_id}", response_model=schemas.Supplier)
|
|
def update_supplier(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
supplier_id: str,
|
|
supplier_in: schemas.SupplierUpdate,
|
|
) -> Any:
|
|
"""
|
|
Update a supplier.
|
|
"""
|
|
supplier = crud.supplier.get(db, supplier_id=supplier_id)
|
|
if not supplier:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Supplier not found",
|
|
)
|
|
|
|
supplier = crud.supplier.update(db, db_obj=supplier, obj_in=supplier_in)
|
|
return supplier
|
|
|
|
|
|
@router.delete("/{supplier_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
|
def delete_supplier(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
supplier_id: str,
|
|
) -> Any:
|
|
"""
|
|
Delete a supplier.
|
|
"""
|
|
supplier = crud.supplier.get(db, supplier_id=supplier_id)
|
|
if not supplier:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Supplier not found",
|
|
)
|
|
|
|
# Check if supplier has products before deleting
|
|
if supplier.products and len(supplier.products) > 0:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Cannot delete supplier with products. Remove or reassign products first.",
|
|
)
|
|
|
|
crud.supplier.remove(db, supplier_id=supplier_id)
|
|
return None
|