fix(catalog): strictly guarantee only products with verified images on disk in related_products

This commit is contained in:
iFixKart Dev 2026-11-17 16:14:00 +05:30
parent bb1c4a3c9d
commit 1754f42878

View file

@ -1135,6 +1135,18 @@ def get_product_detail_by_slug(slug: str, db: Session = Depends(get_db)):
]
# Find related products prioritizing same brand and products with verified images on disk
def _is_image_verified(p):
if not p.images:
return False
for pi in p.images:
if pi.image_url:
rel = pi.image_url.lstrip('/')
if pi.image_url.startswith('http://') or pi.image_url.startswith('https://'):
return True
if os.path.exists(os.path.join(os.getcwd(), rel)) or os.path.exists(os.path.join('/var/www/fastapi/ifixkart', rel)):
return True
return False
related_stmt = (
select(Product)
.options(
@ -1143,31 +1155,39 @@ def get_product_detail_by_slug(slug: str, db: Session = Depends(get_db)):
selectinload(Product.images),
selectinload(Product.brand),
)
.where(Product.category_id == product.category_id, Product.product_id != product.product_id)
.where(Product.category_id == product.category_id, Product.product_id != product.product_id, Product.is_active == True)
)
if product.brand_id:
related_stmt = related_stmt.order_by((Product.brand_id == product.brand_id).desc(), Product.created_at.desc())
else:
related_stmt = related_stmt.order_by(Product.created_at.desc())
candidates = db.execute(related_stmt.limit(20)).scalars().all()
with_valid_img = []
without_img = []
for cp in candidates:
has_file = False
if cp.images:
for pi in cp.images:
if pi.image_url:
rel = pi.image_url.strip('/')
if not rel.startswith('uploads/') or os.path.exists(os.path.join(os.getcwd(), rel)):
has_file = True
break
if has_file:
with_valid_img.append(cp)
else:
without_img.append(cp)
candidates = db.execute(related_stmt.limit(50)).scalars().all()
with_valid_img = [cp for cp in candidates if _is_image_verified(cp)]
related = (with_valid_img + without_img)[:5]
# If category has fewer than 5 valid products, backfill from other active products with verified images
if len(with_valid_img) < 5:
existing_ids = {product.product_id}.union({p.product_id for p in with_valid_img})
backfill_stmt = (
select(Product)
.options(
selectinload(Product.variants).selectinload(ProductVariant.attributes),
selectinload(Product.variants).selectinload(ProductVariant.images),
selectinload(Product.images),
selectinload(Product.brand),
)
.where(Product.product_id.notin_(existing_ids), Product.is_active == True)
.order_by(Product.created_at.desc())
.limit(30)
)
backfill_candidates = db.execute(backfill_stmt).scalars().all()
for bp in backfill_candidates:
if _is_image_verified(bp):
with_valid_img.append(bp)
if len(with_valid_img) >= 5:
break
related = with_valid_img[:5]
related_serialized = [product_response_with_stock(p, db).model_dump(mode="json") for p in related]
compatibles = []