feat: subs and views

This commit is contained in:
Artem Tsyrulnikov
2025-11-10 17:08:56 +03:00
parent 2549242b06
commit 0bed5c266d
34 changed files with 1706 additions and 119 deletions

View File

@@ -299,3 +299,57 @@ class Postgres(DatabaseBase):
)
result = await self.session.execute(stmt)
return result.scalar_one_or_none() is not None
async def get_purchase_by_invite_link(self, invite_link: str) -> domain.Purchase | None:
stmt = (
select(domain.Purchase)
.options(
selectinload(domain.Purchase.target_channel),
selectinload(domain.Purchase.external_channel),
selectinload(domain.Purchase.creative),
)
.where(domain.Purchase.invite_link == invite_link)
)
result = await self.session.execute(stmt)
return result.scalar_one_or_none()
async def create_subscription(self, subscription: domain.Subscription) -> domain.Subscription:
self.session.add(subscription)
await self.session.flush()
await self.session.refresh(subscription, ['purchase'])
return subscription
async def get_subscription_by_user_and_purchase(
self, user_telegram_id: int, purchase_id: uuid.UUID
) -> domain.Subscription | None:
stmt = select(domain.Subscription).where(
domain.Subscription.user_telegram_id == user_telegram_id,
domain.Subscription.purchase_id == purchase_id,
)
result = await self.session.execute(stmt)
return result.scalar_one_or_none()
async def create_views_snapshot(self, snapshot: domain.ViewsSnapshot) -> domain.ViewsSnapshot:
self.session.add(snapshot)
await self.session.flush()
await self.session.refresh(snapshot, ['purchase'])
return snapshot
async def get_views_history(
self,
purchase_id: uuid.UUID,
*,
from_date: datetime.datetime | None = None,
to_date: datetime.datetime | None = None,
) -> list[domain.ViewsSnapshot]:
stmt = select(domain.ViewsSnapshot).where(domain.ViewsSnapshot.purchase_id == purchase_id)
if from_date:
stmt = stmt.where(domain.ViewsSnapshot.fetched_at >= from_date)
if to_date:
stmt = stmt.where(domain.ViewsSnapshot.fetched_at <= to_date)
stmt = stmt.order_by(domain.ViewsSnapshot.fetched_at.asc())
result = await self.session.execute(stmt)
return list(result.scalars().all())

View File

@@ -26,3 +26,34 @@ class Telegram(TelegramBase):
creates_join_request=requires_approval,
)
return invite_link.invite_link
async def get_post_views(self, post_url: str) -> int | None:
"""
Получить количество просмотров поста по URL.
ЗАГЛУШКА: В текущей реализации возвращает None.
Для реальной работы необходимо:
1. Интегрировать TDLib/MTProto клиент
2. Парсить post_url (формат: t.me/<username>/<message_id> или t.me/c/<chat_id>/<message_id>)
3. Вызывать channels.getMessages через TDLib
4. Извлекать поле views из ответа
Returns:
int | None: Количество просмотров или None если не удалось получить
"""
log.warning(
'get_post_views is not implemented yet (TDLib integration required). URL: %s',
post_url,
)
# TODO: Implement TDLib integration
# Example pseudo-code:
# try:
# username, message_id = parse_telegram_url(post_url)
# channel = await tdlib.resolve_username(username)
# message = await tdlib.get_message(channel.id, message_id)
# return message.views
# except Exception as e:
# log.error('Failed to get post views: %s', e)
# return None
return None

View File

@@ -5,6 +5,7 @@ from src.controller.http.creatives import creatives_router
from src.controller.http.external_channels import external_channels_router
from src.controller.http.purchases import purchases_router
from src.controller.http.target_channels import target_channels_router
from src.controller.http.views import views_router
api_router = APIRouter()
@@ -17,5 +18,6 @@ api_v1_router.include_router(target_channels_router)
api_v1_router.include_router(external_channels_router)
api_v1_router.include_router(creatives_router)
api_v1_router.include_router(purchases_router)
api_v1_router.include_router(views_router)
api_router.include_router(api_v1_router)

View File

@@ -0,0 +1,59 @@
import datetime
import uuid
from typing import Annotated
from fastapi import Depends
from fastapi.routing import APIRouter
from src import dependencies, dto
from src.adapter.jwt import JWTPayload
views_router = APIRouter(prefix='/purchases/{purchase_id}/views', tags=['views'])
@views_router.get('/history')
async def get_views_history(
purchase_id: uuid.UUID,
current_user: Annotated[JWTPayload, Depends(dependencies.get_current_user)],
from_date: datetime.datetime | None = None,
to_date: datetime.datetime | None = None,
) -> dto.GetViewsHistoryOutput:
"""Получить историю просмотров для закупа."""
input_data = dto.GetViewsHistoryInput(
purchase_id=purchase_id,
user_id=current_user.user_id,
from_date=from_date,
to_date=to_date,
)
return await dependencies.get_usecase().get_views_history(input=input_data)
@views_router.post('/fetch')
async def fetch_views(
purchase_id: uuid.UUID,
current_user: Annotated[JWTPayload, Depends(dependencies.get_current_user)],
) -> dto.FetchViewsOutput:
"""Получить актуальные просмотры через Telegram API."""
input_data = dto.FetchViewsInput(
purchase_id=purchase_id,
user_id=current_user.user_id,
)
return await dependencies.get_usecase().fetch_views(input=input_data)
@views_router.post('/manual')
async def update_views_manually(
purchase_id: uuid.UUID,
views_count: int,
current_user: Annotated[JWTPayload, Depends(dependencies.get_current_user)],
) -> dto.PurchaseOutput:
"""Обновить просмотры вручную."""
input_data = dto.UpdateViewsManuallyInput(
purchase_id=purchase_id,
user_id=current_user.user_id,
views_count=views_count,
)
return await dependencies.get_usecase().update_views_manually(input=input_data)

View File

@@ -3,4 +3,4 @@ from aiogram import Router
telegram_callback_router = Router()
# Import handlers to register them
from . import my_chat_member, start_with_login # noqa: E402, F401
from . import chat_join_request, chat_member_updated, my_chat_member, start_with_login # noqa: E402, F401

View File

@@ -0,0 +1,37 @@
import logging
from aiogram.types import ChatJoinRequest
from src import dependencies
from src.controller.telegram_callback import telegram_callback_router
log = logging.getLogger(__name__)
@telegram_callback_router.chat_join_request()
async def on_chat_join_request(event: ChatJoinRequest) -> None:
"""
Обрабатывает запросы на вступление в канал через приватную invite_link с одобрением.
Событие приходит когда пользователь отправляет запрос на вступление в канал.
"""
if event.chat.type not in {'channel', 'supergroup'}:
return
if not event.from_user:
log.error('Failed to get user data from chat join request')
return
# Получаем invite_link, по которой пользователь отправил запрос
invite_link = event.invite_link
if not invite_link or not invite_link.invite_link:
log.debug('No invite_link in chat join request event')
return
usecase = dependencies.get_usecase()
await usecase.handle_subscription(
user_telegram_id=event.from_user.id,
username=event.from_user.username,
invite_link=invite_link.invite_link,
)

View File

@@ -0,0 +1,48 @@
import logging
from aiogram.types import ChatMemberUpdated
from src import dependencies
from src.controller.telegram_callback import telegram_callback_router
log = logging.getLogger(__name__)
@telegram_callback_router.chat_member()
async def on_chat_member_updated(event: ChatMemberUpdated) -> None:
"""
Обрабатывает события подписки пользователей в канал через открытую invite_link.
Событие приходит когда пользователь вступает в канал напрямую (без запроса на вступление).
"""
if event.chat.type not in {'channel', 'supergroup'}:
return
if not event.from_user:
log.error('Failed to get user data from chat member update')
return
old_status = event.old_chat_member.status
new_status = event.new_chat_member.status
# Проверяем что пользователь присоединился к каналу
was_not_member = old_status in ('left', 'kicked')
is_now_member = new_status in ('member', 'administrator', 'creator')
user_joined = was_not_member and is_now_member
if not user_joined:
return
# Получаем invite_link, по которой пользователь присоединился
invite_link = event.invite_link
if not invite_link or not invite_link.invite_link:
log.debug('No invite_link in chat member update event')
return
usecase = dependencies.get_usecase()
await usecase.handle_subscription(
user_telegram_id=event.from_user.id,
username=event.from_user.username,
invite_link=invite_link.invite_link,
)

View File

@@ -5,10 +5,13 @@ __all__ = (
'ExternalChannel',
'Creative',
'Purchase',
'Subscription',
'ViewsSnapshot',
'TargetChannelStatus',
'CreativeStatus',
'PurchaseStatus',
'InviteLinkType',
'PostViewsAvailability',
'LoginToken',
'UserNotFound',
'LoginTokenNotFound',
@@ -42,6 +45,8 @@ from .error import (
)
from .external_channel import ExternalChannel
from .login_token import LoginToken
from .purchase import InviteLinkType, Purchase, PurchaseStatus
from .purchase import InviteLinkType, PostViewsAvailability, Purchase, PurchaseStatus
from .subscription import Subscription
from .target_channel import TargetChannel, TargetChannelStatus
from .user import User
from .views_snapshot import ViewsSnapshot

View File

@@ -24,6 +24,15 @@ class InviteLinkType(StrEnum):
APPROVAL = 'approval' # с одобрением ботом
class PostViewsAvailability(StrEnum):
"""Статус доступности получения просмотров поста."""
UNKNOWN = 'unknown' # Ещё не проверялось
AVAILABLE = 'available' # Просмотры доступны
UNAVAILABLE = 'unavailable' # Нет доступа / битая ссылка / приватный канал
MANUAL = 'manual' # Просмотры вводятся вручную
class Purchase(domain.Base):
# Основные поля
target_channel_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('targetchannels.id'), index=True)
@@ -44,7 +53,11 @@ class Purchase(domain.Base):
# Метрики (будут обновляться из Telegram API)
subscriptions_count: Mapped[int] = mapped_column(default=0, server_default='0')
views_count: Mapped[int | None] # просмотры рекламного поста (если доступны)
views_count: Mapped[int | None] # последние известные просмотры (кэш из последнего snapshot)
# Статус доступности просмотров
views_availability: Mapped[PostViewsAvailability] = mapped_column(default=PostViewsAvailability.UNKNOWN)
last_views_fetch_at: Mapped[datetime.datetime | None] # когда последний раз получали просмотры
# Relationships
target_channel: Mapped['TargetChannel'] = relationship()

View File

@@ -0,0 +1,22 @@
import uuid
from typing import TYPE_CHECKING
from sqlalchemy import BigInteger, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from src import domain
if TYPE_CHECKING:
from .purchase import Purchase
class Subscription(domain.Base):
"""Подписка пользователя в целевой канал через конкретный закуп."""
purchase_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('purchases.id'), index=True)
user_telegram_id: Mapped[int] = mapped_column(BigInteger, index=True)
username: Mapped[str | None]
invite_link: Mapped[str] = mapped_column(index=True) # По которой пришёл пользователь
# Relationship
purchase: Mapped['Purchase'] = relationship()

View File

@@ -0,0 +1,22 @@
import datetime
import uuid
from typing import TYPE_CHECKING
from sqlalchemy import ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from src import domain
if TYPE_CHECKING:
from .purchase import Purchase
class ViewsSnapshot(domain.Base):
"""Снимок просмотров рекламного поста в определенный момент времени."""
purchase_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('purchases.id'), index=True)
views_count: Mapped[int] # Количество просмотров на момент снимка
fetched_at: Mapped[datetime.datetime] = mapped_column(index=True) # Когда получены данные
# Relationship
purchase: Mapped['Purchase'] = relationship()

View File

@@ -34,6 +34,12 @@ __all__ = (
'UpdatePurchaseInput',
'ArchivePurchaseInput',
'DeletePurchaseInput',
'ViewsSnapshotOutput',
'GetViewsHistoryInput',
'GetViewsHistoryOutput',
'FetchViewsInput',
'FetchViewsOutput',
'UpdateViewsManuallyInput',
)
from .creative import (
@@ -78,3 +84,11 @@ from .target_channel import (
)
from .telegram_login import TelegramLoginInput
from .validate_login_token import ValidateLoginTokenInput, ValidateLoginTokenOutput
from .views import (
FetchViewsInput,
FetchViewsOutput,
GetViewsHistoryInput,
GetViewsHistoryOutput,
UpdateViewsManuallyInput,
ViewsSnapshotOutput,
)

View File

@@ -23,6 +23,8 @@ class PurchaseOutput(pydantic.BaseModel):
status: domain.PurchaseStatus
subscriptions_count: int
views_count: int | None
views_availability: domain.PostViewsAvailability
last_views_fetch_at: datetime.datetime | None
created_at: datetime.datetime

56
src/dto/views.py Normal file
View File

@@ -0,0 +1,56 @@
import datetime
import uuid
import pydantic
from src import domain
class ViewsSnapshotOutput(pydantic.BaseModel):
"""Снимок просмотров."""
id: uuid.UUID
purchase_id: uuid.UUID
views_count: int
fetched_at: datetime.datetime
created_at: datetime.datetime
class GetViewsHistoryInput(pydantic.BaseModel):
"""Получить историю просмотров для закупа."""
purchase_id: uuid.UUID
user_id: uuid.UUID
from_date: datetime.datetime | None = None # Фильтр: с какой даты
to_date: datetime.datetime | None = None # Фильтр: по какую дату
class GetViewsHistoryOutput(pydantic.BaseModel):
"""История просмотров."""
snapshots: list[ViewsSnapshotOutput]
class FetchViewsInput(pydantic.BaseModel):
"""Запросить обновление просмотров для закупа."""
purchase_id: uuid.UUID
user_id: uuid.UUID
class FetchViewsOutput(pydantic.BaseModel):
"""Результат получения просмотров."""
purchase_id: uuid.UUID
views_count: int | None # None если не удалось получить
views_availability: domain.PostViewsAvailability
fetched_at: datetime.datetime
error_message: str | None = None # Сообщение об ошибке если не удалось
class UpdateViewsManuallyInput(pydantic.BaseModel):
"""Ручное обновление просмотров."""
purchase_id: uuid.UUID
user_id: uuid.UUID
views_count: int

View File

@@ -22,6 +22,7 @@ from .purchase.delete_purchase import delete_purchase
from .purchase.get_purchase import get_purchase
from .purchase.get_purchases import get_purchases
from .purchase.update_purchase import update_purchase
from .subscription.handle_subscription import handle_subscription
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
@@ -29,6 +30,9 @@ from .target_channel.get_user_target_chans import get_user_target_chans
from .target_channel.update_target_chan_permissions import update_target_chan_permissions
from .telegram_login import telegram_login
from .validate_login_token import validate_login_token
from .views.fetch_views import fetch_views
from .views.get_views_history import get_views_history
from .views.update_views_manually import update_views_manually
class Database(typing.Protocol):
@@ -110,6 +114,24 @@ class Database(typing.Protocol):
async def check_creative_in_use(self, creative_id: UUID) -> bool: ...
async def get_purchase_by_invite_link(self, invite_link: str) -> domain.Purchase | None: ...
async def create_subscription(self, subscription: domain.Subscription) -> domain.Subscription: ...
async def get_subscription_by_user_and_purchase(
self, user_telegram_id: int, purchase_id: UUID
) -> domain.Subscription | None: ...
async def create_views_snapshot(self, snapshot: domain.ViewsSnapshot) -> domain.ViewsSnapshot: ...
async def get_views_history(
self,
purchase_id: UUID,
*,
from_date: datetime.datetime | None = None,
to_date: datetime.datetime | None = None,
) -> list[domain.ViewsSnapshot]: ...
class TelegramWriter(typing.Protocol):
async def send_message(self, text: str, chat_id: int) -> None: ...
@@ -120,6 +142,8 @@ class TelegramWriter(typing.Protocol):
async def create_chat_invite_link(self, chat_id: int, requires_approval: bool = False) -> str: ...
async def get_post_views(self, post_url: str) -> int | None: ... # None если не удалось получить
class JWTEncoder(typing.Protocol):
def encode_access_token(self, user_id: UUID, telegram_id: int, username: str | None = None) -> str: ...
@@ -155,3 +179,7 @@ class Usecase:
update_purchase = update_purchase
archive_purchase = archive_purchase
delete_purchase = delete_purchase
handle_subscription = handle_subscription
fetch_views = fetch_views
get_views_history = get_views_history
update_views_manually = update_views_manually

View File

@@ -20,13 +20,13 @@ async def archive_creative(self: 'Usecase', creative_id: uuid.UUID, user_id: uui
creative.status = domain.CreativeStatus.ARCHIVED
updated = await self.database.update_creative(creative)
return dto.CreativeOutput(
id=updated.id,
name=updated.name,
text=updated.text,
target_channel_id=updated.target_channel_id,
target_channel_title=updated.target_channel.title,
created_at=updated.created_at,
status=updated.status,
purchases_count=updated.purchases_count,
)
return dto.CreativeOutput(
id=updated.id,
name=updated.name,
text=updated.text,
target_channel_id=updated.target_channel_id,
target_channel_title=updated.target_channel.title,
created_at=updated.created_at,
status=updated.status,
purchases_count=updated.purchases_count,
)

View File

@@ -22,19 +22,20 @@ async def create_creative(self: 'Usecase', input: dto.CreateCreativeInput, user_
creative = domain.Creative(
name=input.name,
text=input.text,
status=domain.CreativeStatus.ACTIVE,
target_channel_id=target_channel.id,
user_id=user_id,
)
created = await self.database.create_creative(creative)
return dto.CreativeOutput(
id=created.id,
name=created.name,
text=created.text,
target_channel_id=created.target_channel_id,
target_channel_title=created.target_channel.title,
created_at=created.created_at,
status=created.status,
purchases_count=created.purchases_count,
)
return dto.CreativeOutput(
id=created.id,
name=created.name,
text=created.text,
target_channel_id=created.target_channel_id,
target_channel_title=created.target_channel.title,
created_at=created.created_at,
status=created.status,
purchases_count=created.purchases_count,
)

View File

@@ -16,13 +16,13 @@ async def get_creative(self: 'Usecase', input: dto.GetCreativeInput) -> dto.Crea
log.warning('User %s attempted to access unavailable creative %s', input.user_id, input.creative_id)
raise domain.CreativeNotFound(input.creative_id)
return dto.CreativeOutput(
id=creative.id,
name=creative.name,
text=creative.text,
target_channel_id=creative.target_channel_id,
target_channel_title=creative.target_channel.title,
created_at=creative.created_at,
status=creative.status,
purchases_count=creative.purchases_count,
)
return dto.CreativeOutput(
id=creative.id,
name=creative.name,
text=creative.text,
target_channel_id=creative.target_channel_id,
target_channel_title=creative.target_channel.title,
created_at=creative.created_at,
status=creative.status,
purchases_count=creative.purchases_count,
)

View File

@@ -26,13 +26,13 @@ async def update_creative(
updated = await self.database.update_creative(creative)
return dto.CreativeOutput(
id=updated.id,
name=updated.name,
text=updated.text,
target_channel_id=updated.target_channel_id,
target_channel_title=updated.target_channel.title,
created_at=updated.created_at,
status=updated.status,
purchases_count=updated.purchases_count,
)
return dto.CreativeOutput(
id=updated.id,
name=updated.name,
text=updated.text,
target_channel_id=updated.target_channel_id,
target_channel_title=updated.target_channel.title,
created_at=updated.created_at,
status=updated.status,
purchases_count=updated.purchases_count,
)

View File

@@ -20,22 +20,24 @@ async def archive_purchase(self: 'Usecase', purchase_id: uuid.UUID, user_id: uui
purchase.status = domain.PurchaseStatus.ARCHIVED
updated = await self.database.update_purchase(purchase)
return dto.PurchaseOutput(
id=updated.id,
target_channel_id=updated.target_channel_id,
target_channel_title=updated.target_channel.title,
external_channel_id=updated.external_channel_id,
external_channel_title=updated.external_channel.title,
creative_id=updated.creative_id,
creative_name=updated.creative.name,
placement_date=updated.placement_date,
cost=updated.cost,
comment=updated.comment,
ad_post_url=updated.ad_post_url,
invite_link_type=updated.invite_link_type,
invite_link=updated.invite_link,
status=updated.status,
subscriptions_count=updated.subscriptions_count,
views_count=updated.views_count,
created_at=updated.created_at,
)
return dto.PurchaseOutput(
id=updated.id,
target_channel_id=updated.target_channel_id,
target_channel_title=updated.target_channel.title,
external_channel_id=updated.external_channel_id,
external_channel_title=updated.external_channel.title,
creative_id=updated.creative_id,
creative_name=updated.creative.name,
placement_date=updated.placement_date,
cost=updated.cost,
comment=updated.comment,
ad_post_url=updated.ad_post_url,
invite_link_type=updated.invite_link_type,
invite_link=updated.invite_link,
status=updated.status,
subscriptions_count=updated.subscriptions_count,
views_count=updated.views_count,
views_availability=updated.views_availability,
last_views_fetch_at=updated.last_views_fetch_at,
created_at=updated.created_at,
)

View File

@@ -62,22 +62,25 @@ async def create_purchase(self: 'Usecase', input: dto.CreatePurchaseInput, user_
creative.purchases_count += 1
await self.database.update_creative(creative)
return dto.PurchaseOutput(
id=created.id,
target_channel_id=created.target_channel_id,
target_channel_title=created.target_channel.title,
external_channel_id=created.external_channel_id,
external_channel_title=created.external_channel.title,
creative_id=created.creative_id,
creative_name=created.creative.name,
placement_date=created.placement_date,
cost=created.cost,
comment=created.comment,
ad_post_url=created.ad_post_url,
invite_link_type=created.invite_link_type,
invite_link=created.invite_link,
status=created.status,
subscriptions_count=created.subscriptions_count,
views_count=created.views_count,
created_at=created.created_at,
)
# Формируем ответ внутри транзакции, пока объекты в сессии
return dto.PurchaseOutput(
id=created.id,
target_channel_id=created.target_channel_id,
target_channel_title=target_channel.title,
external_channel_id=created.external_channel_id,
external_channel_title=external_channel.title,
creative_id=created.creative_id,
creative_name=creative.name,
placement_date=created.placement_date,
cost=created.cost,
comment=created.comment,
ad_post_url=created.ad_post_url,
invite_link_type=created.invite_link_type,
invite_link=created.invite_link,
status=created.status,
subscriptions_count=created.subscriptions_count,
views_count=created.views_count,
views_availability=created.views_availability,
last_views_fetch_at=created.last_views_fetch_at,
created_at=created.created_at,
)

View File

@@ -16,22 +16,24 @@ async def get_purchase(self: 'Usecase', input: dto.GetPurchaseInput) -> dto.Purc
log.warning('Purchase %s not found for user %s', input.purchase_id, input.user_id)
raise domain.PurchaseNotFound(input.purchase_id)
return dto.PurchaseOutput(
id=purchase.id,
target_channel_id=purchase.target_channel_id,
target_channel_title=purchase.target_channel.title,
external_channel_id=purchase.external_channel_id,
external_channel_title=purchase.external_channel.title,
creative_id=purchase.creative_id,
creative_name=purchase.creative.name,
placement_date=purchase.placement_date,
cost=purchase.cost,
comment=purchase.comment,
ad_post_url=purchase.ad_post_url,
invite_link_type=purchase.invite_link_type,
invite_link=purchase.invite_link,
status=purchase.status,
subscriptions_count=purchase.subscriptions_count,
views_count=purchase.views_count,
created_at=purchase.created_at,
)
return dto.PurchaseOutput(
id=purchase.id,
target_channel_id=purchase.target_channel_id,
target_channel_title=purchase.target_channel.title,
external_channel_id=purchase.external_channel_id,
external_channel_title=purchase.external_channel.title,
creative_id=purchase.creative_id,
creative_name=purchase.creative.name,
placement_date=purchase.placement_date,
cost=purchase.cost,
comment=purchase.comment,
ad_post_url=purchase.ad_post_url,
invite_link_type=purchase.invite_link_type,
invite_link=purchase.invite_link,
status=purchase.status,
subscriptions_count=purchase.subscriptions_count,
views_count=purchase.views_count,
views_availability=purchase.views_availability,
last_views_fetch_at=purchase.last_views_fetch_at,
created_at=purchase.created_at,
)

View File

@@ -35,6 +35,8 @@ async def get_purchases(self: 'Usecase', input: dto.GetPurchasesInput) -> dto.Ge
status=purchase.status,
subscriptions_count=purchase.subscriptions_count,
views_count=purchase.views_count,
views_availability=purchase.views_availability,
last_views_fetch_at=purchase.last_views_fetch_at,
created_at=purchase.created_at,
)
for purchase in purchases

View File

@@ -31,22 +31,24 @@ async def update_purchase(
updated = await self.database.update_purchase(purchase)
return dto.PurchaseOutput(
id=updated.id,
target_channel_id=updated.target_channel_id,
target_channel_title=updated.target_channel.title,
external_channel_id=updated.external_channel_id,
external_channel_title=updated.external_channel.title,
creative_id=updated.creative_id,
creative_name=updated.creative.name,
placement_date=updated.placement_date,
cost=updated.cost,
comment=updated.comment,
ad_post_url=updated.ad_post_url,
invite_link_type=updated.invite_link_type,
invite_link=updated.invite_link,
status=updated.status,
subscriptions_count=updated.subscriptions_count,
views_count=updated.views_count,
created_at=updated.created_at,
)
return dto.PurchaseOutput(
id=updated.id,
target_channel_id=updated.target_channel_id,
target_channel_title=updated.target_channel.title,
external_channel_id=updated.external_channel_id,
external_channel_title=updated.external_channel.title,
creative_id=updated.creative_id,
creative_name=updated.creative.name,
placement_date=updated.placement_date,
cost=updated.cost,
comment=updated.comment,
ad_post_url=updated.ad_post_url,
invite_link_type=updated.invite_link_type,
invite_link=updated.invite_link,
status=updated.status,
subscriptions_count=updated.subscriptions_count,
views_count=updated.views_count,
views_availability=updated.views_availability,
last_views_fetch_at=updated.last_views_fetch_at,
created_at=updated.created_at,
)

View File

@@ -0,0 +1,59 @@
import logging
from typing import TYPE_CHECKING
from src import domain
if TYPE_CHECKING:
from .. import Usecase
log = logging.getLogger(__name__)
async def handle_subscription(
self: 'Usecase',
user_telegram_id: int,
username: str | None,
invite_link: str,
) -> None:
"""
Обрабатывает подписку пользователя в целевой канал.
Находит закуп по invite_link и создаёт запись о подписке,
инкрементируя счётчик подписок у закупа.
"""
async with self.database.transaction():
# Находим закуп по пригласительной ссылке
purchase = await self.database.get_purchase_by_invite_link(invite_link)
if not purchase:
log.warning('Purchase not found for invite_link: %s', invite_link)
return
# Проверяем, не создана ли уже подписка для этого пользователя
existing_subscription = await self.database.get_subscription_by_user_and_purchase(user_telegram_id, purchase.id)
if existing_subscription:
log.info(
'Subscription already exists for user %s and purchase %s',
user_telegram_id,
purchase.id,
)
return
# Создаём запись о подписке
subscription = domain.Subscription(
purchase_id=purchase.id,
user_telegram_id=user_telegram_id,
username=username,
invite_link=invite_link,
)
await self.database.create_subscription(subscription)
# Увеличиваем счётчик подписок у закупа
purchase.subscriptions_count += 1
await self.database.update_purchase(purchase)
log.info(
'Subscription created: user %s subscribed via purchase %s (invite_link: %s)',
user_telegram_id,
purchase.id,
invite_link,
)

View File

@@ -0,0 +1,77 @@
import datetime
import logging
from typing import TYPE_CHECKING
from src import domain, dto
if TYPE_CHECKING:
from .. import Usecase
log = logging.getLogger(__name__)
async def fetch_views(self: 'Usecase', input: dto.FetchViewsInput) -> dto.FetchViewsOutput:
"""
Получить просмотры для закупа через Telegram API.
Создаёт снимок просмотров и обновляет метрики закупа.
"""
async with self.database.transaction():
purchase = await self.database.get_purchase(input.user_id, input.purchase_id)
if not purchase:
log.warning('Purchase %s not found for user %s', input.purchase_id, input.user_id)
raise domain.PurchaseNotFound(input.purchase_id)
if not purchase.ad_post_url:
log.warning('Purchase %s has no ad_post_url', input.purchase_id)
return dto.FetchViewsOutput(
purchase_id=purchase.id,
views_count=None,
views_availability=domain.PostViewsAvailability.UNAVAILABLE,
fetched_at=datetime.datetime.now(datetime.UTC),
error_message='No ad_post_url specified',
)
# Попытка получить просмотры через Telegram API
views_count = await self.telegram_writer.get_post_views(purchase.ad_post_url)
fetched_at = datetime.datetime.now(datetime.UTC)
if views_count is not None:
# Успешно получены просмотры
purchase.views_count = views_count
purchase.views_availability = domain.PostViewsAvailability.AVAILABLE
purchase.last_views_fetch_at = fetched_at
await self.database.update_purchase(purchase)
# Создаём снимок
snapshot = domain.ViewsSnapshot(
purchase_id=purchase.id,
views_count=views_count,
fetched_at=fetched_at,
)
await self.database.create_views_snapshot(snapshot)
log.info('Views fetched for purchase %s: %d', purchase.id, views_count)
return dto.FetchViewsOutput(
purchase_id=purchase.id,
views_count=views_count,
views_availability=domain.PostViewsAvailability.AVAILABLE,
fetched_at=fetched_at,
)
else:
# Не удалось получить просмотры
purchase.views_availability = domain.PostViewsAvailability.UNAVAILABLE
purchase.last_views_fetch_at = fetched_at
await self.database.update_purchase(purchase)
log.warning('Failed to fetch views for purchase %s', purchase.id)
return dto.FetchViewsOutput(
purchase_id=purchase.id,
views_count=None,
views_availability=domain.PostViewsAvailability.UNAVAILABLE,
fetched_at=fetched_at,
error_message='Failed to fetch views from Telegram API',
)

View File

@@ -0,0 +1,37 @@
import logging
from typing import TYPE_CHECKING
from src import domain, dto
if TYPE_CHECKING:
from .. import Usecase
log = logging.getLogger(__name__)
async def get_views_history(self: 'Usecase', input: dto.GetViewsHistoryInput) -> dto.GetViewsHistoryOutput:
"""Получить историю просмотров для закупа."""
async with self.database.transaction():
purchase = await self.database.get_purchase(input.user_id, input.purchase_id)
if not purchase:
log.warning('Purchase %s not found for user %s', input.purchase_id, input.user_id)
raise domain.PurchaseNotFound(input.purchase_id)
snapshots = await self.database.get_views_history(
input.purchase_id,
from_date=input.from_date,
to_date=input.to_date,
)
return dto.GetViewsHistoryOutput(
snapshots=[
dto.ViewsSnapshotOutput(
id=snapshot.id,
purchase_id=snapshot.purchase_id,
views_count=snapshot.views_count,
fetched_at=snapshot.fetched_at,
created_at=snapshot.created_at,
)
for snapshot in snapshots
]
)

View File

@@ -0,0 +1,60 @@
import datetime
import logging
from typing import TYPE_CHECKING
from src import domain, dto
if TYPE_CHECKING:
from .. import Usecase
log = logging.getLogger(__name__)
async def update_views_manually(self: 'Usecase', input: dto.UpdateViewsManuallyInput) -> dto.PurchaseOutput:
"""Ручное обновление просмотров для закупа."""
async with self.database.transaction():
purchase = await self.database.get_purchase(input.user_id, input.purchase_id)
if not purchase:
log.warning('Purchase %s not found for user %s', input.purchase_id, input.user_id)
raise domain.PurchaseNotFound(input.purchase_id)
fetched_at = datetime.datetime.now(datetime.UTC)
# Обновляем метрики закупа
purchase.views_count = input.views_count
purchase.views_availability = domain.PostViewsAvailability.MANUAL
purchase.last_views_fetch_at = fetched_at
await self.database.update_purchase(purchase)
# Создаём снимок
snapshot = domain.ViewsSnapshot(
purchase_id=purchase.id,
views_count=input.views_count,
fetched_at=fetched_at,
)
await self.database.create_views_snapshot(snapshot)
log.info('Views manually updated for purchase %s: %d', purchase.id, input.views_count)
# Возвращаем обновлённый закуп
return dto.PurchaseOutput(
id=purchase.id,
target_channel_id=purchase.target_channel_id,
target_channel_title=purchase.target_channel.title,
external_channel_id=purchase.external_channel_id,
external_channel_title=purchase.external_channel.title,
creative_id=purchase.creative_id,
creative_name=purchase.creative.name,
placement_date=purchase.placement_date,
cost=purchase.cost,
comment=purchase.comment,
ad_post_url=purchase.ad_post_url,
invite_link_type=purchase.invite_link_type,
invite_link=purchase.invite_link,
status=purchase.status,
subscriptions_count=purchase.subscriptions_count,
views_count=purchase.views_count,
views_availability=purchase.views_availability,
last_views_fetch_at=purchase.last_views_fetch_at,
created_at=purchase.created_at,
)