feat: переезд на tortose

This commit is contained in:
Artem Tsyrulnikov
2025-12-11 09:17:31 +03:00
parent 2af23f84fe
commit 0f0de396e1
16 changed files with 437 additions and 611 deletions

View File

@@ -2,55 +2,41 @@ import datetime
import typing
import uuid
from sqlalchemy import delete, select
from sqlalchemy.orm import selectinload
from tortoise.transactions import in_transaction
from shared.datebase_base import DatabaseBase
from src import domain
class Postgres(DatabaseBase):
def transaction(self) -> typing.AsyncContextManager[None]:
return in_transaction()
async def get_user(self, user_id: uuid.UUID | None = None, telegram_id: int | None = None) -> domain.User | None:
if user_id:
return await self.session.get(domain.User, user_id)
return await domain.User.get_or_none(id=user_id)
elif telegram_id:
q = select(domain.User).where(domain.User.telegram_id == telegram_id)
result = await self.session.execute(q)
return result.scalar_one_or_none()
return await domain.User.get_or_none(telegram_id=telegram_id)
raise ValueError('Either user_id or telegram_id must be provided')
async def create_user(self, user: domain.User) -> domain.User:
self.session.add(user)
await self.session.flush()
await self.session.refresh(user)
await user.save()
return user
async def create_login_token(
self, user_id: uuid.UUID, token: str, expires_at: datetime.datetime
) -> domain.LoginToken:
login_token = domain.LoginToken(user_id=user_id, token=token, expires_at=expires_at)
self.session.add(login_token)
await self.session.flush()
await self.session.refresh(login_token)
login_token = await domain.LoginToken.create(user_id=user_id, token=token, expires_at=expires_at)
return login_token
async def get_login_token(self, token: str) -> domain.LoginToken | None:
q = select(domain.LoginToken).where(domain.LoginToken.token == token)
result = await self.session.execute(q)
return result.scalar_one_or_none()
return await domain.LoginToken.get_or_none(token=token)
async def mark_token_as_used(self, token: str) -> None:
q = select(domain.LoginToken).where(domain.LoginToken.token == token)
result = await self.session.execute(q)
login_token = result.scalar_one_or_none()
login_token = await domain.LoginToken.get_or_none(token=token)
if login_token:
login_token.used_at = datetime.datetime.now(datetime.UTC)
await self.session.flush()
await login_token.save()
async def get_target_channel(
self, user_id: uuid.UUID, channel_id: uuid.UUID | None = None, telegram_id: int | None = None
@@ -58,22 +44,19 @@ class Postgres(DatabaseBase):
if not channel_id and not telegram_id:
raise ValueError('Either channel_id or telegram_id must be provided')
q = select(domain.TargetChannel).where(domain.TargetChannel.user_id == user_id)
filters = {'user_id': user_id}
if channel_id:
q = q.where(domain.TargetChannel.id == channel_id)
filters['id'] = channel_id
if telegram_id:
q = q.where(domain.TargetChannel.telegram_id == telegram_id)
filters['telegram_id'] = telegram_id
result = await self.session.execute(q)
return result.scalar_one_or_none()
return await domain.TargetChannel.get_or_none(**filters)
async def upsert_target_channel(self, channel: domain.TargetChannel) -> domain.TargetChannel:
existing = await self.get_target_channel(user_id=channel.user_id, telegram_id=channel.telegram_id)
if not existing:
self.session.add(channel)
await self.session.flush()
await self.session.refresh(channel)
await channel.save()
return channel
existing.title = channel.title
@@ -82,180 +65,114 @@ class Postgres(DatabaseBase):
existing.status = channel.status
existing.deleted_at = None
existing.updated_at = datetime.datetime.now(datetime.UTC)
await self.session.flush()
await self.session.refresh(existing)
await existing.save()
return existing
async def get_user_target_channels(self, user_id: uuid.UUID) -> list[domain.TargetChannel]:
q = select(domain.TargetChannel).where(
domain.TargetChannel.status == domain.TargetChannelStatus.ACTIVE,
domain.TargetChannel.user_id == user_id,
)
result = await self.session.execute(q)
return list(result.scalars().all())
return await domain.TargetChannel.filter(user_id=user_id, status=domain.TargetChannelStatus.ACTIVE).all()
async def update_target_channel(self, channel: domain.TargetChannel) -> domain.TargetChannel:
await self.session.flush()
await self.session.refresh(channel)
await channel.save()
return channel
async def get_external_channel(
self, user_id: uuid.UUID, channel_id: uuid.UUID | None = None, telegram_id: int | None = None
) -> domain.ExternalChannel | None:
q = select(domain.ExternalChannel).where(domain.ExternalChannel.user_id == user_id)
filters = {'user_id': user_id}
if channel_id:
q = q.where(domain.ExternalChannel.id == channel_id)
filters['id'] = channel_id
if telegram_id:
q = q.where(domain.ExternalChannel.telegram_id == telegram_id)
filters['telegram_id'] = telegram_id
result = await self.session.execute(q)
return result.scalar_one_or_none()
return await domain.ExternalChannel.get_or_none(**filters)
async def create_external_channel(self, channel: domain.ExternalChannel) -> domain.ExternalChannel:
self.session.add(channel)
await self.session.flush()
await self.session.refresh(channel)
await channel.save()
return channel
async def get_external_channels_for_target(self, target_channel_id: uuid.UUID) -> list[domain.ExternalChannel]:
q = (
select(domain.ExternalChannel)
.join(domain.ExternalChannel.target_channels)
.where(domain.TargetChannel.id == target_channel_id)
)
result = await self.session.execute(q)
return list(result.scalars().all())
target = await domain.TargetChannel.get_or_none(id=target_channel_id).prefetch_related('external_channels')
if not target:
return []
return await target.external_channels.all()
async def get_user_external_channels(self, user_id: uuid.UUID) -> list[domain.ExternalChannel]:
q = select(domain.ExternalChannel).where(domain.ExternalChannel.user_id == user_id)
result = await self.session.execute(q)
return list(result.scalars().all())
return await domain.ExternalChannel.filter(user_id=user_id).all()
async def add_external_channel_to_targets(
self, external_channel_id: uuid.UUID, target_channel_ids: list[uuid.UUID]
) -> None:
q = (
select(domain.ExternalChannel)
.where(domain.ExternalChannel.id == external_channel_id)
.options(selectinload(domain.ExternalChannel.target_channels))
)
result = await self.session.execute(q)
external_channel = result.scalar_one_or_none()
external_channel = await domain.ExternalChannel.get_or_none(id=external_channel_id)
if not external_channel:
raise ValueError(f'ExternalChannel {external_channel_id} not found')
for target_id in target_channel_ids:
target_channel = await self.session.get(domain.TargetChannel, target_id)
if target_channel and target_channel not in external_channel.target_channels:
external_channel.target_channels.append(target_channel)
await self.session.flush()
target_channel = await domain.TargetChannel.get_or_none(id=target_id)
if target_channel:
await external_channel.external_channels.add(target_channel)
async def remove_external_channel_from_target(
self, external_channel_id: uuid.UUID, target_channel_id: uuid.UUID
) -> None:
q = (
select(domain.ExternalChannel)
.where(domain.ExternalChannel.id == external_channel_id)
.options(selectinload(domain.ExternalChannel.target_channels))
)
result = await self.session.execute(q)
external_channel = result.scalar_one_or_none()
external_channel = await domain.ExternalChannel.get_or_none(id=external_channel_id)
if not external_channel:
raise ValueError(f'ExternalChannel {external_channel_id} not found')
target_channel = await self.session.get(domain.TargetChannel, target_channel_id)
if target_channel and target_channel in external_channel.target_channels:
external_channel.target_channels.remove(target_channel)
await self.session.flush()
target_channel = await domain.TargetChannel.get_or_none(id=target_channel_id)
if target_channel:
await external_channel.target_channels.remove(target_channel)
async def delete_external_channel(self, channel_id: uuid.UUID) -> None:
q = delete(domain.ExternalChannel).where(domain.ExternalChannel.id == channel_id)
await self.session.execute(q)
await self.session.flush()
await domain.ExternalChannel.filter(id=channel_id).delete()
async def update_external_channel(self, channel: domain.ExternalChannel) -> domain.ExternalChannel:
await self.session.flush()
await self.session.refresh(channel)
await channel.save()
return channel
async def get_creative(self, user_id: uuid.UUID, creative_id: uuid.UUID) -> domain.Creative | None:
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(q)
return result.scalar_one_or_none()
return await domain.Creative.get_or_none(id=creative_id, user_id=user_id).prefetch_related('target_channel')
async def create_creative(self, creative: domain.Creative) -> domain.Creative:
self.session.add(creative)
await self.session.flush()
await self.session.refresh(creative)
await creative.save()
await creative.fetch_related('target_channel')
return creative
async def update_creative(self, creative: domain.Creative) -> domain.Creative:
await self.session.flush()
await self.session.refresh(creative)
await creative.save()
await creative.fetch_related('target_channel')
return creative
async def get_user_creatives(
self, user_id: uuid.UUID, target_channel_id: uuid.UUID | None = None, include_archived: bool = False
) -> list[domain.Creative]:
q = (
select(domain.Creative)
.options(selectinload(domain.Creative.target_channel))
.where(domain.Creative.user_id == user_id)
)
query = domain.Creative.filter(user_id=user_id)
if target_channel_id:
q = q.where(domain.Creative.target_channel_id == target_channel_id)
query = query.filter(target_channel_id=target_channel_id)
if not include_archived:
q = q.where(domain.Creative.status == domain.CreativeStatus.ACTIVE)
query = query.filter(status=domain.CreativeStatus.ACTIVE)
q = q.order_by(domain.Creative.created_at.desc())
result = await self.session.execute(q)
return list(result.scalars().all())
return await query.prefetch_related('target_channel').order_by('-created_at').all()
async def delete_creative(self, creative_id: uuid.UUID) -> None:
q = delete(domain.Creative).where(domain.Creative.id == creative_id)
await self.session.execute(q)
await self.session.flush()
await domain.Creative.filter(id=creative_id).delete()
async def get_placement(self, user_id: uuid.UUID, placement_id: uuid.UUID) -> domain.Placement | None:
q = (
select(domain.Placement)
.options(
selectinload(domain.Placement.target_channel),
selectinload(domain.Placement.external_channel),
selectinload(domain.Placement.creative),
)
.where(domain.Placement.id == placement_id, domain.Placement.user_id == user_id)
return await domain.Placement.get_or_none(id=placement_id, user_id=user_id).prefetch_related(
'target_channel', 'external_channel', 'creative'
)
result = await self.session.execute(q)
return result.scalar_one_or_none()
async def create_placement(self, placement: domain.Placement) -> domain.Placement:
self.session.add(placement)
await self.session.flush()
await self.session.refresh(
placement,
['target_channel', 'external_channel', 'creative'],
)
await placement.save()
await placement.fetch_related('target_channel', 'external_channel', 'creative')
return placement
async def update_placement(self, placement: domain.Placement) -> domain.Placement:
await self.session.flush()
await self.session.refresh(
placement,
['target_channel', 'external_channel', 'creative'],
)
await placement.save()
await placement.fetch_related('target_channel', 'external_channel', 'creative')
return placement
async def get_user_placements(
@@ -266,56 +183,39 @@ class Postgres(DatabaseBase):
creative_id: uuid.UUID | None = None,
include_archived: bool = False,
) -> list[domain.Placement]:
q = (
select(domain.Placement)
.options(
selectinload(domain.Placement.target_channel),
selectinload(domain.Placement.external_channel),
selectinload(domain.Placement.creative),
)
.where(domain.Placement.user_id == user_id)
)
query = domain.Placement.filter(user_id=user_id)
if target_channel_id:
q = q.where(domain.Placement.target_channel_id == target_channel_id)
query = query.filter(target_channel_id=target_channel_id)
if external_channel_id:
q = q.where(domain.Placement.external_channel_id == external_channel_id)
query = query.filter(external_channel_id=external_channel_id)
if creative_id:
q = q.where(domain.Placement.creative_id == creative_id)
query = query.filter(creative_id=creative_id)
if not include_archived:
q = q.where(domain.Placement.status == domain.PlacementStatus.ACTIVE)
query = query.filter(status=domain.PlacementStatus.ACTIVE)
q = q.order_by(domain.Placement.placement_date.desc())
result = await self.session.execute(q)
return list(result.scalars().all())
return (
await query.prefetch_related('target_channel', 'external_channel', 'creative')
.order_by('-placement_date')
.all()
)
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()
await domain.Placement.filter(id=placement_id).delete()
async def get_placement_by_invite_link(self, invite_link: str) -> domain.Placement | None:
q = (
select(domain.Placement)
.options(
selectinload(domain.Placement.target_channel),
selectinload(domain.Placement.external_channel),
selectinload(domain.Placement.creative),
)
.where(domain.Placement.invite_link == invite_link)
return await domain.Placement.get_or_none(invite_link=invite_link).prefetch_related(
'target_channel', 'external_channel', 'creative'
)
result = await self.session.execute(q)
return result.scalar_one_or_none()
async def get_placement_by_id(self, placement_id: uuid.UUID) -> domain.Placement | None:
return await self.session.get(domain.Placement, placement_id)
return await domain.Placement.get_or_none(id=placement_id)
async def update_placement_from_post_found(
self, placement_id: uuid.UUID, ad_post_url: str, message_id: int, views_count: int
) -> domain.Placement:
placement = await self.session.get(domain.Placement, placement_id)
placement = await domain.Placement.get_or_none(id=placement_id)
if not placement:
raise ValueError(f'Placement {placement_id} not found')
@@ -326,42 +226,34 @@ class Postgres(DatabaseBase):
placement.views_availability = domain.PostViewsAvailability.AVAILABLE
placement.last_views_fetch_at = datetime.datetime.now(datetime.UTC)
await self.session.flush()
await self.session.refresh(placement)
await placement.save()
return placement
async def update_placement_from_post_deleted(self, placement_id: uuid.UUID) -> domain.Placement:
placement = await self.session.get(domain.Placement, placement_id)
placement = await domain.Placement.get_or_none(id=placement_id)
if not placement:
raise ValueError(f'Placement {placement_id} not found')
placement.status = domain.PlacementStatus.DELETED
await self.session.flush()
await self.session.refresh(placement)
await placement.save()
return placement
async def update_placement_views(self, placement_id: uuid.UUID, views_count: int) -> domain.Placement:
placement = await self.session.get(domain.Placement, placement_id)
placement = await domain.Placement.get_or_none(id=placement_id)
if not placement:
raise ValueError(f'Placement {placement_id} not found')
placement.views_count = views_count
placement.last_views_fetch_at = datetime.datetime.now(datetime.UTC)
await self.session.flush()
await self.session.refresh(placement)
await placement.save()
return placement
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()
return await domain.Subscriber.get_or_none(telegram_id=telegram_id)
async def create_subscriber(self, subscriber: domain.Subscriber) -> domain.Subscriber:
self.session.add(subscriber)
await self.session.flush()
await self.session.refresh(subscriber)
await subscriber.save()
return subscriber
async def upsert_subscriber(self, subscriber: domain.Subscriber) -> domain.Subscriber:
@@ -371,73 +263,56 @@ class Postgres(DatabaseBase):
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)
await existing.save()
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, ['placement', 'subscriber'])
await subscription.save()
await subscription.fetch_related('placement', 'subscriber')
return subscription
async def get_subscription_by_subscriber_and_placement(
self, subscriber_id: uuid.UUID, placement_id: uuid.UUID
) -> domain.Subscription | None:
q = select(domain.Subscription).where(
domain.Subscription.subscriber_id == subscriber_id,
domain.Subscription.placement_id == placement_id,
)
result = await self.session.execute(q)
return result.scalar_one_or_none()
return await domain.Subscription.get_or_none(subscriber_id=subscriber_id, placement_id=placement_id)
async def update_subscription(self, subscription: domain.Subscription) -> domain.Subscription:
await self.session.flush()
await self.session.refresh(subscription, ['placement', 'subscriber'])
await subscription.save()
await subscription.fetch_related('placement', 'subscriber')
return subscription
async def get_active_subscriptions_by_subscriber_and_channel(
self, subscriber_id: uuid.UUID, channel_telegram_id: int
) -> list[domain.Subscription]:
q = (
select(domain.Subscription)
.join(domain.Placement, domain.Subscription.placement_id == domain.Placement.id)
.join(domain.TargetChannel, domain.Placement.target_channel_id == domain.TargetChannel.id)
.where(
domain.Subscription.subscriber_id == subscriber_id,
domain.TargetChannel.telegram_id == channel_telegram_id,
domain.Subscription.status == domain.SubscriptionStatus.ACTIVE,
return (
await domain.Subscription.filter(
subscriber_id=subscriber_id,
target_channel__telegram_id=channel_telegram_id,
status=domain.SubscriptionStatus.ACTIVE,
)
.options(selectinload(domain.Subscription.placement), selectinload(domain.Subscription.subscriber))
.prefetch_related('placement', 'subscriber')
.all()
)
result = await self.session.execute(q)
return list(result.scalars().all())
async def get_active_subscription_by_subscriber_and_channel(
self, subscriber_id: uuid.UUID, channel_telegram_id: int
) -> domain.Subscription | None:
"""Получить активную подписку пользователя на канал (должна быть только одна благодаря UNIQUE constraint)."""
q = (
select(domain.Subscription)
.join(domain.Placement, domain.Subscription.placement_id == domain.Placement.id)
.join(domain.TargetChannel, domain.Placement.target_channel_id == domain.TargetChannel.id)
.where(
domain.Subscription.subscriber_id == subscriber_id,
domain.TargetChannel.telegram_id == channel_telegram_id,
domain.Subscription.status == domain.SubscriptionStatus.ACTIVE,
return (
await domain.Subscription.filter(
subscriber_id=subscriber_id,
target_channel__telegram_id=channel_telegram_id,
status=domain.SubscriptionStatus.ACTIVE,
)
.options(selectinload(domain.Subscription.placement), selectinload(domain.Subscription.subscriber))
.prefetch_related('placement', 'subscriber')
.first()
)
result = await self.session.execute(q)
return result.scalar_one_or_none()
async def create_placement_views_history(
self, history: domain.PlacementViewsHistory
) -> domain.PlacementViewsHistory:
self.session.add(history)
await self.session.flush()
await self.session.refresh(history, ['placement'])
await history.save()
await history.fetch_related('placement')
return history
async def get_views_history(
@@ -447,22 +322,17 @@ class Postgres(DatabaseBase):
from_date: datetime.datetime | None = None,
to_date: datetime.datetime | None = None,
) -> list[domain.PlacementViewsHistory]:
q = select(domain.PlacementViewsHistory).where(domain.PlacementViewsHistory.placement_id == placement_id)
query = domain.PlacementViewsHistory.filter(placement_id=placement_id)
if from_date:
q = q.where(domain.PlacementViewsHistory.fetched_at >= from_date)
query = query.filter(fetched_at__gte=from_date)
if to_date:
q = q.where(domain.PlacementViewsHistory.fetched_at <= to_date)
query = query.filter(fetched_at__lte=to_date)
q = q.order_by(domain.PlacementViewsHistory.fetched_at.asc())
result = await self.session.execute(q)
return list(result.scalars().all())
return await query.order_by('fetched_at').all()
async def get_telegram_state(self, telegram_id: int) -> domain.TelegramState | None:
q = select(domain.TelegramState).where(domain.TelegramState.telegram_id == telegram_id)
result = await self.session.execute(q)
return result.scalar_one_or_none()
return await domain.TelegramState.get_or_none(telegram_id=telegram_id)
async def set_telegram_state(
self, telegram_id: int, state: domain.TelegramStateEnum, context: dict[str, typing.Any]
@@ -473,16 +343,11 @@ class Postgres(DatabaseBase):
existing.state = state
existing.context = context
existing.updated_at = datetime.datetime.now(datetime.UTC)
await self.session.flush()
await self.session.refresh(existing)
await existing.save()
return existing
new_state = domain.TelegramState(telegram_id=telegram_id, state=state, context=context)
self.session.add(new_state)
await self.session.flush()
await self.session.refresh(new_state)
new_state = await domain.TelegramState.create(telegram_id=telegram_id, state=state, context=context)
return new_state
async def clear_telegram_state(self, telegram_id: int) -> None:
q = delete(domain.TelegramState).where(domain.TelegramState.telegram_id == telegram_id)
await self.session.execute(q)
await domain.TelegramState.filter(telegram_id=telegram_id).delete()