34 lines
1.5 KiB
Python
34 lines
1.5 KiB
Python
# utils/subscribe.py
|
|
from sqlalchemy import delete, select
|
|
from utils.db.regions import Region
|
|
from utils.db import AsyncSessionLocal, Subscription
|
|
|
|
|
|
async def handle_subscribe(user_id, region_ids):
|
|
async with AsyncSessionLocal() as session:
|
|
async with session.begin():
|
|
# Пример: удаляем старые подписки и добавляем новые
|
|
await session.execute(delete(Subscription).where(Subscription.user_id == user_id))
|
|
new_subscriptions = [Subscription(user_id=user_id, region_id=region_id) for region_id in region_ids]
|
|
session.add_all(new_subscriptions)
|
|
await session.commit()
|
|
|
|
async def handle_unsubscribe(user_id):
|
|
async with AsyncSessionLocal() as session:
|
|
async with session.begin():
|
|
# Удаление всех подписок пользователя
|
|
await session.execute(delete(Subscription).where(Subscription.user_id == user_id))
|
|
await session.commit()
|
|
|
|
|
|
async def get_user_subscriptions(user_id):
|
|
async with AsyncSessionLocal() as session:
|
|
async with session.begin():
|
|
result = await session.execute(
|
|
select(Subscription.region_id, Region.region_name)
|
|
.join(Region, Subscription.region_id == Region.region_id)
|
|
.where(Subscription.user_id == user_id, Subscription.active == True)
|
|
)
|
|
subscriptions = result.fetchall()
|
|
return subscriptions
|