подписки сразу отслеживаются
This commit is contained in:
@@ -21,7 +21,7 @@ async def get_views_history(
|
||||
to_date: datetime.datetime | None = None,
|
||||
) -> Page[dto.PostViewsHistoryOutput]:
|
||||
input_data = dto.GetViewsHistoryInput(
|
||||
placement_post_id=placement_id,
|
||||
placement_id=placement_id,
|
||||
user_id=current_user.user_id,
|
||||
workspace_id=workspace_id,
|
||||
from_date=from_date,
|
||||
|
||||
@@ -7,7 +7,7 @@ from tortoise import fields
|
||||
from .base import TimestampedModel
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .placement_post import PlacementPost
|
||||
from .placement import Placement
|
||||
from .telegram_user import TelegramUser
|
||||
|
||||
|
||||
@@ -21,17 +21,17 @@ class Subscription(TimestampedModel):
|
||||
status = fields.CharEnumField(SubscriptionStatus, default=SubscriptionStatus.ACTIVE)
|
||||
unsubscribed_at = fields.DatetimeField(null=True)
|
||||
|
||||
placement_post: fields.ForeignKeyRelation['PlacementPost'] = fields.ForeignKeyField(
|
||||
'models.PlacementPost', related_name='subscriptions', on_delete=fields.CASCADE, index=True
|
||||
placement: fields.ForeignKeyRelation['Placement'] = fields.ForeignKeyField(
|
||||
'models.Placement', related_name='subscriptions', on_delete=fields.CASCADE, index=True
|
||||
)
|
||||
telegram_user: fields.ForeignKeyRelation['TelegramUser'] = fields.ForeignKeyField(
|
||||
'models.TelegramUser', related_name='subscriptions', on_delete=fields.CASCADE, index=True
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
placement_post_id: UUID
|
||||
placement_id: UUID
|
||||
telegram_user_id: UUID
|
||||
|
||||
class Meta:
|
||||
table = 'subscription'
|
||||
unique_together = (('placement_post_id', 'telegram_user_id'),)
|
||||
unique_together = (('placement_id', 'telegram_user_id'),)
|
||||
|
||||
@@ -15,9 +15,9 @@ class PostViewsHistoryOutput(pydantic.BaseModel):
|
||||
|
||||
|
||||
class GetViewsHistoryInput(pydantic.BaseModel):
|
||||
"""Получить историю просмотров для публикации."""
|
||||
"""Получить историю просмотров для placement."""
|
||||
|
||||
placement_post_id: uuid.UUID
|
||||
placement_id: uuid.UUID
|
||||
user_id: uuid.UUID
|
||||
workspace_id: uuid.UUID
|
||||
from_date: datetime.datetime | None = None # Фильтр: с какой даты
|
||||
|
||||
@@ -74,8 +74,8 @@ async def get_placement_user(self: 'Usecase', input: dto.GetPlacementInput) -> d
|
||||
placement_id=placement.id,
|
||||
include_archived=True,
|
||||
)
|
||||
placement_post_ids = [post.id for post in placement_posts]
|
||||
subscriptions_counts = await self.database.count_subscriptions_by_placement_post_batch(placement_post_ids)
|
||||
# Подсчёт подписок по placement_id (один Placement = одна ссылка = один счётчик подписок)
|
||||
subscriptions_count = await self.database.count_subscriptions_by_placement(placement.id)
|
||||
post_ids = [placement_post.post.id for placement_post in placement_posts if placement_post.post]
|
||||
views_map = await self.database.get_latest_views_data_batch(post_ids) if post_ids else {}
|
||||
|
||||
@@ -89,7 +89,7 @@ async def get_placement_user(self: 'Usecase', input: dto.GetPlacementInput) -> d
|
||||
views_count = views_map.get(placement_post.post.id, (None,))[0]
|
||||
placement_post_output = _build_placement_post_output(
|
||||
placement_post,
|
||||
subscriptions_counts.get(placement_post.id, 0),
|
||||
subscriptions_count,
|
||||
views_count,
|
||||
)
|
||||
if placement_post_output is not None:
|
||||
|
||||
@@ -34,8 +34,8 @@ async def get_placements(self: 'Usecase', input: dto.GetPlacementsInput) -> dto.
|
||||
placement_ids,
|
||||
include_archived=True,
|
||||
)
|
||||
placement_post_ids = [post.id for post in placement_posts]
|
||||
subscriptions_counts = await self.database.count_subscriptions_by_placement_post_batch(placement_post_ids)
|
||||
# Подсчёт подписок по placement_id (один Placement = одна ссылка = один счётчик подписок)
|
||||
subscriptions_counts = await self.database.count_subscriptions_by_placement_batch(placement_ids)
|
||||
post_ids = [placement_post.post.id for placement_post in placement_posts if placement_post.post]
|
||||
views_map = await self.database.get_latest_views_data_batch(post_ids) if post_ids else {}
|
||||
|
||||
@@ -46,7 +46,7 @@ async def get_placements(self: 'Usecase', input: dto.GetPlacementsInput) -> dto.
|
||||
views_count = views_map.get(placement_post.post.id, (None,))[0]
|
||||
placement_post_output = _build_placement_post_output(
|
||||
placement_post,
|
||||
subscriptions_counts.get(placement_post.id, 0),
|
||||
subscriptions_counts.get(placement_post.placement_id, 0),
|
||||
views_count,
|
||||
)
|
||||
if placement_post_output is None:
|
||||
|
||||
@@ -17,13 +17,9 @@ async def handle_subscription(
|
||||
first_name: str | None = None,
|
||||
last_name: str | None = None,
|
||||
) -> None:
|
||||
placement_post = await self.database.get_placement_post_by_invite_link(invite_link)
|
||||
if not placement_post:
|
||||
log.warning('PlacementPost not found for invite_link: %s', invite_link)
|
||||
return
|
||||
|
||||
if not placement_post.placement:
|
||||
log.error('PlacementPost %s has no placement', placement_post.id)
|
||||
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 = await self.database.get_telegram_user(telegram_id=user_telegram_id)
|
||||
@@ -42,27 +38,27 @@ async def handle_subscription(
|
||||
await self.database.update_telegram_user(subscriber)
|
||||
|
||||
active_subscription = await self.database.get_active_subscription_by_subscriber_and_project(
|
||||
subscriber.id, placement_post.placement.project_id
|
||||
subscriber.id, placement.project_id
|
||||
)
|
||||
|
||||
if active_subscription:
|
||||
# Пользователь уже подписан на канал через другую публикацию
|
||||
# Пользователь уже подписан на канал через другой placement
|
||||
# Это не должно случиться (Telegram не даст подписаться дважды),
|
||||
# но если случилось - логируем и игнорируем
|
||||
log.warning(
|
||||
'User %s (telegram_id: %s) already has active subscription to channel %s via placement_post %s, '
|
||||
'ignoring new subscription attempt via placement_post %s',
|
||||
'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_post.placement.project_id,
|
||||
active_subscription.placement_post_id,
|
||||
placement_post.id,
|
||||
placement.project_id,
|
||||
active_subscription.placement_id,
|
||||
placement.id,
|
||||
)
|
||||
return
|
||||
|
||||
# Проверяем, была ли раньше подписка через ЭТУ публикацию (для реактивации)
|
||||
existing_sub = await self.database.get_subscription_by_subscriber_and_placement_post(
|
||||
subscriber.id, placement_post.id
|
||||
# Проверяем, была ли раньше подписка через ЭТОТ 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:
|
||||
@@ -71,24 +67,24 @@ async def handle_subscription(
|
||||
await self.database.update_subscription(existing_sub)
|
||||
|
||||
log.info(
|
||||
'Subscription reactivated: subscriber %s (telegram_id: %s) resubscribed via same placement_post %s',
|
||||
'Subscription reactivated: subscriber %s (telegram_id: %s) resubscribed via same placement %s',
|
||||
subscriber.id,
|
||||
user_telegram_id,
|
||||
placement_post.id,
|
||||
placement.id,
|
||||
)
|
||||
return
|
||||
|
||||
subscription = domain.Subscription(
|
||||
placement_post_id=placement_post.id,
|
||||
placement_id=placement.id,
|
||||
telegram_user_id=subscriber.id,
|
||||
invite_link=invite_link,
|
||||
)
|
||||
await self.database.create_subscription(subscription)
|
||||
|
||||
log.info(
|
||||
'Subscription created: subscriber %s (telegram_id: %s) subscribed via placement_post %s (invite_link: %s)',
|
||||
'Subscription created: subscriber %s (telegram_id: %s) subscribed via placement %s (invite_link: %s)',
|
||||
subscriber.id,
|
||||
user_telegram_id,
|
||||
placement_post.id,
|
||||
placement.id,
|
||||
invite_link,
|
||||
)
|
||||
|
||||
@@ -39,8 +39,8 @@ async def handle_unsubscription(self: 'Usecase', user_telegram_id: int, channel_
|
||||
await self.database.update_subscription(subscription)
|
||||
|
||||
log.info(
|
||||
'Subscription marked as unsubscribed: subscriber %s (telegram_id: %s) unsubscribed from placement_post %s',
|
||||
'Subscription marked as unsubscribed: subscriber %s (telegram_id: %s) unsubscribed from placement %s',
|
||||
subscriber.id,
|
||||
user_telegram_id,
|
||||
subscription.placement_post_id,
|
||||
subscription.placement_id,
|
||||
)
|
||||
|
||||
@@ -14,18 +14,31 @@ async def get_views_history(self: 'Usecase', input: dto.GetViewsHistoryInput) ->
|
||||
input.workspace_id, input.user_id, domain.PermissionKey.PLACEMENTS_READ
|
||||
)
|
||||
|
||||
placement_post = await self.database.get_placement_post(input.workspace_id, input.placement_post_id)
|
||||
if not placement_post:
|
||||
log.warning('PlacementPost %s not found for user %s', input.placement_post_id, input.user_id)
|
||||
raise domain.PlacementPostNotFound(input.placement_post_id)
|
||||
placement = await self.database.get_placement(input.workspace_id, input.placement_id)
|
||||
if not placement:
|
||||
log.warning('Placement %s not found for user %s', input.placement_id, input.user_id)
|
||||
raise domain.PlacementNotFound(input.placement_id)
|
||||
|
||||
if not placement_post.placement:
|
||||
log.error('PlacementPost %s has no placement', placement_post.id)
|
||||
raise domain.PlacementNotFound(placement_post.placement_id)
|
||||
context.ensure_project_permission(domain.PermissionKey.PLACEMENTS_READ, placement.project_id)
|
||||
|
||||
context.ensure_project_permission(domain.PermissionKey.PLACEMENTS_READ, placement_post.placement.project_id)
|
||||
# Получаем PlacementPost для этого Placement (для получения связанного Post)
|
||||
placement_posts = await self.database.get_workspace_placement_posts(
|
||||
input.workspace_id,
|
||||
placement_id=placement.id,
|
||||
include_archived=True,
|
||||
)
|
||||
|
||||
if not placement_post.post:
|
||||
if not placement_posts:
|
||||
return []
|
||||
|
||||
# Берём первый PlacementPost с постом
|
||||
placement_post = None
|
||||
for pp in placement_posts:
|
||||
if pp.post:
|
||||
placement_post = pp
|
||||
break
|
||||
|
||||
if not placement_post or not placement_post.post:
|
||||
return []
|
||||
|
||||
histories = await self.database.get_views_history(
|
||||
|
||||
Reference in New Issue
Block a user