43 lines
1.4 KiB
Python
43 lines
1.4 KiB
Python
from fastapi import APIRouter, Depends, Query
|
|
from sqlalchemy import or_, select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.api.deps import get_current_user, get_db
|
|
from app.models.customer import Customer
|
|
from app.schemas import CurrentUser, CustomerOptionOut
|
|
|
|
router = APIRouter(prefix="/api/v1/customers", tags=["customers"])
|
|
|
|
|
|
@router.get("", response_model=list[CustomerOptionOut])
|
|
def search_customers(
|
|
query: str = Query(min_length=2, max_length=100),
|
|
limit: int = Query(default=20, ge=1, le=50),
|
|
db: Session = Depends(get_db),
|
|
_user: CurrentUser = Depends(get_current_user),
|
|
) -> list[CustomerOptionOut]:
|
|
term = f"%{query.strip()}%"
|
|
customers = db.scalars(
|
|
select(Customer)
|
|
.where(
|
|
Customer.merged_into_customer_id.is_(None),
|
|
Customer.anonymized_at.is_(None),
|
|
or_(
|
|
Customer.public_ref.ilike(term),
|
|
Customer.first_name.ilike(term),
|
|
Customer.last_name.ilike(term),
|
|
Customer.email.ilike(term),
|
|
),
|
|
)
|
|
.order_by(Customer.last_name, Customer.first_name)
|
|
.limit(limit)
|
|
).all()
|
|
return [
|
|
CustomerOptionOut(
|
|
public_ref=customer.public_ref,
|
|
display_name=f"{customer.first_name} {customer.last_name}",
|
|
email=customer.email,
|
|
)
|
|
for customer in customers
|
|
]
|