from sqlalchemy import select, update, func from market.models.market import CartItem async def adopt_session_cart_for_user(session, user_id: int, session_id: str | None) -> None: """ When a user logs in or registers: - If there are cart items for this anonymous session, take them over. - Replace any existing cart items for this user with the anonymous cart. """ if not session_id: return # 1) Find anonymous cart items for this session result = await session.execute( select(CartItem) .where( CartItem.deleted_at.is_(None), CartItem.user_id.is_(None), CartItem.session_id == session_id, ) ) anon_items = result.scalars().all() if not anon_items: # nothing to adopt return # 2) Soft-delete any existing cart for this user await session.execute( update(CartItem) .where( CartItem.deleted_at.is_(None), CartItem.user_id == user_id, ) .values(deleted_at=func.now()) ) # 3) Reassign anonymous cart items to the user for ci in anon_items: ci.user_id = user_id # optional: you can keep the session_id as well, but user_id will take precedence # ci.session_id = session_id # No explicit commit here; caller's transaction will handle it