82 lines
2.0 KiB
Python
82 lines
2.0 KiB
Python
from typing import Any, Dict, List, Optional, Union
|
|
|
|
from fastapi.encoders import jsonable_encoder
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models.supplier import Supplier
|
|
from app.schemas.supplier import SupplierCreate, SupplierUpdate
|
|
from app.utils.uuid import generate_uuid
|
|
|
|
|
|
def get(db: Session, supplier_id: str) -> Optional[Supplier]:
|
|
"""
|
|
Get a supplier by ID.
|
|
"""
|
|
return db.query(Supplier).filter(Supplier.id == supplier_id).first()
|
|
|
|
|
|
def get_by_name(db: Session, name: str) -> Optional[Supplier]:
|
|
"""
|
|
Get a supplier by name (exact match).
|
|
"""
|
|
return db.query(Supplier).filter(Supplier.name == name).first()
|
|
|
|
|
|
def get_multi(
|
|
db: Session, *, skip: int = 0, limit: int = 100, name: Optional[str] = None
|
|
) -> List[Supplier]:
|
|
"""
|
|
Get multiple suppliers with optional filtering by name.
|
|
"""
|
|
query = db.query(Supplier)
|
|
|
|
if name:
|
|
query = query.filter(Supplier.name.ilike(f"%{name}%"))
|
|
|
|
return query.offset(skip).limit(limit).all()
|
|
|
|
|
|
def create(db: Session, *, obj_in: SupplierCreate) -> Supplier:
|
|
"""
|
|
Create a new supplier.
|
|
"""
|
|
obj_in_data = jsonable_encoder(obj_in)
|
|
db_obj = Supplier(**obj_in_data, id=generate_uuid())
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
|
|
def update(
|
|
db: Session, *, db_obj: Supplier, obj_in: Union[SupplierUpdate, Dict[str, Any]]
|
|
) -> Supplier:
|
|
"""
|
|
Update a supplier.
|
|
"""
|
|
obj_data = jsonable_encoder(db_obj)
|
|
if isinstance(obj_in, dict):
|
|
update_data = obj_in
|
|
else:
|
|
update_data = obj_in.model_dump(exclude_unset=True)
|
|
|
|
for field in obj_data:
|
|
if field in update_data:
|
|
setattr(db_obj, field, update_data[field])
|
|
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
|
|
def remove(db: Session, *, supplier_id: str) -> Optional[Supplier]:
|
|
"""
|
|
Delete a supplier.
|
|
"""
|
|
obj = db.query(Supplier).get(supplier_id)
|
|
if obj:
|
|
db.delete(obj)
|
|
db.commit()
|
|
return obj
|