This repository has been archived on 2026-02-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
glue/services/cart_adoption.py
2026-02-18 20:46:41 +00:00

51 lines
1.6 KiB
Python

"""Glue service: adopt anonymous cart items + calendar entries for a logged-in user."""
from __future__ import annotations
from sqlalchemy import select, update, func
from sqlalchemy.ext.asyncio import AsyncSession
from shared.models.market import CartItem
from shared.models.calendars import CalendarEntry
async def adopt_session_for_user(
session: AsyncSession,
user_id: int,
session_id: str,
) -> None:
"""Adopt anonymous cart items + calendar entries for a logged-in user."""
# --- adopt cart items ---
anon_result = await session.execute(
select(CartItem).where(
CartItem.deleted_at.is_(None),
CartItem.user_id.is_(None),
CartItem.session_id == session_id,
)
)
anon_items = anon_result.scalars().all()
if anon_items:
# Soft-delete existing user cart
await session.execute(
update(CartItem)
.where(CartItem.deleted_at.is_(None), CartItem.user_id == user_id)
.values(deleted_at=func.now())
)
for ci in anon_items:
ci.user_id = user_id
# --- adopt calendar entries ---
await session.execute(
update(CalendarEntry)
.where(CalendarEntry.deleted_at.is_(None), CalendarEntry.user_id == user_id)
.values(deleted_at=func.now())
)
cal_result = await session.execute(
select(CalendarEntry).where(
CalendarEntry.deleted_at.is_(None),
CalendarEntry.session_id == session_id,
)
)
for entry in cal_result.scalars().all():
entry.user_id = user_id