44 lines
1.4 KiB
Python
44 lines
1.4 KiB
Python
"""Customers router.
|
|
|
|
GET /api/customers
|
|
GET /api/customers/{id}
|
|
POST /api/customers
|
|
"""
|
|
from typing import List
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.database import get_db
|
|
from app.routers.auth import require_admin
|
|
from app.models import Customer
|
|
from app.schemas import CustomerOut, CustomerRegister
|
|
|
|
router = APIRouter(dependencies=[Depends(require_admin)])
|
|
|
|
|
|
@router.get("", response_model=List[CustomerOut])
|
|
def list_customers(db: Session = Depends(get_db)):
|
|
return db.query(Customer).order_by(Customer.created_at.desc()).all()
|
|
|
|
|
|
@router.get("/{customer_id}", response_model=CustomerOut)
|
|
def get_customer(customer_id, db: Session = Depends(get_db)):
|
|
customer = db.query(Customer).filter(Customer.id == customer_id).first()
|
|
if customer is None:
|
|
raise HTTPException(status_code=404, detail="customer not found")
|
|
return customer
|
|
|
|
|
|
@router.post("", response_model=CustomerOut)
|
|
def create_customer(body: CustomerRegister, db: Session = Depends(get_db)):
|
|
email = body.email.strip().lower()
|
|
existing = db.query(Customer).filter(Customer.email == email).first()
|
|
if existing is not None:
|
|
raise HTTPException(status_code=409, detail="email already registered")
|
|
customer = Customer(email=email, name=body.name, shipping_addr=body.shipping_addr or {})
|
|
db.add(customer)
|
|
db.commit()
|
|
db.refresh(customer)
|
|
return customer
|