feat: доменный нейминг изменен

This commit is contained in:
Artem Tsyrulnikov
2025-11-13 01:18:04 +03:00
parent a48d5e67cb
commit bba37fbb21
51 changed files with 1144 additions and 1154 deletions

View File

@@ -14,8 +14,8 @@ class Postgres(DatabaseBase):
return await self.session.get(domain.User, user_id)
elif telegram_id:
stmt = select(domain.User).where(domain.User.telegram_id == telegram_id)
result = await self.session.execute(stmt)
q = select(domain.User).where(domain.User.telegram_id == telegram_id)
result = await self.session.execute(q)
return result.scalar_one_or_none()
raise ValueError('Either user_id or telegram_id must be provided')
@@ -37,15 +37,15 @@ class Postgres(DatabaseBase):
return login_token
async def get_login_token(self, token: str) -> domain.LoginToken | None:
stmt = select(domain.LoginToken).where(domain.LoginToken.token == token)
q = select(domain.LoginToken).where(domain.LoginToken.token == token)
result = await self.session.execute(stmt)
result = await self.session.execute(q)
return result.scalar_one_or_none()
async def mark_token_as_used(self, token: str) -> None:
stmt = select(domain.LoginToken).where(domain.LoginToken.token == token)
q = select(domain.LoginToken).where(domain.LoginToken.token == token)
result = await self.session.execute(stmt)
result = await self.session.execute(q)
login_token = result.scalar_one_or_none()
if login_token:
login_token.used_at = datetime.datetime.now(datetime.UTC)
@@ -57,13 +57,13 @@ class Postgres(DatabaseBase):
if not channel_id and not telegram_id:
raise ValueError('Either channel_id or telegram_id must be provided')
stmt = select(domain.TargetChannel).where(domain.TargetChannel.user_id == user_id)
q = select(domain.TargetChannel).where(domain.TargetChannel.user_id == user_id)
if channel_id:
stmt = stmt.where(domain.TargetChannel.id == channel_id)
q = q.where(domain.TargetChannel.id == channel_id)
if telegram_id:
stmt = stmt.where(domain.TargetChannel.telegram_id == telegram_id)
q = q.where(domain.TargetChannel.telegram_id == telegram_id)
result = await self.session.execute(stmt)
result = await self.session.execute(q)
return result.scalar_one_or_none()
async def create_target_channel(self, channel: domain.TargetChannel) -> domain.TargetChannel:
@@ -93,11 +93,11 @@ class Postgres(DatabaseBase):
return existing
async def get_user_target_channels(self, user_id: uuid.UUID) -> list[domain.TargetChannel]:
stmt = select(domain.TargetChannel).where(
q = select(domain.TargetChannel).where(
domain.TargetChannel.status == domain.TargetChannelStatus.ACTIVE,
domain.TargetChannel.user_id == user_id,
)
result = await self.session.execute(stmt)
result = await self.session.execute(q)
return list(result.scalars().all())
async def update_target_channel(self, channel: domain.TargetChannel) -> domain.TargetChannel:
@@ -108,13 +108,13 @@ class Postgres(DatabaseBase):
async def get_external_channel(
self, user_id: uuid.UUID, channel_id: uuid.UUID | None = None, telegram_id: int | None = None
) -> domain.ExternalChannel | None:
stmt = select(domain.ExternalChannel).where(domain.ExternalChannel.user_id == user_id)
q = select(domain.ExternalChannel).where(domain.ExternalChannel.user_id == user_id)
if channel_id:
stmt = stmt.where(domain.ExternalChannel.id == channel_id)
q = q.where(domain.ExternalChannel.id == channel_id)
if telegram_id:
stmt = stmt.where(domain.ExternalChannel.telegram_id == telegram_id)
q = q.where(domain.ExternalChannel.telegram_id == telegram_id)
result = await self.session.execute(stmt)
result = await self.session.execute(q)
return result.scalar_one_or_none()
async def create_external_channel(self, channel: domain.ExternalChannel) -> domain.ExternalChannel:
@@ -124,23 +124,23 @@ class Postgres(DatabaseBase):
return channel
async def get_external_channels_for_target(self, target_channel_id: uuid.UUID) -> list[domain.ExternalChannel]:
stmt = (
q = (
select(domain.ExternalChannel)
.join(domain.ExternalChannel.target_channels)
.where(domain.TargetChannel.id == target_channel_id)
)
result = await self.session.execute(stmt)
result = await self.session.execute(q)
return list(result.scalars().all())
async def add_external_channel_to_targets(
self, external_channel_id: uuid.UUID, target_channel_ids: list[uuid.UUID]
) -> None:
stmt = (
q = (
select(domain.ExternalChannel)
.where(domain.ExternalChannel.id == external_channel_id)
.options(selectinload(domain.ExternalChannel.target_channels))
)
result = await self.session.execute(stmt)
result = await self.session.execute(q)
external_channel = result.scalar_one_or_none()
if not external_channel:
@@ -156,12 +156,12 @@ class Postgres(DatabaseBase):
async def remove_external_channel_from_target(
self, external_channel_id: uuid.UUID, target_channel_id: uuid.UUID
) -> None:
stmt = (
q = (
select(domain.ExternalChannel)
.where(domain.ExternalChannel.id == external_channel_id)
.options(selectinload(domain.ExternalChannel.target_channels))
)
result = await self.session.execute(stmt)
result = await self.session.execute(q)
external_channel = result.scalar_one_or_none()
if not external_channel:
@@ -174,8 +174,8 @@ class Postgres(DatabaseBase):
await self.session.flush()
async def delete_external_channel(self, channel_id: uuid.UUID) -> None:
stmt = delete(domain.ExternalChannel).where(domain.ExternalChannel.id == channel_id)
await self.session.execute(stmt)
q = delete(domain.ExternalChannel).where(domain.ExternalChannel.id == channel_id)
await self.session.execute(q)
await self.session.flush()
async def update_external_channel(self, channel: domain.ExternalChannel) -> domain.ExternalChannel:
@@ -184,12 +184,12 @@ class Postgres(DatabaseBase):
return channel
async def get_creative(self, user_id: uuid.UUID, creative_id: uuid.UUID) -> domain.Creative | None:
stmt = (
q = (
select(domain.Creative)
.options(selectinload(domain.Creative.target_channel))
.where(domain.Creative.id == creative_id, domain.Creative.user_id == user_id)
)
result = await self.session.execute(stmt)
result = await self.session.execute(q)
return result.scalar_one_or_none()
async def create_creative(self, creative: domain.Creative) -> domain.Creative:
@@ -206,59 +206,59 @@ class Postgres(DatabaseBase):
async def get_user_creatives(
self, user_id: uuid.UUID, *, target_channel_id: uuid.UUID | None = None, include_archived: bool = False
) -> list[domain.Creative]:
stmt = (
q = (
select(domain.Creative)
.options(selectinload(domain.Creative.target_channel))
.where(domain.Creative.user_id == user_id)
)
if target_channel_id:
stmt = stmt.where(domain.Creative.target_channel_id == target_channel_id)
q = q.where(domain.Creative.target_channel_id == target_channel_id)
if not include_archived:
stmt = stmt.where(domain.Creative.status == domain.CreativeStatus.ACTIVE)
q = q.where(domain.Creative.status == domain.CreativeStatus.ACTIVE)
stmt = stmt.order_by(domain.Creative.created_at.desc())
q = q.order_by(domain.Creative.created_at.desc())
result = await self.session.execute(stmt)
result = await self.session.execute(q)
return list(result.scalars().all())
async def delete_creative(self, creative_id: uuid.UUID) -> None:
stmt = delete(domain.Creative).where(domain.Creative.id == creative_id)
await self.session.execute(stmt)
q = delete(domain.Creative).where(domain.Creative.id == creative_id)
await self.session.execute(q)
await self.session.flush()
async def get_purchase(self, user_id: uuid.UUID, purchase_id: uuid.UUID) -> domain.Purchase | None:
stmt = (
select(domain.Purchase)
async def get_placement(self, user_id: uuid.UUID, placement_id: uuid.UUID) -> domain.Placement | None:
q = (
select(domain.Placement)
.options(
selectinload(domain.Purchase.target_channel),
selectinload(domain.Purchase.external_channel),
selectinload(domain.Purchase.creative),
selectinload(domain.Placement.target_channel),
selectinload(domain.Placement.external_channel),
selectinload(domain.Placement.creative),
)
.where(domain.Purchase.id == purchase_id, domain.Purchase.user_id == user_id)
.where(domain.Placement.id == placement_id, domain.Placement.user_id == user_id)
)
result = await self.session.execute(stmt)
result = await self.session.execute(q)
return result.scalar_one_or_none()
async def create_purchase(self, purchase: domain.Purchase) -> domain.Purchase:
self.session.add(purchase)
async def create_placement(self, placement: domain.Placement) -> domain.Placement:
self.session.add(placement)
await self.session.flush()
await self.session.refresh(
purchase,
placement,
['target_channel', 'external_channel', 'creative'],
)
return purchase
return placement
async def update_purchase(self, purchase: domain.Purchase) -> domain.Purchase:
async def update_placement(self, placement: domain.Placement) -> domain.Placement:
await self.session.flush()
await self.session.refresh(
purchase,
placement,
['target_channel', 'external_channel', 'creative'],
)
return purchase
return placement
async def get_user_purchases(
async def get_user_placements(
self,
user_id: uuid.UUID,
*,
@@ -266,109 +266,134 @@ class Postgres(DatabaseBase):
external_channel_id: uuid.UUID | None = None,
creative_id: uuid.UUID | None = None,
include_archived: bool = False,
) -> list[domain.Purchase]:
stmt = (
select(domain.Purchase)
) -> list[domain.Placement]:
q = (
select(domain.Placement)
.options(
selectinload(domain.Purchase.target_channel),
selectinload(domain.Purchase.external_channel),
selectinload(domain.Purchase.creative),
selectinload(domain.Placement.target_channel),
selectinload(domain.Placement.external_channel),
selectinload(domain.Placement.creative),
)
.where(domain.Purchase.user_id == user_id)
.where(domain.Placement.user_id == user_id)
)
if target_channel_id:
stmt = stmt.where(domain.Purchase.target_channel_id == target_channel_id)
q = q.where(domain.Placement.target_channel_id == target_channel_id)
if external_channel_id:
stmt = stmt.where(domain.Purchase.external_channel_id == external_channel_id)
q = q.where(domain.Placement.external_channel_id == external_channel_id)
if creative_id:
stmt = stmt.where(domain.Purchase.creative_id == creative_id)
q = q.where(domain.Placement.creative_id == creative_id)
if not include_archived:
stmt = stmt.where(domain.Purchase.status == domain.PurchaseStatus.ACTIVE)
q = q.where(domain.Placement.status == domain.PlacementStatus.ACTIVE)
stmt = stmt.order_by(domain.Purchase.placement_date.desc())
q = q.order_by(domain.Placement.placement_date.desc())
result = await self.session.execute(stmt)
result = await self.session.execute(q)
return list(result.scalars().all())
async def delete_purchase(self, purchase_id: uuid.UUID) -> None:
stmt = delete(domain.Purchase).where(domain.Purchase.id == purchase_id)
await self.session.execute(stmt)
async def delete_placement(self, placement_id: uuid.UUID) -> None:
q = delete(domain.Placement).where(domain.Placement.id == placement_id)
await self.session.execute(q)
await self.session.flush()
async def check_creative_in_use(self, creative_id: uuid.UUID) -> bool:
stmt = select(domain.Purchase).where(
domain.Purchase.creative_id == creative_id,
domain.Purchase.status == domain.PurchaseStatus.ACTIVE,
q = select(domain.Placement).where(
domain.Placement.creative_id == creative_id,
domain.Placement.status == domain.PlacementStatus.ACTIVE,
)
result = await self.session.execute(stmt)
result = await self.session.execute(q)
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)
async def get_placement_by_invite_link(self, invite_link: str) -> domain.Placement | None:
q = (
select(domain.Placement)
.options(
selectinload(domain.Purchase.target_channel),
selectinload(domain.Purchase.external_channel),
selectinload(domain.Purchase.creative),
selectinload(domain.Placement.target_channel),
selectinload(domain.Placement.external_channel),
selectinload(domain.Placement.creative),
)
.where(domain.Purchase.invite_link == invite_link)
.where(domain.Placement.invite_link == invite_link)
)
result = await self.session.execute(stmt)
result = await self.session.execute(q)
return result.scalar_one_or_none()
async def get_subscriber(self, telegram_id: int) -> domain.Subscriber | None:
q = select(domain.Subscriber).where(domain.Subscriber.telegram_id == telegram_id)
result = await self.session.execute(q)
return result.scalar_one_or_none()
async def create_subscriber(self, subscriber: domain.Subscriber) -> domain.Subscriber:
self.session.add(subscriber)
await self.session.flush()
await self.session.refresh(subscriber)
return subscriber
async def upsert_subscriber(self, subscriber: domain.Subscriber) -> domain.Subscriber:
existing = await self.get_subscriber(subscriber.telegram_id)
if existing:
# Обновляем данные если изменились
existing.username = subscriber.username
existing.first_name = subscriber.first_name
existing.last_name = subscriber.last_name
await self.session.flush()
await self.session.refresh(existing)
return existing
return await self.create_subscriber(subscriber)
async def create_subscription(self, subscription: domain.Subscription) -> domain.Subscription:
self.session.add(subscription)
await self.session.flush()
await self.session.refresh(subscription, ['purchase'])
await self.session.refresh(subscription, ['placement', 'subscriber'])
return subscription
async def get_subscription_by_user_and_purchase(
self, user_telegram_id: int, purchase_id: uuid.UUID
async def get_subscription_by_subscriber_and_placement(
self, subscriber_id: uuid.UUID, placement_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,
q = select(domain.Subscription).where(
domain.Subscription.subscriber_id == subscriber_id,
domain.Subscription.placement_id == placement_id,
)
result = await self.session.execute(stmt)
result = await self.session.execute(q)
return result.scalar_one_or_none()
async def create_views_snapshot(self, snapshot: domain.ViewsSnapshot) -> domain.ViewsSnapshot:
self.session.add(snapshot)
async def create_placement_views_history(
self, history: domain.PlacementViewsHistory
) -> domain.PlacementViewsHistory:
self.session.add(history)
await self.session.flush()
await self.session.refresh(snapshot, ['purchase'])
return snapshot
await self.session.refresh(history, ['placement'])
return history
async def get_views_history(
self,
purchase_id: uuid.UUID,
placement_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)
) -> list[domain.PlacementViewsHistory]:
q = select(domain.PlacementViewsHistory).where(domain.PlacementViewsHistory.placement_id == placement_id)
if from_date:
stmt = stmt.where(domain.ViewsSnapshot.fetched_at >= from_date)
q = q.where(domain.PlacementViewsHistory.fetched_at >= from_date)
if to_date:
stmt = stmt.where(domain.ViewsSnapshot.fetched_at <= to_date)
q = q.where(domain.PlacementViewsHistory.fetched_at <= to_date)
stmt = stmt.order_by(domain.ViewsSnapshot.fetched_at.asc())
q = q.order_by(domain.PlacementViewsHistory.fetched_at.asc())
result = await self.session.execute(stmt)
result = await self.session.execute(q)
return list(result.scalars().all())
async def get_active_purchases_with_urls(self) -> list[domain.Purchase]:
stmt = (
select(domain.Purchase)
async def get_active_placements_with_urls(self) -> list[domain.Placement]:
q = (
select(domain.Placement)
.where(
domain.Purchase.status == domain.PurchaseStatus.ACTIVE,
domain.Purchase.ad_post_url.isnot(None),
domain.Purchase.views_availability != domain.PostViewsAvailability.MANUAL,
domain.Placement.status == domain.PlacementStatus.ACTIVE,
domain.Placement.ad_post_url.isnot(None),
domain.Placement.views_availability != domain.PostViewsAvailability.MANUAL,
)
.order_by(domain.Purchase.created_at.asc())
.order_by(domain.Placement.created_at.asc())
)
result = await self.session.execute(stmt)
result = await self.session.execute(q)
return list(result.scalars().all())

View File

@@ -3,7 +3,7 @@ from fastapi import APIRouter
from src.controller.http.auth import auth_router
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.placements import placements_router
from src.controller.http.target_channels import target_channels_router
from src.controller.http.views import views_router
@@ -17,7 +17,7 @@ api_v1_router = APIRouter(prefix='/api/v1')
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(placements_router)
api_v1_router.include_router(views_router)
api_router.include_router(api_v1_router)

View File

@@ -0,0 +1,76 @@
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
placements_router = APIRouter(prefix='/placements', tags=['placements'])
@placements_router.get('')
async def list_placements(
current_user: Annotated[JWTPayload, Depends(dependencies.get_current_user)],
target_channel_id: uuid.UUID | None = None,
external_channel_id: uuid.UUID | None = None,
creative_id: uuid.UUID | None = None,
include_archived: bool = False,
) -> dto.GetPlacementsOutput:
input = dto.GetPlacementsInput(
user_id=current_user.user_id,
target_channel_id=target_channel_id,
external_channel_id=external_channel_id,
creative_id=creative_id,
include_archived=include_archived,
)
return await dependencies.get_usecase().get_placements(input=input)
@placements_router.get('/{placement_id}')
async def get_placement(
placement_id: uuid.UUID,
current_user: Annotated[JWTPayload, Depends(dependencies.get_current_user)],
) -> dto.PlacementOutput:
input = dto.GetPlacementInput(
placement_id=placement_id,
user_id=current_user.user_id,
)
return await dependencies.get_usecase().get_placement(input=input)
@placements_router.post('')
async def create_placement(
request: dto.CreatePlacementInput,
current_user: Annotated[JWTPayload, Depends(dependencies.get_current_user)],
) -> dto.PlacementOutput:
return await dependencies.get_usecase().create_placement(request, current_user.user_id)
@placements_router.patch('/{placement_id}')
async def update_placement(
placement_id: uuid.UUID,
request: dto.UpdatePlacementInput,
current_user: Annotated[JWTPayload, Depends(dependencies.get_current_user)],
) -> dto.PlacementOutput:
return await dependencies.get_usecase().update_placement(
placement_id=placement_id,
input=request,
user_id=current_user.user_id,
)
@placements_router.delete('/{placement_id}')
async def delete_placement(
placement_id: uuid.UUID,
current_user: Annotated[JWTPayload, Depends(dependencies.get_current_user)],
) -> None:
input = dto.DeletePlacementInput(
placement_id=placement_id,
user_id=current_user.user_id,
)
await dependencies.get_usecase().delete_placement(input)

View File

@@ -1,76 +0,0 @@
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
purchases_router = APIRouter(prefix='/purchases', tags=['purchases'])
@purchases_router.get('')
async def list_purchases(
current_user: Annotated[JWTPayload, Depends(dependencies.get_current_user)],
target_channel_id: uuid.UUID | None = None,
external_channel_id: uuid.UUID | None = None,
creative_id: uuid.UUID | None = None,
include_archived: bool = False,
) -> dto.GetPurchasesOutput:
input = dto.GetPurchasesInput(
user_id=current_user.user_id,
target_channel_id=target_channel_id,
external_channel_id=external_channel_id,
creative_id=creative_id,
include_archived=include_archived,
)
return await dependencies.get_usecase().get_purchases(input=input)
@purchases_router.get('/{purchase_id}')
async def get_purchase(
purchase_id: uuid.UUID,
current_user: Annotated[JWTPayload, Depends(dependencies.get_current_user)],
) -> dto.PurchaseOutput:
input = dto.GetPurchaseInput(
purchase_id=purchase_id,
user_id=current_user.user_id,
)
return await dependencies.get_usecase().get_purchase(input=input)
@purchases_router.post('')
async def create_purchase(
request: dto.CreatePurchaseInput,
current_user: Annotated[JWTPayload, Depends(dependencies.get_current_user)],
) -> dto.PurchaseOutput:
return await dependencies.get_usecase().create_purchase(request, current_user.user_id)
@purchases_router.patch('/{purchase_id}')
async def update_purchase(
purchase_id: uuid.UUID,
request: dto.UpdatePurchaseInput,
current_user: Annotated[JWTPayload, Depends(dependencies.get_current_user)],
) -> dto.PurchaseOutput:
return await dependencies.get_usecase().update_purchase(
purchase_id=purchase_id,
input=request,
user_id=current_user.user_id,
)
@purchases_router.delete('/{purchase_id}')
async def delete_purchase(
purchase_id: uuid.UUID,
current_user: Annotated[JWTPayload, Depends(dependencies.get_current_user)],
) -> None:
input = dto.DeletePurchaseInput(
purchase_id=purchase_id,
user_id=current_user.user_id,
)
await dependencies.get_usecase().delete_purchase(input)

View File

@@ -8,19 +8,19 @@ 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 = APIRouter(prefix='/placements/{placement_id}/views', tags=['views'])
@views_router.get('/history')
async def get_views_history(
purchase_id: uuid.UUID,
placement_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,
placement_id=placement_id,
user_id=current_user.user_id,
from_date=from_date,
to_date=to_date,
@@ -31,12 +31,12 @@ async def get_views_history(
@views_router.post('/fetch')
async def fetch_views(
purchase_id: uuid.UUID,
placement_id: uuid.UUID,
current_user: Annotated[JWTPayload, Depends(dependencies.get_current_user)],
) -> dto.FetchViewsManuallyOutput:
"""Получить актуальные просмотры через Telegram API."""
input_data = dto.FetchViewsInputManually(
purchase_id=purchase_id,
placement_id=placement_id,
user_id=current_user.user_id,
)
@@ -45,13 +45,13 @@ async def fetch_views(
@views_router.post('/manual')
async def update_views_manually(
purchase_id: uuid.UUID,
placement_id: uuid.UUID,
views_count: int,
current_user: Annotated[JWTPayload, Depends(dependencies.get_current_user)],
) -> dto.PurchaseOutput:
) -> dto.PlacementOutput:
"""Обновить просмотры вручную."""
input_data = dto.UpdateViewsManuallyInput(
purchase_id=purchase_id,
placement_id=placement_id,
user_id=current_user.user_id,
views_count=views_count,
)

View File

@@ -4,12 +4,13 @@ __all__ = (
'TargetChannel',
'ExternalChannel',
'Creative',
'Purchase',
'Placement',
'Subscription',
'ViewsSnapshot',
'Subscriber',
'PlacementViewsHistory',
'TargetChannelStatus',
'CreativeStatus',
'PurchaseStatus',
'PlacementStatus',
'InviteLinkType',
'PostViewsAvailability',
'LoginToken',
@@ -24,7 +25,7 @@ __all__ = (
'ExternalChannelAlreadyExists',
'CreativeNotFound',
'CreativeInUse',
'PurchaseNotFound',
'PlacementNotFound',
)
from .base import Base
@@ -39,14 +40,15 @@ from .error import (
LoginTokenAlreadyUsed,
LoginTokenExpired,
LoginTokenNotFound,
PurchaseNotFound,
PlacementNotFound,
TargetChannelNotFound,
UserNotFound,
)
from .external_channel import ExternalChannel
from .login_token import LoginToken
from .purchase import InviteLinkType, PostViewsAvailability, Purchase, PurchaseStatus
from .placement import InviteLinkType, Placement, PlacementStatus, PostViewsAvailability
from .placement_views_history import PlacementViewsHistory
from .subscriber import Subscriber
from .subscription import Subscription
from .target_channel import TargetChannel, TargetChannelStatus
from .user import User
from .views_snapshot import ViewsSnapshot

View File

@@ -1,4 +1,5 @@
import datetime
import re
import uuid
from sqlalchemy import func
@@ -6,6 +7,12 @@ from sqlalchemy.orm import DeclarativeBase, Mapped, declared_attr, mapped_column
from sqlalchemy.types import DateTime
def _camel_to_snake(name: str) -> str:
"""Convert CamelCase to snake_case."""
name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower()
class Base(DeclarativeBase):
__abstract__ = True
@@ -14,10 +21,10 @@ class Base(DeclarativeBase):
datetime.datetime: DateTime(timezone=True),
}
# Авто имя таблиц по названию класса
# Авто имя таблиц по названию класса в snake_case
@declared_attr.directive
def __tablename__(cls) -> str:
return f'{cls.__name__.lower()}s'
return _camel_to_snake(cls.__name__)
id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4)
created_at: Mapped[datetime.datetime] = mapped_column(server_default=func.now())

View File

@@ -20,8 +20,8 @@ class Creative(domain.Base):
name: Mapped[str]
text: Mapped[str]
status: Mapped[CreativeStatus]
purchases_count: Mapped[int] = mapped_column(default=0, server_default='0')
user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('users.id'), index=True)
placements_count: Mapped[int] = mapped_column(default=0, server_default='0')
user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('user.id'), index=True)
target_channel_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('targetchannels.id'), index=True)
target_channel_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('target_channel.id'), index=True)
target_channel: Mapped['TargetChannel'] = relationship(back_populates='creatives')

View File

@@ -56,11 +56,11 @@ def CreativeNotFound(creative_id: uuid.UUID | None = None) -> HTTPException:
def CreativeInUse(creative_id: uuid.UUID) -> HTTPException:
return HTTPException(
status.HTTP_400_BAD_REQUEST,
f'Creative {creative_id} is used in active purchases and cannot be deleted',
f'Creative {creative_id} is used in active placements and cannot be deleted',
)
def PurchaseNotFound(purchase_id: uuid.UUID | None = None) -> HTTPException:
if purchase_id is None:
return HTTPException(status.HTTP_404_NOT_FOUND, 'Purchase not found')
return HTTPException(status.HTTP_404_NOT_FOUND, f'Purchase {purchase_id} not found')
def PlacementNotFound(placement_id: uuid.UUID | None = None) -> HTTPException:
if placement_id is None:
return HTTPException(status.HTTP_404_NOT_FOUND, 'Placement not found')
return HTTPException(status.HTTP_404_NOT_FOUND, f'Placement {placement_id} not found')

View File

@@ -9,12 +9,11 @@ from src import domain
if TYPE_CHECKING:
from . import TargetChannel
# M2M association table between TargetChannel and ExternalChannel
target_channel_external_channel = Table(
'target_channel_external_channels',
target_external_channel = Table(
'target_external_channel',
domain.Base.metadata,
Column('target_channel_id', ForeignKey('targetchannels.id', ondelete='CASCADE'), primary_key=True),
Column('external_channel_id', ForeignKey('externalchannels.id', ondelete='CASCADE'), primary_key=True),
Column('target_channel_id', ForeignKey('target_channel.id', ondelete='CASCADE'), primary_key=True),
Column('external_channel_id', ForeignKey('external_channel.id', ondelete='CASCADE'), primary_key=True),
)
@@ -24,10 +23,9 @@ class ExternalChannel(domain.Base):
username: Mapped[str | None] = mapped_column(index=True)
description: Mapped[str | None]
subscribers_count: Mapped[int | None]
user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('users.id'), index=True)
user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('user.id'), index=True)
# M2M relationship with target channels
target_channels: Mapped[list['TargetChannel']] = relationship(
secondary=target_channel_external_channel,
secondary=target_external_channel,
back_populates='external_channels',
)

View File

@@ -9,6 +9,6 @@ from src import domain
class LoginToken(domain.Base):
token: Mapped[str] = mapped_column(unique=True, index=True)
user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('users.id'))
user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('user.id'))
expires_at: Mapped[datetime.datetime]
used_at: Mapped[datetime.datetime | None]

View File

@@ -11,10 +11,12 @@ from src import domain
if TYPE_CHECKING:
from .creative import Creative
from .external_channel import ExternalChannel
from .placement_views_history import PlacementViewsHistory
from .subscription import Subscription
from .target_channel import TargetChannel
class PurchaseStatus(StrEnum):
class PlacementStatus(StrEnum):
ACTIVE = 'active'
ARCHIVED = 'archived'
@@ -33,12 +35,12 @@ class PostViewsAvailability(StrEnum):
MANUAL = 'manual' # Просмотры вводятся вручную
class Purchase(domain.Base):
class Placement(domain.Base):
# Основные поля
target_channel_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('targetchannels.id'), index=True)
external_channel_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('externalchannels.id'), index=True)
creative_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('creatives.id'), index=True)
user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('users.id'), index=True)
target_channel_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('target_channel.id'), index=True)
external_channel_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('external_channel.id'), index=True)
creative_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('creative.id'), index=True)
user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('user.id'), index=True)
# Данные закупа
placement_date: Mapped[datetime.datetime] # дата размещения (планируемая или фактическая)
@@ -49,7 +51,7 @@ class Purchase(domain.Base):
invite_link: Mapped[str] # уникальная пригласительная ссылка
# Статус
status: Mapped[PurchaseStatus] = mapped_column(default=PurchaseStatus.ACTIVE)
status: Mapped[PlacementStatus] = mapped_column(default=PlacementStatus.ACTIVE)
# Метрики (будут обновляться из Telegram API)
subscriptions_count: Mapped[int] = mapped_column(default=0, server_default='0')
@@ -63,3 +65,5 @@ class Purchase(domain.Base):
target_channel: Mapped['TargetChannel'] = relationship()
external_channel: Mapped['ExternalChannel'] = relationship()
creative: Mapped['Creative'] = relationship()
subscriptions: Mapped[list['Subscription']] = relationship(back_populates='placement')
views_histories: Mapped[list['PlacementViewsHistory']] = relationship(back_populates='placement')

View File

@@ -0,0 +1,19 @@
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 .placement import Placement
class PlacementViewsHistory(domain.Base):
placement_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('placement.id'), index=True)
views_count: Mapped[int] # Количество просмотров на момент снимка
fetched_at: Mapped[datetime.datetime] = mapped_column(index=True)
placement: Mapped['Placement'] = relationship(back_populates='views_histories')

21
src/domain/subscriber.py Normal file
View File

@@ -0,0 +1,21 @@
from typing import TYPE_CHECKING
from sqlalchemy import BigInteger
from sqlalchemy.orm import Mapped, mapped_column, relationship
from src import domain
if TYPE_CHECKING:
from .subscription import Subscription
class Subscriber(domain.Base):
"""Пользователь Telegram, подписавшийся через invite links."""
telegram_id: Mapped[int] = mapped_column(BigInteger, unique=True, index=True)
username: Mapped[str | None]
first_name: Mapped[str | None]
last_name: Mapped[str | None]
# Relationships
subscriptions: Mapped[list['Subscription']] = relationship(back_populates='subscriber')

View File

@@ -1,22 +1,21 @@
import uuid
from typing import TYPE_CHECKING
from sqlalchemy import BigInteger, ForeignKey
from sqlalchemy import ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from src import domain
if TYPE_CHECKING:
from .purchase import Purchase
from .placement import Placement
from .subscriber import Subscriber
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]
placement_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('placement.id'), index=True)
subscriber_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('subscriber.id'), index=True)
invite_link: Mapped[str] = mapped_column(index=True) # По которой пришёл пользователь
# Relationship
purchase: Mapped['Purchase'] = relationship()
# Relationships
placement: Mapped['Placement'] = relationship(back_populates='subscriptions')
subscriber: Mapped['Subscriber'] = relationship(back_populates='subscriptions')

View File

@@ -8,7 +8,9 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
from src import domain
if TYPE_CHECKING:
from . import ExternalChannel, creative, user
from . import ExternalChannel
from .creative import Creative
from .user import User
class TargetChannelStatus(StrEnum):
@@ -21,24 +23,24 @@ class TargetChannel(domain.Base):
telegram_id: Mapped[int] = mapped_column(BigInteger, unique=True, index=True)
title: Mapped[str]
username: Mapped[str | None] = mapped_column(index=True)
status: Mapped[TargetChannelStatus]
status: Mapped[TargetChannelStatus] = mapped_column(default=TargetChannelStatus.ACTIVE)
# Relationship with user
user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('users.id'), index=True)
user: Mapped['user.User'] = relationship(back_populates='target_channels')
user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('user.id'), index=True)
user: Mapped['User'] = relationship(back_populates='target_channels')
# M2M relationship with external channels
external_channels: Mapped[list['ExternalChannel']] = relationship(
secondary='target_channel_external_channels',
secondary='target_external_channel',
back_populates='target_channels',
)
creatives: Mapped[list['creative.Creative']] = relationship(back_populates='target_channel')
creatives: Mapped[list['Creative']] = relationship(back_populates='target_channel')
@property
def is_active(self) -> bool:
return self.status == domain.TargetChannelStatus.ACTIVE
return self.status == TargetChannelStatus.ACTIVE
@is_active.setter
def is_active(self, value: bool) -> None:
self.status = domain.TargetChannelStatus.ACTIVE if value else domain.TargetChannelStatus.INACTIVE
self.status = TargetChannelStatus.ACTIVE if value else TargetChannelStatus.INACTIVE

View File

@@ -1,22 +0,0 @@
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

@@ -24,14 +24,14 @@ __all__ = (
'CreateCreativeInput',
'UpdateCreativeInput',
'DeleteCreativeInput',
'PurchaseOutput',
'GetPurchasesInput',
'GetPurchasesOutput',
'GetPurchaseInput',
'CreatePurchaseInput',
'UpdatePurchaseInput',
'DeletePurchaseInput',
'ViewsSnapshotOutput',
'PlacementOutput',
'GetPlacementsInput',
'GetPlacementsOutput',
'GetPlacementInput',
'CreatePlacementInput',
'UpdatePlacementInput',
'DeletePlacementInput',
'PlacementViewsHistoryOutput',
'GetViewsHistoryInput',
'GetViewsHistoryOutput',
'FetchViewsInputManually',
@@ -57,14 +57,14 @@ from .external_channel import (
UpdateExternalChannelInput,
UpdateExternalChannelLinksInput,
)
from .purchase import (
CreatePurchaseInput,
DeletePurchaseInput,
GetPurchaseInput,
GetPurchasesInput,
GetPurchasesOutput,
PurchaseOutput,
UpdatePurchaseInput,
from .placement import (
CreatePlacementInput,
DeletePlacementInput,
GetPlacementInput,
GetPlacementsInput,
GetPlacementsOutput,
PlacementOutput,
UpdatePlacementInput,
)
from .target_channel import (
ChannelBotPermissions,
@@ -83,6 +83,6 @@ from .views import (
FetchViewsManuallyOutput,
GetViewsHistoryInput,
GetViewsHistoryOutput,
PlacementViewsHistoryOutput,
UpdateViewsManuallyInput,
ViewsSnapshotOutput,
)

View File

@@ -14,7 +14,7 @@ class CreativeOutput(pydantic.BaseModel):
target_channel_title: str
created_at: datetime.datetime
status: domain.CreativeStatus
purchases_count: int
placements_count: int
class GetCreativesInput(pydantic.BaseModel):

View File

@@ -6,7 +6,7 @@ import pydantic
from src import domain
class PurchaseOutput(pydantic.BaseModel):
class PlacementOutput(pydantic.BaseModel):
id: uuid.UUID
target_channel_id: uuid.UUID
target_channel_title: str
@@ -20,7 +20,7 @@ class PurchaseOutput(pydantic.BaseModel):
ad_post_url: str | None
invite_link_type: domain.InviteLinkType
invite_link: str
status: domain.PurchaseStatus
status: domain.PlacementStatus
subscriptions_count: int
views_count: int | None
views_availability: domain.PostViewsAvailability
@@ -28,7 +28,7 @@ class PurchaseOutput(pydantic.BaseModel):
created_at: datetime.datetime
class GetPurchasesInput(pydantic.BaseModel):
class GetPlacementsInput(pydantic.BaseModel):
user_id: uuid.UUID
target_channel_id: uuid.UUID | None = None
external_channel_id: uuid.UUID | None = None
@@ -36,16 +36,16 @@ class GetPurchasesInput(pydantic.BaseModel):
include_archived: bool = False
class GetPurchasesOutput(pydantic.BaseModel):
purchases: list[PurchaseOutput]
class GetPlacementsOutput(pydantic.BaseModel):
placements: list[PlacementOutput]
class GetPurchaseInput(pydantic.BaseModel):
purchase_id: uuid.UUID
class GetPlacementInput(pydantic.BaseModel):
placement_id: uuid.UUID
user_id: uuid.UUID
class CreatePurchaseInput(pydantic.BaseModel):
class CreatePlacementInput(pydantic.BaseModel):
target_channel_id: uuid.UUID
external_channel_id: uuid.UUID
creative_id: uuid.UUID
@@ -56,14 +56,14 @@ class CreatePurchaseInput(pydantic.BaseModel):
invite_link_type: domain.InviteLinkType = domain.InviteLinkType.PUBLIC
class UpdatePurchaseInput(pydantic.BaseModel):
class UpdatePlacementInput(pydantic.BaseModel):
placement_date: datetime.datetime | None = None
cost: float | None = None
comment: str | None = None
ad_post_url: str | None = None
status: domain.PurchaseStatus | None = None
status: domain.PlacementStatus | None = None
class DeletePurchaseInput(pydantic.BaseModel):
purchase_id: uuid.UUID
class DeletePlacementInput(pydantic.BaseModel):
placement_id: uuid.UUID
user_id: uuid.UUID

View File

@@ -6,11 +6,11 @@ import pydantic
from src import domain
class ViewsSnapshotOutput(pydantic.BaseModel):
"""Снимок просмотров."""
class PlacementViewsHistoryOutput(pydantic.BaseModel):
"""История просмотров placement."""
id: uuid.UUID
purchase_id: uuid.UUID
placement_id: uuid.UUID
views_count: int
fetched_at: datetime.datetime
created_at: datetime.datetime
@@ -19,7 +19,7 @@ class ViewsSnapshotOutput(pydantic.BaseModel):
class GetViewsHistoryInput(pydantic.BaseModel):
"""Получить историю просмотров для закупа."""
purchase_id: uuid.UUID
placement_id: uuid.UUID
user_id: uuid.UUID
from_date: datetime.datetime | None = None # Фильтр: с какой даты
to_date: datetime.datetime | None = None # Фильтр: по какую дату
@@ -28,18 +28,18 @@ class GetViewsHistoryInput(pydantic.BaseModel):
class GetViewsHistoryOutput(pydantic.BaseModel):
"""История просмотров."""
snapshots: list[ViewsSnapshotOutput]
histories: list[PlacementViewsHistoryOutput]
class FetchViewsInputManually(pydantic.BaseModel):
"""Запросить обновление просмотров для закупа."""
purchase_id: uuid.UUID
placement_id: uuid.UUID
user_id: uuid.UUID
class FetchViewsManuallyOutput(pydantic.BaseModel):
purchase_id: uuid.UUID
placement_id: uuid.UUID
views_count: int | None # None если не удалось получить
views_availability: domain.PostViewsAvailability
fetched_at: datetime.datetime
@@ -49,6 +49,6 @@ class FetchViewsManuallyOutput(pydantic.BaseModel):
class UpdateViewsManuallyInput(pydantic.BaseModel):
"""Ручное обновление просмотров."""
purchase_id: uuid.UUID
placement_id: uuid.UUID
user_id: uuid.UUID
views_count: int

View File

@@ -15,11 +15,11 @@ from .external_channel.delete_external_channel import delete_external_channel
from .external_channel.get_external_channels import get_external_channels
from .external_channel.update_external_channel import update_external_channel
from .external_channel.update_external_channel_links import update_external_channel_links
from .purchase.create_purchase import create_purchase
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 .placement.create_placement import create_placement
from .placement.delete_placement import delete_placement
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 .target_channel.connect_target_chan import connect_target_chan
from .target_channel.disconnect_target_chan import disconnect_target_chan
@@ -95,13 +95,13 @@ class Database(typing.Protocol):
async def delete_creative(self, creative_id: UUID) -> None: ...
async def get_purchase(self, user_id: UUID, purchase_id: UUID) -> domain.Purchase | None: ...
async def get_placement(self, user_id: UUID, placement_id: UUID) -> domain.Placement | None: ...
async def create_purchase(self, purchase: domain.Purchase) -> domain.Purchase: ...
async def create_placement(self, placement: domain.Placement) -> domain.Placement: ...
async def update_purchase(self, purchase: domain.Purchase) -> domain.Purchase: ...
async def update_placement(self, placement: domain.Placement) -> domain.Placement: ...
async def get_user_purchases(
async def get_user_placements(
self,
user_id: UUID,
*,
@@ -109,31 +109,39 @@ class Database(typing.Protocol):
external_channel_id: UUID | None = None,
creative_id: UUID | None = None,
include_archived: bool = False,
) -> list[domain.Purchase]: ...
) -> list[domain.Placement]: ...
async def delete_purchase(self, purchase_id: UUID) -> None: ...
async def delete_placement(self, placement_id: UUID) -> None: ...
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 get_placement_by_invite_link(self, invite_link: str) -> domain.Placement | None: ...
async def get_subscriber(self, telegram_id: int) -> domain.Subscriber | None: ...
async def create_subscriber(self, subscriber: domain.Subscriber) -> domain.Subscriber: ...
async def upsert_subscriber(self, subscriber: domain.Subscriber) -> domain.Subscriber: ...
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
async def get_subscription_by_subscriber_and_placement(
self, subscriber_id: UUID, placement_id: UUID
) -> domain.Subscription | None: ...
async def create_views_snapshot(self, snapshot: domain.ViewsSnapshot) -> domain.ViewsSnapshot: ...
async def create_placement_views_history(
self, history: domain.PlacementViewsHistory
) -> domain.PlacementViewsHistory: ...
async def get_views_history(
self,
purchase_id: UUID,
placement_id: UUID,
*,
from_date: datetime.datetime | None = None,
to_date: datetime.datetime | None = None,
) -> list[domain.ViewsSnapshot]: ...
) -> list[domain.PlacementViewsHistory]: ...
async def get_active_purchases_with_urls(self) -> list[domain.Purchase]: ... # Для worker
async def get_active_placements_with_urls(self) -> list[domain.Placement]: ... # Для worker
class TelegramBotWriter(typing.Protocol):
@@ -178,11 +186,11 @@ class Usecase:
create_creative = create_creative
update_creative = update_creative
delete_creative = delete_creative
get_purchases = get_purchases
get_purchase = get_purchase
create_purchase = create_purchase
update_purchase = update_purchase
delete_purchase = delete_purchase
get_placements = get_placements
get_placement = get_placement
create_placement = create_placement
update_placement = update_placement
delete_placement = delete_placement
handle_subscription = handle_subscription
fetch_views = fetch_views_manually
run_views_worker_cycle = run_views_worker_cycle

View File

@@ -37,5 +37,5 @@ async def create_creative(self: 'Usecase', input: dto.CreateCreativeInput, user_
target_channel_title=created.target_channel.title,
created_at=created.created_at,
status=created.status,
purchases_count=created.purchases_count,
placements_count=created.placements_count,
)

View File

@@ -16,8 +16,8 @@ async def delete_creative(self: 'Usecase', input: dto.DeleteCreativeInput) -> No
log.warning('User %s attempted to delete unavailable creative %s', input.user_id, input.creative_id)
raise domain.CreativeNotFound(input.creative_id)
if creative.purchases_count > 0:
log.warning('Creative %s is used in purchases and cannot be deleted', input.creative_id)
if creative.placements_count > 0:
log.warning('Creative %s is used in placements and cannot be deleted', input.creative_id)
raise domain.CreativeInUse(input.creative_id)
await self.database.delete_creative(input.creative_id)

View File

@@ -24,5 +24,5 @@ async def get_creative(self: 'Usecase', input: dto.GetCreativeInput) -> dto.Crea
target_channel_title=creative.target_channel.title,
created_at=creative.created_at,
status=creative.status,
purchases_count=creative.purchases_count,
placements_count=creative.placements_count,
)

View File

@@ -22,7 +22,7 @@ async def get_creatives(self: 'Usecase', input: dto.GetCreativesInput) -> dto.Ge
target_channel_title=creative.target_channel.title,
created_at=creative.created_at,
status=creative.status,
purchases_count=creative.purchases_count,
placements_count=creative.placements_count,
)
for creative in creatives
]

View File

@@ -36,5 +36,5 @@ async def update_creative(
target_channel_title=updated.target_channel.title,
created_at=updated.created_at,
status=updated.status,
purchases_count=updated.purchases_count,
placements_count=updated.placements_count,
)

View File

@@ -10,13 +10,13 @@ if TYPE_CHECKING:
log = logging.getLogger(__name__)
async def create_purchase(self: 'Usecase', input: dto.CreatePurchaseInput, user_id: uuid.UUID) -> dto.PurchaseOutput:
async def create_placement(self: 'Usecase', input: dto.CreatePlacementInput, user_id: uuid.UUID) -> dto.PlacementOutput:
async with self.database.transaction():
# Проверяем существование целевого канала
target_channel = await self.database.get_target_channel(user_id, channel_id=input.target_channel_id)
if not target_channel:
log.warning(
'User %s attempted to create purchase for unavailable target %s', user_id, input.target_channel_id
'User %s attempted to create placement for unavailable target %s', user_id, input.target_channel_id
)
raise domain.TargetChannelNotFound(input.target_channel_id)
@@ -24,14 +24,14 @@ async def create_purchase(self: 'Usecase', input: dto.CreatePurchaseInput, user_
external_channel = await self.database.get_external_channel(user_id, channel_id=input.external_channel_id)
if not external_channel:
log.warning(
'User %s attempted to create purchase for unavailable external %s', user_id, input.external_channel_id
'User %s attempted to create placement for unavailable external %s', user_id, input.external_channel_id
)
raise domain.ExternalChannelNotFound(input.external_channel_id)
# Проверяем существование креатива
creative = await self.database.get_creative(user_id, input.creative_id)
if not creative:
log.warning('User %s attempted to create purchase for unavailable creative %s', user_id, input.creative_id)
log.warning('User %s attempted to create placement for unavailable creative %s', user_id, input.creative_id)
raise domain.CreativeNotFound(input.creative_id)
# Создаём уникальную пригласительную ссылку через Telegram Bot API
@@ -42,7 +42,7 @@ async def create_purchase(self: 'Usecase', input: dto.CreatePurchaseInput, user_
)
# Создаём закуп
purchase = domain.Purchase(
placement = domain.Placement(
target_channel_id=input.target_channel_id,
external_channel_id=input.external_channel_id,
creative_id=input.creative_id,
@@ -53,17 +53,17 @@ async def create_purchase(self: 'Usecase', input: dto.CreatePurchaseInput, user_
ad_post_url=input.ad_post_url,
invite_link_type=input.invite_link_type,
invite_link=invite_link,
status=domain.PurchaseStatus.ACTIVE,
status=domain.PlacementStatus.ACTIVE,
)
created = await self.database.create_purchase(purchase)
created = await self.database.create_placement(placement)
# Увеличиваем счётчик закупов у креатива
creative.purchases_count += 1
creative.placements_count += 1
await self.database.update_creative(creative)
# Формируем ответ внутри транзакции, пока объекты в сессии
return dto.PurchaseOutput(
return dto.PlacementOutput(
id=created.id,
target_channel_id=created.target_channel_id,
target_channel_title=target_channel.title,

View File

@@ -0,0 +1,26 @@
import logging
from typing import TYPE_CHECKING
from src import domain, dto
if TYPE_CHECKING:
from .. import Usecase
log = logging.getLogger(__name__)
async def delete_placement(self: 'Usecase', input: dto.DeletePlacementInput) -> None:
async with self.database.transaction():
placement = await self.database.get_placement(input.user_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 placement.status == domain.PlacementStatus.ACTIVE:
creative = await self.database.get_creative(input.user_id, placement.creative_id)
if creative and creative.placements_count > 0:
creative.placements_count -= 1
await self.database.update_creative(creative)
await self.database.delete_placement(input.placement_id)

View File

@@ -0,0 +1,39 @@
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_placement(self: 'Usecase', input: dto.GetPlacementInput) -> dto.PlacementOutput:
async with self.database.transaction():
placement = await self.database.get_placement(input.user_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)
return dto.PlacementOutput(
id=placement.id,
target_channel_id=placement.target_channel_id,
target_channel_title=placement.target_channel.title,
external_channel_id=placement.external_channel_id,
external_channel_title=placement.external_channel.title,
creative_id=placement.creative_id,
creative_name=placement.creative.name,
placement_date=placement.placement_date,
cost=placement.cost,
comment=placement.comment,
ad_post_url=placement.ad_post_url,
invite_link_type=placement.invite_link_type,
invite_link=placement.invite_link,
status=placement.status,
subscriptions_count=placement.subscriptions_count,
views_count=placement.views_count,
views_availability=placement.views_availability,
last_views_fetch_at=placement.last_views_fetch_at,
created_at=placement.created_at,
)

View File

@@ -0,0 +1,44 @@
from typing import TYPE_CHECKING
from src import dto
if TYPE_CHECKING:
from .. import Usecase
async def get_placements(self: 'Usecase', input: dto.GetPlacementsInput) -> dto.GetPlacementsOutput:
async with self.database.transaction():
placements = await self.database.get_user_placements(
input.user_id,
target_channel_id=input.target_channel_id,
external_channel_id=input.external_channel_id,
creative_id=input.creative_id,
include_archived=input.include_archived,
)
return dto.GetPlacementsOutput(
placements=[
dto.PlacementOutput(
id=placement.id,
target_channel_id=placement.target_channel_id,
target_channel_title=placement.target_channel.title,
external_channel_id=placement.external_channel_id,
external_channel_title=placement.external_channel.title,
creative_id=placement.creative_id,
creative_name=placement.creative.name,
placement_date=placement.placement_date,
cost=placement.cost,
comment=placement.comment,
ad_post_url=placement.ad_post_url,
invite_link_type=placement.invite_link_type,
invite_link=placement.invite_link,
status=placement.status,
subscriptions_count=placement.subscriptions_count,
views_count=placement.views_count,
views_availability=placement.views_availability,
last_views_fetch_at=placement.last_views_fetch_at,
created_at=placement.created_at,
)
for placement in placements
]
)

View File

@@ -10,30 +10,30 @@ if TYPE_CHECKING:
log = logging.getLogger(__name__)
async def update_purchase(
self: 'Usecase', purchase_id: uuid.UUID, input: dto.UpdatePurchaseInput, user_id: uuid.UUID
) -> dto.PurchaseOutput:
async def update_placement(
self: 'Usecase', placement_id: uuid.UUID, input: dto.UpdatePlacementInput, user_id: uuid.UUID
) -> dto.PlacementOutput:
async with self.database.transaction():
purchase = await self.database.get_purchase(user_id, purchase_id)
if not purchase:
log.warning('Purchase %s not found for user %s', purchase_id, user_id)
raise domain.PurchaseNotFound(purchase_id)
placement = await self.database.get_placement(user_id, placement_id)
if not placement:
log.warning('Placement %s not found for user %s', placement_id, user_id)
raise domain.PlacementNotFound(placement_id)
# Обновляем только те поля, которые были переданы
if input.placement_date is not None:
purchase.placement_date = input.placement_date
placement.placement_date = input.placement_date
if input.cost is not None:
purchase.cost = input.cost
placement.cost = input.cost
if input.comment is not None:
purchase.comment = input.comment
placement.comment = input.comment
if input.ad_post_url is not None:
purchase.ad_post_url = input.ad_post_url
placement.ad_post_url = input.ad_post_url
if input.status is not None:
purchase.status = input.status
placement.status = input.status
updated = await self.database.update_purchase(purchase)
updated = await self.database.update_placement(placement)
return dto.PurchaseOutput(
return dto.PlacementOutput(
id=updated.id,
target_channel_id=updated.target_channel_id,
target_channel_title=updated.target_channel.title,

View File

@@ -1,26 +0,0 @@
import logging
from typing import TYPE_CHECKING
from src import domain, dto
if TYPE_CHECKING:
from .. import Usecase
log = logging.getLogger(__name__)
async def delete_purchase(self: 'Usecase', input: dto.DeletePurchaseInput) -> None:
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 purchase.status == domain.PurchaseStatus.ACTIVE:
creative = await self.database.get_creative(input.user_id, purchase.creative_id)
if creative and creative.purchases_count > 0:
creative.purchases_count -= 1
await self.database.update_creative(creative)
await self.database.delete_purchase(input.purchase_id)

View File

@@ -1,39 +0,0 @@
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_purchase(self: 'Usecase', input: dto.GetPurchaseInput) -> 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)
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

@@ -1,44 +0,0 @@
from typing import TYPE_CHECKING
from src import dto
if TYPE_CHECKING:
from .. import Usecase
async def get_purchases(self: 'Usecase', input: dto.GetPurchasesInput) -> dto.GetPurchasesOutput:
async with self.database.transaction():
purchases = await self.database.get_user_purchases(
input.user_id,
target_channel_id=input.target_channel_id,
external_channel_id=input.external_channel_id,
creative_id=input.creative_id,
include_archived=input.include_archived,
)
return dto.GetPurchasesOutput(
purchases=[
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,
)
for purchase in purchases
]
)

View File

@@ -14,6 +14,8 @@ async def handle_subscription(
user_telegram_id: int,
username: str | None,
invite_link: str,
first_name: str | None = None,
last_name: str | None = None,
) -> None:
"""
Обрабатывает подписку пользователя в целевой канал.
@@ -23,37 +25,48 @@ async def handle_subscription(
"""
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)
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,
first_name=first_name,
last_name=last_name,
)
subscriber = await self.database.upsert_subscriber(subscriber)
# Проверяем, не создана ли уже подписка для этого пользователя
existing_subscription = await self.database.get_subscription_by_user_and_purchase(user_telegram_id, purchase.id)
existing_subscription = await self.database.get_subscription_by_subscriber_and_placement(
subscriber.id, placement.id
)
if existing_subscription:
log.info(
'Subscription already exists for user %s and purchase %s',
user_telegram_id,
purchase.id,
'Subscription already exists for subscriber %s and placement %s',
subscriber.id,
placement.id,
)
return
# Создаём запись о подписке
subscription = domain.Subscription(
purchase_id=purchase.id,
user_telegram_id=user_telegram_id,
username=username,
placement_id=placement.id,
subscriber_id=subscriber.id,
invite_link=invite_link,
)
await self.database.create_subscription(subscription)
# Увеличиваем счётчик подписок у закупа
purchase.subscriptions_count += 1
await self.database.update_purchase(purchase)
placement.subscriptions_count += 1
await self.database.update_placement(placement)
log.info(
'Subscription created: user %s subscribed via purchase %s (invite_link: %s)',
'Subscription created: subscriber %s (telegram_id: %s) subscribed via placement %s (invite_link: %s)',
subscriber.id,
user_telegram_id,
purchase.id,
placement.id,
invite_link,
)

View File

@@ -12,52 +12,52 @@ log = logging.getLogger(__name__)
async def fetch_views_manually(self: 'Usecase', input: dto.FetchViewsInputManually) -> dto.FetchViewsManuallyOutput:
async with self.database.transaction():
purchase = await self.database.get_purchase(input.user_id, input.purchase_id)
if not purchase:
raise domain.PurchaseNotFound(input.purchase_id)
placement = await self.database.get_placement(input.user_id, input.placement_id)
if not placement:
raise domain.PlacementNotFound(input.placement_id)
if not purchase.ad_post_url:
if not placement.ad_post_url:
return dto.FetchViewsManuallyOutput(
purchase_id=purchase.id,
placement_id=placement.id,
views_count=None,
views_availability=domain.PostViewsAvailability.UNAVAILABLE,
fetched_at=datetime.datetime.now(datetime.UTC),
error_message='No ad_post_url specified',
)
views_count = await self.telegram_parser.get_post_views(purchase.ad_post_url)
views_count = await self.telegram_parser.get_post_views(placement.ad_post_url)
fetched_at = datetime.datetime.now(datetime.UTC)
if views_count:
purchase.views_count = views_count
purchase.views_availability = domain.PostViewsAvailability.AVAILABLE
purchase.last_views_fetch_at = fetched_at
await self.database.update_purchase(purchase)
placement.views_count = views_count
placement.views_availability = domain.PostViewsAvailability.AVAILABLE
placement.last_views_fetch_at = fetched_at
await self.database.update_placement(placement)
snapshot = domain.ViewsSnapshot(
purchase_id=purchase.id,
history = domain.PlacementViewsHistory(
placement_id=placement.id,
views_count=views_count,
fetched_at=fetched_at,
)
await self.database.create_views_snapshot(snapshot)
await self.database.create_placement_views_history(history)
log.info('Views fetched for purchase %s: %d', purchase.id, views_count)
log.info('Views fetched for placement %s: %d', placement.id, views_count)
return dto.FetchViewsManuallyOutput(
purchase_id=purchase.id,
placement_id=placement.id,
views_count=views_count,
views_availability=domain.PostViewsAvailability.AVAILABLE,
fetched_at=fetched_at,
)
purchase.views_availability = domain.PostViewsAvailability.UNAVAILABLE
purchase.last_views_fetch_at = fetched_at
await self.database.update_purchase(purchase)
placement.views_availability = domain.PostViewsAvailability.UNAVAILABLE
placement.last_views_fetch_at = fetched_at
await self.database.update_placement(placement)
log.warning('Failed to fetch views for purchase %s', purchase.id)
log.warning('Failed to fetch views for placement %s', placement.id)
return dto.FetchViewsManuallyOutput(
purchase_id=purchase.id,
placement_id=placement.id,
views_count=None,
views_availability=domain.PostViewsAvailability.UNAVAILABLE,
fetched_at=fetched_at,

View File

@@ -12,26 +12,26 @@ 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)
placement = await self.database.get_placement(input.user_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)
snapshots = await self.database.get_views_history(
input.purchase_id,
histories = await self.database.get_views_history(
input.placement_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,
histories=[
dto.PlacementViewsHistoryOutput(
id=history.id,
placement_id=history.placement_id,
views_count=history.views_count,
fetched_at=history.fetched_at,
created_at=history.created_at,
)
for snapshot in snapshots
for history in histories
]
)

View File

@@ -1,6 +1,7 @@
import asyncio
import datetime
import logging
import uuid
from typing import TYPE_CHECKING, cast
from aiolimiter import AsyncLimiter
@@ -13,53 +14,55 @@ if TYPE_CHECKING:
log = logging.getLogger(__name__)
async def _process_purchase(self: 'Usecase', purchase_id, user_id, ad_post_url: str):
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)
async with self.database.transaction():
p = await self.database.get_purchase(user_id=user_id, purchase_id=purchase_id)
p = await self.database.get_placement(user_id=user_id, placement_id=placement_id)
if not p:
log.error('Purchase %s not found', purchase_id)
log.error('Placement %s not found', placement_id)
return
p.last_views_fetch_at = fetched_at
if not views_count:
p.views_availability = domain.PostViewsAvailability.UNAVAILABLE
await self.database.update_purchase(p)
log.warning('Failed to fetch views for %s', purchase_id)
await self.database.update_placement(p)
log.warning('Failed to fetch views for %s', placement_id)
return
p.views_count = views_count
p.views_availability = domain.PostViewsAvailability.AVAILABLE
await self.database.update_purchase(p)
await self.database.update_placement(p)
snapshot = domain.ViewsSnapshot(
purchase_id=purchase_id,
history = domain.PlacementViewsHistory(
placement_id=placement_id,
views_count=views_count,
fetched_at=fetched_at,
)
await self.database.create_views_snapshot(snapshot)
await self.database.create_placement_views_history(history)
log.info('Updated purchase %s: %d', purchase_id, views_count)
log.info('Updated placement %s: %d', placement_id, views_count)
async def run_views_worker_cycle(self: 'Usecase', interval_seconds: int) -> None:
async with self.database.transaction():
purchases = await self.database.get_active_purchases_with_urls()
placements = await self.database.get_active_placements_with_urls()
if not purchases:
log.debug('ViewsWorkerCycle: No purchases to process')
if not placements:
log.debug('ViewsWorkerCycle: No placements to process')
return
limiter = AsyncLimiter(max_rate=len(purchases), time_period=interval_seconds)
log.info('Processing %d purchases for %d seconds', len(purchases), interval_seconds)
limiter = AsyncLimiter(max_rate=len(placements), time_period=interval_seconds)
log.info('Processing %d placements for %d seconds', len(placements), interval_seconds)
async def process(p):
async def process(p: domain.Placement) -> None:
async with limiter:
try:
await _process_purchase(self, p.id, p.user_id, cast(str, p.ad_post_url))
await _process_placement(self, p.id, p.user_id, cast(str, p.ad_post_url))
except Exception:
log.exception('Error updating views for %s', p.id)
await asyncio.gather(*(process(p) for p in purchases))
await asyncio.gather(*(process(p) for p in placements))

View File

@@ -10,47 +10,47 @@ if TYPE_CHECKING:
log = logging.getLogger(__name__)
async def update_views_manually(self: 'Usecase', input: dto.UpdateViewsManuallyInput) -> dto.PurchaseOutput:
async def update_views_manually(self: 'Usecase', input: dto.UpdateViewsManuallyInput) -> dto.PlacementOutput:
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)
placement = await self.database.get_placement(input.user_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)
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)
placement.views_count = input.views_count
placement.views_availability = domain.PostViewsAvailability.MANUAL
placement.last_views_fetch_at = fetched_at
await self.database.update_placement(placement)
snapshot = domain.ViewsSnapshot(
purchase_id=purchase.id,
history = domain.PlacementViewsHistory(
placement_id=placement.id,
views_count=input.views_count,
fetched_at=fetched_at,
)
await self.database.create_views_snapshot(snapshot)
await self.database.create_placement_views_history(history)
log.info('Views manually updated for purchase %s: %d', purchase.id, input.views_count)
log.info('Views manually updated for placement %s: %d', placement.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,
return dto.PlacementOutput(
id=placement.id,
target_channel_id=placement.target_channel_id,
target_channel_title=placement.target_channel.title,
external_channel_id=placement.external_channel_id,
external_channel_title=placement.external_channel.title,
creative_id=placement.creative_id,
creative_name=placement.creative.name,
placement_date=placement.placement_date,
cost=placement.cost,
comment=placement.comment,
ad_post_url=placement.ad_post_url,
invite_link_type=placement.invite_link_type,
invite_link=placement.invite_link,
status=placement.status,
subscriptions_count=placement.subscriptions_count,
views_count=placement.views_count,
views_availability=placement.views_availability,
last_views_fetch_at=placement.last_views_fetch_at,
created_at=placement.created_at,
)