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( q: str | None = None, db: Session = Depends(get_db), ): """列表客户,支持 q 按名称、联系方式模糊搜索。""" query = db.query(models.Customer).order_by(models.Customer.created_at.desc()) if q and q.strip(): term = f"%{q.strip()}%" query = query.filter( (models.Customer.name.ilike(term)) | (models.Customer.contact_info.ilike(term)) ) return query.all() @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, tags=payload.tags, ) 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 if payload.tags is not None: customer.tags = payload.tags 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