feat: handle unsubscribe
This commit is contained in:
@@ -26,6 +26,7 @@ from .placement.get_placement import get_placement
|
||||
from .placement.get_placements import get_placements
|
||||
from .placement.update_placement import update_placement
|
||||
from .subscription.handle_subscription import handle_subscription
|
||||
from .subscription.handle_unsubscription import handle_unsubscription
|
||||
from .target_channel.connect_target_chan import connect_target_chan
|
||||
from .target_channel.disconnect_target_chan import disconnect_target_chan
|
||||
from .target_channel.disconnect_target_chan_by_tg_id import disconnect_target_chan_by_tg_id
|
||||
@@ -131,6 +132,16 @@ class Database(typing.Protocol):
|
||||
self, subscriber_id: UUID, placement_id: UUID
|
||||
) -> domain.Subscription | None: ...
|
||||
|
||||
async def update_subscription(self, subscription: domain.Subscription) -> domain.Subscription: ...
|
||||
|
||||
async def get_active_subscriptions_by_subscriber_and_channel(
|
||||
self, subscriber_id: UUID, channel_telegram_id: int
|
||||
) -> list[domain.Subscription]: ...
|
||||
|
||||
async def get_active_subscription_by_subscriber_and_channel(
|
||||
self, subscriber_id: UUID, channel_telegram_id: int
|
||||
) -> domain.Subscription | None: ...
|
||||
|
||||
async def create_placement_views_history(
|
||||
self, history: domain.PlacementViewsHistory
|
||||
) -> domain.PlacementViewsHistory: ...
|
||||
@@ -195,6 +206,7 @@ class Usecase:
|
||||
update_placement = update_placement
|
||||
delete_placement = delete_placement
|
||||
handle_subscription = handle_subscription
|
||||
handle_unsubscription = handle_unsubscription
|
||||
fetch_views = fetch_views_manually
|
||||
run_views_worker_cycle = run_views_worker_cycle
|
||||
get_views_history = get_views_history
|
||||
|
||||
@@ -19,4 +19,3 @@ async def get_me(self: 'Usecase', user_id: uuid.UUID) -> dto.UserOutput:
|
||||
telegram_id=user.telegram_id,
|
||||
username=user.username,
|
||||
)
|
||||
|
||||
|
||||
@@ -17,20 +17,12 @@ async def handle_subscription(
|
||||
first_name: str | None = None,
|
||||
last_name: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Обрабатывает подписку пользователя в целевой канал.
|
||||
|
||||
Находит закуп по invite_link и создаёт запись о подписке,
|
||||
инкрементируя счётчик подписок у закупа.
|
||||
"""
|
||||
async with self.database.transaction():
|
||||
# Находим закуп по пригласительной ссылке
|
||||
placement = await self.database.get_placement_by_invite_link(invite_link)
|
||||
if not placement:
|
||||
log.warning('Placement not found for invite_link: %s', invite_link)
|
||||
return
|
||||
|
||||
# Создаём или обновляем подписчика
|
||||
subscriber = domain.Subscriber(
|
||||
telegram_id=user_telegram_id,
|
||||
username=username,
|
||||
@@ -39,27 +31,53 @@ async def handle_subscription(
|
||||
)
|
||||
subscriber = await self.database.upsert_subscriber(subscriber)
|
||||
|
||||
# Проверяем, не создана ли уже подписка для этого пользователя
|
||||
existing_subscription = await self.database.get_subscription_by_subscriber_and_placement(
|
||||
subscriber.id, placement.id
|
||||
active_subscription = await self.database.get_active_subscription_by_subscriber_and_channel(
|
||||
subscriber.id, placement.target_channel.telegram_id
|
||||
)
|
||||
if existing_subscription:
|
||||
log.info(
|
||||
'Subscription already exists for subscriber %s and placement %s',
|
||||
|
||||
if active_subscription:
|
||||
# Пользователь уже подписан на канал через другой placement
|
||||
# Это не должно случиться (Telegram не даст подписаться дважды),
|
||||
# но если случилось - логируем и игнорируем
|
||||
log.warning(
|
||||
'User %s (telegram_id: %s) already has active subscription to channel %s via placement %s, '
|
||||
'ignoring new subscription attempt via placement %s',
|
||||
subscriber.id,
|
||||
user_telegram_id,
|
||||
placement.target_channel_id,
|
||||
active_subscription.placement_id,
|
||||
placement.id,
|
||||
)
|
||||
return
|
||||
|
||||
# Проверяем, была ли раньше подписка через ЭТОТ placement (для реактивации)
|
||||
existing_sub = await self.database.get_subscription_by_subscriber_and_placement(subscriber.id, placement.id)
|
||||
|
||||
if existing_sub and existing_sub.status == domain.SubscriptionStatus.UNSUBSCRIBED:
|
||||
# Реактивируем старую подписку через тот же placement
|
||||
existing_sub.status = domain.SubscriptionStatus.ACTIVE
|
||||
existing_sub.unsubscribed_at = None
|
||||
await self.database.update_subscription(existing_sub)
|
||||
|
||||
placement.subscriptions_count += 1
|
||||
await self.database.update_placement(placement)
|
||||
|
||||
log.info(
|
||||
'Subscription reactivated: subscriber %s (telegram_id: %s) resubscribed via same placement %s',
|
||||
subscriber.id,
|
||||
user_telegram_id,
|
||||
placement.id,
|
||||
)
|
||||
return
|
||||
|
||||
# Создаём запись о подписке
|
||||
subscription = domain.Subscription(
|
||||
placement_id=placement.id,
|
||||
subscriber_id=subscriber.id,
|
||||
target_channel_id=placement.target_channel_id,
|
||||
invite_link=invite_link,
|
||||
)
|
||||
await self.database.create_subscription(subscription)
|
||||
|
||||
# Увеличиваем счётчик подписок у закупа
|
||||
placement.subscriptions_count += 1
|
||||
await self.database.update_placement(placement)
|
||||
|
||||
|
||||
49
src/usecase/subscription/handle_unsubscription.py
Normal file
49
src/usecase/subscription/handle_unsubscription.py
Normal file
@@ -0,0 +1,49 @@
|
||||
import datetime
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from src import domain
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .. import Usecase
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def handle_unsubscription(self: 'Usecase', user_telegram_id: int, channel_telegram_id: int) -> None:
|
||||
async with self.database.transaction():
|
||||
subscriber = await self.database.get_subscriber(user_telegram_id)
|
||||
if not subscriber:
|
||||
log.warning('Subscriber not found for telegram_id: %s', user_telegram_id)
|
||||
return
|
||||
|
||||
subscriptions = await self.database.get_active_subscriptions_by_subscriber_and_channel(
|
||||
subscriber.id, channel_telegram_id
|
||||
)
|
||||
|
||||
if not subscriptions:
|
||||
log.info(
|
||||
'No active subscriptions found for subscriber %s (telegram_id: %s) in channel %s',
|
||||
subscriber.id,
|
||||
user_telegram_id,
|
||||
channel_telegram_id,
|
||||
)
|
||||
return
|
||||
|
||||
for subscription in subscriptions:
|
||||
subscription.status = domain.SubscriptionStatus.UNSUBSCRIBED
|
||||
subscription.unsubscribed_at = datetime.datetime.now(datetime.UTC)
|
||||
await self.database.update_subscription(subscription)
|
||||
|
||||
# Декрементируем счётчик подписок у закупа
|
||||
placement = subscription.placement
|
||||
if placement.subscriptions_count > 0:
|
||||
placement.subscriptions_count -= 1
|
||||
await self.database.update_placement(placement)
|
||||
|
||||
log.info(
|
||||
'Subscription marked as unsubscribed: subscriber %s (telegram_id: %s) unsubscribed from placement %s',
|
||||
subscriber.id,
|
||||
user_telegram_id,
|
||||
placement.id,
|
||||
)
|
||||
@@ -14,9 +14,7 @@ if TYPE_CHECKING:
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def _process_placement(
|
||||
self: 'Usecase', placement_id: uuid.UUID, user_id: uuid.UUID, ad_post_url: str
|
||||
) -> None:
|
||||
async def _process_placement(self: 'Usecase', placement_id: uuid.UUID, user_id: uuid.UUID, ad_post_url: str) -> None:
|
||||
views_count = await self.telegram_parser.get_post_views(ad_post_url)
|
||||
fetched_at = datetime.datetime.now(datetime.UTC)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user