refactor: centralize product cache invalidation logic in _invalidate_product_cache function
This commit is contained in:
+13
-4
@@ -37,6 +37,13 @@ STOCK_RESERVATION_SESSION_KEY = "stock_reservation_id"
|
||||
STOCK_RESERVATION_PAYMENT_SESSION_KEY = "stock_reservation_payment_method"
|
||||
|
||||
|
||||
def _invalidate_product_cache(product_ids):
|
||||
unique_product_ids = {product_id for product_id in product_ids if product_id is not None}
|
||||
if not unique_product_ids:
|
||||
return
|
||||
cache.delete_many([f"product_{product_id}" for product_id in unique_product_ids])
|
||||
|
||||
|
||||
def _normalize_location_text(value: str) -> str:
|
||||
normalized = unicodedata.normalize("NFD", (value or ""))
|
||||
without_accents = "".join(char for char in normalized if unicodedata.category(char) != "Mn")
|
||||
@@ -442,7 +449,7 @@ def _create_stock_reservation_for_cart(request: HttpRequest, cart_items, payment
|
||||
for item in cart_items
|
||||
])
|
||||
|
||||
cache.delete_many([f"product_{product_id}" for product_id in product_ids])
|
||||
_invalidate_product_cache(product_ids)
|
||||
|
||||
return reservation, []
|
||||
|
||||
@@ -594,7 +601,8 @@ def create_order_from_cart(request, payment_method, payment_reference="", shippi
|
||||
product_row = product_map.get(item.product_id)
|
||||
product_row.stock -= item.quantity
|
||||
product_row.save(update_fields=["stock"])
|
||||
cache.delete(f"product_{product_row.id}")
|
||||
|
||||
_invalidate_product_cache(product_ids)
|
||||
|
||||
cart.items.all().delete()
|
||||
|
||||
@@ -880,6 +888,7 @@ def crear_producto(request: HttpRequest):
|
||||
primary_image=primary_image,
|
||||
creator=request.user
|
||||
)
|
||||
_invalidate_product_cache([producto.id])
|
||||
|
||||
# Agregar imágenes secundarias si se proporcionan
|
||||
if secondary_images_files:
|
||||
@@ -970,7 +979,7 @@ def editar_producto(request: HttpRequest, id: int):
|
||||
producto.primary_image = primary_image
|
||||
|
||||
producto.save()
|
||||
cache.delete(f"product_{producto.id}")
|
||||
_invalidate_product_cache([producto.id])
|
||||
|
||||
if secondary_images_files:
|
||||
producto.secondary_images.clear()
|
||||
@@ -1000,7 +1009,7 @@ def borrar_producto(request: HttpRequest, id: int):
|
||||
|
||||
producto = get_object_or_404(Product, id=id, creator=request.user)
|
||||
nombre = producto.name
|
||||
cache.delete(f"product_{producto.id}")
|
||||
_invalidate_product_cache([producto.id])
|
||||
producto.delete()
|
||||
messages.success(request, f"Producto '{nombre}' eliminado correctamente.")
|
||||
return redirect("mis_productos")
|
||||
|
||||
Reference in New Issue
Block a user