69 lines
2.0 KiB
Python

from typing import Any, Dict, List, Optional, Union
from sqlalchemy.orm import Session
from app.models.customer import Customer
from app.schemas.customer import CustomerCreate, CustomerUpdate
def get_customer(db: Session, user_id: int, customer_id: int) -> Optional[Customer]:
"""Get a customer by ID for a specific user."""
return db.query(Customer).filter(
Customer.id == customer_id, Customer.user_id == user_id
).first()
def get_customers(
db: Session, user_id: int, skip: int = 0, limit: int = 100
) -> List[Customer]:
"""Get a list of customers for a specific user."""
return db.query(Customer).filter(Customer.user_id == user_id).offset(skip).limit(limit).all()
def create_customer(db: Session, user_id: int, customer_in: CustomerCreate) -> Customer:
"""Create a new customer for a specific user."""
customer_data = customer_in.model_dump()
db_customer = Customer(**customer_data, user_id=user_id)
db.add(db_customer)
db.commit()
db.refresh(db_customer)
return db_customer
def update_customer(
db: Session,
user_id: int,
db_customer: Customer,
customer_in: Union[CustomerUpdate, Dict[str, Any]]
) -> Customer:
"""Update a customer."""
customer_data = db_customer.to_dict()
if isinstance(customer_in, dict):
update_data = customer_in
else:
update_data = customer_in.model_dump(exclude_unset=True)
# Update customer fields
for field in customer_data:
if field in update_data:
setattr(db_customer, field, update_data[field])
db.add(db_customer)
db.commit()
db.refresh(db_customer)
return db_customer
def delete_customer(db: Session, user_id: int, customer_id: int) -> Optional[Customer]:
"""Delete a customer."""
customer = db.query(Customer).filter(
Customer.id == customer_id, Customer.user_id == user_id
).first()
if not customer:
return None
db.delete(customer)
db.commit()
return customer