Files
nanocode/fumamxCRM/backend/routers/customers.py
T
Ubuntu 32b43f85bd a
2026-07-03 16:58:28 +08:00

94 lines
2.6 KiB
Python

"""
客户管理路由
"""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from database import get_db
from models import User, Customer
from schemas import CustomerCreate, CustomerResponse
from auth import get_current_user
router = APIRouter(prefix="/customers", tags=["客户管理"])
@router.get("", response_model=List[CustomerResponse])
def list_customers(
skip: int = 0,
limit: int = 100,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""获取客户列表"""
customers = db.query(Customer).offset(skip).limit(limit).all()
return customers
@router.get("/{customer_id}", response_model=CustomerResponse)
def get_customer(
customer_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""获取客户详情"""
customer = db.query(Customer).filter(Customer.id == customer_id).first()
if not customer:
raise HTTPException(status_code=404, detail="客户不存在")
return customer
@router.post("", response_model=CustomerResponse)
def create_customer(
data: CustomerCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""添加客户"""
# 检查是否已存在
existing = db.query(Customer).filter(Customer.name == data.name).first()
if existing:
raise HTTPException(status_code=400, detail="客户已存在")
customer = Customer(**data.dict())
db.add(customer)
db.commit()
db.refresh(customer)
return customer
@router.put("/{customer_id}", response_model=CustomerResponse)
def update_customer(
customer_id: int,
data: CustomerCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""更新客户"""
customer = db.query(Customer).filter(Customer.id == customer_id).first()
if not customer:
raise HTTPException(status_code=404, detail="客户不存在")
for key, value in data.dict().items():
setattr(customer, key, value)
db.commit()
db.refresh(customer)
return customer
@router.delete("/{customer_id}")
def delete_customer(
customer_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""删除客户"""
customer = db.query(Customer).filter(Customer.id == customer_id).first()
if not customer:
raise HTTPException(status_code=404, detail="客户不存在")
db.delete(customer)
db.commit()
return {"message": "删除成功"}