hisham-cmd commited on
Commit
12c6b0e
·
verified ·
1 Parent(s): dab14ee

Upload verify_filter.py

Browse files
Files changed (1) hide show
  1. verify_filter.py +49 -0
verify_filter.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.db.base import SessionLocal
2
+ from app.models.product import Category, Product
3
+ from app.schemas.product import CategoryResponse
4
+
5
+ def test_filtering():
6
+ db = SessionLocal()
7
+ try:
8
+ # 1. Fetch all categories
9
+ all_categories = db.query(Category).all()
10
+
11
+ # 2. Identify category IDs that have at least one active product
12
+ active_product_cat_ids = {
13
+ row[0] for row in db.query(Product.category_id)
14
+ .filter(Product.is_active == True)
15
+ .distinct()
16
+ .all()
17
+ if row[0] is not None
18
+ }
19
+
20
+ # 3. Determine visibility: a category is visible if it has products
21
+ # OR if any of its descendants have products.
22
+ visible_ids = set()
23
+
24
+ def mark_visible(cat_id: int):
25
+ if cat_id in visible_ids:
26
+ return
27
+ visible_ids.add(cat_id)
28
+ cat = next((c for c in all_categories if c.id == cat_id), None)
29
+ if cat and cat.parent_id:
30
+ mark_visible(cat.parent_id)
31
+
32
+ for cat_id in active_product_cat_ids:
33
+ mark_visible(cat_id)
34
+
35
+ print(f"Total Categories in DB: {len(all_categories)}")
36
+ print(f"Categories with Products: {len(active_product_cat_ids)}")
37
+ print(f"Total Visible Categories (including parents): {len(visible_ids)}")
38
+
39
+ filtered_categories = [c for c in all_categories if c.id in visible_ids]
40
+ filtered_categories.sort(key=lambda x: x.sort_order)
41
+
42
+ for c in filtered_categories:
43
+ print(f"- {c.name_en} (ID: {c.id}, Parent: {c.parent_id})")
44
+
45
+ finally:
46
+ db.close()
47
+
48
+ if __name__ == "__main__":
49
+ test_filtering()