From 28938e38b5b869700cd71bff9599a49efa07b6fd Mon Sep 17 00:00:00 2001 From: giles Date: Sun, 15 Feb 2026 10:39:43 +0000 Subject: [PATCH] Fix cart count: query DB directly instead of cross-app API Two bugs fixed: 1. First htmx add didn't update mini cart count because the context processor's API call couldn't see the uncommitted transaction. Fix: pass cart_count/cart_total explicitly from the route handler. 2. Page refresh always showed cart count 0 because the internal API call to the cart service failed to resolve cart identity correctly. Fix: replace the API call with a direct DB query using the same shared database and session, matching how the cart app itself works. Co-Authored-By: Claude Opus 4.6 --- app.py | 30 +++++++++++++++++++++--------- bp/product/routes.py | 2 ++ 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/app.py b/app.py index 3a5f639..a0bfba2 100644 --- a/app.py +++ b/app.py @@ -18,24 +18,36 @@ async def market_context() -> dict: Market app context processor. - menu_items: direct DB query via glue layer - - cart_count/cart_total: fetched from cart internal API + - cart_count/cart_total: direct DB query (same shared DB) """ from shared.infrastructure.context import base_context from glue.services.navigation import get_navigation_tree - from shared.infrastructure.internal_api import get as api_get + from shared.infrastructure.cart_identity import current_cart_identity + from models.market import CartItem + from sqlalchemy.orm import selectinload ctx = await base_context() ctx["menu_items"] = await get_navigation_tree(g.s) - # Cart data from cart API - cart_data = await api_get("cart", "/internal/cart/summary", forward_session=True) - if cart_data: - ctx["cart_count"] = cart_data.get("count", 0) - ctx["cart_total"] = cart_data.get("total", 0) + # Cart data: query shared DB directly (avoids stale cross-app API responses) + ident = current_cart_identity() + cart_filters = [CartItem.deleted_at.is_(None)] + if ident["user_id"] is not None: + cart_filters.append(CartItem.user_id == ident["user_id"]) else: - ctx["cart_count"] = 0 - ctx["cart_total"] = 0 + cart_filters.append(CartItem.session_id == ident["session_id"]) + + cart_result = await g.s.execute( + select(CartItem) + .where(*cart_filters) + .options(selectinload(CartItem.product)) + ) + cart_items = cart_result.scalars().all() + + from bp.cart.services import total + ctx["cart_count"] = sum(ci.quantity for ci in cart_items) + ctx["cart_total"] = total(cart_items) or 0 return ctx diff --git a/bp/product/routes.py b/bp/product/routes.py index 4926173..9a51042 100644 --- a/bp/product/routes.py +++ b/bp/product/routes.py @@ -251,6 +251,8 @@ def register(): cart=g.cart, item=ci, total=total, + cart_count=sum(i.quantity for i in g.cart), + cart_total=total(g.cart), calendar_total=lambda entries: 0, calendar_cart_entries=[], )