ref: рефакторинг usecases

This commit is contained in:
Artem Tsyrulnikov
2025-12-11 18:02:46 +03:00
parent 38f1b3feba
commit 1f80d9bdfb
47 changed files with 853 additions and 3454 deletions

View File

@@ -50,11 +50,11 @@ class Database(typing.Protocol):
async def get_user(self, user_id: UUID | None = None, telegram_id: int | None = None) -> domain.User | None: ...
async def create_user(self, user: domain.User) -> domain.User: ...
async def create_user(self, user: domain.User) -> None: ...
async def create_login_token(
self, user_id: UUID, token: str, expires_at: datetime.datetime
) -> domain.LoginToken: ...
async def create_login_token(self, login_token: domain.LoginToken) -> None: ...
async def create_creative(self, creative: domain.Creative) -> None: ...
async def get_login_token(self, token: str) -> domain.LoginToken | None: ...
@@ -64,17 +64,17 @@ class Database(typing.Protocol):
self, user_id: UUID, channel_id: UUID | None = None, telegram_id: int | None = None
) -> domain.TargetChannel | None: ...
async def upsert_target_channel(self, channel: domain.TargetChannel) -> domain.TargetChannel: ...
async def upsert_target_channel(self, channel: domain.TargetChannel) -> None: ...
async def get_user_target_channels(self, user_id: UUID) -> list[domain.TargetChannel]: ...
async def update_target_channel(self, channel: domain.TargetChannel) -> domain.TargetChannel: ...
async def update_target_channel(self, channel: domain.TargetChannel) -> None: ...
async def get_external_channel(
self, user_id: UUID, channel_id: UUID | None = None, telegram_id: int | None = None
) -> domain.ExternalChannel | None: ...
async def create_external_channel(self, channel: domain.ExternalChannel) -> domain.ExternalChannel: ...
async def create_external_channel(self, channel: domain.ExternalChannel) -> None: ...
async def get_external_channels_for_target(self, target_channel_id: UUID) -> list[domain.ExternalChannel]: ...
@@ -88,13 +88,11 @@ class Database(typing.Protocol):
async def delete_external_channel(self, channel_id: UUID) -> None: ...
async def update_external_channel(self, channel: domain.ExternalChannel) -> domain.ExternalChannel: ...
async def update_external_channel(self, channel: domain.ExternalChannel) -> None: ...
async def get_creative(self, user_id: UUID, creative_id: UUID) -> domain.Creative | None: ...
async def create_creative(self, creative: domain.Creative) -> domain.Creative: ...
async def update_creative(self, creative: domain.Creative) -> domain.Creative: ...
async def update_creative(self, creative: domain.Creative) -> None: ...
async def get_user_creatives(
self, user_id: UUID, target_channel_id: UUID | None = None, include_archived: bool = False
@@ -104,9 +102,9 @@ class Database(typing.Protocol):
async def get_placement(self, user_id: UUID, placement_id: UUID) -> domain.Placement | None: ...
async def create_placement(self, placement: domain.Placement) -> domain.Placement: ...
async def create_placement(self, placement: domain.Placement) -> None: ...
async def update_placement(self, placement: domain.Placement) -> domain.Placement: ...
async def update_placement(self, placement: domain.Placement) -> None: ...
async def get_user_placements(
self,
@@ -123,17 +121,15 @@ class Database(typing.Protocol):
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) -> None: ...
async def upsert_subscriber(self, subscriber: domain.Subscriber) -> domain.Subscriber: ...
async def create_subscription(self, subscription: domain.Subscription) -> domain.Subscription: ...
async def create_subscription(self, subscription: domain.Subscription) -> None: ...
async def get_subscription_by_subscriber_and_placement(
self, subscriber_id: UUID, placement_id: UUID
) -> domain.Subscription | None: ...
async def update_subscription(self, subscription: domain.Subscription) -> domain.Subscription: ...
async def update_subscription(self, subscription: domain.Subscription) -> None: ...
async def get_active_subscriptions_by_subscriber_and_channel(
self, subscriber_id: UUID, channel_telegram_id: int
@@ -143,9 +139,7 @@ class Database(typing.Protocol):
self, subscriber_id: UUID, channel_telegram_id: int
) -> domain.Subscription | None: ...
async def create_placement_views_history(
self, history: domain.PlacementViewsHistory
) -> domain.PlacementViewsHistory: ...
async def create_placement_views_history(self, history: domain.PlacementViewsHistory) -> None: ...
async def get_views_history(
self,
@@ -163,17 +157,6 @@ class Database(typing.Protocol):
async def clear_telegram_state(self, telegram_id: int) -> None: ...
# NATS-related methods for placement tracking
async def get_placement_by_id(self, placement_id: UUID) -> domain.Placement | None: ...
async def update_placement_from_post_found(
self, placement_id: UUID, ad_post_url: str, message_id: int, views_count: int
) -> domain.Placement: ...
async def update_placement_from_post_deleted(self, placement_id: UUID) -> domain.Placement: ...
async def update_placement_views(self, placement_id: UUID, views_count: int) -> domain.Placement: ...
class TelegramBotWriter(typing.Protocol):
async def send_message(self, text: str, chat_id: int) -> None: ...
@@ -186,8 +169,6 @@ class TelegramBotWriter(typing.Protocol):
async def edit_message_reply_markup(self, chat_id: int, message_id: int) -> None: ...
async def get_chat_member(self, chat_id: int, user_id: int) -> dict[str, typing.Any]: ...
async def create_chat_invite_link(self, chat_id: int, requires_approval: bool = False) -> str: ...

View File

@@ -14,65 +14,57 @@ log = logging.getLogger(__name__)
async def get_creatives_analytics(
self: 'Usecase', input: dto.GetCreativesAnalyticsInput
) -> dto.GetCreativesAnalyticsOutput:
async with self.database.transaction():
if input.target_channel_id:
target_channel = await self.database.get_target_channel(input.user_id, input.target_channel_id)
if not target_channel:
raise domain.TargetChannelNotFound(input.target_channel_id)
if input.target_channel_id:
target_channel = await self.database.get_target_channel(input.user_id, input.target_channel_id)
if not target_channel:
raise domain.TargetChannelNotFound(input.target_channel_id)
creatives = await self.database.get_user_creatives(
input.user_id, input.target_channel_id, include_archived=False
creatives = await self.database.get_user_creatives(input.user_id, input.target_channel_id, include_archived=False)
placements = await self.database.get_user_placements(input.user_id, input.target_channel_id, include_archived=False)
@dataclass
class CreativeStats:
total_cost: float = 0.0
total_subscriptions: int = 0
total_views: int = 0
placements_count: int = 0
creative_stats: dict[UUID, CreativeStats] = {cr.id: CreativeStats() for cr in creatives}
for p in placements:
stats = creative_stats.get(p.creative_id)
if stats is None:
continue
stats.total_cost += p.cost if p.cost is not None else 0
stats.total_subscriptions += p.subscriptions_count
stats.total_views += p.views_count if p.views_count is not None else 0
stats.placements_count += 1
result = []
for cr in creatives:
stats = creative_stats[cr.id]
avg_cpf = (
(stats.total_cost / stats.total_subscriptions)
if stats.total_subscriptions > 0 and stats.total_cost > 0
else None
)
avg_cpm = (
(stats.total_cost / stats.total_views * 1000) if stats.total_views > 0 and stats.total_cost > 0 else None
)
placements = await self.database.get_user_placements(
input.user_id, input.target_channel_id, include_archived=False
result.append(
dto.CreativeAnalyticsOutput(
id=cr.id,
name=cr.name,
placements_count=stats.placements_count,
total_cost=stats.total_cost,
total_subscriptions=stats.total_subscriptions,
total_views=stats.total_views,
avg_cpf=avg_cpf,
avg_cpm=avg_cpm,
)
)
@dataclass
class CreativeStats:
total_cost: float = 0.0
total_subscriptions: int = 0
total_views: int = 0
placements_count: int = 0
creative_stats: dict[UUID, CreativeStats] = {cr.id: CreativeStats() for cr in creatives}
for p in placements:
stats = creative_stats.get(p.creative_id)
if stats is None:
continue
stats.total_cost += p.cost if p.cost is not None else 0
stats.total_subscriptions += p.subscriptions_count
stats.total_views += p.views_count if p.views_count is not None else 0
stats.placements_count += 1
result = []
for cr in creatives:
stats = creative_stats[cr.id]
avg_cpf = (
(stats.total_cost / stats.total_subscriptions)
if stats.total_subscriptions > 0 and stats.total_cost > 0
else None
)
avg_cpm = (
(stats.total_cost / stats.total_views * 1000)
if stats.total_views > 0 and stats.total_cost > 0
else None
)
result.append(
dto.CreativeAnalyticsOutput(
id=cr.id,
name=cr.name,
placements_count=stats.placements_count,
total_cost=stats.total_cost,
total_subscriptions=stats.total_subscriptions,
total_views=stats.total_views,
avg_cpf=avg_cpf,
avg_cpm=avg_cpm,
)
)
return dto.GetCreativesAnalyticsOutput(creatives=result)
return dto.GetCreativesAnalyticsOutput(creatives=result)

View File

@@ -14,65 +14,60 @@ log = logging.getLogger(__name__)
async def get_external_channels_analytics(
self: 'Usecase', input: dto.GetExternalChannelsAnalyticsInput
) -> dto.GetExternalChannelsAnalyticsOutput:
async with self.database.transaction():
if input.target_channel_id:
target_channel = await self.database.get_target_channel(input.user_id, input.target_channel_id)
if not target_channel:
raise domain.TargetChannelNotFound(input.target_channel_id)
external_channels = await self.database.get_external_channels_for_target(input.target_channel_id)
else:
external_channels = await self.database.get_user_external_channels(input.user_id)
if input.target_channel_id:
target_channel = await self.database.get_target_channel(input.user_id, input.target_channel_id)
if not target_channel:
raise domain.TargetChannelNotFound(input.target_channel_id)
external_channels = await self.database.get_external_channels_for_target(input.target_channel_id)
else:
external_channels = await self.database.get_user_external_channels(input.user_id)
placements = await self.database.get_user_placements(
input.user_id, input.target_channel_id, include_archived=False
placements = await self.database.get_user_placements(input.user_id, input.target_channel_id, include_archived=False)
@dataclass
class ChannelStats:
total_cost: float = 0.0
total_subscriptions: int = 0
total_views: int = 0
placements_count: int = 0
channel_stats: dict[UUID, ChannelStats] = {ch.id: ChannelStats() for ch in external_channels}
for p in placements:
stats = channel_stats.get(p.external_channel_id)
if stats is None:
continue
stats.total_cost += p.cost if p.cost is not None else 0
stats.total_subscriptions += p.subscriptions_count
stats.total_views += p.views_count if p.views_count is not None else 0
stats.placements_count += 1
result = []
for ch in external_channels:
stats = channel_stats[ch.id]
avg_cpf = (
(stats.total_cost / stats.total_subscriptions)
if stats.total_subscriptions > 0 and stats.total_cost > 0
else None
)
avg_cpm = (
(stats.total_cost / stats.total_views * 1000) if stats.total_views > 0 and stats.total_cost > 0 else None
)
@dataclass
class ChannelStats:
total_cost: float = 0.0
total_subscriptions: int = 0
total_views: int = 0
placements_count: int = 0
channel_stats: dict[UUID, ChannelStats] = {ch.id: ChannelStats() for ch in external_channels}
for p in placements:
stats = channel_stats.get(p.external_channel_id)
if stats is None:
continue
stats.total_cost += p.cost if p.cost is not None else 0
stats.total_subscriptions += p.subscriptions_count
stats.total_views += p.views_count if p.views_count is not None else 0
stats.placements_count += 1
result = []
for ch in external_channels:
stats = channel_stats[ch.id]
avg_cpf = (
(stats.total_cost / stats.total_subscriptions)
if stats.total_subscriptions > 0 and stats.total_cost > 0
else None
)
avg_cpm = (
(stats.total_cost / stats.total_views * 1000)
if stats.total_views > 0 and stats.total_cost > 0
else None
result.append(
dto.ExternalChannelAnalyticsOutput(
id=ch.id,
title=ch.title,
username=ch.username,
placements_count=stats.placements_count,
total_cost=stats.total_cost,
total_subscriptions=stats.total_subscriptions,
total_views=stats.total_views,
avg_cpf=avg_cpf,
avg_cpm=avg_cpm,
)
)
result.append(
dto.ExternalChannelAnalyticsOutput(
id=ch.id,
title=ch.title,
username=ch.username,
placements_count=stats.placements_count,
total_cost=stats.total_cost,
total_subscriptions=stats.total_subscriptions,
total_views=stats.total_views,
avg_cpf=avg_cpf,
avg_cpm=avg_cpm,
)
)
return dto.GetExternalChannelsAnalyticsOutput(external_channels=result)
return dto.GetExternalChannelsAnalyticsOutput(external_channels=result)

View File

@@ -24,33 +24,30 @@ def _calculate_cpm(cost: float | None, views: int | None) -> float | None:
async def get_placements_analytics(
self: 'Usecase', input: dto.GetPlacementsAnalyticsInput
) -> dto.GetPlacementsAnalyticsOutput:
async with self.database.transaction():
if input.target_channel_id:
target_channel = await self.database.get_target_channel(input.user_id, input.target_channel_id)
if not target_channel:
raise domain.TargetChannelNotFound(input.target_channel_id)
if input.target_channel_id:
target_channel = await self.database.get_target_channel(input.user_id, input.target_channel_id)
if not target_channel:
raise domain.TargetChannelNotFound(input.target_channel_id)
placements = await self.database.get_user_placements(
input.user_id, input.target_channel_id, include_archived=False
placements = await self.database.get_user_placements(input.user_id, input.target_channel_id, include_archived=False)
result = [
dto.PlacementAnalyticsOutput(
id=p.id,
target_channel_id=p.target_channel_id,
target_channel_title=p.target_channel.title,
external_channel_id=p.external_channel_id,
external_channel_title=p.external_channel.title,
creative_id=p.creative_id,
creative_name=p.creative.name,
placement_date=p.placement_date,
cost=p.cost,
subscriptions_count=p.subscriptions_count,
views_count=p.views_count,
cpf=_calculate_cpf(p.cost, p.subscriptions_count),
cpm=_calculate_cpm(p.cost, p.views_count),
)
for p in placements
]
result = [
dto.PlacementAnalyticsOutput(
id=p.id,
target_channel_id=p.target_channel_id,
target_channel_title=p.target_channel.title,
external_channel_id=p.external_channel_id,
external_channel_title=p.external_channel.title,
creative_id=p.creative_id,
creative_name=p.creative.name,
placement_date=p.placement_date,
cost=p.cost,
subscriptions_count=p.subscriptions_count,
views_count=p.views_count,
cpf=_calculate_cpf(p.cost, p.subscriptions_count),
cpm=_calculate_cpm(p.cost, p.views_count),
)
for p in placements
]
return dto.GetPlacementsAnalyticsOutput(placements=result)
return dto.GetPlacementsAnalyticsOutput(placements=result)

View File

@@ -33,82 +33,79 @@ def _format_period(dt: 'datetime.datetime', grouping: dto.DateGrouping) -> str:
async def get_spending_analytics(
self: 'Usecase', input: dto.GetSpendingAnalyticsInput
) -> dto.GetSpendingAnalyticsOutput:
async with self.database.transaction():
if input.target_channel_id:
target_channel = await self.database.get_target_channel(input.user_id, input.target_channel_id)
if not target_channel:
raise domain.TargetChannelNotFound(input.target_channel_id)
if input.target_channel_id:
target_channel = await self.database.get_target_channel(input.user_id, input.target_channel_id)
if not target_channel:
raise domain.TargetChannelNotFound(input.target_channel_id)
placements = await self.database.get_user_placements(
input.user_id, input.target_channel_id, include_archived=False
)
placements = await self.database.get_user_placements(input.user_id, input.target_channel_id, include_archived=False)
filtered = [
p
for p in placements
if (not input.date_from or p.placement_date >= input.date_from)
and (not input.date_to or p.placement_date <= input.date_to)
]
filtered = [
p
for p in placements
if (not input.date_from or p.placement_date >= input.date_from)
and (not input.date_to or p.placement_date <= input.date_to)
]
total_cost = 0.0
total_subs = 0
total_views = 0
total_cost = 0.0
total_subs = 0
total_views = 0
@dataclass
class PeriodData:
cost: float = 0.0
subscriptions: int = 0
views: int = 0
@dataclass
class PeriodData:
cost: float = 0.0
subscriptions: int = 0
views: int = 0
# Группировка по периодам
period_data: dict[str, PeriodData] = defaultdict(PeriodData)
# Группировка по периодам
period_data: dict[str, PeriodData] = defaultdict(PeriodData)
for p in filtered:
period = _format_period(p.placement_date, input.grouping)
pd = period_data[period]
for p in filtered:
period = _format_period(p.placement_date, input.grouping)
pd = period_data[period]
if p.cost is not None:
total_cost += p.cost
pd.cost += p.cost
if p.cost is not None:
total_cost += p.cost
pd.cost += p.cost
total_subs += p.subscriptions_count
pd.subscriptions += p.subscriptions_count
total_subs += p.subscriptions_count
pd.subscriptions += p.subscriptions_count
if p.views_count is not None:
total_views += p.views_count
pd.views += p.views_count
if p.views_count is not None:
total_views += p.views_count
pd.views += p.views_count
avg_cpf = total_cost / total_subs if total_subs > 0 and total_cost > 0 else None
avg_cpm = (total_cost / total_views * 1000) if total_views > 0 and total_cost > 0 else None
avg_cpf = total_cost / total_subs if total_subs > 0 and total_cost > 0 else None
avg_cpm = (total_cost / total_views * 1000) if total_views > 0 and total_cost > 0 else None
# Данные для графика
chart_data = []
for period in sorted(period_data.keys()):
d = period_data[period]
# Данные для графика
chart_data = []
for period in sorted(period_data.keys()):
d = period_data[period]
cost = d.cost
subs = d.subscriptions
views = d.views
cost = d.cost
subs = d.subscriptions
views = d.views
cpf = cost / subs if subs > 0 and cost > 0 else None
cpm = (cost / views * 1000) if views > 0 and cost > 0 else None
cpf = cost / subs if subs > 0 and cost > 0 else None
cpm = (cost / views * 1000) if views > 0 and cost > 0 else None
chart_data.append(
dto.SpendingDataPoint(
period=period,
cost=cost,
subscriptions=subs,
views=views,
cpf=cpf,
cpm=cpm,
)
chart_data.append(
dto.SpendingDataPoint(
period=period,
cost=cost,
subscriptions=subs,
views=views,
cpf=cpf,
cpm=cpm,
)
return dto.GetSpendingAnalyticsOutput(
total_cost=total_cost,
total_subscriptions=total_subs,
total_views=total_views,
avg_cpf=avg_cpf,
avg_cpm=avg_cpm,
chart_data=chart_data,
)
return dto.GetSpendingAnalyticsOutput(
total_cost=total_cost,
total_subscriptions=total_subs,
total_views=total_views,
avg_cpf=avg_cpf,
avg_cpm=avg_cpm,
chart_data=chart_data,
)

View File

@@ -8,14 +8,13 @@ if typing.TYPE_CHECKING:
async def get_me(self: 'Usecase', user_id: uuid.UUID) -> dto.UserOutput:
async with self.database.transaction():
user = await self.database.get_user(user_id=user_id)
user = await self.database.get_user(user_id=user_id)
if not user:
raise domain.UserNotFound(user_id)
if not user:
raise domain.UserNotFound(user_id)
return dto.UserOutput(
id=user.id,
telegram_id=user.telegram_id,
username=user.username,
)
return dto.UserOutput(
id=user.id,
telegram_id=user.telegram_id,
username=user.username,
)

View File

@@ -2,6 +2,8 @@ import datetime
import secrets
import typing
from tortoise import timezone
from src import domain, dto
from src.config import settings
@@ -10,27 +12,29 @@ if typing.TYPE_CHECKING:
async def telegram_login(self: 'Usecase', input: dto.TelegramLoginInput) -> None:
async with self.database.transaction():
user: domain.User | None = await self.database.get_user(telegram_id=input.telegram_id)
user = await self.database.get_user(telegram_id=input.telegram_id)
if not user:
user = domain.User(
telegram_id=input.telegram_id,
username=input.username,
)
await self.database.create_user(user)
if not user:
user = domain.User(
telegram_id=input.telegram_id,
username=input.username,
)
user = await self.database.create_user(user)
token = secrets.token_urlsafe(32)
expires_at = timezone.now() + datetime.timedelta(minutes=10)
token = secrets.token_urlsafe(32)
expires_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(minutes=10)
login_token = domain.LoginToken(
token=token,
user=user,
expires_at=expires_at,
)
await self.database.create_login_token(login_token)
await self.database.create_login_token(user.id, token, expires_at)
login_url = f'{settings.app.URL}{login_token.token}'
login_url = f'{settings.app.URL}{token}'
username_display = f'@{user.username}' if user.username else 'пользователь'
await self.telegram_bot.send_message_with_button(
f'Привет, {username_display}!\n\nНажми кнопку ниже для входа на сайт.',
chat_id=input.chat_id,
f'Привет, {user.username or "аноним"}!\n\nНажми кнопку ниже для входа на сайт.',
input.chat_id,
button_text='Войти на сайт',
button_url=login_url,
)

View File

@@ -8,13 +8,12 @@ log = logging.getLogger(__name__)
async def telegram_start(self: 'Usecase', telegram_id: int, chat_id: int) -> None:
async with self.database.transaction():
user = await self.database.get_user(telegram_id=telegram_id)
user = await self.database.get_user(telegram_id=telegram_id)
if user:
username_display = f'@{user.username}' if user.username else 'пользователь'
message = f'Привет, {username_display}! 👋\n\nДоступные команды:\n/new_creative - Создать новый креатив'
else:
message = 'Привет! 👋\n\nДля работы с ботом необходимо авторизоваться через веб-интерфейс.'
if not user:
message = 'Привет! 👋\n\nДля работы с ботом необходимо авторизоваться через веб-интерфейс.'
await self.telegram_bot.send_message(message, chat_id)
return
await self.telegram_bot.send_message(message, chat_id=chat_id)
message = f'Привет, {user.username or "аноним"}! 👋\n\nДоступные команды:\n/new_creative - Создать новый креатив'
await self.telegram_bot.send_message(message, chat_id)

View File

@@ -1,6 +1,7 @@
import datetime
import typing
from tortoise import timezone
from src import domain, dto
if typing.TYPE_CHECKING:
@@ -8,25 +9,23 @@ if typing.TYPE_CHECKING:
async def validate_login_token(self: 'Usecase', input: dto.ValidateLoginTokenInput) -> dto.ValidateLoginTokenOutput:
async with self.database.transaction():
login_token = await self.database.get_login_token(input.token)
login_token = await self.database.get_login_token(input.token)
if not login_token:
raise domain.LoginTokenNotFound()
if not login_token:
raise domain.LoginTokenNotFound()
if login_token.used_at:
raise domain.LoginTokenAlreadyUsed()
if login_token.used_at:
raise domain.LoginTokenAlreadyUsed()
if login_token.expires_at < datetime.datetime.now(datetime.UTC):
raise domain.LoginTokenExpired()
if login_token.expires_at < timezone.now():
raise domain.LoginTokenExpired()
user = await self.database.get_user(user_id=login_token.user_id)
if not user:
raise domain.UserNotFound(login_token.user_id)
user = await self.database.get_user(user_id=login_token.user_id)
if not user:
raise domain.UserNotFound(login_token.user_id)
await self.database.mark_token_as_used(input.token)
await self.database.mark_token_as_used(input.token)
# Генерируем JWT токен с информацией о пользователе
access_token = self.jwt_encoder.encode_access_token(
user_id=user.id,
telegram_id=user.telegram_id,

View File

@@ -11,31 +11,28 @@ log = logging.getLogger(__name__)
async def create_creative(self: 'Usecase', input: dto.CreateCreativeInput, user_id: uuid.UUID) -> dto.CreativeOutput:
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 creative for unavailable target %s', user_id, input.target_channel_id
)
raise domain.TargetChannelNotFound(input.target_channel_id)
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 creative for unavailable target %s', user_id, input.target_channel_id)
raise domain.TargetChannelNotFound(input.target_channel_id)
creative = domain.Creative(
name=input.name,
text=input.text,
status=domain.CreativeStatus.ACTIVE,
target_channel_id=target_channel.id,
user_id=user_id,
)
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)
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,
placements_count=created.placements_count,
)
return dto.CreativeOutput(
id=creative.id,
name=creative.name,
text=creative.text,
target_channel_id=target_channel.id,
target_channel_title=target_channel.title,
created_at=creative.created_at,
status=creative.status,
placements_count=creative.placements_count,
)

View File

@@ -10,14 +10,13 @@ log = logging.getLogger(__name__)
async def delete_creative(self: 'Usecase', input: dto.DeleteCreativeInput) -> None:
async with self.database.transaction():
creative = await self.database.get_creative(input.user_id, input.creative_id)
if not creative:
log.warning('User %s attempted to delete unavailable creative %s', input.user_id, input.creative_id)
raise domain.CreativeNotFound(input.creative_id)
creative = await self.database.get_creative(input.user_id, input.creative_id)
if not creative:
log.warning('User %s attempted to delete unavailable creative %s', input.user_id, input.creative_id)
raise domain.CreativeNotFound(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)
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)
await self.database.delete_creative(input.creative_id)

View File

@@ -10,19 +10,18 @@ log = logging.getLogger(__name__)
async def get_creative(self: 'Usecase', input: dto.GetCreativeInput) -> dto.CreativeOutput:
async with self.database.transaction():
creative = await self.database.get_creative(input.user_id, input.creative_id)
if not creative:
log.warning('User %s attempted to access unavailable creative %s', input.user_id, input.creative_id)
raise domain.CreativeNotFound(input.creative_id)
creative = await self.database.get_creative(input.user_id, input.creative_id)
if not creative:
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,
placements_count=creative.placements_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,
placements_count=creative.placements_count,
)

View File

@@ -7,10 +7,7 @@ if TYPE_CHECKING:
async def get_creatives(self: 'Usecase', input: dto.GetCreativesInput) -> dto.GetCreativesOutput:
async with self.database.transaction():
creatives = await self.database.get_user_creatives(
input.user_id, target_channel_id=input.target_channel_id, include_archived=input.include_archived
)
creatives = await self.database.get_user_creatives(input.user_id, input.target_channel_id, input.include_archived)
return dto.GetCreativesOutput(
creatives=[

View File

@@ -13,43 +13,40 @@ log = logging.getLogger(__name__)
async def handle_creative_callback(
self: 'Usecase', telegram_id: int, chat_id: int, callback_data: str, message_id: int
) -> None:
async with self.database.transaction():
state = await self.database.get_telegram_state(telegram_id)
if not state or state.state != domain.TelegramStateEnum.CREATIVE_WAITING_CHANNEL:
log.debug('User %s has no active creative creation flow or wrong state', telegram_id)
return
state = await self.database.get_telegram_state(telegram_id)
if not state or state.state != domain.TelegramStateEnum.CREATIVE_WAITING_CHANNEL:
log.debug('User %s has no active creative creation flow or wrong state', telegram_id)
return
if not callback_data.startswith('cc_ch:'):
log.warning('Invalid callback data format: %s', callback_data)
return
if not callback_data.startswith('cc_ch:'):
log.warning('Invalid callback data format: %s', callback_data)
return
channel_id_str = callback_data.split(':', 1)[1]
try:
channel_id = uuid.UUID(channel_id_str)
except ValueError:
log.error('Invalid channel UUID in callback data: %s', channel_id_str)
return
channel_id_str = callback_data.split(':', 1)[1]
try:
channel_id = uuid.UUID(channel_id_str)
except ValueError:
log.error('Invalid channel UUID in callback data: %s', channel_id_str)
return
user = await self.database.get_user(telegram_id=telegram_id)
if not user:
await self.telegram_bot.send_message('❌ Ошибка: пользователь не найден.', chat_id=chat_id)
await self.database.clear_telegram_state(telegram_id)
return
user = await self.database.get_user(telegram_id=telegram_id)
if not user:
await self.telegram_bot.send_message('❌ Ошибка: пользователь не найден.', chat_id)
await self.database.clear_telegram_state(telegram_id)
return
channel = await self.database.get_target_channel(user.id, channel_id=channel_id)
if not channel:
await self.telegram_bot.send_message('❌ Канал не найден или не принадлежит вам.', chat_id=chat_id)
await self.database.clear_telegram_state(telegram_id)
return
channel = await self.database.get_target_channel(user.id, channel_id=channel_id)
if not channel:
await self.telegram_bot.send_message('❌ Канал не найден или не принадлежит вам.', chat_id)
await self.database.clear_telegram_state(telegram_id)
return
await self.database.set_telegram_state(
telegram_id=telegram_id,
state=domain.TelegramStateEnum.CREATIVE_WAITING_NAME,
context={'target_channel_id': str(channel_id), 'channel_title': channel.title},
)
await self.database.set_telegram_state(
telegram_id,
domain.TelegramStateEnum.CREATIVE_WAITING_NAME,
{'target_channel_id': str(channel_id), 'channel_title': channel.title},
)
await self.telegram_bot.edit_message_reply_markup(chat_id, message_id)
await self.telegram_bot.edit_message_reply_markup(chat_id, message_id)
await self.telegram_bot.send_message(
f'✅ Канал выбран: {channel.title}\n\n📝 Введите название креатива:', chat_id=chat_id
)
await self.telegram_bot.send_message(f'✅ Канал выбран: {channel.title}\n\n📝 Введите название креатива:', chat_id)

View File

@@ -13,86 +13,79 @@ log = logging.getLogger(__name__)
async def handle_creative_text_input(
self: 'Usecase',
telegram_id: int,
chat_id: int,
text: str,
text_html: str | None = None,
self: 'Usecase', telegram_id: int, chat_id: int, text: str, text_html: str | None = None
) -> None:
async with self.database.transaction():
state = await self.database.get_telegram_state(telegram_id)
if not state:
return
state = await self.database.get_telegram_state(telegram_id)
if not state:
return
user = await self.database.get_user(telegram_id=telegram_id)
if not user:
await self.telegram_bot.send_message('❌ Ошибка: пользователь не найден.', chat_id=chat_id)
user = await self.database.get_user(telegram_id=telegram_id)
if not user:
await self.telegram_bot.send_message('❌ Ошибка: пользователь не найден.', chat_id)
await self.database.clear_telegram_state(telegram_id)
return
if state.state == domain.TelegramStateEnum.CREATIVE_WAITING_NAME:
await self.database.set_telegram_state(
telegram_id, domain.TelegramStateEnum.CREATIVE_WAITING_TEXT, {**state.context, 'creative_name': text}
)
await self.telegram_bot.send_message(
'✅ Название сохранено!\n\n'
'💬 Теперь отправьте или перешлите текст креатива.\n'
'Используйте {link} для обозначения места вставки ссылки на ваш канал.\n'
'Вы также можете указать текст ссылки в формате [текст]{link}.',
chat_id,
)
elif state.state == domain.TelegramStateEnum.CREATIVE_WAITING_TEXT:
target_channel_id_str = state.context.get('target_channel_id')
creative_name = state.context.get('creative_name')
if not target_channel_id_str or not creative_name:
log.error('Missing context data for creative creation: %s', state.context)
await self.telegram_bot.send_message('❌ Ошибка: данные не найдены. Начните заново.', chat_id)
await self.database.clear_telegram_state(telegram_id)
return
if state.state == domain.TelegramStateEnum.CREATIVE_WAITING_NAME:
await self.database.set_telegram_state(
telegram_id=telegram_id,
state=domain.TelegramStateEnum.CREATIVE_WAITING_TEXT,
context={**state.context, 'creative_name': text},
)
await self.telegram_bot.send_message(
'✅ Название сохранено!\n\n'
'💬 Теперь отправьте или перешлите текст креатива.\n'
'Используйте {link} для обозначения места вставки ссылки на ваш канал.\n'
'Вы также можете указать текст ссылки в формате [текст]{link}.',
chat_id=chat_id,
)
try:
target_channel_id = uuid.UUID(target_channel_id_str)
except ValueError:
log.error('Invalid target_channel_id in context: %s', target_channel_id_str)
await self.telegram_bot.send_message('❌ Ошибка: неверный формат данных.', chat_id)
await self.database.clear_telegram_state(telegram_id)
return
elif state.state == domain.TelegramStateEnum.CREATIVE_WAITING_TEXT:
target_channel_id_str = state.context.get('target_channel_id')
creative_name = state.context.get('creative_name')
channel = await self.database.get_target_channel(user.id, channel_id=target_channel_id)
if not channel:
await self.telegram_bot.send_message('❌ Канал не найден.', chat_id)
await self.database.clear_telegram_state(telegram_id)
return
if not target_channel_id_str or not creative_name:
log.error('Missing context data for creative creation: %s', state.context)
await self.telegram_bot.send_message('❌ Ошибка: данные не найдены. Начните заново.', chat_id=chat_id)
await self.database.clear_telegram_state(telegram_id)
return
message_html = text_html or text
creative_text = prepare_creative_text_html(message_html)
try:
target_channel_id = uuid.UUID(target_channel_id_str)
except ValueError:
log.error('Invalid target_channel_id in context: %s', target_channel_id_str)
await self.telegram_bot.send_message('❌ Ошибка: неверный формат данных.', chat_id=chat_id)
await self.database.clear_telegram_state(telegram_id)
return
channel = await self.database.get_target_channel(user.id, channel_id=target_channel_id)
if not channel:
await self.telegram_bot.send_message('❌ Канал не найден.', chat_id=chat_id)
await self.database.clear_telegram_state(telegram_id)
return
message_html = text_html or text
creative_text = prepare_creative_text_html(message_html)
creative = domain.Creative(
name=creative_name,
text=creative_text,
status=domain.CreativeStatus.ACTIVE,
user_id=user.id,
target_channel_id=target_channel_id,
)
created = await self.database.create_creative(creative)
creative = domain.Creative(
name=creative_name,
text=creative_text,
status=domain.CreativeStatus.ACTIVE,
user_id=user.id,
target_channel_id=target_channel_id,
)
async with self.database.transaction():
await self.database.create_creative(creative)
await self.database.clear_telegram_state(telegram_id)
text_preview_source = text
text_preview = text_preview_source[:100] + '...' if len(text_preview_source) > 100 else text_preview_source
await self.telegram_bot.send_message(
f'✅ Креатив успешно создан!\n\n'
f'📝 Название: {created.name}\n'
f'📢 Канал: {channel.title}\n\n'
f'💬 Текст:\n{text_preview}',
chat_id=chat_id,
)
text_preview_source = text
text_preview = text_preview_source[:100] + '...' if len(text_preview_source) > 100 else text_preview_source
await self.telegram_bot.send_message(
f'✅ Креатив успешно создан!\n\n'
f'📝 Название: {creative.name}\n'
f'📢 Канал: {channel.title}\n\n'
f'💬 Текст:\n{text_preview}',
chat_id,
)
else:
log.warning('Unknown state: %s', state.state)
await self.database.clear_telegram_state(telegram_id)
else:
log.warning('Unknown state: %s', state.state)
await self.database.clear_telegram_state(telegram_id)

View File

@@ -12,32 +12,22 @@ log = logging.getLogger(__name__)
async def start_creative_creation(self: 'Usecase', telegram_id: int, chat_id: int) -> None:
async with self.database.transaction():
user = await self.database.get_user(telegram_id=telegram_id)
if not user:
await self.telegram_bot.send_message(
'❌ Вы не авторизованы. Используйте /start для входа.', chat_id=chat_id
)
return
user = await self.database.get_user(telegram_id=telegram_id)
if not user:
await self.telegram_bot.send_message('❌ Вы не авторизованы. Используйте /start для входа.', chat_id)
return
channels = await self.database.get_user_target_channels(user.id)
if not channels:
await self.telegram_bot.send_message(
'У вас нет подключенных каналов. Добавьте бота в свой канал для начала работы.', chat_id=chat_id
)
return
buttons = [
[InlineKeyboardButton(text=channel.title, callback_data=f'cc_ch:{channel.id}')] for channel in channels
]
await self.telegram_bot.send_message_with_inline_keyboard(
'✨ Создание нового креатива\n\nВыберите канал, для которого создается креатив:',
chat_id=chat_id,
buttons=buttons,
channels = await self.database.get_user_target_channels(user.id)
if not channels:
await self.telegram_bot.send_message(
'У вас нет подключенных каналов. Добавьте бота в свой канал для начала работы.', chat_id
)
return
await self.database.set_telegram_state(
telegram_id=telegram_id, state=domain.TelegramStateEnum.CREATIVE_WAITING_CHANNEL, context={}
)
buttons = [[InlineKeyboardButton(text=channel.title, callback_data=f'cc_ch:{channel.id}')] for channel in channels]
await self.telegram_bot.send_message_with_inline_keyboard(
'✨ Создание нового креатива\n\nВыберите канал, для которого создается креатив:', chat_id, buttons
)
await self.database.set_telegram_state(telegram_id, domain.TelegramStateEnum.CREATIVE_WAITING_CHANNEL, context={})

View File

@@ -13,28 +13,27 @@ log = logging.getLogger(__name__)
async def update_creative(
self: 'Usecase', creative_id: uuid.UUID, input: dto.UpdateCreativeInput, user_id: uuid.UUID
) -> dto.CreativeOutput:
async with self.database.transaction():
creative = await self.database.get_creative(user_id, creative_id)
if not creative:
log.warning('User %s attempted to update unavailable creative %s', user_id, creative_id)
raise domain.CreativeNotFound(creative_id)
creative = await self.database.get_creative(user_id, creative_id)
if not creative:
log.warning('User %s attempted to update unavailable creative %s', user_id, creative_id)
raise domain.CreativeNotFound(creative_id)
if input.name is not None:
creative.name = input.name
if input.text is not None:
creative.text = input.text
if input.status is not None:
creative.status = input.status
if input.name:
creative.name = input.name
if input.text:
creative.text = input.text
if input.status:
creative.status = input.status
updated = await self.database.update_creative(creative)
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,
placements_count=updated.placements_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,
placements_count=creative.placements_count,
)

View File

@@ -13,13 +13,14 @@ log = logging.getLogger(__name__)
async def create_external_channel(
self: 'Usecase', input: dto.CreateExternalChannelInput, user_id: uuid.UUID
) -> dto.ExternalChannelOutput:
async with self.database.transaction():
for target_id in input.target_channel_ids:
target_channel = await self.database.get_target_channel(user_id, channel_id=target_id)
if not target_channel:
log.warning('User %s attempted to add external channel to unavailable target %s', user_id, target_id)
raise domain.TargetChannelNotFound(target_id)
for target_id in input.target_channel_ids:
target_channel = await self.database.get_target_channel(user_id, channel_id=target_id)
if not target_channel:
log.warning('User %s attempted to add external channel to unavailable target %s', user_id, target_id)
raise domain.TargetChannelNotFound(target_id)
async with self.database.transaction():
channel = domain.ExternalChannel(
telegram_id=input.telegram_id,
title=input.title,
@@ -28,20 +29,20 @@ async def create_external_channel(
subscribers_count=input.subscribers_count,
user_id=user_id,
)
created_channel = await self.database.create_external_channel(channel)
await self.database.create_external_channel(channel)
if input.target_channel_ids:
await self.database.add_external_channel_to_targets(created_channel.id, input.target_channel_ids)
await self.database.add_external_channel_to_targets(channel.id, input.target_channel_ids)
log.info(
'External channel %s created and linked to %s target channels', input.telegram_id, len(input.target_channel_ids)
)
return dto.ExternalChannelOutput(
id=created_channel.id,
telegram_id=created_channel.telegram_id,
title=created_channel.title,
username=created_channel.username,
description=created_channel.description,
subscribers_count=created_channel.subscribers_count,
id=channel.id,
telegram_id=channel.telegram_id,
title=channel.title,
username=channel.username,
description=channel.description,
subscribers_count=channel.subscribers_count,
)

View File

@@ -10,11 +10,10 @@ log = logging.getLogger(__name__)
async def delete_external_channel(self: 'Usecase', input: dto.DeleteExternalChannelInput) -> None:
async with self.database.transaction():
channel = await self.database.get_external_channel(input.user_id, channel_id=input.channel_id)
if not channel:
log.warning('User %s attempted to delete unavailable external channel %s', input.user_id, input.channel_id)
raise domain.ExternalChannelNotFound(input.channel_id)
channel = await self.database.get_external_channel(input.user_id, channel_id=input.channel_id)
if not channel:
log.warning('User %s attempted to delete unavailable external channel %s', input.user_id, input.channel_id)
raise domain.ExternalChannelNotFound(input.channel_id)
await self.database.delete_external_channel(input.channel_id)
log.info('User %s deleted external channel %s', input.user_id, input.channel_id)
await self.database.delete_external_channel(input.channel_id)
log.info('User %s deleted external channel %s', input.user_id, input.channel_id)

View File

@@ -10,15 +10,12 @@ log = logging.getLogger(__name__)
async def get_external_channels(self: 'Usecase', input: dto.GetExternalChannelsInput) -> dto.GetExternalChannelsOutput:
async with self.database.transaction():
target_channel = await self.database.get_target_channel(input.user_id, channel_id=input.target_channel_id)
if not target_channel:
log.warning(
'Target channel %s not found or not accessible for user %s', input.target_channel_id, input.user_id
)
raise domain.TargetChannelNotFound(input.target_channel_id)
target_channel = await self.database.get_target_channel(input.user_id, channel_id=input.target_channel_id)
if not target_channel:
log.warning('Target channel %s not found or not accessible for user %s', input.target_channel_id, input.user_id)
raise domain.TargetChannelNotFound(input.target_channel_id)
channels = await self.database.get_external_channels_for_target(input.target_channel_id)
channels = await self.database.get_external_channels_for_target(input.target_channel_id)
return dto.GetExternalChannelsOutput(
external_channels=[

View File

@@ -13,30 +13,29 @@ log = logging.getLogger(__name__)
async def update_external_channel(
self: 'Usecase', channel_id: uuid.UUID, input: dto.UpdateExternalChannelInput, user_id: uuid.UUID
) -> dto.ExternalChannelOutput:
async with self.database.transaction():
external_channel = await self.database.get_external_channel(user_id, channel_id=channel_id)
if not external_channel:
log.warning('External channel %s not found', channel_id)
raise domain.ExternalChannelNotFound(channel_id)
external_channel = await self.database.get_external_channel(user_id, channel_id=channel_id)
if not external_channel:
log.warning('External channel %s not found', channel_id)
raise domain.ExternalChannelNotFound(channel_id)
if input.title is not None:
external_channel.title = input.title
if input.username is not None:
external_channel.username = input.username
if input.description is not None:
external_channel.description = input.description
if input.subscribers_count is not None:
external_channel.subscribers_count = input.subscribers_count
if input.title is not None:
external_channel.title = input.title
if input.username is not None:
external_channel.username = input.username
if input.description is not None:
external_channel.description = input.description
if input.subscribers_count is not None:
external_channel.subscribers_count = input.subscribers_count
updated = await self.database.update_external_channel(external_channel)
await self.database.update_external_channel(external_channel)
log.info('External channel %s updated', channel_id)
log.info('External channel %s updated', channel_id)
return dto.ExternalChannelOutput(
id=updated.id,
telegram_id=updated.telegram_id,
title=updated.title,
username=updated.username,
description=updated.description,
subscribers_count=updated.subscribers_count,
)
return dto.ExternalChannelOutput(
id=external_channel.id,
telegram_id=external_channel.telegram_id,
title=external_channel.title,
username=external_channel.username,
description=external_channel.description,
subscribers_count=external_channel.subscribers_count,
)

View File

@@ -13,32 +13,30 @@ log = logging.getLogger(__name__)
async def update_external_channel_links(
self: 'Usecase', channel_id: uuid.UUID, input: dto.UpdateExternalChannelLinksInput, user_id: uuid.UUID
) -> dto.ExternalChannelOutput:
external_channel = await self.database.get_external_channel(user_id, channel_id=channel_id)
if not external_channel:
log.warning('External channel %s not found', channel_id)
raise domain.ExternalChannelNotFound(channel_id)
for target_id in input.add_target_channel_ids:
target_channel = await self.database.get_target_channel(user_id, channel_id=target_id)
if not target_channel:
log.warning('User %s attempted to link external channel to target %s they do not own', user_id, target_id)
raise domain.TargetChannelNotFound(target_id)
async with self.database.transaction():
external_channel = await self.database.get_external_channel(user_id, channel_id=channel_id)
if not external_channel:
log.warning('External channel %s not found', channel_id)
raise domain.ExternalChannelNotFound(channel_id)
for target_id in input.add_target_channel_ids:
target_channel = await self.database.get_target_channel(user_id, channel_id=target_id)
if not target_channel:
log.warning(
'User %s attempted to link external channel to target %s they do not own', user_id, target_id
)
raise domain.TargetChannelNotFound(target_id)
if input.add_target_channel_ids:
await self.database.add_external_channel_to_targets(channel_id, input.add_target_channel_ids)
for target_id in input.remove_target_channel_ids:
await self.database.remove_external_channel_from_target(channel_id, target_id)
log.info(
'External channel %s links updated: %s added, %s removed',
channel_id,
len(input.add_target_channel_ids),
len(input.remove_target_channel_ids),
)
log.info(
'External channel %s links updated: %s added, %s removed',
channel_id,
len(input.add_target_channel_ids),
len(input.remove_target_channel_ids),
)
return dto.ExternalChannelOutput(
id=external_channel.id,

View File

@@ -11,74 +11,63 @@ log = logging.getLogger(__name__)
async def create_placement(self: 'Usecase', input: dto.CreatePlacementInput, user_id: uuid.UUID) -> dto.PlacementOutput:
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 placement for unavailable target %s', user_id, input.target_channel_id)
raise domain.TargetChannelNotFound(input.target_channel_id)
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 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 placement for unavailable creative %s', user_id, input.creative_id)
raise domain.CreativeNotFound(input.creative_id)
requires_approval = input.invite_link_type == domain.InviteLinkType.APPROVAL
invite_link = await self.telegram_bot.create_chat_invite_link(target_channel.telegram_id, requires_approval)
placement = domain.Placement(
target_channel_id=input.target_channel_id,
external_channel_id=input.external_channel_id,
creative_id=input.creative_id,
user_id=user_id,
placement_date=input.placement_date,
cost=input.cost,
comment=input.comment,
invite_link_type=input.invite_link_type,
invite_link=invite_link,
status=domain.PlacementStatus.PENDING,
)
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 placement for unavailable target %s', user_id, input.target_channel_id
)
raise domain.TargetChannelNotFound(input.target_channel_id)
await self.database.create_placement(placement)
# Проверяем существование внешнего канала
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 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 placement for unavailable creative %s', user_id, input.creative_id)
raise domain.CreativeNotFound(input.creative_id)
# Создаём уникальную пригласительную ссылку через Telegram Bot API
requires_approval = input.invite_link_type == domain.InviteLinkType.APPROVAL
invite_link = await self.telegram_bot.create_chat_invite_link(
chat_id=target_channel.telegram_id,
requires_approval=requires_approval,
)
# Создаём закуп со статусом PENDING (ожидаем публикацию поста)
placement = domain.Placement(
target_channel_id=input.target_channel_id,
external_channel_id=input.external_channel_id,
creative_id=input.creative_id,
user_id=user_id,
placement_date=input.placement_date,
cost=input.cost,
comment=input.comment,
invite_link_type=input.invite_link_type,
invite_link=invite_link,
status=domain.PlacementStatus.PENDING,
)
created = await self.database.create_placement(placement)
# Увеличиваем счётчик закупов у креатива
creative.placements_count += 1
await self.database.update_creative(creative)
return dto.PlacementOutput(
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,
)
return dto.PlacementOutput(
id=placement.id,
target_channel_id=placement.target_channel_id,
target_channel_title=target_channel.title,
external_channel_id=placement.external_channel_id,
external_channel_title=external_channel.title,
creative_id=placement.creative_id,
creative_name=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

@@ -10,17 +10,19 @@ 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)
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)
if placement.status != domain.PlacementStatus.ACTIVE:
await self.database.delete_placement(input.placement_id)
return
async with self.database.transaction():
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

@@ -10,30 +10,29 @@ 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)
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,
)
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

@@ -7,14 +7,13 @@ if TYPE_CHECKING:
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,
)
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=[

View File

@@ -13,42 +13,40 @@ log = logging.getLogger(__name__)
async def update_placement(
self: 'Usecase', placement_id: uuid.UUID, input: dto.UpdatePlacementInput, user_id: uuid.UUID
) -> dto.PlacementOutput:
async with self.database.transaction():
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)
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:
placement.placement_date = input.placement_date
if input.cost is not None:
placement.cost = input.cost
if input.comment is not None:
placement.comment = input.comment
if input.status is not None:
placement.status = input.status
if input.placement_date is not None:
placement.placement_date = input.placement_date
if input.cost is not None:
placement.cost = input.cost
if input.comment is not None:
placement.comment = input.comment
if input.status is not None:
placement.status = input.status
updated = await self.database.update_placement(placement)
await self.database.update_placement(placement)
return dto.PlacementOutput(
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,
)
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

@@ -17,44 +17,43 @@ async def handle_subscription(
first_name: str | None = None,
last_name: str | None = None,
) -> None:
async with self.database.transaction():
placement = await self.database.get_placement_by_invite_link(invite_link)
if not placement:
log.warning('Placement not found for invite_link: %s', invite_link)
return
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 = domain.Subscriber(
telegram_id=user_telegram_id,
username=username,
first_name=first_name,
last_name=last_name,
)
await self.database.upsert_subscriber(subscriber)
active_subscription = await self.database.get_active_subscription_by_subscriber_and_channel(
subscriber.id, placement.target_channel.telegram_id
)
if active_subscription:
# Пользователь уже подписан на канал через другой placement
# Это не должно случиться (Telegram не даст подписаться дважды),
# но если случилось - логируем и игнорируем
log.warning(
'User %s (telegram_id: %s) already has active subscription to channel %s via placement %s, '
'ignoring new subscription attempt via placement %s',
subscriber.id,
user_telegram_id,
placement.target_channel_id,
active_subscription.placement_id,
placement.id,
)
subscriber = await self.database.upsert_subscriber(subscriber)
return
active_subscription = await self.database.get_active_subscription_by_subscriber_and_channel(
subscriber.id, placement.target_channel.telegram_id
)
# Проверяем, была ли раньше подписка через ЭТОТ placement (для реактивации)
existing_sub = await self.database.get_subscription_by_subscriber_and_placement(subscriber.id, placement.id)
if active_subscription:
# Пользователь уже подписан на канал через другой placement
# Это не должно случиться (Telegram не даст подписаться дважды),
# но если случилось - логируем и игнорируем
log.warning(
'User %s (telegram_id: %s) already has active subscription to channel %s via placement %s, '
'ignoring new subscription attempt via placement %s',
subscriber.id,
user_telegram_id,
placement.target_channel_id,
active_subscription.placement_id,
placement.id,
)
return
# Проверяем, была ли раньше подписка через ЭТОТ placement (для реактивации)
existing_sub = await self.database.get_subscription_by_subscriber_and_placement(subscriber.id, placement.id)
if existing_sub and existing_sub.status == domain.SubscriptionStatus.UNSUBSCRIBED:
# Реактивируем старую подписку через тот же placement
if existing_sub and existing_sub.status == domain.SubscriptionStatus.UNSUBSCRIBED:
async with self.database.transaction():
existing_sub.status = domain.SubscriptionStatus.ACTIVE
existing_sub.unsubscribed_at = None
await self.database.update_subscription(existing_sub)
@@ -62,29 +61,30 @@ async def handle_subscription(
placement.subscriptions_count += 1
await self.database.update_placement(placement)
log.info(
'Subscription reactivated: subscriber %s (telegram_id: %s) resubscribed via same placement %s',
subscriber.id,
user_telegram_id,
placement.id,
)
return
subscription = domain.Subscription(
placement_id=placement.id,
subscriber_id=subscriber.id,
target_channel_id=placement.target_channel_id,
invite_link=invite_link,
log.info(
'Subscription reactivated: subscriber %s (telegram_id: %s) resubscribed via same placement %s',
subscriber.id,
user_telegram_id,
placement.id,
)
return
subscription = domain.Subscription(
placement_id=placement.id,
subscriber_id=subscriber.id,
target_channel_id=placement.target_channel_id,
invite_link=invite_link,
)
async with self.database.transaction():
await self.database.create_subscription(subscription)
placement.subscriptions_count += 1
await self.database.update_placement(placement)
log.info(
'Subscription created: subscriber %s (telegram_id: %s) subscribed via placement %s (invite_link: %s)',
subscriber.id,
user_telegram_id,
placement.id,
invite_link,
)
log.info(
'Subscription created: subscriber %s (telegram_id: %s) subscribed via placement %s (invite_link: %s)',
subscriber.id,
user_telegram_id,
placement.id,
invite_link,
)

View File

@@ -1,7 +1,8 @@
import datetime
import logging
from typing import TYPE_CHECKING
from tortoise import timezone
from src import domain
if TYPE_CHECKING:
@@ -11,39 +12,38 @@ log = logging.getLogger(__name__)
async def handle_unsubscription(self: 'Usecase', user_telegram_id: int, channel_telegram_id: int) -> None:
async with self.database.transaction():
subscriber = await self.database.get_subscriber(user_telegram_id)
if not subscriber:
log.warning('Subscriber not found for telegram_id: %s', user_telegram_id)
return
subscriber = await self.database.get_subscriber(user_telegram_id)
if not subscriber:
log.warning('Subscriber not found for telegram_id: %s', user_telegram_id)
return
subscriptions = await self.database.get_active_subscriptions_by_subscriber_and_channel(
subscriber.id, channel_telegram_id
subscriptions = await self.database.get_active_subscriptions_by_subscriber_and_channel(
subscriber.id, channel_telegram_id
)
if not subscriptions:
log.info(
'No active subscriptions found for subscriber %s (telegram_id: %s) in channel %s',
subscriber.id,
user_telegram_id,
channel_telegram_id,
)
return
if not subscriptions:
log.info(
'No active subscriptions found for subscriber %s (telegram_id: %s) in channel %s',
subscriber.id,
user_telegram_id,
channel_telegram_id,
)
return
for subscription in subscriptions:
for subscription in subscriptions:
async with self.database.transaction():
subscription.status = domain.SubscriptionStatus.UNSUBSCRIBED
subscription.unsubscribed_at = datetime.datetime.now(datetime.UTC)
subscription.unsubscribed_at = timezone.now()
await self.database.update_subscription(subscription)
# Декрементируем счётчик подписок у закупа
placement = subscription.placement
if placement.subscriptions_count > 0:
placement.subscriptions_count -= 1
await self.database.update_placement(placement)
log.info(
'Subscription marked as unsubscribed: subscriber %s (telegram_id: %s) unsubscribed from placement %s',
subscriber.id,
user_telegram_id,
placement.id,
)
log.info(
'Subscription marked as unsubscribed: subscriber %s (telegram_id: %s) unsubscribed from placement %s',
subscriber.id,
user_telegram_id,
placement.id,
)

View File

@@ -17,7 +17,7 @@ async def connect_target_chan(self: 'Usecase', input: dto.ConnectTargetChanInput
await self.telegram_bot.send_message(
f'⚠️ Бот был добавлен в канал "{input.title}", но не является админом.\n\n'
'Пожалуйста, сделайте бота администратором канала.',
chat_id=input.user_telegram_id,
input.user_telegram_id,
)
raise domain.ChannelNoAdminRights()
@@ -37,42 +37,38 @@ async def connect_target_chan(self: 'Usecase', input: dto.ConnectTargetChanInput
f'⚠️ Бот был добавлен в канал "{input.title}", но не имеет необходимых прав.\n\n'
f'Отсутствующие права:\n{permissions_text}\n\n'
'Пожалуйста, предоставьте эти права боту в настройках канала.',
chat_id=input.user_telegram_id,
input.user_telegram_id,
)
raise domain.ChannelNoAdminRights()
async with self.database.transaction():
user = await self.database.get_user(telegram_id=input.user_telegram_id)
if not user:
log.warning(f'User {input.user_telegram_id} not found when trying to connect channel {input.telegram_id}')
await self.telegram_bot.send_message(
f'⚠️ Канал "{input.title}" не может быть подключен.\n\n'
'Вы должны сначала авторизоваться в веб-панели перед подключением каналов.',
chat_id=input.user_telegram_id,
)
raise domain.UserNotFound()
channel = domain.TargetChannel(
telegram_id=input.telegram_id,
title=input.title,
username=input.username,
user_id=user.id,
status=domain.TargetChannelStatus.ACTIVE,
user = await self.database.get_user(telegram_id=input.user_telegram_id)
if not user:
log.warning(f'User {input.user_telegram_id} not found when trying to connect channel {input.telegram_id}')
await self.telegram_bot.send_message(
f'⚠️ Канал "{input.title}" не может быть подключен.\n\n'
'Вы должны сначала авторизоваться в веб-панели перед подключением каналов.',
input.user_telegram_id,
)
raise domain.UserNotFound()
upserted_channel = await self.database.upsert_target_channel(channel)
log.info(f'Channel {input.telegram_id} connected/updated successfully by user {input.user_telegram_id}')
await self.telegram_bot.send_message(
f'✅ Канал "{input.title}" успешно подключен!',
chat_id=input.user_telegram_id,
channel = domain.TargetChannel(
telegram_id=input.telegram_id,
title=input.title,
username=input.username,
user_id=user.id,
status=domain.TargetChannelStatus.ACTIVE,
)
await self.database.upsert_target_channel(channel)
log.info(f'Channel {input.telegram_id} connected/updated successfully by user {input.user_telegram_id}')
await self.telegram_bot.send_message(f'✅ Канал "{input.title}" успешно подключен!', input.user_telegram_id)
return dto.ConnectTargetChanOutput(
id=upserted_channel.id,
telegram_id=upserted_channel.telegram_id,
title=upserted_channel.title,
username=upserted_channel.username,
status=upserted_channel.status,
is_active=upserted_channel.status == domain.TargetChannelStatus.ACTIVE,
id=channel.id,
telegram_id=channel.telegram_id,
title=channel.title,
username=channel.username,
status=channel.status,
is_active=channel.status == domain.TargetChannelStatus.ACTIVE,
)

View File

@@ -10,12 +10,11 @@ log = logging.getLogger(__name__)
async def disconnect_target_chan(self: 'Usecase', input: dto.DisconnectTargetChanInput) -> None:
async with self.database.transaction():
channel = await self.database.get_target_channel(channel_id=input.channel_id, user_id=input.user_id)
if not channel:
raise domain.TargetChannelNotFound(input.channel_id)
channel = await self.database.get_target_channel(channel_id=input.channel_id, user_id=input.user_id)
if not channel:
raise domain.TargetChannelNotFound(input.channel_id)
channel.status = domain.TargetChannelStatus.INACTIVE
await self.database.update_target_channel(channel)
channel.status = domain.TargetChannelStatus.INACTIVE
await self.database.update_target_channel(channel)
log.info(f'Target channel {input.channel_id} deactivated')

View File

@@ -10,18 +10,17 @@ log = logging.getLogger(__name__)
async def disconnect_target_chan_by_tg_id(self: 'Usecase', input: dto.DisconnectTargetChanByTgIdInput) -> None:
async with self.database.transaction():
user = await self.database.get_user(telegram_id=input.user_telegram_id)
if not user:
log.warning(f'User with telegram_id {input.user_telegram_id} not found when disconnecting channel')
return
user = await self.database.get_user(telegram_id=input.user_telegram_id)
if not user:
log.warning(f'User with telegram_id {input.user_telegram_id} not found when disconnecting channel')
return
channel = await self.database.get_target_channel(user.id, telegram_id=input.telegram_id)
if not channel:
log.warning(f'Target channel {input.telegram_id} not found')
raise domain.TargetChannelNotFound()
channel = await self.database.get_target_channel(user.id, telegram_id=input.telegram_id)
if not channel:
log.warning(f'Target channel {input.telegram_id} not found')
raise domain.TargetChannelNotFound()
channel.status = domain.TargetChannelStatus.INACTIVE
await self.database.update_target_channel(channel)
channel.status = domain.TargetChannelStatus.INACTIVE
await self.database.update_target_channel(channel)
log.info(f'Target channel {input.telegram_id} deactivated')

View File

@@ -7,8 +7,7 @@ if TYPE_CHECKING:
async def get_user_target_chans(self: 'Usecase', input: dto.GetUserTargetChansInput) -> dto.GetUserTargetChansOutput:
async with self.database.transaction():
channels = await self.database.get_user_target_channels(input.user_id)
channels = await self.database.get_user_target_channels(input.user_id)
return dto.GetUserTargetChansOutput(
target_channels=[

View File

@@ -22,34 +22,31 @@ async def update_target_chan_permissions(self: 'Usecase', input: dto.UpdateTarge
log.warning(f'User with telegram_id {input.user_telegram_id} not found when updating channel permissions')
return
async with self.database.transaction():
channel = await self.database.get_target_channel(user.id, telegram_id=input.telegram_id)
if not channel:
log.warning(f'Target channel {input.telegram_id} not found when permissions changed')
raise domain.TargetChannelNotFound()
channel = await self.database.get_target_channel(user.id, telegram_id=input.telegram_id)
if not channel:
log.warning(f'Target channel {input.telegram_id} not found when permissions changed')
raise domain.TargetChannelNotFound()
if not missing_permissions:
if channel.status != domain.TargetChannelStatus.ACTIVE:
channel.status = domain.TargetChannelStatus.ACTIVE
await self.database.update_target_channel(channel)
await self.telegram_bot.send_message(
f'✅ Канал "{input.chat_title}" был активирован.\n\nВсе необходимые права боту предоставлены!',
chat_id=input.user_telegram_id,
)
log.info(f'Target channel {input.telegram_id} reactivated - all permissions granted')
return
if channel.status == domain.TargetChannelStatus.ACTIVE:
channel.status = domain.TargetChannelStatus.INACTIVE
if not missing_permissions:
if channel.status != domain.TargetChannelStatus.ACTIVE:
channel.status = domain.TargetChannelStatus.ACTIVE
await self.database.update_target_channel(channel)
missed_permissions = '\n'.join(f'{p}' for p in missing_permissions)
await self.telegram_bot.send_message(
f'⚠️ Канал "{input.chat_title}" был деактивирован.\
\n\nБоту убрали необходимые права:\n{missed_permissions}',
chat_id=input.user_telegram_id,
)
log.warning(
f'Target channel {input.telegram_id} deactivated due to missing permissions: {missing_permissions}'
f' Канал "{input.chat_title}" был активирован.\n\nВсе необходимые права боту предоставлены!',
input.user_telegram_id,
)
log.info(f'Target channel {input.telegram_id} reactivated - all permissions granted')
return
if channel.status == domain.TargetChannelStatus.ACTIVE:
channel.status = domain.TargetChannelStatus.INACTIVE
await self.database.update_target_channel(channel)
missed_permissions = '\n'.join(f'{p}' for p in missing_permissions)
await self.telegram_bot.send_message(
f'⚠️ Канал "{input.chat_title}" был деактивирован.\
\n\nБоту убрали необходимые права:\n{missed_permissions}',
input.user_telegram_id,
)
log.warning(f'Target channel {input.telegram_id} deactivated due to missing permissions: {missing_permissions}')

View File

@@ -10,18 +10,16 @@ log = logging.getLogger(__name__)
async def get_views_history(self: 'Usecase', input: dto.GetViewsHistoryInput) -> dto.GetViewsHistoryOutput:
"""Получить историю просмотров для закупа."""
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)
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)
histories = await self.database.get_views_history(
input.placement_id,
from_date=input.from_date,
to_date=input.to_date,
)
histories = await self.database.get_views_history(
input.placement_id,
from_date=input.from_date,
to_date=input.to_date,
)
return dto.GetViewsHistoryOutput(
histories=[

View File

@@ -1,7 +1,8 @@
import datetime
import logging
from typing import TYPE_CHECKING
from tortoise import timezone
from src import domain, dto
if TYPE_CHECKING:
@@ -11,14 +12,14 @@ log = logging.getLogger(__name__)
async def update_views_manually(self: 'Usecase', input: dto.UpdateViewsManuallyInput) -> dto.PlacementOutput:
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 = timezone.now()
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)
fetched_at = datetime.datetime.now(datetime.UTC)
placement.views_count = input.views_count
placement.views_availability = domain.PostViewsAvailability.MANUAL
placement.last_views_fetch_at = fetched_at
@@ -31,26 +32,26 @@ async def update_views_manually(self: 'Usecase', input: dto.UpdateViewsManuallyI
)
await self.database.create_placement_views_history(history)
log.info('Views manually updated for placement %s: %d', placement.id, input.views_count)
log.info('Views manually updated for placement %s: %d', placement.id, input.views_count)
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,
)
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,
)