from typing import List from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session from backend.app.db import get_db from backend.app import models from backend.app.schemas import ( CustomerCreate, CustomerRead, CustomerUpdate, ) router = APIRouter(prefix="/customers", tags=["customers"]) @router.get("/", response_model=List[CustomerRead]) async def list_customers(db: Session = Depends(get_db)): customers = db.query(models.Customer).order_by(models.Customer.created_at.desc()).all() return customers @router.post("/", response_model=CustomerRead, status_code=status.HTTP_201_CREATED) async def create_customer(payload: CustomerCreate, db: Session = Depends(get_db)): customer = models.Customer( name=payload.name, contact_info=payload.contact_info, ) db.add(customer) db.commit() db.refresh(customer) return customer @router.get("/{customer_id}", response_model=CustomerRead) async def get_customer(customer_id: int, db: Session = Depends(get_db)): customer = db.query(models.Customer).get(customer_id) if not customer: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Customer not found") return customer @router.put("/{customer_id}", response_model=CustomerRead) async def update_customer( customer_id: int, payload: CustomerUpdate, db: Session = Depends(get_db) ): customer = db.query(models.Customer).get(customer_id) if not customer: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Customer not found") if payload.name is not None: customer.name = payload.name if payload.contact_info is not None: customer.contact_info = payload.contact_info db.commit() db.refresh(customer) return customer @router.delete("/{customer_id}", status_code=status.HTTP_204_NO_CONTENT) async def delete_customer(customer_id: int, db: Session = Depends(get_db)): customer = db.query(models.Customer).get(customer_id) if not customer: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Customer not found") db.delete(customer) db.commit() return None