feat(catalog): hierarchical category tree, recursive product count, and child-aware brand filtering

This commit is contained in:
iFixKart Dev 2026-11-06 15:14:36 +05:30
parent 593e0a972d
commit 3ac30e702e
2 changed files with 57 additions and 15 deletions

View file

@ -136,11 +136,22 @@ def get_all_brands(
return db.execute(stmt).scalars().all()
if category_id:
from app.models.ProductModel import Product
target_cats = db.execute(
select(Category.category_id).where((Category.category_id == category_id) | (Category.slug == category_id))
).scalars().all()
if target_cats:
child_cats = db.execute(
select(Category.category_id).where(Category.parent_category_id.in_(target_cats))
).scalars().all()
all_cat_ids = list(set(target_cats + child_cats))
else:
all_cat_ids = [category_id]
stmt = select(Brand).where(
Brand.is_active == True,
Brand.brand_id.in_(
select(Product.brand_id)
.where(Product.category_id == category_id, Product.status == 'active')
.where(Product.category_id.in_(all_cat_ids), Product.status == 'active')
)
)
return db.execute(stmt).scalars().all()
@ -174,11 +185,15 @@ def create_brand(data: BrandCreate, db: Session = Depends(get_db), current_user:
# ================= CATEGORY ENDPOINTS =================
@router.get("/categories/all", response_model=List[CategoryResponse])
def get_all_categories(has_products: bool = Query(False), db: Session = Depends(get_db)):
def get_all_categories(
has_products: bool = Query(False),
root_only: bool = Query(False),
db: Session = Depends(get_db)
):
from sqlalchemy import func
from app.models.ProductModel import Product
# Compute count of active products for each category
# Compute count of direct active products for each category
counts_rows = db.execute(
select(Product.category_id, func.count(Product.product_id))
.where(Product.status == "active")
@ -187,28 +202,52 @@ def get_all_categories(has_products: bool = Query(False), db: Session = Depends(
count_map = {cat_id: cnt for cat_id, cnt in counts_rows if cat_id}
stmt = select(Category).where(Category.is_active == True)
if has_products:
stmt = stmt.where(Category.category_id.in_(count_map.keys()))
categories = db.execute(stmt.order_by(Category.sort_order)).scalars().all()
res = []
# Build category items lookup
cat_lookup = {}
for cat in categories:
data = {
cat_lookup[cat.category_id] = {
"category_id": cat.category_id,
"parent_category_id": cat.parent_category_id,
"name": cat.name,
"slug": cat.slug,
"description": cat.description,
"image_url": cat.image_url,
"sort_order": cat.sort_order,
"sort_order": cat.sort_order or "0",
"is_parent_feature": getattr(cat, "is_parent_feature", False),
"is_active": cat.is_active,
"product_count": count_map.get(cat.category_id, 0),
"sub_categories": [],
"created_at": cat.created_at,
}
res.append(data)
# Nest sub-categories under their parents
for cat in categories:
if cat.parent_category_id and cat.parent_category_id in cat_lookup:
cat_lookup[cat.parent_category_id]["sub_categories"].append(cat_lookup[cat.category_id])
# Aggregate product counts recursively from children to parents
for cat in categories:
if not cat.parent_category_id:
parent_item = cat_lookup[cat.category_id]
children_sum = sum(child["product_count"] for child in parent_item["sub_categories"])
parent_item["product_count"] = parent_item["product_count"] + children_sum
if root_only:
res = [item for item in cat_lookup.values() if not item["parent_category_id"]]
else:
res = list(cat_lookup.values())
if has_products:
res = [item for item in res if item["product_count"] > 0]
return res
@router.get("/categories/tree", response_model=List[CategoryResponse])
def get_categories_tree(has_products: bool = Query(False), db: Session = Depends(get_db)):
return get_all_categories(has_products=has_products, root_only=True, db=db)
@router.post("/categories/create", response_model=CategoryResponse, status_code=status.HTTP_201_CREATED)
def create_category(data: CategoryCreate, db: Session = Depends(get_db), current_user: User = Depends(RoleChecker(["Super Admin", "Admin"]))):
slug = slugify(data.name)

View file

@ -47,20 +47,23 @@ class CategoryUpdate(BaseModel):
class CategoryResponse(BaseModel):
category_id: str
parent_category_id: Optional[str]
parent_category_id: Optional[str] = None
name: str
slug: str
description: Optional[str]
image_url: Optional[str]
sort_order: str
description: Optional[str] = None
image_url: Optional[str] = None
sort_order: Optional[str] = "0"
is_parent_feature: bool = False
is_active: bool
is_active: bool = True
product_count: Optional[int] = 0
sub_categories: Optional[List['CategoryResponse']] = None
created_at: Optional[datetime] = None
class Config:
from_attributes = True
CategoryResponse.model_rebuild()
# --- Category Parent Hierarchy (nested response) ---
class HierarchyModelItem(BaseModel):
model_id: str