67 lines
2.3 KiB
Python
67 lines
2.3 KiB
Python
from typing import List, Optional, Any
|
|
|
|
from sqlalchemy import or_
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.database.crud_base import CRUDBase
|
|
from app.models.item import Item
|
|
from app.schemas.item import ItemCreate, ItemUpdate
|
|
|
|
|
|
class CRUDItem(CRUDBase[Item, ItemCreate, ItemUpdate]):
|
|
def get_by_name(self, db: Session, *, name: str) -> Optional[Item]:
|
|
return db.query(Item).filter(Item.name == name).first()
|
|
|
|
def get_multi_by_active(
|
|
self, db: Session, *, active: bool, skip: int = 0, limit: int = 100
|
|
) -> List[Item]:
|
|
return (
|
|
db.query(Item)
|
|
.filter(Item.is_active == active)
|
|
.offset(skip)
|
|
.limit(limit)
|
|
.all()
|
|
)
|
|
|
|
def search(
|
|
self, db: Session, *, filter_text: str, skip: int = 0, limit: int = 100, **filters: Any
|
|
) -> List[Item]:
|
|
"""
|
|
Search for items based on the provided filter text and additional filters.
|
|
|
|
Args:
|
|
db: Database session
|
|
filter_text: Search filter text to match against name and description
|
|
skip: Number of records to skip
|
|
limit: Maximum number of records to return
|
|
**filters: Additional filters (e.g., active=True)
|
|
|
|
Returns:
|
|
List of items matching the search criteria
|
|
"""
|
|
db_query = db.query(Item)
|
|
|
|
# Apply search filter to name and description
|
|
if filter_text:
|
|
search_filter = or_(
|
|
Item.name.ilike(f"%{filter_text}%"),
|
|
Item.description.ilike(f"%{filter_text}%"),
|
|
)
|
|
db_query = db_query.filter(search_filter)
|
|
|
|
# Apply additional filters
|
|
if "active" in filters and filters["active"] is not None:
|
|
db_query = db_query.filter(Item.is_active == filters["active"])
|
|
|
|
# Apply price range filter if provided
|
|
if "price_min" in filters and filters["price_min"] is not None:
|
|
db_query = db_query.filter(Item.price >= filters["price_min"])
|
|
|
|
if "price_max" in filters and filters["price_max"] is not None:
|
|
db_query = db_query.filter(Item.price <= filters["price_max"])
|
|
|
|
# Return paginated results
|
|
return db_query.offset(skip).limit(limit).all()
|
|
|
|
|
|
item = CRUDItem(Item) |