Phase 1-3 of decoupling: - path_setup.py adds project root to sys.path - Cart-owned models in cart/models/ (order, page_config) - All imports updated: shared.infrastructure, shared.db, shared.browser, etc. - PageConfig uses container_type/container_id instead of post_id FK Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
47 lines
1.3 KiB
Python
47 lines
1.3 KiB
Python
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
|